MCPcopy
hub / github.com/modelcontextprotocol/python-sdk / Client

Class Client

src/mcp/client/client.py:128–504  ·  view source on GitHub ↗

A high-level MCP client for connecting to MCP servers. Supports in-memory transport for testing (pass a Server or MCPServer instance), Streamable HTTP transport (pass a URL string), or a custom Transport instance. Example: ```python from mcp.client import Client

Source from the content-addressed store, hash-verified

126
127@dataclass
128class Client:
129 """A high-level MCP client for connecting to MCP servers.
130
131 Supports in-memory transport for testing (pass a Server or MCPServer instance),
132 Streamable HTTP transport (pass a URL string), or a custom Transport instance.
133
134 Example:
135 ```python
136 from mcp.client import Client
137 from mcp.server.mcpserver import MCPServer
138
139 server = MCPServer("test")
140
141 @server.tool()
142 def add(a: int, b: int) -> int:
143 return a + b
144
145 async def main():
146 async with Client(server) as client:
147 result = await client.call_tool("add", {"a": 1, "b": 2})
148
149 asyncio.run(main())
150 ```
151 """
152
153 server: Server[Any] | MCPServer | Transport | str
154 """The MCP server to connect to.
155
156 If the server is a `Server` or `MCPServer` instance, it will be connected in-process.
157 If the server is a URL string, it will be used as the URL for a `streamable_http_client` transport.
158 If the server is a `Transport` instance, it will be used directly.
159 """
160
161 _: KW_ONLY
162
163 # TODO(Marcelo): When do `raise_exceptions=True` actually raises?
164 raise_exceptions: bool = False
165 """Whether to raise exceptions from the server."""
166
167 read_timeout_seconds: float | None = None
168 """Timeout for read operations."""
169
170 sampling_callback: SamplingFnT | None = None
171 """Callback for handling sampling requests."""
172
173 list_roots_callback: ListRootsFnT | None = None
174 """Callback for handling list roots requests."""
175
176 logging_callback: LoggingFnT | None = None
177 """Callback for handling logging notifications."""
178
179 # TODO(Marcelo): Why do we have both "callback" and "handler"?
180 message_handler: MessageHandlerFnT | None = None
181 """Callback for handling raw messages."""
182
183 client_info: Implementation | None = None
184 """Client implementation info to send to server."""
185

Calls

no outgoing calls