Merge branch 'main' into tool_tests

This commit is contained in:
William Easton 2025-06-02 17:58:31 -05:00 committed by GitHub
commit fc642cc384
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
17 changed files with 769 additions and 120 deletions

View file

@ -12,14 +12,14 @@
<a href="https://trendshift.io/repositories/13266" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13266" alt="jlowin%2Ffastmcp | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
</div>
> [!NOTE]
> #### FastMCP 2.0 & The Official MCP SDK
> [!Note]
> #### Beyond the Protocol
>
> FastMCP is the standard framework for working with the Model Context Protocol. FastMCP 1.0 was incorporated into the [official low-level Python SDK](https://github.com/modelcontextprotocol/python-sdk), and FastMCP 2.0 *(this project)* provides a complete toolkit for working with the MCP ecosystem.
>
> FastMCP is the standard framework for building MCP servers and clients. FastMCP 1.0 was incorporated into the [official MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk).
> FastMCP has a comprehensive set of features that go far beyond the core MCP specification, all in service of providing **the simplest path to production**. These include client support, server composition, auth, automatic generation from OpenAPI specs, remote server proxying, built-in testing tools, integrations, and more.
>
> **This is FastMCP 2.0,** the actively maintained version that significantly expands on 1.0's basic server-building capabilities by introducing full client support, server composition, OpenAPI/FastAPI integration, remote server proxying, built-in testing tools, and more.
>
> FastMCP 2.0 is the complete toolkit for modern AI applications. Ready to upgrade or get started? Follow the [installation instructions](https://gofastmcp.com/getting-started/installation), which include specific steps for upgrading from the official MCP SDK.
> Ready to upgrade or get started? Follow the [installation instructions](/getting-started/installation), which include specific steps for upgrading from the official MCP SDK.
---
@ -86,20 +86,20 @@ There are two ways to access the LLM-friendly documentation:
## What is MCP?
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can:
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. It is often described as "the USB-C port for AI", providing a uniform way to connect LLMs to resources they can use. It may be easier to think of it as an API, but specifically designed for LLM interactions. MCP servers can:
- Expose data through **Resources** (similar to `GET` requests; load info into context)
- Provide functionality through **Tools** (similar to `POST`/`PUT` requests; execute actions)
- Define interaction patterns through **Prompts** (reusable templates)
- Expose data through **Resources** (think of these sort of like GET endpoints; they are used to load information into the LLM's context)
- Provide functionality through **Tools** (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect)
- Define interaction patterns through **Prompts** (reusable templates for LLM interactions)
- And more!
FastMCP provides a high-level, Pythonic interface for building and interacting with these servers.
FastMCP provides a high-level, Pythonic interface for building, managing, and interacting with these servers.
## Why FastMCP?
The MCP protocol is powerful but implementing it involves a lot of boilerplate - server setup, protocol handlers, content types, error management. FastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It's designed to be high-level and Pythonic; in most cases, decorating a function is all you need.
While the core server concepts of FastMCP 1.0 laid the groundwork and were contributed to the official MCP SDK, **FastMCP 2.0 (this project) is the actively developed successor**, adding significant enhancements and entirely new capabilities like a powerful **client library**, server **proxying**, **composition** patterns, **OpenAPI/FastAPI integration**, and much more.
FastMCP 2.0 has evolved into a comprehensive platform that goes far beyond basic protocol implementation. While 1.0 provided server-building capabilities (and is now part of the official MCP SDK), 2.0 offers a complete ecosystem including client libraries, authentication systems, deployment tools, integrations with major AI platforms, testing frameworks, and production-ready infrastructure patterns.
FastMCP aims to be:
@ -109,7 +109,7 @@ FastMCP aims to be:
🐍 **Pythonic:** Feels natural to Python developers
🔍 **Complete:** FastMCP aims to provide a full implementation of the core MCP specification for both servers and clients
🔍 **Complete:** A comprehensive platform for all MCP use cases, from dev to prod
## Installation

BIN
docs/assets/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
docs/assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 486 KiB

View file

@ -30,23 +30,25 @@ The most straightforward way to use a pre-existing Bearer token is to provide it
If you're using a string token, do not include the `Bearer` prefix. FastMCP will add it for you.
</Tip>
```python {4}
```python {5}
from fastmcp import Client
async with Client(
"https://fastmcp.cloud/mcp", auth="<your-token>"
"https://fastmcp.cloud/mcp",
auth="<your-token>",
) as client:
await client.ping()
```
You can also supply a Bearer token to a transport instance, such as `StreamableHttpTransport` or `SSETransport`:
```python {5}
```python {6}
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport
transport = StreamableHttpTransport(
"http://fastmcp.cloud/mcp", auth="<your-token>"
"http://fastmcp.cloud/mcp",
auth="<your-token>",
)
async with Client(transport) as client:
@ -57,12 +59,13 @@ async with Client(transport) as client:
If you prefer to be more explicit and not rely on FastMCP to transform your string token, you can use the `BearerAuth` class yourself, which implements the `httpx.Auth` interface.
```python {5}
```python {6}
from fastmcp import Client
from fastmcp.client.auth import BearerAuth
async with Client(
"https://fastmcp.cloud/mcp", auth=BearerAuth(token="<your-token>")
"https://fastmcp.cloud/mcp",
auth=BearerAuth(token="<your-token>"),
) as client:
await client.ping()
```
@ -71,11 +74,12 @@ async with Client(
If the MCP server expects a custom header or token scheme, you can manually set the client's `headers` instead of using the `auth` parameter:
```python {4}
```python {5}
from fastmcp import Client
async with Client(
"https://fastmcp.cloud/mcp", headers={"X-API-Key": "<your-token>"}
"https://fastmcp.cloud/mcp",
headers={"X-API-Key": "<your-token>"},
) as client:
await client.ping()
```

View file

@ -345,7 +345,7 @@ For consistent behavior across all transports, we recommend explicitly setting t
#### Error Handling
When a `call_tool` request results in an error on the server (e.g., the tool function raised an exception), the `client.call_tool()` method will raise a `fastmcp.client.ClientError`.
When a `call_tool` request results in an error on the server (e.g., the tool function raised an exception), the `client.call_tool()` method will raise a `fastmcp.exceptions.ClientError`.
```python
async def safe_call_tool():

View file

@ -1,5 +1,9 @@
{
"$schema": "https://mintlify.com/docs.json",
"appearance": {
"default": "system",
"strict": false
},
"background": {
"color": {
"dark": "#222831",
@ -13,6 +17,10 @@
"primary": "#2d00f7"
},
"description": "The fast, Pythonic way to build MCP servers and clients.",
"favicon": {
"dark": "/assets/favicon.ico",
"light": "/assets/favicon.ico"
},
"footer": {
"socials": {
"bluesky": "https://bsky.app/profile/jlowin.dev",
@ -68,10 +76,10 @@
"servers/composition",
{
"group": "Deployment",
"icon": "upload",
"pages": [
"deployment/running-server",
"deployment/asgi",
"deployment/cli"
"deployment/asgi"
]
}
]
@ -92,18 +100,23 @@
"clients/advanced-features"
]
},
{
"group": "Integrations",
"pages": [
"integrations/anthropic",
"integrations/claude-desktop",
"integrations/openai",
"integrations/contrib"
]
},
{
"group": "Patterns",
"pages": [
"patterns/decorating-methods",
"patterns/http-requests",
"patterns/contrib",
"patterns/testing"
"patterns/testing",
"patterns/cli"
]
},
{
"group": "Deployment",
"pages": []
}
]
},
@ -117,5 +130,8 @@
"source": "/patterns/composition"
}
],
"search": {
"prompt": "Search the docs..."
},
"theme": "mint"
}

