π The fast, Pythonic way to build MCP servers and clients.
docs: correct the integration pages against main (#6408)
nate nowackd5c0e28ef593
diff --git a/docs/integrations/anthropic.mdx b/docs/integrations/anthropic.mdxindex 6fb8841e1..cde529fc0 100644--- a/docs/integrations/anthropic.mdx+++ b/docs/integrations/anthropic.mdx@@ -69,11 +69,11 @@ You'll also need to authenticate with Anthropic. You can do this by setting theexport ANTHROPIC_API_KEY="your-api-key"```-Here is an example of how to call your server from Python. Note that you'll need to replace `https://your-server-url.com` with the actual URL of your server. In addition, we use `/mcp/` as the endpoint because we deployed a streamable-HTTP server with the default path; you may need to use a different endpoint if you customized your server's deployment.+Here is an example of how to call your server from Python. Note that you'll need to replace `https://your-server-url.com` with the actual URL of your server. In addition, we use `/mcp` as the endpoint because we deployed a streamable-HTTP server with the default path; you may need to use a different endpoint if you customized your server's deployment.The connector is in beta, so the call goes through `client.beta.messages` with the `mcp-client-2025-11-20` flag. Each entry in `mcp_servers` also needs a matching `mcp_toolset` entry in `tools` that references it by name; declaring the server without the toolset is rejected as a validation error.-```python {5, 14-23}+```python {5, 12, 14-21}import anthropicfrom rich import print@@ -90,7 +90,7 @@ response = client.beta.messages.create(mcp_servers=[{"type": "url",- "url": f"{url}/mcp/",+ "url": f"{url}/mcp","name": "dice-server",}],@@ -214,7 +214,7 @@ response = client.beta.messages.create(mcp_servers=[{"type": "url",- "url": f"{url}/mcp/",+ "url": f"{url}/mcp","name": "dice-server","authorization_token": access_token}diff --git a/docs/integrations/auth0.mdx b/docs/integrations/auth0.mdxindex ce2dcc670..7e8176f27 100644--- a/docs/integrations/auth0.mdx+++ b/docs/integrations/auth0.mdx@@ -114,7 +114,7 @@ Create an Application in your Auth0 settings to get the credentials needed for a- **API Audience**: A URL that uniquely identifies the API<Tip>- Store this along with of the credentials above. Never commit this to version control. Use environment variables or a secrets manager in production.+ Store the audience alongside the credentials above; `Auth0Provider` needs it.</Tip></Step></Steps>@@ -198,7 +198,7 @@ When you run the client for the first time:<VersionBadge version="2.13.0" />-For production deployments with persistent token management across server restarts, configure `jwt_signing_key`, and `client_storage`:+For production deployments with persistent token management across server restarts, configure `jwt_signing_key` and `client_storage`:```python server.pyimport osdiff --git a/docs/integrations/authkit.mdx b/docs/integrations/authkit.mdxindex 05c6e5d7b..6e4ed15d0 100644--- a/docs/integrations/authkit.mdx+++ b/docs/integrations/authkit.mdx@@ -90,7 +90,7 @@ if __name__ == "__main__":## Production Configuration-For production deployments, load sensitive configuration from environment variables:+For production deployments, load configuration from environment variables:```python server.pyimport os@@ -99,7 +99,7 @@ from fastmcp.server.auth.providers.workos import AuthKitProvider# Load configuration from environment variablesauth = AuthKitProvider(- authkit_domain=os.environ.get("AUTHKIT_DOMAIN"),+ authkit_domain=os.environ["AUTHKIT_DOMAIN"],base_url=os.environ.get("BASE_URL", "https://your-server.com"),)diff --git a/docs/integrations/aws-cognito.mdx b/docs/integrations/aws-cognito.mdxindex b7df29222..b0686e574 100644--- a/docs/integrations/aws-cognito.mdx+++ b/docs/integrations/aws-cognito.mdx@@ -9,7 +9,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx"<VersionBadge version="2.12.4" />-This guide shows you how to secure your FastMCP server using **AWS Cognito user pools**. Since AWS Cognito doesn't support Dynamic Client Registration, this integration uses the [**OAuth Proxy**](/servers/auth/oauth-proxy) pattern to bridge AWS Cognito's traditional OAuth with MCP's authentication requirements. It also includes robust JWT token validation, ensuring enterprise-grade authentication.+This guide shows you how to secure your FastMCP server using **AWS Cognito user pools**. Since AWS Cognito doesn't support Dynamic Client Registration, this integration uses the [**OIDC Proxy**](/servers/auth/oidc-proxy) pattern to bridge AWS Cognito's traditional OAuth with MCP's authentication requirements, and validates Cognito's JWTs on every request.## Configuration@@ -106,7 +106,7 @@ Set up AWS Cognito user pool with an app client to get the credentials needed fo- **User Pool ID**: Format like `eu-central-1_XXXXXXXXX`- **Client ID**: Your application's client identifier- **Client Secret**: Generated client secret (keep secure)- - **AWS Region**: Where Your AWS Cognito user pool is located+ - **AWS Region**: Where your AWS Cognito user pool is located<Tip>Store these credentials securely. Never commit them to version control. Use environment variables or AWS Secrets Manager in production.@@ -161,7 +161,7 @@ Your server is now running and protected by AWS Cognito OAuth authentication.### Testing with a Client-Create a test client that authenticates with Your AWS Cognito-protected server:+Create a test client that authenticates with your AWS Cognito-protected server:```python test_client.pyfrom fastmcp import Client@@ -199,7 +199,7 @@ The client caches tokens locally, so you won't need to re-authenticate for subse<VersionBadge version="2.13.0" />-For production deployments with persistent token management across server restarts, configure `jwt_signing_key`, and `client_storage`:+For production deployments with persistent token management across server restarts, configure `jwt_signing_key` and `client_storage`:```python server.pyimport os@@ -241,38 +241,50 @@ For complete details on these parameters, see the [OAuth Proxy documentation](/s### JWT Token Validation-The AWS Cognito provider includes robust JWT token validation:+The AWS Cognito provider validates every token it receives:- **Signature Verification**: Validates tokens against AWS Cognito's public keys (JWKS)- **Expiration Checking**: Automatically rejects expired tokens- **Issuer Validation**: Ensures tokens come from your specific AWS Cognito user pool+- **Client Validation**: Ensures the token's `client_id` claim matches your app client- **Scope Enforcement**: Verifies required OAuth scopes are present### User Claims and Groups-Access rich user information from AWS Cognito JWT tokens:+The provider exposes three claims from the Cognito access token on `token.claims`: `sub`, `username`, and `cognito:groups`. Other claims are dropped.++To restrict a tool to members of a Cognito group, use [`require_roles`](/servers/authorization#require_roles) with an extractor that reads `cognito:groups`:```python-from fastmcp.server.dependencies import get_access_token+from fastmcp import FastMCP+from fastmcp.server.auth import require_roles+from fastmcp.server.auth.providers.aws import AWSCognitoProvider-async def admin_only_tool() -> str:- """A tool only available to admin users."""- token = get_access_token()- user_groups = token.claims.get("cognito:groups", [])+auth_provider = AWSCognitoProvider(+ user_pool_id="eu-central-1_XXXXXXXXX",+ aws_region="eu-central-1",+ client_id="your-app-client-id",+ client_secret="your-app-client-secret",+ base_url="http://localhost:8000",+)- if "admin" not in user_groups:- raise ValueError("This tool requires admin access")+mcp = FastMCP(name="AWS Cognito Secured App", auth=auth_provider)++def cognito_groups(claims: dict) -> list[str]:+ return claims["cognito:groups"]++[email protected](auth=require_roles("admin", extract=cognito_groups))+async def admin_only_tool() -> str:+ """A tool only available to members of the admin group."""return "Admin access granted!"```-### Enterprise Integration+### Identity Features-Perfect for enterprise environments with:+Because Cognito handles sign-in, its user pool features apply without changes on the FastMCP side:-- **Single Sign-On (SSO)**: Integrate with corporate identity providers-- **Multi-Factor Authentication (MFA)**: Leverage AWS Cognito's built-in MFA-- **User Groups**: Role-based access control through AWS Cognito groups-- **Custom Attributes**: Access custom user attributes defined in your AWS Cognito user pool-- **Compliance**: Meet enterprise security and compliance requirements\ No newline at end of file+- **Single Sign-On (SSO)**: Federate with corporate identity providers+- **Multi-Factor Authentication (MFA)**: Use AWS Cognito's built-in MFA+- **User Groups**: Gate tools on Cognito groups, as shown above\ No newline at end of filediff --git a/docs/integrations/azure.mdx b/docs/integrations/azure.mdxindex e3d21662a..1e6d56de7 100644--- a/docs/integrations/azure.mdx+++ b/docs/integrations/azure.mdx@@ -139,13 +139,12 @@ async def get_user_info() -> dict:from fastmcp.server.dependencies import get_access_tokentoken = get_access_token()- # The AzureProvider stores user data in token claims+ # Claims come from the Azure access tokenreturn {- "azure_id": token.claims.get("sub"),- "email": token.claims.get("email"),+ "azure_id": token.claims.get("oid"),+ "username": token.claims.get("preferred_username"),"name": token.claims.get("name"),- "job_title": token.claims.get("job_title"),- "office_location": token.claims.get("office_location")+ "tenant_id": token.claims.get("tid"),}```@@ -254,7 +253,7 @@ async def main():# Test the protected toolresult = await client.call_tool("get_user_info")user_info = result.data- print(f"Azure user: {user_info['email']}")+ print(f"Azure user: {user_info['username']}")print(f"Name: {user_info['name']}")if __name__ == "__main__":diff --git a/docs/integrations/chatgpt.mdx b/docs/integrations/chatgpt.mdxindex 23249f92c..9b5ed5c77 100644--- a/docs/integrations/chatgpt.mdx+++ b/docs/integrations/chatgpt.mdx@@ -8,7 +8,7 @@ icon: message-smile[ChatGPT](https://chatgpt.com/) supports MCP servers through remote HTTP connections in two modes: **Chat mode** for interactive conversations and **Deep Research mode** for comprehensive information retrieval.<Tip>-**Developer Mode Required for Chat Mode**: To use MCP servers in regular ChatGPT conversations, you must first enable Developer Mode in your ChatGPT settings. This feature is available for ChatGPT Pro, Team, Enterprise, and Edu users.+**Developer Mode Required for Chat Mode**: To use MCP servers in regular ChatGPT conversations, you must first enable Developer Mode in your ChatGPT settings. [OpenAI's Developer Mode guide](https://platform.openai.com/docs/guides/developer-mode) lists which plans include it.</Tip><Note>@@ -66,7 +66,7 @@ Chat mode lets you use MCP tools directly in ChatGPT conversations. See [OpenAI'1. In **Settings** β **Connectors**, click **Create**2. Enter:- **Name**: Your server name- - **Server URL**: `https://your-server.ngrok.io/mcp/`+ - **Server URL**: `https://your-server.ngrok.io/mcp`3. Check **I trust this provider**4. Add authentication if needed5. Click **Create**@@ -95,7 +95,10 @@ The connector must be explicitly enabled in each chat session through DeveloperUse `annotations=ToolAnnotations(readOnlyHint=True)` to skip confirmation prompts for read-only tools:```python-from mcp.types import ToolAnnotations+from fastmcp import FastMCP+from mcp_types import ToolAnnotations++mcp = FastMCP("Demo Server")@mcp.tool(annotations=ToolAnnotations(readOnlyHint=True))def get_status() -> str:@@ -121,6 +124,10 @@ Deep Research mode provides systematic information retrieval with citations. SeeDeep Research tools must follow this pattern:```python+from fastmcp import FastMCP++mcp = FastMCP("Research Server")+@mcp.tool()def search(query: str) -> dict:"""diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdxindex 7addeaaad..fbfe744d7 100644--- a/docs/integrations/claude-code.mdx+++ b/docs/integrations/claude-code.mdx@@ -96,6 +96,12 @@ Alternatively, you can use a `fastmcp.json` configuration file (recommended):}```+Pass the configuration file to the install command in place of the server file:++```bash+fastmcp install claude-code fastmcp.json+```+#### Python Version and Project Configuration@@ -107,12 +113,14 @@ Control the Python environment for your server with these options:fastmcp install claude-code server.py --python 3.11```-**Project directory**: Use `--project` to run your server within a specific project context. This tells `uv` to use the project's configuration files and virtual environment:+**Project directory**: Use `--project` to select the directory containing your MCP server's `pyproject.toml`. FastMCP passes this to `uv run --project`, which discovers the project's configuration and installs its dependencies into the project environment:```bash-fastmcp install claude-code server.py --project /path/to/my-project+fastmcp install claude-code /path/to/mcp-server/server.py --project /path/to/mcp-server```+`--project` selects the Python environment without changing the server's working directory. If your server reads local files, use absolute paths or resolve them relative to the server file.+#### Environment VariablesIf your server needs environment variables (like API keys), you must include them:@@ -130,7 +138,7 @@ fastmcp install claude-code server.py --name "Weather Server" --env-file .env```<Warning>-**Claude Code must be installed**. The integration looks for the Claude Code CLI at the default installation location (`~/.claude/local/claude`) and uses the `claude mcp add` command to register servers.+**Claude Code must be installed**. The integration looks for the `claude` executable on your `PATH`, then in common install locations such as `~/.claude/local/claude`, and uses the `claude mcp add` command to register servers.</Warning>### Manual Configurationdiff --git a/docs/integrations/claude-desktop.mdx b/docs/integrations/claude-desktop.mdxindex 8baf6db3d..0cd86a1d8 100644--- a/docs/integrations/claude-desktop.mdx+++ b/docs/integrations/claude-desktop.mdx@@ -26,7 +26,7 @@ This guide focuses specifically on using FastMCP servers with Claude Desktop. FoClaude Desktop traditionally requires MCP servers to run locally using STDIO transport, where your server communicates with Claude through standard input/output rather than HTTP. However, users on certain plans now have access to remote server support as well.<Tip>-If you don't have access to remote server support or need to connect to remote servers, you can create a **proxy server** that runs locally via STDIO and forwards requests to remote HTTP servers. See the [Proxy Servers](#proxy-servers) section below.+If you don't have access to remote server support or need to connect to remote servers, you can create a **proxy server** that runs locally via STDIO and forwards requests to remote HTTP servers. See the [Remote Servers](#remote-servers) section below.</Tip>## Create a Server@@ -115,6 +115,12 @@ Alternatively, you can use a `fastmcp.json` configuration file (recommended):}```+Pass the configuration file to the install command in place of the server file:++```bash+fastmcp install claude-desktop fastmcp.json+```+#### Python Version and Project Directory@@ -269,7 +275,7 @@ from fastmcp.server import create_proxy# Create a proxy to a remote serverproxy = create_proxy(- "https://example.com/mcp/sse",+ "https://example.com/mcp",name="Remote Server Proxy")@@ -281,14 +287,14 @@ if __name__ == "__main__":For authenticated remote servers, create an authenticated client following the guidance in the [client auth documentation](/clients/auth/bearer) and pass it to the proxy:-```python auth_proxy_server.py {7}+```python auth_proxy_server.py {8}from fastmcp import Clientfrom fastmcp.client.auth import BearerAuthfrom fastmcp.server import create_proxy# Create authenticated clientclient = Client(- "https://api.example.com/mcp/sse",+ "https://api.example.com/mcp",auth=BearerAuth(token="your-access-token"))diff --git a/docs/integrations/cursor.mdx b/docs/integrations/cursor.mdxindex 1aec1920a..c31f7152e 100644--- a/docs/integrations/cursor.mdx+++ b/docs/integrations/cursor.mdx@@ -74,7 +74,7 @@ fastmcp install cursor server.py:my_custom_serverAfter running the command, Cursor will open automatically and prompt you to install the server. The command will be `uv`, which is expected as this is a Python STDIO server. Click "Install" to confirm:-+#### Dependencies@@ -115,6 +115,12 @@ Alternatively, you can use a `fastmcp.json` configuration file (recommended):}```+Pass the configuration file to the install command in place of the server file:++```bash+fastmcp install cursor fastmcp.json+```+#### Python Version and Project Configurationdiff --git a/docs/integrations/descope.mdx b/docs/integrations/descope.mdxindex f6e31bb55..03392f551 100644--- a/docs/integrations/descope.mdx+++ b/docs/integrations/descope.mdx@@ -37,13 +37,13 @@ Before you begin, you will need:<Step title="Copy the Well-Known URL">`DescopeProvider` accepts both resource-specific MCP Server URLs:- ```+ ```texthttps://api.descope.com/v1/apps/agentic/P.../M.../.well-known/openid-configuration```and project-level inbound app URLs:- ```+ ```texthttps://api.descope.com/v1/apps/P.../.well-known/openid-configuration```@@ -138,7 +138,7 @@ from fastmcp.server.auth.providers.descope import DescopeProvider# Load configuration from environment variablesauth = DescopeProvider(- config_url=os.environ.get("DESCOPE_CONFIG_URL"),+ config_url=os.environ["DESCOPE_CONFIG_URL"],base_url=os.environ.get("BASE_URL", "https://your-server.com"))diff --git a/docs/integrations/discord.mdx b/docs/integrations/discord.mdxindex 43586d578..900758d8e 100644--- a/docs/integrations/discord.mdx+++ b/docs/integrations/discord.mdx@@ -139,6 +139,8 @@ Discord OAuth supports several scopes for accessing different types of user dataTo request additional scopes:```python+from fastmcp.server.auth.providers.discord import DiscordProvider+auth_provider = DiscordProvider(client_id="...",client_secret="...",diff --git a/docs/integrations/eunomia-authorization.mdx b/docs/integrations/eunomia-authorization.mdxindex 2fd2ca4a5..2134c0e7c 100644--- a/docs/integrations/eunomia-authorization.mdx+++ b/docs/integrations/eunomia-authorization.mdx@@ -5,17 +5,17 @@ description: Add policy-based authorization to your FastMCP servers with Eunomiaicon: shield-check----Add **policy-based authorization** to your FastMCP servers with one-line code addition with the **[Eunomia][eunomia-github] authorization middleware**.+Add **policy-based authorization** to your FastMCP servers with a single line of code using the **[Eunomia][eunomia-github] authorization middleware**.Control which tools, resources and prompts MCP clients can view and execute on your server. Define dynamic JSON-based policies and obtain a comprehensive audit log of all access attempts and violations.## How it Works-Exploiting FastMCP's [Middleware][fastmcp-middleware], the Eunomia middleware intercepts all MCP requests to your server and automatically maps MCP methods to authorization checks.+Built on FastMCP's [Middleware][fastmcp-middleware], the Eunomia middleware intercepts all MCP requests to your server and automatically maps MCP methods to authorization checks.### Listing Operations-The middleware behaves as a filter for listing operations (`tools/list`, `resources/list`, `prompts/list`), hiding to the client components that are not authorized by the defined policies.+The middleware behaves as a filter for listing operations (`tools/list`, `resources/list`, `prompts/list`), hiding components that the defined policies do not authorize.```mermaidsequenceDiagram@@ -116,7 +116,7 @@ Start your FastMCP server normally:python server.py```-The middleware will now intercept all MCP requests and check them against your policies. Requests include agent identification through headers like `X-Agent-ID`, `X-User-ID`, `User-Agent`, or `Authorization` and an automatic mapping of MCP methods to authorization resources and actions.+The middleware now intercepts all MCP requests and checks them against your policies, mapping each MCP method to an authorization resource and action. Over HTTP transports, the middleware identifies the caller from the `X-Agent-ID`, `X-User-ID`, and `User-Agent` headers; over stdio there are no headers, so requests are evaluated as an unknown agent.<Tip>For detailed policy configuration, custom authentication, and remotediff --git a/docs/integrations/fastapi.mdx b/docs/integrations/fastapi.mdxindex 45172e91f..b6527401e 100644--- a/docs/integrations/fastapi.mdx+++ b/docs/integrations/fastapi.mdx@@ -175,7 +175,7 @@ if __name__ == "__main__":Once you've converted your FastAPI app to an MCP server, you can interact with it using the FastMCP client to test functionality before deploying it to an LLM-based application.-```python {3, }+```python {3}# Assumes the FastAPI app from above is already definedfrom fastmcp import FastMCPfrom fastmcp.client import Client@@ -256,12 +256,12 @@ To learn more about customizing the conversion process, see the [OpenAPI IntegraYou can configure headers and other client options via the `httpx_client_kwargs` parameter. For example, to add authentication to your FastAPI app, you can pass a `headers` dictionary to the `httpx_client_kwargs` parameter:-```python {27-31}+```python {26-30}# Assumes the FastAPI app from above is already definedfrom fastmcp import FastMCP# Add authentication to your FastAPI app-from fastapi import Depends, Header+from fastapi import Dependsfrom fastapi.security import HTTPBearer, HTTPAuthorizationCredentialssecurity = HTTPBearer()@@ -300,7 +300,8 @@ In addition to generating servers, FastMCP can facilitate adding MCP servers toTo mount an MCP server, you can use the `http_app` method on your FastMCP instance. This will return an ASGI application that can be mounted to your FastAPI application.-```python {23-30}+```python {24-30}+# Assumes products_db from the example app above is already definedfrom fastmcp import FastMCPfrom fastapi import FastAPI@@ -331,7 +332,7 @@ app = FastAPI(title="E-commerce API", lifespan=mcp_app.lifespan)# Mount the MCP serverapp.mount("/analytics", mcp_app)-# Now: API at /products/*, MCP at /analytics/mcp/+# Now: MCP at /analytics/mcp```### Testing a Mounted Server@@ -423,7 +424,7 @@ This approach lets you maintain a single codebase while offering both traditiona### Operation IDs-FastAPI operation IDs become MCP component names. Always specify meaningful operation IDs:+FastAPI operation IDs become MCP component names, cut at the first double underscore (`__`). Without an explicit `operation_id`, FastAPI generates one such as `get_user_users__user_id__get`, which becomes the tool name `get_user_users`. Specify meaningful operation IDs:```python# Good - explicit operation_iddiff --git a/docs/integrations/gemini-cli.mdx b/docs/integrations/gemini-cli.mdxindex 86d35b20b..4563d831c 100644--- a/docs/integrations/gemini-cli.mdx+++ b/docs/integrations/gemini-cli.mdx@@ -96,6 +96,12 @@ Alternatively, you can use a `fastmcp.json` configuration file (recommended):}```+Pass the configuration file to the install command in place of the server file:++```bash+fastmcp install gemini-cli fastmcp.json+```+#### Python Version and Project Configuration@@ -107,12 +113,14 @@ Control the Python environment for your server with these options:fastmcp install gemini-cli server.py --python 3.11```-**Project directory**: Use `--project` to run your server within a specific project context. This tells `uv` to use the project's configuration files and virtual environment:+**Project directory**: Use `--project` to select the directory containing your MCP server's `pyproject.toml`. FastMCP passes this to `uv run --project`, which discovers the project's configuration and installs its dependencies into the project environment:```bash-fastmcp install gemini-cli server.py --project /path/to/my-project+fastmcp install gemini-cli /path/to/mcp-server/server.py --project /path/to/mcp-server```+`--project` selects the Python environment without changing the server's working directory. If your server reads local files, use absolute paths or resolve them relative to the server file.+#### Environment VariablesIf your server needs environment variables (like API keys), you must include them:diff --git a/docs/integrations/gemini.mdx b/docs/integrations/gemini.mdxindex a7d6dc24e..e47d06d61 100644--- a/docs/integrations/gemini.mdx+++ b/docs/integrations/gemini.mdx@@ -43,7 +43,7 @@ if __name__ == "__main__":### Call the Server-To use the Gemini API with MCP, you'll need to install the Google Generative AI SDK:+To use the Gemini API with MCP, you'll need to install the Google Gen AI SDK:```bashpip install google-genai@@ -57,7 +57,7 @@ export GEMINI_API_KEY="your-api-key"Gemini's SDK interacts directly with the MCP client session. To call the server, you'll need to instantiate a FastMCP client, enter its connection context, and pass the client session to the Gemini SDK.-```python {5, 9, 15}+```python {6, 10, 16}from pathlib import Pathfrom fastmcp import Clientfrom google import genai@@ -66,7 +66,7 @@ import asynciomcp_client = Client(Path("server.py"))gemini_client = genai.Client()-async def main():+async def main():async with mcp_client:response = await gemini_client.aio.models.generate_content(model="gemini-2.0-flash",@@ -99,7 +99,7 @@ from fastmcp import Clientfrom fastmcp.client.auth import BearerAuthmcp_client = Client(- "https://my-server.com/mcp/",+ "https://my-server.com/mcp",auth=BearerAuth("<your-token>"),)```diff --git a/docs/integrations/google.mdx b/docs/integrations/google.mdxindex f8d471bc6..8689ebb8c 100644--- a/docs/integrations/google.mdx+++ b/docs/integrations/google.mdx@@ -27,7 +27,7 @@ Create an OAuth 2.0 Client ID in your Google Cloud Console to get the credential<Step title="Navigate to OAuth Consent Screen">Go to the [Google Cloud Console](https://console.cloud.google.com/apis/credentials) and select your project (or create a new one).- First, configure the OAuth consent screen by navigating to **APIs & Services β OAuth consent screen**. Choose "External" for testing or "Internal" for G Suite organizations.+ First, configure the OAuth consent screen by navigating to **APIs & Services β OAuth consent screen**. Choose "External" for testing or "Internal" for Google Workspace organizations.</Step><Step title="Create OAuth 2.0 Client ID">diff --git a/docs/integrations/goose.mdx b/docs/integrations/goose.mdxindex fc2ff8e39..0013d85a8 100644--- a/docs/integrations/goose.mdx+++ b/docs/integrations/goose.mdx@@ -88,6 +88,12 @@ Alternatively, you can use a `fastmcp.json` configuration file (recommended):}```+Pass the configuration file to the install command in place of the server file:++```bash+fastmcp install goose fastmcp.json+```+#### Python VersionUse `--python` to specify which Python version your server should use:diff --git a/docs/integrations/huggingface.mdx b/docs/integrations/huggingface.mdxindex 55794024b..95b3797b7 100644--- a/docs/integrations/huggingface.mdx+++ b/docs/integrations/huggingface.mdx@@ -104,6 +104,8 @@ omit `client_secret` and provide a `jwt_signing_key` so FastMCP can sign itsown proxy tokens:```python+from fastmcp.server.auth.providers.huggingface import HuggingFaceProvider+auth_provider = HuggingFaceProvider(client_id="your-public-huggingface-client-id",base_url="http://localhost:8000",@@ -122,6 +124,8 @@ You can also use a Client ID Metadata Document URL as the `client_id` when yourclient metadata is hosted at a stable HTTPS URL:```python+from fastmcp.server.auth.providers.huggingface import HuggingFaceProvider+auth_provider = HuggingFaceProvider(client_id="https://your-client.example/.well-known/oauth-cimd",base_url="http://localhost:8000",@@ -237,6 +241,8 @@ need Hub capabilities:| `write-discussions` | Open discussions and pull requests, and interact with discussions |```python+from fastmcp.server.auth.providers.huggingface import HuggingFaceProvider+auth_provider = HuggingFaceProvider(client_id="your-huggingface-client-id",client_secret="your-huggingface-client-secret",@@ -251,6 +257,8 @@ authorization parameter. The value is the organization ID from the`organizations.sub` field in the Hugging Face userinfo response:```python+from fastmcp.server.auth.providers.huggingface import HuggingFaceProvider+auth_provider = HuggingFaceProvider(client_id="your-huggingface-client-id",client_secret="your-huggingface-client-secret",diff --git a/docs/integrations/keycloak.mdx b/docs/integrations/keycloak.mdxindex 71797e607..5d71bd21b 100644--- a/docs/integrations/keycloak.mdx+++ b/docs/integrations/keycloak.mdx@@ -59,6 +59,8 @@ async def get_access_token_claims() -> dict:**Production security**: Always configure the `audience` parameter in production. Without it, your server accepts tokens issued for any audience. Configure Keycloak audience mappers and set `audience` to your server's base URL to ensure tokens are specifically intended for your server.</Warning>+`required_scopes` defaults to `["openid"]`, which ensures the `sub` claim is present in access tokens. Pass your own list to require additional scopes.+## Local DevelopmentLocal infrastructure tooling is deliberately kept out of the FastMCP core library to keep auth integrations slim and the associated maintenance burden as low as possible. That said, Keycloak is a popular identity provider for local development and testing, so a dedicated FastMCP-compatible setup blueprint lives in the companion project [**fastmcp-keycloak-local**](https://github.com/stephaneberle9/fastmcp-keycloak-local).@@ -105,8 +107,18 @@ On first run, your browser will open to Keycloak's authorization page. After logAccess user information from Keycloak JWT tokens:```python+from fastmcp import FastMCP+from fastmcp.server.auth.providers.keycloak import KeycloakAuthProviderfrom fastmcp.server.dependencies import get_access_token+auth = KeycloakAuthProvider(+ realm_url="http://localhost:8080/realms/myrealm",+ base_url="http://localhost:8000",+)++mcp = FastMCP("Keycloak Example Server", auth=auth)++@mcp.toolasync def admin_only_tool() -> str:"""A tool only available to admin users."""@@ -121,6 +133,8 @@ async def admin_only_tool() -> str:### Custom Token Verifier+Pass `token_verifier` to replace the default `JWTVerifier`. The provider's `required_scopes` and `audience` only configure the default verifier, so set them on your custom verifier instead.+```pythonfrom fastmcp.server.auth.providers.jwt import JWTVerifierfrom fastmcp.server.auth.providers.keycloak import KeycloakAuthProviderdiff --git a/docs/integrations/mcp-json-configuration.mdx b/docs/integrations/mcp-json-configuration.mdxindex e3793ee22..e5cb7be66 100644--- a/docs/integrations/mcp-json-configuration.mdx+++ b/docs/integrations/mcp-json-configuration.mdx@@ -72,7 +72,7 @@ This format is widely adopted across the MCP ecosystem:- **Claude Desktop**: Uses `~/Library/Application Support/Claude/claude_desktop_config.json` on macOS, `%APPDATA%\Claude\claude_desktop_config.json` on Windows- **Cursor**: Uses `~/.cursor/mcp.json`-- **VS Code**: Uses workspace `.vscode/mcp.json`+- **VS Code**: Uses workspace `.vscode/mcp.json`, with servers under a top-level `servers` key instead of `mcpServers`- **Other clients**: Many MCP-compatible applications follow this standard## Overview@@ -239,7 +239,7 @@ fastmcp install mcp-json server.py --copy```<Note>-The `--copy` flag requires the `pyperclip` Python package. If not installed, you'll see an error message with installation instructions.+`--copy` uses the `pyperclip` package, which installs with FastMCP. On Linux, `pyperclip` also needs a system clipboard tool such as `xclip`, `xsel`, or `wl-clipboard`.</Note>## Usage Examples@@ -381,19 +381,7 @@ Output:}```-You can also use `fastmcp.json` with a local project:--```json fastmcp.json-{- "$schema": "https://gofastmcp.com/public/schemas/fastmcp.json/v1.json",- "source": {- "path": "server.py"- },- "environment": {- "project": "."- }-}-```+When you install from a `fastmcp.json` file, `fastmcp install mcp-json` reads its `source` and `environment.dependencies` and ignores the rest of `environment`. Pass `--project` on the command line even when the file sets `environment.project`.If your server needs additional packages beyond those in `pyproject.toml`, add them via the `dependencies` array or `--with`.@@ -462,8 +450,8 @@ Copy the `mcpServers` object into Claude Desktop's config file (`~/Library/Appli</Note>Add to `~/.cursor/mcp.json`-### VS Code-Add to your workspace's `.vscode/mcp.json` file+### VS Code+Add the server object to the top-level `servers` key in your workspace's `.vscode/mcp.json` file. VS Code does not read `mcpServers`.### Custom ApplicationsUse the JSON configuration with any application that supports the MCP protocol@@ -498,7 +486,7 @@ To use this in an MCP client, add it to the client's `mcpServers` configuration## Requirements- **uv**: Must be installed and available in your system PATH-- **pyperclip** (optional): Required only for `--copy` functionality+- **A system clipboard tool** (Linux only, optional): `--copy` needs `xclip`, `xsel`, or `wl-clipboard`Install uv if not already available:@@ -506,6 +494,11 @@ Install uv if not already available:# macOSbrew install uv-# Linux/Windows+# macOS/Linuxcurl -LsSf https://astral.sh/uv/install.sh | sh```++```powershell+# Windows+powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"+```diff --git a/docs/integrations/oci.mdx b/docs/integrations/oci.mdxindex 72165238d..e0f9db463 100644--- a/docs/integrations/oci.mdx+++ b/docs/integrations/oci.mdx@@ -91,13 +91,34 @@ Follow the Steps as mentioned below to create an OAuth client.</Step></Steps>+### Step 3: FastMCP Configuration++Create your FastMCP server with `OCIProvider`. Set `config_url` to your identity domain's OIDC discovery URL, `https://<IAM_GUID>.identity.oraclecloud.com/.well-known/openid-configuration`, and pass the client ID and secret from Step 2. `required_scopes` defaults to `["openid"]`.++```python server.py+import os++from fastmcp import FastMCP+from fastmcp.server.auth.providers.oci import OCIProvider++auth_provider = OCIProvider(+ config_url=os.environ["OCI_CONFIG_URL"],+ client_id=os.environ["OCI_CLIENT_ID"],+ client_secret=os.environ["OCI_CLIENT_SECRET"],+ base_url="http://localhost:8000",+ required_scopes=["openid", "profile", "email"],+)++mcp = FastMCP(name="OCI Secured App", auth=auth_provider)+```+This is all you need to implement MCP server authentication against OCI IAM. However, you may want to use an authenticated user token to invoke OCI control plane APIs and propagate identity to the OCI control plane instead of using a service user account. In that case, you need to implement token exchange.-### Step 3: Token Exchange Setup (Only if MCP server needs to talk to OCI Control Plane)+### Step 4: Token Exchange Setup (Only if MCP server needs to talk to OCI Control Plane)-Token exchange helps you exchange a logged-in user's OCI IAM token for an OCI control plane session token, also known as UPST (User Principal Session Token). To learn more about token exchange, refer to my [Workload Identity Federation Blog](https://www.ateam-oracle.com/post/workload-identity-federation)+Token exchange helps you exchange a logged-in user's OCI IAM token for an OCI control plane session token, also known as UPST (User Principal Session Token). To learn more about token exchange, see the [Workload Identity Federation blog post](https://www.ateam-oracle.com/post/workload-identity-federation)-For token exchange, we need to configure Identity propagation trust. The blog above discusses setting up the trust using REST APIs. However, you can also use OCI CLI. Before using the CLI command below, ensure that you have created a token exchange OAuth client. In most cases, you can use the same OAuth client that you created above. Replace `<IAM_GUID>` and `<CLIENT_ID>` in the CLI command below with your actual values.+For token exchange, you need to configure an identity propagation trust. The blog above discusses setting up the trust using REST APIs. However, you can also use OCI CLI. Before using the CLI command below, ensure that you have created a token exchange OAuth client. In most cases, you can use the same OAuth client that you created above. Replace `<IAM_GUID>` and `<CLIENT_ID>` in the CLI command below with your actual values.```bashoci identity-domains identity-propagation-trust create \@@ -238,7 +259,7 @@ mcp = FastMCP(name="Production OCI App", auth=auth_provider)```<Note>-Parameters (`jwt_signing_key` and `client_storage`) work together to ensure tokens and client registrations survive server restarts. **Wrap your storage in `FernetEncryptionWrapper` to encrypt sensitive OAuth tokens at Rest** - without it, tokens are stored in plaintext. Store secrets in environment variables and use a persistent storage backend like Redis for distributed deployments.+Parameters (`jwt_signing_key` and `client_storage`) work together to ensure tokens and client registrations survive server restarts. **Wrap your storage in `FernetEncryptionWrapper` to encrypt sensitive OAuth tokens at rest** - without it, tokens are stored in plaintext. Store secrets in environment variables and use a persistent storage backend like Redis for distributed deployments.For complete details on these parameters, see the [OAuth Proxy documentation](/servers/auth/oauth-proxy#configuration-parameters).</Note>diff --git a/docs/integrations/openai.mdx b/docs/integrations/openai.mdxindex 94ca82b40..ed652ac6b 100644--- a/docs/integrations/openai.mdx+++ b/docs/integrations/openai.mdx@@ -13,7 +13,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx"OpenAI's [Responses API](https://platform.openai.com/docs/api-reference/responses) supports [MCP servers](https://platform.openai.com/docs/guides/tools-remote-mcp) as remote tool sources, allowing you to extend AI capabilities with custom functions.<Note>-The Responses API is a distinct API from OpenAI's Completions API or Assistants API. At this time, only the Responses API supports MCP.+The Responses API is a distinct API from OpenAI's Chat Completions and Assistants APIs, which do not support MCP servers.</Note><Tip>@@ -76,7 +76,7 @@ You'll also need to authenticate with OpenAI. You can do this by setting the `OPexport OPENAI_API_KEY="your-api-key"```-Here is an example of how to call your server from Python. Note that you'll need to replace `https://your-server-url.com` with the actual URL of your server. In addition, we use `/mcp/` as the endpoint because we deployed a streamable-HTTP server with the default path; you may need to use a different endpoint if you customized your server's deployment.+Here is an example of how to call your server from Python. Note that you'll need to replace `https://your-server-url.com` with the actual URL of your server. In addition, we use `/mcp` as the endpoint because we deployed a streamable-HTTP server with the default path; you may need to use a different endpoint if you customized your server's deployment.```python {4, 11-16}from openai import OpenAI@@ -92,7 +92,7 @@ resp = client.responses.create({"type": "mcp","server_label": "dice_server",- "server_url": f"{url}/mcp/",+ "server_url": f"{url}/mcp","require_approval": "never",},],@@ -211,7 +211,7 @@ resp = client.responses.create({"type": "mcp","server_label": "dice_server",- "server_url": f"{url}/mcp/",+ "server_url": f"{url}/mcp","require_approval": "never","headers": {"Authorization": f"Bearer {access_token}"diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdxindex 1a8b26ca1..510a8b244 100644--- a/docs/integrations/openapi.mdx+++ b/docs/integrations/openapi.mdx@@ -9,7 +9,7 @@ import { VersionBadge } from '/snippets/version-badge.mdx'<VersionBadge version="2.0.0" />-FastMCP can automatically generate an MCP server from any OpenAPI specification, allowing AI models to interact with existing APIs through the MCP protocol. Instead of manually creating tools and resources, you provide an OpenAPI spec and FastMCP intelligently converts API endpoints into the appropriate MCP components.+FastMCP can automatically generate an MCP server from any OpenAPI specification, allowing AI models to interact with existing APIs through the MCP protocol. Instead of manually creating tools and resources, you provide an OpenAPI spec and FastMCP converts API endpoints into the appropriate MCP components.<Note>Under the hood, OpenAPI integration uses OpenAPIProvider (v3.0.0+) to source tools from the specification. See [Providers](/servers/providers/overview) to understand how FastMCP sources components.@@ -32,12 +32,12 @@ from fastmcp import FastMCP# Create an HTTP client for your APIclient = httpx2.AsyncClient(base_url="https://api.example.com")-# Load your OpenAPI spec-openapi_spec = httpx2.get("https://api.example.com/openapi.json").json()+# Load your OpenAPI spec+spec = httpx2.get("https://api.example.com/openapi.json").json()# Create the MCP servermcp = FastMCP.from_openapi(- openapi_spec=openapi_spec,+ openapi_spec=spec,client=client,name="My API Server")@@ -46,6 +46,8 @@ if __name__ == "__main__":mcp.run()```+Later examples that call `FastMCP.from_openapi()` reuse `spec` and `client` from this example.+### AuthenticationIf your API requires authentication, configure it on the HTTP client:@@ -102,11 +104,11 @@ By default, FastMCP converts **every endpoint** in your OpenAPI specification inWhile this is a pragmatic default for maximum compatibility, you can easily customize this behavior. Internally, FastMCP uses an ordered list of `RouteMap` objects to determine how to map OpenAPI routes to various MCP component types.-Each `RouteMap` specifies a combination of methods, patterns, and tags, as well as a corresponding MCP component type. Each OpenAPI route is checked against each `RouteMap` in order, and the first one that matches every criteria is used to determine its converted MCP type. A special type, `EXCLUDE`, can be used to exclude routes from the MCP server entirely.+Each `RouteMap` specifies a combination of methods, patterns, and tags, as well as a corresponding MCP component type. Each OpenAPI route is checked against each `RouteMap` in order, and the first one that matches every criterion is used to determine its converted MCP type. A special type, `EXCLUDE`, can be used to exclude routes from the MCP server entirely.- **Methods**: HTTP methods to match (e.g. `["GET", "POST"]` or `"*"` for all)- **Pattern**: Regex pattern to match the route path (e.g. `r"^/users/.*"` or `r".*"` for all)-- **Tags**: A set of OpenAPI tags that must all be present. An empty set (`{}`) means no tag filtering, so the route matches regardless of its tags.+- **Tags**: A set of OpenAPI tags that must all be present. An empty set (`set()`, the default) means no tag filtering, so the route matches regardless of its tags.- **MCP type**: What MCP component type to create (`TOOL`, `RESOURCE`, `RESOURCE_TEMPLATE`, or `EXCLUDE`)- **MCP tags**: A set of custom tags to add to components created from matching routes@@ -272,7 +274,7 @@ mcp = FastMCP.from_openapi(<VersionBadge version="2.5.0" />-FastMCP automatically generates names for MCP components based on the OpenAPI specification. By default, it uses the `operationId` from your OpenAPI spec, up to the first double underscore (`__`).+FastMCP automatically generates names for MCP components based on the OpenAPI specification. By default, it uses the `operationId` from your OpenAPI spec, up to the first double underscore (`__`). Routes without an `operationId` use their summary, or the HTTP method and path when there is no summary.All component names are automatically:- **Slugified**: Spaces and special characters are converted to underscores or removed@@ -282,6 +284,8 @@ All component names are automatically:For more control over component names, you can provide an `mcp_names` dictionary that maps `operationId` values to your desired names. The `operationId` must be exactly as it appears in the OpenAPI spec. The provided name will always be slugified and truncated.```python+from fastmcp import FastMCP+mcp = FastMCP.from_openapi(openapi_spec=spec,client=client,@@ -306,6 +310,7 @@ FastMCP provides several ways to add tags to your MCP components, allowing you tYou can add custom tags to components created from specific routes using the `mcp_tags` parameter in `RouteMap`. These tags will be applied to all components created from routes that match that particular route map.```python+from fastmcp import FastMCPfrom fastmcp.server.providers.openapi import RouteMap, MCPTypemcp = FastMCP.from_openapi(@@ -344,6 +349,8 @@ mcp = FastMCP.from_openapi(You can add tags to **all** components by providing a `tags` parameter when creating your MCP server. These global tags will be applied to every component created from your OpenAPI specification.```python+from fastmcp import FastMCP+mcp = FastMCP.from_openapi(openapi_spec=spec,client=client,@@ -397,6 +404,7 @@ Your `mcp_component_fn` is expected to modify the component in-place, not to ret</Tip>```python+from fastmcp import FastMCPfrom fastmcp.server.providers.openapi import (OpenAPITool,OpenAPIResource,@@ -432,7 +440,7 @@ Tool arguments map to the parameters and request body that the operation declareA header parameter that the operation declares takes the value the tool call supplies. Otherwise, headers you configure on the HTTP client are sent with each request, except `Host`, which FastMCP takes from the request URL. When the MCP server runs over HTTP, FastMCP also forwards headers from the incoming MCP request, except credential and connection headers such as `Authorization`, `Cookie`, and `Host`. Forwarded headers only fill in headers that the outgoing request does not already set. This applies to tools, resources, and resource templates.-FastMCP intelligently handles different types of parameters in OpenAPI requests:+FastMCP handles each parameter location as follows.### Query Parameters@@ -495,7 +503,9 @@ For `multipart/form-data`, non-empty string arrays use one form field per elemenThis applies when the property's `encoding` is omitted or explicitly uses the defaults: `style: form`, `explode: true`, `contentType: text/plain`, `allowReserved: false`, and no custom headers. Existing scalar fields and binary file parts keep their serialization.-Empty arrays still send one field containing `[]`, and non-string arrays still use their Python string representation. Custom encodings, including `explode: false`, JSON parts, and charset overrides, are not implemented by this fix and retain their existing serialization. If a backend depended on Python list strings for non-empty string arrays, adapt it to read repeated fields.+Other arrays are sent as a single field holding the list's Python string representation. That covers empty arrays (sent as `[]`), non-string arrays, and string arrays whose property declares a custom encoding such as `explode: false`, a JSON part, or a charset override.++If a backend depended on Python list strings for non-empty string arrays, adapt it to read repeated fields.### JSON Request Bodiesdiff --git a/docs/integrations/permit.mdx b/docs/integrations/permit.mdxindex 34c60d6fd..8d3cee50e 100644--- a/docs/integrations/permit.mdx+++ b/docs/integrations/permit.mdx@@ -5,13 +5,13 @@ description: Add fine-grained authorization to your FastMCP servers with Permit.icon: shield-check----Add **policy-based authorization** to your FastMCP servers with one-line code addition with the **[Permit.io][permit-github] authorization middleware**.+Add **policy-based authorization** to your FastMCP servers with a single line of code using the **[Permit.io][permit-github] authorization middleware**.Control which tools, resources and prompts MCP clients can view and execute on your server. Define dynamic policies using Permit.io's powerful RBAC, ABAC, and REBAC capabilities, and obtain comprehensive audit logs of all access attempts and violations.## How it Works-Leveraging FastMCP's [Middleware][fastmcp-middleware], the Permit.io middleware intercepts all MCP requests to your server and automatically maps MCP methods to authorization checks against your Permit.io policies; covering both server methods and tool execution.+Leveraging FastMCP's [Middleware][fastmcp-middleware], the Permit.io middleware intercepts all MCP requests to your server and automatically maps MCP methods to authorization checks against your Permit.io policies, covering both server methods and tool execution.### Policy Mapping@@ -39,7 +39,7 @@ For detailed policy mapping examples and configuration, see [Detailed Policy Map### Listing Operations-The middleware behaves as a filter for listing operations (`tools/list`, `resources/list`, `prompts/list`), hiding to the client components that are not authorized by the defined policies.+The middleware behaves as a filter for listing operations (`tools/list`, `resources/list`, `prompts/list`), hiding components that the defined policies do not authorize.```mermaidsequenceDiagram@@ -201,17 +201,22 @@ The middleware supports multiple identity extraction modes:- **JWT-based**: Extract and verify JWT tokens- **Source-based**: Use the MCP context source field-For detailed identity mode configuration and environment variables, see [Identity Modes & Environment Variables](https://github.com/permitio/permit-fastmcp/blob/main/docs/identity-modes.md).+The middleware reads its `PERMIT_MCP_*` environment variables once, when `permit_fastmcp` is imported, so set them before the import. For detailed identity mode configuration and environment variables, see [Identity Modes & Environment Variables](https://github.com/permitio/permit-fastmcp/blob/main/docs/identity-modes.md).#### JWT Authentication Example```pythonimport os-# Configure JWT identity extraction+# Configure JWT identity extraction before importing the middlewareos.environ["PERMIT_MCP_IDENTITY_MODE"] = "jwt"os.environ["PERMIT_MCP_IDENTITY_JWT_SECRET"] = "your-jwt-secret"+from fastmcp import FastMCP+from permit_fastmcp.middleware.middleware import PermitMcpMiddleware++mcp = FastMCP("Secure FastMCP Server π")+mcp.add_middleware(PermitMcpMiddleware(permit_pdp_url="http://localhost:7766",permit_api_key="your-permit-api-key"@@ -231,6 +236,16 @@ The middleware supports Attribute-Based Access Control (ABAC) policies that canCreate a dynamic resource with conditions like `resource.arg_number greater-than 10` to allow the `conditional-greet` tool only when the number argument exceeds 10.```python+from fastmcp import FastMCP+from permit_fastmcp.middleware.middleware import PermitMcpMiddleware++mcp = FastMCP("Secure FastMCP Server π")+mcp.add_middleware(PermitMcpMiddleware(+ permit_pdp_url="http://localhost:7766",+ permit_api_key="your-permit-api-key"+))++@mcp.tooldef conditional_greet(name: str, number: int) -> str:"""Greet a user only if number > 10"""@@ -281,8 +296,11 @@ For a complete list of all configuration options and environment variables, see### Custom Middleware Configuration```python+from fastmcp import FastMCPfrom permit_fastmcp.middleware.middleware import PermitMcpMiddleware+mcp = FastMCP("Secure FastMCP Server π")+middleware = PermitMcpMiddleware(permit_pdp_url="http://localhost:7766",permit_api_key="your-api-key",@@ -304,13 +322,14 @@ import osimport datetimeimport jwt-from fastmcp import FastMCP, Context-from permit_fastmcp.middleware.middleware import PermitMcpMiddleware-# Configure JWT identity extraction+# Configure JWT identity extraction before importing the middlewareos.environ["PERMIT_MCP_IDENTITY_MODE"] = "jwt"os.environ["PERMIT_MCP_IDENTITY_JWT_SECRET"] = "mysecretkey"+from fastmcp import FastMCP, Context+from permit_fastmcp.middleware.middleware import PermitMcpMiddleware+mcp = FastMCP("My MCP Server")@mcp.tool@@ -318,7 +337,7 @@ def login(username: str, password: str) -> str:"""Login to get a JWT token"""if username == "admin" and password == "password":token = jwt.encode(- {"sub": username, "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)},+ {"sub": username, "exp": datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1)},"mysecretkey",algorithm="HS256")diff --git a/docs/integrations/propelauth.mdx b/docs/integrations/propelauth.mdxindex 7875a1ce2..147ca2006 100644--- a/docs/integrations/propelauth.mdx+++ b/docs/integrations/propelauth.mdx@@ -151,7 +151,7 @@ auth = PropelAuthProvider(auth_url=os.environ["PROPELAUTH_AUTH_URL"],introspection_client_id=os.environ["PROPELAUTH_INTROSPECTION_CLIENT_ID"],introspection_client_secret=os.environ["PROPELAUTH_INTROSPECTION_CLIENT_SECRET"],- base_url=os.environ.get("BASE_URL", "https://your-server.com"),+ base_url=os.environ["SERVER_URL"],required_scopes=["read:user_data"],resource="https://your-server.com/mcp", # Restrict to tokens intended for this server (RFC 8707)token_introspection_overrides={diff --git a/docs/integrations/pydantic-ai.mdx b/docs/integrations/pydantic-ai.mdxindex 805d604c1..e2226da7f 100644--- a/docs/integrations/pydantic-ai.mdx+++ b/docs/integrations/pydantic-ai.mdx@@ -62,6 +62,8 @@ Pass a FastMCP [transport](/clients/transports) such as `StdioTransport` for conFor a bearer token, pass `headers`. For [OAuth](/clients/auth/oauth), pass `auth="oauth"` or build the `Client` yourself.```python+from pydantic_ai.mcp import MCPToolset+toolset = MCPToolset("https://your-server-url.com/mcp",headers={"Authorization": "Bearer your-access-token"},@@ -95,6 +97,9 @@ agent = Agent("openai:gpt-5", toolsets=load_mcp_toolsets("mcp_config.json"))Pass an `elicitation_handler` to answer a server's [elicitation](/servers/elicitation) requests. It has the same signature as the FastMCP Client's [elicitation handler](/clients/elicitation).```python+from pydantic_ai.mcp import MCPToolset++async def approve(message, response_type, params, context):return {"approved": True}diff --git a/docs/integrations/scalekit.mdx b/docs/integrations/scalekit.mdxindex ac04b46df..223c8f52c 100644--- a/docs/integrations/scalekit.mdx+++ b/docs/integrations/scalekit.mdx@@ -9,13 +9,15 @@ import { VersionBadge } from "/snippets/version-badge.mdx"<VersionBadge version="2.13.0" />-Install auth stack to your FastMCP server with [Scalekit](https://scalekit.com) using the [Remote OAuth](/servers/auth/remote-oauth) pattern: Scalekit handles user authentication, and the MCP server validates issued tokens.+This guide shows you how to secure your FastMCP server with [Scalekit](https://scalekit.com) using the [Remote OAuth](/servers/auth/remote-oauth) pattern: Scalekit handles user authentication, and your FastMCP server validates the tokens it issues.++## Configuration### Prerequisites-Before you begin+Before you begin, you will need:-1. Get a [Scalekit account](https://app.scalekit.com/) and grab your **Environment URL** from _Dashboard > Settings_ .+1. Get a [Scalekit account](https://app.scalekit.com/) and grab your **Environment URL** from _Dashboard > Settings_.2. Have your FastMCP server's base URL ready (can be localhost for development, e.g., `http://localhost:8000/`)### Step 1: Configure MCP server in Scalekit environment@@ -34,8 +36,6 @@ Record these values in a `.env` file in your FastMCP project:SCALEKIT_ENVIRONMENT_URL=https://your-env.scalekit.comSCALEKIT_RESOURCE_ID=res_926EXAMPLE5878BASE_URL=http://localhost:8000-# Optional: additional scopes tokens must have-# SCALEKIT_REQUIRED_SCOPES=read,write```</Step>@@ -45,7 +45,9 @@ BASE_URL=http://localhost:8000Create your FastMCP server file and use the ScalekitProvider to handle all the OAuth integration automatically. Nothing reads `.env` automatically, so load it explicitly with [python-dotenv](https://pypi.org/project/python-dotenv/) (`pip install python-dotenv`) before constructing the provider.-> **Warning:** The legacy `mcp_url` and `client_id` parameters are deprecated and will be removed in a future release. Use `base_url` instead of `mcp_url` and remove `client_id` from your configuration.+<Warning>+The legacy `mcp_url` and `client_id` parameters are deprecated and will be removed in a future release. Use `base_url` instead of `mcp_url` and remove `client_id` from your configuration.+</Warning>```python server.pyimport os@@ -70,13 +72,11 @@ mcp = FastMCP(name="My Scalekit Protected Server", auth=auth_provider)@mcp.tooldef auth_status() -> dict:"""Show Scalekit authentication status."""- # Extract user claims from the JWTreturn {"message": "This tool requires authentication via Scalekit","authenticated": True,"provider": "Scalekit"}-```<Tip>@@ -87,8 +87,8 @@ Set `required_scopes` when you need tokens to carry specific permissions. Leave### Start the MCP server-```sh-uv run python server.py+```bash+fastmcp run server.py --transport http --port 8000```Use any MCP client (for example, mcp-inspector, Claude, VS Code, or Windsurf) to connect to the running server. Verify that authentication succeeds and requests are authorized as expected.@@ -127,11 +127,10 @@ Scalekit supports OAuth 2.1 with Dynamic Client Registration for MCP clients and## Debugging-Enable detailed logging to troubleshoot authentication issues:+FastMCP's loggers do not propagate to the root logger, so `logging.basicConfig` will not surface them. Set `FASTMCP_LOG_LEVEL` to see token validation and metadata forwarding details:-```python-import logging-logging.basicConfig(level=logging.DEBUG)+```bash+FASTMCP_LOG_LEVEL=DEBUG fastmcp run server.py --transport http --port 8000```### Token inspection@@ -139,8 +138,20 @@ logging.basicConfig(level=logging.DEBUG)You can inspect JWT tokens in your tools to understand the user context:```python+import os++from fastmcp import FastMCP+from fastmcp.server.auth.providers.scalekit import ScalekitProviderfrom fastmcp.server.dependencies import get_access_token+auth = ScalekitProvider(+ environment_url=os.environ["SCALEKIT_ENVIRONMENT_URL"],+ resource_id=os.environ["SCALEKIT_RESOURCE_ID"],+ base_url=os.environ.get("BASE_URL", "http://localhost:8000"),+)++mcp = FastMCP(name="My Scalekit Protected Server", auth=auth)+@mcp.tooldef inspect_token() -> dict:"""Inspect the current JWT token claims."""diff --git a/docs/integrations/supabase.mdx b/docs/integrations/supabase.mdxindex d39696da7..250de9da9 100644--- a/docs/integrations/supabase.mdx+++ b/docs/integrations/supabase.mdx@@ -50,7 +50,7 @@ In your Supabase Dashboard:### Step 3: FastMCP Configuration-Create your FastMCP server using the `SupabaseProvider`:+Create your FastMCP server using the `SupabaseProvider`. It verifies tokens against the JWKS published under `{project_url}/auth/v1`; pass `auth_route` if a self-hosted Supabase Auth instance serves a different path.```python server.pyfrom fastmcp import FastMCPdiff --git a/docs/integrations/workos.mdx b/docs/integrations/workos.mdxindex 4f13a5512..db990567f 100644--- a/docs/integrations/workos.mdx+++ b/docs/integrations/workos.mdx@@ -31,7 +31,7 @@ Create an OAuth App in your WorkOS dashboard to get the credentials needed for a<Step title="Create OAuth Application">In your WorkOS dashboard:1. Navigate to **Applications**-2. Click **Create Application**+2. Click **Create Application**3. Select **OAuth Application**4. Name your application</Step>@@ -102,12 +102,12 @@ Create a test client that authenticates with your WorkOS-protected server:from fastmcp import Clientimport asyncio-async def main():+async def main():# The client will automatically handle WorkOS OAuthasync with Client("http://localhost:8000/mcp", auth="oauth") as client:# First-time connection will open WorkOS login in your browserprint("β Authenticated with WorkOS!")-+# Test the protected toolresult = await client.call_tool("protected_tool", {"message": "Hello!"})print(result)@@ -129,7 +129,7 @@ The client caches tokens locally, so you won't need to re-authenticate for subse<VersionBadge version="2.13.0" />-For production deployments with persistent token management across server restarts, configure `jwt_signing_key`, and `client_storage`:+For production deployments with persistent token management across server restarts, configure `jwt_signing_key` and `client_storage`:```python server.pyimport os@@ -187,7 +187,7 @@ Your FastMCP server's public URL</ParamField><ParamField path="required_scopes" default="[]">-OAuth scopes to request+OAuth scopes every token must carry. These are also the scopes advertised to clients unless you set `valid_scopes`.</ParamField><ParamField path="redirect_path" default="/auth/callback">