Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e9b2b20
feat: Integrate MCP Apps into A2UI
dmandar Mar 2, 2026
77e96a2
chore: address PR review comments from gemini-code-assist
dmandar Mar 2, 2026
24cbc89
fix: Secure postMessage by capturing trusted host origin statefully
dmandar Mar 2, 2026
ab56d17
fix: fully secure MCP iframe initialization handshake with sandbox-in…
dmandar Mar 3, 2026
ad105f4
Merge branch 'main' into md-mcpuinew
dmandar Mar 3, 2026
e22bed7
style: run pyink auto-formatter to fix CI build
dmandar Mar 3, 2026
f5b2f41
fix(markdown-it): add missing package main and exports to resolve dow…
dmandar Mar 10, 2026
22859bf
fix(contact): resolve MCP iframe security issues and location double-…
dmandar Mar 10, 2026
0f43a44
revert(markdown-it): undo package exports change per PR review
dmandar Mar 10, 2026
63a3fd3
refactor(contact): address PR 748 review comments for McpApps integra…
dmandar Mar 10, 2026
04c0782
Merge main and resolve conflicts
dmandar Mar 11, 2026
c1b84a1
fix(lit): resolve compiler type errors and review comments
dmandar Mar 11, 2026
62bfcd3
chore: remove internal Google3 configs and properly align renderer sc…
dmandar Mar 11, 2026
22cfcec
Fix A2UI schema validator for incremental updates and update sample i…
dmandar Mar 12, 2026
6c53d20
Fix f-string curly brace escaping in prompt_builder.py
dmandar Mar 12, 2026
776fa4d
Fix LLM prompt for chart_node_click missing context to extract name
dmandar Mar 12, 2026
6bf4868
Address remaining PR #748 comments
dmandar Mar 13, 2026
7a544f8
Merge remote-tracking branch 'origin/main' into md-mcpuinew
dmandar Mar 13, 2026
441f282
Auto-format python code and add missing Apache license headers
dmandar Mar 13, 2026
b80812e
Merge main into md-mcpuinew
dmandar Mar 13, 2026
5f3a7db
chore: fix CI sample formatting, lit workspace, and revert agent_sdks…
dmandar Mar 13, 2026
57091eb
chore: fix NPM 401 error by regenerating package-lock.json via public…
dmandar Mar 13, 2026
dd1d846
chore: revert non-functional pyink formatting outside sample scope an…
dmandar Mar 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions samples/agent/adk/contact_multiple_surfaces/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@ This sample uses the Agent Development Kit (ADK) along with the A2A protocol to
uv run .
```

4. (Optional) Run the server with standard `WebFrame` instead of the custom `McpAppsCustomComponent`:

```bash
USE_MCP_SANDBOX=false uv run .
```


## Disclaimer

Expand Down
112 changes: 104 additions & 8 deletions samples/agent/adk/contact_multiple_surfaces/a2ui_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,108 @@
FLOOR_PLAN_FILE = "floor_plan.json"


def load_floor_plan_example() -> str:
"""Loads the floor plan example specifically."""
def load_floor_plan_example(html_content: str = "") -> list[dict]:
"""Constructs the JSON for the location surface displaying the floor plan."""
import os
return [
{
"beginRendering": {
"surfaceId": "location-surface",
"root": "floor-plan-card",
}
},
{
"surfaceUpdate": {
"surfaceId": "location-surface",
"components": [
{
"id": "floor-plan-card",
"component": {"Card": {"child": "floor-plan-col"}},
},
{
"id": "floor-plan-col",
"component": {
"Column": {
"children": {
"explicitList": [
"floor-plan-title",
"floor-plan-comp",
"dismiss-fp",
]
}
}
},
},
{
"id": "floor-plan-title",
"component": {
"Text": {
"usageHint": "h2",
"text": {"literalString": "Office Floor Plan"},
}
},
},
{
"id": "floor-plan-comp",
"component": {
"McpAppsCustomComponent": {
"htmlContent": html_content,
"height": 400,
"allowedTools": ["chart_node_click"],
}
} if os.environ.get("USE_MCP_SANDBOX", "true").lower() == "true" else {
"WebFrame": {
"html": html_content,
"height": 400,
"interactionMode": "interactive",
"allowedEvents": ["chart_node_click"],
}
},
},
{
"id": "dismiss-fp-text",
"component": {
"Text": {"text": {"literalString": "Close Map"}}
},
},
{
"id": "dismiss-fp",
"component": {
"Button": {
"child": "dismiss-fp-text",
# Represents closing the FloorPlan overlay
"action": {"name": "close_modal", "context": []},
}
},
},
],
}
},
]

def load_close_modal_example() -> list[dict]:
"""Constructs the JSON for closing the floor plan modal."""
return [{"deleteSurface": {"surfaceId": "location-surface"}}]

def load_send_message_example(contact_name: str) -> str:
"""Constructs the JSON string for the send message confirmation."""
from pathlib import Path
examples_dir = Path(os.path.dirname(__file__)) / "examples"
file_path = examples_dir / FLOOR_PLAN_FILE
try:
return file_path.read_text(encoding="utf-8")
except FileNotFoundError:
logger.error(f"Floor plan example not found: {file_path}")
return "[]"
action_file = examples_dir / "action_confirmation.json"

if action_file.exists():
json_content = action_file.read_text(encoding="utf-8").strip()
if contact_name != "Unknown":
json_content = json_content.replace(
"Your action has been processed.", f"Message sent to {contact_name}!"
)
return json_content
return (
'[{ "beginRendering": { "surfaceId": "action-modal", "root":'
' "modal-wrapper" } }, { "surfaceUpdate": { "surfaceId": "action-modal",'
' "components": [ { "id": "modal-wrapper", "component": { "Modal": {'
' "entryPointChild": "hidden", "contentChild": "msg", "open": true } } },'
' { "id": "hidden", "component": { "Text": { "text": {"literalString": "'
' "} } } }, { "id": "msg", "component": { "Text": { "text":'
' {"literalString": "Message Sent (Fallback)"} } } } ] } }]'
)
114 changes: 52 additions & 62 deletions samples/agent/adk/contact_multiple_surfaces/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,75 +185,65 @@ async def stream(self, query, session_id) -> AsyncIterable[dict[str, Any]]:
logger.info(f"--- ContactAgent.stream: Received query: '{query}' ---")

# --- Check for User Action ---
# If the query looks like an action (starts with "ACTION:"), parsing it to see if it's send_message

if query.startswith("ACTION:") and "send_message" in query:
logger.info("--- ContactAgent.stream: Detected send_message ACTION ---")

# Re-implement logic to read from file
from pathlib import Path

examples_dir = Path(__file__).parent / "examples"
action_file = examples_dir / "action_confirmation.json"

if action_file.exists():
json_content = action_file.read_text(encoding="utf-8").strip()

# Extract contact name from query if present
# If the query looks like an action (starts with "ACTION:"), parsing it to see which action
if query.startswith("ACTION:"):
from a2ui_examples import load_floor_plan_example, load_close_modal_example, load_send_message_example

if "send_message" in query:
logger.info("--- ContactAgent.stream: Detected send_message ACTION ---")
contact_name = "Unknown"
if "(contact:" in query:
try:
contact_name = query.split("(contact:")[1].split(")")[0].strip()
except Exception:
pass
json_content = load_send_message_example(contact_name)
yield {
"is_task_complete": True,
"content": f"Message sent to {contact_name}\n---a2ui_JSON---\n{json_content}",
}
return

elif "view_location" in query:
logger.info("--- ContactAgent.stream: Detected view_location ACTION ---")
# Action maps to opening the FloorPlan overlay to view the contact's location
from mcp import ClientSession
from mcp.client.sse import sse_client
import os

sse_url = os.environ.get("FLOOR_PLAN_SERVER_URL", "http://127.0.0.1:8000/sse")
try:
async with sse_client(sse_url) as (read, write):
async with ClientSession(read, write) as mcp_session:
await mcp_session.initialize()
logger.info("--- ContactAgent: Fetching ui://floor-plan-server/map from persistent SSE server ---")
result = await mcp_session.read_resource("ui://floor-plan-server/map")

if not result.contents or len(result.contents) == 0:
raise ValueError("No content returned from floor plan server")
html_content = result.contents[0].text
except Exception as e:
logger.error(f"Failed to fetch floor plan: {e}")
yield {"is_task_complete": True, "content": f"Failed to load floor plan data: {str(e)}"}
return

json_content = load_floor_plan_example(html_content)
logger.info(f"--- ContactAgent.stream: Sending Floor Plan ---")
yield {
"is_task_complete": True,
"content": f"Here is the floor plan.\n---a2ui_JSON---\n{json.dumps(json_content)}"
}
return

# Inject contact name into the message
if contact_name != "Unknown":
json_content = json_content.replace(
"Your action has been processed.", f"Message sent to {contact_name}!"
)

else:
logger.error(
"Could not find ACTION_CONFIRMATION_EXAMPLE in CONTACT_UI_EXAMPLES"
)
# Fallback to a minimal valid response to avoid crash
json_content = (
'[{ "beginRendering": { "surfaceId": "action-modal", "root":'
' "modal-wrapper" } }, { "surfaceUpdate": { "surfaceId": "action-modal",'
' "components": [ { "id": "modal-wrapper", "component": { "Modal": {'
' "entryPointChild": "hidden", "contentChild": "msg", "open": true } } },'
' { "id": "hidden", "component": { "Text": { "text": {"literalString": "'
' "} } } }, { "id": "msg", "component": { "Text": { "text":'
' {"literalString": "Message Sent (Fallback)"} } } } ] } }]'
)

final_response_content = (
f"Message sent to {contact_name}\n---a2ui_JSON---\n{json_content}"
)

yield {
"is_task_complete": True,
"content": final_response_content,
}
return

if query.startswith("ACTION:") and "view_location" in query:
logger.info("--- ContactAgent.stream: Detected view_location ACTION ---")

# Use the predefined example floor plan
json_content = load_floor_plan_example().strip()
start_idx = json_content.find("[")
end_idx = json_content.rfind("]")
if start_idx != -1 and end_idx != -1:
json_content = json_content[start_idx : end_idx + 1]

logger.info(f"--- ContactAgent.stream: Sending Floor Plan ---")
final_response_content = (
f"Here is the floor plan.\n---a2ui_JSON---\n{json_content}"
)
yield {"is_task_complete": True, "content": final_response_content}
return
elif "close_modal" in query:
logger.info("--- ContactAgent.stream: Handling close_modal ACTION ---")
# Action maps to closing the FloorPlan overlay
json_content = load_close_modal_example()
yield {
"is_task_complete": True,
"content": f"Modal closed.\n---a2ui_JSON---\n{json.dumps(json_content)}"
}
return

current_message = types.Content(
role="user", parts=[types.Part.from_text(text=current_query_text)]
Expand Down
64 changes: 64 additions & 0 deletions samples/agent/adk/contact_multiple_surfaces/floor_plan_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import asyncio
from mcp.server import Server
from mcp.types import Resource, TextContent

app = Server("floor-plan-server")

RESOURCE_URI = "ui://floor-plan-server/map"
MIME_TYPE = "text/html;profile=mcp-app"


@app.list_resources()
async def list_resources() -> list[Resource]:
return [
Resource(
uri=RESOURCE_URI,
name="Interactive Floor Plan",
mimeType=MIME_TYPE,
description="A visual floor plan showing desk assignments.",
)
]


@app.read_resource()
async def read_resource(uri: str) -> str | bytes:
if str(uri) != RESOURCE_URI:
raise ValueError(f"Unknown resource: {uri}")

import os

agent_static_url = os.environ.get("AGENT_STATIC_URL", "http://localhost:10004")

from pathlib import Path
template_path = Path(__file__).parent / "floor_plan_template.html"
html = template_path.read_text(encoding="utf-8")
html = html.replace("__AGENT_STATIC_URL__", agent_static_url)
return html


import uvicorn
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Mount, Route
from mcp.server.sse import SseServerTransport

sse = SseServerTransport("/messages/")


async def handle_sse(request: Request):
"""Handle the initial SSE connection from the A2UI agent."""
async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
await app.run(streams[0], streams[1], app.create_initialization_options())
return Response()


starlette_app = Starlette(
routes=[
Route("/sse", endpoint=handle_sse, methods=["GET"]),
Mount("/messages/", app=sse.handle_post_message),
]
)

if __name__ == "__main__":
uvicorn.run(starlette_app, host="127.0.0.1", port=8000)
Loading