|
| 1 | +# Copyright (C) 2025 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import os |
| 6 | +from contextlib import AsyncExitStack |
| 7 | +from typing import List, Optional |
| 8 | + |
| 9 | +from mcp import ClientSession, StdioServerParameters |
| 10 | +from mcp.client.sse import sse_client |
| 11 | +from mcp.client.stdio import stdio_client |
| 12 | +from pydantic import BaseModel, Field |
| 13 | + |
| 14 | +from comps import CustomLogger |
| 15 | +from comps.cores.mcp.tool import OpeaMCPClientTool |
| 16 | + |
| 17 | +logger = CustomLogger("comps-mcp-client") |
| 18 | +log_flag = os.getenv("LOGFLAG", False) |
| 19 | + |
| 20 | + |
| 21 | +class OpeaMCPClient(BaseModel): |
| 22 | + """A client for interacting with MCP servers, managing tools, and handling server communication.""" |
| 23 | + |
| 24 | + description: str = "MCP client for server interaction and tool management" |
| 25 | + session: Optional[ClientSession] = None |
| 26 | + exit_stack: AsyncExitStack = AsyncExitStack() |
| 27 | + |
| 28 | + tools: List[OpeaMCPClientTool] = Field(default_factory=list) |
| 29 | + tool_registry: dict[str, OpeaMCPClientTool] = Field(default_factory=dict) |
| 30 | + |
| 31 | + class Config: |
| 32 | + arbitrary_types_allowed = True |
| 33 | + |
| 34 | + async def connect_via_sse(self, server_url: str, api_key: Optional[str] = None, timeout: float = 30.0) -> None: |
| 35 | + """Establish a connection to an MCP server using SSE (Server-Sent Events) transport. |
| 36 | +
|
| 37 | + Args: |
| 38 | + server_url: The URL of the SSE server to connect to. |
| 39 | + api_key: Optional API key for authentication. |
| 40 | + timeout: Connection timeout in seconds. Default is 30 seconds. |
| 41 | +
|
| 42 | + Raises: |
| 43 | + ValueError: If the server URL is not provided. |
| 44 | + asyncio.TimeoutError: If the connection times out. |
| 45 | + Exception: For other connection errors. |
| 46 | + """ |
| 47 | + if not server_url: |
| 48 | + raise ValueError("Server URL is required.") |
| 49 | + if self.session: |
| 50 | + await self.disconnect() |
| 51 | + |
| 52 | + try: |
| 53 | + |
| 54 | + async def connect_with_timeout(): |
| 55 | + streams_context = sse_client( |
| 56 | + url=server_url, |
| 57 | + headers={"Authorization": f"Bearer {api_key}"} if api_key else None, |
| 58 | + timeout=timeout, |
| 59 | + ) |
| 60 | + streams = await self.exit_stack.enter_async_context(streams_context) |
| 61 | + self.session = await self.exit_stack.enter_async_context(ClientSession(*streams)) |
| 62 | + await self._initialize_tools() |
| 63 | + |
| 64 | + await asyncio.wait_for(connect_with_timeout(), timeout=timeout) |
| 65 | + except asyncio.TimeoutError: |
| 66 | + logger.error(f"Connection to {server_url} timed out after {timeout} seconds") |
| 67 | + await self.disconnect() |
| 68 | + raise |
| 69 | + except Exception as e: |
| 70 | + logger.error(f"Error connecting to {server_url}: {str(e)}") |
| 71 | + await self.disconnect() |
| 72 | + raise |
| 73 | + |
| 74 | + async def connect_via_stdio(self, command: str, args: List[str]) -> None: |
| 75 | + """Establish a connection to an MCP server using stdio (standard input/output) transport. |
| 76 | +
|
| 77 | + Args: |
| 78 | + command: The command to start the server. |
| 79 | + args: A list of arguments for the command. |
| 80 | +
|
| 81 | + Raises: |
| 82 | + ValueError: If the command is not provided. |
| 83 | + Exception: For other connection errors. |
| 84 | + """ |
| 85 | + if not command: |
| 86 | + raise ValueError("Server command is required.") |
| 87 | + if self.session: |
| 88 | + await self.disconnect() |
| 89 | + |
| 90 | + try: |
| 91 | + server_params = StdioServerParameters(command=command, args=args) |
| 92 | + stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params)) |
| 93 | + read, write = stdio_transport |
| 94 | + self.session = await self.exit_stack.enter_async_context(ClientSession(read, write)) |
| 95 | + |
| 96 | + await self._initialize_tools() |
| 97 | + except Exception as e: |
| 98 | + logger.error(f"Error connecting to {command}: {str(e)}") |
| 99 | + await self.disconnect() |
| 100 | + raise |
| 101 | + |
| 102 | + async def _initialize_tools(self) -> None: |
| 103 | + """Initialize the client session and populate the tool registry with available tools. |
| 104 | +
|
| 105 | + Raises: |
| 106 | + RuntimeError: If the session is not initialized. |
| 107 | + """ |
| 108 | + if not self.session: |
| 109 | + raise RuntimeError("Session not initialized.") |
| 110 | + |
| 111 | + await self.session.initialize() |
| 112 | + response = await self.session.list_tools() |
| 113 | + |
| 114 | + # Clear existing tools |
| 115 | + self.tools = [] |
| 116 | + self.tool_registry = {} |
| 117 | + |
| 118 | + # Populate tools and registry |
| 119 | + for tool in response.tools: |
| 120 | + client_tool = OpeaMCPClientTool( |
| 121 | + name=tool.name, |
| 122 | + description=tool.description, |
| 123 | + inputSchema=tool.inputSchema, |
| 124 | + session=self.session, |
| 125 | + ) |
| 126 | + self.tool_registry[tool.name] = client_tool |
| 127 | + self.tools.append(client_tool) |
| 128 | + |
| 129 | + logger.info(f"Connected to server with tools: {[tool.name for tool in response.tools]}") |
| 130 | + |
| 131 | + async def invoke_tool(self, tool_name: str, parameters: dict): |
| 132 | + """Invoke a tool on the MCP server. |
| 133 | +
|
| 134 | + Args: |
| 135 | + tool_name: The name of the tool to invoke. |
| 136 | + parameters: The parameters to pass to the tool. |
| 137 | +
|
| 138 | + Returns: |
| 139 | + The result of the tool invocation. |
| 140 | +
|
| 141 | + Raises: |
| 142 | + ValueError: If the tool is not found in the registry. |
| 143 | + RuntimeError: If the client session is not available. |
| 144 | + """ |
| 145 | + if tool_name not in self.tool_registry: |
| 146 | + raise ValueError(f"Tool '{tool_name}' not found in the registry.") |
| 147 | + if not self.session: |
| 148 | + raise RuntimeError("Client session is not available.") |
| 149 | + |
| 150 | + return await self.session.call_tool(name=tool_name, arguments=parameters) |
| 151 | + |
| 152 | + async def disconnect(self) -> None: |
| 153 | + """Disconnect from the MCP server and clean up resources.""" |
| 154 | + if self.session: |
| 155 | + try: |
| 156 | + if hasattr(self.session, "close"): |
| 157 | + await self.session.close() |
| 158 | + await self.exit_stack.aclose() |
| 159 | + except Exception as e: |
| 160 | + logger.error(f"Error during disconnect: {str(e)}") |
| 161 | + finally: |
| 162 | + self.session = None |
| 163 | + self.tools = [] |
| 164 | + self.tool_registry = {} |
| 165 | + logger.info("Disconnected from MCP server") |
0 commit comments