|
1 | 1 | from contextlib import AsyncExitStack |
2 | 2 | from types import TracebackType |
3 | | -from typing import Literal, cast |
| 3 | +from typing import Literal, TypedDict, cast |
4 | 4 |
|
5 | 5 | from langchain_core.tools import BaseTool |
6 | 6 | from mcp import ClientSession, StdioServerParameters |
|
13 | 13 | DEFAULT_ENCODING_ERROR_HANDLER = "strict" |
14 | 14 |
|
15 | 15 |
|
| 16 | +class StdioConnection(TypedDict): |
| 17 | + transport: Literal["stdio"] |
| 18 | + command: str |
| 19 | + args: list[str] |
| 20 | + env: dict[str, str] | None |
| 21 | + encoding: str |
| 22 | + encoding_error_handler: Literal["strict", "ignore", "replace"] |
| 23 | + |
| 24 | + |
| 25 | +class SSEConnection(TypedDict): |
| 26 | + transport: Literal["sse"] |
| 27 | + url: str |
| 28 | + |
| 29 | + |
16 | 30 | class MultiServerMCPClient: |
17 | 31 | """Client for connecting to multiple MCP servers and loading LangChain-compatible tools from them.""" |
18 | 32 |
|
19 | | - def __init__(self) -> None: |
| 33 | + def __init__(self, connections: dict[str, StdioConnection | SSEConnection] = None) -> None: |
| 34 | + self.connections = connections |
20 | 35 | self.exit_stack = AsyncExitStack() |
21 | 36 | self.sessions: dict[str, ClientSession] = {} |
22 | 37 | self.server_name_to_tools: dict[str, list[BaseTool]] = {} |
@@ -151,6 +166,14 @@ def get_tools(self) -> list[BaseTool]: |
151 | 166 | return all_tools |
152 | 167 |
|
153 | 168 | async def __aenter__(self) -> "MultiServerMCPClient": |
| 169 | + connections = self.connections or {} |
| 170 | + for server_name, connection in connections.items(): |
| 171 | + connection_dict = connection.copy() |
| 172 | + transport = connection_dict.pop("transport") |
| 173 | + if transport == "stdio": |
| 174 | + await self.connect_to_server_via_stdio(server_name, **connection_dict) |
| 175 | + elif transport == "sse": |
| 176 | + await self.connect_to_server_via_sse(server_name, **connection_dict) |
154 | 177 | return self |
155 | 178 |
|
156 | 179 | async def __aexit__( |
|
0 commit comments