Base class for MCP server connections.
| 11 | |
| 12 | |
| 13 | class MCPConnection(ABC): |
| 14 | """Base class for MCP server connections.""" |
| 15 | |
| 16 | def __init__(self): |
| 17 | self.session = None |
| 18 | self._stack = None |
| 19 | |
| 20 | @abstractmethod |
| 21 | def _create_context(self): |
| 22 | """Create the connection context based on connection type.""" |
| 23 | |
| 24 | async def __aenter__(self): |
| 25 | """Initialize MCP server connection.""" |
| 26 | self._stack = AsyncExitStack() |
| 27 | await self._stack.__aenter__() |
| 28 | |
| 29 | try: |
| 30 | ctx = self._create_context() |
| 31 | result = await self._stack.enter_async_context(ctx) |
| 32 | |
| 33 | if len(result) == 2: |
| 34 | read, write = result |
| 35 | elif len(result) == 3: |
| 36 | read, write, _ = result |
| 37 | else: |
| 38 | raise ValueError(f"Unexpected context result: {result}") |
| 39 | |
| 40 | session_ctx = ClientSession(read, write) |
| 41 | self.session = await self._stack.enter_async_context(session_ctx) |
| 42 | await self.session.initialize() |
| 43 | return self |
| 44 | except BaseException: |
| 45 | await self._stack.__aexit__(None, None, None) |
| 46 | raise |
| 47 | |
| 48 | async def __aexit__(self, exc_type, exc_val, exc_tb): |
| 49 | """Clean up MCP server connection resources.""" |
| 50 | if self._stack: |
| 51 | await self._stack.__aexit__(exc_type, exc_val, exc_tb) |
| 52 | self.session = None |
| 53 | self._stack = None |
| 54 | |
| 55 | async def list_tools(self) -> list[dict[str, Any]]: |
| 56 | """Retrieve available tools from the MCP server.""" |
| 57 | response = await self.session.list_tools() |
| 58 | return [ |
| 59 | { |
| 60 | "name": tool.name, |
| 61 | "description": tool.description, |
| 62 | "input_schema": tool.inputSchema, |
| 63 | } |
| 64 | for tool in response.tools |
| 65 | ] |
| 66 | |
| 67 | async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any: |
| 68 | """Call a tool on the MCP server with provided arguments.""" |
| 69 | result = await self.session.call_tool(tool_name, arguments=arguments) |
| 70 | return result.content |
nothing calls this directly
no outgoing calls
no test coverage detected