|
| 1 | +import json |
| 2 | +import os |
| 3 | +from contextlib import AsyncExitStack |
| 4 | +from dataclasses import dataclass |
| 5 | +from typing import Any, Dict, List, Optional |
| 6 | + |
| 7 | +from dotenv import load_dotenv |
| 8 | +from mcp import ClientSession, StdioServerParameters |
| 9 | +from mcp.client.stdio import stdio_client |
| 10 | +from mcp.types import CallToolResult |
| 11 | +from openai.types import FunctionDefinition |
| 12 | +from openai.types.chat import ChatCompletionToolParam |
| 13 | + |
| 14 | +from eval_protocol.types.types import MCPMultiClientConfiguration |
| 15 | + |
| 16 | +load_dotenv() # load environment variables from .env |
| 17 | + |
| 18 | + |
| 19 | +class MCPMultiClient: |
| 20 | + """ |
| 21 | + Implements what clients like Cursor and Claude Desktop do when you configure |
| 22 | + them to use multiple MCP servers. The difference is that it validates |
| 23 | + against a list of environment variables rather than injects them into the |
| 24 | + MCP server process. This is so you can version control your configuration |
| 25 | + without exposing your environment variables to the MCP server process. |
| 26 | +
|
| 27 | + Environment variables should instead be set in a .env file |
| 28 | + """ |
| 29 | + |
| 30 | + def __init__(self, config_path: Optional[str] = None): |
| 31 | + # Initialize session and client objects |
| 32 | + self.sessions: Dict[str, ClientSession] = {} |
| 33 | + self.tools_to_sessions: Dict[str, ClientSession] = {} |
| 34 | + self.exit_stack = AsyncExitStack() |
| 35 | + self.config = self._load_config(config_path) |
| 36 | + |
| 37 | + def _load_config(self, config_path: Optional[str] = None) -> MCPMultiClientConfiguration: |
| 38 | + """Load MCP server configuration from file or use default""" |
| 39 | + if config_path and os.path.exists(config_path): |
| 40 | + with open(config_path, "r") as f: |
| 41 | + return json.load(f) |
| 42 | + |
| 43 | + # Default configuration - can be overridden by config file |
| 44 | + return {"mcpServers": {}} |
| 45 | + |
| 46 | + def _validate_environment_variables(self, server_name: str, required_env: List[str]) -> None: |
| 47 | + """Validate that required environment variables are set in os.environ""" |
| 48 | + missing_vars = [] |
| 49 | + for env_var in required_env: |
| 50 | + if env_var not in os.environ: |
| 51 | + missing_vars.append(env_var) |
| 52 | + |
| 53 | + if missing_vars: |
| 54 | + raise ValueError( |
| 55 | + f"Server '{server_name}' requires the following environment variables " |
| 56 | + f"to be set in os.environ: {missing_vars}. " |
| 57 | + f"Please set these variables in your environment or .env file." |
| 58 | + ) |
| 59 | + |
| 60 | + async def connect_to_servers(self): |
| 61 | + """Connect to all configured MCP servers""" |
| 62 | + if not self.config.get("mcpServers"): |
| 63 | + print("No MCP servers configured. Please provide a configuration file.") |
| 64 | + return |
| 65 | + |
| 66 | + for server_name, server_config in self.config["mcpServers"].items(): |
| 67 | + try: |
| 68 | + await self._connect_to_server(server_name, server_config) |
| 69 | + except Exception as e: |
| 70 | + print(f"Failed to connect to server '{server_name}': {e}") |
| 71 | + |
| 72 | + async def _connect_to_server(self, server_name: str, server_config: Dict[str, Any]): |
| 73 | + """Connect to a specific MCP server using its configuration""" |
| 74 | + command = server_config.get("command") |
| 75 | + args = server_config.get("args", []) |
| 76 | + env_config = server_config.get("env", []) |
| 77 | + |
| 78 | + if not command: |
| 79 | + raise ValueError(f"Server '{server_name}' must have a 'command' specified") |
| 80 | + |
| 81 | + # Validate that required environment variables are set |
| 82 | + if env_config: |
| 83 | + self._validate_environment_variables(server_name, env_config) |
| 84 | + |
| 85 | + # Use the current system environment (os.environ) - don't override with config |
| 86 | + server_params = StdioServerParameters(command=command, args=args, env=os.environ) |
| 87 | + |
| 88 | + stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params)) |
| 89 | + stdio, write = stdio_transport |
| 90 | + session = await self.exit_stack.enter_async_context(ClientSession(stdio, write)) |
| 91 | + |
| 92 | + await session.initialize() |
| 93 | + self.sessions[server_name] = session |
| 94 | + |
| 95 | + # List available tools |
| 96 | + response = await session.list_tools() |
| 97 | + tools = response.tools |
| 98 | + for tool in tools: |
| 99 | + if tool.name in self.tools_to_sessions: |
| 100 | + raise ValueError(f"Tool '{tool.name}' already exists") |
| 101 | + self.tools_to_sessions[tool.name] = session |
| 102 | + print( |
| 103 | + f"\nConnected to server '{server_name}' with tools:", |
| 104 | + [tool.name for tool in tools], |
| 105 | + ) |
| 106 | + |
| 107 | + async def get_available_tools(self) -> List[ChatCompletionToolParam]: |
| 108 | + """Get all available tools from all connected servers""" |
| 109 | + all_tools = [] |
| 110 | + for server_name, session in self.sessions.items(): |
| 111 | + try: |
| 112 | + response = await session.list_tools() |
| 113 | + for tool in response.tools: |
| 114 | + all_tools.append( |
| 115 | + ChatCompletionToolParam( |
| 116 | + function=FunctionDefinition( |
| 117 | + name=tool.name, # Prefix with server name |
| 118 | + description=tool.description, |
| 119 | + parameters=tool.inputSchema, |
| 120 | + ), |
| 121 | + type="function", |
| 122 | + ) |
| 123 | + ) |
| 124 | + except Exception as e: |
| 125 | + print(f"Error listing tools from server '{server_name}': {e}") |
| 126 | + |
| 127 | + return all_tools |
| 128 | + |
| 129 | + async def call_tool(self, tool_name: str, tool_args: Dict[str, Any]) -> CallToolResult: |
| 130 | + """Call a specific tool by name with arguments""" |
| 131 | + |
| 132 | + session = self.tools_to_sessions[tool_name] |
| 133 | + try: |
| 134 | + result = await session.call_tool(tool_name, tool_args) |
| 135 | + return result |
| 136 | + except Exception as e: |
| 137 | + return f"Error calling tool {tool_name}: {e}" |
| 138 | + |
| 139 | + async def cleanup(self): |
| 140 | + """Clean up resources""" |
| 141 | + await self.exit_stack.aclose() |
0 commit comments