View file

@ -9,7 +9,7 @@ icon: hand-wave
The [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) is a new, standardized way to provide context and tools to your LLMs, and FastMCP makes building MCP servers and clients simple and intuitive. Create tools, expose resources, define prompts, and more with clean, Pythonic code:
```python {1, 3, 5, 11}
```python {1}
from fastmcp import FastMCP
mcp = FastMCP("Demo 🚀")
@ -24,16 +24,17 @@ if __name__ == "__main__":
```
## FastMCP and the Official MCP SDK
## Beyond the Protocol
FastMCP is the standard framework for building MCP servers and clients. FastMCP 1.0 was incorporated into the [official MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk).
FastMCP is the standard framework for working with the Model Context Protocol. FastMCP 1.0 was incorporated into the [official low-level Python SDK](https://github.com/modelcontextprotocol/python-sdk), and FastMCP 2.0 *(this project)* provides a complete toolkit for working with the MCP ecosystem.
**This is FastMCP 2.0,** the [actively maintained version](https://github.com/jlowin/fastmcp) that significantly expands on 1.0's basic server-building capabilities by introducing full client support, server composition, OpenAPI/FastAPI integration, remote server proxying, built-in testing tools, and more.
FastMCP has a comprehensive set of features that go far beyond the core MCP specification, all in service of providing **the simplest path to production**. These include client support, server composition, auth, automatic generation from OpenAPI specs, remote server proxying, built-in testing tools, integrations, and more.
FastMCP 2.0 is the complete toolkit for modern AI applications. Ready to upgrade or get started? Follow the [installation instructions](/getting-started/installation), which include specific steps for upgrading from the official MCP SDK.
Ready to upgrade or get started? Follow the [installation instructions](/getting-started/installation), which include specific steps for upgrading from the official MCP SDK.
## What is MCP?
The Model Context Protocol lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. It is often described as "the USB-C port for AI", providing a uniform way to connect LLMs to resources they can use. It may be easier to think of it as an API, but specifically designed for LLM interactions. MCP servers can:
- Expose data through `Resources` (think of these sort of like GET endpoints; they are used to load information into the LLM's context)
@ -41,14 +42,13 @@ The Model Context Protocol lets you build servers that expose data and functiona
- Define interaction patterns through `Prompts` (reusable templates for LLM interactions)
- And more!
There is a low-level Python SDK available for implementing the protocol directly, but FastMCP aims to make that easier by providing a high-level, Pythonic interface.
FastMCP provides a high-level, Pythonic interface for building, managing, and interacting with these servers.
## Why FastMCP?
The MCP protocol is powerful but implementing it involves a lot of boilerplate - server setup, protocol handlers, content types, error management. FastMCP handles all the complex protocol details and server management, so you can focus on building great tools. It's designed to be high-level and Pythonic; in most cases, decorating a function is all you need.
While the core server concepts of FastMCP 1.0 laid the groundwork and were contributed to the official MCP SDK, FastMCP 2.0 (this project) is the actively developed successor, adding significant enhancements and entirely new capabilities like a powerful client library, server proxying, composition patterns, and much more.
FastMCP 2.0 has evolved into a comprehensive platform that goes far beyond basic protocol implementation. While 1.0 provided server-building capabilities (and is now part of the official MCP SDK), 2.0 offers a complete ecosystem including client libraries, authentication systems, deployment tools, integrations with major AI platforms, testing frameworks, and production-ready infrastructure patterns.
FastMCP aims to be:
@ -58,7 +58,7 @@ FastMCP aims to be:
🐍 **Pythonic**: Feels natural to Python developers
🔍 **Complete**: FastMCP aims to provide a full implementation of the core MCP specification
🔍 **Complete**: A comprehensive platform for all MCP use cases, from dev to prod
## `llms.txt`

View file

@ -0,0 +1,225 @@
---
title: Anthropic
sidebarTitle: Anthropic
description: Access FastMCP servers from the Anthropic Messages API
icon: message-smile
---
import { VersionBadge } from "/snippets/version-badge.mdx"
Anthropic supports MCP servers through the [MCP connector](https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector) feature in the Messages API, allowing you to extend AI capabilities with custom tools from remote MCP servers.
## Messages API
Anthropic's [Messages API](https://docs.anthropic.com/en/api/messages) supports MCP servers as remote tool sources. This tutorial will show you how to create a FastMCP server and deploy it to a public URL, then how to call it from the Messages API.
<Tip>
Currently, the MCP connector only accesses **tools** from MCP servers—it queries the `list_tools` endpoint and exposes those functions to Claude. Other MCP features like resources and prompts are not currently supported. You can read more about the MCP connector in the [Anthropic documentation](https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector).
</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(transport="sse", port=8000)
```
### Deploy the Server
Your server must be deployed to a public URL in order for Anthropic to access it. The MCP connector supports both SSE and Streamable HTTP transports.
For development, you can use tools like `ngrok` to temporarily expose a locally-running server to the internet. We'll do that for this example (you may need to install `ngrok` and create a free account), but you can use any other method to deploy your server.
Assuming you saved the above code as `server.py`, you can run the following two commands in two separate terminals to deploy your server and expose it to the internet:
<CodeGroup>
```bash FastMCP server
python server.py
```
```bash ngrok
ngrok http 8000
```
</CodeGroup>
<Warning>
This exposes your unauthenticated server to the internet. Only run this command in a safe environment if you understand the risks.
</Warning>
### Call the Server
To use the Messages API with MCP servers, you'll need to install the Anthropic Python SDK (not included with FastMCP):
```bash
pip install anthropic
```
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}
import anthropic
from rich import print
# Your server URL (replace with your actual URL)
url = 'https://your-server-url.com'
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1000,
messages=[{"role": "user", "content": "Roll a few dice!"}],
mcp_servers=[
{
"type": "url",
"url": f"{url}/sse",
"name": "dice-server",
}
],
extra_headers={
"anthropic-beta": "mcp-client-2025-04-04"
}
)
print(response.content)
```
If you run this code, you'll see something like the following output:
```text
I'll roll some dice for you! Let me use the dice rolling tool.
I rolled 3 dice and got: 4, 2, 6
The results were 4, 2, and 6. Would you like me to roll again or roll a different number of dice?
```
### Authentication
<VersionBadge version="2.6.0" />
The MCP connector supports OAuth authentication through authorization tokens, which means you can secure your server while still allowing Anthropic to access it.
#### Server Authentication
The simplest way to add authentication to the server is to use a bearer token scheme.
For this example, we'll quickly generate our own tokens with FastMCP's `RSAKeyPair` utility, but this may not be appropriate for production use. For more details, see the complete server-side [Bearer Auth](/servers/auth/bearer) documentation.
We'll start by creating an RSA key pair to sign and verify tokens.
```python
from fastmcp.server.auth.providers.bearer import RSAKeyPair
key_pair = RSAKeyPair.generate()
access_token = key_pair.create_token(audience="dice-server")
```
<Warning>
FastMCP's `RSAKeyPair` utility is for development and testing only.
</Warning>
Next, we'll create a `BearerAuthProvider` to authenticate the server.
```python
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider
auth = BearerAuthProvider(
public_key=key_pair.public_key,
audience="dice-server",
)
mcp = FastMCP(name="Dice Roller", auth=auth)
```
Here is a complete example that you can copy/paste. For simplicity and the purposes of this example only, it will print the token to the console. **Do NOT do this in production!**
```python server.py [expandable]
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider
from fastmcp.server.auth.providers.bearer import RSAKeyPair
import random
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)
```
#### Client Authentication
If you try to call the authenticated server with the same Anthropic code we wrote earlier, you'll get an error indicating that the server rejected the request because it's not authenticated.
```python
Error code: 400 - {
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "MCP server 'dice-server' requires authentication. Please provide an authorization_token.",
},
}
```
To authenticate the client, you can pass the token using the `authorization_token` parameter in your MCP server configuration:
```python {8, 21}
import anthropic
from rich import print
# Your server URL (replace with your actual URL)
url = 'https://your-server-url.com'
# Your access token (replace with your actual token)
access_token = 'your-access-token'
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1000,
messages=[{"role": "user", "content": "Roll a few dice!"}],
mcp_servers=[
{
"type": "url",
"url": f"{url}/sse",
"name": "dice-server",
"authorization_token": access_token
}
],
extra_headers={
"anthropic-beta": "mcp-client-2025-04-04"
}
)
print(response.content)
```
You should now see the dice roll results in the output.

View file

@ -0,0 +1,221 @@
---
title: Claude Desktop
sidebarTitle: Claude Desktop
description: Integrate FastMCP servers with Claude Desktop
icon: desktop
---
Claude Desktop supports MCP servers through local STDIO connections, allowing you to extend Claude's capabilities with custom tools, resources, and prompts from your FastMCP servers.
<Note>
This guide focuses specifically on using FastMCP servers with Claude Desktop. For general Claude Desktop MCP setup and official examples, see the [official Claude Desktop quickstart guide](https://modelcontextprotocol.io/quickstart/user).
</Note>
## Requirements
Claude Desktop requires MCP servers to run locally using STDIO transport. This means your server will communicate with Claude through standard input/output rather than HTTP.
<Tip>
If you 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.
</Tip>
## Create a Server
The examples in this guide will use the following simple dice-rolling server, saved as `server.py`.
```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()
```
## Install the Server
### FastMCP CLI
The easiest way to install a FastMCP server in Claude Desktop is using the `fastmcp install` command. This automatically handles the configuration and dependency management.
```bash
fastmcp install server.py
```
The install command supports the same `file.py:object` notation as the `run` command. If no object is specified, it will automatically look for a FastMCP server object named `mcp`, `server`, or `app` in your file:
```bash
# These are equivalent if your server object is named 'mcp'
fastmcp install server.py
fastmcp install server.py:mcp
# Use explicit object name if your server has a different name
fastmcp install server.py:my_custom_server
```
After installation, restart Claude Desktop completely. You should see a hammer icon (🔨) in the bottom left of the input box, indicating that MCP tools are available.
#### Dependencies
If your server has dependencies, include them with the `--with` flag:
```bash
fastmcp install server.py --with pandas --with requests
```
Alternatively, you can specify dependencies directly in your server code:
```python server.py
from fastmcp import FastMCP
mcp = FastMCP(
name="Dice Roller",
dependencies=["pandas", "requests"]
)
```
#### Environment Variables
<Warning>
Claude Desktop runs servers in a completely isolated environment with no access to your shell environment or locally installed applications. You must explicitly pass any environment variables your server needs.
</Warning>
If your server needs environment variables (like API keys), you must include them:
```bash
fastmcp install server.py --name "Weather Server" \
--env-var API_KEY=your-api-key \
--env-var DEBUG=true
```
Or load them from a `.env` file:
```bash
fastmcp install server.py --name "Weather Server" --env-file .env
```
<Warning>
- **`uv` must be installed and available in your system PATH**. Claude Desktop runs in its own isolated environment and needs `uv` to manage dependencies.
- **On macOS, it is recommended to install `uv` globally with Homebrew** so that Claude Desktop will detect it: `brew install uv`. Installing `uv` with other methods may not make it accessible to Claude Desktop.
</Warning>
### Manual Configuration
For more control over the configuration, you can manually edit Claude Desktop's configuration file. You can open the configuration file from Claude's developer settings, or find it in the following locations:
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
The configuration file is a JSON object with a `mcpServers` key, which contains the configuration for each MCP server.
```json
{
"mcpServers": {
"dice-roller": {
"command": "python",
"args": ["path/to/your/server.py"]
}
}
}
```
After updating the configuration file, restart Claude Desktop completely. Look for the hammer icon (🔨) to confirm your server is loaded.
#### Dependencies
If your server has dependencies, you can use `uv` or another package manager to set up the environment.
```json
{
"mcpServers": {
"dice-roller": {
"command": "uv",
"args": [
"run",
"--with", "pandas",
"--with", "requests",
"python",
"path/to/your/server.py"
]
}
}
}
```
<Warning>
- **`uv` must be installed and available in your system PATH**. Claude Desktop runs in its own isolated environment and needs `uv` to manage dependencies.
- **On macOS, it is recommended to install `uv` globally with Homebrew** so that Claude Desktop will detect it: `brew install uv`. Installing `uv` with other methods may not make it accessible to Claude Desktop.
</Warning>
#### Environment Variables
You can also specify environment variables in the configuration:
```json
{
"mcpServers": {
"weather-server": {
"command": "python",
"args": ["path/to/weather_server.py"],
"env": {
"API_KEY": "your-api-key",
"DEBUG": "true"
}
}
}
}
```
<Warning>
Claude Desktop runs servers in a completely isolated environment with no access to your shell environment or locally installed applications. You must explicitly pass any environment variables your server needs.
</Warning>
## Remote Servers
Claude Desktop only supports local STDIO servers, but FastMCP can create a proxy server that forwards requests to a remote HTTP server. You can install the proxy server in Claude Desktop.
Create a proxy server that connects to a remote HTTP server:
```python proxy_server.py
from fastmcp import FastMCP
# Create a proxy to a remote server
proxy = FastMCP.as_proxy(
"https://example.com/mcp/sse",
name="Remote Server Proxy"
)
if __name__ == "__main__":
proxy.run() # Runs via STDIO for Claude Desktop
```
### Authentication
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}
from fastmcp import FastMCP, Client
from fastmcp.client.auth import BearerAuth
# Create authenticated client
client = Client(
"https://api.example.com/mcp/sse",
auth=BearerAuth(token="your-access-token")
)
# Create proxy using the authenticated client
proxy = FastMCP.as_proxy(client, name="Authenticated Proxy")
if __name__ == "__main__":
proxy.run()
```

