Skip to content

Commit 999c4a5

Browse files
authored
New multi-surface agent example that works with the contact custom component client (#275)
* feat(client): update contact client for custom components and multiple surfaces * feat(renderer): enable custom component registration * Add a new multi-surface contact lookup agent that streams to the custom component 'contact' client. * Add readme. * Refactored the Contact Multiple Surfaces agent to address review comments, specifically moving large example strings into separate JSON files and improving error handling. * Rename inlineCatalog to inlineCatalogs * remove newline * Fix build
1 parent 56c20eb commit 999c4a5

37 files changed

+6482
-1473
lines changed

renderers/lit/src/0.8/ui/component-registry.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,15 @@
1717
import { CustomElementConstructorOf } from "./ui.js";
1818

1919
export class ComponentRegistry {
20+
private schemas: Map<string, unknown> = new Map();
2021
private registry: Map<string, CustomElementConstructorOf<HTMLElement>> =
2122
new Map();
2223

2324
register(
2425
typeName: string,
2526
constructor: CustomElementConstructorOf<HTMLElement>,
26-
tagName?: string
27+
tagName?: string,
28+
schema?: unknown
2729
) {
2830
if (!/^[a-zA-Z0-9]+$/.test(typeName)) {
2931
throw new Error(
@@ -32,6 +34,9 @@ export class ComponentRegistry {
3234
}
3335

3436
this.registry.set(typeName, constructor);
37+
if (schema) {
38+
this.schemas.set(typeName, schema);
39+
}
3540
const actualTagName = tagName || `a2ui-custom-${typeName.toLowerCase()}`;
3641

3742
const existingName = customElements.getName(constructor);
@@ -53,6 +58,14 @@ export class ComponentRegistry {
5358
get(typeName: string): CustomElementConstructorOf<HTMLElement> | undefined {
5459
return this.registry.get(typeName);
5560
}
61+
62+
getInlineCatalog(): { components: { [key: string]: unknown } } {
63+
const components: { [key: string]: unknown } = {};
64+
for (const [key, value] of this.schemas) {
65+
components[key] = value;
66+
}
67+
return { components };
68+
}
5669
}
5770

5871
export const componentRegistry = new ComponentRegistry();

renderers/lit/src/0.8/ui/surface.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ export class Surface extends Root {
6868
</div>`;
6969
}
7070

71+
@property()
72+
accessor enableCustomElements = false;
73+
74+
7175
#renderSurface() {
7276
const styles: Record<string, string> = {};
7377
if (this.surface?.styles) {
@@ -121,6 +125,7 @@ export class Surface extends Root {
121125
.childComponents=${this.surface?.componentTree
122126
? [this.surface.componentTree]
123127
: null}
128+
.enableCustomElements=${this.enableCustomElements}
124129
></a2ui-root>`;
125130
}
126131

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# A2UI Contact Multiple Surfaces Agent Sample
2+
3+
This sample uses the Agent Development Kit (ADK) along with the A2A protocol to create a simple "Contact Lookup" 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. Navigate to the samples directory:
14+
15+
```bash
16+
cd a2a_samples/a2ui_contact_lookup
17+
```
18+
19+
2. Create an environment file with your API key:
20+
21+
```bash
22+
echo "GEMINI_API_KEY=your_api_key_here" > .env
23+
```
24+
25+
3. Run the server:
26+
27+
```bash
28+
uv run .
29+
```
30+
31+
32+
## Disclaimer
33+
34+
Important: The sample code provided is for demonstration purposes and illustrates the mechanics of 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.
35+
36+
All data received from an external agent—including but not limited to its AgentCard, messages, artifacts, and task statuses—should be handled as untrusted input. For example, a malicious agent could provide an AgentCard containing crafted data in its fields (e.g., description, name, skills.description). If this data is used without sanitization to construct prompts for a Large Language Model (LLM), it could expose your application to prompt injection attacks. Failure to properly validate and sanitize this data before use can introduce security vulnerabilities into your application.
37+
38+
Developers are responsible for implementing appropriate security measures, such as input validation and secure handling of credentials to protect their systems and users.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# A2UI Custom Components & Multiple Surfaces Guide
2+
3+
This guide explains how the **Contact Client** and **Contact Multiple Surfaces Agent** work in tandem to deliver rich, custom user interfaces beyond the standard A2UI library.
4+
5+
## Architecture Overview
6+
7+
Unlike standard A2UI agents that rely solely on the core component library, this sample demonstrates a **Client-First Extension Model**:
8+
9+
1. **Client Defines Components**: The web client (`contact` sample) defines custom components (`OrgChart`, `WebFrame`) and their schemas.
10+
2. **Inline Catalog Negotiation**: When the client connects to the agent, it sends these schemas in its connection handshake (Client Event) under `metadata.inlineCatalog`.
11+
3. **Agent Adaptation**: The agent (`contact_multiple_surfaces`) dynamically reads this catalog and injects the schema into the LLM's system prompt (via `[SYSTEM]` messages).
12+
4. **Rich Rendering**: The LLM can then instruct the client to render these custom components.
13+
14+
## Key Features
15+
16+
### 1. Multiple Surfaces
17+
The agent manages multiple distinct UI areas ("surfaces") simultaneously:
18+
- **`contact-card`**: The main profile view validation.
19+
- **`org-chart-view`**: A side-by-side organizational chart.
20+
- **`location-surface`**: A transient modal/overlay for map views.
21+
22+
### 2. Custom Components
23+
24+
#### `OrgChart`
25+
A custom LitElement component created in the client that renders a hierarchical view.
26+
- **Schema**: Defined in `samples/client/lit/contact/ui/custom-components`.
27+
- **Usage**: The agent sends a JSON structure matching the schema, and the client renders it natively.
28+
29+
#### `WebFrame` (Iframe Component)
30+
A powerful component that allows embedding external web content or local static HTML files within the A2UI interface.
31+
- **Usage in Sample**: Used to render the "Office Floor Plan".
32+
- **Security**: Uses standard iframe sequencing and sandbox attributes.
33+
- **Interactivity**: Can communicate back to the parent A2UI application (e.g., clicking a desk on the map triggers an A2UI action `chart_node_click`).
34+
35+
## How to Run in Tandem
36+
37+
1. **Start the Agent**:
38+
```bash
39+
cd samples/agent/adk/contact_multiple_surfaces
40+
uv run .
41+
```
42+
*Runs on port 10004.*
43+
44+
2. **Start the Client**:
45+
```bash
46+
cd samples/client/lit/contact
47+
npm run dev
48+
```
49+
*Configured to connect to localhost:10004.*
50+
51+
## Flow Example: "View Location"
52+
53+
1. **User Trigger**: User clicks "Location" on a profile card.
54+
2. **Action**: Client sends standard A2UI action `view_location`.
55+
3. **Agent Response**: Agent detects the intent and returns a message to render the `location-surface`.
56+
4. **Component Payload**:
57+
```json
58+
{
59+
"WebFrame": {
60+
"url": "http://localhost:10004/static/floorplan.html?data=...",
61+
"interactionMode": "interactive"
62+
}
63+
}
64+
```
65+
5. **Rendering**: Client receives the message, creates the surface, and instantiates the `WebFrame` component, loading the static HTML map served by the agent.
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: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
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+
import logging
16+
import os
17+
18+
import click
19+
from a2a.server.apps import A2AStarletteApplication
20+
from a2a.server.request_handlers import DefaultRequestHandler
21+
from a2a.server.tasks import InMemoryTaskStore
22+
from a2a.types import AgentCapabilities, AgentCard, AgentSkill
23+
from a2ui.a2ui_extension import get_a2ui_agent_extension
24+
from agent import ContactAgent
25+
from agent_executor import ContactAgentExecutor
26+
from dotenv import load_dotenv
27+
from starlette.middleware.cors import CORSMiddleware
28+
from starlette.staticfiles import StaticFiles
29+
30+
load_dotenv()
31+
32+
logging.basicConfig(level=logging.INFO)
33+
logger = logging.getLogger(__name__)
34+
35+
36+
class MissingAPIKeyError(Exception):
37+
"""Exception for missing API key."""
38+
39+
40+
@click.command()
41+
@click.option("--host", default="localhost")
42+
@click.option("--port", default=10004)
43+
def main(host, port):
44+
try:
45+
# Check for API key only if Vertex AI is not configured
46+
if not os.getenv("GOOGLE_GENAI_USE_VERTEXAI") == "TRUE":
47+
if not os.getenv("GEMINI_API_KEY"):
48+
raise MissingAPIKeyError(
49+
"GEMINI_API_KEY environment variable not set and GOOGLE_GENAI_USE_VERTEXAI is not TRUE."
50+
)
51+
52+
capabilities = AgentCapabilities(
53+
streaming=True,
54+
extensions=[get_a2ui_agent_extension()],
55+
)
56+
skill = AgentSkill(
57+
id="find_contact",
58+
name="Find Contact Tool",
59+
description="Helps find contact information for colleagues (e.g., email, location, team).",
60+
tags=["contact", "directory", "people", "finder"],
61+
examples=["Who is David Chen in marketing?", "Find Sarah Lee from engineering"],
62+
)
63+
64+
base_url = f"http://{host}:{port}"
65+
66+
agent_card = AgentCard(
67+
name="Contact Lookup Agent",
68+
description="This agent helps find contact info for people in your organization.",
69+
url=base_url, # <-- Use base_url here
70+
version="1.0.0",
71+
default_input_modes=ContactAgent.SUPPORTED_CONTENT_TYPES,
72+
default_output_modes=ContactAgent.SUPPORTED_CONTENT_TYPES,
73+
capabilities=capabilities,
74+
skills=[skill],
75+
)
76+
77+
agent_executor = ContactAgentExecutor(base_url=base_url)
78+
79+
request_handler = DefaultRequestHandler(
80+
agent_executor=agent_executor,
81+
task_store=InMemoryTaskStore(),
82+
)
83+
server = A2AStarletteApplication(
84+
agent_card=agent_card, http_handler=request_handler
85+
)
86+
import uvicorn
87+
88+
app = server.build()
89+
90+
app.add_middleware(
91+
CORSMiddleware,
92+
allow_origins=["http://localhost:5173"],
93+
allow_credentials=True,
94+
allow_methods=["*"],
95+
allow_headers=["*"],
96+
)
97+
98+
app.mount("/static", StaticFiles(directory="images"), name="static")
99+
100+
uvicorn.run(app, host=host, port=port)
101+
except MissingAPIKeyError as e:
102+
logger.error(f"Error: {e}")
103+
exit(1)
104+
except Exception as e:
105+
logger.error(f"An error occurred during server startup: {e}")
106+
exit(1)
107+
108+
109+
if __name__ == "__main__":
110+
main()

0 commit comments

Comments
 (0)