|
| 1 | +"""Example demonstrating how to implement a custom transport |
| 2 | +that complies with `BaseClientSession` without using read/write streams or JSON-RPC. |
| 3 | +""" |
| 4 | + |
| 5 | +import asyncio |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +from mcp import types |
| 9 | +from mcp.client.base_client_session import BaseClientSession |
| 10 | +from mcp.shared.session import ProgressFnT |
| 11 | + |
| 12 | + |
| 13 | +class CustomDirectSession: |
| 14 | + """A custom MCP session that communicates with a hypothetical internal API |
| 15 | + rather than using streaming JSON-RPC. |
| 16 | +
|
| 17 | + It satisfies the `BaseClientSession` protocol simply by implementing the required |
| 18 | + methods – no inheritance from `BaseSession` or stream initialization required! |
| 19 | + """ |
| 20 | + |
| 21 | + async def initialize(self) -> types.InitializeResult: |
| 22 | + print("[CustomSession] Initializing custom transport...") |
| 23 | + return types.InitializeResult( |
| 24 | + protocolVersion="2024-11-05", |
| 25 | + capabilities=types.ServerCapabilities(), |
| 26 | + serverInfo=types.Implementation(name="CustomDirectServer", version="1.0.0"), |
| 27 | + ) |
| 28 | + |
| 29 | + async def list_tools(self, *, params: types.PaginatedRequestParams | None = None) -> types.ListToolsResult: |
| 30 | + print("[CustomSession] Fetching tools...") |
| 31 | + return types.ListToolsResult( |
| 32 | + tools=[ |
| 33 | + types.Tool( |
| 34 | + name="direct_tool", |
| 35 | + description="A tool executed via direct internal Python call", |
| 36 | + inputSchema={"type": "object", "properties": {}}, |
| 37 | + ) |
| 38 | + ] |
| 39 | + ) |
| 40 | + |
| 41 | + async def call_tool( |
| 42 | + self, |
| 43 | + name: str, |
| 44 | + arguments: dict[str, Any] | None = None, |
| 45 | + read_timeout_seconds: float | None = None, |
| 46 | + progress_callback: ProgressFnT | None = None, |
| 47 | + *, |
| 48 | + meta: types.RequestParamsMeta | None = None, |
| 49 | + ) -> types.CallToolResult: |
| 50 | + print(f"[CustomSession] Executing tool '{name}'...") |
| 51 | + return types.CallToolResult( |
| 52 | + content=[ |
| 53 | + types.TextContent( |
| 54 | + type="text", text=f"Hello from the custom transport! Tool '{name}' executed successfully." |
| 55 | + ) |
| 56 | + ] |
| 57 | + ) |
| 58 | + |
| 59 | + # Note: To fully satisfy the structural protocol of BaseClientSession for static |
| 60 | + # type checking (mypy/pyright), all protocol methods must be defined. |
| 61 | + # Here we stub the remaining methods for brevity. |
| 62 | + async def send_ping(self, *, meta: types.RequestParamsMeta | None = None) -> types.EmptyResult: |
| 63 | + return types.EmptyResult() |
| 64 | + |
| 65 | + async def send_request(self, *args: Any, **kwargs: Any) -> Any: |
| 66 | + raise NotImplementedError() |
| 67 | + |
| 68 | + async def send_notification(self, *args: Any, **kwargs: Any) -> None: |
| 69 | + raise NotImplementedError() |
| 70 | + |
| 71 | + async def send_progress_notification(self, *args: Any, **kwargs: Any) -> None: |
| 72 | + raise NotImplementedError() |
| 73 | + |
| 74 | + async def list_resources(self, *args: Any, **kwargs: Any) -> Any: |
| 75 | + raise NotImplementedError() |
| 76 | + |
| 77 | + async def list_resource_templates(self, *args: Any, **kwargs: Any) -> Any: |
| 78 | + raise NotImplementedError() |
| 79 | + |
| 80 | + async def read_resource(self, *args: Any, **kwargs: Any) -> Any: |
| 81 | + raise NotImplementedError() |
| 82 | + |
| 83 | + async def subscribe_resource(self, *args: Any, **kwargs: Any) -> Any: |
| 84 | + raise NotImplementedError() |
| 85 | + |
| 86 | + async def unsubscribe_resource(self, *args: Any, **kwargs: Any) -> Any: |
| 87 | + raise NotImplementedError() |
| 88 | + |
| 89 | + async def list_prompts(self, *args: Any, **kwargs: Any) -> Any: |
| 90 | + raise NotImplementedError() |
| 91 | + |
| 92 | + async def get_prompt(self, *args: Any, **kwargs: Any) -> Any: |
| 93 | + raise NotImplementedError() |
| 94 | + |
| 95 | + async def complete(self, *args: Any, **kwargs: Any) -> Any: |
| 96 | + raise NotImplementedError() |
| 97 | + |
| 98 | + async def set_logging_level(self, *args: Any, **kwargs: Any) -> Any: |
| 99 | + raise NotImplementedError() |
| 100 | + |
| 101 | + async def send_roots_list_changed(self, *args: Any, **kwargs: Any) -> None: |
| 102 | + raise NotImplementedError() |
| 103 | + |
| 104 | + |
| 105 | +# --------------------------------------------------------------------------- |
| 106 | +# Using the session with code strictly typed against BaseClientSession |
| 107 | +# --------------------------------------------------------------------------- |
| 108 | + |
| 109 | +async def interact_with_mcp(session: BaseClientSession) -> None: |
| 110 | + """This function doesn't know or care if the session is communicating |
| 111 | + via stdio streams, SSE, or a custom internal API! |
| 112 | + It only depends on the abstract `BaseClientSession` methods. |
| 113 | + """ |
| 114 | + |
| 115 | + # 1. Initialize |
| 116 | + init_result = await session.initialize() |
| 117 | + print(f"Connected to: {init_result.serverInfo.name}@{init_result.serverInfo.version}") |
| 118 | + |
| 119 | + # 2. List Tools |
| 120 | + tools_result = await session.list_tools() |
| 121 | + for tool in tools_result.tools: |
| 122 | + print(f"Found tool: {tool.name} - {tool.description}") |
| 123 | + |
| 124 | + # 3. Call Tool |
| 125 | + if tools_result.tools: |
| 126 | + call_result = await session.call_tool(tools_result.tools[0].name, arguments={}) |
| 127 | + for content in call_result.content: |
| 128 | + if isinstance(content, types.TextContent): |
| 129 | + print(f"Tool Output: {content.text}") |
| 130 | + |
| 131 | + |
| 132 | +async def main(): |
| 133 | + # Instantiate our custom non-streaming transport session |
| 134 | + custom_session = CustomDirectSession() |
| 135 | + |
| 136 | + # Pass it to the generic runner! |
| 137 | + await interact_with_mcp(custom_session) |
| 138 | + |
| 139 | + |
| 140 | +if __name__ == "__main__": |
| 141 | + asyncio.run(main()) |
0 commit comments