|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +""" |
| 5 | +MCP Tool Registration Service for Google ADK. |
| 6 | +
|
| 7 | +This service provides MCP (Model Context Protocol) tool registration |
| 8 | +capabilities for Google ADK-based agents. |
| 9 | +""" |
| 10 | + |
| 11 | +# Standard library imports |
| 12 | +import logging |
| 13 | +from typing import List, Optional |
| 14 | + |
| 15 | +# Third-party imports |
| 16 | +from google.adk.agents import Agent |
| 17 | +from google.adk.tools.mcp_tool.mcp_toolset import McpToolset, StreamableHTTPConnectionParams |
| 18 | + |
| 19 | +# Local imports |
| 20 | +from microsoft_agents.hosting.core import Authorization, TurnContext |
| 21 | +from microsoft_agents_a365.runtime.utility import Utility |
| 22 | +from microsoft_agents_a365.tooling.models import ToolOptions |
| 23 | +from microsoft_agents_a365.tooling.services.mcp_tool_server_configuration_service import ( |
| 24 | + McpToolServerConfigurationService, |
| 25 | +) |
| 26 | +from microsoft_agents_a365.tooling.utils.constants import Constants |
| 27 | +from microsoft_agents_a365.tooling.utils.utility import ( |
| 28 | + get_mcp_platform_authentication_scope, |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +class McpToolRegistrationService: |
| 33 | + """ |
| 34 | + Provides MCP tool registration services for Google ADK agents. |
| 35 | +
|
| 36 | + This service handles registration and management of MCP (Model Context Protocol) |
| 37 | + tool servers with Google ADK agents. |
| 38 | + """ |
| 39 | + |
| 40 | + _orchestrator_name: str = "GoogleADK" |
| 41 | + |
| 42 | + def __init__(self, logger: Optional[logging.Logger] = None): |
| 43 | + """ |
| 44 | + Initialize the MCP Tool Registration Service for Google ADK. |
| 45 | +
|
| 46 | + Args: |
| 47 | + logger: Logger instance for logging operations. |
| 48 | + """ |
| 49 | + self._logger = logger or logging.getLogger(self.__class__.__name__) |
| 50 | + self._mcp_server_configuration_service = McpToolServerConfigurationService( |
| 51 | + logger=self._logger |
| 52 | + ) |
| 53 | + self._connected_servers: List[McpToolset] = [] |
| 54 | + |
| 55 | + async def add_tool_servers_to_agent( |
| 56 | + self, |
| 57 | + agent: Agent, |
| 58 | + auth: Authorization, |
| 59 | + auth_handler_name: str, |
| 60 | + context: TurnContext, |
| 61 | + auth_token: Optional[str] = None, |
| 62 | + ) -> None: |
| 63 | + """ |
| 64 | + Add new MCP servers to the agent from MCP Platform. |
| 65 | +
|
| 66 | + Note: Modifies the provided agent in place to add new MCP tool servers. |
| 67 | +
|
| 68 | + Args: |
| 69 | + agent: The existing agent to add servers to. |
| 70 | + auth: Authorization object used to exchange tokens for MCP server access. |
| 71 | + auth_handler_name: Name of the authorization handler. |
| 72 | + context: TurnContext object representing the current turn/session context. |
| 73 | + auth_token: Authentication token to access the MCP servers. |
| 74 | + If not provided, will be obtained using `auth` and `context`. |
| 75 | +
|
| 76 | + Returns: |
| 77 | + None |
| 78 | + """ |
| 79 | + if not auth_token: |
| 80 | + scopes = get_mcp_platform_authentication_scope() |
| 81 | + auth_token_obj = await auth.exchange_token(context, scopes, auth_handler_name) |
| 82 | + auth_token = auth_token_obj.token |
| 83 | + |
| 84 | + agentic_app_id = Utility.resolve_agent_identity(context, auth_token) |
| 85 | + self._logger.info(f"Listing MCP tool servers for agent {agentic_app_id}") |
| 86 | + |
| 87 | + options = ToolOptions(orchestrator_name=self._orchestrator_name) |
| 88 | + mcp_server_configs = await self._mcp_server_configuration_service.list_tool_servers( |
| 89 | + agentic_app_id=agentic_app_id, |
| 90 | + auth_token=auth_token, |
| 91 | + options=options, |
| 92 | + ) |
| 93 | + |
| 94 | + self._logger.info(f"Loaded {len(mcp_server_configs)} MCP server configurations") |
| 95 | + |
| 96 | + # Collect existing server URLs to prevent duplicates (use set for O(1) lookup) |
| 97 | + existing_server_urls = set() |
| 98 | + for tool in agent.tools: |
| 99 | + # Check if the tool is an McpToolset and has a connection_params.url |
| 100 | + if hasattr(tool, "connection_params") and hasattr(tool.connection_params, "url"): |
| 101 | + existing_server_urls.add(tool.connection_params.url) |
| 102 | + |
| 103 | + self._logger.debug(f"Found {len(existing_server_urls)} existing MCP servers in agent") |
| 104 | + |
| 105 | + # Convert MCP server configs to McpToolset objects (only new ones) |
| 106 | + mcp_servers_info = [] |
| 107 | + mcp_server_headers = { |
| 108 | + Constants.Headers.AUTHORIZATION: f"{Constants.Headers.BEARER_PREFIX} {auth_token}", |
| 109 | + Constants.Headers.USER_AGENT: Utility.get_user_agent_header(self._orchestrator_name), |
| 110 | + } |
| 111 | + |
| 112 | + for server_config in mcp_server_configs: |
| 113 | + # Skip if server URL already exists |
| 114 | + if server_config.url in existing_server_urls: |
| 115 | + self._logger.debug( |
| 116 | + f"Skipping MCP server '{server_config.mcp_server_name}' " |
| 117 | + f"at {server_config.url} - already exists in agent" |
| 118 | + ) |
| 119 | + continue |
| 120 | + |
| 121 | + try: |
| 122 | + server_info = McpToolset( |
| 123 | + connection_params=StreamableHTTPConnectionParams( |
| 124 | + url=server_config.url, |
| 125 | + headers=mcp_server_headers, |
| 126 | + ) |
| 127 | + ) |
| 128 | + |
| 129 | + mcp_servers_info.append(server_info) |
| 130 | + self._connected_servers.append(server_info) |
| 131 | + existing_server_urls.add(server_config.url) |
| 132 | + self._logger.info( |
| 133 | + f"Created MCP toolset for '{server_config.mcp_server_name}' " |
| 134 | + f"at {server_config.url}" |
| 135 | + ) |
| 136 | + |
| 137 | + except (ConnectionError, TimeoutError, ValueError) as tool_ex: |
| 138 | + # Expected connection/configuration errors |
| 139 | + self._logger.warning( |
| 140 | + f"Failed to create MCP toolset for '{server_config.mcp_server_name}': {tool_ex}" |
| 141 | + ) |
| 142 | + continue |
| 143 | + except Exception as tool_ex: |
| 144 | + # Unexpected errors - log at ERROR level with full traceback |
| 145 | + self._logger.error( |
| 146 | + f"Unexpected error creating MCP toolset for '{server_config.mcp_server_name}': {tool_ex}", |
| 147 | + exc_info=True, |
| 148 | + ) |
| 149 | + continue |
| 150 | + |
| 151 | + # Only modify agent.tools if we have new servers to add |
| 152 | + if mcp_servers_info: |
| 153 | + all_tools = list(agent.tools) + mcp_servers_info |
| 154 | + agent.tools = all_tools |
| 155 | + self._logger.info( |
| 156 | + f"Successfully configured agent with {len(mcp_servers_info)} new MCP tool servers " |
| 157 | + f"(total tools: {len(all_tools)})" |
| 158 | + ) |
| 159 | + else: |
| 160 | + self._logger.info("No new MCP servers to add to agent") |
| 161 | + |
| 162 | + async def cleanup(self): |
| 163 | + """Clean up any resources used by the service.""" |
| 164 | + try: |
| 165 | + for toolset in self._connected_servers: |
| 166 | + try: |
| 167 | + if hasattr(toolset, "close"): |
| 168 | + await toolset.close() |
| 169 | + except Exception as cleanup_ex: |
| 170 | + self._logger.debug(f"Error during cleanup: {cleanup_ex}") |
| 171 | + self._connected_servers.clear() |
| 172 | + except Exception as ex: |
| 173 | + self._logger.debug(f"Error during service cleanup: {ex}") |
0 commit comments