Merge branch 'main' into tool_tests

This commit is contained in:
William Easton 2025-06-03 09:32:02 -05:00 committed by GitHub
commit e7f2d504ce
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 172 additions and 95 deletions

View file

@ -74,6 +74,7 @@ There are two ways to access the LLM-friendly documentation:
- [Proxy Servers](#proxy-servers)
- [Composing MCP Servers](#composing-mcp-servers)
- [OpenAPI \& FastAPI Generation](#openapi--fastapi-generation)
- [Authentication \& Security](#authentication--security)
- [Running Your Server](#running-your-server)
- [Contributing](#contributing)
- [Prerequisites](#prerequisites)
@ -127,7 +128,7 @@ These are the building blocks for creating MCP servers and clients with FastMCP.
### The `FastMCP` Server
The central object representing your MCP application. It holds your tools, resources, and prompts, manages connections, and can be configured with settings like [authentication providers](https://gofastmcp.com/servers/fastmcp#authentication).
The central object representing your MCP application. It holds your tools, resources, and prompts, manages connections, and can be configured with settings like authentication.
```python
from fastmcp import FastMCP
@ -300,6 +301,16 @@ Automatically generate FastMCP servers from existing OpenAPI specifications (`Fa
Learn more: [**OpenAPI Integration**](https://gofastmcp.com/patterns/openapi) | [**FastAPI Integration**](https://gofastmcp.com/patterns/fastapi).
### Authentication & Security
FastMCP provides built-in authentication support to secure both your MCP servers and clients in production environments. Protect your server endpoints from unauthorized access and authenticate your clients against secured MCP servers using industry-standard protocols.
- **Server Protection**: Secure your FastMCP server endpoints with configurable authentication providers
- **Client Authentication**: Connect to authenticated MCP servers with automatic credential management
- **Production Ready**: Support for common authentication patterns used in enterprise environments
Learn more in the **Authentication Documentation** for [servers](https://gofastmcp.com/servers/auth) and [clients](https://gofastmcp.com/clients/auth).
## Running Your Server
The main way to run a FastMCP server is by calling the `run()` method on your server instance:

View file

@ -1,7 +1,7 @@
---
title: Bearer Token Authentication
sidebarTitle: Bearer Auth
description: Authenticate your FastMCP client using pre-existing OAuth 2.0 Bearer tokens.
description: Authenticate your FastMCP client with a Bearer token.
icon: key
---

View file

@ -1,7 +1,7 @@
---
title: OAuth Authentication
sidebarTitle: OAuth
description: Authenticate your FastMCP client with servers using the OAuth 2.0 Authorization Code Grant, including user interaction via a web browser.
description: Authenticate your FastMCP client via OAuth 2.1.
icon: window
---
@ -13,7 +13,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
OAuth authentication is only relevant for HTTP-based transports and requires user interaction via a web browser.
</Tip>
When your FastMCP client needs to access an MCP server protected by OAuth 2.0, and the process requires user interaction (like logging in and granting consent), you should use the Authorization Code Flow. FastMCP provides the `fastmcp.client.auth.OAuth` helper to simplify this entire process.
When your FastMCP client needs to access an MCP server protected by OAuth 2.1, and the process requires user interaction (like logging in and granting consent), you should use the Authorization Code Flow. FastMCP provides the `fastmcp.client.auth.OAuth` helper to simplify this entire process.
This flow is common for user-facing applications where the application acts on behalf of the user.
@ -35,7 +35,7 @@ async with Client("https://fastmcp.cloud/mcp", auth="oauth") as client:
### `OAuth` Helper
To fully configure the OAuth flow, use the `OAuth` helper and pass it to the `auth` parameter of the `Client` or transport instance. `OAuth` manages the complexities of the OAuth 2.0 Authorization Code Grant with PKCE (Proof Key for Code Exchange) for enhanced security, and implements the full `httpx.Auth` interface.
To fully configure the OAuth flow, use the `OAuth` helper and pass it to the `auth` parameter of the `Client` or transport instance. `OAuth` manages the complexities of the OAuth 2.1 Authorization Code Grant with PKCE (Proof Key for Code Exchange) for enhanced security, and implements the full `httpx.Auth` interface.
```python {2, 4, 6}
from fastmcp import Client

View file

@ -59,7 +59,7 @@ For development and testing, you can use the `dev` command to run your server wi
fastmcp dev server.py
```
See the [CLI documentation](/deployment/cli) for detailed information about all available commands and options.
See the [CLI documentation](/patterns/cli) for detailed information about all available commands and options.
## Transport Options
@ -270,4 +270,4 @@ async def health_check(request: Request) -> PlainTextResponse:
if __name__ == "__main__":
mcp.run()
```
```

View file

@ -93,8 +93,8 @@
"group": "Authentication",
"icon": "user-shield",
"pages": [
"clients/auth/bearer",
"clients/auth/oauth"
"clients/auth/oauth",
"clients/auth/bearer"
]
},
"clients/advanced-features"
@ -106,6 +106,7 @@
"integrations/anthropic",
"integrations/claude-desktop",
"integrations/openai",
"integrations/gemini",
"integrations/contrib"
]
},

View file

@ -1,7 +1,7 @@
---
title: Anthropic
sidebarTitle: Anthropic
description: Access FastMCP servers from the Anthropic Messages API
description: Call FastMCP servers from the Anthropic API
icon: message-smile
---
@ -66,6 +66,12 @@ To use the Messages API with MCP servers, you'll need to install the Anthropic P
pip install anthropic
```
You'll also need to authenticate with Anthropic. You can do this by setting the `ANTHROPIC_API_KEY` environment variable. Consult the Anthropic SDK documentation for more information.
```bash
export 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 `/sse` as the endpoint because we deployed an SSE server with the default path; you may need to use a different endpoint if you customized your server's deployment. **At this time you must also include the `extra_headers` parameter with the `anthropic-beta` header.**
```python {5, 13-22}

View file

@ -1,7 +1,7 @@
---
title: Claude Desktop
sidebarTitle: Claude Desktop
description: Integrate FastMCP servers with Claude Desktop
description: Call FastMCP servers from Claude Desktop
icon: desktop
---

View file

@ -0,0 +1,108 @@
---
title: Gemini SDK
sidebarTitle: Gemini SDK
description: Call FastMCP servers from the Google Gemini SDK
icon: message-smile
---
import { VersionBadge } from "/snippets/version-badge.mdx"
Google's Gemini API includes built-in support for MCP servers in their Python and JavaScript SDKs, allowing you to connect directly to MCP servers and use their tools seamlessly with Gemini models.
## Gemini Python SDK
Google's [Gemini Python SDK](https://ai.google.dev/gemini-api/docs) can use FastMCP clients directly.
<Note>
Google's MCP integration is currently experimental and available in the Python and JavaScript SDKs. The API automatically calls MCP tools when needed and can connect to both local and remote MCP servers.
</Note>
<Tip>
Currently, Gemini's MCP support only accesses **tools** from MCP servers—it queries the `list_tools` endpoint and exposes those functions to the AI. Other MCP features like resources and prompts are not currently supported.
</Tip>
### Create a Server
First, create a FastMCP server with the tools you want to expose. For this example, we'll create a server with a single tool that rolls dice.
```python server.py
import random
from fastmcp import FastMCP
mcp = FastMCP(name="Dice Roller")
@mcp.tool()
def roll_dice(n_dice: int) -> list[int]:
"""Roll `n_dice` 6-sided dice and return the results."""
return [random.randint(1, 6) for _ in range(n_dice)]
if __name__ == "__main__":
mcp.run()
```
### Call the Server
To use the Gemini API with MCP, you'll need to install the Google Generative AI SDK:
```bash
pip install google-genai
```
You'll also need to authenticate with Google. You can do this by setting the `GEMINI_API_KEY` environment variable. Consult the Gemini SDK documentation for more information.
```bash
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}
from fastmcp import Client
from google import genai
import asyncio
mcp_client = Client("server.py")
gemini_client = genai.Client()
async def main():
async with client:
response = await gemini_client.aio.models.generate_content(
model="gemini-2.0-flash",
contents="Roll 3 dice!",
config=genai.types.GenerateContentConfig(
temperature=0,
tools=[mcp_client.session], # Pass the FastMCP client session
),
)
print(response.text)
if __name__ == "__main__":
asyncio.run(main())
```
If you run this code, you'll see output like:
```text
Okay, I rolled 3 dice and got a 5, 4, and 1.
```
### Remote & Authenticated Servers
In the above example, we connected to our local server using `stdio` transport. Because we're using a FastMCP client, you can also connect to any local or remote MCP server, using any [transport](/clients/transports) or [auth](/clients/auth) method supported by FastMCP, simply by changing the client configuration.
For example, to connect to a remote, authenticated server, you can use the following client:
```python
from fastmcp import Client
from fastmcp.client.auth import BearerAuth
client = Client(
"https://my-server.com/sse",
auth=BearerAuth("<your-token>"),
)
```
The rest of the code remains the same.

View file

@ -1,7 +1,7 @@
---
title: OpenAI
sidebarTitle: OpenAI
description: Access FastMCP servers from the OpenAI API
description: Call FastMCP servers from the OpenAI API
icon: message-smile
---
@ -9,7 +9,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
OpenAI recently announced support for MCP servers in the Responses API. Note that at this time, MCP is not supported in ChatGPT.
## MCP in the Responses API
## Responses API
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.
@ -71,6 +71,12 @@ To use the Responses API, you'll need to install the OpenAI Python SDK (not incl
pip install openai
```
You'll also need to authenticate with OpenAI. You can do this by setting the `OPENAI_API_KEY` environment variable. Consult the OpenAI SDK documentation for more information.
```bash
export 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 `/sse` as the endpoint because we deployed an SSE server with the default path; you may need to use a different endpoint if you customized your server's deployment.
```python {4, 11-16}

View file

@ -12,6 +12,10 @@ import { VersionBadge } from "/snippets/version-badge.mdx"
Authentication and authorization are only relevant for HTTP-based transports.
</Tip>
<Note>
The [MCP specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) requires servers to implement full OAuth 2.1 authorization flows with dynamic client registration, server metadata discovery, and complete token endpoints. FastMCP's Bearer Token authentication provides a simpler, more practical alternative by directly validating pre-issued JWT tokens—ideal for service-to-service communication and programmatic environments where full OAuth flows may be impractical, and in accordance with how the MCP ecosystem is pragmatically evolving. However, please note that since it doesn't implement the full OAuth 2.1 flow, this implementation does not strictly comply with the MCP specification.
</Note>
Bearer Token authentication is a common way to secure HTTP-based APIs. In this model, the client sends a token (usually a JSON Web Token or JWT) in the `Authorization` header with the "Bearer" scheme. The server then validates this token to grant or deny access.
FastMCP supports Bearer Token authentication for its HTTP-based transports (`streamable-http` and `sse`), allowing you to protect your server from unauthorized access.
@ -32,7 +36,7 @@ This design allows you to integrate FastMCP servers into existing authentication
To enable Bearer Token validation on your FastMCP server, use the `BearerAuthProvider` class. This provider validates incoming JWTs by verifying signatures, checking expiration, and optionally validating claims.
<Warning>
The `BearerAuthProvider` validates tokens; it does **not** issue them (or implement any part of an OAuth flow). You'll need to generate tokens separately, either using FastMCP utilities or an external Identity Provider (IdP) or OAuth 2.0 Authorization Server.
The `BearerAuthProvider` validates tokens; it does **not** issue them (or implement any part of an OAuth flow). You'll need to generate tokens separately, either using FastMCP utilities or an external Identity Provider (IdP) or OAuth 2.1 Authorization Server.
</Warning>
### Basic Setup
@ -100,7 +104,7 @@ JWKS is recommended for production as it supports automatic key rotation and mul
For development and testing, FastMCP provides the `RSAKeyPair` utility class to generate tokens without needing an external OAuth provider.
<Warning>
The `RSAKeyPair` utility is intended for development and testing only. For production, use a proper OAuth 2.0 Authorization Server or Identity Provider.
The `RSAKeyPair` utility is intended for development and testing only. For production, use a proper OAuth 2.1 Authorization Server or Identity Provider.
</Warning>
### Basic Token Generation

View file

@ -33,7 +33,7 @@ The choice of importing or mounting depends on your use case and requirements.
### Proxy Servers
FastMCP supports [MCP proxying](/patterns/proxy), which allows you to mirror a local or remote server in a local FastMCP instance. Proxies are fully compatible with both importing and mounting.
FastMCP supports [MCP proxying](/servers/proxy), which allows you to mirror a local or remote server in a local FastMCP instance. Proxies are fully compatible with both importing and mounting.
<VersionBadge version="2.4.0" />

View file

@ -135,7 +135,7 @@ For detailed information on each transport, how to configure them (host, port, p
FastMCP supports composing multiple servers together using `import_server` (static copy) and `mount` (live link). This allows you to organize large applications into modular components or reuse existing servers.
See the [Server Composition](/patterns/composition) guide for full details, best practices, and examples.
See the [Server Composition](/servers/composition) guide for full details, best practices, and examples.
```python
# Example: Importing a subserver
@ -159,7 +159,7 @@ main.mount("sub", sub)
FastMCP can act as a proxy for any MCP server (local or remote) using `FastMCP.as_proxy`, letting you bridge transports or add a frontend to existing servers. For example, you can expose a remote SSE server locally via stdio, or vice versa.
See the [Proxying Servers](/patterns/proxy) guide for details and advanced usage.
See the [Proxying Servers](/servers/proxy) guide for details and advanced usage.
```python
from fastmcp import FastMCP, Client
@ -232,29 +232,3 @@ This customization is useful when you want to:
<Tip>
If the serializer function raises an exception, the tool will fall back to the default JSON serialization to avoid breaking the server.
</Tip>
## Authentication
<VersionBadge version="2.2.7" />
FastMCP supports OAuth 2.0 authentication, allowing servers to protect their tools and resources. This is configured by providing an `auth_server_provider` and `auth` settings during `FastMCP` initialization.
```python
from fastmcp import FastMCP
from mcp.server.auth.settings import AuthSettings #, ... other auth imports
# from your_auth_implementation import MyOAuthServerProvider # Placeholder
# Create a server with authentication (conceptual example)
# mcp = FastMCP(
# name="SecureApp",
# auth_server_provider=MyOAuthServerProvider(),
# auth=AuthSettings(
# issuer_url="https://myapp.com",
# # ... other OAuth settings ...
# required_scopes=["myscope"],
# ),
# )
```
Due to the low-level nature of the current MCP SDK's auth provider interface, detailed implementation is beyond a quick example. Refer to the [MCP SDK documentation](https://modelcontextprotocol.io/specification/2025-03-26/basic/authorization) for specifics on implementing an `OAuthAuthorizationServerProvider`. FastMCP integrates with this by passing the provider and settings to the underlying MCP server.
A dedicated [Authentication guide](/deployment/authentication) will cover this in more detail once higher-level abstractions are available in FastMCP.

View file

@ -1,13 +1,12 @@
export const VersionBadge = ({ version }) => {
return (
<code className="version-badge-container">
<div className="version-badge">
<p className="version-badge">
<span className="version-badge-label">New in version:</span>&nbsp;
<span className="version-badge-version">{version}</span>
</div>
<code className="version-badge-version">{version}</code>
</p>
</code>
);
};

View file

@ -17,16 +17,18 @@ h6 code:not(pre code) {
display: inline-block;
align-items: center;
gap: 0.3em;
padding: 0.2em 0.8em;
font-size: 1.1em;
font-weight: 400;
font-size: 1em;
margin-top: 0px;
margin-bottom: 0px;
padding-top: 6px;
padding-bottom: 6px;
padding-left: 20px;
padding-right: 20px;
font-family: "Inter", sans-serif;
letter-spacing: 0.025em;
color: #ff5400;
background: #ffeee6;
border: 1px solid rgb(255, 84, 0, 0.5);
border-radius: 6px;
background: #fef2f2;
border: 1px solid rgba(220, 38, 38, 0.3);
border-radius: 12px;
box-shadow: none;
vertical-align: middle;
position: relative;
@ -44,7 +46,7 @@ h6 code:not(pre code) {
}
.dark .version-badge {
color: #fff;
background: #312e81;
border: 1.5px solid #a78bfa;
color: #f1f5f9;
background: #334155;
border: 1px solid #64748b;
}

View file

@ -1,26 +0,0 @@
import random
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider
from fastmcp.server.auth.providers.bearer import RSAKeyPair
key_pair = RSAKeyPair.generate()
access_token = key_pair.create_token(audience="dice-server")
auth = BearerAuthProvider(
public_key=key_pair.public_key,
audience="dice-server",
)
mcp = FastMCP(name="Dice Roller", auth=auth)
@mcp.tool()
def roll_dice(n_dice: int) -> list[int]:
"""Roll `n_dice` 6-sided dice and return the results."""
return [random.randint(1, 6) for _ in range(n_dice)]
if __name__ == "__main__":
print(f"\n---\n\n🔑 Dice Roller access token:\n\n{access_token}\n\n---\n")
mcp.run(transport="sse", port=8000)

View file

@ -68,9 +68,6 @@ class ServerOAuthMetadata(_MCPServerOAuthMetadata):
class OAuthClientProvider(_MCPOAuthClientProvider):
"""
OAuth client provider with more flexible OAuth metadata discovery.
This subclass handles real-world OAuth servers that may not conform
strictly to the MCP OAuth specification but are still valid OAuth 2.0 servers.
"""
async def _discover_oauth_metadata(

0
src/fastmcp/py.typed Normal file
View file

View file

@ -1,8 +1,3 @@
"""
This is a simple in-memory OAuth provider for testing purposes.
It simulates the OAuth 2.0 flow locally without external calls.
"""
import secrets
import time
@ -36,7 +31,7 @@ DEFAULT_REFRESH_TOKEN_EXPIRY_SECONDS = None # No expiry
class InMemoryOAuthProvider(OAuthProvider):
"""
An in-memory OAuth provider for testing purposes.
It simulates the OAuth 2.0 flow locally without external calls.
It simulates the OAuth 2.1 flow locally without external calls.
"""
def __init__(

View file

@ -342,7 +342,7 @@ async def tokens(test_client, registered_client, auth_code, pkce_challenge, requ
class TestAuthEndpoints:
async def test_metadata_endpoint(self, test_client: httpx.AsyncClient):
"""Test the OAuth 2.0 metadata endpoint."""
"""Test the OAuth 2.1 metadata endpoint."""
print("Sending request to metadata endpoint")
response = await test_client.get("/.well-known/oauth-authorization-server")
print(f"Got response: {response.status_code}")