View file

@ -0,0 +1,222 @@
---
title: OpenAI
sidebarTitle: OpenAI
description: Access FastMCP servers from the OpenAI API
icon: message-smile
---
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
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, Assistants API, or ChatGPT. At this time, only the Responses API supports MCP.
</Note>
<Tip>
Currently, the Responses API only accesses **tools** from MCP servers—it queries the `list_tools` endpoint and exposes those functions to the AI agent. 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(transport="sse", port=8000)
```
### Deploy the Server
Your server must be deployed to a public URL in order for OpenAI to access it.
For development, you can use tools like `ngrok` to temporarily expose a locally-running server to the internet. We'll do that for this example (you may need to install `ngrok` and create a free account), but you can use any other method to deploy your server.
Assuming you saved the above code as `server.py`, you can run the following two commands in two separate terminals to deploy your server and expose it to the internet:
<CodeGroup>
```bash FastMCP server
python server.py
```
```bash ngrok
ngrok http 8000
```
</CodeGroup>
<Warning>
This exposes your unauthenticated server to the internet. Only run this command in a safe environment if you understand the risks.
</Warning>
### Call the Server
To use the Responses API, you'll need to install the OpenAI Python SDK (not included with FastMCP):
```bash
pip install openai
```
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}
from openai import OpenAI
# Your server URL (replace with your actual URL)
url = 'https://your-server-url.com'
client = OpenAI()
resp = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "mcp",
"server_label": "dice_server",
"server_url": f"{url}/sse",
"require_approval": "never",
},
],
input="Roll a few dice!",
)
print(resp.output_text)
```
If you run this code, you'll see something like the following output:
```text
You rolled 3 dice and got the following results: 6, 4, and 2!
```
### Authentication
<VersionBadge version="2.6.0" />
The Responses API can include headers to authenticate the request, which means you don't have to worry about your server being publicly accessible.
#### Server Authentication
The simplest way to add authentication to the server is to use a bearer token scheme.
For this example, we'll quickly generate our own tokens with FastMCP's `RSAKeyPair` utility, but this may not be appropriate for production use. For more details, see the complete server-side [Bearer Auth](/servers/auth/bearer) documentation.
We'll start by creating an RSA key pair to sign and verify tokens.
```python
from fastmcp.server.auth.providers.bearer import RSAKeyPair
key_pair = RSAKeyPair.generate()
access_token = key_pair.create_token(audience="dice-server")
```
<Warning>
FastMCP's `RSAKeyPair` utility is for development and testing only.
</Warning>
Next, we'll create a `BearerAuthProvider` to authenticate the server.
```python
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider
auth = BearerAuthProvider(
public_key=key_pair.public_key,
audience="dice-server",
)
mcp = FastMCP(name="Dice Roller", auth=auth)
```
Here is a complete example that you can copy/paste. For simplicity and the purposes of this example only, it will print the token to the console. **Do NOT do this in production!**
```python server.py [expandable]
from fastmcp import FastMCP
from fastmcp.server.auth import BearerAuthProvider
from fastmcp.server.auth.providers.bearer import RSAKeyPair
import random
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)
```
#### Client Authentication
If you try to call the authenticated server with the same OpenAI code we wrote earlier, you'll get an error like this:
```python
pythonAPIStatusError: Error code: 424 - {
"error": {
"message": "Error retrieving tool list from MCP server: 'dice_server'. Http status code: 401 (Unauthorized)",
"type": "external_connector_error",
"param": "tools",
"code": "http_error"
}
}
```
As expected, the server is rejecting the request because it's not authenticated.
To authenticate the client, you can pass the token in the `Authorization` header with the `Bearer` scheme:
```python {4, 7, 19-21} [expandable]
from openai import OpenAI
# Your server URL (replace with your actual URL)
url = 'https://your-server-url.com'
# Your access token (replace with your actual token)
access_token = 'your-access-token'
client = OpenAI()
resp = client.responses.create(
model="gpt-4.1",
tools=[
{
"type": "mcp",
"server_label": "dice_server",
"server_url": f"{url}/sse",
"require_approval": "never",
"headers": {
"Authorization": f"Bearer {access_token}"
}
},
],
input="Roll a few dice!",
)
print(resp.output_text)
```
You should now see the dice roll results in the output.

