|
| 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