Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

pypi-fastmcp

Describes: pypipypi/fastmcp

Description
The fast, Pythonic way to build MCP servers and clients with minimal boilerplate code.
Author
tessl
Last updated

How to use

npx @tessl/cli registry install tessl/pypi-fastmcp@2.12.0

client.md docs/

1
# Client Library
2
3
Full-featured MCP client supporting multiple transports, authentication, and advanced features like LLM sampling. The FastMCP client allows you to connect to and interact with any MCP server programmatically.
4
5
## Capabilities
6
7
### Client Class
8
9
Main client implementation for connecting to MCP servers with support for multiple transports and authentication methods.
10
11
```python { .api }
12
class Client:
13
def __init__(
14
self,
15
server_or_config: str | FastMCP | dict,
16
transport: ClientTransport | None = None,
17
auth: BearerAuth | OAuth | None = None,
18
sampling_handler: SamplingHandler | None = None,
19
elicitation_handler: ElicitationHandler | None = None,
20
timeout: float = 30.0
21
):
22
"""
23
Create a client to connect to an MCP server.
24
25
Parameters:
26
- server_or_config: Server script path, FastMCP instance, or MCP config
27
- transport: Specific transport to use (auto-detected if None)
28
- auth: Authentication for secured servers
29
- sampling_handler: Handler for server LLM sampling requests
30
- elicitation_handler: Handler for server elicitation requests
31
- timeout: Request timeout in seconds
32
"""
33
```
34
35
### Tool Operations
36
37
List and call tools available on the connected MCP server.
38
39
```python { .api }
40
async def list_tools(self) -> list[dict]:
41
"""
42
List all available tools on the server.
43
44
Returns:
45
List of tool metadata dictionaries with name, description, and schema
46
"""
47
48
async def call_tool(
49
self,
50
name: str,
51
arguments: dict | None = None
52
) -> ToolResult:
53
"""
54
Call a tool on the server.
55
56
Parameters:
57
- name: Tool name to call
58
- arguments: Tool arguments as dictionary
59
60
Returns:
61
Tool execution result with text content and optional metadata
62
"""
63
```
64
65
### Resource Operations
66
67
List and read resources available on the connected MCP server.
68
69
```python { .api }
70
async def list_resources(self) -> list[dict]:
71
"""
72
List all available resources on the server.
73
74
Returns:
75
List of resource metadata dictionaries with uri, name, description, and mime_type
76
"""
77
78
async def read_resource(self, uri: str) -> ResourceResult:
79
"""
80
Read a resource from the server.
81
82
Parameters:
83
- uri: Resource URI to read
84
85
Returns:
86
Resource content with text/binary data and metadata
87
"""
88
89
async def list_resource_templates(self) -> list[dict]:
90
"""
91
List all available resource templates on the server.
92
93
Returns:
94
List of resource template metadata with uri_template, name, and description
95
"""
96
```
97
98
### Prompt Operations
99
100
List and get prompts available on the connected MCP server.
101
102
```python { .api }
103
async def list_prompts(self) -> list[dict]:
104
"""
105
List all available prompts on the server.
106
107
Returns:
108
List of prompt metadata dictionaries with name, description, and schema
109
"""
110
111
async def get_prompt(
112
self,
113
name: str,
114
arguments: dict | None = None
115
) -> PromptResult:
116
"""
117
Get a prompt from the server.
118
119
Parameters:
120
- name: Prompt name to retrieve
121
- arguments: Prompt arguments as dictionary
122
123
Returns:
124
Prompt result with formatted messages
125
"""
126
```
127
128
### Connection Management
129
130
Context manager support for automatic connection lifecycle management.
131
132
```python { .api }
133
async def __aenter__(self) -> "Client":
134
"""Enter async context manager."""
135
136
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
137
"""Exit async context manager."""
138
139
async def close(self) -> None:
140
"""Close the client connection."""
141
```
142
143
## Usage Examples
144
145
### Basic Client Usage
146
147
```python
148
from fastmcp import Client
149
import asyncio
150
151
async def main():
152
# Connect to a server via stdio
153
async with Client("my_server.py") as client:
154
# List available capabilities
155
tools = await client.list_tools()
156
resources = await client.list_resources()
157
prompts = await client.list_prompts()
158
159
print(f"Available tools: {[t['name'] for t in tools]}")
160
print(f"Available resources: {[r['uri'] for r in resources]}")
161
print(f"Available prompts: {[p['name'] for p in prompts]}")
162
163
# Call a tool
164
result = await client.call_tool("add", {"a": 5, "b": 3})
165
print(f"Tool result: {result.text}")
166
167
# Read a resource
168
resource = await client.read_resource("config://version")
169
print(f"Resource content: {resource.content}")
170
171
# Get a prompt
172
prompt = await client.get_prompt("summarize", {"text": "Hello world"})
173
print(f"Prompt messages: {prompt.messages}")
174
175
asyncio.run(main())
176
```
177
178
### Client with Different Transports
179
180
```python
181
from fastmcp import Client
182
183
async def stdio_client():
184
"""Connect via stdio transport."""
185
async with Client("python server.py") as client:
186
result = await client.call_tool("hello", {"name": "World"})
187
return result.text
188
189
async def sse_client():
190
"""Connect via SSE transport."""
191
async with Client("http://localhost:8000/sse") as client:
192
tools = await client.list_tools()
193
return tools
194
195
async def http_client():
196
"""Connect via HTTP transport."""
197
async with Client("http://localhost:8000/mcp") as client:
198
resources = await client.list_resources()
199
return resources
200
201
# Auto-detection also works
202
async def auto_detect():
203
"""Client auto-detects transport type."""
204
clients = [
205
Client("./server.py"), # stdio
206
Client("http://localhost:8000/sse"), # SSE
207
Client("http://localhost:8000/mcp"), # HTTP
208
]
209
210
for client in clients:
211
async with client:
212
tools = await client.list_tools()
213
print(f"Connected with {len(tools)} tools")
214
```
215
216
### Client with Authentication
217
218
```python
219
from fastmcp import Client
220
from fastmcp.client.auth import BearerAuth, OAuth
221
222
async def authenticated_client():
223
"""Connect to secured server with Bearer token."""
224
auth = BearerAuth("your-bearer-token")
225
226
async with Client(
227
"https://secure-server.com/mcp",
228
auth=auth
229
) as client:
230
result = await client.call_tool("secure_operation", {})
231
return result.text
232
233
async def oauth_client():
234
"""Connect with OAuth authentication."""
235
oauth = OAuth(
236
client_id="your-client-id",
237
client_secret="your-client-secret",
238
token_url="https://auth.example.com/token"
239
)
240
241
async with Client(
242
"https://api.example.com/mcp",
243
auth=oauth
244
) as client:
245
result = await client.call_tool("api_operation", {})
246
return result.text
247
```
248
249
### Client with LLM Sampling Handler
250
251
```python
252
from fastmcp import Client
253
254
async def sampling_handler(messages):
255
"""Handle server LLM sampling requests."""
256
# This would typically connect to your LLM
257
# For example, OpenAI GPT, Claude, etc.
258
response = "This is a sample response"
259
return {"text": response}
260
261
async def client_with_sampling():
262
"""Client that can handle server sampling requests."""
263
async with Client(
264
"intelligent_server.py",
265
sampling_handler=sampling_handler
266
) as client:
267
# Server can now request LLM completions via ctx.sample()
268
result = await client.call_tool("analyze_data", {
269
"data": "Some complex data to analyze"
270
})
271
return result.text
272
```
273
274
### Multi-Server Client Configuration
275
276
```python
277
from fastmcp import Client
278
279
async def multi_server_client():
280
"""Connect to multiple servers with unified client."""
281
config = {
282
"mcpServers": {
283
"weather": {
284
"url": "https://weather-api.example.com/mcp"
285
},
286
"assistant": {
287
"command": "python",
288
"args": ["./assistant_server.py"]
289
},
290
"database": {
291
"url": "http://localhost:8080/mcp",
292
"auth": {"type": "bearer", "token": "db-token"}
293
}
294
}
295
}
296
297
async with Client(config) as client:
298
# Tools are prefixed with server names
299
forecast = await client.call_tool(
300
"weather_get_forecast",
301
{"city": "London"}
302
)
303
304
answer = await client.call_tool(
305
"assistant_answer_question",
306
{"query": "What is MCP?"}
307
)
308
309
data = await client.call_tool(
310
"database_query",
311
{"sql": "SELECT * FROM users LIMIT 10"}
312
)
313
314
return {
315
"forecast": forecast.text,
316
"answer": answer.text,
317
"data": data.text
318
}
319
```
320
321
### In-Memory Testing with FastMCP
322
323
```python
324
from fastmcp import FastMCP, Client
325
326
async def test_server_with_client():
327
"""Test a FastMCP server using in-memory client."""
328
# Create server
329
mcp = FastMCP("Test Server")
330
331
@mcp.tool
332
def multiply(a: int, b: int) -> int:
333
"""Multiply two numbers."""
334
return a * b
335
336
# Connect via in-memory transport (no subprocess)
337
async with Client(mcp) as client:
338
# Test the server directly
339
result = await client.call_tool("multiply", {"a": 6, "b": 7})
340
assert result.text == "42"
341
342
tools = await client.list_tools()
343
assert len(tools) == 1
344
assert tools[0]["name"] == "multiply"
345
```
346
347
## Result Types
348
349
```python { .api }
350
class ToolResult:
351
"""Result from calling a tool."""
352
text: str
353
content: list[dict] | None
354
is_error: bool
355
356
class ResourceResult:
357
"""Result from reading a resource."""
358
content: str | bytes
359
mime_type: str | None
360
uri: str
361
362
class PromptResult:
363
"""Result from getting a prompt."""
364
messages: list[dict]
365
description: str | None
366
```