Skip to content

Commit bd3d34c

Browse files
committed
feat: Implement MCP Calculator App and Relay Agent
1 parent d13cfeb commit bd3d34c

File tree

10 files changed

+602
-26
lines changed

10 files changed

+602
-26
lines changed

agent_sdks/python/src/a2ui/adk/a2a_extension/send_a2ui_to_client_toolset.py

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -339,8 +339,9 @@ class A2uiPartConverter:
339339
catalog to validate and fix JSON payloads.
340340
"""
341341

342-
def __init__(self, a2ui_catalog: A2uiCatalog):
342+
def __init__(self, a2ui_catalog: A2uiCatalog, bypass_tool_check: bool = False):
343343
self._catalog = a2ui_catalog
344+
self._bypass_tool_check = bypass_tool_check
344345

345346
def convert(self, part: genai_types.Part) -> list[a2a_types.Part]:
346347
"""Converts a GenAI part to A2A parts, with A2UI validation.
@@ -352,30 +353,39 @@ def convert(self, part: genai_types.Part) -> list[a2a_types.Part]:
352353
A list of A2A parts.
353354
"""
354355
# 1. Handle Tool Responses (FunctionResponse)
355-
if (
356-
(function_response := part.function_response)
357-
and function_response.name
358-
== SendA2uiToClientToolset._SendA2uiJsonToClientTool.TOOL_NAME
359-
):
360-
if (
361-
SendA2uiToClientToolset._SendA2uiJsonToClientTool.TOOL_ERROR_KEY
362-
in function_response.response
363-
):
364-
logger.warning(
365-
"A2UI tool call failed:"
366-
f" {function_response.response[SendA2uiToClientToolset._SendA2uiJsonToClientTool.TOOL_ERROR_KEY]}"
367-
)
368-
return []
369-
370-
# The tool returns the list of messages directly on success
371-
json_data = function_response.response.get(
372-
SendA2uiToClientToolset._SendA2uiJsonToClientTool.VALIDATED_A2UI_JSON_KEY
356+
if function_response := part.function_response:
357+
is_send_a2ui_json_to_client_response = (
358+
function_response.name
359+
== SendA2uiToClientToolset._SendA2uiJsonToClientTool.TOOL_NAME
373360
)
374-
if not json_data:
375-
logger.info("No result in A2UI tool response")
376-
return []
377361

378-
return [create_a2ui_part(message) for message in json_data]
362+
if is_send_a2ui_json_to_client_response or self._bypass_tool_check:
363+
response_dict = function_response.response or {}
364+
365+
if (
366+
SendA2uiToClientToolset._SendA2uiJsonToClientTool.TOOL_ERROR_KEY
367+
in response_dict
368+
):
369+
logger.warning(
370+
"A2UI tool call failed:"
371+
f" {response_dict[SendA2uiToClientToolset._SendA2uiJsonToClientTool.TOOL_ERROR_KEY]}"
372+
)
373+
return []
374+
375+
if (
376+
isinstance(response_dict, dict)
377+
and SendA2uiToClientToolset._SendA2uiJsonToClientTool.VALIDATED_A2UI_JSON_KEY
378+
in response_dict
379+
):
380+
json_data = response_dict.get(
381+
SendA2uiToClientToolset._SendA2uiJsonToClientTool.VALIDATED_A2UI_JSON_KEY
382+
)
383+
if json_data:
384+
return [create_a2ui_part(message) for message in json_data]
385+
386+
if is_send_a2ui_json_to_client_response:
387+
logger.info("No result in A2UI tool response")
388+
return []
379389

380390
# 2. Handle Tool Calls (FunctionCall) - Skip sending to client
381391
if (
@@ -403,8 +413,11 @@ class A2uiEventConverter:
403413
catalog is session-specific.
404414
"""
405415

406-
def __init__(self, catalog_key: str = "system:a2ui_catalog"):
416+
def __init__(
417+
self, catalog_key: str = "system:a2ui_catalog", bypass_tool_check: bool = False
418+
):
407419
self._catalog_key = catalog_key
420+
self._bypass_tool_check = bypass_tool_check
408421

