mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-21 21:14:17 +02:00
Update client docs
Co-Authored-By: Claude <claude@users.noreply.github.com>
This commit is contained in:
parent
d12cebce1f
commit
8e98d711fc
11 changed files with 909 additions and 471 deletions
|
|
@ -1,152 +0,0 @@
|
|||
---
|
||||
title: Advanced Features
|
||||
sidebarTitle: Advanced Features
|
||||
description: Learn about the advanced features of the FastMCP Client.
|
||||
icon: stars
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
In addition to basic server interaction, FastMCP clients can also handle more advanced features and server interaction patterns. The `Client` constructor accepts additional configuration to handle these server requests.
|
||||
|
||||
<Tip>
|
||||
To enable many of these features, you must provide an appropriate handler or callback function. For example. In most cases, if you do not provide a handler, FastMCP's default handler will emit a `DEBUG` level log.
|
||||
</Tip>
|
||||
|
||||
## Logging and Notifications
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
MCP servers can emit logs to clients. To process these logs, you can provide a `log_handler` to the client.
|
||||
|
||||
The `log_handler` must be an async function that accepts a single argument, which is an instance of `fastmcp.client.logging.LogMessage`. This has attributes like `level`, `logger`, and `data`.
|
||||
|
||||
```python {2, 12}
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.logging import LogMessage
|
||||
|
||||
async def log_handler(message: LogMessage):
|
||||
level = message.level.upper()
|
||||
logger = message.logger or 'default'
|
||||
data = message.data
|
||||
print(f"[Server Log - {level}] {logger}: {data}")
|
||||
|
||||
client_with_logging = Client(
|
||||
...,
|
||||
log_handler=log_handler,
|
||||
)
|
||||
```
|
||||
## Progress Monitoring
|
||||
|
||||
<VersionBadge version="2.3.5" />
|
||||
|
||||
MCP servers can report progress during long-running operations. The client can set a progress handler to receive and process these updates.
|
||||
|
||||
```python {2, 13}
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.progress import ProgressHandler
|
||||
|
||||
async def my_progress_handler(
|
||||
progress: float,
|
||||
total: float | None,
|
||||
message: str | None
|
||||
) -> None:
|
||||
print(f"Progress: {progress} / {total} ({message})")
|
||||
|
||||
client = Client(
|
||||
...,
|
||||
progress_handler=my_progress_handler
|
||||
)
|
||||
```
|
||||
|
||||
By default, FastMCP uses a handler that logs progress updates at the debug level. This default handler properly handles cases where `total` or `message` might be None.
|
||||
|
||||
You can override the progress handler for specific tool calls:
|
||||
|
||||
```python
|
||||
# Client uses the default debug logger for progress
|
||||
client = Client(...)
|
||||
|
||||
async with client:
|
||||
# Use default progress handler (debug logging)
|
||||
result1 = await client.call_tool("long_task", {"param": "value"})
|
||||
|
||||
# Override with custom progress handler just for this call
|
||||
result2 = await client.call_tool(
|
||||
"another_task",
|
||||
{"param": "value"},
|
||||
progress_handler=my_progress_handler
|
||||
)
|
||||
```
|
||||
|
||||
A typical progress update includes:
|
||||
- Current progress value (e.g., 2 of 5 steps completed)
|
||||
- Total expected value (may be None)
|
||||
- Status message (may be None)
|
||||
|
||||
## LLM Sampling
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
MCP Servers can request LLM completions from clients. The client can provide a `sampling_handler` to handle these requests. The sampling handler receives a list of messages and other parameters from the server, and should return a string completion.
|
||||
|
||||
The following example uses the `marvin` library to generate a completion:
|
||||
|
||||
```python {8-17, 21}
|
||||
import marvin
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.sampling import (
|
||||
SamplingMessage,
|
||||
SamplingParams,
|
||||
RequestContext,
|
||||
)
|
||||
|
||||
async def sampling_handler(
|
||||
messages: list[SamplingMessage],
|
||||
params: SamplingParams,
|
||||
context: RequestContext
|
||||
) -> str:
|
||||
return await marvin.say_async(
|
||||
message=[m.content.text for m in messages],
|
||||
instructions=params.systemPrompt,
|
||||
)
|
||||
|
||||
client = Client(
|
||||
...,
|
||||
sampling_handler=sampling_handler,
|
||||
)
|
||||
```
|
||||
|
||||
|
||||
## Roots
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
Roots are a way for clients to inform servers about the resources they have access to or certain boundaries on their access. The server can use this information to adjust behavior or provide more accurate responses.
|
||||
|
||||
Servers can request roots from clients, and clients can notify servers when their roots change.
|
||||
|
||||
To set the roots when creating a client, users can either provide a list of roots (which can be a list of strings) or an async function that returns a list of roots.
|
||||
|
||||
<CodeGroup>
|
||||
```python Static Roots {5}
|
||||
from fastmcp import Client
|
||||
|
||||
client = Client(
|
||||
...,
|
||||
roots=["/path/to/root1", "/path/to/root2"],
|
||||
)
|
||||
```
|
||||
```python Dynamic Roots Callback {4-6, 10}
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.roots import RequestContext
|
||||
|
||||
async def roots_callback(context: RequestContext) -> list[str]:
|
||||
print(f"Server requested roots (Request ID: {context.request_id})")
|
||||
return ["/path/to/root1", "/path/to/root2"]
|
||||
|
||||
client = Client(
|
||||
...,
|
||||
roots=roots_callback,
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
---
|
||||
title: Client Overview
|
||||
sidebarTitle: Overview
|
||||
description: Learn how to use the FastMCP Client to interact with MCP servers.
|
||||
description: Learn how to use the FastMCP Client to programmatically interact with MCP servers.
|
||||
icon: user-robot
|
||||
---
|
||||
|
||||
|
|
@ -9,388 +9,198 @@ import { VersionBadge } from '/snippets/version-badge.mdx'
|
|||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
The `fastmcp.Client` provides a high-level, asynchronous interface for interacting with any Model Context Protocol (MCP) server, whether it's built with FastMCP or another implementation. It simplifies communication by handling protocol details and connection management.
|
||||
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:
|
||||
|
||||
## FastMCP Client
|
||||
- **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
|
||||
|
||||
The FastMCP Client architecture separates the protocol logic (`Client`) from the connection mechanism (`Transport`).
|
||||
All client operations require using the `async with` context manager for proper connection lifecycle management.
|
||||
|
||||
- **`Client`**: Handles sending MCP requests (like `tools/call`, `resources/read`), receiving responses, and managing callbacks.
|
||||
- **`Transport`**: Responsible for establishing and maintaining the connection to the server (e.g., via WebSockets, SSE, Stdio, or in-memory).
|
||||
<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>
|
||||
|
||||
### Transports
|
||||
## Quick Start
|
||||
|
||||
Clients must be initialized with a `transport`. You can either provide an already instantiated transport object, or provide a transport source and let FastMCP attempt to infer the correct transport to use.
|
||||
|
||||
The following inference rules are used to determine the appropriate `ClientTransport` based on the input type:
|
||||
|
||||
1. **`ClientTransport` Instance**: If you provide an already instantiated transport object, it's used directly.
|
||||
2. **`FastMCP` Instance**: Creates a `FastMCPTransport` for efficient in-memory communication (ideal for testing). This also works with a **FastMCP 1.0 server** created via `mcp.server.fastmcp.FastMCP`.
|
||||
3. **`Path` or `str` pointing to an existing file**:
|
||||
* If it ends with `.py`: Creates a `PythonStdioTransport` to run the script using `python`.
|
||||
* If it ends with `.js`: Creates a `NodeStdioTransport` to run the script using `node`.
|
||||
4. **`AnyUrl` or `str` pointing to a URL that begins with `http://` or `https://`**:
|
||||
* Creates a `StreamableHttpTransport`
|
||||
5. **`MCPConfig` or dictionary matching MCPConfig schema**: Creates a client that connects to one or more MCP servers specified in the config.
|
||||
6. **Other**: Raises a `ValueError` if the type cannot be inferred.
|
||||
The client uses transport inference to automatically determine the connection method:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from fastmcp import Client, FastMCP
|
||||
|
||||
# Example transports (more details in Transports page)
|
||||
server_instance = FastMCP(name="TestServer") # In-memory server
|
||||
http_url = "https://example.com/mcp" # HTTP server URL
|
||||
server_script = "my_mcp_server.py" # Path to a Python server file
|
||||
# In-memory server (ideal for testing)
|
||||
server = FastMCP("TestServer")
|
||||
client = Client(server)
|
||||
|
||||
# Client automatically infers the transport type
|
||||
client_in_memory = Client(server_instance)
|
||||
client_http = Client(http_url)
|
||||
# HTTP server
|
||||
client = Client("https://example.com/mcp")
|
||||
|
||||
client_stdio = Client(server_script)
|
||||
# Local Python script
|
||||
client = Client("my_mcp_server.py")
|
||||
|
||||
print(client_in_memory.transport)
|
||||
print(client_http.transport)
|
||||
print(client_stdio.transport)
|
||||
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)
|
||||
|
||||
# Expected Output (types may vary slightly based on environment):
|
||||
# <FastMCP(server='TestServer')>
|
||||
# <StreamableHttp(url='https://example.com/mcp')>
|
||||
# <PythonStdioTransport(command='python', args=['/path/to/your/my_mcp_server.py'])>
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
You can also initialize a client from an MCP configuration dictionary or `MCPConfig` file:
|
||||
## 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
|
||||
from fastmcp import Client, FastMCP
|
||||
|
||||
config = {
|
||||
"mcpServers": {
|
||||
"local": {"command": "python", "args": ["local_server.py"]},
|
||||
"remote": {"url": "https://example.com/mcp"},
|
||||
}
|
||||
}
|
||||
|
||||
client_config = Client(config)
|
||||
# Examples of transport inference
|
||||
client_memory = Client(FastMCP("TestServer"))
|
||||
client_script = Client("./server.py")
|
||||
client_http = Client("https://api.example.com/mcp")
|
||||
```
|
||||
|
||||
<Tip>
|
||||
For more control over connection details (like headers for SSE, environment variables for Stdio), you can instantiate the specific `ClientTransport` class yourself and pass it to the `Client`. See the [Transports](/clients/transports) page for details.
|
||||
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>
|
||||
|
||||
### Multi-Server Clients
|
||||
## Multi-Server Clients
|
||||
|
||||
<VersionBadge version="2.4.0" />
|
||||
|
||||
FastMCP supports creating clients that connect to multiple MCP servers through a single client interface using a standard MCP configuration format (`MCPConfig`). This configuration approach makes it easy to connect to multiple specialized servers or create composable systems with a simple, declarative syntax.
|
||||
|
||||
<Note>
|
||||
The MCP configuration format follows an emerging standard and may evolve as the specification matures. FastMCP will strive to maintain compatibility with future versions, but be aware that field names or structure might change.
|
||||
</Note>
|
||||
|
||||
When you create a client with an `MCPConfig` containing multiple servers:
|
||||
|
||||
1. FastMCP creates a composite client that internally mounts all servers using their config names as prefixes
|
||||
2. Tools and resources from each server are accessible with appropriate prefixes in the format `servername_toolname` and `protocol://servername/resource/path`
|
||||
3. You interact with this as a single unified client, with requests automatically routed to the appropriate server
|
||||
Connect to multiple MCP servers through a single client using MCP configuration:
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
|
||||
# Create a standard MCP configuration with multiple servers
|
||||
config = {
|
||||
"mcpServers": {
|
||||
# A remote HTTP server
|
||||
"weather": {
|
||||
"url": "https://weather-api.example.com/mcp",
|
||||
"transport": "streamable-http"
|
||||
},
|
||||
# A local server running via stdio
|
||||
"assistant": {
|
||||
"command": "python",
|
||||
"args": ["./my_assistant_server.py"],
|
||||
"env": {"DEBUG": "true"}
|
||||
}
|
||||
"weather": {"url": "https://weather-api.example.com/mcp"},
|
||||
"assistant": {"command": "python", "args": ["./assistant_server.py"]}
|
||||
}
|
||||
}
|
||||
|
||||
# Create a client that connects to both servers
|
||||
client = Client(config)
|
||||
|
||||
async def main():
|
||||
async with client:
|
||||
# Access tools from different servers with prefixes
|
||||
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?"})
|
||||
|
||||
# Access resources with prefixed URIs
|
||||
weather_icons = await client.read_resource("weather://weather/icons/sunny")
|
||||
templates = await client.read_resource("resource://assistant/templates/list")
|
||||
|
||||
print(f"Weather: {weather_data}")
|
||||
print(f"Assistant: {response}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
If your configuration has only a single server, FastMCP will create a direct client to that server without any prefixing.
|
||||
|
||||
## Client Usage
|
||||
|
||||
### Connection Lifecycle
|
||||
|
||||
The client operates asynchronously and must be used within an `async with` block. This context manager handles establishing the connection, initializing the MCP session, and cleaning up resources upon exit.
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from fastmcp import Client
|
||||
|
||||
client = Client("my_mcp_server.py") # Assumes my_mcp_server.py exists
|
||||
|
||||
async def main():
|
||||
# Connection is established here
|
||||
async with client:
|
||||
print(f"Client connected: {client.is_connected()}")
|
||||
|
||||
# Make MCP calls within the context
|
||||
tools = await client.list_tools()
|
||||
print(f"Available tools: {tools}")
|
||||
|
||||
if any(tool.name == "greet" for tool in tools):
|
||||
result = await client.call_tool("greet", {"name": "World"})
|
||||
print(f"Greet result: {result}")
|
||||
|
||||
# Connection is closed automatically here
|
||||
print(f"Client connected: {client.is_connected()}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
You can make multiple calls to the server within the same `async with` block using the established session.
|
||||
|
||||
### Client Methods
|
||||
|
||||
The `Client` provides methods corresponding to standard MCP requests:
|
||||
|
||||
<Warning>
|
||||
The standard client methods return user-friendly representations that may change as the protocol evolves. For consistent access to the complete data structure, use the `*_mcp` methods described later.
|
||||
</Warning>
|
||||
|
||||
#### Tool Operations
|
||||
|
||||
* **`list_tools()`**: Retrieves a list of tools available on the server.
|
||||
```python
|
||||
tools = await client.list_tools()
|
||||
# tools -> list[mcp.types.Tool]
|
||||
```
|
||||
* **`call_tool(name: str, arguments: dict[str, Any] | None = None, timeout: float | None = None, progress_handler: ProgressHandler | None = None)`**: Executes a tool on the server.
|
||||
```python
|
||||
result = await client.call_tool("add", {"a": 5, "b": 3})
|
||||
# result -> list[mcp.types.TextContent | mcp.types.ImageContent | ...]
|
||||
print(result[0].text) # Assuming TextContent, e.g., '8'
|
||||
|
||||
# With timeout (aborts if execution takes longer than 2 seconds)
|
||||
result = await client.call_tool("long_running_task", {"param": "value"}, timeout=2.0)
|
||||
|
||||
# With progress handler (to track execution progress)
|
||||
result = await client.call_tool(
|
||||
"long_running_task",
|
||||
{"param": "value"},
|
||||
progress_handler=my_progress_handler
|
||||
)
|
||||
```
|
||||
* Arguments are passed as a dictionary. FastMCP servers automatically handle JSON string parsing for complex types if needed.
|
||||
* Returns a list of content objects (usually `TextContent` or `ImageContent`).
|
||||
* The optional `timeout` parameter limits the maximum execution time (in seconds) for this specific call, overriding any client-level timeout.
|
||||
* The optional `progress_handler` parameter receives progress updates during execution, overriding any client-level progress handler.
|
||||
|
||||
#### Resource Operations
|
||||
|
||||
* **`list_resources()`**: Retrieves a list of static resources.
|
||||
```python
|
||||
resources = await client.list_resources()
|
||||
# resources -> list[mcp.types.Resource]
|
||||
```
|
||||
* **`list_resource_templates()`**: Retrieves a list of resource templates.
|
||||
```python
|
||||
templates = await client.list_resource_templates()
|
||||
# templates -> list[mcp.types.ResourceTemplate]
|
||||
```
|
||||
* **`read_resource(uri: str | AnyUrl)`**: Reads the content of a resource or a resolved template.
|
||||
```python
|
||||
# Read a static resource
|
||||
readme_content = await client.read_resource("file:///path/to/README.md")
|
||||
# readme_content -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents]
|
||||
print(readme_content[0].text) # Assuming text
|
||||
|
||||
# Read a resource generated from a template
|
||||
weather_content = await client.read_resource("data://weather/london")
|
||||
print(weather_content[0].text) # Assuming text JSON
|
||||
```
|
||||
|
||||
#### Prompt Operations
|
||||
|
||||
* **`list_prompts()`**: Retrieves available prompt templates.
|
||||
* **`get_prompt(name: str, arguments: dict[str, Any] | None = None)`**: Retrieves a rendered prompt message list.
|
||||
|
||||
<VersionBadge version="2.9.0" />
|
||||
|
||||
**Automatic Argument Serialization**: When calling prompts with complex arguments, the FastMCP client automatically serializes non-string values to JSON strings as required by the MCP specification. This allows you to pass typed objects directly while maintaining protocol compliance.
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass
|
||||
class UserData:
|
||||
name: str
|
||||
age: int
|
||||
|
||||
async with client:
|
||||
# You can pass complex objects directly
|
||||
result = await client.get_prompt("analyze_user", {
|
||||
"user": UserData(name="Alice", age=30), # Automatically serialized to JSON
|
||||
"preferences": {"theme": "dark"}, # Dict serialized to JSON string
|
||||
"scores": [85, 92, 78], # List serialized to JSON string
|
||||
"simple_name": "Bob" # Strings passed through unchanged
|
||||
})
|
||||
# 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")
|
||||
```
|
||||
|
||||
The client handles the serialization automatically using `pydantic_core.to_json()` for consistent formatting, while the server can deserialize these JSON strings back to the expected types if using FastMCP's server-side type conversion.
|
||||
## Connection Lifecycle
|
||||
|
||||
### Raw MCP Protocol Objects
|
||||
|
||||
<VersionBadge version="2.2.7" />
|
||||
|
||||
The FastMCP client attempts to provide a "friendly" interface to the MCP protocol, but sometimes you may need access to the raw MCP protocol objects. Each of the main client methods that returns data has a corresponding `*_mcp` method that returns the raw MCP protocol objects directly.
|
||||
|
||||
<Warning>
|
||||
The standard client methods (without `_mcp`) return user-friendly representations of MCP data, while `*_mcp` methods will always return the complete MCP protocol objects. As the protocol evolves, changes to these user-friendly representations may occur and could potentially be breaking. If you need consistent, stable access to the full data structure, prefer using the `*_mcp` methods.
|
||||
</Warning>
|
||||
The client operates asynchronously and uses context managers for connection management:
|
||||
|
||||
```python
|
||||
# Standard method - returns just the list of tools
|
||||
tools = await client.list_tools()
|
||||
# tools -> list[mcp.types.Tool]
|
||||
|
||||
# Raw MCP method - returns the full protocol object
|
||||
result = await client.list_tools_mcp()
|
||||
# result -> mcp.types.ListToolsResult
|
||||
tools = result.tools
|
||||
```
|
||||
|
||||
Available raw MCP methods:
|
||||
|
||||
* **`list_tools_mcp()`**: Returns `mcp.types.ListToolsResult`
|
||||
* **`call_tool_mcp(name, arguments)`**: Returns `mcp.types.CallToolResult`
|
||||
* **`list_resources_mcp()`**: Returns `mcp.types.ListResourcesResult`
|
||||
* **`list_resource_templates_mcp()`**: Returns `mcp.types.ListResourceTemplatesResult`
|
||||
* **`read_resource_mcp(uri)`**: Returns `mcp.types.ReadResourceResult`
|
||||
* **`list_prompts_mcp()`**: Returns `mcp.types.ListPromptsResult`
|
||||
* **`get_prompt_mcp(name, arguments)`**: Returns `mcp.types.GetPromptResult`
|
||||
* **`complete_mcp(ref, argument)`**: Returns `mcp.types.CompleteResult`
|
||||
|
||||
These methods are especially useful for debugging or when you need to access metadata or fields that aren't exposed by the simplified methods.
|
||||
|
||||
### Additional Features
|
||||
|
||||
#### Pinging the Server
|
||||
|
||||
The client can be used to ping the server to verify connectivity.
|
||||
|
||||
```python
|
||||
async with client:
|
||||
await client.ping()
|
||||
print("Server is reachable")
|
||||
```
|
||||
|
||||
#### Session Management
|
||||
|
||||
When using stdio transports, clients support a `keep_alive` feature (enabled by default) that maintains subprocess sessions between connection contexts. You can manually control this behavior using the client's `close()` method.
|
||||
|
||||
When `keep_alive=False`, the client will automatically close the session when the context manager exits.
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
|
||||
client = Client("my_mcp_server.py") # keep_alive=True by default
|
||||
|
||||
async def example():
|
||||
async with client:
|
||||
await client.ping()
|
||||
client = Client("my_mcp_server.py")
|
||||
|
||||
# Connection established here
|
||||
async with client:
|
||||
await client.ping() # Same subprocess as above
|
||||
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()}")
|
||||
```
|
||||
|
||||
<Note>
|
||||
For detailed examples and configuration options, see [Session Management in Transports](/clients/transports#session-management).
|
||||
</Note>
|
||||
## Core Operations
|
||||
|
||||
#### Timeouts
|
||||
The client provides methods for all standard MCP operations:
|
||||
|
||||
<VersionBadge version="2.3.4" />
|
||||
| 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 |
|
||||
|
||||
You can control request timeouts at both the client level and individual request level:
|
||||
### Quick Examples
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Tool operations
|
||||
tools = await client.list_tools()
|
||||
result = await client.call_tool("calculate", {"a": 5, "b": 3})
|
||||
|
||||
# Resource operations
|
||||
resources = await client.list_resources()
|
||||
content = await client.read_resource("file:///config/settings.json")
|
||||
|
||||
# Prompt operations
|
||||
prompts = await client.list_prompts()
|
||||
messages = await client.get_prompt("welcome", {"name": "Alice"})
|
||||
```
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
The client supports additional configuration for specialized use cases:
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
from fastmcp.exceptions import McpError
|
||||
from fastmcp.client.logging import LogMessage
|
||||
|
||||
async def log_handler(message: LogMessage):
|
||||
print(f"Server log: {message.data}")
|
||||
|
||||
async def progress_handler(progress: float, total: float | None, message: str | None):
|
||||
print(f"Progress: {progress}/{total} - {message}")
|
||||
|
||||
# Client with a global 5-second timeout for all requests
|
||||
client = Client(
|
||||
my_mcp_server,
|
||||
timeout=5.0 # Default timeout in seconds
|
||||
"my_mcp_server.py",
|
||||
log_handler=log_handler, # Handle server logs
|
||||
progress_handler=progress_handler, # Monitor long operations
|
||||
timeout=30.0 # Set request timeout
|
||||
)
|
||||
|
||||
async with client:
|
||||
# This uses the global 5-second timeout
|
||||
result1 = await client.call_tool("quick_task", {"param": "value"})
|
||||
|
||||
# This specifies a 10-second timeout for this specific call
|
||||
result2 = await client.call_tool("slow_task", {"param": "value"}, timeout=10.0)
|
||||
|
||||
try:
|
||||
# This will likely timeout
|
||||
result3 = await client.call_tool("medium_task", {"param": "value"}, timeout=0.01)
|
||||
except McpError as e:
|
||||
# Handle timeout error
|
||||
print(f"The task timed out: {e}")
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Timeout behavior varies between transport types:
|
||||
## Next Steps
|
||||
|
||||
- With **SSE** transport, the per-request (tool call) timeout **always** takes precedence, regardless of which is lower.
|
||||
- With **HTTP** transport, the **lower** of the two timeouts (client or tool call) takes precedence.
|
||||
Explore the detailed documentation for each operation type:
|
||||
|
||||
For consistent behavior across all transports, we recommend explicitly setting timeouts at the individual tool call level when needed, rather than relying on client-level timeouts.
|
||||
</Warning>
|
||||
### 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
|
||||
|
||||
#### Error Handling
|
||||
### 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
|
||||
|
||||
When a `call_tool` request results in an error on the server (e.g., the tool function raised an exception), the `client.call_tool()` method will raise a `fastmcp.exceptions.ClientError`.
|
||||
|
||||
```python
|
||||
async def safe_call_tool():
|
||||
async with client:
|
||||
try:
|
||||
# Assume 'divide' tool exists and might raise ZeroDivisionError
|
||||
result = await client.call_tool("divide", {"a": 10, "b": 0})
|
||||
print(f"Result: {result}")
|
||||
except ClientError as e:
|
||||
print(f"Tool call failed: {e}")
|
||||
except ConnectionError as e:
|
||||
print(f"Connection failed: {e}")
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred: {e}")
|
||||
|
||||
# Example Output if division by zero occurs:
|
||||
# Tool call failed: Division by zero is not allowed.
|
||||
```
|
||||
|
||||
Other errors, like connection failures, will raise standard Python exceptions (e.g., `ConnectionError`, `TimeoutError`).
|
||||
### Connection Details
|
||||
- **[Transports](/clients/transports)** - Configure connection methods and parameters
|
||||
- **[Authentication](/clients/auth/oauth)** - Set up OAuth and bearer token authentication
|
||||
|
||||
<Tip>
|
||||
The client transport often has its own error-handling mechanisms, so you can not always trap errors like those raised by `call_tool` outside of the `async with` block. Instead, you can use `call_tool_mcp()` to get the raw `mcp.types.CallToolResult` object and handle errors yourself by checking its `isError` attribute.
|
||||
</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>
|
||||
63
docs/clients/logging.mdx
Normal file
63
docs/clients/logging.mdx
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
---
|
||||
title: Server Logging
|
||||
sidebarTitle: Logging
|
||||
description: Learn how to receive and handle log messages from MCP servers.
|
||||
icon: file-text
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
MCP servers can emit log messages to clients. The client can handle these logs through a log handler callback.
|
||||
|
||||
## Setting Up Log Handling
|
||||
|
||||
Provide a `log_handler` function when creating the client:
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.logging import LogMessage
|
||||
|
||||
async def log_handler(message: LogMessage):
|
||||
level = message.level.upper()
|
||||
logger = message.logger or 'server'
|
||||
data = message.data
|
||||
print(f"[{level}] {logger}: {data}")
|
||||
|
||||
client = Client(
|
||||
"my_mcp_server.py",
|
||||
log_handler=log_handler,
|
||||
)
|
||||
```
|
||||
|
||||
## LogMessage Structure
|
||||
|
||||
The `log_handler` receives a `LogMessage` object with:
|
||||
|
||||
- **`level`**: Log level (e.g., "debug", "info", "warning", "error")
|
||||
- **`logger`**: Logger name (optional, may be None)
|
||||
- **`data`**: The actual log message content
|
||||
|
||||
```python
|
||||
async def detailed_log_handler(message: LogMessage):
|
||||
if message.level == "error":
|
||||
print(f"ERROR: {message.data}")
|
||||
elif message.level == "warning":
|
||||
print(f"WARNING: {message.data}")
|
||||
else:
|
||||
print(f"{message.level.upper()}: {message.data}")
|
||||
```
|
||||
|
||||
## Default Log Handling
|
||||
|
||||
If you don't provide a custom `log_handler`, FastMCP uses a default handler that emits DEBUG level logs:
|
||||
|
||||
```python
|
||||
# Without custom handler - uses default DEBUG logging
|
||||
client = Client("my_mcp_server.py")
|
||||
|
||||
async with client:
|
||||
# Server logs will be emitted at DEBUG level
|
||||
await client.call_tool("some_tool")
|
||||
```
|
||||
59
docs/clients/progress.mdx
Normal file
59
docs/clients/progress.mdx
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
---
|
||||
title: Progress Monitoring
|
||||
sidebarTitle: Progress
|
||||
description: Learn how to handle progress notifications from long-running server operations.
|
||||
icon: chart-line
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.3.5" />
|
||||
|
||||
MCP servers can report progress during long-running operations. The client can receive these updates through a progress handler.
|
||||
|
||||
## Setting Up Progress Handling
|
||||
|
||||
Set a progress handler when creating the client:
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
|
||||
async def my_progress_handler(
|
||||
progress: float,
|
||||
total: float | None,
|
||||
message: str | None
|
||||
) -> None:
|
||||
if total is not None:
|
||||
percentage = (progress / total) * 100
|
||||
print(f"Progress: {percentage:.1f}% - {message or ''}")
|
||||
else:
|
||||
print(f"Progress: {progress} - {message or ''}")
|
||||
|
||||
client = Client(
|
||||
"my_mcp_server.py",
|
||||
progress_handler=my_progress_handler
|
||||
)
|
||||
```
|
||||
|
||||
## Per-Call Progress Handler
|
||||
|
||||
Override the progress handler for specific tool calls:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Override with specific progress handler for this call
|
||||
result = await client.call_tool(
|
||||
"long_running_task",
|
||||
{"param": "value"},
|
||||
progress_handler=my_progress_handler
|
||||
)
|
||||
```
|
||||
|
||||
## Handler Parameters
|
||||
|
||||
The progress handler receives:
|
||||
|
||||
- **`progress`** (float): Current progress value
|
||||
- **`total`** (float | None): Expected total value (may be None)
|
||||
- **`message`** (str | None): Optional status message (may be None)
|
||||
|
||||
187
docs/clients/prompts.mdx
Normal file
187
docs/clients/prompts.mdx
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
---
|
||||
title: Prompt Operations
|
||||
sidebarTitle: Prompts
|
||||
description: Learn how to list and use server-side prompts with automatic argument serialization.
|
||||
icon: message-square
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
Prompts are reusable message templates exposed by MCP servers. They can accept arguments to generate personalized message sequences for LLM interactions.
|
||||
|
||||
## Listing Prompts
|
||||
|
||||
Use `list_prompts()` to retrieve all available prompt templates:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
prompts = await client.list_prompts()
|
||||
# prompts -> list[mcp.types.Prompt]
|
||||
|
||||
for prompt in prompts:
|
||||
print(f"Prompt: {prompt.name}")
|
||||
print(f"Description: {prompt.description}")
|
||||
if prompt.arguments:
|
||||
print(f"Arguments: {[arg.name for arg in prompt.arguments]}")
|
||||
```
|
||||
|
||||
## Using Prompts
|
||||
|
||||
### Basic Usage
|
||||
|
||||
Request a rendered prompt using `get_prompt()` with the prompt name and arguments:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Simple prompt without arguments
|
||||
result = await client.get_prompt("welcome_message")
|
||||
# result -> mcp.types.GetPromptResult
|
||||
|
||||
# Access the generated messages
|
||||
for message in result.messages:
|
||||
print(f"Role: {message.role}")
|
||||
print(f"Content: {message.content}")
|
||||
```
|
||||
|
||||
### Prompts with Arguments
|
||||
|
||||
Pass arguments as a dictionary to customize the prompt:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Prompt with simple arguments
|
||||
result = await client.get_prompt("user_greeting", {
|
||||
"name": "Alice",
|
||||
"role": "administrator"
|
||||
})
|
||||
|
||||
# Access the personalized messages
|
||||
for message in result.messages:
|
||||
print(f"Generated message: {message.content}")
|
||||
```
|
||||
|
||||
## Automatic Argument Serialization
|
||||
|
||||
<VersionBadge version="2.9.0" />
|
||||
|
||||
FastMCP automatically serializes complex arguments to JSON strings as required by the MCP specification. This allows you to pass typed objects directly:
|
||||
|
||||
```python
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass
|
||||
class UserData:
|
||||
name: str
|
||||
age: int
|
||||
|
||||
async with client:
|
||||
# Complex arguments are automatically serialized
|
||||
result = await client.get_prompt("analyze_user", {
|
||||
"user": UserData(name="Alice", age=30), # Automatically serialized to JSON
|
||||
"preferences": {"theme": "dark"}, # Dict serialized to JSON string
|
||||
"scores": [85, 92, 78], # List serialized to JSON string
|
||||
"simple_name": "Bob" # Strings passed through unchanged
|
||||
})
|
||||
```
|
||||
|
||||
The client handles serialization using `pydantic_core.to_json()` for consistent formatting. FastMCP servers can automatically deserialize these JSON strings back to the expected types.
|
||||
|
||||
### Serialization Examples
|
||||
|
||||
```python
|
||||
async with client:
|
||||
result = await client.get_prompt("data_analysis", {
|
||||
# These will be automatically serialized to JSON strings:
|
||||
"config": {
|
||||
"format": "csv",
|
||||
"include_headers": True,
|
||||
"delimiter": ","
|
||||
},
|
||||
"filters": [
|
||||
{"field": "age", "operator": ">", "value": 18},
|
||||
{"field": "status", "operator": "==", "value": "active"}
|
||||
],
|
||||
# This remains a string:
|
||||
"report_title": "Monthly Analytics Report"
|
||||
})
|
||||
```
|
||||
|
||||
## Working with Prompt Results
|
||||
|
||||
The `get_prompt()` method returns a `GetPromptResult` object containing a list of messages:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
result = await client.get_prompt("conversation_starter", {"topic": "climate"})
|
||||
|
||||
# Access individual messages
|
||||
for i, message in enumerate(result.messages):
|
||||
print(f"Message {i + 1}:")
|
||||
print(f" Role: {message.role}")
|
||||
print(f" Content: {message.content.text if hasattr(message.content, 'text') else message.content}")
|
||||
```
|
||||
|
||||
## Raw MCP Protocol Access
|
||||
|
||||
For access to the complete MCP protocol objects, use the `*_mcp` methods:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Raw MCP method returns full protocol object
|
||||
prompts_result = await client.list_prompts_mcp()
|
||||
# prompts_result -> mcp.types.ListPromptsResult
|
||||
|
||||
prompt_result = await client.get_prompt_mcp("example_prompt", {"arg": "value"})
|
||||
# prompt_result -> mcp.types.GetPromptResult
|
||||
```
|
||||
|
||||
## Multi-Server Clients
|
||||
|
||||
When using multi-server clients, prompts are accessible without prefixing (unlike tools):
|
||||
|
||||
```python
|
||||
async with client: # Multi-server client
|
||||
# Prompts from any server are directly accessible
|
||||
result1 = await client.get_prompt("weather_prompt", {"city": "London"})
|
||||
result2 = await client.get_prompt("assistant_prompt", {"query": "help"})
|
||||
```
|
||||
|
||||
## Common Prompt Patterns
|
||||
|
||||
### System Messages
|
||||
|
||||
Many prompts generate system messages for LLM configuration:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
result = await client.get_prompt("system_configuration", {
|
||||
"role": "helpful assistant",
|
||||
"expertise": "python programming"
|
||||
})
|
||||
|
||||
# Typically returns messages with role="system"
|
||||
system_message = result.messages[0]
|
||||
print(f"System prompt: {system_message.content}")
|
||||
```
|
||||
|
||||
### Conversation Templates
|
||||
|
||||
Prompts can generate multi-turn conversation templates:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
result = await client.get_prompt("interview_template", {
|
||||
"candidate_name": "Alice",
|
||||
"position": "Senior Developer"
|
||||
})
|
||||
|
||||
# Multiple messages for a conversation flow
|
||||
for message in result.messages:
|
||||
print(f"{message.role}: {message.content}")
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Prompt arguments and their expected types depend on the specific prompt implementation. Check the server's documentation or use `list_prompts()` to see available arguments for each prompt.
|
||||
</Tip>
|
||||
171
docs/clients/resources.mdx
Normal file
171
docs/clients/resources.mdx
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
---
|
||||
title: Resource Operations
|
||||
sidebarTitle: Resources
|
||||
description: Learn how to list and read static and templated resources from MCP servers.
|
||||
icon: folder-open
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
Resources are data sources exposed by MCP servers. They can be static files or dynamic templates that generate content based on parameters.
|
||||
|
||||
## Types of Resources
|
||||
|
||||
MCP servers expose two types of resources:
|
||||
|
||||
- **Static Resources**: Fixed content accessible via URI (e.g., configuration files, documentation)
|
||||
- **Resource Templates**: Dynamic resources that accept parameters to generate content (e.g., API endpoints, database queries)
|
||||
|
||||
## Listing Resources
|
||||
|
||||
### Static Resources
|
||||
|
||||
Use `list_resources()` to retrieve all static resources available on the server:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
resources = await client.list_resources()
|
||||
# resources -> list[mcp.types.Resource]
|
||||
|
||||
for resource in resources:
|
||||
print(f"Resource URI: {resource.uri}")
|
||||
print(f"Name: {resource.name}")
|
||||
print(f"Description: {resource.description}")
|
||||
print(f"MIME Type: {resource.mimeType}")
|
||||
```
|
||||
|
||||
### Resource Templates
|
||||
|
||||
Use `list_resource_templates()` to retrieve available resource templates:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
templates = await client.list_resource_templates()
|
||||
# templates -> list[mcp.types.ResourceTemplate]
|
||||
|
||||
for template in templates:
|
||||
print(f"Template URI: {template.uriTemplate}")
|
||||
print(f"Name: {template.name}")
|
||||
print(f"Description: {template.description}")
|
||||
```
|
||||
|
||||
## Reading Resources
|
||||
|
||||
### Static Resources
|
||||
|
||||
Read a static resource using its URI:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Read a static resource
|
||||
content = await client.read_resource("file:///path/to/README.md")
|
||||
# content -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents]
|
||||
|
||||
# Access text content
|
||||
if hasattr(content[0], 'text'):
|
||||
print(content[0].text)
|
||||
|
||||
# Access binary content
|
||||
if hasattr(content[0], 'blob'):
|
||||
print(f"Binary data: {len(content[0].blob)} bytes")
|
||||
```
|
||||
|
||||
### Resource Templates
|
||||
|
||||
Read from a resource template by providing the URI with parameters:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Read a resource generated from a template
|
||||
# For example, a template like "weather://{{city}}/current"
|
||||
weather_content = await client.read_resource("weather://london/current")
|
||||
|
||||
# Access the generated content
|
||||
print(weather_content[0].text) # Assuming text JSON response
|
||||
```
|
||||
|
||||
## Content Types
|
||||
|
||||
Resources can return different content types:
|
||||
|
||||
### Text Resources
|
||||
|
||||
```python
|
||||
async with client:
|
||||
content = await client.read_resource("resource://config/settings.json")
|
||||
|
||||
for item in content:
|
||||
if hasattr(item, 'text'):
|
||||
print(f"Text content: {item.text}")
|
||||
print(f"MIME type: {item.mimeType}")
|
||||
```
|
||||
|
||||
### Binary Resources
|
||||
|
||||
```python
|
||||
async with client:
|
||||
content = await client.read_resource("resource://images/logo.png")
|
||||
|
||||
for item in content:
|
||||
if hasattr(item, 'blob'):
|
||||
print(f"Binary content: {len(item.blob)} bytes")
|
||||
print(f"MIME type: {item.mimeType}")
|
||||
|
||||
# Save to file
|
||||
with open("downloaded_logo.png", "wb") as f:
|
||||
f.write(item.blob)
|
||||
```
|
||||
|
||||
## Working with Multi-Server Clients
|
||||
|
||||
When using multi-server clients, resource URIs are automatically prefixed with the server name:
|
||||
|
||||
```python
|
||||
async with client: # Multi-server client
|
||||
# Access resources from different servers
|
||||
weather_icons = await client.read_resource("weather://weather/icons/sunny")
|
||||
templates = await client.read_resource("resource://assistant/templates/list")
|
||||
|
||||
print(f"Weather icon: {weather_icons[0].blob}")
|
||||
print(f"Templates: {templates[0].text}")
|
||||
```
|
||||
|
||||
## Raw MCP Protocol Access
|
||||
|
||||
For access to the complete MCP protocol objects, use the `*_mcp` methods:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Raw MCP methods return full protocol objects
|
||||
resources_result = await client.list_resources_mcp()
|
||||
# resources_result -> mcp.types.ListResourcesResult
|
||||
|
||||
templates_result = await client.list_resource_templates_mcp()
|
||||
# templates_result -> mcp.types.ListResourceTemplatesResult
|
||||
|
||||
content_result = await client.read_resource_mcp("resource://example")
|
||||
# content_result -> mcp.types.ReadResourceResult
|
||||
```
|
||||
|
||||
## Common Resource URI Patterns
|
||||
|
||||
Different MCP servers may use various URI schemes:
|
||||
|
||||
```python
|
||||
# File system resources
|
||||
"file:///path/to/file.txt"
|
||||
|
||||
# Custom protocol resources
|
||||
"weather://london/current"
|
||||
"database://users/123"
|
||||
|
||||
# Generic resource protocol
|
||||
"resource://config/settings"
|
||||
"resource://templates/email"
|
||||
```
|
||||
|
||||
<Tip>
|
||||
Resource URIs and their formats depend on the specific MCP server implementation. Check the server's documentation for available resources and their URI patterns.
|
||||
</Tip>
|
||||
42
docs/clients/roots.mdx
Normal file
42
docs/clients/roots.mdx
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
---
|
||||
title: Client Roots
|
||||
sidebarTitle: Roots
|
||||
description: Learn how to provide local context to MCP servers.
|
||||
icon: tree
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
Roots are a way for clients to inform servers about the resources they have access to. Servers can use this information to adjust behavior or provide more relevant responses.
|
||||
|
||||
## Setting Static Roots
|
||||
|
||||
Provide a list of roots when creating the client:
|
||||
|
||||
<CodeGroup>
|
||||
```python Static Roots
|
||||
from fastmcp import Client
|
||||
|
||||
client = Client(
|
||||
"my_mcp_server.py",
|
||||
roots=["/path/to/root1", "/path/to/root2"]
|
||||
)
|
||||
```
|
||||
|
||||
```python Dynamic Roots Callback
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.roots import RequestContext
|
||||
|
||||
async def roots_callback(context: RequestContext) -> list[str]:
|
||||
print(f"Server requested roots (Request ID: {context.request_id})")
|
||||
return ["/path/to/root1", "/path/to/root2"]
|
||||
|
||||
client = Client(
|
||||
"my_mcp_server.py",
|
||||
roots=roots_callback
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
94
docs/clients/sampling.mdx
Normal file
94
docs/clients/sampling.mdx
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
---
|
||||
title: LLM Sampling
|
||||
sidebarTitle: Sampling
|
||||
description: Learn how to handle server-initiated LLM sampling requests.
|
||||
icon: brain
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
MCP servers can request LLM completions from clients. The client handles these requests through a sampling handler callback.
|
||||
|
||||
## Setting Up Sampling Handling
|
||||
|
||||
Provide a `sampling_handler` function when creating the client:
|
||||
|
||||
```python
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.sampling import (
|
||||
SamplingMessage,
|
||||
SamplingParams,
|
||||
RequestContext,
|
||||
)
|
||||
|
||||
async def sampling_handler(
|
||||
messages: list[SamplingMessage],
|
||||
params: SamplingParams,
|
||||
context: RequestContext
|
||||
) -> str:
|
||||
# Your LLM integration logic here
|
||||
# Extract text from messages and generate a response
|
||||
return "Generated response based on the messages"
|
||||
|
||||
client = Client(
|
||||
"my_mcp_server.py",
|
||||
sampling_handler=sampling_handler,
|
||||
)
|
||||
```
|
||||
|
||||
## Handler Parameters
|
||||
|
||||
The sampling handler receives:
|
||||
|
||||
- **`messages`**: List of `SamplingMessage` objects representing the conversation
|
||||
- **`params`**: `SamplingParams` object with generation parameters (systemPrompt, maxTokens, temperature, etc.)
|
||||
- **`context`**: `RequestContext` object with request metadata
|
||||
|
||||
## Basic Example
|
||||
|
||||
```python
|
||||
async def basic_sampling_handler(
|
||||
messages: list[SamplingMessage],
|
||||
params: SamplingParams,
|
||||
context: RequestContext
|
||||
) -> str:
|
||||
# Extract message content
|
||||
conversation = []
|
||||
for message in messages:
|
||||
content = message.content.text if hasattr(message.content, 'text') else str(message.content)
|
||||
conversation.append(f"{message.role}: {content}")
|
||||
|
||||
# Use the system prompt if provided
|
||||
system_prompt = params.systemPrompt or "You are a helpful assistant."
|
||||
|
||||
# Here you would integrate with your preferred LLM service
|
||||
# This is just a placeholder response
|
||||
return f"Response based on conversation: {' | '.join(conversation)}"
|
||||
|
||||
client = Client(
|
||||
"my_mcp_server.py",
|
||||
sampling_handler=basic_sampling_handler
|
||||
)
|
||||
```
|
||||
|
||||
## Accessing Parameters
|
||||
|
||||
```python
|
||||
async def parameter_handler(
|
||||
messages: list[SamplingMessage],
|
||||
params: SamplingParams,
|
||||
context: RequestContext
|
||||
) -> str:
|
||||
# Available parameters from the server
|
||||
system_prompt = params.systemPrompt
|
||||
max_tokens = params.maxTokens
|
||||
temperature = params.temperature
|
||||
top_p = params.topP
|
||||
stop_sequences = params.stopSequences
|
||||
|
||||
# Use these parameters with your LLM service
|
||||
return "Generated response"
|
||||
```
|
||||
|
||||
143
docs/clients/tools.mdx
Normal file
143
docs/clients/tools.mdx
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
---
|
||||
title: Tool Operations
|
||||
sidebarTitle: Tools
|
||||
description: Learn how to discover and execute tools on MCP servers.
|
||||
icon: wrench
|
||||
---
|
||||
|
||||
import { VersionBadge } from '/snippets/version-badge.mdx'
|
||||
|
||||
<VersionBadge version="2.0.0" />
|
||||
|
||||
Tools are executable functions exposed by MCP servers. The FastMCP client provides methods to discover available tools and execute them with arguments.
|
||||
|
||||
## Discovering Tools
|
||||
|
||||
Use `list_tools()` to retrieve all tools available on the server:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
tools = await client.list_tools()
|
||||
# tools -> list[mcp.types.Tool]
|
||||
|
||||
for tool in tools:
|
||||
print(f"Tool: {tool.name}")
|
||||
print(f"Description: {tool.description}")
|
||||
if tool.inputSchema:
|
||||
print(f"Parameters: {tool.inputSchema}")
|
||||
```
|
||||
|
||||
## Executing Tools
|
||||
|
||||
### Basic Execution
|
||||
|
||||
Execute a tool using `call_tool()` with the tool name and arguments:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Simple tool call
|
||||
result = await client.call_tool("add", {"a": 5, "b": 3})
|
||||
# result -> list[mcp.types.TextContent | mcp.types.ImageContent | ...]
|
||||
|
||||
# Access the result content
|
||||
print(result[0].text) # Assuming TextContent, e.g., '8'
|
||||
```
|
||||
|
||||
### Advanced Execution Options
|
||||
|
||||
The `call_tool()` method supports additional parameters for timeout control and progress monitoring:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# With timeout (aborts if execution takes longer than 2 seconds)
|
||||
result = await client.call_tool(
|
||||
"long_running_task",
|
||||
{"param": "value"},
|
||||
timeout=2.0
|
||||
)
|
||||
|
||||
# With progress handler (to track execution progress)
|
||||
result = await client.call_tool(
|
||||
"long_running_task",
|
||||
{"param": "value"},
|
||||
progress_handler=my_progress_handler
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `name`: The tool name (string)
|
||||
- `arguments`: Dictionary of arguments to pass to the tool (optional)
|
||||
- `timeout`: Maximum execution time in seconds (optional, overrides client-level timeout)
|
||||
- `progress_handler`: Progress callback function (optional, overrides client-level handler)
|
||||
|
||||
## Handling Results
|
||||
|
||||
Tool execution returns a list of content objects. The most common types are:
|
||||
|
||||
- **`TextContent`**: Text-based results with a `.text` attribute
|
||||
- **`ImageContent`**: Image data with image-specific attributes
|
||||
- **`BlobContent`**: Binary data content
|
||||
|
||||
```python
|
||||
async with client:
|
||||
result = await client.call_tool("get_weather", {"city": "London"})
|
||||
|
||||
for content in result:
|
||||
if hasattr(content, 'text'):
|
||||
print(f"Text result: {content.text}")
|
||||
elif hasattr(content, 'data'):
|
||||
print(f"Binary data: {len(content.data)} bytes")
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Exception-Based Error Handling
|
||||
|
||||
By default, `call_tool()` raises a `ToolError` if the tool execution fails:
|
||||
|
||||
```python
|
||||
from fastmcp.exceptions import ToolError
|
||||
|
||||
async with client:
|
||||
try:
|
||||
result = await client.call_tool("potentially_failing_tool", {"param": "value"})
|
||||
print("Tool succeeded:", result)
|
||||
except ToolError as e:
|
||||
print(f"Tool failed: {e}")
|
||||
```
|
||||
|
||||
### Manual Error Checking
|
||||
|
||||
For more granular control, use `call_tool_mcp()` which returns the raw MCP protocol object with an `isError` flag:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
result = await client.call_tool_mcp("potentially_failing_tool", {"param": "value"})
|
||||
# result -> mcp.types.CallToolResult
|
||||
|
||||
if result.isError:
|
||||
print(f"Tool failed: {result.content}")
|
||||
else:
|
||||
print(f"Tool succeeded: {result.content}")
|
||||
```
|
||||
|
||||
## Argument Handling
|
||||
|
||||
Arguments are passed as a dictionary to the tool:
|
||||
|
||||
```python
|
||||
async with client:
|
||||
# Simple arguments
|
||||
result = await client.call_tool("greet", {"name": "World"})
|
||||
|
||||
# Complex arguments
|
||||
result = await client.call_tool("process_data", {
|
||||
"config": {"format": "json", "validate": True},
|
||||
"items": [1, 2, 3, 4, 5],
|
||||
"metadata": {"source": "api", "version": "1.0"}
|
||||
})
|
||||
```
|
||||
|
||||
<Tip>
|
||||
For multi-server clients, tool names are automatically prefixed with the server name (e.g., `weather_get_forecast` for a tool named `get_forecast` on the `weather` server).
|
||||
</Tip>
|
||||
|
|
@ -94,13 +94,31 @@
|
|||
"group": "Clients",
|
||||
"pages": [
|
||||
"clients/client",
|
||||
{
|
||||
"group": "Core Interactions",
|
||||
"icon": "handshake",
|
||||
"pages": [
|
||||
"clients/tools",
|
||||
"clients/resources",
|
||||
"clients/prompts"
|
||||
]
|
||||
},
|
||||
{
|
||||
"group": "Advanced Features",
|
||||
"icon": "stars",
|
||||
"pages": [
|
||||
"clients/logging",
|
||||
"clients/progress",
|
||||
"clients/sampling",
|
||||
"clients/roots"
|
||||
]
|
||||
},
|
||||
"clients/transports",
|
||||
{
|
||||
"group": "Authentication",
|
||||
"icon": "user-shield",
|
||||
"pages": ["clients/auth/oauth", "clients/auth/bearer"]
|
||||
},
|
||||
"clients/advanced-features"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
|
|||
5
justfile
5
justfile
|
|
@ -24,4 +24,7 @@ api-ref *MODULES:
|
|||
|
||||
# Clean up API reference documentation
|
||||
api-ref-clean:
|
||||
rm -rf docs/python-sdk
|
||||
rm -rf docs/python-sdk
|
||||
|
||||
copy-context:
|
||||
uvx --with-editable . --refresh-package copychat copychat@latest src/ docs/ -x changelog.mdx -x python-sdk/ -v
|
||||
Loading…
Add table
Add a link
Reference in a new issue