diff --git a/README.md b/README.md index d2e5ee1a7..c2552c910 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/docs/clients/auth/bearer.mdx b/docs/clients/auth/bearer.mdx index 4ad8103fb..ee8b66606 100644 --- a/docs/clients/auth/bearer.mdx +++ b/docs/clients/auth/bearer.mdx @@ -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 --- diff --git a/docs/clients/auth/oauth.mdx b/docs/clients/auth/oauth.mdx index e1973edce..36549237d 100644 --- a/docs/clients/auth/oauth.mdx +++ b/docs/clients/auth/oauth.mdx @@ -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. -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 diff --git a/docs/deployment/running-server.mdx b/docs/deployment/running-server.mdx index 58f9852bf..48cf389d2 100644 --- a/docs/deployment/running-server.mdx +++ b/docs/deployment/running-server.mdx @@ -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() -``` \ No newline at end of file +``` diff --git a/docs/docs.json b/docs/docs.json index d730d3254..fa5933534 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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" ] }, diff --git a/docs/integrations/anthropic.mdx b/docs/integrations/anthropic.mdx index b01f01ede..0920afce2 100644 --- a/docs/integrations/anthropic.mdx +++ b/docs/integrations/anthropic.mdx @@ -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} diff --git a/docs/integrations/claude-desktop.mdx b/docs/integrations/claude-desktop.mdx index 9212418f1..7edafa68b 100644 --- a/docs/integrations/claude-desktop.mdx +++ b/docs/integrations/claude-desktop.mdx @@ -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 --- diff --git a/docs/integrations/gemini.mdx b/docs/integrations/gemini.mdx new file mode 100644 index 000000000..d61d0feb0 --- /dev/null +++ b/docs/integrations/gemini.mdx @@ -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. + + +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. + + + +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. + + +### 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(""), +) +``` + +The rest of the code remains the same. + + diff --git a/docs/integrations/openai.mdx b/docs/integrations/openai.mdx index 2db6fdbcd..86f01e626 100644 --- a/docs/integrations/openai.mdx +++ b/docs/integrations/openai.mdx @@ -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} diff --git a/docs/servers/auth/bearer.mdx b/docs/servers/auth/bearer.mdx index 712c55518..c695c10e6 100644 --- a/docs/servers/auth/bearer.mdx +++ b/docs/servers/auth/bearer.mdx @@ -12,6 +12,10 @@ import { VersionBadge } from "/snippets/version-badge.mdx" Authentication and authorization are only relevant for HTTP-based transports. + +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. + + 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. -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. ### 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. -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. ### Basic Token Generation diff --git a/docs/servers/composition.mdx b/docs/servers/composition.mdx index 73b40affc..b1519b3f3 100644 --- a/docs/servers/composition.mdx +++ b/docs/servers/composition.mdx @@ -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. diff --git a/docs/servers/fastmcp.mdx b/docs/servers/fastmcp.mdx index 02e13aa27..598d056b6 100644 --- a/docs/servers/fastmcp.mdx +++ b/docs/servers/fastmcp.mdx @@ -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: If the serializer function raises an exception, the tool will fall back to the default JSON serialization to avoid breaking the server. - -## Authentication - - - -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. diff --git a/docs/snippets/version-badge.mdx b/docs/snippets/version-badge.mdx index d8ef3dd95..cbb28cb9d 100644 --- a/docs/snippets/version-badge.mdx +++ b/docs/snippets/version-badge.mdx @@ -1,13 +1,12 @@ export const VersionBadge = ({ version }) => { return ( -
+

New in version:  - {version} -

+ {version} +

- ); }; \ No newline at end of file diff --git a/docs/style.css b/docs/style.css index be64b3edd..a868d9d79 100644 --- a/docs/style.css +++ b/docs/style.css @@ -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; } diff --git a/server.py b/server.py deleted file mode 100644 index 0ddc68740..000000000 --- a/server.py +++ /dev/null @@ -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) diff --git a/src/fastmcp/client/auth/oauth.py b/src/fastmcp/client/auth/oauth.py index 43df9d442..e8d988c10 100644 --- a/src/fastmcp/client/auth/oauth.py +++ b/src/fastmcp/client/auth/oauth.py @@ -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( diff --git a/src/fastmcp/py.typed b/src/fastmcp/py.typed new file mode 100644 index 000000000..e69de29bb diff --git a/src/fastmcp/server/auth/providers/in_memory.py b/src/fastmcp/server/auth/providers/in_memory.py index 6494ef18b..941ecbc16 100644 --- a/src/fastmcp/server/auth/providers/in_memory.py +++ b/src/fastmcp/server/auth/providers/in_memory.py @@ -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__( diff --git a/tests/server/test_auth_integration.py b/tests/server/test_auth_integration.py index f64bd0843..0b6849264 100644 --- a/tests/server/test_auth_integration.py +++ b/tests/server/test_auth_integration.py @@ -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}")