mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-24 06:24:18 +02:00
202 lines
No EOL
6.7 KiB
Text
202 lines
No EOL
6.7 KiB
Text
---
|
|
title: Client Overview
|
|
sidebarTitle: Overview
|
|
description: Learn how to use the FastMCP Client to programmatically interact with MCP servers.
|
|
icon: user-robot
|
|
---
|
|
|
|
import { VersionBadge } from '/snippets/version-badge.mdx'
|
|
|
|
<VersionBadge version="2.0.0" />
|
|
|
|
The `fastmcp.Client` is a **programmatic client** for interacting with any Model Context Protocol (MCP) server. It provides a high-level, well-typed, Pythonic interface for deterministic MCP access, making it ideal for:
|
|
|
|
- **Testing MCP servers** during development
|
|
- **Building deterministic applications** that need reliable MCP interactions
|
|
- **Creating the foundation for agentic or LLM-based clients** with structured, type-safe operations
|
|
|
|
|
|
<Note>
|
|
This is not an agentic client - it requires explicit function calls and provides direct control over all MCP operations. Use it as a building block for higher-level systems.
|
|
</Note>
|
|
|
|
## Quick Start
|
|
|
|
Note that all client operations require using the `async with` context manager for proper connection lifecycle management. The client uses transport inference to automatically determine the connection method.
|
|
|
|
```python
|
|
import asyncio
|
|
from fastmcp import Client, FastMCP
|
|
|
|
# In-memory server (ideal for testing)
|
|
server = FastMCP("TestServer")
|
|
client = Client(server)
|
|
|
|
# HTTP server
|
|
client = Client("https://example.com/mcp")
|
|
|
|
# Local Python script
|
|
client = Client("my_mcp_server.py")
|
|
|
|
async def main():
|
|
async with client:
|
|
# Basic server interaction
|
|
await client.ping()
|
|
|
|
# List available operations
|
|
tools = await client.list_tools()
|
|
resources = await client.list_resources()
|
|
prompts = await client.list_prompts()
|
|
|
|
# Execute operations
|
|
result = await client.call_tool("example_tool", {"param": "value"})
|
|
print(result)
|
|
|
|
asyncio.run(main())
|
|
```
|
|
|
|
## Client-Transport Architecture
|
|
|
|
The FastMCP Client separates concerns between protocol and connection:
|
|
|
|
- **`Client`**: Handles MCP protocol operations (tools, resources, prompts) and manages callbacks
|
|
- **`Transport`**: Establishes and maintains the connection (WebSockets, HTTP, Stdio, in-memory)
|
|
|
|
### Transport Inference
|
|
|
|
The client automatically infers the appropriate transport based on the input:
|
|
|
|
1. **`FastMCP` instance** → In-memory transport (perfect for testing)
|
|
2. **File path ending in `.py`** → Python Stdio transport
|
|
3. **File path ending in `.js`** → Node.js Stdio transport
|
|
4. **URL starting with `http://` or `https://`** → HTTP transport
|
|
5. **`MCPConfig` dictionary** → Multi-server client
|
|
|
|
```python
|
|
from fastmcp import Client, FastMCP
|
|
|
|
# Examples of transport inference
|
|
client_memory = Client(FastMCP("TestServer"))
|
|
client_script = Client("./server.py")
|
|
client_http = Client("https://api.example.com/mcp")
|
|
```
|
|
|
|
<Tip>
|
|
For testing and development, always prefer the in-memory transport by passing a `FastMCP` server directly to the client. This eliminates network complexity and separate processes.
|
|
</Tip>
|
|
|
|
## Configuration-Based Clients
|
|
|
|
<VersionBadge version="2.4.0" />
|
|
|
|
Create clients from MCP configuration dictionaries, which can include multiple servers. While there is no official standard for MCP configuration format, FastMCP follows established conventions used by tools like Claude Desktop.
|
|
|
|
### Configuration Format
|
|
|
|
```python
|
|
config = {
|
|
"mcpServers": {
|
|
"server_name": {
|
|
# Remote HTTP/SSE server
|
|
"transport": "streamable-http", # or "sse"
|
|
"url": "https://api.example.com/mcp",
|
|
"headers": {"Authorization": "Bearer token"},
|
|
"auth": "oauth" # or bearer token string
|
|
},
|
|
"local_server": {
|
|
# Local stdio server
|
|
"transport": "stdio"
|
|
"command": "python",
|
|
"args": ["./server.py", "--verbose"],
|
|
"env": {"DEBUG": "true"},
|
|
"cwd": "/path/to/server",
|
|
}
|
|
}
|
|
}
|
|
```
|
|
|
|
### Multi-Server Example
|
|
|
|
```python
|
|
config = {
|
|
"mcpServers": {
|
|
"weather": {"url": "https://weather-api.example.com/mcp"},
|
|
"assistant": {"command": "python", "args": ["./assistant_server.py"]}
|
|
}
|
|
}
|
|
|
|
client = Client(config)
|
|
|
|
async with client:
|
|
# Tools are prefixed with server names
|
|
weather_data = await client.call_tool("weather_get_forecast", {"city": "London"})
|
|
response = await client.call_tool("assistant_answer_question", {"question": "What's the capital of France?"})
|
|
|
|
# Resources use prefixed URIs
|
|
icons = await client.read_resource("weather://weather/icons/sunny")
|
|
templates = await client.read_resource("resource://assistant/templates/list")
|
|
```
|
|
|
|
## Connection Lifecycle
|
|
|
|
The client operates asynchronously and uses context managers for connection management:
|
|
|
|
```python
|
|
async def example():
|
|
client = Client("my_mcp_server.py")
|
|
|
|
# Connection established here
|
|
async with client:
|
|
print(f"Connected: {client.is_connected()}")
|
|
|
|
# Make multiple calls within the same session
|
|
tools = await client.list_tools()
|
|
result = await client.call_tool("greet", {"name": "World"})
|
|
|
|
# Connection closed automatically here
|
|
print(f"Connected: {client.is_connected()}")
|
|
```
|
|
|
|
## Core Operations
|
|
|
|
The client provides methods for all standard MCP operations:
|
|
|
|
| Operation | Method | Description |
|
|
|-----------|--------|-------------|
|
|
| **Tools** | `list_tools()`, `call_tool()` | Execute server-side functions |
|
|
| **Resources** | `list_resources()`, `read_resource()` | Access server data sources |
|
|
| **Prompts** | `list_prompts()`, `get_prompt()` | Retrieve message templates |
|
|
| **Utility** | `ping()` | Test server connectivity |
|
|
|
|
### Server Connectivity
|
|
|
|
Use `ping()` to verify the server is reachable:
|
|
|
|
```python
|
|
async with client:
|
|
await client.ping()
|
|
print("Server is reachable")
|
|
```
|
|
|
|
## Next Steps
|
|
|
|
Explore the detailed documentation for each operation type:
|
|
|
|
### Core Interactions
|
|
- **[Tools](/clients/tools)** - Execute server-side functions and handle results
|
|
- **[Resources](/clients/resources)** - Access static and templated resources
|
|
- **[Prompts](/clients/prompts)** - Work with message templates and argument serialization
|
|
|
|
### Advanced Features
|
|
- **[Logging](/clients/logging)** - Handle server log messages
|
|
- **[Progress](/clients/progress)** - Monitor long-running operations
|
|
- **[Sampling](/clients/sampling)** - Respond to server LLM requests
|
|
- **[Roots](/clients/roots)** - Provide local context to servers
|
|
|
|
### Connection Details
|
|
- **[Transports](/clients/transports)** - Configure connection methods and parameters
|
|
- **[Authentication](/clients/auth/oauth)** - Set up OAuth and bearer token authentication
|
|
|
|
<Tip>
|
|
The FastMCP Client is designed as a foundational tool. Use it directly for deterministic operations, or build higher-level agentic systems on top of its reliable, type-safe interface.
|
|
</Tip> |