Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

docs: correct the client pages against main (#6407)

nate nowackc30070aed343
diff --git a/docs/clients/auth/bearer.mdx b/docs/clients/auth/bearer.mdx
index 109f54df6..0bac0ce8f 100644
--- a/docs/clients/auth/bearer.mdx
+++ b/docs/clients/auth/bearer.mdx
@@ -15,7 +15,7 @@ Bearer Token authentication is only relevant for HTTP-based transports.
You can configure your FastMCP client to use **bearer authentication** by supplying a valid access token. This is most appropriate for service accounts, long-lived API keys, CI/CD, applications where authentication is managed separately, or other non-interactive authentication methods.
-A Bearer token is a JSON Web Token (JWT) that is used to authenticate a request. It is most commonly used in the `Authorization` header of an HTTP request, using the `Bearer` scheme:
+A bearer token grants access to whoever presents it. It is often a JSON Web Token (JWT), but it can be any opaque string the server accepts. The client sends it in the `Authorization` header of each HTTP request, using the `Bearer` scheme:
```http
Authorization: Bearer <token>
@@ -47,7 +47,7 @@ from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
transport = StreamableHttpTransport(
- "http://your-server.fastmcp.app/mcp",
+ "https://your-server.fastmcp.app/mcp",
auth="<your-token>",
)
@@ -74,7 +74,7 @@ async with Client(
If the MCP server expects a custom header or token scheme, you can manually set the client's `headers` instead of using the `auth` parameter by setting them on your transport:
-```python {5}
+```python {7}
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
diff --git a/docs/clients/auth/cimd.mdx b/docs/clients/auth/cimd.mdx
index 5c8904bc6..a90f249cf 100644
--- a/docs/clients/auth/cimd.mdx
+++ b/docs/clients/auth/cimd.mdx
@@ -15,7 +15,7 @@ CIMD authentication is only relevant for HTTP-based transports and requires a se
With standard OAuth, your client registers dynamically with every server it connects to, receiving a fresh `client_id` each time. This works, but the server has no way to verify *who* your client actually is β€” any client can claim any name during registration.
-CIMD (Client ID Metadata Documents) flips this around. You host a small JSON document at an HTTPS URL you control, and that URL becomes your `client_id`. When your client connects to a server, the server fetches your metadata document and can verify your identity through your domain ownership. Users see a verified domain badge in the consent screen instead of an unverified client name.
+CIMD (Client ID Metadata Documents) flips this around. You host a small JSON document at an HTTPS URL you control, and that URL becomes your `client_id`. When your client connects to a server, the server fetches your metadata document and can verify your identity through your domain ownership. On a FastMCP OAuth proxy, users see a verified domain badge in the consent screen instead of an unverified client name.
## Client Usage
@@ -34,7 +34,7 @@ async with Client(
await client.list_tools()
```
-When the server supports CIMD, the client uses your metadata URL as its `client_id` instead of performing Dynamic Client Registration. The server fetches your document, validates it, and proceeds with the standard OAuth authorization flow.
+When the server's authorization metadata advertises CIMD support, the client uses your metadata URL as its `client_id` instead of performing Dynamic Client Registration. The server fetches your document, validates it, and proceeds with the standard OAuth authorization flow. When the server does not advertise CIMD support, the client falls back to Dynamic Client Registration.
<Note>
You don't need to pass `mcp_url` when using `OAuth` with `Client(auth=...)` β€” the transport provides the server URL automatically.
@@ -81,7 +81,7 @@ The `create` command accepts these flags:
| `--scope` | Space-separated list of scopes the client may request |
| `--client-uri` | URL of the client's home page |
| `--logo-uri` | URL of the client's logo image |
-| `--no-pretty` | Output compact JSON |
+| `--pretty=false` | Output compact JSON |
### Redirect URIs
@@ -120,7 +120,7 @@ When your client connects to a CIMD-enabled server, the flow works like this:
Your client sends its `client_metadata_url` as the `client_id` in the OAuth authorization request.
</Step>
<Step title="Server Recognizes CIMD URL">
-The server sees that the `client_id` is an HTTPS URL with a path β€” the signature of a CIMD client β€” and skips Dynamic Client Registration.
+The server sees that the `client_id` is an HTTPS URL with a path β€” the signature of a CIMD client β€” and resolves it from the document instead of looking up a registered client.
</Step>
<Step title="Server Fetches and Validates">
The server fetches your JSON document from the URL, validates that `client_id` matches the URL, and extracts your client metadata (name, redirect URIs, scopes).
diff --git a/docs/clients/auth/oauth.mdx b/docs/clients/auth/oauth.mdx
index 21236406d..0c95b24d4 100644
--- a/docs/clients/auth/oauth.mdx
+++ b/docs/clients/auth/oauth.mdx
@@ -56,11 +56,13 @@ You don't need to pass `mcp_url` when using `OAuth` with `Client(auth=...)` β€”
- **`scopes`** (`str | list[str]`, optional): OAuth scopes to request. Can be space-separated string or list of strings
- **`client_name`** (`str`, optional): Client name for dynamic registration. Defaults to `"FastMCP Client"`
- **`client_id`** (`str`, optional): Pre-registered OAuth client ID. When provided, skips Dynamic Client Registration entirely. See [Pre-Registered Clients](#pre-registered-clients)
-- **`client_secret`** (`str`, optional): OAuth client secret for pre-registered clients. Optional β€” public clients that rely on PKCE can omit this
+- **`client_secret`** (`str`, optional): OAuth client secret for pre-registered clients, sent to the token endpoint with `client_secret_post` unless `additional_client_metadata` sets `token_endpoint_auth_method`. Public clients that rely on PKCE can omit it
- **`client_metadata_url`** (`str`, optional): URL-based client identity (CIMD). See [CIMD Authentication](/clients/auth/cimd) for details
-- **`token_storage`** (`AsyncKeyValue`, optional): Storage backend for persisting OAuth tokens. Defaults to in-memory storage (tokens lost on restart). See [Token Storage](#token-storage) for encrypted storage options
+- **`token_storage`** (`AsyncKeyValue`, optional): Storage backend for persisting OAuth tokens. Defaults to in-memory storage, which loses tokens on restart and emits a warning. See [Token Storage](#token-storage) for encrypted storage options
- **`additional_client_metadata`** (`dict[str, Any]`, optional): Extra metadata for client registration
- **`callback_port`** (`int`, optional): Fixed port for OAuth callback server. If not specified, uses a random available port
+- **`callback_host`** (`str`, optional): Hostname for the callback server and the `redirect_uri`. Defaults to `"localhost"`
+- **`callback_timeout`** (`float`, optional): Seconds to wait for the browser callback before raising `TimeoutError`. Defaults to `300.0`
- **`httpx_client_factory`** (`McpHttpClientFactory`, optional): Factory for creating httpx2 clients
@@ -73,13 +75,13 @@ The OAuth flow is triggered when you use a FastMCP `Client` configured to use OA
The client first checks the configured `token_storage` backend for existing, valid tokens for the target server. If one is found, it will be used to authenticate the client.
</Step>
<Step title="OAuth Server Discovery">
-If no valid tokens exist, the client attempts to discover the OAuth server's endpoints using a well-known URI (e.g., `/.well-known/oauth-authorization-server`) based on the `mcp_url`.
+If no valid tokens exist, the client reads the MCP server's protected resource metadata (`/.well-known/oauth-protected-resource`) to find its authorization server, then fetches that server's metadata (`/.well-known/oauth-authorization-server` or OpenID Connect discovery) to learn its endpoints.
</Step>
<Step title="Client Registration">
If a `client_id` is provided, the client uses those pre-registered credentials directly and skips this step entirely. Otherwise, if a `client_metadata_url` is configured and the server supports CIMD, the client uses its metadata URL as its identity. As a fallback, the client performs Dynamic Client Registration (RFC 7591) if the server supports it.
</Step>
<Step title="Local Callback Server">
-A temporary local HTTP server is started on an available port (or the port specified via `callback_port`). This server's address (e.g., `http://127.0.0.1:<port>/callback`) acts as the `redirect_uri` for the OAuth flow.
+A temporary local HTTP server is started on an available port (or the port specified via `callback_port`). This server's address (by default `http://localhost:<port>/callback`, set by `callback_host`) acts as the `redirect_uri` for the OAuth flow.
</Step>
<Step title="Browser Interaction">
The user's default web browser is automatically opened, directing them to the OAuth server's authorization endpoint. The user logs in and grants (or denies) the requested `scopes`.
@@ -109,17 +111,31 @@ By default, tokens are stored in memory and lost when your application restarts.
</Warning>
```python
+import os
+from pathlib import Path
+
+from cryptography.fernet import Fernet
from fastmcp import Client
from fastmcp.client.auth import OAuth
-from key_value.aio.stores.disk import DiskStore
+from key_value.aio.stores.filetree import (
+ FileTreeStore,
+ FileTreeV1CollectionSanitizationStrategy,
+ FileTreeV1KeySanitizationStrategy,
+)
from key_value.aio.wrappers.encryption import FernetEncryptionWrapper
-from cryptography.fernet import Fernet
-import os
-# Create encrypted disk storage
+token_dir = Path("~/.fastmcp/oauth-tokens").expanduser()
+token_dir.mkdir(parents=True, exist_ok=True)
+
+file_store = FileTreeStore(
+ data_directory=token_dir,
+ key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(token_dir),
+ collection_sanitization_strategy=FileTreeV1CollectionSanitizationStrategy(token_dir),
+)
+
encrypted_storage = FernetEncryptionWrapper(
- key_value=DiskStore(directory="~/.fastmcp/oauth-tokens"),
- fernet=Fernet(os.environ["OAUTH_STORAGE_ENCRYPTION_KEY"])
+ key_value=file_store,
+ fernet=Fernet(os.environ["OAUTH_STORAGE_ENCRYPTION_KEY"]),
)
oauth = OAuth(token_storage=encrypted_storage)
@@ -178,6 +194,8 @@ async with Client(
Public clients that rely on PKCE for security can omit `client_secret`:
```python
+from fastmcp.client.auth import OAuth
+
oauth = OAuth(client_id="my-public-client-id")
```
diff --git a/docs/clients/client-groups.mdx b/docs/clients/client-groups.mdx
index fa374f5b6..e3738091b 100644
--- a/docs/clients/client-groups.mdx
+++ b/docs/clients/client-groups.mdx
@@ -50,7 +50,7 @@ async def main() -> None:
asyncio.run(main())
```
-Tool names are prefixed with the configured client name by default. For example, a `get_weather` tool exposed by the `modern` client becomes `modern_get_weather`.
+Tool names are prefixed with the configured client name. For example, a `get_weather` tool exposed by the `modern` client becomes `modern_get_weather`.
A group with a single client is a supported way to get namespacing alone: the one server's tools are presented under its configured name, with no other behavior change.
@@ -116,7 +116,7 @@ config = {
group = ClientGroup.from_config(config)
```
-Entries without a `mode` use `"auto"` by default.
+Entries without a `mode` use the `default_mode` argument to `from_config`, which is `"auto"`.
## Manage connections explicitly
diff --git a/docs/clients/client-only-package.mdx b/docs/clients/client-only-package.mdx
index 8406dbc1c..c72100b66 100644
--- a/docs/clients/client-only-package.mdx
+++ b/docs/clients/client-only-package.mdx
@@ -84,7 +84,7 @@ Use the full package for:
- defining or running FastMCP servers
- in-memory clients connected directly to `FastMCP` server objects
-- multi-server MCP configurations
+- multi-server MCP configurations, and configurations that use tool transformations or tag filters
- FastMCP apps, proxies, server auth, middleware, and other server-side features
The `fastmcp-slim` package is intentionally narrower: it is for client-only consumers who want FastMCP's MCP client behavior without depending on the full framework.
diff --git a/docs/clients/client.mdx b/docs/clients/client.mdx
index 01547c312..9a32fc3f1 100644
--- a/docs/clients/client.mdx
+++ b/docs/clients/client.mdx
@@ -110,6 +110,8 @@ See [Transports](/clients/transports) for detailed configuration options includi
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.
```python
+from fastmcp import Client
+
config = {
"mcpServers": {
"weather": {
@@ -209,6 +211,8 @@ client = Client("https://example.com/mcp", mode="auto")
Set `mode="legacy"` to force the initialize handshake. This behaves identically to earlier FastMCP versions and is the opt-out if a server misbehaves under discovery or you need the legacy `initialize` result object.
```python
+from fastmcp import Client
+
client = Client("https://example.com/mcp", mode="legacy")
```
@@ -221,6 +225,8 @@ A FastMCP server serves both eras, so a default client negotiates the modern one
You can also pin a specific modern protocol version to adopt it directly, without a discovery probe:
```python
+from fastmcp import Client
+
client = Client("https://example.com/mcp", mode="2026-07-28")
```
@@ -260,7 +266,7 @@ async with client:
tools = await client.list_tools() # served from the cache
```
-The default (`cache=None`) and `cache=False` both disable caching. For control over the store, TTL, or partitioning, pass a `CacheConfig`. A custom config requires a `target_id`, since in-memory FastMCP transports expose no server URL to derive a shared-store identity from.
+The default (`cache=None`) and `cache=False` both disable caching. For control over the store, TTL, or partitioning, pass a `CacheConfig`. A config with a custom `store` also requires a `target_id`, since FastMCP transports expose no server URL to derive a shared-store identity from.
```python
from fastmcp import Client
@@ -281,7 +287,7 @@ async with client:
The default cache lives in each client's process. To share cached responses across a fleet β€” a set of proxy replicas backed by one Redis, for example β€” pass a `KeyValueResponseCacheStore`, FastMCP's adapter over the same `AsyncKeyValue` key-value abstraction the event store and OAuth proxy use. It accepts any compatible backend (memory, Redis, and more).
-A shared store mingles responses from different principals, so it requires an explicit `partition` that isolates them. Derive the partition from a verified credential β€” never from request data or the server URL β€” and construct a new client when the principal changes. Only responses the server marks `"public"` are ever served across partitions.
+A shared store mingles responses from different principals, so it requires an explicit `partition` that isolates them. Derive the partition from a verified credential β€” never from request data or the server URL β€” and construct a new client when the principal changes. By default no response is served across partitions; set `share_public=True` on the `CacheConfig` to serve responses the server marks `"public"` to every partition.
```python
from fastmcp import Client
@@ -296,7 +302,7 @@ config = CacheConfig(store=store, partition="tenant-a", target_id="weather-api")
client = Client("https://example.com/mcp", mode="auto", cache=config)
```
-The adapter serializes each result through a type-tagged envelope validated against an allowlist of cacheable result models, so a value naming an unknown type is treated as a cache miss rather than deserialized blindly. Each store instance owns its own collection namespace; `clear()` affects only that namespace, never another tenant's entries.
+The adapter serializes each result through a type-tagged envelope validated against an allowlist of cacheable result models, so a value naming an unknown type is treated as a cache miss rather than deserialized blindly. Each store reads and writes one collection, set with `collection=`, and `clear()` removes only that collection's entries. Stores created without `collection=` share the default collection, so give each tenant its own collection when one tenant's `clear()` must not drop another's entries.
## Client extensions
@@ -311,7 +317,7 @@ from myproject.extensions import AppsExtension
client = Client("https://example.com/mcp", extensions=[AppsExtension()])
```
-Each extension's contributions are threaded into the underlying session. FastMCP folds in its own internal extension for [background tasks](/clients/tasks) automatically, and your own extensions *compose* with it rather than replacing it β€” pass your own tasks extension with the same identifier if you need to override it. When a tool returns a shape an extension claims, `client.call_tool()` resolves it transparently through the owning claim's resolver and hands you back an ordinary result. Result claims and their advertisements are honored only on modern-era connections, so they are inert on a legacy handshake.
+Each extension's contributions are threaded into the underlying session. When `fastmcp_tasks` is imported, FastMCP folds in its internal extension for [background tasks](/clients/tasks) automatically, and your own extensions *compose* with it rather than replacing it β€” pass your own tasks extension with the same identifier if you need to override it. When a tool returns a shape an extension claims, `client.call_tool()` resolves it transparently through the owning claim's resolver and hands you back an ordinary result. Result claims and their advertisements are honored only on modern-era connections, so they are inert on a legacy handshake.
For the rare case where you need to register additional result claims against an extension that is already advertised, pass them through `result_claims=`, keyed by the extension's identifier. Prefer declaring claims on the extension itself; this parameter merges extra claims with an extension's own.
diff --git a/docs/clients/elicitation.mdx b/docs/clients/elicitation.mdx
index 73cc6fdb7..507dfe140 100644
--- a/docs/clients/elicitation.mdx
+++ b/docs/clients/elicitation.mdx
@@ -20,6 +20,8 @@ Elicitation allows MCP servers to request structured input from users during ope
## Handler Template
```python
+from pathlib import Path
+
from fastmcp import Client
from fastmcp.client.elicitation import ElicitResult, ElicitRequestParams, RequestContext
@@ -53,11 +55,11 @@ async def elicitation_handler(
if response_type is None:
return ElicitResult(action="accept")
- # Create response using the provided dataclass type
+ # A scalar request, such as ctx.elicit(..., response_type=str), has one `value` field
return response_type(value=user_input)
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
mode="legacy",
elicitation_handler=elicitation_handler,
)
@@ -65,7 +67,7 @@ client = Client(
## How It Works
-When a server needs user input, it sends an elicitation request with a message prompt. Form elicitation requests include a JSON schema describing the expected response structure, and FastMCP automatically converts that schema into a Python dataclass type. URL elicitation requests and empty-object schemas use `response_type=None`.
+When a server needs user input, it sends an elicitation request with a message prompt. Form elicitation requests include a JSON schema describing the expected response structure, and FastMCP automatically converts that schema into a Python dataclass type. A server that asks for a single scalar, such as a string or number, gets a dataclass with one `value` field, which is what the examples on this page construct. URL elicitation requests and empty-object schemas use `response_type=None`.
The handler receives four parameters:
@@ -89,7 +91,7 @@ The handler receives four parameters:
## Response Actions
-You can return data directly, which implicitly accepts the elicitation:
+You can return data directly, either an instance of `response_type` or a plain `dict`, which implicitly accepts the elicitation:
```python
async def elicitation_handler(message, response_type, params, context):
@@ -127,6 +129,8 @@ async def elicitation_handler(message, response_type, params, context):
A file management tool might ask which directory to create:
```python
+from pathlib import Path
+
from fastmcp import Client
from fastmcp.client.elicitation import ElicitResult
@@ -142,7 +146,7 @@ async def elicitation_handler(message, response_type, params, context):
return response_type(value=user_response)
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
mode="legacy",
elicitation_handler=elicitation_handler
)
@@ -157,6 +161,8 @@ On protocol version `2026-07-28` and later, a server can ask for input before it
The `input_required_max_rounds` parameter caps how many rounds the client will answer before giving up, guarding against a server that never terminates. It defaults to `10`.
```python
+from fastmcp import Client
+
client = Client(
"https://example.com/mcp",
mode="auto",
diff --git a/docs/clients/logging.mdx b/docs/clients/logging.mdx
index f70461511..12631fa86 100644
--- a/docs/clients/logging.mdx
+++ b/docs/clients/logging.mdx
@@ -85,6 +85,8 @@ The handler receives a `LogMessage` object:
The `message.data` attribute contains the server's JSON-serializable log payload. FastMCP servers commonly send a dictionary with `msg` and `extra` keys, which enables structured logging with rich contextual information.
```python
+from fastmcp.client.logging import LogMessage
+
async def detailed_log_handler(message: LogMessage):
data = message.data
msg = data.get('msg', data) if isinstance(data, dict) else data
@@ -102,10 +104,13 @@ This structure is preserved even when logs are forwarded through a FastMCP proxy
## Default Behavior
-If you do not provide a custom `log_handler`, FastMCP's default handler routes server logs to Python's logging system at the appropriate severity level. The MCP levels map as follows: `notice` becomes INFO; `alert` and `emergency` become CRITICAL.
+If you do not provide a custom `log_handler`, FastMCP's default handler routes server logs to Python's logging system through the `fastmcp.client.from_server` logger, at the matching severity. The MCP levels map as follows: `notice` becomes INFO; `alert` and `emergency` become CRITICAL.
```python
from pathlib import Path
+
+from fastmcp import Client
+
client = Client(Path("my_mcp_server.py"))
async with client:
diff --git a/docs/clients/notifications.mdx b/docs/clients/notifications.mdx
index 67c59b6f7..5e0e1210b 100644
--- a/docs/clients/notifications.mdx
+++ b/docs/clients/notifications.mdx
@@ -51,23 +51,23 @@ from pathlib import Path
from fastmcp import Client
from fastmcp.client.messages import MessageHandler
-import mcp.types
+import mcp_types
class MyMessageHandler(MessageHandler):
async def on_tool_list_changed(
- self, notification: mcp.types.ToolListChangedNotification
+ self, notification: mcp_types.ToolListChangedNotification
) -> None:
"""Handle tool list changes."""
print("Tool list changed - refreshing available tools")
async def on_resource_list_changed(
- self, notification: mcp.types.ResourceListChangedNotification
+ self, notification: mcp_types.ResourceListChangedNotification
) -> None:
"""Handle resource list changes."""
print("Resource list changed")
async def on_prompt_list_changed(
- self, notification: mcp.types.PromptListChangedNotification
+ self, notification: mcp_types.PromptListChangedNotification
) -> None:
"""Handle prompt list changes."""
print("Prompt list changed")
@@ -82,57 +82,61 @@ client = Client(
```python
from fastmcp.client.messages import MessageHandler
-import mcp.types
+import mcp_types
class MyMessageHandler(MessageHandler):
async def on_message(self, message) -> None:
- """Called for ALL messages (requests and notifications)."""
+ """Called for every notification and transport exception."""
+ pass
+
+ async def on_exception(self, exception: Exception) -> None:
+ """Called for transport-level exceptions."""
pass
async def on_notification(
- self, notification: mcp.types.ServerNotification
+ self, notification: mcp_types.ServerNotification
) -> None:
"""Called for notifications (fire-and-forget)."""
pass
async def on_tool_list_changed(
- self, notification: mcp.types.ToolListChangedNotification
+ self, notification: mcp_types.ToolListChangedNotification
) -> None:
"""Called when the server's tool list changes."""
pass
async def on_resource_list_changed(
- self, notification: mcp.types.ResourceListChangedNotification
+ self, notification: mcp_types.ResourceListChangedNotification
) -> None:
"""Called when the server's resource list changes."""
pass
async def on_prompt_list_changed(
- self, notification: mcp.types.PromptListChangedNotification
+ self, notification: mcp_types.PromptListChangedNotification
) -> None:
"""Called when the server's prompt list changes."""
pass
async def on_progress(
- self, notification: mcp.types.ProgressNotification
+ self, notification: mcp_types.ProgressNotification
) -> None:
"""Called for progress updates during long-running operations."""
pass
async def on_resource_updated(
- self, notification: mcp.types.ResourceUpdatedNotification
+ self, notification: mcp_types.ResourceUpdatedNotification
) -> None:
"""Called when a specific resource changes."""
pass
async def on_cancelled(
- self, notification: mcp.types.CancelledNotification
+ self, notification: mcp_types.CancelledNotification
) -> None:
"""Called when a request is cancelled."""
pass
async def on_logging_message(
- self, notification: mcp.types.LoggingMessageNotification
+ self, notification: mcp_types.LoggingMessageNotification
) -> None:
"""Called for log messages from the server."""
pass
@@ -146,14 +150,14 @@ A practical example of maintaining a tool cache that refreshes when tools change
from pathlib import Path
from fastmcp import Client
from fastmcp.client.messages import MessageHandler
-import mcp.types
+import mcp_types
class ToolCacheHandler(MessageHandler):
def __init__(self):
self.cached_tools = []
async def on_tool_list_changed(
- self, notification: mcp.types.ToolListChangedNotification
+ self, notification: mcp_types.ToolListChangedNotification
) -> None:
"""Clear tool cache when tools change."""
print("Tools changed - clearing cache")
@@ -164,11 +168,13 @@ client = Client(Path("server.py"), message_handler=ToolCacheHandler())
## Server Requests
-While the message handler receives server-initiated requests, you should use dedicated callback parameters for most interactive scenarios:
+The message handler receives only notifications and transport exceptions; server-initiated requests never reach it. Answer those through the client's dedicated parameters:
- **Sampling requests**: Use [`sampling_handler`](/clients/sampling)
- **Elicitation requests**: Use [`elicitation_handler`](/clients/elicitation)
+- **Roots requests**: Use [`roots`](/clients/roots)
+
+Progress and log notifications reach the message handler as well, but their dedicated callbacks are simpler to use:
+
- **Progress updates**: Use [`progress_handler`](/clients/progress)
- **Log messages**: Use [`log_handler`](/clients/logging)
-
-The message handler is primarily for monitoring and handling notifications rather than responding to requests.
diff --git a/docs/clients/progress.mdx b/docs/clients/progress.mdx
index 707ab8dac..ccba8cbf9 100644
--- a/docs/clients/progress.mdx
+++ b/docs/clients/progress.mdx
@@ -18,6 +18,8 @@ MCP servers can report progress during operations. The client receives these upd
Set a handler when creating the client:
```python
+from pathlib import Path
+
from fastmcp import Client
async def progress_handler(
@@ -25,14 +27,14 @@ async def progress_handler(
total: float | None,
message: str | None
) -> None:
- if total is not None:
+ if total:
percentage = (progress / total) * 100
print(f"Progress: {percentage:.1f}% - {message or ''}")
else:
print(f"Progress: {progress} - {message or ''}")
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
progress_handler=progress_handler
)
```
diff --git a/docs/clients/prompts.mdx b/docs/clients/prompts.mdx
index fcebfe967..81a5b1897 100644
--- a/docs/clients/prompts.mdx
+++ b/docs/clients/prompts.mdx
@@ -81,7 +81,7 @@ async with client:
print(f" Content: {message.content.text if hasattr(message.content, 'text') else message.content}")
```
-Prompts can generate different message types. System messages configure LLM behavior:
+Every prompt message has the role `user` or `assistant`; MCP prompts have no system role. A prompt can return a single message that sets up the LLM's task:
```python
async with client:
@@ -124,11 +124,11 @@ async with client:
result_v1 = await client.get_prompt("summarize", {"text": "..."}, version="1.0")
```
-See [Metadata](/servers/versioning#version-discovery) for how to discover available versions.
+See [Version Discovery](/servers/versioning#version-discovery) for how to discover available versions.
## Multi-Server Clients
-When using multi-server clients, prompts are mounted with the server name as a prefix, just like tools:
+When using multi-server clients, prompt names are prefixed with the server name, just like tools, so `weather_prompt` on the `weather` server becomes `weather_weather_prompt`:
```python
async with client: # Multi-server client
diff --git a/docs/clients/resources.mdx b/docs/clients/resources.mdx
index 041ad0978..887e4eab5 100644
--- a/docs/clients/resources.mdx
+++ b/docs/clients/resources.mdx
@@ -31,7 +31,7 @@ async with client:
print(f"Binary data: {len(content[0].blob)} bytes")
```
-Resource templates generate content based on URI parameters. The template defines a pattern like `weather://{{city}}/current`, and you fill in the parameters when reading:
+Resource templates generate content based on URI parameters. The template defines a pattern like `weather://{city}/current`, and you fill in the parameters when reading:
```python
async with client:
@@ -56,9 +56,7 @@ async with client:
print(f"MIME type: {item.mime_type}")
```
-Binary resources include images, PDFs, and other non-text data:
-
-Binary resources arrive as `BlobResourceContents`, whose `blob` field is a base64 **string**, so decode it before writing bytes to disk:
+Binary resources include images, PDFs, and other non-text data. They arrive as `BlobResourceContents`, whose `blob` field is a base64 **string**, so decode it before writing bytes to disk:
```python
import base64
@@ -81,7 +79,7 @@ async with client:
## Multi-Server Clients
-When using multi-server clients, resource URIs are prefixed with the server name:
+When using multi-server clients, the server name is inserted after the URI scheme, so `weather://icons/sunny` on the `weather` server becomes `weather://weather/icons/sunny`:
```python
async with client: # Multi-server client
@@ -104,7 +102,7 @@ async with client:
content_v1 = await client.read_resource("data://config", version="1.0")
```
-See [Metadata](/servers/versioning#version-discovery) for how to discover available versions.
+See [Version Discovery](/servers/versioning#version-discovery) for how to discover available versions.
## Raw Protocol Access
diff --git a/docs/clients/sampling.mdx b/docs/clients/sampling.mdx
index 3fbeb4940..24b9eed2f 100644
--- a/docs/clients/sampling.mdx
+++ b/docs/clients/sampling.mdx
@@ -19,9 +19,10 @@ The handler receives the conversation the server wants completed, the parameters
```python
from pathlib import Path
+
from fastmcp import Client
-from fastmcp.client.sampling import SamplingMessage, SamplingParams, RequestContext
-from mcp.types import TextContent
+from fastmcp.client.sampling import RequestContext, SamplingMessage, SamplingParams
+from mcp_types import TextContent
async def sampling_handler(
@@ -55,8 +56,8 @@ Everything the server sends arrives in the first two arguments. The messages are
The role of the message
</ResponseField>
-<ResponseField name="content" type="TextContent | ImageContent | AudioContent">
- The content of the message. TextContent has a `.text` attribute.
+<ResponseField name="content" type="TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent | list[...]">
+ The content of the message: one content block or a list of them. `TextContent` has a `.text` attribute; tool-use and tool-result blocks appear only in requests that carry tools.
</ResponseField>
</Card>
@@ -86,7 +87,7 @@ Everything the server sends arrives in the first two arguments. The messages are
</ResponseField>
<ResponseField name="tool_choice" type="ToolChoice | None">
- Tool usage behavior (`auto`, `required`, or `none`)
+ Tool usage behavior; its `mode` is `auto`, `required`, or `none`
</ResponseField>
</Card>
@@ -99,11 +100,13 @@ Writing the provider call yourself is rarely worth it. FastMCP ships handlers fo
<VersionBadge version="2.11.0" />
```python
+from pathlib import Path
+
from fastmcp import Client
from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
sampling_handler=OpenAISamplingHandler(default_model="gpt-4o"),
)
```
@@ -111,12 +114,14 @@ client = Client(
Point the handler at any OpenAI-compatible API, including a local model server, by passing your own provider client:
```python
+from pathlib import Path
+
from fastmcp import Client
from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
from openai import AsyncOpenAI
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
sampling_handler=OpenAISamplingHandler(
default_model="llama-3.1-70b",
client=AsyncOpenAI(base_url="http://localhost:8000/v1"),
@@ -133,11 +138,13 @@ Install the OpenAI handler with `pip install 'fastmcp[openai]'`.
<VersionBadge version="2.14.1" />
```python
+from pathlib import Path
+
from fastmcp import Client
from fastmcp.client.sampling.handlers.anthropic import AnthropicSamplingHandler
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
sampling_handler=AnthropicSamplingHandler(default_model="claude-sonnet-4-5"),
)
```
@@ -153,11 +160,13 @@ When upgrading to Anthropic SDK 1.x, custom HTTP clients passed to `AsyncAnthrop
<VersionBadge version="3.1.0" />
```python
+from pathlib import Path
+
from fastmcp import Client
from fastmcp.client.sampling.handlers.google_genai import GoogleGenaiSamplingHandler
client = Client(
- "my_mcp_server.py",
+ Path("my_mcp_server.py"),
sampling_handler=GoogleGenaiSamplingHandler(default_model="gemini-2.0-flash"),
)
```
@@ -172,21 +181,19 @@ The [source of these handlers](https://github.com/PrefectHQ/fastmcp/tree/main/fa
A sampling request can carry tools. When it does, your handler passes them to the model and returns whatever comes back, tool calls included β€” the server executes the tools itself and sends a follow-up sampling request with the results if it needs another turn. Your handler never runs a tool.
-Registering any `sampling_handler` advertises full sampling support, tools included. A handler that only generates text should say so, so servers know not to send tools it will drop:
+Registering a `sampling_handler` advertises basic sampling only, and the protocol lets a server send tools only to a client that declares the `sampling.tools` capability. When your handler can pass tools to its model, as the built-in handlers can, declare it with `sampling_capabilities`:
```python
-from fastmcp import Client
-from mcp.types import SamplingCapability
-
-
-async def text_only_handler(messages, params, context) -> str:
- return "Generated response based on the messages"
+from pathlib import Path
+from fastmcp import Client
+from fastmcp.client.sampling.handlers.openai import OpenAISamplingHandler
+from mcp_types import SamplingCapability, SamplingToolsCapability
client = Client(
- "my_mcp_server.py",
- sampling_handler=text_only_handler,
- sampling_capabilities=SamplingCapability(),
+ Path("my_mcp_server.py"),
+ sampling_handler=OpenAISamplingHandler(default_model="gpt-4o"),
+ sampling_capabilities=SamplingCapability(tools=SamplingToolsCapability()),
)
```
diff --git a/docs/clients/tasks.mdx b/docs/clients/tasks.mdx
index 71a1384c9..e084bf054 100644
--- a/docs/clients/tasks.mdx
+++ b/docs/clients/tasks.mdx
@@ -117,6 +117,8 @@ import asyncio
from fastmcp import Client
from fastmcp_tasks import call_tool_task
+server = "http://localhost:8000/mcp"
+
async def main():
async with Client(server, mode="auto") as client:
# Return immediately and drive the task yourself
diff --git a/docs/clients/tools.mdx b/docs/clients/tools.mdx
index 41a1f8bb5..fa0199b90 100644
--- a/docs/clients/tools.mdx
+++ b/docs/clients/tools.mdx
@@ -116,6 +116,10 @@ async with client:
<ResponseField name=".is_error" type="bool">
Boolean indicating if the tool execution failed.
</ResponseField>
+
+<ResponseField name=".meta" type="dict[str, Any] | None">
+ The `_meta` object the server attached to the result, if any.
+</ResponseField>
</Card>
Structured content without an output schema is returned as a dictionary in `.data`, including an empty object (`{}`). When structured content is absent or deserialization fails, `.data` is `None`. Fall back to content blocks in that case:
@@ -191,6 +195,19 @@ async with client:
See [Client Metadata](/servers/context#client-metadata) to learn how servers access this data.
+## Version Selection
+
+<VersionBadge version="3.0.0" />
+
+When a server exposes multiple versions of a tool, `call_tool()` runs the highest by default. Pass `version` to call a specific one:
+
+```python
+async with client:
+ result = await client.call_tool("calculate", {"x": 1, "y": 2}, version="1.0")
+```
+
+See [Version Discovery](/servers/versioning#version-discovery) for how to discover available versions.
+
## Raw Protocol Access
For complete control, use `call_tool_mcp()` which returns the raw MCP protocol object:
diff --git a/docs/clients/transports.mdx b/docs/clients/transports.mdx
index f30d0bfc6..3ee779359 100644
--- a/docs/clients/transports.mdx
+++ b/docs/clients/transports.mdx
@@ -49,12 +49,14 @@ Transport inference treats its input as trusted configuration. A string naming a
### Environment Variables
-Values you pass through `env` are merged on top of the inherited allowlist, so you add configuration rather than replacing the base environment. Anything your server needs beyond those six variables has to be listed explicitly.
+Values you pass through `env` are merged on top of the inherited allowlist, so you add configuration rather than replacing the base environment. Anything your server needs beyond the allowlist has to be listed explicitly.
**Selective forwarding** passes only the variables your server needs:
```python
import os
+
+from fastmcp import Client
from fastmcp.client.transports import StdioTransport
required_vars = ["API_KEY", "DATABASE_URL", "REDIS_HOST"]
@@ -68,6 +70,7 @@ client = Client(transport)
```python
from dotenv import dotenv_values
+from fastmcp import Client
from fastmcp.client.transports import StdioTransport
env = {
@@ -84,6 +87,7 @@ client = Client(transport)
STDIO transports maintain sessions across multiple client contexts by default (`keep_alive=True`). This reuses the same subprocess for multiple connections, improving performance.
```python
+from fastmcp import Client
from fastmcp.client.transports import StdioTransport
transport = StdioTransport(command="python", args=["server.py"])
@@ -166,6 +170,9 @@ By default, HTTPS connections verify the server's SSL certificate using the oper
Keep the trust store used by your deployment current. Updating certifi does not update the operating system's CA store or a custom bundle selected by `SSL_CERT_FILE`, `SSL_CERT_DIR`, or `verify`. Custom client factories configure their own TLS verification. Rebuild containers and restart processes after updating trust stores. This also matters for servers making outbound HTTPS requests to OAuth providers, JWKS endpoints, and upstream APIs.
For the October 2026 eMudhra CA incident, follow the [FastMCP security notice](https://github.com/PrefectHQ/fastmcp/blob/main/SECURITY.md#certificate-authority-incident-october-2026). A FastMCP package upgrade alone does not remediate every trust store.
+
+The `verify` parameter on `Client` accepts a boolean, a CA bundle path, or an `ssl.SSLContext`:
+
```python
from fastmcp import Client
@@ -185,6 +192,7 @@ client = Client("https://corp-server.internal/mcp", verify=ctx)
The `verify` parameter is also available directly on `StreamableHttpTransport` and `SSETransport`:
```python
+from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
transport = StreamableHttpTransport(
@@ -223,6 +231,7 @@ These 30s connect / 300s read values match the defaults FastMCP applies when no
Server-Sent Events transport is maintained for backward compatibility. Use Streamable HTTP for new deployments unless you have specific infrastructure requirements.
```python
+from fastmcp import Client
from fastmcp.client.transports import SSETransport
transport = SSETransport(
@@ -317,7 +326,7 @@ With multiple servers, the client timeout also limits the entire routed request,
### Tool Transformations
-FastMCP supports tool transformations within the configuration. You can change names, descriptions, tags, and arguments for tools from a server.
+FastMCP supports tool transformations within the configuration. You can change names, descriptions, tags, and arguments for tools from a server. Key each transformation by the tool's name on that server, before any server-name prefix is added.
```python
config = {
@@ -326,7 +335,7 @@ config = {
"url": "https://weather.example.com/mcp",
"transport": "http",
"tools": {
- "weather_get_forecast": {
+ "get_forecast": {
"name": "miami_weather",
"description": "Get the weather for Miami",
"arguments": {