View file

@ -148,8 +148,8 @@ Install a MCP server in the Claude desktop app.
fastmcp install server.py
```
Note that for security reasons, Claude runs every MCP server in a completely isolated environment. Therefore, all dependencies must be explicitly specified using the `--with` and/or `--with-editable` options (following `uv` conventions) or by attaching them to your server in code via the `dependencies` parameter.
<Warning>
- **`uv` must be installed and available in your system PATH**. Claude Desktop runs in its own isolated environment and needs `uv` to manage dependencies.
- **On macOS, it is recommended to install `uv` globally with Homebrew** so that Claude Desktop will detect it: `brew install uv`. Installing `uv` with other methods may not make it accessible to Claude Desktop.
@ -159,21 +159,24 @@ Note that for security reasons, Claude runs every MCP server in a completely iso
The `install` command currently only sets up servers for STDIO transport. When installed in the Claude desktop app, your server will be run using STDIO regardless of any transport configuration in your code.
</Warning>
#### Options
#### Server Specification
| Option | Flag | Description |
| ------ | ---- | ----------- |
| Server Name | `--name`, `-n` | Custom name for the server |
| Editable Package | `--with-editable`, `-e` | Directory containing pyproject.toml to install in editable mode |
| Additional Packages | `--with` | Additional packages to install (can be used multiple times) |
| Environment Variables | `--env-var`, `-v` | Environment variables in KEY=VALUE format (can be used multiple times) |
| Environment File | `--env-file`, `-f` | Load environment variables from a .env file |
The `install` command supports the same `file.py:object` notation as the `run` command:
**Example**
1. `server.py` - imports the module and looks for a FastMCP object named `mcp`, `server`, or `app`. Errors if no such object is found.
2. `server.py:custom_name` - imports and uses the specified server object
**Examples**
```bash
# Install server with custom name, dependencies, and environment variables
fastmcp install server.py -n "My Analysis Server" -e . --with pandas --env-var API_KEY=12345
# Auto-detects server object (looks for 'mcp', 'server', or 'app')
fastmcp install server.py
# Uses specific server object
fastmcp install server.py:my_server
# With custom name and dependencies
fastmcp install server.py:my_server -n "My Analysis Server" --with pandas
```
### `version`

View file

@ -1,47 +0,0 @@
---
title: FastAPI Integration
sidebarTitle: FastAPI
description: Generate MCP servers from FastAPI apps
icon: square-bolt
---
import { VersionBadge } from '/snippets/version-badge.mdx'
<VersionBadge version="2.0.0" />
<Note>
**Documentation Moved**: The comprehensive FastAPI integration documentation has been moved to the [OpenAPI Integration](/patterns/openapi#fastapi-integration) page, where it's covered alongside all other OpenAPI features including route mapping and tags support.
</Note>
## Quick Start
FastMCP can automatically convert FastAPI applications into MCP servers:
```python
from fastapi import FastAPI
from fastmcp import FastMCP
# A FastAPI app
app = FastAPI()
@app.get("/items")
def list_items():
return [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]
@app.get("/items/{item_id}")
def get_item(item_id: int):
return {"id": item_id, "name": f"Item {item_id}"}
@app.post("/items")
def create_item(name: str):
return {"id": 3, "name": name}
# Create an MCP server from your FastAPI app
mcp = FastMCP.from_fastapi(app=app)
if __name__ == "__main__":
mcp.run() # Start the MCP server
```
<Tip>
For complete documentation including tag-based routing, route mapping configuration, timeout settings, authentication examples, and advanced configuration options, see the comprehensive [OpenAPI Integration documentation](/patterns/openapi#fastapi-integration).
</Tip>

View file

@ -25,7 +25,7 @@ mcp_with_instructions = FastMCP(
instructions="""
This server provides data analysis tools.
Call get_average() to analyze numerical data.
"""
""",
)
```

