0
# Client Operations
1
2
Core client functionality for connecting to and interacting with MCP servers. The client APIs provide session management, tool calling, resource access, and prompt handling with support for multiple concurrent server connections.
3
4
## Capabilities
5
6
### ClientSession
7
8
Primary client class for managing individual connections to MCP servers with full protocol support.
9
10
```python { .api }
11
class ClientSession:
12
def __init__(
13
self,
14
read_stream: MemoryObjectReceiveStream,
15
write_stream: MemoryObjectSendStream,
16
read_timeout_seconds: timedelta | None = None,
17
sampling_callback: Callable | None = None,
18
elicitation_callback: Callable | None = None,
19
list_roots_callback: Callable | None = None,
20
logging_callback: Callable | None = None,
21
message_handler: Callable | None = None,
22
client_info: Implementation | None = None,
23
):
24
"""
25
Initialize a client session for communicating with an MCP server.
26
27
Parameters:
28
- read_stream: Stream for receiving messages from server
29
- write_stream: Stream for sending messages to server
30
- read_timeout_seconds: Timeout for read operations
31
- sampling_callback: Callback for LLM sampling requests
32
- elicitation_callback: Callback for user input requests
33
- list_roots_callback: Callback for root directory listing
34
- logging_callback: Callback for server log messages
35
- message_handler: Custom message handler
36
- client_info: Client implementation metadata
37
"""
38
39
async def initialize(self) -> InitializeResult:
40
"""
41
Initialize the MCP connection with the server.
42
43
Returns:
44
InitializeResult containing server capabilities and metadata
45
"""
46
47
async def list_tools(self, cursor: str | None = None) -> ListToolsResult:
48
"""
49
List all available tools from the server.
50
51
Parameters:
52
- cursor: Pagination cursor for continuation
53
54
Returns:
55
ListToolsResult containing tools and optional next cursor
56
"""
57
58
async def call_tool(
59
self,
60
name: str,
61
arguments: dict[str, Any] | None = None
62
) -> CallToolResult:
63
"""
64
Call a specific tool with provided arguments.
65
66
Parameters:
67
- name: Name of the tool to call
68
- arguments: Tool arguments as key-value pairs
69
70
Returns:
71
CallToolResult containing tool output content
72
"""
73
74
async def list_resources(self, cursor: str | None = None) -> ListResourcesResult:
75
"""
76
List all available resources from the server.
77
78
Parameters:
79
- cursor: Pagination cursor for continuation
80
81
Returns:
82
ListResourcesResult containing resources and optional next cursor
83
"""
84
85
async def list_resource_templates(self, cursor: str | None = None) -> ListResourceTemplatesResult:
86
"""
87
List all available resource templates from the server.
88
89
Parameters:
90
- cursor: Pagination cursor for continuation
91
92
Returns:
93
ListResourceTemplatesResult containing resource templates and optional next cursor
94
"""
95
96
async def read_resource(self, uri: AnyUrl) -> ReadResourceResult:
97
"""
98
Read the content of a specific resource.
99
100
Parameters:
101
- uri: URI of the resource to read
102
103
Returns:
104
ReadResourceResult containing resource content
105
"""
106
107
async def subscribe_resource(self, uri: AnyUrl) -> EmptyResult:
108
"""
109
Subscribe to updates for a specific resource.
110
111
Parameters:
112
- uri: URI of the resource to subscribe to
113
114
Returns:
115
EmptyResult indicating success
116
"""
117
118
async def unsubscribe_resource(self, uri: AnyUrl) -> EmptyResult:
119
"""
120
Unsubscribe from updates for a specific resource.
121
122
Parameters:
123
- uri: URI of the resource to unsubscribe from
124
125
Returns:
126
EmptyResult indicating success
127
"""
128
129
async def list_prompts(self, cursor: str | None = None) -> ListPromptsResult:
130
"""
131
List all available prompts from the server.
132
133
Parameters:
134
- cursor: Pagination cursor for continuation
135
136
Returns:
137
ListPromptsResult containing prompts and optional next cursor
138
"""
139
140
async def get_prompt(
141
self,
142
name: str,
143
arguments: dict[str, str] | None = None
144
) -> GetPromptResult:
145
"""
146
Get a specific prompt with provided arguments.
147
148
Parameters:
149
- name: Name of the prompt to get
150
- arguments: Prompt arguments as key-value pairs
151
152
Returns:
153
GetPromptResult containing prompt messages
154
"""
155
156
async def set_logging_level(self, level: LoggingLevel) -> EmptyResult:
157
"""
158
Set the logging level for server messages.
159
160
Parameters:
161
- level: Logging level (DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY)
162
163
Returns:
164
EmptyResult indicating success
165
"""
166
167
async def send_progress_notification(
168
self,
169
progress_token: ProgressToken,
170
progress: float,
171
total: float | None = None
172
) -> None:
173
"""
174
Send progress notification to server.
175
176
Parameters:
177
- progress_token: Token identifying the operation
178
- progress: Current progress value
179
- total: Total expected value (optional)
180
"""
181
182
async def send_ping(self) -> EmptyResult:
183
"""
184
Send ping request to server for connection health check.
185
186
Returns:
187
EmptyResult indicating server responded to ping
188
"""
189
190
async def complete(
191
self,
192
ref: CompletionReference,
193
argument: CompletionArgument | None = None
194
) -> CompleteResult:
195
"""
196
Request completion suggestions for prompts or resources.
197
198
Parameters:
199
- ref: Reference to prompt or resource for completion
200
- argument: Optional completion argument context
201
202
Returns:
203
CompleteResult containing completion suggestions
204
"""
205
206
async def send_roots_list_changed(self) -> None:
207
"""
208
Send notification that the roots directory listing has changed.
209
Used to inform the server about changes in available root directories.
210
"""
211
```
212
213
### ClientSessionGroup
214
215
Multi-session manager for coordinating connections to multiple MCP servers simultaneously with aggregated tool/resource access.
216
217
```python { .api }
218
class ClientSessionGroup:
219
def __init__(
220
self,
221
exit_stack: AsyncExitStack | None = None,
222
component_name_hook: Callable | None = None,
223
):
224
"""
225
Initialize a client session group for managing multiple server connections.
226
227
Parameters:
228
- exit_stack: Async context manager stack for cleanup
229
- component_name_hook: Hook for customizing component names
230
"""
231
232
async def connect_to_server(self, server_params: ServerParameters) -> ClientSession:
233
"""
234
Connect to an MCP server and add to the group.
235
236
Parameters:
237
- server_params: Server connection parameters
238
239
Returns:
240
ClientSession for the connected server
241
"""
242
243
async def disconnect_from_server(self, session: ClientSession) -> None:
244
"""
245
Disconnect from a server and remove from the group.
246
247
Parameters:
248
- session: ClientSession to disconnect
249
"""
250
251
async def call_tool(self, name: str, args: dict[str, Any]) -> CallToolResult:
252
"""
253
Call a tool from any connected server by name.
254
255
Parameters:
256
- name: Name of the tool to call
257
- args: Tool arguments
258
259
Returns:
260
CallToolResult from the server that provides the tool
261
"""
262
263
@property
264
def sessions(self) -> list[ClientSession]:
265
"""List of all active client sessions."""
266
267
@property
268
def tools(self) -> dict[str, Tool]:
269
"""Dictionary of all available tools from all connected servers."""
270
271
@property
272
def resources(self) -> dict[str, Resource]:
273
"""Dictionary of all available resources from all connected servers."""
274
275
@property
276
def prompts(self) -> dict[str, Prompt]:
277
"""Dictionary of all available prompts from all connected servers."""
278
```
279
280
### Transport Client Functions
281
282
Functions for creating client transport connections to MCP servers.
283
284
```python { .api }
285
def stdio_client(server: StdioServerParameters) -> AsyncContextManager:
286
"""
287
Create a stdio transport client connection.
288
289
Parameters:
290
- server: Stdio server parameters
291
292
Returns:
293
Async context manager yielding (read_stream, write_stream)
294
"""
295
296
def websocket_client(url: str, **kwargs) -> AsyncContextManager:
297
"""
298
Create a WebSocket client connection.
299
300
Parameters:
301
- url: WebSocket server URL
302
- **kwargs: Additional connection options
303
304
Returns:
305
Async context manager yielding (read_stream, write_stream)
306
"""
307
308
def sse_client(
309
url: str,
310
headers: dict[str, str] | None = None,
311
**kwargs
312
) -> AsyncContextManager:
313
"""
314
Create a Server-Sent Events client connection.
315
316
Parameters:
317
- url: SSE endpoint URL
318
- headers: HTTP headers for connection
319
- **kwargs: Additional connection options
320
321
Returns:
322
Async context manager yielding (read_stream, write_stream)
323
"""
324
325
def streamablehttp_client(
326
url: str,
327
headers: dict[str, str] | None = None,
328
**kwargs
329
) -> AsyncContextManager:
330
"""
331
Create a streaming HTTP client connection.
332
333
Parameters:
334
- url: HTTP endpoint URL
335
- headers: HTTP headers for connection
336
- **kwargs: Additional connection options
337
338
Returns:
339
Async context manager yielding (read_stream, write_stream)
340
"""
341
```
342
343
### Transport Configuration Classes
344
345
Configuration classes for different transport types.
346
347
```python { .api }
348
class StdioServerParameters:
349
def __init__(
350
self,
351
command: str | list[str],
352
args: list[str] | None = None,
353
env: dict[str, str] | None = None,
354
cwd: str | None = None,
355
):
356
"""
357
Parameters for stdio server connection.
358
359
Parameters:
360
- command: Server command to execute
361
- args: Command arguments
362
- env: Environment variables
363
- cwd: Working directory
364
"""
365
366
class SseServerParameters:
367
def __init__(
368
self,
369
url: str,
370
headers: dict[str, str] | None = None,
371
**kwargs
372
):
373
"""
374
Parameters for Server-Sent Events connection.
375
376
Parameters:
377
- url: SSE endpoint URL
378
- headers: HTTP headers
379
- **kwargs: Additional options
380
"""
381
382
class StreamableHttpParameters:
383
def __init__(
384
self,
385
url: str,
386
headers: dict[str, str] | None = None,
387
**kwargs
388
):
389
"""
390
Parameters for streaming HTTP connection.
391
392
Parameters:
393
- url: HTTP endpoint URL
394
- headers: HTTP headers
395
- **kwargs: Additional options
396
"""
397
```
398
399
### Client Authentication
400
401
Client-side authentication utilities for connecting to secured MCP servers.
402
403
```python { .api }
404
class ClientAuth:
405
def __init__(self, token: str | None = None, **kwargs):
406
"""
407
Client authentication handler.
408
409
Parameters:
410
- token: Bearer token for authentication
411
- **kwargs: Additional auth options
412
"""
413
414
async def get_headers(self) -> dict[str, str]:
415
"""
416
Get authentication headers for requests.
417
418
Returns:
419
Dictionary of HTTP headers for authentication
420
"""
421
422
class AuthenticationError(Exception):
423
"""Exception raised for authentication failures."""
424
```
425
426
## Usage Examples
427
428
### Basic Client Connection
429
430
```python
431
import asyncio
432
import mcp
433
434
async def basic_client():
435
# Connect to a stdio server
436
server_params = mcp.StdioServerParameters(
437
command=["python", "my_server.py"]
438
)
439
440
async with mcp.stdio_client(server_params) as (read, write):
441
async with mcp.ClientSession(read, write) as session:
442
# Initialize connection
443
result = await session.initialize()
444
print(f"Connected to: {result.server_info.name}")
445
446
# List and call tools
447
tools = await session.list_tools()
448
if tools.tools:
449
tool_result = await session.call_tool(
450
tools.tools[0].name,
451
{"input": "test"}
452
)
453
print(f"Tool result: {tool_result}")
454
455
asyncio.run(basic_client())
456
```
457
458
### Multi-Server Management
459
460
```python
461
import asyncio
462
import mcp
463
464
async def multi_server_client():
465
async with mcp.ClientSessionGroup() as group:
466
# Connect to multiple servers
467
server1 = mcp.StdioServerParameters(command=["server1"])
468
server2 = mcp.StdioServerParameters(command=["server2"])
469
470
session1 = await group.connect_to_server(server1)
471
session2 = await group.connect_to_server(server2)
472
473
# Access aggregated tools from all servers
474
print(f"All tools: {list(group.tools.keys())}")
475
476
# Call tools from any server
477
result = await group.call_tool("any_tool_name", {"param": "value"})
478
print(f"Result: {result}")
479
480
asyncio.run(multi_server_client())
481
```
482
483
### WebSocket Client
484
485
```python
486
import asyncio
487
import mcp
488
489
async def websocket_client_example():
490
async with mcp.websocket_client("ws://localhost:8000/mcp") as (read, write):
491
async with mcp.ClientSession(read, write) as session:
492
await session.initialize()
493
494
# Use WebSocket connection
495
resources = await session.list_resources()
496
for resource in resources.resources:
497
content = await session.read_resource(resource.uri)
498
print(f"Resource {resource.name}: {content}")
499
500
asyncio.run(websocket_client_example())
501
```