|
| 1 | +import sys |
| 2 | +from contextlib import AsyncExitStack |
| 3 | +from typing import Any, Awaitable, Callable, ClassVar, Self |
| 4 | + |
| 5 | +from mcp import ClientSession, StdioServerParameters |
| 6 | +from mcp.client.stdio import stdio_client |
| 7 | + |
| 8 | +from mcp_client import chat |
| 9 | +from mcp_client.handlers import OpenAIQueryHandler |
| 10 | + |
| 11 | + |
| 12 | +class MCPClient: |
| 13 | + """MCP client to interact with MCP server. |
| 14 | +
|
| 15 | + Usage: |
| 16 | + async with MCPClient(server_path) as client: |
| 17 | + # Call client methods here... |
| 18 | + """ |
| 19 | + |
| 20 | + client_session: ClassVar[ClientSession] |
| 21 | + |
| 22 | + def __init__(self, server_path: str): |
| 23 | + self.server_path = server_path |
| 24 | + self.exit_stack = AsyncExitStack() |
| 25 | + |
| 26 | + async def __aenter__(self) -> Self: |
| 27 | + cls = type(self) |
| 28 | + cls.client_session = await self._connect_to_server() |
| 29 | + return self |
| 30 | + |
| 31 | + async def __aexit__(self, *_) -> None: |
| 32 | + await self.exit_stack.aclose() |
| 33 | + |
| 34 | + async def _connect_to_server(self) -> ClientSession: |
| 35 | + try: |
| 36 | + read, write = await self.exit_stack.enter_async_context( |
| 37 | + stdio_client( |
| 38 | + server=StdioServerParameters( |
| 39 | + command="sh", |
| 40 | + args=[ |
| 41 | + "-c", |
| 42 | + f"{sys.executable} {self.server_path} 2>/dev/null", |
| 43 | + ], |
| 44 | + env=None, |
| 45 | + ) |
| 46 | + ) |
| 47 | + ) |
| 48 | + client_session = await self.exit_stack.enter_async_context( |
| 49 | + ClientSession(read, write) |
| 50 | + ) |
| 51 | + await client_session.initialize() |
| 52 | + return client_session |
| 53 | + except Exception: |
| 54 | + raise RuntimeError("Error: Failed to connect to server") |
| 55 | + |
| 56 | + async def list_all_members(self) -> None: |
| 57 | + """List all available tools, prompts, and resources.""" |
| 58 | + print("MCP Server Members") |
| 59 | + print("=" * 50) |
| 60 | + |
| 61 | + sections = { |
| 62 | + "tools": self.client_session.list_tools, |
| 63 | + "prompts": self.client_session.list_prompts, |
| 64 | + "resources": self.client_session.list_resources, |
| 65 | + } |
| 66 | + for section, listing_method in sections.items(): |
| 67 | + await self._list_section(section, listing_method) |
| 68 | + |
| 69 | + print("\n" + "=" * 50) |
| 70 | + |
| 71 | + async def _list_section( |
| 72 | + self, |
| 73 | + section: str, |
| 74 | + list_method: Callable[[], Awaitable[Any]], |
| 75 | + ) -> None: |
| 76 | + try: |
| 77 | + items = getattr(await list_method(), section) |
| 78 | + if items: |
| 79 | + print(f"\n{section.upper()} ({len(items)}):") |
| 80 | + print("-" * 30) |
| 81 | + for item in items: |
| 82 | + description = item.description or "No description" |
| 83 | + print(f" > {item.name} - {description}") |
| 84 | + else: |
| 85 | + print(f"\n{section.upper()}: None available") |
| 86 | + except Exception as e: |
| 87 | + print(f"\n{section.upper()}: Error - {e}") |
| 88 | + |
| 89 | + async def run_chat(self) -> None: |
| 90 | + """Start interactive chat with MCP server using OpenAI.""" |
| 91 | + try: |
| 92 | + handler = OpenAIQueryHandler(self.client_session) |
| 93 | + await chat.run_chat(handler) |
| 94 | + except RuntimeError as e: |
| 95 | + print(e) |
0 commit comments