409422
def __call__(
410423
self,
@@ -420,7 +433,9 @@ def __call__(
420433
catalog = invocation_context.session.state.get(self._catalog_key)
421434
if catalog:
422435
# Use the catalog-aware part converter
423-
effective_converter = A2uiPartConverter(catalog).convert
436+
effective_converter = A2uiPartConverter(
437+
catalog, bypass_tool_check=self._bypass_tool_check
438+
).convert
424439
else:
425440
effective_converter = part_converter_func
426441

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Copy this file to .env and fill in your API key
2+
# Get your API key at: https://aistudio.google.com/apikey
3+
4+
GEMINI_API_KEY=your_gemini_api_key_here
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# A2UI MCP Apps Proxy Agent sample
2+
3+
This sample uses the Agent Development Kit (ADK) along with the A2A protocol to create a simple "MCP Apps Proxy" agent that is hosted as an A2A server.
4+
5+
## Prerequisites
6+
7+
- Python 3.9 or higher
8+
- [UV](https://docs.astral.sh/uv/)
9+
- Access to an LLM and API Key
10+
11+
## Running the sample
12+
13+
1. Run the MCP Server that serves the MCP Apps. ([Link to instructions](../../agent/mcp/README.md))
14+
15+
16+
2. Navigate to the samples directory:
17+
18+
```bash
19+
cd samples/agent/adk/mcp_app_proxy
20+
```
21+
22+
2. Create an environment file with your API key:
23+
24+
```bash
25+
cp .env.example .env
26+
# Edit .env with your actual API key (do not commit .env)
27+
```
28+
29+
3. Run the server:
30+
31+
```bash
32+
uv run .
33+
```
34+
35+
36+
## Disclaimer
37+
38+
Important: The sample code provided is for demonstration purposes and illustrates the mechanics of A2UI and the Agent-to-Agent (A2A) protocol. When building production applications, it is critical to treat any agent operating outside of your direct control as a potentially untrusted entity.
39+
40+
All operational data received from an external agent—including its AgentCard, messages, artifacts, and task statuses—should be handled as untrusted input. For example, a malicious agent could provide crafted data in its fields (e.g., name, skills.description) that, if used without sanitization to construct prompts for a Large Language Model (LLM), could expose your application to prompt injection attacks.
41+
42+
Similarly, any UI definition or data stream received must be treated as untrusted. Malicious agents could attempt to spoof legitimate interfaces to deceive users (phishing), inject malicious scripts via property values (XSS), or generate excessive layout complexity to degrade client performance (DoS). If your application supports optional embedded content (such as iframes or web views), additional care must be taken to prevent exposure to malicious external sites.
43+
44+
Developer Responsibility: Failure to properly validate data and strictly sandbox rendered content can introduce severe vulnerabilities. Developers are responsible for implementing appropriate security measures—such as input sanitization, Content Security Policies (CSP), strict isolation for optional embedded content, and secure credential handling—to protect their systems and users.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from . import agent
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
# Copyright 2025 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# https://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from a2a.server.apps import A2AStarletteApplication
16+
from a2a.server.request_handlers import DefaultRequestHandler
17+
from a2a.server.tasks import InMemoryTaskStore
18+
from a2ui.core.schema.constants import VERSION_0_8
19+
from a2ui.core.schema.manager import A2uiSchemaManager, CatalogConfig
20+
from agent import McpAppProxyAgent
21+
from agent_executor import McpAppProxyAgentExecutor, get_a2ui_enabled, get_a2ui_catalog, get_a2ui_examples
22+
from dotenv import load_dotenv
23+
from google.adk.artifacts import InMemoryArtifactService
24+
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
25+
from google.adk.models.lite_llm import LiteLlm
26+
from google.adk.runners import Runner
27+
from google.adk.sessions.in_memory_session_service import InMemorySessionService
28+
from google.adk.tools.tool_context import ToolContext
29+
from mcp import ClientSession
30+
from mcp.client.sse import sse_client
31+
from starlette.middleware.cors import CORSMiddleware
32+
import anyio
33+
import click
34+
import httpx
35+
import logging
36+
import os
37+
import traceback
38+
import urllib.parse
39+
40+
load_dotenv()
41+
42+
logging.basicConfig(level=logging.INFO)
43+
logger = logging.getLogger(__name__)
44+
45+
46+
class MissingAPIKeyError(Exception):
47+
"""Exception for missing API key."""
48+
49+
50+
@click.command()
51+
@click.option("--host", default="localhost")
52+
@click.option("--port", default=10006)
53+
def main(host, port):
54+
try:
55+
if not os.getenv("GOOGLE_GENAI_USE_VERTEXAI") == "TRUE":
56+
if not os.getenv("GEMINI_API_KEY"):
57+
raise MissingAPIKeyError(
58+
"GEMINI_API_KEY environment variable not set and GOOGLE_GENAI_USE_VERTEXAI"
59+
" is not TRUE."
60+
)
61+
62+
lite_llm_model = os.getenv("LITELLM_MODEL", "gemini/gemini-2.5-flash")
63+
base_url = f"http://{host}:{port}"
64+
65+
schema_manager = A2uiSchemaManager(
66+
VERSION_0_8,
67+
catalogs=[
68+
CatalogConfig.from_path(
69+
name="mcp_app_proxy",
70+
catalog_path="mcp_app_catalog.json",
71+
),
72+
],
73+
accepts_inline_catalogs=True,
74+
)
75+
76+
# Define get_calculator_app tool in a way that the LlmAgent can use.
77+
async def get_calculator_app(tool_context: ToolContext):
78+
"""Fetches the calculator app."""
79+
# Connect to the MCP server via SSE
80+
mcp_server_host = os.getenv("MCP_SERVER_HOST", "localhost")
81+
mcp_server_port = os.getenv("MCP_SERVER_PORT", "8000")
82+
sse_url = f"http://{mcp_server_host}:{mcp_server_port}/sse"
83+
84+
try:
85+
async with sse_client(sse_url) as streams:
86+
async with ClientSession(streams[0], streams[1]) as session:
87+
await session.initialize()
88+
89+
# Read the resource
90+
result = await session.read_resource("ui://calculator/app")
91+
92+
# Package the resource as an A2UI message
93+
if result.contents and hasattr(result.contents[0], "text"):
94+
html_content = result.contents[0].text
95+
encoded_html = "url_encoded:" + urllib.parse.quote(html_content)
96+
messages = [
97+
{
98+
"beginRendering": {
99+
"surfaceId": "calculator_surface",
100+
"root": "calculator_app_root",
101+
},
102+
},
103+
{
104+
"surfaceUpdate": {
105+
"surfaceId": "calculator_surface",
106+
"components": [
107+
{
108+
"id": "calculator_app_root",
109+
"component": {
110+
"McpApp": {
111+
"content": {"literalString": encoded_html},
112+
"title": {"literalString": "Calculator"},
113+
}
114+
},
115+
}
116+
],
117+
},
118+
},
119+
]
120+
tool_context.actions.skip_summarization = True
121+
return {"validated_a2ui_json": messages}
122+
else:
123+
logger.error("Failed to get text content from resource")
124+
return {"error": "Could not fetch calculator app content."}
125+
126+
except Exception as e:
127+
logger.error(f"Error fetching calculator app: {e} {traceback.format_exc()}")
128+
return {"error": f"Failed to connect to MCP server or fetch app. Details: {e}"}
129+
130+
131+
tools = [get_calculator_app]
132+
133+
agent = McpAppProxyAgent(
134+
base_url=base_url,
135+
model=LiteLlm(model=lite_llm_model),
136+
schema_manager=schema_manager,
137+
a2ui_enabled_provider=get_a2ui_enabled,
138+
a2ui_catalog_provider=get_a2ui_catalog,
139+
a2ui_examples_provider=get_a2ui_examples,
140+
tools=tools,
141+
)
142+
143+
runner = Runner(
144+
app_name=agent.name,
145+
agent=agent,
146+
artifact_service=InMemoryArtifactService(),
147+
session_service=InMemorySessionService(),
148+
memory_service=InMemoryMemoryService(),
149+
)
150+
151+
agent_executor = McpAppProxyAgentExecutor(
152+
base_url=base_url,
153+
runner=runner,
154+
schema_manager=schema_manager,
155+
)
156+
157+
request_handler = DefaultRequestHandler(
158+
agent_executor=agent_executor,
159+
task_store=InMemoryTaskStore(),
160+
)
161+
server = A2AStarletteApplication(
162+
agent_card=agent.get_agent_card(), http_handler=request_handler
163+
)
164+
import uvicorn
165+
166+
app = server.build()
167+
168+
app.add_middleware(
169+
CORSMiddleware,
170+
allow_origins=["http://localhost:5173"],
171+
allow_credentials=True,
172+
allow_methods=["*"],
173+
allow_headers=["*"],
174+
)
175+
176+
uvicorn.run(app, host=host, port=port)
177+
except MissingAPIKeyError as e:
178+
logger.error(f"Error: {e} {traceback.format_exc()}")
179+
exit(1)
180+
except Exception as e:
181+
logger.error(
182+
f"An error occurred during server startup: {e} {traceback.format_exc()}"
183+
)
184+
exit(1)
185+
186+
187+
if __name__ == "__main__":
188+
main()

0 commit comments

Comments
 (0)