26
server.py Normal file
View file

@ -0,0 +1,26 @@
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

@ -131,16 +131,6 @@ class FastMCP(Generic[LifespanResultT]):
tools: list[Tool | Callable[..., Any]] | None = None,
**settings: Any,
):
if settings:
# TODO: remove settings. Deprecated since 2.3.4
warnings.warn(
"Passing runtime and transport-specific settings as kwargs "
"to the FastMCP constructor is deprecated (as of 2.3.4), "
"including most transport settings. If possible, provide settings when calling "
"run() instead.",
DeprecationWarning,
stacklevel=2,
)
self.settings = fastmcp.settings.ServerSettings(**settings)
# If mask_error_details is provided, override the settings value

View file

@ -9,17 +9,6 @@ from starlette.applications import Starlette
from fastmcp import Client, FastMCP
def test_fastmcp_kwargs_settings_deprecation_warning():
"""Test that passing settings as kwargs to FastMCP raises a deprecation warning."""
with pytest.warns(
DeprecationWarning,
match="Passing runtime and transport-specific settings as kwargs to the FastMCP constructor is deprecated",
):
server = FastMCP("TestServer", host="127.0.0.2", port=8001)
assert server.settings.host == "127.0.0.2"
assert server.settings.port == 8001
def test_sse_app_deprecation_warning():
"""Test that sse_app raises a deprecation warning."""
server = FastMCP("TestServer")