Skip to content

🚀 The fast, Pythonic way to build MCP servers and clients.

docs: correct the server pages against main (#6406)

nate nowackf8c153c882ed
diff --git a/docs/servers/auth/authentication.mdx b/docs/servers/auth/authentication.mdx
index c1cd927cf..db336af37 100644
--- a/docs/servers/auth/authentication.mdx
+++ b/docs/servers/auth/authentication.mdx
@@ -69,13 +69,13 @@ This pattern makes sense only when you need complete control over the authentica
## FastMCP Authentication Providers
-FastMCP translates these authentication responsibility levels into a variety of concrete classes that handle the complexities of MCP protocol integration. You can build on these classes to handle the complexities of MCP protocol integration.
+FastMCP translates these authentication responsibility levels into concrete classes that handle MCP protocol integration. You can use them directly or build on them.
### TokenVerifier
-`TokenVerifier` provides pure token validation without OAuth metadata endpoints. This class focuses on the essential task of determining whether a token is valid and extracting authorization information from its claims.
+`TokenVerifier` is the base class for pure token validation without OAuth metadata endpoints. A verifier decides whether a token is valid and extracts authorization information from its claims.
-The implementation handles JWT signature verification, expiration checking, and claim extraction. It validates tokens against known issuers and audiences, ensuring that tokens intended for your server are not accepted by other systems.
+`JWTVerifier`, the most common implementation, handles JWT signature verification, expiration checking, and claim extraction. It validates tokens against known issuers and audiences, so tokens intended for other systems are not accepted by your server.
```python
from fastmcp import FastMCP
@@ -100,7 +100,7 @@ This example configures token validation against a JWT issuer. The `JWTVerifier`
`RemoteAuthProvider` enables authentication with identity providers that **support Dynamic Client Registration (DCR)**, such as Descope and WorkOS AuthKit. With DCR, MCP clients can automatically register themselves with the identity provider and obtain credentials without any manual configuration.
-This class combines token validation with OAuth discovery metadata. It extends `TokenVerifier` functionality by adding OAuth 2.0 protected resource endpoints that advertise your authentication requirements. MCP clients examine these endpoints to understand which identity providers you trust and how to obtain valid tokens.
+This class combines token validation with OAuth discovery metadata. It wraps a `TokenVerifier` and adds OAuth 2.0 protected resource endpoints that advertise your authentication requirements. MCP clients examine these endpoints to understand which identity providers you trust and how to obtain valid tokens.
The key requirement is that your identity provider must support DCR - the ability for clients to dynamically register and obtain credentials. This is what enables the seamless, automated authentication flow that MCP requires.
@@ -165,16 +165,17 @@ The implementation provides all required OAuth endpoints including authorization
from fastmcp import FastMCP
from fastmcp.server.auth import OAuthProvider
-auth = MyOAuthProvider(
- user_store=your_user_database,
- client_store=your_client_registry,
- # Additional configuration...
-)
+
+class MyOAuthProvider(OAuthProvider):
+ ...
+
+
+auth = MyOAuthProvider(base_url="https://your-server.com")
mcp = FastMCP(name="Auth Server", auth=auth)
```
-This example shows the basic structure of a custom OAuth provider. The actual implementation requires significant additional configuration for user management, client registration, and security policies.
+This example shows the basic structure of a custom OAuth provider: subclass `OAuthProvider` and pass your server's public `base_url`. The subclass must implement the client registration, authorization code, and token storage methods listed in the complete guide, along with your own user authentication and consent logic.
`OAuthProvider` should be used only when you have specific requirements that external providers cannot meet and the expertise to implement OAuth securely.
diff --git a/docs/servers/auth/full-oauth-server.mdx b/docs/servers/auth/full-oauth-server.mdx
index 529a01784..3a63dabc7 100644
--- a/docs/servers/auth/full-oauth-server.mdx
+++ b/docs/servers/auth/full-oauth-server.mdx
@@ -22,7 +22,7 @@ This documentation exists for completeness - the vast majority of applications s
## OAuthProvider
-FastMCP provides the `OAuthProvider` abstract class that implements the OAuth 2.1 specification. To use this pattern, you must subclass `OAuthProvider` and implement all required abstract methods.
+FastMCP provides the `OAuthProvider` base class that implements the OAuth 2.1 specification. To use this pattern, subclass `OAuthProvider` and implement the methods below. Its constructor takes your server's public `base_url`, plus optional `resource_base_url`, `issuer_url`, `service_documentation_url`, `client_registration_options`, `revocation_options`, and `required_scopes`.
<Note>
`OAuthProvider` handles OAuth endpoints, protocol flows, and security requirements, but delegates all storage, user management, and business logic to your implementation of the abstract methods.
@@ -30,7 +30,7 @@ FastMCP provides the `OAuthProvider` abstract class that implements the OAuth 2.
## Required Implementation
-You must implement these abstract methods to create a functioning OAuth server:
+You must implement these methods to create a functioning OAuth server:
### Client Management
@@ -206,7 +206,7 @@ You must implement these abstract methods to create a functioning OAuth server:
</ParamField>
<ParamField body="verify_token" type="async method">
- Verify bearer token for incoming requests. Return `AccessToken` if valid, `None` if invalid.
+ Verify bearer token for incoming requests. Return `AccessToken` if valid, `None` if invalid. `OAuthProvider` already implements this by calling `load_access_token`, so override it only when verification needs more than that lookup.
<Expandable title="Parameters">
<ParamField body="token" type="str">
diff --git a/docs/servers/auth/multi-auth.mdx b/docs/servers/auth/multi-auth.mdx
index d997aedc5..e022756fa 100644
--- a/docs/servers/auth/multi-auth.mdx
+++ b/docs/servers/auth/multi-auth.mdx
@@ -69,7 +69,7 @@ You don't always need a full OAuth server. If your server only needs to accept t
```python
from fastmcp import FastMCP
from fastmcp.server.auth import MultiAuth
-from fastmcp.server.auth.providers.jwt import JWTVerifier, StaticTokenVerifier
+from fastmcp.server.auth.providers.jwt import JWTVerifier
auth = MultiAuth(
verifiers=[
@@ -125,7 +125,8 @@ This changes `get_access_token().client_id` and ownership for existing `MultiAut
| Parameter | Type | Description |
| --- | --- | --- |
| `server` | `AuthProvider \| None` | Optional auth provider that owns routes and OAuth metadata. Also tried first for token verification. |
-| `verifiers` | `Mapping[str, TokenVerifier] \| list[TokenVerifier] \| TokenVerifier` | Named or distinctly configured token verifiers tried after the server. |
-| `server_source_id` | `str \| None` | Stable name for the delegated server source. Defaults to its derived identity. |
-| `base_url` | `str \| None` | Override the base URL. Defaults to the server's `base_url`. |
+| `verifiers` | `Mapping[str, TokenVerifier] \| Sequence[TokenVerifier] \| TokenVerifier \| None` | Named or distinctly configured token verifiers tried after the server. At least one is required when `server` is omitted. |
+| `server_source_id` | `str \| None` | Stable name for the delegated server source. Defaults to its derived identity. Requires `server`. |
+| `base_url` | `AnyHttpUrl \| str \| None` | Override the base URL. Defaults to the server's `base_url`. |
+| `resource_base_url` | `AnyHttpUrl \| str \| None` | Override the public base URL advertised for the protected resource. Defaults to the server's `resource_base_url`, and an explicit value is also applied to the server. |
| `required_scopes` | `list[str] \| None` | Override required scopes. Defaults to the server's scopes. |
diff --git a/docs/servers/auth/oauth-proxy.mdx b/docs/servers/auth/oauth-proxy.mdx
index c882f3fb4..2962f4a51 100644
--- a/docs/servers/auth/oauth-proxy.mdx
+++ b/docs/servers/auth/oauth-proxy.mdx
@@ -11,7 +11,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx";
The OAuth proxy enables FastMCP servers to authenticate with OAuth providers that **don't support Dynamic Client Registration (DCR)**. This includes virtually all traditional OAuth providers: GitHub, Google, Azure, AWS, Discord, Facebook, and most enterprise identity systems. For providers that do support DCR (like Descope and WorkOS AuthKit), use [`RemoteAuthProvider`](/servers/auth/remote-oauth) instead.
-MCP clients expect to register automatically and obtain credentials on the fly, but traditional providers require manual app registration through their developer consoles. The OAuth proxy bridges this gap by presenting a DCR-compliant interface to MCP clients while using your pre-registered credentials with the upstream provider. When a client attempts to register, the proxy returns your fixed credentials. When a client initiates authorization, the proxy handles the complexity of callback forwarding—storing the client's dynamic callback URL, using its own fixed callback with the provider, then forwarding back to the client after token exchange.
+MCP clients expect to register automatically and obtain credentials on the fly, but traditional providers require manual app registration through their developer consoles. The OAuth proxy bridges this gap by presenting a DCR-compliant interface to MCP clients while using your pre-registered credentials with the upstream provider. When a client registers, the proxy records it locally as a public client; your upstream credentials never leave the server. When a client initiates authorization, the proxy handles the complexity of callback forwarding—storing the client's dynamic callback URL, using its own fixed callback with the provider, then forwarding back to the client after token exchange.
This approach enables any MCP client (whether using random localhost ports or fixed URLs like Claude.ai) to authenticate with traditional OAuth providers. By default, the proxy applies consent and browser-binding protections and forwards PKCE upstream. Options that disable these checks reduce the corresponding security protections, as described below.
@@ -343,6 +343,30 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
</Warning>
</ParamField>
+<ParamField body="fallback_access_token_expiry_seconds" type="int | None">
+ Access token lifetime to assume when the upstream token response omits
+ `expires_in`. Defaults to 1 hour when the upstream issues a refresh token, and
+ 1 year when it does not (for API-key-style tokens such as GitHub OAuth Apps).
+</ParamField>
+
+<ParamField body="fallback_refresh_token_expiry_seconds" type="int | None">
+ Lifetime of the FastMCP-issued refresh token when the upstream response omits
+ `refresh_expires_in`. Defaults to 1 year. The upstream refresh remains
+ authoritative: if the provider rejects it, the client receives `invalid_grant`
+ and re-authenticates.
+</ParamField>
+
+<ParamField body="fastmcp_access_token_expiry_seconds" type="int | None">
+ Lifetime of the FastMCP-issued access token, decoupled from the upstream
+ `expires_in`. Defaults to the upstream lifetime. See [Token
+ Architecture](#token-architecture).
+</ParamField>
+
+<ParamField body="token_expiry_threshold_seconds" type="int" default="0">
+ Treat upstream tokens as expired this many seconds before their actual expiry,
+ so a token that is about to expire is refreshed before use.
+</ParamField>
+
<ParamField body="consent_csp_policy" type="str | None" default="None">
Content Security Policy for the consent page.
@@ -369,6 +393,7 @@ auth = OAuthProxy(..., client_storage=MemoryStore())
FastMCP includes pre-configured providers for common services:
```python
+from fastmcp import FastMCP
from fastmcp.server.auth.providers.github import GitHubProvider
auth = GitHubProvider(
@@ -404,7 +429,7 @@ OAuth scopes control what permissions your application requests from users. They
JWTVerifier(..., required_scopes = ["read:user", "write:data"])
```
-Dynamic clients created by the proxy will automatically include these scopes in their authorization requests. See the [Token Verification](#token-verification) section below for detailed setup.
+Dynamic clients created by the proxy will automatically include these scopes in their authorization requests. See the [Token Verification](#token-verification) section above for detailed setup.
`required_scopes` and `valid_scopes` play different roles. `required_scopes` is what every token must carry, and it is the set the `WWW-Authenticate` challenge tells clients to request. `valid_scopes` is the catalog of scopes clients may request, advertised as `scopes_supported` in protected resource metadata. MCP clients that follow the challenge request only the required scopes, so a scope that appears only in `valid_scopes` stays optional.
@@ -476,7 +501,7 @@ sequenceDiagram
Note over Client, Proxy: Dynamic Registration (Local)
Client->>Proxy: 1. POST /register<br/>redirect_uri: localhost:54321/callback
- Proxy-->>Client: 2. Returns fixed upstream credentials
+ Proxy-->>Client: 2. Returns local client registration<br/>(public client, no secret)
Note over Client, User: Authorization with User Consent
Client->>Proxy: 3. GET /authorize<br/>redirect_uri=localhost:54321/callback<br/>code_challenge=CLIENT_CHALLENGE
@@ -504,7 +529,7 @@ The flow diagram above illustrates the complete OAuth proxy pattern. Let's under
### Registration Phase
-When an MCP client calls `/register` with its dynamic callback URL, the proxy responds with your pre-configured upstream credentials. The client stores these credentials believing it has registered a new app. Meanwhile, the proxy records the client's callback URL for later use.
+When an MCP client calls `/register` with its dynamic callback URL, the proxy validates the redirect URIs and stores the registration in its own client storage. The client receives a standard DCR response for a public client (`token_endpoint_auth_method` of `none`, no client secret). Your upstream client ID and secret are never sent to the client; the proxy uses them itself when it talks to the provider.
### Authorization Phase
@@ -542,10 +567,10 @@ The OAuth proxy implements a **token factory pattern**: instead of directly forw
When an MCP client completes authorization, the proxy:
1. **Receives upstream tokens** from the OAuth provider (GitHub, Google, etc.)
-2. **Encrypts and stores** these tokens using Fernet encryption (AES-128-CBC + HMAC-SHA256)
+2. **Stores** these tokens in `client_storage`. The default store encrypts them with Fernet (AES-128-CBC + HMAC-SHA256); wrap a custom store in `FernetEncryptionWrapper` for the same protection
3. **Issues FastMCP JWT tokens** to the client, signed with HS256
-The FastMCP JWT contains minimal claims: issuer, audience, client ID, scopes, expiration, and a unique token identifier (JTI). The JTI acts as a reference linking to the encrypted upstream token.
+The FastMCP JWT contains minimal claims: issuer, audience, client ID, scopes, issued-at and expiration times, and a unique token identifier (JTI). Providers that extract claims from the upstream token embed them under an `upstream_claims` claim. The JTI acts as a reference linking to the encrypted upstream token.
**Token validation:**
@@ -632,7 +657,7 @@ auth = OAuthProxy(
)
```
-Check your server logs for "Client registered with redirect_uri" messages to identify what URLs your clients use.
+With debug logging enabled, the proxy logs a "Client registered with redirect_uri" message for each registration, which shows the URLs your clients use.
### Application Type (Web vs. Native)
@@ -740,12 +765,17 @@ To enable it, pass an `IdentityAssertion` configuration listing the issuers you
```python
from fastmcp import FastMCP
from fastmcp.server.auth import OAuthProxy, IdentityAssertion
+from fastmcp.server.auth.providers.jwt import JWTVerifier
auth = OAuthProxy(
upstream_authorization_endpoint="https://accounts.example.com/authorize",
upstream_token_endpoint="https://accounts.example.com/token",
upstream_client_id="your-client-id",
upstream_client_secret="your-client-secret",
+ token_verifier=JWTVerifier(
+ jwks_uri="https://accounts.example.com/.well-known/jwks.json",
+ issuer="https://accounts.example.com",
+ ),
base_url="https://your-server.com",
identity_assertion=IdentityAssertion(
trusted_issuers=["https://login.acme-corp.com"],
@@ -771,7 +801,7 @@ For each ID-JAG presented at the token endpoint, the proxy checks that:
- the JOSE header `typ` is `oauth-id-jag+jwt`;
- the `iss` claim is one of the configured `trusted_issuers`;
- the signature verifies against the issuer's published keys;
-- the `aud` claim identifies this authorization server — configure your identity provider to mint assertions whose `aud` is the `issuer` value published at `/.well-known/oauth-authorization-server`, which is your `issuer_url` when you set one and your `base_url` otherwise;
+- the `aud` claim identifies this authorization server — configure your identity provider to mint assertions whose `aud` is the `issuer` value published at `/.well-known/oauth-authorization-server`, which is your `issuer_url` when you set one and your `base_url` otherwise (set `audience` on `IdentityAssertion` only if your IdP binds assertions to a different identifier);
- the signed `client_id` claim matches the client presenting the assertion — an assertion the IdP minted for one client cannot be redeemed by another;
- the signed `resource` claim names this server — an assertion minted for a different MCP server behind the same IdP is rejected;
- `exp` (and `iat`/`nbf`, when present) place the assertion within a short lifetime and its validity window; and
@@ -813,7 +843,7 @@ The OAuth proxy requires cryptographic keys for JWT signing and storage encrypti
On every platform, FastMCP deterministically derives `jwt_signing_key` from `upstream_client_secret` using HKDF, and storage defaults to an encrypted disk store in your platform's data directory (derived from `platformdirs`). Tokens survive server restarts as long as `upstream_client_secret` doesn't change. This is **only** suitable for development and local testing.
**For production:**
-Configure the following parameters together: provide a unique `jwt_signing_key` (for signing FastMCP JWTs), and a shared `client_storage` backend (for storing tokens). Both are required for production deployments. Use a network-accessible storage backend like Redis or DynamoDB rather than local disk storage. **Wrap your storage in `FernetEncryptionWrapper` to encrypt sensitive OAuth tokens at rest** (see the `client_storage` parameter documentation above for examples). The keys accept any secret string and derive proper cryptographic keys using HKDF. See [OAuth Token Security](/deployment/http#oauth-token-security) and [Storage Backends](/servers/storage-backends) for complete production setup.
+Configure the following parameters together: provide a unique `jwt_signing_key` (for signing FastMCP JWTs), and a shared `client_storage` backend (for storing tokens). Both are required for production deployments. Use a network-accessible storage backend like Redis or DynamoDB rather than local disk storage. **Wrap your storage in `FernetEncryptionWrapper` to encrypt sensitive OAuth tokens at rest** (see the `client_storage` parameter documentation above for examples). A string `jwt_signing_key` is stretched into a 32-byte key with PBKDF2, as described under the `jwt_signing_key` parameter. See [OAuth Token Security](/deployment/http#oauth-token-security) and [Storage Backends](/servers/storage-backends) for complete production setup.
#### Expired state cleanup
diff --git a/docs/servers/auth/oidc-proxy.mdx b/docs/servers/auth/oidc-proxy.mdx
index 25c0ead01..3834b8e80 100644
--- a/docs/servers/auth/oidc-proxy.mdx
+++ b/docs/servers/auth/oidc-proxy.mdx
@@ -108,8 +108,8 @@ mcp = FastMCP(name="My Server", auth=auth)
</ParamField>
<ParamField body="algorithm" type="str | None">
- JWT algorithm to use for token verification (e.g., "RS256"). If not specified,
- uses the provider's default. Only used when `token_verifier` is not provided.
+ JWT algorithm to use for token verification (e.g., "ES256"). Defaults to
+ `RS256`. Only used when `token_verifier` is not provided.
</ParamField>
<ParamField body="required_scopes" type="list[str] | None">
@@ -117,6 +117,17 @@ mcp = FastMCP(name="My Server", auth=auth)
included in authorization requests. Only used when `token_verifier` is not provided.
</ParamField>
+<ParamField body="verify_id_token" type="bool" default="False">
+
+<VersionBadge version="3.0.1" />
+ Verify the upstream OIDC `id_token` instead of the access token. Use this for
+ providers that issue opaque access tokens but standard JWT ID tokens. The
+ default verifier then checks the ID token's audience against `client_id`, and
+ `required_scopes` is enforced on FastMCP-issued tokens instead of the upstream
+ token, since ID tokens carry no scope claim. The upstream access token is
+ still stored for calls to the provider's APIs.
+</ParamField>
+
<ParamField body="redirect_path" type="str" default="/auth/callback">
Path for OAuth callbacks. Must match the redirect URI configured in your OAuth
application
@@ -224,25 +235,28 @@ auth = OIDCProxy(
</ParamField>
</Card>
+`OIDCProxy` also accepts `issuer_url`, `forward_resource`, `extra_authorize_params`, `extra_token_params`, the token expiry options, and `identity_assertion`, with the same meaning as on [`OAuthProxy`](/servers/auth/oauth-proxy#configuration-parameters). When you set `audience`, it is added to both the authorization and token requests; an `audience` key in `extra_authorize_params` or `extra_token_params` takes precedence.
+
### Using Built-in Providers
FastMCP includes pre-configured OIDC providers for common services:
```python
+from fastmcp import FastMCP
from fastmcp.server.auth.providers.auth0 import Auth0Provider
auth = Auth0Provider(
- config_url="https://.../.well-known/openid-configuration",
+ config_url="https://your-tenant.us.auth0.com/.well-known/openid-configuration",
client_id="your-auth0-client-id",
client_secret="your-auth0-client-secret",
- audience="https://...",
- base_url="https://localhost:8000"
+ audience="https://your-api-identifier.com",
+ base_url="http://localhost:8000"
)
mcp = FastMCP(name="My Server", auth=auth)
```
-Available providers include `Auth0Provider` at present.
+Available providers include [`Auth0Provider`](/integrations/auth0), [`AWSCognitoProvider`](/integrations/aws-cognito), and [`OCIProvider`](/integrations/oci).
### Scope Configuration
@@ -281,7 +295,7 @@ auth = Auth0Provider(
client_id=os.environ.get("AUTH0_CLIENT_ID"),
client_secret=os.environ.get("AUTH0_CLIENT_SECRET"),
audience=os.environ.get("AUTH0_AUDIENCE"),
- base_url=os.environ.get("BASE_URL", "https://localhost:8000")
+ base_url=os.environ.get("BASE_URL", "http://localhost:8000")
)
mcp = FastMCP(name="My Server", auth=auth)
diff --git a/docs/servers/auth/remote-oauth.mdx b/docs/servers/auth/remote-oauth.mdx
index 9a7dfea52..19d0cfcef 100644
--- a/docs/servers/auth/remote-oauth.mdx
+++ b/docs/servers/auth/remote-oauth.mdx
@@ -130,6 +130,18 @@ The `authorization_servers` list tells MCP clients which identity providers you
Some identity providers use different scope formats for authorization requests versus token claims. For example, Azure AD requires clients to request full URI scopes like `api://client-id/read`, but the token's `scp` claim contains just `read`. The `scopes_supported` parameter lets you advertise the full-form scopes in metadata while validating against the short form:
```python
+from pydantic import AnyHttpUrl
+
+from fastmcp.server.auth import RemoteAuthProvider
+from fastmcp.server.auth.providers.jwt import JWTVerifier
+
+token_verifier = JWTVerifier(
+ jwks_uri="https://auth.example.com/.well-known/jwks.json",
+ issuer="https://auth.example.com",
+ audience="my-api",
+ required_scopes=["read"],
+)
+
auth = RemoteAuthProvider(
token_verifier=token_verifier,
authorization_servers=[AnyHttpUrl("https://auth.example.com")],
@@ -140,6 +152,30 @@ auth = RemoteAuthProvider(
When not set, `scopes_supported` defaults to the token verifier's `required_scopes`. For Azure AD specifically, see the [AzureJWTVerifier](/integrations/azure#token-verification-only-managed-identity) which handles this automatically.
+`challenge_scopes` applies the same translation to the `WWW-Authenticate` challenge, which tells clients which scopes to request when they lack a valid token. Set it to the request-facing form of the verifier's `required_scopes`; validation still checks the short form. When omitted, the challenge comes from the token verifier's `get_challenge_scopes`, which returns `required_scopes` unchanged unless the verifier overrides it:
+
+```python
+from pydantic import AnyHttpUrl
+
+from fastmcp.server.auth import RemoteAuthProvider
+from fastmcp.server.auth.providers.jwt import JWTVerifier
+
+token_verifier = JWTVerifier(
+ jwks_uri="https://auth.example.com/.well-known/jwks.json",
+ issuer="https://auth.example.com",
+ audience="my-api",
+ required_scopes=["read"],
+)
+
+auth = RemoteAuthProvider(
+ token_verifier=token_verifier,
+ authorization_servers=[AnyHttpUrl("https://auth.example.com")],
+ base_url="https://api.example.com",
+ scopes_supported=["api://my-api/read", "api://my-api/write"],
+ challenge_scopes=["api://my-api/read"],
+)
+```
+
### Custom Endpoints
You can extend `RemoteAuthProvider` to add additional endpoints beyond the standard OAuth protected resource metadata. These don't have to be OAuth-specific - you can add any endpoints your authentication integration requires.
@@ -226,7 +262,7 @@ Redirect URIs are validated by the DCR provider itself, since it owns the regist
Remote OAuth integration requires careful attention to several technical details that affect reliability and security.
-**Token Validation Performance**: Your server validates every incoming token by checking signatures against your identity provider's public keys. Consider implementing key caching and rotation handling to minimize latency while maintaining security.
+**Token Validation Performance**: Your server validates every incoming token by checking signatures against your identity provider's public keys. `JWTVerifier` caches JWKS keys for an hour and refetches when a token arrives with an unknown key ID, at most once per `jwks_refresh_interval`. See [JWKS Endpoint Integration](/servers/auth/token-verification#jwks-endpoint-integration) for the details.
**Error Handling**: Network issues with your identity provider can affect token validation. Implement appropriate timeouts, retry logic, and graceful degradation to maintain service availability during identity provider outages.
diff --git a/docs/servers/auth/token-verification.mdx b/docs/servers/auth/token-verification.mdx
index 126ab0baa..1210371c1 100644
--- a/docs/servers/auth/token-verification.mdx
+++ b/docs/servers/auth/token-verification.mdx
@@ -50,9 +50,9 @@ FastMCP provides the `TokenVerifier` class to handle token validation complexity
`TokenVerifier` focuses exclusively on token validation without providing OAuth discovery metadata. This makes it ideal for internal systems where clients already know how to obtain tokens, or for microservices that trust tokens from known issuers.
-The class validates token signatures, checks expiration timestamps, and extracts authorization information from token claims. It supports various token formats and validation strategies while maintaining a consistent interface for authorization decisions.
+`TokenVerifier` is a base class: each implementation defines `verify_token`, which returns an `AccessToken` for a valid token and `None` otherwise. FastMCP ships implementations for JWTs, opaque tokens, and development use, described below. Each one presents the same interface to the rest of the server, so authorization decisions don't depend on the token format.
-You can subclass `TokenVerifier` to implement custom validation logic for specialized token formats or validation requirements. The base class handles common patterns while allowing extension for unique use cases.
+You can subclass `TokenVerifier` and implement `verify_token` yourself for specialized token formats or validation requirements.
## JWT Token Verification
@@ -85,6 +85,8 @@ The `issuer` parameter ensures tokens come from your trusted authentication syst
`JWTVerifier` accepts RSA (`RS*` and `PS*`), ECDSA (`ES*`), and Edwards-curve (`Ed25519` and `Ed448`) signatures from JWKS endpoints. Set `algorithm` when your issuer does not use the default `RS256`:
```python
+from fastmcp.server.auth.providers.jwt import JWTVerifier
+
verifier = JWTVerifier(
jwks_uri="https://auth.yourcompany.com/.well-known/jwks.json",
issuer="https://auth.yourcompany.com",
@@ -157,6 +159,7 @@ mcp = FastMCP(name="Protected API", auth=verifier)
```
This configuration validates tokens using a specific RSA, ECDSA, or EdDSA public key. The key must correspond to the private key used by your token issuer. While less flexible than JWKS endpoints, this approach can be useful in development environments or when testing with fixed keys.
+
## Opaque Token Verification
Many authorization servers issue opaque tokens rather than self-contained JWTs. Opaque tokens are random strings that carry no information themselves - the authorization server maintains their state and validation requires querying the server. FastMCP supports opaque token validation through OAuth 2.0 Token Introspection (RFC 7662).
@@ -190,6 +193,8 @@ mcp = FastMCP(name="Protected API", auth=verifier)
The verifier authenticates to the introspection endpoint using client credentials and queries it whenever a bearer token arrives. FastMCP checks whether the token is active and has sufficient scopes before allowing access.
+Introspection results are not cached by default, so a token revoked at the authorization server is rejected on its next request. Set `cache_ttl_seconds` to cache results for that many seconds when the per-request network call costs more than immediate revocation is worth; `max_cache_size` bounds the cache and defaults to 10,000 tokens.
+
If your authorization server returns an `aud` field, set `audience` to select tokens for your API. You can provide one audience or a list of allowed audiences. The response must contain a matching string or an array of nonempty strings with at least one match; a missing or malformed `aud` is rejected when `audience` is configured.
```python
@@ -213,6 +218,8 @@ Two standard client authentication methods are supported, both defined in RFC 67
Most OAuth providers support both methods, though some may require one specifically. Configure the authentication method with the `client_auth_method` parameter:
```python
+from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier
+
# Use POST body authentication instead of Basic Auth
verifier = IntrospectionTokenVerifier(
introspection_url="https://auth.yourcompany.com/oauth/introspect",
@@ -281,6 +288,7 @@ By default, `DebugTokenVerifier` accepts any non-empty token as valid. This elim
For more controlled testing, provide custom validation logic:
```python
+from fastmcp import FastMCP
from fastmcp.server.auth.providers.debug import DebugTokenVerifier
# Synchronous validation - check token prefix
@@ -296,12 +304,18 @@ mcp = FastMCP(name="Development Server", auth=verifier)
The validation callable can also be async, enabling database lookups or external service calls:
```python
+from redis.asyncio import Redis
+
+from fastmcp import FastMCP
from fastmcp.server.auth.providers.debug import DebugTokenVerifier
-# Asynchronous validation - check against cache
+redis = Redis()
+
+
+# Asynchronous validation - check against Redis
async def validate_token(token: str) -> bool:
- # Check if token exists in Redis, database, etc.
- return await redis.exists(f"valid_tokens:{token}")
+ return await redis.exists(f"valid_tokens:{token}") > 0
+
verifier = DebugTokenVerifier(
validate=validate_token,
@@ -387,8 +401,11 @@ mcp = FastMCP(name="Protected API", auth=verifier)
The same pattern works for `JWTVerifier` when using JWKS endpoints:
```python
+import httpx2
from fastmcp.server.auth.providers.jwt import JWTVerifier
+http_client = httpx2.AsyncClient(timeout=10)
+
verifier = JWTVerifier(
jwks_uri="https://auth.yourcompany.com/.well-known/jwks.json",
issuer="https://auth.yourcompany.com",
@@ -405,6 +422,8 @@ When you provide an `http_client`, you are responsible for its lifecycle. The ve
```python
from contextlib import asynccontextmanager
+
+import httpx2
from fastmcp import FastMCP
from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier
@@ -426,7 +445,7 @@ mcp = FastMCP(name="My API", auth=verifier, lifespan=lifespan)
```
</Note>
-The convenience providers (`GitHubProvider`, `GoogleProvider`, `DiscordProvider`, `WorkOSProvider`, `AzureProvider`) also accept `http_client` and pass it through to their internal token verifier.
+The convenience providers (`GitHubProvider`, `GoogleProvider`, `DiscordProvider`, `WorkOSProvider`, `AzureProvider`, `ClerkProvider`, `HuggingFaceProvider`) also accept `http_client` and pass it through to their internal token verifier.
## Production Configuration
diff --git a/docs/servers/authorization.mdx b/docs/servers/authorization.mdx
index d6a288626..5d598ff90 100644
--- a/docs/servers/authorization.mdx
+++ b/docs/servers/authorization.mdx
@@ -215,6 +215,10 @@ from fastmcp.server.auth import AuthContext
mcp = FastMCP("Async Auth Server")
+async def fetch_user_permissions(user_id: str | None) -> set[str]:
+ """Look up a user's permissions in your own store."""
+ return set()
+
async def check_user_permissions(ctx: AuthContext) -> bool:
"""Async auth check that reads server state."""
if ctx.token is None:
@@ -397,7 +401,7 @@ def update_record(id: str) -> str:
This holds across several `AuthMiddleware` instances too, not just several checks within one. In the [tag-based configuration](#tag-based-global-authorization) each middleware contributes its own requirement, and the first to find a shortfall reports the requirements of the others alongside its own — so one re-authorization covers the whole chain rather than one layer at a time.
-A shortfall is reported only when the scope requirement is what actually caused the denial. If you [combine checks](#combining-checks) and a non-scope check rejects the request first — a tenant policy, say — the denial stays a plain `AuthorizationError` and names no scopes at all. Disclosing a scope requirement for a component the caller could not reach anyway would leak information about components they are not authorized to see.
+A shortfall is reported only when the scope requirement is what actually caused the denial. If you [combine checks](#combining-checks) and a non-scope check rejects the request — a tenant policy, say — the denial stays a plain `AuthorizationError` and names no scopes at all. Disclosing a scope requirement for a component the caller could not reach anyway would leak information about components they are not authorized to see.
That rule also bounds what gets aggregated. Combining requirements only reaches as far down the chain as the request itself would have gone: it stops at the first layer holding a custom check, since whether that layer would admit the caller is unknown until it runs, and running it early would trigger authorization logic the request had not reached yet. Requirements at or beyond that point sit behind an unverified gate and are left out.
diff --git a/docs/servers/completions.mdx b/docs/servers/completions.mdx
index d59a18488..87164617a 100644
--- a/docs/servers/completions.mdx
+++ b/docs/servers/completions.mdx
@@ -118,7 +118,9 @@ A handler may return any of three things:
- `None` — treated as an empty completion, for references and arguments the handler does not recognize.
- A `Completion` object — when you want to include pagination hints alongside the values.
-The MCP protocol caps a single response at 100 values. When more candidates exist, return a `Completion` and set `total` (how many candidates match in all) and `has_more` (whether values were truncated) so the client can indicate that the list is partial.
+Returning a bare string raises `TypeError`; wrap a single candidate in a list.
+
+The MCP protocol caps a single response at 100 values. FastMCP truncates a longer list to its first 100 values and sets `total` to the full count and `has_more` to `True`, so returning every match is safe. Return a `Completion` yourself when you only fetched part of the result set and know the real total, so the client can still show that the list is partial.
```python
from fastmcp import FastMCP
@@ -134,19 +136,20 @@ def pick_city(city: str) -> str:
return f"Tell me about {city}"
-def search_cities(prefix: str) -> list[str]:
- # A real lookup might return thousands of matches; ALL_CITIES stands in.
- return [c for c in ALL_CITIES if c.startswith(prefix)]
+def search_cities(prefix: str, limit: int) -> tuple[list[str], int]:
+ # A real lookup would query a database for one page and a count.
+ matches = [c for c in ALL_CITIES if c.startswith(prefix)]
+ return matches[:limit], len(matches)
@mcp.completion
def complete(ref, argument, context):
if isinstance(ref, PromptReference) and argument.name == "city":
- matches = search_cities(argument.value)
+ page, total = search_cities(argument.value, limit=100)
return Completion(
- values=matches[:100],
- total=len(matches),
- has_more=len(matches) > 100,
+ values=page,
+ total=total,
+ has_more=total > len(page),
)
return None
```
diff --git a/docs/servers/composition.mdx b/docs/servers/composition.mdx
index 5eb205aea..ba8308fc3 100644
--- a/docs/servers/composition.mdx
+++ b/docs/servers/composition.mdx
@@ -113,6 +113,8 @@ For advanced configuration, see [Proxying](/servers/providers/proxy).
When mounting multiple servers, use namespaces to avoid naming conflicts:
```python
+from fastmcp import FastMCP
+
weather = FastMCP("Weather")
calendar = FastMCP("Calendar")
@@ -151,6 +153,10 @@ Resource and template URIs without `://`, such as `urn:example:config`, remain u
Because `mount()` creates a live link, you can add components to a child server after mounting and they'll be immediately available through the parent:
```python
+from fastmcp import FastMCP
+
+dynamic_server = FastMCP("Dynamic")
+
main = FastMCP("Main")
main.mount(dynamic_server, namespace="dynamic")
@@ -175,6 +181,8 @@ Compose providers that need new extensions before the parent starts. Once extens
Parent server tag filters apply recursively to mounted servers:
```python
+from fastmcp import FastMCP
+
api_server = FastMCP("API")
@api_server.tool(tags={"production"})
@@ -234,6 +242,8 @@ main.mount(subserver, namespace="sub")
When mounting multiple servers with the same namespace (or no namespace), FastMCP queries all mounted providers for a requested component and returns the highest matching version. If two unversioned components (or two equal versions) use the same identifier, the provider registered first wins.
```python
+from fastmcp import FastMCP
+
server_a = FastMCP("A")
server_b = FastMCP("B")
diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx
index 40d80eb4d..84c8188a3 100644
--- a/docs/servers/context.mdx
+++ b/docs/servers/context.mdx
@@ -32,7 +32,7 @@ The `Context` object provides a clean interface to access MCP features within yo
The preferred way to access context is using the `CurrentContext()` dependency:
-```python {1, 6}
+```python {2, 8}
from fastmcp import FastMCP
from fastmcp.dependencies import CurrentContext
from fastmcp.server.context import Context
@@ -107,12 +107,12 @@ async def process_data(data: list[float]) -> dict:
# Get the active context - only works when called within a request
ctx = get_context()
await ctx.info(f"Processing {len(data)} data points")
+ return {"count": len(data), "total": sum(data)}
@mcp.tool
-async def analyze_dataset(dataset_name: str) -> dict:
+async def analyze_dataset(data: list[float]) -> dict:
# Call utility function that uses context internally
- data = load_data(dataset_name)
- await process_data(data)
+ return await process_data(data)
```
**Important Notes:**
@@ -140,7 +140,7 @@ See [Server Logging](/servers/logging) for complete documentation and examples.
<VersionBadge version="2.10.0" />
-Request structured input from clients during tool execution, enabling interactive workflows and progressive disclosure. This is a new feature in the 6/18/2025 MCP spec.
+Request structured input from clients during tool execution, enabling interactive workflows and progressive disclosure. Elicitation was introduced in the 6/18/2025 MCP spec.
```python
result = await ctx.elicit("Enter your name:", response_type=str)
@@ -197,7 +197,7 @@ messages = result.messages
```
**Method signatures:**
-- **`ctx.list_prompts() -> list[MCPPrompt]`**: Returns list of all available prompts
+- **`ctx.list_prompts() -> list[mcp.types.Prompt]`**: Returns list of all available prompts
- **`ctx.get_prompt(name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult`**: Get a specific prompt with optional arguments
### Request State
@@ -244,13 +244,28 @@ With the default `serializable=True`, values live in the current server's state
The most useful thing request state holds is objects you *can't* persist — a database connection or an HTTP client that a middleware or the [lifespan](/servers/lifespan) opens and a handler uses. Pass `serializable=False`:
```python
-async def my_tool(ctx: Context) -> str:
- client = SomeHTTPClient(base_url="https://api.example.com")
- await ctx.set_state("client", client, serializable=False)
+import httpx
+from fastmcp import FastMCP, Context
+from fastmcp.server.middleware import Middleware, MiddlewareContext
+
+mcp = FastMCP("app")
+
+
+class HTTPClientMiddleware(Middleware):
+ async def on_call_tool(self, context: MiddlewareContext, call_next):
+ async with httpx.AsyncClient(base_url="https://api.example.com") as client:
+ await context.fastmcp_context.set_state("client", client, serializable=False)
+ return await call_next(context)
+
+mcp.add_middleware(HTTPClientMiddleware())
+
+
+async def fetch_data(ctx: Context) -> str:
client = await ctx.get_state("client")
- return await client.fetch("/data")
+ response = await client.get("/data")
+ return response.text
```
A `serializable=False` value lives on the request context for the current call only. It is inherently request-scoped — a live connection can't be serialized and stored — which is exactly why it belongs here rather than in a persistent store.
@@ -345,7 +360,7 @@ async def request_info(ctx: Context) -> dict:
**Available Properties:**
- **`ctx.request_id -> str`**: Get the unique ID for the current MCP request
-- **`ctx.client_id -> str | None`**: Get the ID of the client making the request, if provided during initialization
+- **`ctx.client_id -> str | None`**: Get the `client_id` value from the request's metadata, if the client sent one
- **`ctx.session_id -> str`**: Get the identifier of the current MCP connection. It's stable for the session on handshake-era connections but new on every request on 2026-07-28 connections, so don't use it to share data between calls; use [Session State](/servers/sessions) instead. Raises `RuntimeError` if the MCP session is not yet established.
#### Request Context Availability
@@ -396,9 +411,16 @@ For HTTP request access that works regardless of MCP session availability (when
Clients can send contextual information with their requests using the `meta` parameter. This metadata is accessible through `ctx.request_context.meta` and is available for all MCP operations (tools, resources, prompts).
-The `meta` field is `None` when the request carries no metadata. Otherwise it is a plain `dict`, so read values with `meta.get("user_id")`; attribute access such as `meta.user_id` raises `AttributeError`. Alongside the client's own keys, the dictionary can include protocol-level keys such as `progressToken`. The structure of the client's metadata is determined by the client making the request.
+The `meta` field is `None` when the request carries no metadata. Otherwise it is a plain `dict`, so read values with `meta.get("user_id")`; attribute access such as `meta.user_id` raises `AttributeError`. Alongside the client's own keys, the dictionary can include protocol-level keys such as `progressToken` and, on 2026-07-28 connections, `io.modelcontextprotocol/`-prefixed keys like `io.modelcontextprotocol/clientInfo`. The structure of the client's metadata is determined by the client making the request.
```python
+import logging
+
+from fastmcp import FastMCP, Context
+
+logger = logging.getLogger(__name__)
+mcp = FastMCP(name="Email Server")
+
@mcp.tool
def send_email(to: str, subject: str, body: str, ctx: Context) -> str:
"""Send an email, logging metadata about the request."""
@@ -413,7 +435,7 @@ def send_email(to: str, subject: str, body: str, ctx: Context) -> str:
# Use metadata for logging, observability, etc.
if trace_id:
- log_with_trace(f"Sending email for user {user_id}", trace_id)
+ logger.info("Sending email for user %s (trace %s)", user_id, trace_id)
# Send the email...
return f"Email sent to {to}"
diff --git a/docs/servers/dependency-injection.mdx b/docs/servers/dependency-injection.mdx
index e3f83f0d1..dd75fa703 100644
--- a/docs/servers/dependency-injection.mdx
+++ b/docs/servers/dependency-injection.mdx
@@ -81,7 +81,7 @@ async def process_data(data: str, ctx: Context) -> str:
from fastmcp.dependencies import CurrentContext
@mcp.tool
-async def process_data(data: str, ctx: Context = CurrentContext()) -> str:
+async def process_data_explicit(data: str, ctx: Context = CurrentContext()) -> str:
...
```
@@ -232,8 +232,12 @@ async def get_user_id(token: AccessToken = CurrentAccessToken()) -> str:
**Function:** Use `get_access_token()` (returns `None` if not authenticated):
```python
+from fastmcp import FastMCP
from fastmcp.server.dependencies import get_access_token
+mcp = FastMCP("Demo")
+
+
@mcp.tool
async def get_user_info() -> dict:
token = get_access_token()
@@ -265,8 +269,7 @@ async def add_expense(
amount: float,
user_id: str = TokenClaim("oid"), # Azure object ID
) -> dict:
- await db.insert({"user_id": user_id, "amount": amount})
- return {"status": "created", "user_id": user_id}
+ return {"status": "created", "user_id": user_id, "amount": amount}
```
`TokenClaim()` raises a `RuntimeError` if the claim doesn't exist, listing available claims to help with debugging.
@@ -289,9 +292,11 @@ For background task execution, FastMCP provides dependencies that integrate with
```python
from fastmcp import FastMCP
from fastmcp.dependencies import Progress
+from fastmcp_tasks import TasksExtension
from fastmcp_tasks.dependencies import CurrentDocket, CurrentWorker
mcp = FastMCP("Task Demo")
+mcp.add_extension(TasksExtension())
@mcp.tool(task=True)
@@ -316,7 +321,7 @@ async def long_running_task(
- **`Progress()`**: Track task progress with atomic updates
<Note>
-`CurrentDocket()` and `CurrentWorker()` require `pip install 'fastmcp[tasks]'`. They resolve once the server lifespan has initialized Docket, which happens as soon as any component on the server is task-enabled — so regular foreground tools, resources, and prompts can inject them too, not only task-enabled components. `Progress()` can be injected anywhere regardless, though cross-process task progress requires Docket. For comprehensive task patterns, see the [Docket documentation](https://docket.lol/en/latest/task-patterns/).
+`CurrentDocket()` and `CurrentWorker()` require `pip install 'fastmcp[tasks]'`. They resolve once the server lifespan has initialized Docket, which happens when the server has `TasksExtension` registered and at least one task-enabled component — so regular foreground tools, resources, and prompts can inject them too, not only task-enabled components. `Progress()` can be injected anywhere regardless, though cross-process task progress requires Docket. For comprehensive task patterns, see the [Docket documentation](https://docket.lol/en/latest/task-patterns/).
</Note>
## Custom Dependencies
diff --git a/docs/servers/elicitation.mdx b/docs/servers/elicitation.mdx
index 363903267..5d24f9e73 100644
--- a/docs/servers/elicitation.mdx
+++ b/docs/servers/elicitation.mdx
@@ -27,7 +27,7 @@ Elicitation reaches the user two different ways, depending on the protocol era t
- **On handshake-era connections (≤ 2025-11-25)**, a running tool calls [`ctx.elicit()`](#requesting-input-on-handshake-connections). The tool pauses mid-execution, the server sends a request over the session back-channel, and the tool resumes with the answer. This is the original elicitation API and the rest of this page's first half covers it in full.
- **On the modern protocol (2026-07-28)**, that back-channel is gone — server-initiated requests were removed from the wire (SEP-2322, with statelessness from SEP-2575), so a tool cannot issue a request mid-execution and block on the answer. Instead a tool asks for input by *returning* a description of what it needs; each round completes normally and the client issues a new call with the answer attached. This is the [guard pattern](#elicitation-on-the-modern-protocol), covered in the second half.
-The era gate is strict: `ctx.elicit()` only works on handshake connections, and the guard pattern only works on modern ones. A tool that returns a guard result on a handshake connection — or calls `ctx.elicit()` on a modern one — raises a clear era error rather than failing obscurely. A server that serves both eras may need both paths; branch on `ctx.request_context.protocol_version` to pick the right one. `fastmcp.Client` drives whichever the connection negotiated automatically.
+The era gate is strict: `ctx.elicit()` only works on handshake connections, and the guard pattern only works on modern ones. A [background task](/servers/tasks#gathering-input-mid-task) also gathers input with the guard pattern; `ctx.elicit()` raises inside one. A tool that returns a guard result on a handshake connection — or calls `ctx.elicit()` on a modern one — raises a clear era error rather than failing obscurely. A server that serves both eras may need both paths; branch on `ctx.request_context.protocol_version` to pick the right one. `fastmcp.Client` drives whichever the connection negotiated automatically.
## Requesting input on handshake connections
@@ -197,9 +197,8 @@ async def approve_action(ctx: Context) -> str:
result = await ctx.elicit("Approve this action?", response_type=bool)
if result.action == "accept" and result.data:
- return do_action()
- else:
- raise ValueError("Action rejected")
+ return "Action approved"
+ raise ValueError("Action rejected")
```
### Constrained Options
@@ -217,6 +216,7 @@ async def set_priority(ctx: Context) -> str:
if result.action == "accept":
return f"Priority set to: {result.data}"
+ return "No priority set"
```
```python title="Literal type"
from typing import Literal
@@ -268,6 +268,7 @@ async def select_tags(ctx: Context) -> str:
if result.action == "accept":
tags = result.data
return f"Selected tags: {', '.join(tags)}"
+ return "No tags selected"
```
```python title="list[Enum] type"
from enum import Enum
@@ -286,6 +287,7 @@ async def select_tags(ctx: Context) -> str:
if result.action == "accept":
tags = [tag.value for tag in result.data]
return f"Selected: {', '.join(tags)}"
+ return "No tags selected"
```
</CodeGroup>
@@ -309,6 +311,7 @@ async def set_priority(ctx: Context) -> str:
if result.action == "accept":
return f"Priority set to: {result.data}"
+ return "No priority set"
```
For multi-select with titles, wrap the dict in a list:
@@ -327,6 +330,7 @@ async def select_priorities(ctx: Context) -> str:
if result.action == "accept":
return f"Selected: {', '.join(result.data)}"
+ return "No priorities selected"
```
### Structured Responses
@@ -479,7 +483,7 @@ Always check `answer.action` before reading `answer.content`: a client may **dec
### Driving the loop from a client
-`fastmcp.Client` drives the whole loop automatically. Point it at a 2026-era connection (`mode="auto"` negotiates one) and give it an elicitation handler; it fulfils each round's requests and retries until the tool returns its final result.
+`fastmcp.Client` drives the whole loop automatically. Connect on a 2026-era connection (the default `mode="auto"` negotiates one when the server supports it) and give it an elicitation handler; it fulfils each round's requests and retries until the tool returns its final result.
```python
from fastmcp import Client
@@ -630,4 +634,4 @@ class GuardAwareMiddleware(Middleware):
return result
```
-One built-in makes a deliberate exception: the [response caching middleware](/servers/middleware) never stores an `InputRequiredToolResult`, because caching an ask would replay a stale question to a later caller.
+One built-in makes a deliberate exception: the [response caching middleware](/servers/middleware#caching) never stores an `InputRequiredToolResult`, because caching an ask would replay a stale question to a later caller.
diff --git a/docs/servers/extensions.mdx b/docs/servers/extensions.mdx
index f794a3cf3..d27cab967 100644
--- a/docs/servers/extensions.mdx
+++ b/docs/servers/extensions.mdx
@@ -200,7 +200,7 @@ mcp.add_extension(CallCounterExtension())
Counting is harmless either way, so this example passes unaware callers straight through. The check becomes essential the moment an interceptor short-circuits: returning an extension-specific result to a client that never negotiated the extension hands it a shape it has no way to understand. Request methods have the same requirement, and `self.client_settings(ctx)` is the equivalent inside a handler.
-`params` holds the validated `tools/call` params, and `context` is the FastMCP `Context`, so the tool being invoked is reachable as `context.fastmcp.get_tool(params.name)` along with auth scope and the server itself. When several extensions intercept, they nest with the first-registered outermost.
+`params` holds the validated `tools/call` params, and `context` is the FastMCP `Context`, so the tool being invoked is reachable as `await context.fastmcp.get_tool(params.name)` along with auth scope and the server itself. When several extensions intercept, they nest with the first-registered outermost.
Reach for middleware when you want to observe or modify requests generally; reach for an interceptor when the behavior belongs to a negotiated capability and should exist only while that extension is registered.
diff --git a/docs/servers/icons.mdx b/docs/servers/icons.mdx
index 065c28471..6427b0a46 100644
--- a/docs/servers/icons.mdx
+++ b/docs/servers/icons.mdx
@@ -156,7 +156,6 @@ For small icons or when you want to embed the icon directly without external dep
```python
from mcp.types import Icon
-from fastmcp.utilities.types import Image
# SVG icon as data URI
svg_icon = Icon(
diff --git a/docs/servers/logging.mdx b/docs/servers/logging.mdx
index e01fdd875..30918a319 100644
--- a/docs/servers/logging.mdx
+++ b/docs/servers/logging.mdx
@@ -68,6 +68,18 @@ async def process_transaction(transaction_id: str, amount: float, ctx: Context):
)
```
+## Minimum Level
+
+Messages below the minimum level are dropped before they reach the client. Set a server-wide default with `FastMCP(client_log_level=...)` or the `FASTMCP_CLIENT_LOG_LEVEL` [setting](/more/settings). On handshake-era connections a client can override it for its session with the MCP `logging/setLevel` request; the modern protocol has no session to hold that level, so a modern client filters in its own log handler instead. With no minimum set, every level is sent.
+
+```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("LoggingDemo", client_log_level="warning")
+```
+
+With this server, `ctx.debug()` and `ctx.info()` send nothing, while `ctx.warning()` and `ctx.error()` reach the client.
+
## Server-Side Logs
Messages sent to clients via `ctx.log()` and its convenience methods are also logged to the server's log at `DEBUG` level. Enable debug logging on the `fastmcp.server.context.to_client` logger to see these messages:
diff --git a/docs/servers/middleware.mdx b/docs/servers/middleware.mdx
index 18d84120c..46ee4ebde 100644
--- a/docs/servers/middleware.mdx
+++ b/docs/servers/middleware.mdx
@@ -71,10 +71,12 @@ When using [mounted servers](/servers/composition), middleware behavior follows
```python
from fastmcp import FastMCP
+from fastmcp.server.auth import require_scopes
+from fastmcp.server.middleware import AuthMiddleware
from fastmcp.server.middleware.logging import LoggingMiddleware
parent = FastMCP("Parent")
-parent.add_middleware(AuthMiddleware()) # Runs for ALL requests
+parent.add_middleware(AuthMiddleware(auth=require_scopes("api"))) # Runs for ALL requests
child = FastMCP("Child")
child.add_middleware(LoggingMiddleware()) # Only runs for child's tools
@@ -84,7 +86,7 @@ parent.mount(child, namespace="child")
Requests to `child_tool` flow through the parent's `AuthMiddleware` first, then through the child's `LoggingMiddleware`.
-Middleware-stored state does not automatically cross mount boundaries. If `AuthMiddleware` on the parent calls `ctx.set_state("user_id", ...)`, a tool on the child server calling `ctx.get_state("user_id")` will get `None` — each `FastMCP` instance owns its own session state store. To share state across the mount, either pass the same `session_state_store` to both servers or use `serializable=False` for request-scoped values. See [Session State](/servers/sessions) for details.
+Middleware-stored state does not automatically cross mount boundaries. If middleware on the parent calls `ctx.set_state("user_id", ...)`, a tool on the child server calling `ctx.get_state("user_id")` will get `None` — each `FastMCP` instance owns its own state store. To share state across the mount, either pass the same `session_state_store` to both servers or use `serializable=False` for request-scoped values. See [Request State](/servers/context#request-state) for details.
## Hooks
@@ -278,7 +280,7 @@ async def on_list_prompts(self, context: MiddlewareContext, call_next):
<VersionBadge version="2.13.0" />
-Called when a client connects and initializes the session. Middleware can reject the client before `call_next()` raises an error response, or inspect and modify the `InitializeResult` after `call_next()` returns.
+Called when a handshake-era (legacy) client connects and initializes the session; modern clients negotiate through `server/discover` instead, which `on_discover` handles. Middleware can reject the client before `call_next()` raises an error response, or inspect and modify the `InitializeResult` after `call_next()` returns.
The request params carry the identity the client declared for itself on `client_info`, which makes this the natural place to gate access by client. Note that these fields are snake_case: the MCP wire format spells it `clientInfo`, but the Python model exposes `client_info` and treats the camelCase form as a serialization alias only.
@@ -472,6 +474,7 @@ from key_value.aio.stores.filetree import (
)
cache_dir = Path("cache")
+cache_dir.mkdir(parents=True, exist_ok=True)
mcp.add_middleware(ResponseCachingMiddleware(
cache_storage=FileTreeStore(
data_directory=cache_dir,
@@ -536,8 +539,14 @@ from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware, Re
```python
from fastmcp import FastMCP
+from fastmcp.server.middleware import MiddlewareContext
from fastmcp.server.middleware.error_handling import ErrorHandlingMiddleware
+
+def my_error_callback(error: Exception, context: MiddlewareContext) -> None:
+ print(f"{context.method} failed: {error!r}")
+
+
mcp = FastMCP("MyServer")
mcp.add_middleware(ErrorHandlingMiddleware(
include_traceback=True,
@@ -691,7 +700,7 @@ Raise the appropriate error type to stop processing and return an error to the c
from fastmcp.server.middleware import Middleware, MiddlewareContext
from fastmcp.exceptions import ToolError
-class AuthMiddleware(Middleware):
+class AdminToolGuard(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
tool_name = context.message.name
@@ -818,7 +827,7 @@ class PrivateToolFilter(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
if context.fastmcp_context:
tool = await context.fastmcp_context.fastmcp.get_tool(context.message.name)
- if "private" in tool.tags:
+ if tool is not None and "private" in tool.tags:
raise ToolError("Tool not found")
return await call_next(context)
@@ -826,24 +835,19 @@ class PrivateToolFilter(Middleware):
### Accessing Component Metadata
-During execution hooks, component metadata (like tags) isn't directly available. Look up the component through the server:
+During execution hooks, component metadata (like tags) isn't directly available. Look up the component through the server. The lookup returns `None` for a tool that doesn't exist or isn't visible to the caller, so leave that case to the normal call path:
```python
from fastmcp.server.middleware import Middleware, MiddlewareContext
-from fastmcp.exceptions import ToolError
class TagBasedAuth(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
if context.fastmcp_context:
- try:
- tool = await context.fastmcp_context.fastmcp.get_tool(context.message.name)
-
- if "requires-auth" in tool.tags:
- # Check authentication here
- pass
+ tool = await context.fastmcp_context.fastmcp.get_tool(context.message.name)
- except Exception:
- pass # Let execution handle missing tools
+ if tool is not None and "requires-auth" in tool.tags:
+ # Check authentication here
+ pass
return await call_next(context)
```
@@ -873,7 +877,7 @@ class UserMiddleware(Middleware):
# Store for tools to access
if context.fastmcp_context:
- context.fastmcp_context.set_state("user_id", user_id)
+ await context.fastmcp_context.set_state("user_id", user_id)
return await call_next(context)
```
@@ -886,8 +890,8 @@ from fastmcp import FastMCP, Context
mcp = FastMCP("MyServer")
@mcp.tool
-def get_user_data(ctx: Context) -> str:
- user_id = ctx.get_state("user_id")
+async def get_user_data(ctx: Context) -> str:
+ user_id = await ctx.get_state("user_id")
return f"Data for user: {user_id}"
```
diff --git a/docs/servers/progress.mdx b/docs/servers/progress.mdx
index 7dadb73a4..42faa8ad3 100644
--- a/docs/servers/progress.mdx
+++ b/docs/servers/progress.mdx
@@ -46,6 +46,6 @@ For multi-stage operations, map each stage to a portion of the total progress ra
## Client Requirements
-Progress reporting requires clients to support progress handling. Clients must send a `progressToken` in the initial request to receive progress updates. If no progress token is provided, progress calls have no effect (they don't error).
+Progress reporting requires clients to support progress handling. Clients must send a `progressToken` in the initial request to receive progress updates. If no progress token is provided, progress calls have no effect (they don't error). Inside a [background task](/servers/tasks#progress-reporting), `ctx.report_progress()` records progress on the task instead, where the client reads it with the task's status.
See [Client Progress](/clients/progress) for details on implementing client-side progress handling.
diff --git a/docs/servers/prompts.mdx b/docs/servers/prompts.mdx
index e12791ae9..e0c384cfb 100644
--- a/docs/servers/prompts.mdx
+++ b/docs/servers/prompts.mdx
@@ -64,6 +64,8 @@ Functions with `*args` or `**kwargs` are not supported as prompts. This restrict
While FastMCP infers the name and description from your function, you can override these and add additional metadata using arguments to the `@mcp.prompt` decorator:
```python
+from pydantic import Field
+
@mcp.prompt(
name="analyze_data_request", # Custom prompt name
description="Creates a request to analyze data with specific parameters", # Custom description
@@ -113,6 +115,10 @@ def data_analysis_prompt(
Optional version identifier for this prompt. See [Versioning](/servers/versioning) for details.
</ParamField>
+
+<ParamField body="auth" type="AuthCheck | list[AuthCheck] | None">
+ Authorization checks the caller must pass to see and render the prompt. See [Authorization](/servers/authorization) for details.
+</ParamField>
</Card>
#### Using with Methods
@@ -152,17 +158,17 @@ def analyze_data(
"arguments": [
{
"name": "numbers",
- "description": "Provide as a JSON string matching the following schema: {\"items\":{\"type\":\"integer\"},\"type\":\"array\"}",
+ "description": "Provide a value matching the following JSON schema: {\"items\":{\"type\":\"integer\"},\"type\":\"array\"}. Encode non-string values as JSON.",
"required": true
},
{
"name": "metadata",
- "description": "Provide as a JSON string matching the following schema: {\"additionalProperties\":{\"type\":\"string\"},\"type\":\"object\"}",
+ "description": "Provide a value matching the following JSON schema: {\"additionalProperties\":{\"type\":\"string\"},\"type\":\"object\"}. Encode non-string values as JSON.",
"required": true
},
{
"name": "threshold",
- "description": "Provide as a JSON string matching the following schema: {\"type\":\"number\"}",
+ "description": "Provide a value matching the following JSON schema: {\"type\":\"number\"}. Encode non-string values as JSON.",
"required": true
}
]
@@ -183,6 +189,7 @@ def analyze_data(
**But you can still call it directly with proper types:**
```python
# This also works for direct calls
+prompt = await mcp.get_prompt("analyze_data")
result = await prompt.render({
"numbers": [1, 2, 3, 4, 5],
"metadata": {"source": "api", "version": "1.0"},
@@ -399,6 +406,8 @@ See [Visibility](/servers/visibility) for the complete visibility control API in
FastMCP supports both standard (`def`) and asynchronous (`async def`) functions as prompts. Synchronous functions automatically run in a threadpool to avoid blocking the event loop.
```python
+import aiohttp
+
# Synchronous prompt (runs in threadpool)
@mcp.prompt
def simple_question(question: str) -> str:
@@ -444,7 +453,9 @@ For full documentation on the Context object and all its capabilities, see the [
FastMCP automatically sends `notifications/prompts/list_changed` notifications to connected clients when prompts are added, enabled, or disabled. This allows clients to stay up-to-date with the current prompt set without manually polling for changes.
```python
+from fastmcp.prompts import prompt
+
+@prompt
def example_prompt() -> str:
return "Hello!"
diff --git a/docs/servers/providers/custom.mdx b/docs/servers/providers/custom.mdx
index 1f0f4b702..5e8ae869f 100644
--- a/docs/servers/providers/custom.mdx
+++ b/docs/servers/providers/custom.mdx
@@ -39,7 +39,7 @@ A provider implements protected `_list_*` methods that return available componen
from collections.abc import Sequence
from fastmcp.server.providers import Provider
from fastmcp.tools import Tool
-from fastmcp.resources import Resource
+from fastmcp.resources import Resource, ResourceTemplate
from fastmcp.prompts import Prompt
class MyProvider(Provider):
@@ -51,6 +51,10 @@ class MyProvider(Provider):
"""Return all resources this provider offers."""
return []
+ async def _list_resource_templates(self) -> Sequence[ResourceTemplate]:
+ """Return all resource templates this provider offers."""
+ return []
+
async def _list_prompts(self) -> Sequence[Prompt]:
"""Return all prompts this provider offers."""
return []
@@ -58,7 +62,7 @@ class MyProvider(Provider):
You only need to implement the methods for component types you provide. The base class returns empty sequences by default.
-The `_get_*` methods (`_get_tool`, `_get_resource`, `_get_prompt`) have default implementations that search through the list results. Override them only if you can fetch individual components more efficiently than iterating the full list.
+The `_get_*` methods (`_get_tool`, `_get_resource`, `_get_resource_template`, `_get_prompt`) have default implementations that search through the list results and return the highest matching version. Override them only if you can fetch individual components more efficiently than iterating the full list.
## What Providers Return
@@ -90,23 +94,21 @@ Similar `from_function` methods exist for `Resource` and `Prompt`.
## Registering Providers
-Add providers when creating the server:
+Add providers when creating the server. These examples use `MyProvider` from above:
```python
-mcp = FastMCP(
- "MyServer",
- providers=[
- DatabaseProvider(db_url),
- ConfigProvider(config_path),
- ]
-)
+from fastmcp import FastMCP
+
+mcp = FastMCP("MyServer", providers=[MyProvider()])
```
Or add them after creation:
```python
+from fastmcp import FastMCP
+
mcp = FastMCP("MyServer")
-mcp.add_provider(DatabaseProvider(db_url))
+mcp.add_provider(MyProvider())
```
### Bundled Extensions
@@ -155,12 +157,15 @@ mcp = FastMCP("Calculator", providers=[
## Lifecycle Management
-Providers often need to set up connections when the server starts and clean them up when it stops. Override the `lifespan` method:
+Providers often need to set up connections when the server starts and clean them up when it stops. Override the `lifespan` method. In this sketch, `connect_database` and `_make_tool` stand in for your database driver and your row-to-`Tool` conversion:
```python
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator, Sequence
+from fastmcp.server.providers import Provider
+from fastmcp.tools import Tool
+
class DatabaseProvider(Provider):
def __init__(self, db_url: str):
super().__init__()
diff --git a/docs/servers/providers/filesystem.mdx b/docs/servers/providers/filesystem.mdx
index 4540fad61..943c5fcb0 100644
--- a/docs/servers/providers/filesystem.mdx
+++ b/docs/servers/providers/filesystem.mdx
@@ -81,7 +81,7 @@ def add(a: float, b: float) -> float:
return a + b
```
-The decorator supports all standard tool options: `name`, `title`, `description`, `icons`, `tags`, `output_schema`, `annotations`, and `meta`.
+The decorator supports the standard tool options: `name`, `title`, `description`, `icons`, `tags`, `output_schema`, `annotations`, `meta`, `version`, `timeout`, `auth`, `task`, and `run_in_thread`.
### @resource
@@ -107,7 +107,7 @@ def get_user_profile(user_id: str) -> str:
return f'{{"id": "{user_id}", "name": "User"}}'
```
-The decorator supports: `uri` (required), `name`, `title`, `description`, `icons`, `mime_type`, `tags`, `annotations`, and `meta`.
+The decorator supports: `uri` (required), `name`, `title`, `description`, `icons`, `mime_type`, `tags`, `annotations`, `meta`, `version`, `auth`, and `security`.
### @prompt
@@ -131,13 +131,13 @@ def explain(topic: str) -> str:
return f"Explain {topic} using clear examples and analogies."
```
-The decorator supports: `name`, `title`, `description`, `icons`, `tags`, and `meta`.
+The decorator supports: `name`, `title`, `description`, `icons`, `tags`, `meta`, `version`, and `auth`.
## Directory Structure
The directory structure is purely organizational. The provider recursively scans all `.py` files regardless of which subdirectory they're in. Subdirectories like `tools/`, `resources/`, and `prompts/` are optional conventions that help you organize code.
-```
+```text
components/
├── tools/
│ ├── greeting.py # @tool functions
@@ -150,7 +150,7 @@ components/
You can also put all components in a single file or organize by feature rather than type.
-```
+```text
components/
├── user_management.py # @tool, @resource, @prompt for users
├── billing.py # @tool, @resource for billing
@@ -166,7 +166,7 @@ The provider follows these rules when scanning:
| File extensions | Only `.py` files are scanned |
| `__init__.py` | Skipped (used for package structure, not components) |
| `__pycache__` | Skipped |
-| Private functions | Functions starting with `_` are ignored, even if decorated |
+| Private names | Module attributes starting with `_` are ignored, even if decorated |
| No decorators | Files without `@tool`, `@resource`, or `@prompt` are silently skipped |
| Multiple components | A single file can contain any number of decorated functions |
@@ -178,8 +178,11 @@ If your directory contains an `__init__.py` file, the provider imports files as
# components/__init__.py exists
# components/tools/greeting.py
+from fastmcp.tools import tool
+
from ..helpers import format_name # Relative imports work
+
@tool
def greet(name: str) -> str:
return f"Hello, {format_name(name)}!"
@@ -202,7 +205,7 @@ provider = FileSystemProvider(Path(__file__).parent / "components", reload=True)
With `reload=True`, the provider:
1. Re-discovers all Python files on each request
-2. Re-imports modules that have changed
+2. Re-imports every discovered module
3. Updates the component registry with any new, modified, or removed components
<Warning>
@@ -213,7 +216,7 @@ Reload mode adds overhead to every request. Use it only during development, not
When a file fails to import or construct its components (syntax error, missing dependency, unsupported tool signature, etc.), the provider logs a warning, skips that file, and continues scanning other files. Components from other files remain available at startup and during reloads.
-```
+```text
WARNING - Failed to load /path/to/broken.py: No module named 'missing_dep'
```
@@ -225,7 +228,7 @@ Inspect `provider.failed_files` for a snapshot of failures from the most recent
A complete example is available in the repository at `examples/filesystem-provider/`. The structure demonstrates the recommended organization.
-```
+```text
examples/filesystem-provider/
├── server.py # Server entry point
└── components/
diff --git a/docs/servers/providers/local.mdx b/docs/servers/providers/local.mdx
index e04f51598..bf953eaa8 100644
--- a/docs/servers/providers/local.mdx
+++ b/docs/servers/providers/local.mdx
@@ -37,7 +37,7 @@ def analyze(topic: str) -> str:
return f"Please analyze: {topic}"
```
-The `LocalProvider` is always queried first when clients request components, ensuring that your directly-defined components take precedence over those from mounted or proxied servers.
+Because the `LocalProvider` is registered first, your directly-defined components win ties against mounted or proxied components with the same identifier and version. A higher version from another provider still wins; see [Provider Order](/servers/providers/overview#provider-order).
## Component Registration
@@ -46,6 +46,11 @@ The `LocalProvider` is always queried first when clients request components, ens
The most common way to register components:
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("MyServer")
+
+
@mcp.tool
def my_tool(x: int) -> str:
return str(x)
@@ -64,12 +69,30 @@ def my_prompt(topic: str) -> str:
You can also add pre-built component objects:
```python
+from fastmcp import FastMCP
+from fastmcp.prompts import Prompt
+from fastmcp.resources import Resource
from fastmcp.tools import Tool
-# Create a tool object
-my_tool = Tool.from_function(some_function, name="custom_tool")
-# Add it to the server
+def add(a: int, b: int) -> int:
+ return a + b
+
+
+def read_info() -> str:
+ return "info"
+
+
+def discuss(topic: str) -> str:
+ return f"Discuss: {topic}"
+
+
+mcp = FastMCP("MyServer")
+
+my_tool = Tool.from_function(add, name="custom_tool")
+my_resource = Resource.from_function(read_info, uri="data://info")
+my_prompt = Prompt.from_function(discuss)
+
mcp.add_tool(my_tool)
mcp.add_resource(my_resource)
mcp.add_prompt(my_prompt)
@@ -77,7 +100,7 @@ mcp.add_prompt(my_prompt)
### Removing Components
-Remove components by name or URI:
+Remove components by name or URI. Each call removes every version unless you pass `version=`, and raises `KeyError` when nothing matches:
```python
mcp.local_provider.remove_tool("my_tool")
@@ -87,19 +110,21 @@ mcp.local_provider.remove_prompt("my_prompt")
## Duplicate Handling
-When you try to add a component that already exists, the behavior depends on the `on_duplicate` setting:
+When you try to add a component that already exists, the behavior depends on the `on_duplicate` setting. A `FastMCP` server defaults to `"warn"`; a standalone `LocalProvider` defaults to `"error"`.
| Mode | Behavior |
|------|----------|
-| `"error"` (default) | Raise `ValueError` |
-| `"warn"` | Log warning and replace |
+| `"warn"` | Log a warning and replace |
+| `"error"` | Raise `ValueError` |
| `"replace"` | Silently replace |
-| `"ignore"` | Keep existing component |
+| `"ignore"` | Keep the existing component |
Configure this when creating the server:
```python
-mcp = FastMCP("MyServer", on_duplicate="warn")
+from fastmcp import FastMCP
+
+mcp = FastMCP("MyServer", on_duplicate="error")
```
## Component Visibility
@@ -109,6 +134,11 @@ mcp = FastMCP("MyServer", on_duplicate="warn")
Components can be dynamically enabled or disabled at runtime. Disabled components don't appear in listings and can't be called.
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("MyServer")
+
+
@mcp.tool(tags={"admin"})
def delete_all() -> str:
"""Delete everything."""
diff --git a/docs/servers/providers/overview.mdx b/docs/servers/providers/overview.mdx
index 625eba50e..8b7a7e661 100644
--- a/docs/servers/providers/overview.mdx
+++ b/docs/servers/providers/overview.mdx
@@ -17,7 +17,7 @@ When a client connects to your server and asks "what tools do you have?", FastMC
You're already using providers. When you write `@mcp.tool`, you're adding a tool to your server's `LocalProvider` - the default provider that stores components you define directly in code. You just don't have to think about it for simple servers.
-Providers become important when your components come from multiple sources: another FastMCP server to include, a remote MCP server to proxy, or a database where tools are defined dynamically. Each source gets its own provider, and FastMCP queries them all seamlessly.
+Providers become important when your components come from multiple sources: another FastMCP server to include, a remote MCP server to proxy, or a database where tools are defined dynamically. Each source gets its own provider, and FastMCP queries them all.
## Why Providers?
diff --git a/docs/servers/providers/proxy.mdx b/docs/servers/providers/proxy.mdx
index d93433fe4..e4e2bba9b 100644
--- a/docs/servers/providers/proxy.mdx
+++ b/docs/servers/providers/proxy.mdx
@@ -133,6 +133,8 @@ async with Client(Path("backend_server.py")) as connected_client:
Shared sessions may cause context mixing in concurrent scenarios. Use only in single-threaded situations or with explicit synchronization.
</Warning>
+A reused session keeps the settings it connected with, so backend tool results are validated against their declared output schema instead of [relayed as-is](#tool-results-are-relayed-not-inspected). A connected `ProxyClient` is the exception: the proxy builds a fresh session from it for each request.
+
## HTTP Header Forwarding
Proxies forward eligible incoming HTTP headers, including `Authorization` and custom headers, to HTTP and SSE backends by default. Headers configured on the backend transport take precedence. Cookies and connection-specific headers are excluded.
@@ -336,29 +338,16 @@ Proxied components follow standard prefixing rules:
<VersionBadge version="2.10.5" />
-Components from a proxy server are "mirrored" - they reflect the remote server's state and cannot be modified directly.
-
-To modify a proxied component (like disabling it), create a local copy:
+Components from a proxy server are "mirrored": they reflect the remote server's state, and every call goes to the backend. To hide or rename a proxied component, apply [visibility](/servers/visibility) or [transforms](/servers/transforms/transforms) on the proxy or on the server that mounts it:
```python
from pathlib import Path
-from fastmcp import FastMCP
from fastmcp.server import create_proxy
proxy = create_proxy(Path("backend_server.py"))
-# Get mirrored tool
-mirrored_tool = await proxy.get_tool("useful_tool")
-
-# Create modifiable local copy
-local_tool = mirrored_tool.copy()
-
-# Add to your own server
-my_server = FastMCP("MyServer")
-my_server.add_tool(local_tool)
-
-# Now you can control enabled state
-my_server.disable(keys={local_tool.key})
+# Hide one backend tool from clients of this proxy
+proxy.disable(names={"useful_tool"})
```
## Performance Considerations
@@ -402,7 +391,7 @@ You can reuse a single backend session by providing a client factory that return
```python
from fastmcp.server.providers.proxy import FastMCPProxy, ProxyClient
-base_client = ProxyClient("http://backend:8000/mcp")
+base_client = ProxyClient("http://backend:8000/mcp", forward_incoming_headers=False)
shared_client = base_client.new()
proxy = FastMCPProxy(
@@ -411,7 +400,9 @@ proxy = FastMCPProxy(
)
```
-This eliminates the MCP initialization handshake on every call, which can dramatically reduce latency under load. The `Client` uses reference counting for its session lifecycle, so concurrent callers sharing the same instance is safe.
+This eliminates the MCP initialization handshake on every call, which can reduce latency under load. The `Client` uses reference counting for its session lifecycle, so concurrent callers can share the same instance.
+
+Forwarded headers are attached when a session connects, so a shared session carries the headers of whichever request opened it to every request that reuses it. Set `forward_incoming_headers=False` on a shared client, as above, and give it the backend credentials directly.
<Warning>
Only reuse sessions when you know the backend is stateless (e.g. stateless HTTP). For stateful backends (stdio processes, servers that track session state), use the default fresh-session behavior to avoid context mixing.
diff --git a/docs/servers/resources.mdx b/docs/servers/resources.mdx
index a03b137ec..74629fe2e 100644
--- a/docs/servers/resources.mdx
+++ b/docs/servers/resources.mdx
@@ -63,6 +63,7 @@ def get_config() -> str:
You can customize the resource's properties using arguments in the `@mcp.resource` decorator:
```python
+import json
from fastmcp import FastMCP
mcp = FastMCP(name="DataServer")
@@ -113,13 +114,16 @@ def get_application_status() -> str:
</ParamField>
<ParamField body="annotations" type="Annotations | dict | None">
- An optional `Annotations` object or dictionary to add additional metadata about the resource.
+ An optional `Annotations` object or dictionary that tells clients how to use the resource. See [Annotations](#annotations).
<Expandable title="Annotations attributes">
- <ParamField body="readOnlyHint" type="bool | None">
- If true, the resource is read-only and does not modify its environment.
+ <ParamField body="audience" type="list[Literal['user', 'assistant']] | None">
+ Who the content is intended for: the user, the assistant, or both.
+ </ParamField>
+ <ParamField body="priority" type="float | None">
+ How important the resource is, from `0.0` (optional) to `1.0` (effectively required).
</ParamField>
- <ParamField body="idempotentHint" type="bool | None">
- If true, reading the resource repeatedly will have no additional effect on its environment.
+ <ParamField body="lastModified" type="str | None">
+ When the resource was last modified, as an ISO 8601 timestamp.
</ParamField>
</Expandable>
</ParamField>
@@ -135,6 +139,16 @@ def get_application_status() -> str:
Optional version identifier for this resource. See [Versioning](/servers/versioning) for details.
</ParamField>
+
+<ParamField body="auth" type="AuthCheck | list[AuthCheck] | None">
+ Authorization checks the caller must pass to see and read the resource. See [Authorization](/servers/authorization) for details.
+</ParamField>
+
+<ParamField body="security" type="ResourceSecurity | None">
+ <VersionBadge version="4.0.0" />
+
+ Parameter screening for resource templates. Defaults to the server's `resource_security`; `None` turns screening off. See [Path Security](#path-security) for details.
+</ParamField>
</Card>
#### Using with Methods
@@ -250,7 +264,8 @@ See [Visibility](/servers/visibility) for the complete visibility control API in
Resources and resource templates can access additional MCP information and features through the `Context` object. To access it, add a parameter to your resource function with a type annotation of `Context`:
-```python {6, 14}
+```python {7, 15}
+import json
from fastmcp import FastMCP, Context
mcp = FastMCP(name="DataServer")
@@ -375,7 +390,9 @@ Use these when the content is static or sourced directly from a file/URL, bypass
FastMCP automatically sends `notifications/resources/list_changed` notifications to connected clients when resources or templates are added, enabled, or disabled. This allows clients to stay up-to-date with the current resource set without manually polling for changes.
```python
[email protected]("data://example")
+from fastmcp.resources import resource
+
+@resource("data://example")
def example_resource() -> str:
return "Hello!"
@@ -393,36 +410,40 @@ Clients can handle these notifications using a [message handler](/clients/notifi
<VersionBadge version="2.11.0" />
-FastMCP allows you to add specialized metadata to your resources through annotations. These annotations communicate how resources behave to client applications without consuming token context in LLM prompts.
-
-Annotations serve several purposes in client applications:
-- Indicating whether resources are read-only or may have side effects
-- Describing the safety profile of resources (idempotent vs. non-idempotent)
-- Helping clients optimize caching and access patterns
+Annotations tell client applications how to use a resource's content: who it is for, how much it matters, and how fresh it is. They travel with the resource listing, so clients can decide what to show or include in context without reading the resource first.
-You can add annotations to a resource using the `annotations` parameter in the `@mcp.resource` decorator:
+Pass annotations with the `annotations` parameter of `@mcp.resource`, as a dictionary or an `Annotations` object:
```python
+import json
+
+from fastmcp import FastMCP
+
+mcp = FastMCP(name="DataServer")
+
+
@mcp.resource(
"data://config",
annotations={
- "readOnlyHint": True,
- "idempotentHint": True
- }
+ "audience": ["assistant"],
+ "priority": 0.9,
+ "lastModified": "2025-01-12T15:00:58Z",
+ },
)
def get_config() -> str:
"""Get application configuration."""
return json.dumps({"version": "1.0", "debug": False})
```
-FastMCP supports these standard annotations:
+The MCP specification defines these resource annotations:
-| Annotation | Type | Default | Purpose |
-| :--------- | :--- | :------ | :------ |
-| `readOnlyHint` | boolean | true | Indicates if the resource only provides data without side effects |
-| `idempotentHint` | boolean | true | Indicates if repeated reads have the same effect as a single read |
+| Annotation | Type | Purpose |
+| :--------- | :--- | :------ |
+| `audience` | list of `"user"` / `"assistant"` | Who the content is intended for |
+| `priority` | number from 0 to 1 | How important the resource is; `1` means effectively required, `0` entirely optional |
+| `lastModified` | ISO 8601 string | When the resource was last modified |
-Remember that annotations help make better user experiences but should be treated as advisory hints. They help client applications present appropriate UI elements and optimize access patterns, but won't enforce behavior on their own. Always focus on making your annotations accurately represent what your resource actually does.
+Keys outside this list are dropped. Annotations are advisory: they help clients present and prioritize resources but enforce nothing on their own.
## Resource Templates
@@ -458,10 +479,7 @@ def get_weather(city: str) -> str:
# Template with multiple parameters and annotations
@mcp.resource(
"repos://{owner}/{repo}/info",
- annotations={
- "readOnlyHint": True,
- "idempotentHint": True
- }
+ annotations={"audience": ["assistant"], "priority": 0.5},
)
def get_repo_info(owner: str, repo: str) -> str:
"""Retrieves information about a GitHub repository."""
diff --git a/docs/servers/server.mdx b/docs/servers/server.mdx
index 7ec9ca4a4..4c02d36ef 100644
--- a/docs/servers/server.mdx
+++ b/docs/servers/server.mdx
@@ -22,6 +22,8 @@ mcp = FastMCP("MyServer")
Instructions help clients (and the LLMs behind them) understand what your server does and how to use it effectively.
```python
+from fastmcp import FastMCP
+
mcp = FastMCP(
"DataAnalysis",
instructions="Provides tools for analyzing numerical datasets. Start with get_summary() for an overview.",
@@ -35,6 +37,10 @@ FastMCP servers expose three types of components to clients, each serving a dist
**Tools** are functions that clients invoke to perform actions or access external systems.
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("Demo")
+
@mcp.tool
def multiply(a: float, b: float) -> float:
"""Multiplies two numbers together."""
@@ -44,6 +50,10 @@ def multiply(a: float, b: float) -> float:
**Resources** expose data that clients can read — passive data sources rather than invocable functions.
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("Demo")
+
@mcp.resource("data://config")
def get_config() -> dict:
return {"theme": "dark", "version": "1.0"}
@@ -52,6 +62,10 @@ def get_config() -> dict:
**Prompts** are reusable message templates that guide LLM interactions.
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("Demo")
+
@mcp.prompt
def analyze_data(data_points: list[float]) -> str:
formatted_data = ", ".join(str(point) for point in data_points)
@@ -84,8 +98,12 @@ FastMCP supports several transports:
- **SSE**: Legacy web transport (deprecated)
```python
-# Run with HTTP transport
-mcp.run(transport="http", host="127.0.0.1", port=9000)
+from fastmcp import FastMCP
+
+mcp = FastMCP("MyServer")
+
+if __name__ == "__main__":
+ mcp.run(transport="http", host="127.0.0.1", port=9000)
```
The server can also be run using the FastMCP CLI. For detailed information on transports and deployment, see [Running Your Server](/deployment/running-server).
@@ -93,7 +111,7 @@ The server can also be run using the FastMCP CLI. For detailed information on tr
## Configuration Reference
-The `FastMCP` constructor accepts parameters organized into four categories: identity, composition, behavior, and handlers.
+The `FastMCP` constructor accepts parameters organized into four categories: identity, composition, behavior, and storage.
### Identity
@@ -189,7 +207,7 @@ These parameters tune how the server processes requests and communicates with cl
</ParamField>
<ParamField body="tasks" type="bool | None" default="False">
- Enable background task support. When `True`, tools and resources can return `CreateTaskResult` to run work asynchronously while the client polls for results
+ Server-wide default for the `task` argument of `@mcp.tool`. When `True`, every tool that doesn't set `task` itself supports background execution. Requires the `fastmcp-tasks` package; see [Background Tasks](/servers/tasks)
</ParamField>
<ParamField body="client_log_level" type="LoggingLevel | None">
@@ -202,6 +220,14 @@ These parameters tune how the server processes requests and communicates with cl
Automatically dereference `$ref` pointers in JSON schemas generated from complex Pydantic models. Most clients require flat schemas without `$ref`, so this should usually stay enabled. Schemas whose inlined form would be very large keep their `$defs`, with only a root-level `$ref` resolved, as recursive schemas already do.
</ParamField>
+<ParamField body="resource_security" type="ResourceSecurity | None" default="DEFAULT_RESOURCE_SECURITY">
+ Server-wide path-security policy for templated resources, applied to every template that doesn't set its own `security`. The default rejects traversal, absolute paths, and null bytes in parameter values; `None` disables screening. See [Path Security](/servers/resources#path-security)
+</ParamField>
+
+<ParamField body="request_state_security" type="RequestStateSecurity | None" default="None">
+ Signing policy for the request state that multi-round-trip requests echo back to the server. When `None`, state is sealed under a per-process key, which works for a single process; deployments with several replicas must pass a policy with shared keys. See [Multi-replica deployments](/servers/elicitation#multi-replica-deployments)
+</ParamField>
+
<ParamField body="cache_ttl" type="int | None" default="None">
How long, in seconds, a client may treat this server's cacheable responses as fresh (SEP-2549). When set, the hint applies uniformly to `tools/list`, `prompts/list`, `resources/list`, `resources/templates/list`, and `resources/read`. Clients must opt into caching to honor it — see [Response caching](/clients/client#response-caching). Must be a positive integer
</ParamField>
@@ -248,6 +274,10 @@ The hint is inert on its own: a client only reuses a response if it opts into ca
Tags let you categorize components and selectively expose them. This is useful for creating different views of your server for different environments or user types.
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("MyServer")
+
@mcp.tool(tags={"public", "utility"})
def public_tool() -> str:
return "This tool is public"
@@ -267,6 +297,8 @@ To hide a component by default, disable it at the server level with `mcp.disable
</Tip>
```python
+from fastmcp import FastMCP
+
# Only expose components tagged with "public"
mcp = FastMCP()
mcp.enable(tags={"public"}, only=True)
diff --git a/docs/servers/sessions.mdx b/docs/servers/sessions.mdx
index 25f4e8e70..2c0d1cf54 100644
--- a/docs/servers/sessions.mdx
+++ b/docs/servers/sessions.mdx
@@ -94,6 +94,8 @@ Session state lives in the server's [storage backend](/servers/storage-backends)
from key_value.aio.stores.redis import RedisStore
from key_value.aio.wrappers.ttl_clamp import TTLClampWrapper
+from fastmcp import FastMCP
+
store = RedisStore(url="redis://localhost:6379")
store = TTLClampWrapper(store, min_ttl=0, max_ttl=86400, missing_ttl=3600)
diff --git a/docs/servers/skills.mdx b/docs/servers/skills.mdx
index e55fbf662..cf1969c58 100644
--- a/docs/servers/skills.mdx
+++ b/docs/servers/skills.mdx
@@ -142,7 +142,7 @@ You get metadata, not content. [`ClientGroup.list_skills()`](/clients/client-gro
### Read a whole skill
-`read_skill()` fetches every file in the skill's manifest, checks each one's size and SHA-256 digest, and returns a `Skill`. When the extension supplies an entry, the downloaded frontmatter must also match it. The existing 512-file and 16 MiB limits are checked before downloading file contents. It uses `skills/get` when the extension was negotiated, falling back to FastMCP's `_manifest` resource when the extension is unavailable or doesn't know the skill:
+`read_skill()` fetches every file in the skill's manifest, checks each one's size and SHA-256 digest, and returns a `Skill`. When the extension supplies an entry, the downloaded frontmatter must also match it. The 512-file and 16 MiB limits are checked before downloading file contents. It uses `skills/get` when the extension was negotiated, falling back to FastMCP's `_manifest` resource when the extension is unavailable or doesn't know the skill:
```python
from fastmcp import Client
diff --git a/docs/servers/storage-backends.mdx b/docs/servers/storage-backends.mdx
index ea8085d3a..f96793575 100644
--- a/docs/servers/storage-backends.mdx
+++ b/docs/servers/storage-backends.mdx
@@ -9,7 +9,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
<VersionBadge version="2.13.0" />
-FastMCP uses pluggable storage backends for caching responses and managing OAuth state. By default, all storage is in-memory, which is perfect for development but doesn't persist across restarts. FastMCP includes support for multiple storage backends, and you can easily extend it with custom implementations.
+FastMCP uses pluggable storage backends for caching responses, session state, and OAuth state. By default, all storage is in-memory, which is perfect for development but doesn't persist across restarts. FastMCP includes support for multiple storage backends, and you can easily extend it with custom implementations.
<Tip>
The storage layer is powered by **[py-key-value-aio](https://github.com/strawgate/py-key-value)**, an async key-value library maintained by a core FastMCP maintainer. This library provides a unified interface for multiple backends, making it easy to swap implementations based on your deployment needs.
@@ -41,7 +41,7 @@ cache_store = MemoryStore()
**Best for:** Single-server production deployments, persistent caching
-File storage persists data to the filesystem as one JSON file per key, allowing it to survive server restarts. This is the default backend for OAuth storage on Mac and Windows.
+File storage persists data to the filesystem as one JSON file per key, allowing it to survive server restarts. OAuth providers use an encrypted file store as their default storage on every platform.
```python
from pathlib import Path
@@ -53,6 +53,7 @@ from key_value.aio.stores.filetree import (
from fastmcp.server.middleware.caching import ResponseCachingMiddleware
storage_dir = Path("/var/cache/fastmcp")
+storage_dir.mkdir(parents=True, exist_ok=True)
store = FileTreeStore(
data_directory=storage_dir,
key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(storage_dir),
@@ -215,6 +216,7 @@ from key_value.aio.stores.filetree import (
mcp = FastMCP("My Server")
cache_dir = Path("cache")
+cache_dir.mkdir(parents=True, exist_ok=True)
cache_store = FileTreeStore(
data_directory=cache_dir,
key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(cache_dir),
@@ -241,6 +243,19 @@ namespaced_store = PrefixCollectionsWrapper(
middleware = ResponseCachingMiddleware(cache_storage=namespaced_store)
```
+### Session State
+
+[Session state](/servers/sessions) and the serializable values that `ctx.set_state()` writes live in the store you pass as `session_state_store`. It defaults to an in-memory store, so use a shared backend when several server instances must see the same sessions:
+
+```python
+from fastmcp import FastMCP
+from key_value.aio.stores.redis import RedisStore
+
+mcp = FastMCP("My Server", session_state_store=RedisStore(host="redis.example.com"))
+```
+
+FastMCP writes session state without a TTL of its own, so its retention is whatever the store applies; `ctx.set_state()` values carry a one-day TTL. See [Storage and lifetime](/servers/sessions#storage-and-lifetime) for setting a default expiry.
+
### Client-Side OAuth Token Storage
The [FastMCP Client](/clients/client) uses storage for persisting OAuth tokens locally. By default, tokens are stored in memory:
@@ -256,6 +271,7 @@ from key_value.aio.stores.filetree import (
# Store tokens on disk for persistence across restarts
token_dir = Path("~/.local/share/fastmcp/tokens").expanduser()
+token_dir.mkdir(parents=True, exist_ok=True)
token_storage = FileTreeStore(
data_directory=token_dir,
key_sanitization_strategy=FileTreeV1KeySanitizationStrategy(token_dir),
@@ -263,7 +279,7 @@ token_storage = FileTreeStore(
)
oauth_provider = OAuth(
- mcp_url="https://your-mcp-server.com/mcp/sse",
+ mcp_url="https://your-mcp-server.com/mcp",
token_storage=token_storage
)
```
diff --git a/docs/servers/tasks.mdx b/docs/servers/tasks.mdx
index 05ab20945..4c95cafd7 100644
--- a/docs/servers/tasks.mdx
+++ b/docs/servers/tasks.mdx
@@ -141,10 +141,14 @@ Shorter intervals give clients faster feedback but increase server load. The int
### Server-Wide Default
-To enable background task support for all tools by default, pass `tasks=True` to the constructor. Individual decorators can still override this with `task=False`.
+To enable background task support for all tools by default, pass `tasks=True` to the constructor. Individual decorators can still override this with `task=False`. The server still needs the tasks extension registered.
```python
+from fastmcp import FastMCP
+from fastmcp_tasks import TasksExtension
+
mcp = FastMCP("MyServer", tasks=True)
+mcp.add_extension(TasksExtension())
```
<Warning>
@@ -261,7 +265,7 @@ The key protects the snapshot only. Tool arguments and any answers a task gather
## Workers
-Every FastMCP server with task-enabled tools automatically starts an **embedded worker**. You do not need to start a separate worker process for tasks to execute.
+A server with the tasks extension registered and at least one task-enabled tool automatically starts an **embedded worker**. You do not need to start a separate worker process for tasks to execute.
To scale horizontally, add more workers:
@@ -374,19 +378,24 @@ from fastmcp_tasks.dependencies import CurrentDocket, CurrentWorker
mcp = FastMCP("MyServer")
mcp.add_extension(TasksExtension())
+
+async def send_report(user_id: str) -> None:
+ ...
+
+
@mcp.tool(task=True)
async def my_task(
+ user_id: str,
progress: Progress = Progress(),
docket: Docket = CurrentDocket(),
worker: Worker = CurrentWorker(),
) -> str:
# Schedule additional background work
- await docket.add(another_task, arg1, arg2)
+ await docket.add(send_report)(user_id)
- # Access worker metadata
- worker_name = worker.name
-
- return "Done"
+ return f"Report scheduled by {worker.name}"
```
+`docket.add()` takes the function and returns a scheduler; call that with the function's arguments to enqueue it.
+
With `CurrentDocket()`, you can schedule additional background tasks, chain work together, and coordinate complex workflows. See the [Docket documentation](https://docket.lol/) for the complete API, including retry policies, timeouts, and custom dependencies.
diff --git a/docs/servers/telemetry.mdx b/docs/servers/telemetry.mdx
index bd5d9e544..6b0c238dc 100644
--- a/docs/servers/telemetry.mdx
+++ b/docs/servers/telemetry.mdx
@@ -132,6 +132,9 @@ The server creates spans for each operation using [MCP semantic conventions](htt
| `resources/read` | Resource read (URI in `mcp.resource.uri` attribute, not span name) |
| `prompts/get {name}` | Prompt render (e.g., `prompts/get greeting`) |
| `tasks/{operation}` | Task management (`tasks/get`, `tasks/update`, or `tasks/cancel`) |
+| `tools/list`, `resources/list`, `resources/templates/list`, `prompts/list` | Component listing |
+
+Any other request, such as `initialize` or `ping`, gets a server span named after its method.
For mounted servers, an additional `delegate {name}` span shows the delegation to the child server.
@@ -143,7 +146,7 @@ The FastMCP client creates spans for outgoing requests with the same naming patt
Spans form a hierarchy showing the request flow. For mounted servers:
-```
+```text
tools/call weather_forecast (CLIENT)
└── tools/call weather_forecast (SERVER, provider=FastMCPProvider)
└── delegate get_weather (INTERNAL)
@@ -154,7 +157,7 @@ Each request has exactly one `SERVER` span. The mounted server's span is `INTERN
For proxy providers connecting to remote servers:
-```
+```text
tools/call remote_search (CLIENT)
└── tools/call remote_search (SERVER, provider=ProxyProvider)
└── [remote server spans via trace context propagation]
@@ -241,33 +244,29 @@ The context manager has no effect when `telemetry_mode` is already `off`. A requ
## Programmatic Configuration
-For more control, configure the SDK in your Python code before importing FastMCP:
+For more control, configure the SDK in your Python code:
```python
from opentelemetry import trace
+from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
-from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
-# Configure the SDK with OTLP exporter
+from fastmcp import FastMCP
+
provider = TracerProvider()
processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4317"))
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
-# Now import and use FastMCP - traces will be exported automatically
-from fastmcp import FastMCP
-
mcp = FastMCP("my-server")
def greet(name: str) -> str:
return f"Hello, {name}!"
```
-<Tip>
-The SDK must be configured **before** importing FastMCP to ensure the tracer provider is set when FastMCP initializes.
-</Tip>
+FastMCP looks up the global tracer provider each time it creates a span, so import order does not matter. Set the provider at startup, before the server handles requests; spans created earlier are not exported.
### Local Development
@@ -275,7 +274,8 @@ For quick local trace visualization, [otel-desktop-viewer](https://github.com/Ct
```bash
# macOS
-brew install nico-barbas/brew/otel-desktop-viewer
+brew tap ctrlspice/otel-desktop-viewer
+brew install --cask otel-desktop-viewer
# Or download from GitHub releases
```
@@ -311,7 +311,16 @@ from fastmcp.telemetry import get_tracer
mcp = FastMCP("custom-spans")
+
+def parse(text: str) -> list[str]:
+ return text.split()
+
+
+def process(words: list[str]) -> str:
+ return " ".join(sorted(words))
+
+
async def complex_operation(input: str) -> str:
tracer = get_tracer()
@@ -352,6 +361,23 @@ from fastmcp.telemetry import get_tracer
mcp = FastMCP("my-server")
+
+async def fetch_results(query: str) -> list[str]:
+ return [f"{query} result {i}" for i in range(3)]
+
+
+def rank_results(results: list[str]) -> list[str]:
+ return sorted(results)
+
+
+def format_results(results: list[str]) -> str:
+ return "\n".join(results)
+
+
+async def load_doc(slug: str) -> str:
+ return f"# {slug}"
+
+
@mcp.tool
async def search(query: str) -> str:
tracer = get_tracer()
@@ -395,19 +421,20 @@ For providers with their own OTEL integrations, prefer enabling that instrumenta
## Error Handling
-When errors occur, spans are automatically marked with error status and the exception is recorded:
+When a component raises, FastMCP marks its span with error status and records the exception:
```python
+from fastmcp import FastMCP
+
+mcp = FastMCP("my-server")
+
def risky_operation() -> str:
raise ValueError("Something went wrong")
-
-# The span will have:
-# - status = ERROR with exception message as description
-# - error.type = "tool_error" (or exception class name for non-tool errors)
-# - exception event with stack trace
```
+The `tools/call risky_operation` server span gets status `ERROR` with the error message as its description, an exception event carrying the stack trace, and an `error.type` attribute. FastMCP wraps exceptions raised by a tool in a `ToolError`, so tool failures report `error.type` as `tool_error`; other failures report the exception class name.
+
## Attributes Reference
<Warning>
@@ -454,16 +481,19 @@ Provider-specific attributes for delegation context:
|-----------|-------------|
| `fastmcp.delegate.original_name` | Original tool/prompt name before namespacing |
| `fastmcp.delegate.original_uri` | Original resource URI before namespacing |
+| `fastmcp.delegate.original_uri_template` | Original resource template URI before namespacing |
| `fastmcp.proxy.backend_name` | Remote server tool/prompt name |
| `fastmcp.proxy.backend_uri` | Remote server resource URI |
+| `fastmcp.proxy.backend_uri_template` | Remote server resource template URI |
## Testing with Telemetry
-For testing, use the in-memory exporter:
+For testing, use the in-memory exporter. OpenTelemetry allows the global tracer provider to be set only once per process, so install it in a session-scoped fixture and clear the exporter between tests:
```python
-import pytest
from collections.abc import Generator
+
+import pytest
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
@@ -471,21 +501,29 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanE
from fastmcp import FastMCP
-def trace_exporter() -> Generator[InMemorySpanExporter, None, None]:
+
[email protected](scope="session")
+def span_exporter() -> InMemorySpanExporter:
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
- original_provider = trace.get_tracer_provider()
trace.set_tracer_provider(provider)
- yield exporter
- exporter.clear()
- trace.set_tracer_provider(original_provider)
+ return exporter
+
+
+def trace_exporter(
+ span_exporter: InMemorySpanExporter,
+) -> Generator[InMemorySpanExporter, None, None]:
+ span_exporter.clear()
+ yield span_exporter
+ span_exporter.clear()
+
async def test_tool_creates_span(trace_exporter: InMemorySpanExporter) -> None:
mcp = FastMCP("test")
- @mcp.tool()
+ @mcp.tool
def hello() -> str:
return "world"
diff --git a/docs/servers/testing.mdx b/docs/servers/testing.mdx
index 7bd8600c5..a6914708b 100644
--- a/docs/servers/testing.mdx
+++ b/docs/servers/testing.mdx
@@ -51,6 +51,10 @@ We recommend the [inline-snapshot library](https://github.com/15r10nk/inline-sna
```python
from inline_snapshot import snapshot
+from fastmcp.client import Client
+from fastmcp.client.transports import FastMCPTransport
+
+
async def test_list_tools(main_mcp_client: Client[FastMCPTransport]):
list_tools = await main_mcp_client.list_tools()
@@ -71,6 +75,8 @@ from my_project.main import mcp
from fastmcp.client import Client
from fastmcp.client.transports import FastMCPTransport
+
+
@pytest.fixture
async def main_mcp_client():
async with Client(mcp) as client:
diff --git a/docs/servers/tool-fingerprinting.mdx b/docs/servers/tool-fingerprinting.mdx
index b8c06c04e..42b7e4915 100644
--- a/docs/servers/tool-fingerprinting.mdx
+++ b/docs/servers/tool-fingerprinting.mdx
@@ -60,7 +60,7 @@ The fingerprint is stable across process restarts as long as the tool's name, ve
`tool.key` is FastMCP's canonical component identity. It encodes the component type, identifier, and version into a single string:
-```
+```text
tool:[email protected] # versioned tool
tool:greet@ # unversioned tool
```
@@ -76,6 +76,12 @@ Using `key` rather than just the tool name ensures that two versions of the same
You own the inclusion policy. Add or remove fields depending on what constitutes a "contract" in your system:
```python
+import hashlib
+import json
+
+from fastmcp import FastMCP
+
+
async def custom_fingerprint(server: FastMCP, tool_name: str) -> str:
tool = await server.get_tool(tool_name)
if tool is None:
@@ -110,8 +116,8 @@ Common variations:
Store fingerprints as artifacts and compare between deployments:
```python
-import json
import hashlib
+import json
from pathlib import Path
from fastmcp import FastMCP
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 7eabee22d..e29f37742 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -136,6 +136,18 @@ def search_products_implementation(query: str, category: str | None = None) -> l
<ParamField body="run_in_thread" type="bool" default="True">
Applies to sync tool functions only. When `True` (default), sync functions are dispatched to a thread pool so they don't block the event loop. Set to `False` to run the function inline on the event loop thread — useful for libraries with thread affinity like Windows COM (`pywin32`, `uiautomation`, `comtypes`), `tkinter`, or certain GPU/driver bindings. Ignored for async functions, which always run on the event loop. See [Thread affinity](#thread-affinity) for details.
</ParamField>
+
+<ParamField body="task" type="bool | TaskConfig | None">
+ Marks the tool as able to run as a background task. Requires an async function and the tasks extension. See [Background Tasks](/servers/tasks) for details.
+</ParamField>
+
+<ParamField body="auth" type="AuthCheck | list[AuthCheck] | None">
+ Authorization checks the caller must pass to see and call the tool. See [Authorization](/servers/authorization) for details.
+</ParamField>
+
+<ParamField body="app" type="AppConfig | dict | bool | None">
+ Renders the tool's result as an interactive UI in clients that support MCP Apps. See [Apps](/apps/overview) for details.
+</ParamField>
</Card>
### Using with Methods
@@ -279,7 +291,7 @@ In this example, the LLM must provide a `query` parameter, while `max_results`,
By default, FastMCP uses Pydantic's flexible validation that coerces compatible inputs to match your type annotations. This improves compatibility with LLM clients that may send string representations of values (like `"10"` for an integer parameter).
-If you need stricter validation that rejects any type mismatches, you can enable strict input validation. Strict mode uses the MCP SDK's built-in JSON Schema validation to validate inputs against the exact schema before passing them to your function:
+If you need stricter validation that rejects any type mismatches, you can enable strict input validation. Strict mode validates arguments with Pydantic's strict mode, which rejects coercions such as the string `"10"` for an `int` while still accepting the JSON forms your input schema describes (ISO date strings, enum values, UUID strings):
```python
# Enable strict validation for this server
@@ -374,7 +386,7 @@ This shorthand syntax is only applied to `Annotated` types with a single string
For validation constraints and advanced metadata, use Pydantic's `Field` class with `Annotated`:
```python
-from typing import Annotated
+from typing import Annotated, Literal
from pydantic import Field
@mcp.tool
@@ -395,6 +407,8 @@ def process_image(
You can also use the Field as a default value, though the Annotated approach is preferred:
```python
+from pydantic import Field
+
@mcp.tool
def search_database(
query: str = Field(description="Search query string"),
@@ -506,7 +520,7 @@ Each helper class accepts either `path=` or `data=` (mutually exclusive):
<VersionBadge version="2.10.0" />
-The 6/18/2025 MCP spec update [introduced](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content) structured content, which is a new way to return data from tools. Structured content is a JSON object that is sent alongside traditional content. FastMCP automatically creates structured outputs alongside traditional content when your tool returns data that has a JSON object representation. This provides machine-readable JSON data that clients can deserialize back to Python objects.
+The 6/18/2025 MCP spec update [introduced](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#structured-content) structured content: a JSON object sent alongside traditional content. FastMCP automatically creates structured outputs alongside traditional content when your tool returns data that has a JSON object representation. This provides machine-readable JSON data that clients can deserialize back to Python objects.
**Automatic Structured Content Rules:**
- **Object-like results** (`dict`, Pydantic models, dataclasses) → Always become structured content (even without output schema)
@@ -737,11 +751,13 @@ def advanced_tool() -> ToolResult:
)
```
-`ToolResult` accepts three fields:
+`ToolResult` accepts four fields:
**`content`** - The traditional MCP content blocks that clients display to users. Can be a string (automatically converted to `TextContent`), a list of MCP content blocks, or any serializable value (converted to JSON string). At least one of `content` or `structured_content` must be provided.
```python
+from mcp.types import ImageContent, TextContent
+
# Simple string
ToolResult(content="Hello, world!")
@@ -777,6 +793,12 @@ ToolResult(
)
```
+**`is_error`** - Marks the result as a tool execution error. Defaults to `False`. When `True`, the client receives the content as an error result (`isError: true`) instead of a success, without your tool raising an exception.
+
+```python
+ToolResult(content="Upstream service unavailable", is_error=True)
+```
+
<Note>
The `meta` field in `ToolResult` is for runtime metadata about tool execution (e.g., execution time, performance metrics). This is separate from the `meta` parameter in `@mcp.tool(meta={...})`, which provides static metadata about the tool definition itself.
</Note>
@@ -900,7 +922,7 @@ async def long_running_task(
See the [Docket documentation](https://docket.lol/en/latest/task-behaviors/#task-timeouts) for more on task timeouts and retries.
</Warning>
-When a tool times out, FastMCP logs a warning suggesting task mode. For operations you know will be long-running, use `task=True` instead—background tasks offload work to distributed workers and let clients poll for progress.
+When a tool times out, FastMCP logs a warning suggesting task mode. For operations you know will be long-running, use `task=True` instead—[background tasks](/servers/tasks) offload work to distributed workers and let clients poll for progress.
## Component Visibility
@@ -1034,7 +1056,6 @@ Client-specific behavior:
FastMCP automatically sends `notifications/tools/list_changed` notifications to connected clients when tools are added, removed, enabled, or disabled. This allows clients to stay up-to-date with the current tool set without manually polling for changes.
```python
def example_tool() -> str:
return "Hello!"
diff --git a/docs/servers/transforms/code-mode.mdx b/docs/servers/transforms/code-mode.mdx
index 74f6e833e..117f7929b 100644
--- a/docs/servers/transforms/code-mode.mdx
+++ b/docs/servers/transforms/code-mode.mdx
@@ -60,7 +60,7 @@ First, the LLM uses the `search` meta-tool to find tools by keyword.
For example, it might do `search(query="math numbers")` and receive the following response:
-```
+```text
- add: Add two numbers.
- multiply: Multiply two numbers.
```
@@ -73,7 +73,7 @@ Next, the LLM calls `get_schema` to get parameter details for the tools it found
For example, it might do `get_schema(tools=["add", "multiply"])` and receive the following response:
-```
+```text
### add
Add two numbers.
@@ -82,6 +82,9 @@ Add two numbers.
- `x` (integer, required)
- `y` (integer, required)
+**Returns**
+- `result` (integer, required)
+
### multiply
Multiply two numbers.
@@ -89,6 +92,9 @@ Multiply two numbers.
**Parameters**
- `x` (integer, required)
- `y` (integer, required)
+
+**Returns**
+- `result` (integer, required)
```
Now the LLM knows the parameters for the tools it found, and can write code that chains the tool calls. If it needed more detail, it could have called `get_schema` with `detail="full"` to get the complete JSON schema.
@@ -101,11 +107,11 @@ For example, it might write the following code and call the `execute` tool with
```python
a = await call_tool("add", {"x": 3, "y": 4})
-b = await call_tool("multiply", {"x": a, "y": 2})
-return b
+b = await call_tool("multiply", {"x": a["result"], "y": 2})
+return b["result"]
```
-The result is returned to the LLM.
+`call_tool` returns the tool's structured content when the tool has an output schema, and its text otherwise. A tool that returns a bare value such as an `int` has its output wrapped as `{"result": ...}`, which is why the code reads `a["result"]`; the Returns section from `get_schema` shows that shape. The value of the block's `return` is returned to the LLM.
</Step>
</Steps>
@@ -131,7 +137,7 @@ CodeMode ships with four built-in discovery tools: `Search`, `GetSchemas`, `GetT
`Search` finds tools by natural-language query using BM25 ranking. At its default `"brief"` detail, results include just tool names and descriptions — enough to decide which tools are worth inspecting further. The LLM can request `"detailed"` to get parameter schemas inline, or `"full"` for the complete JSON.
-Search results include an annotation like `"2 of 10 tools:"` when the result set is smaller than the full catalog, so the LLM knows there are more tools to discover with different queries.
+Search results include an annotation like `"2 of 10 tools:"` when the result set is smaller than the full catalog, so the LLM knows there are more tools to discover with different queries. Results at `"full"` detail are plain JSON and omit it.
By default, `Search` returns all matching tools (`default_limit=None`). You can cap the result count with `default_limit` to keep large catalogs focused. The LLM can override this limit per call, including requesting more results or passing `limit=None` to return all matches:
@@ -139,17 +145,27 @@ By default, `Search` returns all matching tools (`default_limit=None`). You can
Search(default_limit=5) # return at most 5 results per search
```
-If your tools use [tags](/servers/visibility#tags), Search also accepts a `tags` parameter so the LLM can narrow results to specific categories before searching.
+If your tools use [tags](/servers/visibility#tags), Search also accepts a `tags` parameter so the LLM can narrow results to specific categories before searching. The tag `"untagged"` matches tools with no tags.
+
+To replace BM25 ranking, pass `search_fn`, an async callable that takes the candidate tools and the query string and returns the matching tools in ranked order.
### GetSchemas
`GetSchemas` returns parameter details for specific tools by name. At its default `"detailed"` level, it renders compact markdown with parameter names, types, literal values, defaults, and required markers. Object-valued parameters and return values also list their own field names one level down, following `$ref`s into `$defs`, so a tool returning `list[Card]` renders as ``- `items` (object[]): `id`, `url`, `title`, …`` rather than an opaque `object[]`. At `"full"`, it returns the complete JSON schema — useful when tools have deeply nested parameters that the compact format doesn't capture.
+For example, a parameter declared as `sort: Literal["top", "recent"] = "recent"` appears as:
+
+```text
+- `sort` (string, one of "top"/"recent", default "recent")
+```
+
+Single-value literals also show their allowed value. Literal value lists are included up to eight values; parameter descriptions and complete constraints remain available at `"full"` detail.
+
### GetTags
-`GetTags` lets the LLM browse tools by category using [tag](/servers/visibility#tags) metadata. At brief detail, the LLM sees tag names with counts. At full detail, it sees tools listed under each tag:
+`GetTags` lets the LLM browse tools by category using [tag](/servers/visibility#tags) metadata. It supports only `"brief"` and `"full"` detail. At brief detail, the LLM sees tag names with counts; at full detail, it sees tools listed under each tag. Tools without tags are grouped under `untagged`:
-```
+```text
- math (3 tools)
- text (2 tools)
- untagged (1 tool)
@@ -157,14 +173,6 @@ If your tools use [tags](/servers/visibility#tags), Search also accepts a `tags`
`GetTags` isn't included in the defaults — add it when browsing by category would help the LLM orient itself in a large catalog. The LLM can browse tags first, then pass specific tags into Search to narrow results.
-For example, a parameter declared as `sort: Literal["top", "recent"] = "recent"` appears as:
-
-```text
-- `sort` (string, one of "top"/"recent", default "recent")
-```
-
-Single-value literals also show their allowed value. Literal value lists are included up to eight values; parameter descriptions and complete constraints remain available at `"full"` detail.
-
### ListTools
`ListTools` dumps the entire catalog at whatever detail level the LLM requests. It supports the same three detail levels as `Search` and `GetSchemas`, defaulting to `"brief"`.
@@ -275,7 +283,8 @@ The LLM sees the docstring of each discovery tool's inner function as its descri
Discovery tools and the execute tool can also have custom names:
```python
-from fastmcp.experimental.transforms.code_mode import Search, GetSchemas
+from fastmcp import FastMCP
+from fastmcp.experimental.transforms.code_mode import CodeMode, GetSchemas, Search
code_mode = CodeMode(
discovery_tools=[
@@ -346,14 +355,14 @@ CodeMode(max_tool_calls=None) # no cap
### Custom Sandbox Providers
-You can replace the default sandbox with any object implementing the `SandboxProvider` protocol:
+You can replace the default sandbox with any object implementing the `SandboxProvider` protocol. The `code` it receives is untrusted, LLM-generated Python: run it in an isolated sandbox, never with plain `exec()`.
```python
from collections.abc import Callable
from typing import Any
+from fastmcp import FastMCP
from fastmcp.experimental.transforms.code_mode import CodeMode
-from fastmcp.experimental.transforms.code_mode import SandboxProvider
class RemoteSandboxProvider:
async def run(
diff --git a/docs/servers/transforms/prompts-as-tools.mdx b/docs/servers/transforms/prompts-as-tools.mdx
index 4960ecbe0..07ed0e7f5 100644
--- a/docs/servers/transforms/prompts-as-tools.mdx
+++ b/docs/servers/transforms/prompts-as-tools.mdx
@@ -46,15 +46,21 @@ def explain_concept(concept: str) -> str:
mcp.add_transform(PromptsAsTools(mcp))
```
-Clients now see three items: whatever tools you defined directly, plus `list_prompts` and `get_prompt`.
+Clients now see the tools you defined directly, plus `list_prompts` and `get_prompt`.
## Listing Prompts
-The `list_prompts` tool returns JSON with metadata for each prompt, including its arguments.
+The `list_prompts` tool returns JSON with metadata for each prompt, including its arguments. When a prompt has several versions, only the highest version is listed.
```python
-result = await client.call_tool("list_prompts", {})
-prompts = json.loads(result.data)
+import json
+
+from fastmcp import Client
+
+async with Client(mcp) as client:
+ result = await client.call_tool("list_prompts", {})
+ prompts = json.loads(result.data)
+
# [
# {
# "name": "analyze_code",
@@ -71,7 +77,7 @@ prompts = json.loads(result.data)
# {"name": "concept", "description": null, "required": true}
# ]
# }
-#]
+# ]
```
Each argument includes:
@@ -84,19 +90,20 @@ Each argument includes:
The `get_prompt` tool accepts a prompt name and optional arguments dict. It returns the rendered prompt as JSON with a messages array.
```python
-# Prompt with required and optional arguments
-result = await client.call_tool(
- "get_prompt",
- {
- "name": "analyze_code",
- "arguments": {
- "code": "x = 1\nprint(x)",
- "language": "python"
- }
- }
-)
-
-response = json.loads(result.data)
+import json
+
+from fastmcp import Client
+
+async with Client(mcp) as client:
+ result = await client.call_tool(
+ "get_prompt",
+ {
+ "name": "analyze_code",
+ "arguments": {"code": "x = 1\nprint(x)", "language": "python"},
+ },
+ )
+ response = json.loads(result.data)
+
# {
# "messages": [
# {
@@ -110,20 +117,14 @@ response = json.loads(result.data)
If a prompt has no arguments, you can omit the `arguments` field or pass an empty dict:
```python
-result = await client.call_tool(
- "get_prompt",
- {"name": "simple_prompt"}
-)
+from fastmcp import Client
+
+async with Client(mcp) as client:
+ result = await client.call_tool("get_prompt", {"name": "simple_prompt"})
```
## Message Format
-Rendered prompts return a messages array following the standard MCP format. Each message includes:
-- `role`: The message role ("user" or "assistant")
-- `content`: The message text content
-
-Multi-message prompts are supported - the array will contain all messages in order.
-
-## Binary Content
-
-Unlike resources, prompts always return text content. There is no binary encoding needed.
+Rendered prompts return a messages array in prompt order. Each message includes:
+- `role`: The message role (`"user"` or `"assistant"`)
+- `content`: The message text as a string, or, for non-text content such as images or embedded resources, the MCP content object serialized as JSON
diff --git a/docs/servers/transforms/resources-as-tools.mdx b/docs/servers/transforms/resources-as-tools.mdx
index 7b4f9834d..c96267f10 100644
--- a/docs/servers/transforms/resources-as-tools.mdx
+++ b/docs/servers/transforms/resources-as-tools.mdx
@@ -46,7 +46,7 @@ def user_profile(user_id: str) -> str:
mcp.add_transform(ResourcesAsTools(mcp))
```
-Clients now see three tools: whatever tools you defined directly, plus `list_resources` and `read_resource`.
+Clients now see `list_resources` and `read_resource` alongside any tools you defined directly.
Both generated tools are annotated with `readOnlyHint=True`, since they only read data. Clients that respect tool annotations (like Cursor) can use this to auto-confirm these tool calls without prompting the user.
@@ -83,28 +83,36 @@ The client can distinguish resource types by checking which field is present: `u
The `read_resource` tool accepts a single `uri` argument. For static resources, pass the exact URI. For templates, fill in the placeholders with actual values.
```python
-# Reading a static resource
-result = await client.call_tool("read_resource", {"uri": "config://app"})
-print(result.data) # '{"app_name": "My App", "version": "1.0.0"}'
+from fastmcp import Client
-# Reading a templated resource - fill in {user_id} with an actual ID
-result = await client.call_tool("read_resource", {"uri": "user://42/profile"})
-print(result.data) # '{"user_id": "42", "name": "User 42"}'
+async with Client(mcp) as client:
+ # Reading a static resource
+ result = await client.call_tool("read_resource", {"uri": "config://app"})
+ print(result.data) # '{"app_name": "My App", "version": "1.0.0"}'
+
+ # Reading a templated resource - fill in {user_id} with an actual ID
+ result = await client.call_tool("read_resource", {"uri": "user://42/profile"})
+ print(result.data) # '{"user_id": "42", "name": "User 42"}'
```
The transform handles template matching automatically. When you request `user://42/profile`, it matches against the `user://{user_id}/profile` template, extracts `user_id=42`, and calls your resource function with that parameter.
## Binary Content
-Resources that return binary data (like images or files) are automatically base64-encoded when read through the `read_resource` tool. This ensures binary content can be transmitted as a string in the tool response.
+Resources that return binary data (like images or files) are automatically base64-encoded when read through the `read_resource` tool. This ensures binary content can be transmitted as a string in the tool response. A resource that returns several content items comes back as a JSON array of objects with `content` and `mime_type` fields.
```python
+import base64
+
+from fastmcp import Client
+
@mcp.resource("data://binary", mime_type="application/octet-stream")
def binary_data() -> bytes:
return b"\x00\x01\x02\x03"
-# Client receives base64-encoded string
-result = await client.call_tool("read_resource", {"uri": "data://binary"})
-decoded = base64.b64decode(result.data) # b'\x00\x01\x02\x03'
+async with Client(mcp) as client:
+ # Client receives base64-encoded string
+ result = await client.call_tool("read_resource", {"uri": "data://binary"})
+ decoded = base64.b64decode(result.data) # b'\x00\x01\x02\x03'
```
diff --git a/docs/servers/transforms/tool-search.mdx b/docs/servers/transforms/tool-search.mdx
index 5a28fdc12..0bb41b389 100644
--- a/docs/servers/transforms/tool-search.mdx
+++ b/docs/servers/transforms/tool-search.mdx
@@ -20,9 +20,9 @@ When you add a search transform, `list_tools()` returns just two synthetic tools
The original tools are still callable. They're hidden from the listing but remain fully functional — the search transform controls *discovery*, not *access*.
-Both synthetic tools search across tool names, descriptions, parameter names, and parameter descriptions. A search for `"email"` would match a tool named `send_email`, a tool with "email" in its description, or a tool with an `email_address` parameter.
+`search_tools` searches across tool names, descriptions, parameter names, and parameter descriptions. A search for `"email"` would match a tool named `send_email`, a tool with "email" in its description, or a tool with an `email_address` parameter.
-Search results are returned in the same JSON format as `list_tools`, including the full input schema, so the LLM can construct valid calls immediately without a second round-trip.
+By default, search results are returned in the same JSON format as `list_tools`, including the full input schema, so the LLM can construct valid calls immediately without a second round-trip. See [Result Format](#result-format) to change this.
## Search Strategies
@@ -137,7 +137,7 @@ A catalog no larger than `3 * shortlist` skips the wide pass.
| --- | --- | --- |
| `model` | `jev-latest` | TypeSafe model. Pin a versioned id once `fit_threshold` is tuned. |
| `api_key` | `TYPESAFE_API_KEY` | TypeSafe API key. |
-| `client` | none | A ready `AsyncTypeSafeClient` to use instead of building one. |
+| `client` | none | A ready `AsyncTypeSafeClient` to use instead of building one. When set, `api_key` is not required. |
| `shortlist` | 8 | Candidates each wide-pass request carries forward; with `close_read=True`, it must be at most half of `chunk_size` so repeated passes remain bounded. The close read sees at most three times this or 255 tools, whichever is smaller. |
| `fit_threshold` | 0.3 | Minimum "does this tool do it" probability for a tool to be returned. |
| `chunk_size` | 150 | Tools per wide-pass request, at most 255. |
@@ -196,11 +196,30 @@ mcp.add_transform(RegexSearchTransform(
))
```
+### Result Format
+
+`search_result_serializer` controls what `search_tools` returns. The default, `serialize_tools_for_output_json`, returns the same JSON as `list_tools`. `serialize_tools_for_output_markdown` renders each match as compact Markdown, which uses roughly a third of the tokens:
+
+```python
+from fastmcp import FastMCP
+from fastmcp.server.transforms.search import (
+ BM25SearchTransform,
+ serialize_tools_for_output_markdown,
+)
+
+search = BM25SearchTransform(
+ search_result_serializer=serialize_tools_for_output_markdown,
+)
+mcp = FastMCP("My Server", transforms=[search])
+```
+
+A custom serializer is any function, sync or async, that takes the sequence of matching `Tool` objects and returns the tool result.
+
## The `call_tool` Proxy
The `call_tool` proxy forwards calls to the real tool. When a client calls `call_tool(name="search_database", arguments={...})`, the proxy resolves `search_database` through the server's normal tool pipeline — including transforms and middleware — and executes it.
-The proxy rejects attempts to call the synthetic tools themselves. `call_tool(name="call_tool")` raises an error rather than recursing.
+The proxy rejects attempts to call the synthetic tools themselves. `call_tool(name="call_tool")` raises an error rather than recursing. It also refuses any name outside the catalog the client is allowed to see, such as an app-only or disabled tool, with an "Unknown tool" error.
<Note>
Tools discovered through search can also be called directly via `client.call_tool("search_database", {...})` without going through the proxy. The proxy exists for LLMs that only know about the tools returned by `list_tools` and need a way to invoke discovered tools through a tool they can see.
@@ -215,6 +234,7 @@ App-only tools are excluded too. A [MCP app](/apps/overview) can declare backend
The search tool queries `list_tools()` through the complete pipeline at search time, so the same filtering that controls what a client sees in the listing also controls what they can discover through search.
```python
+from fastmcp import FastMCP
from fastmcp.server.transforms import Visibility
from fastmcp.server.transforms.search import RegexSearchTransform
diff --git a/docs/servers/transforms/tool-transformation.mdx b/docs/servers/transforms/tool-transformation.mdx
index a50513f87..7cbeaf036 100644
--- a/docs/servers/transforms/tool-transformation.mdx
+++ b/docs/servers/transforms/tool-transformation.mdx
@@ -9,7 +9,7 @@ import { VersionBadge } from '/snippets/version-badge.mdx'
<VersionBadge version="3.0.0" />
-Tool transformation lets you modify tool schemas - renaming tools, changing descriptions, adjusting tags, and reshaping argument schemas. FastMCP provides two mechanisms that share the same configuration options but differ in timing.
+Tool transformation lets you modify tool schemas - renaming tools, changing descriptions, adjusting tags, and reshaping argument schemas. FastMCP provides two mechanisms that differ in timing and in the options they accept.
**Deferred transformation** with `ToolTransform` applies modifications when tools flow through a transform chain. Use this for tools from mounted servers, proxies, or other providers where you don't control the source directly.
@@ -80,32 +80,37 @@ The standalone `@tool` decorator (from `fastmcp.tools`) creates a Tool object wi
## Modification Options
-Both mechanisms support the same modifications.
+The two mechanisms overlap but are not identical. Only `ToolTransformConfig` sets `version` and `enabled`; only `Tool.from_tool()` accepts annotations, output schemas, and a custom function.
**Tool-level options:**
-| Option | Description |
-|--------|-------------|
-| `name` | New name for the tool |
-| `description` | New description |
-| `title` | Human-readable title |
-| `tags` | Set of tags for categorization |
-| `annotations` | MCP ToolAnnotations |
-| `meta` | Custom metadata dictionary |
-| `enabled` | Whether the tool is visible to clients (default `True`) |
-
-**Argument-level options** (via `ArgTransform` or `ArgTransformConfig`):
-
-| Option | Description |
-|--------|-------------|
-| `name` | Rename the argument |
-| `description` | New description for the argument |
-| `default` | New default value |
-| `default_factory` | Callable that generates a default (requires `hide=True`) |
-| `hide` | Remove from client-visible schema |
-| `required` | Make an optional argument required |
-| `type` | Change the argument's type |
-| `examples` | Example values for the argument |
+| Option | Description | `ToolTransformConfig` | `Tool.from_tool()` |
+|--------|-------------|:---:|:---:|
+| `name` | New name for the tool | Yes | Yes |
+| `description` | New description | Yes | Yes |
+| `title` | Human-readable title | Yes | Yes |
+| `tags` | Set of tags for categorization | Yes | Yes |
+| `meta` | Custom metadata dictionary | Yes | Yes |
+| `version` | New version for the tool | Yes | No |
+| `enabled` | Whether the tool is visible to clients (default `True`) | Yes | No |
+| `annotations` | MCP `ToolAnnotations` | No | Yes |
+| `output_schema` | Output schema for structured results | No | Yes |
+| `transform_fn` | Custom function that wraps execution (see below) | No | Yes |
+
+Argument transforms go in `arguments` on `ToolTransformConfig` (as `ArgTransformConfig`) and in `transform_args` on `Tool.from_tool()` (as `ArgTransform`).
+
+**Argument-level options:**
+
+| Option | Description | `ArgTransformConfig` | `ArgTransform` |
+|--------|-------------|:---:|:---:|
+| `name` | Rename the argument | Yes | Yes |
+| `description` | New description for the argument | Yes | Yes |
+| `default` | New default value (`ArgTransformConfig` accepts only strings, numbers, booleans, and `None`) | Yes | Yes |
+| `hide` | Remove from client-visible schema | Yes | Yes |
+| `required` | Make an optional argument required (only `True` is accepted) | Yes | Yes |
+| `examples` | Example values for the argument | Yes | Yes |
+| `default_factory` | Callable that generates a default (requires `hide=True`) | No | Yes |
+| `type` | Change the argument's type | No | Yes |
## Hiding Arguments
@@ -129,7 +134,7 @@ transform_args = {
Hidden arguments disappear from the tool's schema. The client never sees them, but the underlying function receives the configured value.
<Warning>
-`default_factory` requires `hide=True`. Visible arguments need static defaults that can be represented in JSON Schema.
+`default_factory` requires `hide=True`. Visible arguments need static defaults that can be represented in JSON Schema. A hidden argument also cannot be `required`, and `required=True` cannot be combined with a default.
</Warning>
## Renaming Arguments
diff --git a/docs/servers/transforms/transforms.mdx b/docs/servers/transforms/transforms.mdx
index fc8f0ceda..6347e5da4 100644
--- a/docs/servers/transforms/transforms.mdx
+++ b/docs/servers/transforms/transforms.mdx
@@ -15,7 +15,7 @@ Transforms modify components as they flow from providers to clients. When a clie
Think of transforms as filters in a pipeline. Components flow from providers through transforms to reach clients:
-```
+```text
Provider → [Transform A] → [Transform B] → Client
```
@@ -27,7 +27,7 @@ FastMCP provides several transforms for common use cases:
- **[Namespace](/servers/transforms/namespace)** - Prefix component names to prevent conflicts when composing servers
- **[Tool Transformation](/servers/transforms/tool-transformation)** - Rename tools, modify descriptions, reshape arguments
-- **[Enabled](/servers/visibility)** - Control which components are visible at runtime
+- **[Visibility](/servers/visibility)** - Control which components are visible at runtime
- **[Tool Search](/servers/transforms/tool-search)** - Replace large tool catalogs with on-demand search
- **[Resources as Tools](/servers/transforms/resources-as-tools)** - Expose resources to tool-only clients
- **[Prompts as Tools](/servers/transforms/prompts-as-tools)** - Expose prompts to tool-only clients
@@ -64,12 +64,28 @@ main = FastMCP("Main", providers=[provider])
# Tool is now: api_process with updated description
```
-When using `mount()`, the returned provider reference lets you add transforms directly.
+`mount()` returns `None`, so it gives you no provider to add transforms to. When a mounted server needs its own transforms, build the `FastMCPProvider` yourself and register it with `add_provider()`, which takes the same `namespace` argument as `mount()`.
```python
+from fastmcp import FastMCP
+from fastmcp.server.providers import FastMCPProvider
+from fastmcp.server.transforms import ToolTransform
+from fastmcp.tools.tool_transform import ToolTransformConfig
+
+sub_server = FastMCP("Sub")
+
+@sub_server.tool
+def process(data: str) -> str:
+ return f"Processed: {data}"
+
+provider = FastMCPProvider(sub_server)
+provider.add_transform(ToolTransform({
+ "process": ToolTransformConfig(description="Process data through the API"),
+}))
+
main = FastMCP("Main")
-mount = main.mount(sub_server, namespace="api")
-mount.add_transform(ToolTransform({...}))
+main.add_provider(provider, namespace="api")
+# Tool is now: api_process with updated description
```
### Server-Level Transforms
@@ -96,10 +112,17 @@ Server-level transforms are useful for API versioning or applying consistent nam
Transforms stack in the order they're added. The first transform added is innermost (closest to the provider), and subsequent transforms wrap it.
```python
+from fastmcp import FastMCP
from fastmcp.server.providers import FastMCPProvider
from fastmcp.server.transforms import Namespace, ToolTransform
from fastmcp.tools.tool_transform import ToolTransformConfig
+server = FastMCP("Sub")
+
+def verbose_name() -> str:
+ return "done"
+
provider = FastMCPProvider(server)
provider.add_transform(Namespace("api")) # Applied first
provider.add_transform(ToolTransform({ # Sees namespaced names
@@ -117,7 +140,7 @@ Create custom transforms by subclassing `Transform` and overriding the methods y
```python
from collections.abc import Sequence
-from fastmcp.server.transforms import Transform, GetToolNext
+from fastmcp.server.transforms import GetToolNext, Transform, VersionSpec
from fastmcp.tools import Tool
class TagFilter(Transform):
@@ -129,31 +152,37 @@ class TagFilter(Transform):
async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:
return [t for t in tools if t.tags & self.required_tags]
- async def get_tool(self, name: str, call_next: GetToolNext) -> Tool | None:
- tool = await call_next(name)
+ async def get_tool(
+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None
+ ) -> Tool | None:
+ tool = await call_next(name, version=version)
if tool and tool.tags & self.required_tags:
return tool
return None
```
-The `Transform` base class provides default implementations that pass through unchanged. Override only the methods relevant to your transform.
+The `Transform` base class provides default implementations that pass through unchanged. Override only the methods relevant to your transform. Get methods receive a keyword-only `version` argument; accept it and pass it to `call_next`, or lookups through your transform raise `TypeError`.
Each component type has two methods with different patterns:
| Method | Pattern | Purpose |
|--------|---------|---------|
| `list_tools(tools)` | Pure function | Transform the sequence of tools |
-| `get_tool(name, call_next)` | Middleware | Transform lookup by name |
+| `get_tool(name, call_next, *, version=None)` | Middleware | Transform lookup by name |
| `list_resources(resources)` | Pure function | Transform the sequence of resources |
-| `get_resource(uri, call_next)` | Middleware | Transform lookup by URI |
+| `get_resource(uri, call_next, *, version=None)` | Middleware | Transform lookup by URI |
| `list_resource_templates(templates)` | Pure function | Transform the sequence of templates |
-| `get_resource_template(uri, call_next)` | Middleware | Transform template lookup by URI |
+| `get_resource_template(uri, call_next, *, version=None)` | Middleware | Transform template lookup by URI |
| `list_prompts(prompts)` | Pure function | Transform the sequence of prompts |
-| `get_prompt(name, call_next)` | Middleware | Transform lookup by name |
+| `get_prompt(name, call_next, *, version=None)` | Middleware | Transform lookup by name |
List methods receive sequences directly and return transformed sequences. Get methods use `call_next` for routing flexibility—when a client requests "new_name", your transform maps it back to "original_name" before calling `call_next()`.
```python
+from collections.abc import Sequence
+from fastmcp.server.transforms import GetToolNext, Transform, VersionSpec
+from fastmcp.tools import Tool
+
class PrefixTransform(Transform):
def __init__(self, prefix: str):
self.prefix = prefix
@@ -161,12 +190,14 @@ class PrefixTransform(Transform):
async def list_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]:
return [t.model_copy(update={"name": f"{self.prefix}_{t.name}"}) for t in tools]
- async def get_tool(self, name: str, call_next: GetToolNext) -> Tool | None:
+ async def get_tool(
+ self, name: str, call_next: GetToolNext, *, version: VersionSpec | None = None
+ ) -> Tool | None:
# Reverse the prefix to find the original
if not name.startswith(f"{self.prefix}_"):
return None
original = name[len(self.prefix) + 1:]
- tool = await call_next(original)
+ tool = await call_next(original, version=version)
if tool:
return tool.model_copy(update={"name": name})
return None
diff --git a/docs/servers/versioning.mdx b/docs/servers/versioning.mdx
index 5547b7842..f1a3cba8a 100644
--- a/docs/servers/versioning.mdx
+++ b/docs/servers/versioning.mdx
@@ -64,7 +64,7 @@ VersionFilter(version_gte="2.0", version_lt="3.0")
### Filtering Mounted Servers
-When you mount child servers and apply a `VersionFilter` to the parent, the filter applies to components from mounted servers as well. Range filtering (`version_gte` and `version_lt`) is handled at the provider level, meaning mounted servers don't need to know about the parent's version constraints.
+When you mount child servers and apply a `VersionFilter` to the parent, the filter applies to components from mounted servers as well. Mounted servers don't need to know about the parent's version constraints.
```python
from fastmcp import FastMCP
@@ -161,7 +161,7 @@ def summarize(text: str, style: str = "concise") -> str:
### Version Discovery
-When clients list components, each versioned component includes metadata about all available versions. This lets clients discover what versions exist before deciding which to use. The `meta.fastmcp.versions` field contains all registered versions sorted from highest to lowest.
+When clients list components, each versioned component includes metadata about all available versions. This lets clients discover what versions exist before deciding which to use. The `meta.fastmcp.versions` field lists every version visible to the client, sorted from highest to lowest. Versions hidden by a `VersionFilter` don't appear.
```python
from fastmcp import Client
@@ -207,7 +207,7 @@ async with Client(server) as client:
prompt = await client.get_prompt("summarize", {"text": "..."}, version="1.0")
```
-If the requested version doesn't exist, the server raises a `NotFoundError`. This ensures you get exactly what you asked for rather than silently falling back to a different version.
+If the requested version doesn't exist, the server raises a `NotFoundError` and the client call fails (for tools, `call_tool` raises a `ToolError`). This ensures you get exactly what you asked for rather than silently falling back to a different version.
### MCP Protocol
@@ -267,7 +267,7 @@ For other formats (dates, custom schemes), FastMCP falls back to lexicographic s
"alpha" < "beta" # Alphabetical order
```
-The `v` prefix is stripped before comparison, so `"v1.0"` and `"1.0"` are treated as equal for sorting purposes.
+The `v` prefix is stripped before comparison, so `"v1.0"` and `"1.0"` are treated as equal for sorting purposes. When one identifier mixes formats, every PEP 440 version sorts below every non-PEP 440 version, so `"2025-01-15"` counts as higher than `"10.0"`. Pick one scheme per component.
## Retrieving Specific Versions
@@ -327,14 +327,17 @@ from fastmcp import FastMCP
mcp = FastMCP()
@mcp.tool(version="1.0")
-def process_data(input: str) -> str:
+def process_data(text: str) -> str:
"""Original implementation, now versioned."""
- return legacy_process(input)
+ return text.upper()
@mcp.tool(version="2.0")
-def process_data(input: str, options: dict | None = None) -> str:
+def process_data(text: str, options: dict | None = None) -> str:
"""Updated implementation with new options parameter."""
- return modern_process(input, options or {})
+ options = options or {}
+ if options.get("reverse"):
+ return text[::-1].upper()
+ return text.upper()
```
Clients automatically see version 2.0 (the highest). During the transition, your server code can still access the original implementation via `get_tool("process_data", version=VersionSpec(eq="1.0"))`.
diff --git a/docs/servers/visibility.mdx b/docs/servers/visibility.mdx
index ea3c2820e..3515801b9 100644
--- a/docs/servers/visibility.mdx
+++ b/docs/servers/visibility.mdx
@@ -111,7 +111,7 @@ A component is disabled if it has **any** of the disabled tags. The component do
### Versions
-When a component has several registered versions, `names` matches every one of them. To act on a particular version, filter by `version` with a [`VersionSpec`](/servers/versioning).
+When a component has several registered versions, `names` matches every one of them. To act on a particular version, filter by `version` with a [`VersionSpec`](/servers/versioning). Unversioned components never match a `version` filter.
```python
from fastmcp.utilities.versions import VersionSpec
@@ -201,11 +201,10 @@ Allowlist mode is useful for restrictive environments where you want to explicit
### Allowlist Behavior
-When you call `enable(only=True)`:
+When you call `enable(only=True)`, FastMCP adds two rules:
-1. Default visibility state switches to "disabled"
-2. Previous allowlists are cleared
-3. Only specified keys/tags become enabled
+1. A rule that disables every component, overriding everything earlier `enable()` calls turned on, including previous allowlists
+2. A rule that enables the components matching your criteria
```python
# Start fresh - only enable these specific tools
@@ -364,7 +363,7 @@ Each call adds a rule to the session. The `dangerous_admin_tool` ends up disable
### Filter Criteria
-The session visibility methods accept the same filter criteria as `server.enable()` and `server.disable()`:
+The session visibility methods accept the same filter criteria as `server.enable()` and `server.disable()`, plus `match_all`. They have no `only` parameter; to build a session allowlist, disable with `match_all=True` and then enable what the session should see.
| Parameter | Description |
|-----------|-------------|
@@ -462,15 +461,23 @@ Sessions start seeing only the activation tools. Calling `activate_finance` reve
## Client Notifications
-When visibility state changes, FastMCP automatically notifies connected clients. Clients supporting the MCP notification protocol receive `list_changed` events and can refresh their component lists.
+Server-level and provider-level `enable()` and `disable()` calls change the rules in place and send no notifications. Connected clients see the change the next time they list components. Session visibility changes are different: they notify the affected session automatically, as described in [Automatic Notifications](#automatic-notifications).
-This happens automatically. You don't need to trigger notifications manually.
+To tell a client about a global change made during a request, send the notification from the tool yourself. This reaches only the session that made the request.
```python
-# This automatically notifies clients
-mcp.disable(tags={"maintenance"})
+import mcp_types
+from fastmcp import FastMCP
+from fastmcp.server.context import Context
-# Clients receive: tools/list_changed, resources/list_changed, etc.
+mcp = FastMCP("Server")
+
+async def start_maintenance(ctx: Context) -> str:
+ """Hide maintenance-tagged tools from every client."""
+ mcp.disable(tags={"maintenance"})
+ await ctx.send_notification(mcp_types.ToolListChangedNotification())
+ return "Maintenance tools hidden"
```
## Filtering Logic