|
| 1 | +import httpx |
| 2 | +import logging |
| 3 | +from fastmcp import Client |
| 4 | +from fastmcp.client.transports import ClientTransport |
| 5 | +from fastmcp.exceptions import NotFoundError |
| 6 | +from fastmcp.server.proxy import ClientFactoryT |
| 7 | +from fastmcp.server.proxy import FastMCPProxy as _FastMCPProxy |
| 8 | +from fastmcp.server.proxy import ProxyClient as _ProxyClient |
| 9 | +from fastmcp.server.proxy import ProxyToolManager as _ProxyToolManager |
| 10 | +from fastmcp.tools import Tool |
| 11 | +from mcp import McpError |
| 12 | +from mcp.types import InitializeRequest, JSONRPCError, JSONRPCMessage |
| 13 | +from typing import Any |
| 14 | +from typing_extensions import override |
| 15 | + |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class AWSProxyToolManager(_ProxyToolManager): |
| 21 | + """Customized proxy tool manager that better suites our needs.""" |
| 22 | + |
| 23 | + def __init__(self, client_factory: ClientFactoryT, **kwargs: Any): |
| 24 | + """Initialize a proxy tool manager. |
| 25 | +
|
| 26 | + Cached tools are set to None. |
| 27 | + """ |
| 28 | + super().__init__(client_factory, **kwargs) |
| 29 | + self._cached_tools: dict[str, Tool] | None = None |
| 30 | + |
| 31 | + @override |
| 32 | + async def get_tool(self, key: str) -> Tool: |
| 33 | + """Return the tool from cached tools. |
| 34 | +
|
| 35 | + This method is invoked when the client tries to call a tool. |
| 36 | +
|
| 37 | + tool = self.get_tool(key) |
| 38 | + tool.invoke(...) |
| 39 | +
|
| 40 | + The parent class implementation always make a mcp call to list the tools. |
| 41 | + Since the client already knows the name of the tools, list_tool is not necessary. |
| 42 | + We are wasting a network call just to get the tools which were already listed. |
| 43 | +
|
| 44 | + In case the server supports notifications/tools/listChanged, the `get_tools` method |
| 45 | + will be called explicity , hence, we are not missing the change to the tool list. |
| 46 | + """ |
| 47 | + if self._cached_tools is None: |
| 48 | + logger.debug('cached_tools not found, calling get_tools') |
| 49 | + self._cached_tools = await self.get_tools() |
| 50 | + if key in self._cached_tools: |
| 51 | + return self._cached_tools[key] |
| 52 | + raise NotFoundError(f'Tool {key!r} not found') |
| 53 | + |
| 54 | + @override |
| 55 | + async def get_tools(self) -> dict[str, Tool]: |
| 56 | + """Return list tools.""" |
| 57 | + self._cached_tools = await super(AWSProxyToolManager, self).get_tools() |
| 58 | + return self._cached_tools |
| 59 | + |
| 60 | + |
| 61 | +class AWSMCPProxy(_FastMCPProxy): |
| 62 | + """Customized MCP Proxy to better suite our needs.""" |
| 63 | + |
| 64 | + def __init__( |
| 65 | + self, |
| 66 | + *, |
| 67 | + client_factory: ClientFactoryT | None = None, |
| 68 | + **kwargs, |
| 69 | + ): |
| 70 | + """Initialize a client.""" |
| 71 | + super().__init__(client_factory=client_factory, **kwargs) |
| 72 | + self._tool_manager = AWSProxyToolManager( |
| 73 | + client_factory=self.client_factory, |
| 74 | + transformations=self._tool_manager.transformations, |
| 75 | + ) |
| 76 | + |
| 77 | + |
| 78 | +class AWSMCPProxyClient(_ProxyClient): |
| 79 | + """Proxy client that handles HTTP errors when connection fails.""" |
| 80 | + |
| 81 | + def __init__(self, transport: ClientTransport, **kwargs): |
| 82 | + """Constructor of AutoRefreshProxyCilent.""" |
| 83 | + super().__init__(transport, **kwargs) |
| 84 | + |
| 85 | + @override |
| 86 | + async def _connect(self): |
| 87 | + """Enter as normal && initialize only once.""" |
| 88 | + logger.debug('Connecting %s', self) |
| 89 | + try: |
| 90 | + result = await super(AWSMCPProxyClient, self)._connect() |
| 91 | + logger.debug('Connected %s', self) |
| 92 | + return result |
| 93 | + except httpx.HTTPStatusError as http_error: |
| 94 | + logger.exception('Connection failed') |
| 95 | + response = http_error.response |
| 96 | + try: |
| 97 | + body = await response.aread() |
| 98 | + jsonrpc_msg = JSONRPCMessage.model_validate_json(body).root |
| 99 | + except Exception: |
| 100 | + logger.debug('HTTP error is not a valid MCP message.') |
| 101 | + raise http_error |
| 102 | + |
| 103 | + if isinstance(jsonrpc_msg, JSONRPCError): |
| 104 | + logger.debug('Converting HTTP error to MCP error %s', http_error) |
| 105 | + # raising McpError so that the sdk can handle the exception properly |
| 106 | + raise McpError(error=jsonrpc_msg.error) from http_error |
| 107 | + else: |
| 108 | + raise http_error |
| 109 | + |
| 110 | + async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 111 | + """The MCP Proxy for AWS project is a proxy from stdio to http (sigv4). |
| 112 | +
|
| 113 | + We want the client to remain connected in the until the stdio connection is closed. |
| 114 | +
|
| 115 | + https://modelcontextprotocol.io/specification/2024-11-05/basic/transports#stdio |
| 116 | +
|
| 117 | + 1. close stdin |
| 118 | + 2. terminate subprocess |
| 119 | +
|
| 120 | + There is no equivalent of the streamble-http DELETE concept in stdio to terminate a session. |
| 121 | + Hence the connection will be terminated only at program exit. |
| 122 | + """ |
| 123 | + # return await super().__aexit__(exc_type, exc_val, exc_tb) |
| 124 | + pass |
| 125 | + |
| 126 | + |
| 127 | +class AWSMCPProxyClientFactory: |
| 128 | + """Client factory that returns a connected client.""" |
| 129 | + |
| 130 | + def __init__(self, transport: ClientTransport) -> None: |
| 131 | + """Initialize a client factory with transport.""" |
| 132 | + self._transport = transport |
| 133 | + self._client = AWSMCPProxyClient(transport) |
| 134 | + self._clients: list[AWSMCPProxyClient] = [] |
| 135 | + self._initialize_request: InitializeRequest | None = None |
| 136 | + |
| 137 | + def set_init_params(self, initialize_request: InitializeRequest): |
| 138 | + """Set client init parameters.""" |
| 139 | + self._initialize_request = initialize_request |
| 140 | + |
| 141 | + async def get_client(self) -> Client: |
| 142 | + """Get client.""" |
| 143 | + if not self._client.is_connected(): |
| 144 | + self._client = AWSMCPProxyClient(self._transport) |
| 145 | + |
| 146 | + return self._client |
| 147 | + |
| 148 | + async def __call__(self) -> Client: |
| 149 | + """Implement the callable factory interface.""" |
| 150 | + return await self.get_client() |
| 151 | + |
| 152 | + async def disconnect_all(self): |
| 153 | + """Disconnect all the clients (no throw).""" |
| 154 | + for client in reversed(self._clients): |
| 155 | + try: |
| 156 | + await client._disconnect(force=True) |
| 157 | + except Exception: |
| 158 | + logger.exception('Failed to disconnect client.') |
0 commit comments