diff --git a/docs/clients/auth/bearer.mdx b/docs/clients/auth/bearer.mdx index 478e1a957..0a5b57902 100644 --- a/docs/clients/auth/bearer.mdx +++ b/docs/clients/auth/bearer.mdx @@ -3,7 +3,6 @@ title: Bearer Token Authentication sidebarTitle: Bearer Auth description: Authenticate your FastMCP client with a Bearer token. icon: key -tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx" diff --git a/docs/docs.json b/docs/docs.json index 8947aef0b..7ae4c5fa4 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -65,7 +65,10 @@ { "group": "Essentials", "icon": "cube", - "pages": ["servers/server", "deployment/running-server"] + "pages": [ + "servers/server", + "deployment/running-server" + ] }, { "group": "Core Components", @@ -95,8 +98,8 @@ "icon": "shield-check", "pages": [ "servers/auth/authentication", + "servers/auth/remote-oauth", "servers/auth/token-verification", - "servers/auth/remote-authentication", "servers/auth/full-oauth-server" ] } @@ -108,7 +111,10 @@ { "group": "Essentials", "icon": "cube", - "pages": ["clients/client", "clients/transports"] + "pages": [ + "clients/client", + "clients/transports" + ] }, { "group": "Core Operations", @@ -134,7 +140,10 @@ { "group": "Authentication", "icon": "user-shield", - "pages": ["clients/auth/oauth", "clients/auth/bearer"] + "pages": [ + "clients/auth/oauth", + "clients/auth/bearer" + ] } ] }, @@ -181,12 +190,17 @@ }, { "anchor": "What's New", - "pages": ["updates", "changelog"] + "pages": [ + "updates", + "changelog" + ] }, { "anchor": "Community", "icon": "users", - "pages": ["community/showcase"] + "pages": [ + "community/showcase" + ] } ] }, @@ -275,10 +289,12 @@ "pages": [ "python-sdk/fastmcp-server-auth-providers-__init__", "python-sdk/fastmcp-server-auth-providers-bearer", - "python-sdk/fastmcp-server-auth-providers-bearer_env", - "python-sdk/fastmcp-server-auth-providers-in_memory" + "python-sdk/fastmcp-server-auth-providers-in_memory", + "python-sdk/fastmcp-server-auth-providers-jwt", + "python-sdk/fastmcp-server-auth-providers-workos" ] - } + }, + "python-sdk/fastmcp-server-auth-registry" ] }, "python-sdk/fastmcp-server-context", @@ -315,7 +331,6 @@ "group": "fastmcp.utilities", "pages": [ "python-sdk/fastmcp-utilities-__init__", - "python-sdk/fastmcp-utilities-cache", "python-sdk/fastmcp-utilities-cli", "python-sdk/fastmcp-utilities-components", "python-sdk/fastmcp-utilities-exceptions", diff --git a/docs/integrations/authkit.mdx b/docs/integrations/authkit.mdx index b61dfae14..36422258c 100644 --- a/docs/integrations/authkit.mdx +++ b/docs/integrations/authkit.mdx @@ -10,7 +10,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx" -This guide shows you how to secure your FastMCP server using **WorkOS AuthKit**, a complete authentication and user management solution. This integration uses the [**Remote Authentication**](/servers/auth/remote-authentication) pattern, where WorkOS handles user login and your FastMCP server validates the tokens. +This guide shows you how to secure your FastMCP server using **WorkOS AuthKit**, a complete authentication and user management solution. This integration uses the [**Remote OAuth**](/servers/auth/remote-oauth) pattern, where WorkOS handles user login and your FastMCP server validates the tokens. ## Configuration diff --git a/docs/integrations/chatgpt.mdx b/docs/integrations/chatgpt.mdx index 6b1c260df..2b552fe3b 100644 --- a/docs/integrations/chatgpt.mdx +++ b/docs/integrations/chatgpt.mdx @@ -3,7 +3,7 @@ title: ChatGPT 🤝 FastMCP sidebarTitle: ChatGPT description: Connect FastMCP servers to ChatGPT Deep Research icon: message-smile -tag: NEW + --- ChatGPT supports MCP servers through remote HTTP connections, allowing you to extend ChatGPT's capabilities with custom tools and knowledge from your FastMCP servers. diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdx index b0bac2748..91c072f39 100644 --- a/docs/integrations/claude-code.mdx +++ b/docs/integrations/claude-code.mdx @@ -3,7 +3,6 @@ title: Claude Code 🤝 FastMCP sidebarTitle: Claude Code description: Install and use FastMCP servers in Claude Code icon: message-smile -tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx" diff --git a/docs/integrations/eunomia-authorization.mdx b/docs/integrations/eunomia-authorization.mdx index 3287c696d..bccfbccdb 100644 --- a/docs/integrations/eunomia-authorization.mdx +++ b/docs/integrations/eunomia-authorization.mdx @@ -3,7 +3,6 @@ title: Eunomia Authorization 🤝 FastMCP sidebarTitle: Eunomia Auth description: Add policy-based authorization to your FastMCP servers with Eunomia icon: shield-check -tag: NEW --- Add **policy-based authorization** to your FastMCP servers with one-line code addition with the **[Eunomia][eunomia-github] authorization middleware**. diff --git a/docs/integrations/mcp-json-configuration.mdx b/docs/integrations/mcp-json-configuration.mdx index f3be1db06..73a815e2b 100644 --- a/docs/integrations/mcp-json-configuration.mdx +++ b/docs/integrations/mcp-json-configuration.mdx @@ -1,6 +1,6 @@ --- title: MCP JSON Configuration 🤝 FastMCP -sidebarTitle: MCP JSON +sidebarTitle: MCP.json description: Generate standard MCP configuration files for any compatible client icon: brackets-curly tag: NEW diff --git a/docs/integrations/openai.mdx b/docs/integrations/openai.mdx index 0e9f3c585..b75787228 100644 --- a/docs/integrations/openai.mdx +++ b/docs/integrations/openai.mdx @@ -3,7 +3,6 @@ title: OpenAI API 🤝 FastMCP sidebarTitle: OpenAI API description: Call FastMCP servers from the OpenAI API icon: message-code -tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx" diff --git a/docs/integrations/permit.mdx b/docs/integrations/permit.mdx index 9b1babe35..066f5b1ea 100644 --- a/docs/integrations/permit.mdx +++ b/docs/integrations/permit.mdx @@ -1,9 +1,8 @@ --- title: Permit.io Authorization 🤝 FastMCP -sidebarTitle: Permit.io Permissions +sidebarTitle: Permit.io description: Add fine-grained authorization to your FastMCP servers with Permit.io icon: shield-check -tag: NEW --- Add **policy-based authorization** to your FastMCP servers with one-line code addition with the **[Permit.io][permit-github] authorization middleware**. diff --git a/docs/python-sdk/fastmcp-cli-cli.mdx b/docs/python-sdk/fastmcp-cli-cli.mdx index 3c1bd0c60..749eb2616 100644 --- a/docs/python-sdk/fastmcp-cli-cli.mdx +++ b/docs/python-sdk/fastmcp-cli-cli.mdx @@ -36,7 +36,7 @@ Run an MCP server with the MCP Inspector for development. ### `run` ```python -run(server_spec: str) -> None +run(server_spec: str, *server_args: str) -> None ``` @@ -55,7 +55,7 @@ fastmcp run server.py -- --config config.json --debug - `server_spec`: Python file, object specification (file\:obj), MCPConfig file, or URL -### `inspect` +### `inspect` ```python inspect(server_spec: str) -> None diff --git a/docs/python-sdk/fastmcp-cli-run.mdx b/docs/python-sdk/fastmcp-cli-run.mdx index b1a477db1..00f8383d8 100644 --- a/docs/python-sdk/fastmcp-cli-run.mdx +++ b/docs/python-sdk/fastmcp-cli-run.mdx @@ -10,7 +10,7 @@ FastMCP run command implementation with enhanced type hints. ## Functions -### `is_url` +### `is_url` ```python is_url(path: str) -> bool @@ -20,7 +20,7 @@ is_url(path: str) -> bool Check if a string is a URL. -### `parse_file_path` +### `parse_file_path` ```python parse_file_path(server_spec: str) -> tuple[Path, str | None] @@ -36,7 +36,7 @@ Parse a file path that may include a server object specification. - Tuple of (file_path, server_object) -### `import_server` +### `import_server` ```python import_server(file: Path, server_object: str | None = None) -> Any @@ -53,7 +53,7 @@ Import a MCP server from a file. - The server object -### `run_with_uv` +### `run_with_uv` ```python run_with_uv(server_spec: str, python_version: str | None = None, with_packages: list[str] | None = None, with_requirements: Path | None = None, project: Path | None = None, transport: TransportType | None = None, host: str | None = None, port: int | None = None, path: str | None = None, log_level: LogLevelType | None = None, show_banner: bool = True) -> None @@ -76,7 +76,7 @@ Run a MCP server using uv run subprocess. - `show_banner`: Whether to show the server banner -### `create_client_server` +### `create_client_server` ```python create_client_server(url: str) -> Any @@ -92,7 +92,7 @@ Create a FastMCP server from a client URL. - A FastMCP server instance -### `create_mcp_config_server` +### `create_mcp_config_server` ```python create_mcp_config_server(mcp_config_path: Path) -> FastMCP[None] @@ -102,7 +102,7 @@ create_mcp_config_server(mcp_config_path: Path) -> FastMCP[None] Create a FastMCP server from a MCPConfig. -### `import_server_with_args` +### `import_server_with_args` ```python import_server_with_args(file: Path, server_object: str | None = None, server_args: list[str] | None = None) -> Any @@ -120,7 +120,7 @@ Import a server with optional command line arguments. - The imported server object -### `run_command` +### `run_command` ```python run_command(server_spec: str, transport: TransportType | None = None, host: str | None = None, port: int | None = None, path: str | None = None, log_level: LogLevelType | None = None, server_args: list[str] | None = None, show_banner: bool = True, use_direct_import: bool = False) -> None @@ -140,3 +140,9 @@ Run a MCP server or connect to a remote one. - `show_banner`: Whether to show the server banner - `use_direct_import`: Whether to use direct import instead of subprocess + +### `run_v1_server` + +```python +run_v1_server(server: FastMCP1x, host: str | None = None, port: int | None = None, transport: TransportType | None = None) -> None +``` diff --git a/docs/python-sdk/fastmcp-client-auth-oauth.mdx b/docs/python-sdk/fastmcp-client-auth-oauth.mdx index fe24548ee..a009f9319 100644 --- a/docs/python-sdk/fastmcp-client-auth-oauth.mdx +++ b/docs/python-sdk/fastmcp-client-auth-oauth.mdx @@ -7,30 +7,13 @@ sidebarTitle: oauth ## Functions -### `default_cache_dir` +### `default_cache_dir` ```python default_cache_dir() -> Path ``` -### `discover_oauth_metadata` - -```python -discover_oauth_metadata(server_base_url: str, httpx_kwargs: dict[str, Any] | None = None) -> OAuthMetadata | None -``` - - -Discover OAuth metadata from the server using RFC 8414 well-known endpoint. - -**Args:** -- `server_base_url`: Base URL of the OAuth server (e.g., "https\://example.com") -- `httpx_kwargs`: Additional kwargs for httpx client - -**Returns:** -- OAuth metadata if found, None otherwise - - -### `check_if_auth_required` +### `check_if_auth_required` ```python check_if_auth_required(mcp_url: str, httpx_kwargs: dict[str, Any] | None = None) -> bool @@ -43,32 +26,9 @@ Check if the MCP endpoint requires authentication by making a test request. - True if auth appears to be required, False otherwise -### `OAuth` - -```python -OAuth(mcp_url: str, scopes: str | list[str] | None = None, client_name: str = 'FastMCP Client', token_storage_cache_dir: Path | None = None, additional_client_metadata: dict[str, Any] | None = None) -> OAuthClientProvider -``` - - -Create an OAuthClientProvider for an MCP server. - -This is intended to be provided to the `auth` parameter of an -httpx.AsyncClient (or appropriate FastMCP client/transport instance) - -**Args:** -- `mcp_url`: Full URL to the MCP endpoint (e.g. "http\://host/mcp/sse/") -- `scopes`: OAuth scopes to request. Can be a -- `client_name`: Name for this client during registration -- `token_storage_cache_dir`: Directory for FileTokenStorage -- `additional_client_metadata`: Extra fields for OAuthClientMetadata - -**Returns:** -- OAuthClientProvider - - ## Classes -### `FileTokenStorage` +### `FileTokenStorage` File-based token storage implementation for OAuth credentials and tokens. @@ -79,7 +39,7 @@ Each instance is tied to a specific server URL for proper token isolation. **Methods:** -#### `get_base_url` +#### `get_base_url` ```python get_base_url(url: str) -> str @@ -88,7 +48,7 @@ get_base_url(url: str) -> str Extract the base URL (scheme + host) from a URL. -#### `get_cache_key` +#### `get_cache_key` ```python get_cache_key(self) -> str @@ -97,7 +57,7 @@ get_cache_key(self) -> str Generate a safe filesystem key from the server's base URL. -#### `get_tokens` +#### `get_tokens` ```python get_tokens(self) -> OAuthToken | None @@ -106,7 +66,7 @@ get_tokens(self) -> OAuthToken | None Load tokens from file storage. -#### `set_tokens` +#### `set_tokens` ```python set_tokens(self, tokens: OAuthToken) -> None @@ -115,7 +75,7 @@ set_tokens(self, tokens: OAuthToken) -> None Save tokens to file storage. -#### `get_client_info` +#### `get_client_info` ```python get_client_info(self) -> OAuthClientInformationFull | None @@ -124,7 +84,7 @@ get_client_info(self) -> OAuthClientInformationFull | None Load client information from file storage. -#### `set_client_info` +#### `set_client_info` ```python set_client_info(self, client_info: OAuthClientInformationFull) -> None @@ -133,7 +93,7 @@ set_client_info(self, client_info: OAuthClientInformationFull) -> None Save client information to file storage. -#### `clear` +#### `clear` ```python clear(self) -> None @@ -142,7 +102,7 @@ clear(self) -> None Clear all cached data for this server. -#### `clear_all` +#### `clear_all` ```python clear_all(cls, cache_dir: Path | None = None) -> None @@ -150,3 +110,32 @@ clear_all(cls, cache_dir: Path | None = None) -> None Clear all cached data for all servers. + +### `OAuth` + + +OAuth client provider for MCP servers with browser-based authentication. + +This class provides OAuth authentication for FastMCP clients by opening +a browser for user authorization and running a local callback server. + + +**Methods:** + +#### `redirect_handler` + +```python +redirect_handler(self, authorization_url: str) -> None +``` + +Open browser for authorization. + + +#### `callback_handler` + +```python +callback_handler(self) -> tuple[str, str | None] +``` + +Handle OAuth callback and return (auth_code, state). + diff --git a/docs/python-sdk/fastmcp-client-transports.mdx b/docs/python-sdk/fastmcp-client-transports.mdx index 0a1c7190d..3650b7f93 100644 --- a/docs/python-sdk/fastmcp-client-transports.mdx +++ b/docs/python-sdk/fastmcp-client-transports.mdx @@ -7,7 +7,7 @@ sidebarTitle: transports ## Functions -### `infer_transport` +### `infer_transport` ```python infer_transport(transport: ClientTransport | FastMCP | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str) -> ClientTransport @@ -57,13 +57,13 @@ transport = infer_transport(config) ## Classes -### `SessionKwargs` +### `SessionKwargs` Keyword arguments for the MCP ClientSession constructor. -### `ClientTransport` +### `ClientTransport` Abstract base class for different MCP client transport mechanisms. @@ -74,7 +74,7 @@ to an MCP server, and providing a ClientSession within an async context. **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] @@ -93,7 +93,7 @@ within this context. constructor (e.g., callbacks, timeouts). -#### `close` +#### `close` ```python close(self) @@ -102,7 +102,7 @@ close(self) Close the transport. -### `WSTransport` +### `WSTransport` Transport implementation that connects to an MCP server via WebSockets. @@ -110,13 +110,13 @@ Transport implementation that connects to an MCP server via WebSockets. **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] ``` -### `SSETransport` +### `SSETransport` Transport implementation that connects to an MCP server via Server-Sent Events. @@ -124,13 +124,13 @@ Transport implementation that connects to an MCP server via Server-Sent Events. **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] ``` -### `StreamableHttpTransport` +### `StreamableHttpTransport` Transport implementation that connects to an MCP server via Streamable HTTP Requests. @@ -138,13 +138,13 @@ Transport implementation that connects to an MCP server via Streamable HTTP Requ **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] ``` -### `StdioTransport` +### `StdioTransport` Base transport for connecting to an MCP server via subprocess with stdio. @@ -155,61 +155,67 @@ transports like Python, Node, Uvx, etc. **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] ``` -#### `connect` +#### `connect` ```python connect(self, **session_kwargs: Unpack[SessionKwargs]) -> ClientSession | None ``` -#### `disconnect` +#### `disconnect` ```python disconnect(self) ``` -#### `close` +#### `close` ```python close(self) ``` -### `PythonStdioTransport` +### `PythonStdioTransport` Transport for running Python scripts. -### `FastMCPStdioTransport` +### `FastMCPStdioTransport` Transport for running FastMCP servers using the FastMCP CLI. -### `NodeStdioTransport` +### `NodeStdioTransport` Transport for running Node.js scripts. -### `UvxStdioTransport` +### `UvStdioTransport` + + +Transport for running commands via the uv tool. + + +### `UvxStdioTransport` Transport for running commands via the uvx tool. -### `NpxStdioTransport` +### `NpxStdioTransport` Transport for running commands via the npx tool. -### `FastMCPTransport` +### `FastMCPTransport` In-memory transport for FastMCP servers. @@ -222,13 +228,13 @@ tests or scenarios where client and server run in the same runtime. **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] ``` -### `MCPConfigTransport` +### `MCPConfigTransport` Transport for connecting to one or more MCP servers defined in an MCPConfig. @@ -281,7 +287,7 @@ async with client: **Methods:** -#### `connect_session` +#### `connect_session` ```python connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession] diff --git a/docs/python-sdk/fastmcp-prompts-prompt.mdx b/docs/python-sdk/fastmcp-prompts-prompt.mdx index 13019b9f3..bb475a0fd 100644 --- a/docs/python-sdk/fastmcp-prompts-prompt.mdx +++ b/docs/python-sdk/fastmcp-prompts-prompt.mdx @@ -57,10 +57,10 @@ to_mcp_prompt(self, **overrides: Any) -> MCPPrompt Convert the prompt to an MCP prompt. -#### `from_function` +#### `from_function` ```python -from_function(fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionPrompt +from_function(fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, enabled: bool | None = None, meta: dict[str, Any] | None = None) -> FunctionPrompt ``` Create a Prompt from a function. @@ -72,7 +72,7 @@ The function can return: - A sequence of any of the above -#### `render` +#### `render` ```python render(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage] @@ -81,7 +81,7 @@ render(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage] Render the prompt with arguments. -### `FunctionPrompt` +### `FunctionPrompt` A prompt that is a function. @@ -89,10 +89,10 @@ A prompt that is a function. **Methods:** -#### `from_function` +#### `from_function` ```python -from_function(cls, fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionPrompt +from_function(cls, fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, enabled: bool | None = None, meta: dict[str, Any] | None = None) -> FunctionPrompt ``` Create a Prompt from a function. @@ -104,7 +104,7 @@ The function can return: - A sequence of any of the above -#### `render` +#### `render` ```python render(self, arguments: dict[str, Any] | None = None) -> list[PromptMessage] diff --git a/docs/python-sdk/fastmcp-resources-resource.mdx b/docs/python-sdk/fastmcp-resources-resource.mdx index 46969c09c..1b09260ae 100644 --- a/docs/python-sdk/fastmcp-resources-resource.mdx +++ b/docs/python-sdk/fastmcp-resources-resource.mdx @@ -10,7 +10,7 @@ Base classes and interfaces for FastMCP resources. ## Classes -### `Resource` +### `Resource` Base class for all resources. @@ -18,25 +18,25 @@ Base class for all resources. **Methods:** -#### `enable` +#### `enable` ```python enable(self) -> None ``` -#### `disable` +#### `disable` ```python disable(self) -> None ``` -#### `from_function` +#### `from_function` ```python -from_function(fn: Callable[..., Any], uri: str | AnyUrl, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResource +from_function(fn: Callable[..., Any], uri: str | AnyUrl, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None) -> FunctionResource ``` -#### `set_default_mime_type` +#### `set_default_mime_type` ```python set_default_mime_type(cls, mime_type: str | None) -> str @@ -45,7 +45,7 @@ set_default_mime_type(cls, mime_type: str | None) -> str Set default MIME type if not provided. -#### `set_default_name` +#### `set_default_name` ```python set_default_name(self) -> Self @@ -54,7 +54,7 @@ set_default_name(self) -> Self Set default name from URI if not provided. -#### `read` +#### `read` ```python read(self) -> str | bytes @@ -63,7 +63,7 @@ read(self) -> str | bytes Read the resource content. -#### `to_mcp_resource` +#### `to_mcp_resource` ```python to_mcp_resource(self, **overrides: Any) -> MCPResource @@ -72,7 +72,7 @@ to_mcp_resource(self, **overrides: Any) -> MCPResource Convert the resource to an MCPResource. -#### `key` +#### `key` ```python key(self) -> str @@ -84,7 +84,7 @@ keys having a certain value, as the same tool loaded from different hierarchies of servers may have different keys. -### `FunctionResource` +### `FunctionResource` A resource that defers data loading by wrapping a function. @@ -101,16 +101,16 @@ The function can return: **Methods:** -#### `from_function` +#### `from_function` ```python -from_function(cls, fn: Callable[..., Any], uri: str | AnyUrl, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResource +from_function(cls, fn: Callable[..., Any], uri: str | AnyUrl, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None) -> FunctionResource ``` Create a FunctionResource from a function. -#### `read` +#### `read` ```python read(self) -> str | bytes diff --git a/docs/python-sdk/fastmcp-resources-template.mdx b/docs/python-sdk/fastmcp-resources-template.mdx index 014d0b121..80feda176 100644 --- a/docs/python-sdk/fastmcp-resources-template.mdx +++ b/docs/python-sdk/fastmcp-resources-template.mdx @@ -10,13 +10,13 @@ Resource template functionality. ## Functions -### `build_regex` +### `build_regex` ```python build_regex(template: str) -> re.Pattern ``` -### `match_uri_template` +### `match_uri_template` ```python match_uri_template(uri: str, uri_template: str) -> dict[str, str] | None @@ -24,7 +24,7 @@ match_uri_template(uri: str, uri_template: str) -> dict[str, str] | None ## Classes -### `ResourceTemplate` +### `ResourceTemplate` A template for dynamically creating resources. @@ -32,25 +32,25 @@ A template for dynamically creating resources. **Methods:** -#### `enable` +#### `enable` ```python enable(self) -> None ``` -#### `disable` +#### `disable` ```python disable(self) -> None ``` -#### `from_function` +#### `from_function` ```python -from_function(fn: Callable[..., Any], uri_template: str, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResourceTemplate +from_function(fn: Callable[..., Any], uri_template: str, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None) -> FunctionResourceTemplate ``` -#### `set_default_mime_type` +#### `set_default_mime_type` ```python set_default_mime_type(cls, mime_type: str | None) -> str @@ -59,7 +59,7 @@ set_default_mime_type(cls, mime_type: str | None) -> str Set default MIME type if not provided. -#### `matches` +#### `matches` ```python matches(self, uri: str) -> dict[str, Any] | None @@ -68,7 +68,7 @@ matches(self, uri: str) -> dict[str, Any] | None Check if URI matches template and extract parameters. -#### `read` +#### `read` ```python read(self, arguments: dict[str, Any]) -> str | bytes @@ -77,7 +77,7 @@ read(self, arguments: dict[str, Any]) -> str | bytes Read the resource content. -#### `create_resource` +#### `create_resource` ```python create_resource(self, uri: str, params: dict[str, Any]) -> Resource @@ -86,7 +86,7 @@ create_resource(self, uri: str, params: dict[str, Any]) -> Resource Create a resource from the template with the given parameters. -#### `to_mcp_template` +#### `to_mcp_template` ```python to_mcp_template(self, **overrides: Any) -> MCPResourceTemplate @@ -95,7 +95,7 @@ to_mcp_template(self, **overrides: Any) -> MCPResourceTemplate Convert the resource template to an MCPResourceTemplate. -#### `from_mcp_template` +#### `from_mcp_template` ```python from_mcp_template(cls, mcp_template: MCPResourceTemplate) -> ResourceTemplate @@ -104,7 +104,7 @@ from_mcp_template(cls, mcp_template: MCPResourceTemplate) -> ResourceTemplate Creates a FastMCP ResourceTemplate from a raw MCP ResourceTemplate object. -#### `key` +#### `key` ```python key(self) -> str @@ -116,7 +116,7 @@ keys having a certain value, as the same tool loaded from different hierarchies of servers may have different keys. -### `FunctionResourceTemplate` +### `FunctionResourceTemplate` A template for dynamically creating resources. @@ -124,7 +124,7 @@ A template for dynamically creating resources. **Methods:** -#### `read` +#### `read` ```python read(self, arguments: dict[str, Any]) -> str | bytes @@ -133,10 +133,10 @@ read(self, arguments: dict[str, Any]) -> str | bytes Read the resource content. -#### `from_function` +#### `from_function` ```python -from_function(cls, fn: Callable[..., Any], uri_template: str, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResourceTemplate +from_function(cls, fn: Callable[..., Any], uri_template: str, name: str | None = None, title: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None) -> FunctionResourceTemplate ``` Create a template from a function. diff --git a/docs/python-sdk/fastmcp-server-auth-auth.mdx b/docs/python-sdk/fastmcp-server-auth-auth.mdx index d7e2e4960..7f17f1c43 100644 --- a/docs/python-sdk/fastmcp-server-auth-auth.mdx +++ b/docs/python-sdk/fastmcp-server-auth-auth.mdx @@ -7,11 +7,86 @@ sidebarTitle: auth ## Classes -### `OAuthProvider` +### `AuthProvider` + + +Base class for all FastMCP authentication providers. + +This class provides a unified interface for all authentication providers, +whether they are simple token verifiers or full OAuth authorization servers. +All providers must be able to verify tokens and can optionally provide +custom authentication routes. + **Methods:** -#### `verify_token` +#### `verify_token` + +```python +verify_token(self, token: str) -> AccessToken | None +``` + +Verify a bearer token and return access info if valid. + +All auth providers must implement token verification. + +**Args:** +- `token`: The token string to validate + +**Returns:** +- AccessToken object if valid, None if invalid or expired + + +#### `customize_auth_routes` + +```python +customize_auth_routes(self, routes: list[Route]) -> list[Route] +``` + +Customize authentication routes after standard creation. + +This method allows providers to modify or add to the standard OAuth routes. +The default implementation returns the routes unchanged. + +**Args:** +- `routes`: List of standard routes (may be empty for token-only providers) + +**Returns:** +- List of routes (potentially modified or extended) + + +### `TokenVerifier` + + +Base class for token verifiers (Resource Servers). + +This class provides token verification capability without OAuth server functionality. +Token verifiers typically don't provide authentication routes by default. + + +**Methods:** + +#### `verify_token` + +```python +verify_token(self, token: str) -> AccessToken | None +``` + +Verify a bearer token and return access info if valid. + + +### `OAuthProvider` + + +OAuth Authorization Server provider. + +This class provides full OAuth server functionality including client registration, +authorization flows, token issuance, and token verification. + + +**Methods:** + +#### `verify_token` ```python verify_token(self, token: str) -> AccessToken | None @@ -28,3 +103,22 @@ to our existing load_access_token method. **Returns:** - AccessToken object if valid, None if invalid or expired + +#### `customize_auth_routes` + +```python +customize_auth_routes(self, routes: list[Route]) -> list[Route] +``` + +Customize OAuth authentication routes after standard creation. + +This method allows providers to modify the standard OAuth routes +returned by create_auth_routes. The default implementation returns +the routes unchanged. + +**Args:** +- `routes`: List of standard OAuth routes from create_auth_routes + +**Returns:** +- List of routes (potentially modified) + diff --git a/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdx b/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdx index f68341f8d..3cfbf0239 100644 --- a/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdx +++ b/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdx @@ -5,148 +5,9 @@ sidebarTitle: bearer # `fastmcp.server.auth.providers.bearer` -## Classes -### `JWKData` +Backwards compatibility shim for BearerAuthProvider. +The BearerAuthProvider class has been moved to fastmcp.server.auth.providers.jwt.JWTVerifier +for better organization. This module provides a backwards-compatible import. -JSON Web Key data structure. - - -### `JWKSData` - - -JSON Web Key Set data structure. - - -### `RSAKeyPair` - -**Methods:** - -#### `generate` - -```python -generate(cls) -> 'RSAKeyPair' -``` - -Generate an RSA key pair for testing. - -**Returns:** -- (private_key_pem, public_key_pem) - - -#### `create_token` - -```python -create_token(self, subject: str = 'fastmcp-user', issuer: str = 'https://fastmcp.example.com', audience: str | list[str] | None = None, scopes: list[str] | None = None, expires_in_seconds: int = 3600, additional_claims: dict[str, Any] | None = None, kid: str | None = None) -> str -``` - -Generate a test JWT token for testing purposes. - -**Args:** -- `private_key_pem`: RSA private key in PEM format -- `subject`: Subject claim (usually user ID) -- `issuer`: Issuer claim -- `audience`: Audience claim - can be a string or list of strings (optional) -- `scopes`: List of scopes to include -- `expires_in_seconds`: Token expiration time in seconds -- `additional_claims`: Any additional claims to include -- `kid`: Key ID for JWKS lookup (optional) - -**Returns:** -- Signed JWT token string - - -### `BearerAuthProvider` - - -Simple JWT Bearer Token validator for hosted MCP servers. -Uses RS256 asymmetric encryption by default but supports all JWA algorithms. Supports either static public key -or JWKS URI for key rotation. - -Note that this provider DOES NOT permit client registration or revocation, or any OAuth flows. -It is intended to be used with a control plane that manages clients and tokens. - - -**Methods:** - -#### `load_access_token` - -```python -load_access_token(self, token: str) -> AccessToken | None -``` - -Validates the provided JWT bearer token. - -**Args:** -- `token`: The JWT token string to validate - -**Returns:** -- AccessToken object if valid, None if invalid or expired - - -#### `verify_token` - -```python -verify_token(self, token: str) -> AccessToken | None -``` - -Verify a bearer token and return access info if valid. - -This method implements the TokenVerifier protocol by delegating -to our existing load_access_token method. - -**Args:** -- `token`: The JWT token string to validate - -**Returns:** -- AccessToken object if valid, None if invalid or expired - - -#### `get_client` - -```python -get_client(self, client_id: str) -> OAuthClientInformationFull | None -``` - -#### `register_client` - -```python -register_client(self, client_info: OAuthClientInformationFull) -> None -``` - -#### `authorize` - -```python -authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str -``` - -#### `load_authorization_code` - -```python -load_authorization_code(self, client: OAuthClientInformationFull, authorization_code: str) -> AuthorizationCode | None -``` - -#### `exchange_authorization_code` - -```python -exchange_authorization_code(self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode) -> OAuthToken -``` - -#### `load_refresh_token` - -```python -load_refresh_token(self, client: OAuthClientInformationFull, refresh_token: str) -> RefreshToken | None -``` - -#### `exchange_refresh_token` - -```python -exchange_refresh_token(self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken -``` - -#### `revoke_token` - -```python -revoke_token(self, token: AccessToken | RefreshToken) -> None -``` diff --git a/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx b/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx index cb97653c8..bb84b81ce 100644 --- a/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx +++ b/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx @@ -16,19 +16,19 @@ It simulates the OAuth 2.1 flow locally without external calls. **Methods:** -#### `get_client` +#### `get_client` ```python get_client(self, client_id: str) -> OAuthClientInformationFull | None ``` -#### `register_client` +#### `register_client` ```python register_client(self, client_info: OAuthClientInformationFull) -> None ``` -#### `authorize` +#### `authorize` ```python authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str @@ -38,37 +38,37 @@ Simulates user authorization and generates an authorization code. Returns a redirect URI with the code and state. -#### `load_authorization_code` +#### `load_authorization_code` ```python load_authorization_code(self, client: OAuthClientInformationFull, authorization_code: str) -> AuthorizationCode | None ``` -#### `exchange_authorization_code` +#### `exchange_authorization_code` ```python exchange_authorization_code(self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode) -> OAuthToken ``` -#### `load_refresh_token` +#### `load_refresh_token` ```python load_refresh_token(self, client: OAuthClientInformationFull, refresh_token: str) -> RefreshToken | None ``` -#### `exchange_refresh_token` +#### `exchange_refresh_token` ```python exchange_refresh_token(self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken ``` -#### `load_access_token` +#### `load_access_token` ```python load_access_token(self, token: str) -> AccessToken | None ``` -#### `verify_token` +#### `verify_token` ```python verify_token(self, token: str) -> AccessToken | None @@ -86,7 +86,7 @@ to our existing load_access_token method. - AccessToken object if valid, None if invalid or expired -#### `revoke_token` +#### `revoke_token` ```python revoke_token(self, token: AccessToken | RefreshToken) -> None diff --git a/docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx b/docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx new file mode 100644 index 000000000..c40254b10 --- /dev/null +++ b/docs/python-sdk/fastmcp-server-auth-providers-jwt.mdx @@ -0,0 +1,149 @@ +--- +title: jwt +sidebarTitle: jwt +--- + +# `fastmcp.server.auth.providers.jwt` + + +TokenVerifier implementations for FastMCP. + +## Classes + +### `JWKData` + + +JSON Web Key data structure. + + +### `JWKSData` + + +JSON Web Key Set data structure. + + +### `RSAKeyPair` + + +RSA key pair for JWT testing. + + +**Methods:** + +#### `generate` + +```python +generate(cls) -> RSAKeyPair +``` + +Generate an RSA key pair for testing. + +**Returns:** +- Generated key pair + + +#### `create_token` + +```python +create_token(self, subject: str = 'fastmcp-user', issuer: str = 'https://fastmcp.example.com', audience: str | list[str] | None = None, scopes: list[str] | None = None, expires_in_seconds: int = 3600, additional_claims: dict[str, Any] | None = None, kid: str | None = None) -> str +``` + +Generate a test JWT token for testing purposes. + +**Args:** +- `subject`: Subject claim (usually user ID) +- `issuer`: Issuer claim +- `audience`: Audience claim - can be a string or list of strings (optional) +- `scopes`: List of scopes to include +- `expires_in_seconds`: Token expiration time in seconds +- `additional_claims`: Any additional claims to include +- `kid`: Key ID to include in header + + +### `JWTVerifierSettings` + + +Settings for JWT token verification. + + +### `JWTVerifier` + + +JWT token verifier using public key or JWKS. + +This verifier validates JWT tokens signed by an external issuer. It's ideal for +scenarios where you have a centralized identity provider (like Auth0, Okta, or +your own OAuth server) that issues JWTs, and your FastMCP server acts as a +resource server validating those tokens. + +Use this when: +- You have JWT tokens issued by an external service +- You want asymmetric key verification (public/private key pairs) +- You need JWKS support for automatic key rotation +- Your tokens contain standard OAuth scopes and claims + + +**Methods:** + +#### `load_access_token` + +```python +load_access_token(self, token: str) -> AccessToken | None +``` + +Validates the provided JWT bearer token. + +**Args:** +- `token`: The JWT token string to validate + +**Returns:** +- AccessToken object if valid, None if invalid or expired + + +#### `verify_token` + +```python +verify_token(self, token: str) -> AccessToken | None +``` + +Verify a bearer token and return access info if valid. + +This method implements the TokenVerifier protocol by delegating +to our existing load_access_token method. + +**Args:** +- `token`: The JWT token string to validate + +**Returns:** +- AccessToken object if valid, None if invalid or expired + + +### `StaticTokenVerifier` + + +Simple static token verifier for testing and development. + +This verifier validates tokens against a predefined dictionary of valid token +strings and their associated claims. When a token string matches a key in the +dictionary, the verifier returns the corresponding claims as if the token was +validated by a real authorization server. + +Use this when: +- You're developing or testing locally without a real OAuth server +- You need predictable tokens for automated testing +- You want to simulate different users/scopes without complex setup +- You're prototyping and need simple API key-style authentication + +WARNING: Never use this in production - tokens are stored in plain text! + + +**Methods:** + +#### `verify_token` + +```python +verify_token(self, token: str) -> AccessToken | None +``` + +Verify token against static token dictionary. + diff --git a/docs/python-sdk/fastmcp-server-auth-providers-workos.mdx b/docs/python-sdk/fastmcp-server-auth-providers-workos.mdx new file mode 100644 index 000000000..6732b97ff --- /dev/null +++ b/docs/python-sdk/fastmcp-server-auth-providers-workos.mdx @@ -0,0 +1,58 @@ +--- +title: workos +sidebarTitle: workos +--- + +# `fastmcp.server.auth.providers.workos` + +## Classes + +### `AuthKitProviderSettings` + +### `AuthKitProvider` + + +WorkOS AuthKit metadata provider for DCR (Dynamic Client Registration). + +This provider implements WorkOS AuthKit integration using metadata forwarding +instead of OAuth proxying. This is the recommended approach for WorkOS DCR +as it allows WorkOS to handle the OAuth flow directly while FastMCP acts +as a resource server. + +IMPORTANT SETUP REQUIREMENTS: + +1. Enable Dynamic Client Registration in WorkOS Dashboard: + - Go to Applications → Configuration + - Toggle "Dynamic Client Registration" to enabled + +2. Configure your FastMCP server URL as a callback: + - Add your server URL to the Redirects tab in WorkOS dashboard + - Example: https://your-fastmcp-server.com/oauth2/callback + +For detailed setup instructions, see: +https://workos.com/docs/authkit/mcp/integrating/token-verification + + +**Methods:** + +#### `verify_token` + +```python +verify_token(self, token: str) -> AccessToken | None +``` + +Verify a WorkOS token using the configured token verifier. + + +#### `customize_auth_routes` + +```python +customize_auth_routes(self, routes: list[BaseRoute]) -> list[BaseRoute] +``` + +Add AuthKit metadata endpoints. + +This adds: +- /.well-known/oauth-authorization-server (forwards AuthKit metadata) +- /.well-known/oauth-protected-resource (returns FastMCP resource info) + diff --git a/docs/python-sdk/fastmcp-server-auth-registry.mdx b/docs/python-sdk/fastmcp-server-auth-registry.mdx new file mode 100644 index 000000000..8815d4b55 --- /dev/null +++ b/docs/python-sdk/fastmcp-server-auth-registry.mdx @@ -0,0 +1,43 @@ +--- +title: registry +sidebarTitle: registry +--- + +# `fastmcp.server.auth.registry` + + +Provider registry for FastMCP auth providers. + +## Functions + +### `register_provider` + +```python +register_provider(name: str) -> Callable[[type[T]], type[T]] +``` + + +Decorator to register an auth provider with a given name. + +**Args:** +- `name`: The name to register the provider under (e.g., 'AUTHKIT') + +**Returns:** +- The decorated class + + +### `get_registered_provider` + +```python +get_registered_provider(name: str) -> type[AuthProvider] +``` + + +Get a registered provider by name. + +**Args:** +- `name`: The provider name (case-insensitive) + +**Returns:** +- The provider class if found, None otherwise + diff --git a/docs/python-sdk/fastmcp-server-context.mdx b/docs/python-sdk/fastmcp-server-context.mdx index b61ba25d7..cc3c79237 100644 --- a/docs/python-sdk/fastmcp-server-context.mdx +++ b/docs/python-sdk/fastmcp-server-context.mdx @@ -7,7 +7,7 @@ sidebarTitle: context ## Functions -### `set_context` +### `set_context` ```python set_context(context: Context) -> Generator[Context, None, None] @@ -15,7 +15,16 @@ set_context(context: Context) -> Generator[Context, None, None] ## Classes -### `Context` +### `LogData` + + +Data object for passing log arguments to client-side handlers. + +This provides an interface to match the Python standard library logging, +for compatibility with structured logging. + + +### `Context` Context object providing access to MCP capabilities. @@ -63,10 +72,10 @@ The context is optional - tools that don't need it can omit the parameter. **Methods:** -#### `request_context` +#### `request_context` ```python -request_context(self) -> RequestContext +request_context(self) -> RequestContext[ServerSession, Any, Request] ``` Access to the underlying request context. @@ -74,7 +83,7 @@ Access to the underlying request context. If called outside of a request context, this will raise a ValueError. -#### `report_progress` +#### `report_progress` ```python report_progress(self, progress: float, total: float | None = None, message: str | None = None) -> None @@ -87,7 +96,7 @@ Report progress for the current operation. - `total`: Optional total value e.g. 100 -#### `read_resource` +#### `read_resource` ```python read_resource(self, uri: str | AnyUrl) -> list[ReadResourceContents] @@ -102,10 +111,10 @@ Read a resource by URI. - The resource content as either text or bytes -#### `log` +#### `log` ```python -log(self, message: str, level: LoggingLevel | None = None, logger_name: str | None = None) -> None +log(self, message: str, level: LoggingLevel | None = None, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None ``` Send a log message to the client. @@ -115,9 +124,10 @@ Send a log message to the client. - `level`: Optional log level. One of "debug", "info", "notice", "warning", "error", "critical", "alert", or "emergency". Default is "info". - `logger_name`: Optional logger name +- `extra`: Optional mapping for additional arguments -#### `client_id` +#### `client_id` ```python client_id(self) -> str | None @@ -126,7 +136,7 @@ client_id(self) -> str | None Get the client ID if available. -#### `request_id` +#### `request_id` ```python request_id(self) -> str @@ -135,24 +145,24 @@ request_id(self) -> str Get the unique ID for this request. -#### `session_id` +#### `session_id` ```python -session_id(self) -> str | None +session_id(self) -> str ``` -Get the MCP session ID for HTTP transports. +Get the MCP session ID for ALL transports. Returns the session ID that can be used as a key for session-based data storage (e.g., Redis) to share data between tool calls within the same client session. **Returns:** -- The session ID for HTTP transports (SSE, StreamableHTTP), or None -- for stdio and in-memory transports which don't use session IDs. +- The session ID for StreamableHTTP transports, or a generated ID +- for other transports. -#### `session` +#### `session` ```python session(self) -> ServerSession @@ -161,43 +171,43 @@ session(self) -> ServerSession Access to the underlying session for advanced usage. -#### `debug` +#### `debug` ```python -debug(self, message: str, logger_name: str | None = None) -> None +debug(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None ``` Send a debug log message. -#### `info` +#### `info` ```python -info(self, message: str, logger_name: str | None = None) -> None +info(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None ``` Send an info log message. -#### `warning` +#### `warning` ```python -warning(self, message: str, logger_name: str | None = None) -> None +warning(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None ``` Send a warning log message. -#### `error` +#### `error` ```python -error(self, message: str, logger_name: str | None = None) -> None +error(self, message: str, logger_name: str | None = None, extra: Mapping[str, Any] | None = None) -> None ``` Send an error log message. -#### `list_roots` +#### `list_roots` ```python list_roots(self) -> list[Root] @@ -206,7 +216,7 @@ list_roots(self) -> list[Root] List the roots available to the server, as indicated by the client. -#### `send_tool_list_changed` +#### `send_tool_list_changed` ```python send_tool_list_changed(self) -> None @@ -215,7 +225,7 @@ send_tool_list_changed(self) -> None Send a tool list changed notification to the client. -#### `send_resource_list_changed` +#### `send_resource_list_changed` ```python send_resource_list_changed(self) -> None @@ -224,7 +234,7 @@ send_resource_list_changed(self) -> None Send a resource list changed notification to the client. -#### `send_prompt_list_changed` +#### `send_prompt_list_changed` ```python send_prompt_list_changed(self) -> None @@ -233,7 +243,7 @@ send_prompt_list_changed(self) -> None Send a prompt list changed notification to the client. -#### `sample` +#### `sample` ```python sample(self, messages: str | list[str | SamplingMessage], system_prompt: str | None = None, include_context: IncludeContext | None = None, temperature: float | None = None, max_tokens: int | None = None, model_preferences: ModelPreferences | str | list[str] | None = None) -> ContentBlock @@ -246,25 +256,25 @@ completion from the client. The client must be appropriately configured, or the request will error. -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: None) -> AcceptedElicitation[dict[str, Any]] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: type[T]) -> AcceptedElicitation[T] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: list[str]) -> AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation ``` -#### `elicit` +#### `elicit` ```python elicit(self, message: str, response_type: type[T] | list[str] | None = None) -> AcceptedElicitation[T] | AcceptedElicitation[dict[str, Any]] | AcceptedElicitation[str] | DeclinedElicitation | CancelledElicitation @@ -293,7 +303,7 @@ type or dataclass or BaseModel. If it is a primitive type, an object schema with a single "value" field will be generated. -#### `get_http_request` +#### `get_http_request` ```python get_http_request(self) -> Request @@ -302,7 +312,7 @@ get_http_request(self) -> Request Get the active starlette request. -#### `set_state` +#### `set_state` ```python set_state(self, key: str, value: Any) -> None @@ -311,7 +321,7 @@ set_state(self, key: str, value: Any) -> None Set a value in the context state. -#### `get_state` +#### `get_state` ```python get_state(self, key: str) -> Any diff --git a/docs/python-sdk/fastmcp-server-dependencies.mdx b/docs/python-sdk/fastmcp-server-dependencies.mdx index 7fd03e574..5c84be69a 100644 --- a/docs/python-sdk/fastmcp-server-dependencies.mdx +++ b/docs/python-sdk/fastmcp-server-dependencies.mdx @@ -19,7 +19,7 @@ get_context() -> Context get_http_request() -> Request ``` -### `get_http_headers` +### `get_http_headers` ```python get_http_headers(include_all: bool = False) -> dict[str, str] diff --git a/docs/python-sdk/fastmcp-server-http.mdx b/docs/python-sdk/fastmcp-server-http.mdx index 48902385d..335710343 100644 --- a/docs/python-sdk/fastmcp-server-http.mdx +++ b/docs/python-sdk/fastmcp-server-http.mdx @@ -7,29 +7,29 @@ sidebarTitle: http ## Functions -### `set_http_request` +### `set_http_request` ```python set_http_request(request: Request) -> Generator[Request, None, None] ``` -### `setup_auth_middleware_and_routes` +### `setup_auth_middleware_and_routes` ```python -setup_auth_middleware_and_routes(auth: OAuthProvider) -> tuple[list[Middleware], list[BaseRoute], list[str]] +setup_auth_middleware_and_routes(auth: AuthProvider) -> tuple[list[Middleware], list[Route], list[str]] ``` Set up authentication middleware and routes if auth is enabled. **Args:** -- `auth`: The OAuthProvider authorization server provider +- `auth`: An AuthProvider for authentication (TokenVerifier or OAuthProvider) **Returns:** - Tuple of (middleware, auth_routes, required_scopes) -### `create_base_app` +### `create_base_app` ```python create_base_app(routes: list[BaseRoute], middleware: list[Middleware], debug: bool = False, lifespan: Callable | None = None) -> StarletteWithLifespan @@ -48,10 +48,10 @@ Create a base Starlette app with common middleware and routes. - A Starlette application -### `create_sse_app` +### `create_sse_app` ```python -create_sse_app(server: FastMCP[LifespanResultT], message_path: str, sse_path: str, auth: OAuthProvider | None = None, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan +create_sse_app(server: FastMCP[LifespanResultT], message_path: str, sse_path: str, auth: AuthProvider | None = None, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan ``` @@ -61,7 +61,7 @@ Return an instance of the SSE server app. - `server`: The FastMCP server instance - `message_path`: Path for SSE messages - `sse_path`: Path for SSE connections -- `auth`: Optional auth provider +- `auth`: Optional authentication provider (AuthProvider) - `debug`: Whether to enable debug mode - `routes`: Optional list of custom routes - `middleware`: Optional list of middleware @@ -70,10 +70,10 @@ Returns: A Starlette application with RequestContextMiddleware -### `create_streamable_http_app` +### `create_streamable_http_app` ```python -create_streamable_http_app(server: FastMCP[LifespanResultT], streamable_http_path: str, event_store: EventStore | None = None, auth: OAuthProvider | None = None, json_response: bool = False, stateless_http: bool = False, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan +create_streamable_http_app(server: FastMCP[LifespanResultT], streamable_http_path: str, event_store: EventStore | None = None, auth: AuthProvider | None = None, json_response: bool = False, stateless_http: bool = False, debug: bool = False, routes: list[BaseRoute] | None = None, middleware: list[Middleware] | None = None) -> StarletteWithLifespan ``` @@ -83,7 +83,7 @@ Return an instance of the StreamableHTTP server app. - `server`: The FastMCP server instance - `streamable_http_path`: Path for StreamableHTTP connections - `event_store`: Optional event store for session management -- `auth`: Optional auth provider +- `auth`: Optional authentication provider (AuthProvider) - `json_response`: Whether to use JSON response format - `stateless_http`: Whether to use stateless mode (new transport per request) - `debug`: Whether to enable debug mode @@ -96,17 +96,17 @@ Return an instance of the StreamableHTTP server app. ## Classes -### `StarletteWithLifespan` +### `StarletteWithLifespan` **Methods:** -#### `lifespan` +#### `lifespan` ```python lifespan(self) -> Lifespan ``` -### `RequestContextMiddleware` +### `RequestContextMiddleware` Middleware that stores each request in a ContextVar diff --git a/docs/python-sdk/fastmcp-server-middleware-middleware.mdx b/docs/python-sdk/fastmcp-server-middleware-middleware.mdx index f9cf66a64..806acaecc 100644 --- a/docs/python-sdk/fastmcp-server-middleware-middleware.mdx +++ b/docs/python-sdk/fastmcp-server-middleware-middleware.mdx @@ -7,7 +7,7 @@ sidebarTitle: middleware ## Functions -### `make_middleware_wrapper` +### `make_middleware_wrapper` ```python make_middleware_wrapper(middleware: Middleware, call_next: CallNext[T, R]) -> CallNext[T, R] @@ -23,9 +23,7 @@ passed to other functions that expect a call_next function. ### `CallNext` -### `ServerResultProtocol` - -### `MiddlewareContext` +### `MiddlewareContext` Unified context for all middleware operations. @@ -33,13 +31,13 @@ Unified context for all middleware operations. **Methods:** -#### `copy` +#### `copy` ```python copy(self, **kwargs: Any) -> MiddlewareContext[T] ``` -### `Middleware` +### `Middleware` Base class for FastMCP middleware with dispatching hooks. @@ -47,61 +45,61 @@ Base class for FastMCP middleware with dispatching hooks. **Methods:** -#### `on_message` +#### `on_message` ```python on_message(self, context: MiddlewareContext[Any], call_next: CallNext[Any, Any]) -> Any ``` -#### `on_request` +#### `on_request` ```python on_request(self, context: MiddlewareContext[mt.Request], call_next: CallNext[mt.Request, Any]) -> Any ``` -#### `on_notification` +#### `on_notification` ```python on_notification(self, context: MiddlewareContext[mt.Notification], call_next: CallNext[mt.Notification, Any]) -> Any ``` -#### `on_call_tool` +#### `on_call_tool` ```python -on_call_tool(self, context: MiddlewareContext[mt.CallToolRequestParams], call_next: CallNext[mt.CallToolRequestParams, mt.CallToolResult]) -> mt.CallToolResult +on_call_tool(self, context: MiddlewareContext[mt.CallToolRequestParams], call_next: CallNext[mt.CallToolRequestParams, ToolResult]) -> ToolResult ``` -#### `on_read_resource` +#### `on_read_resource` ```python on_read_resource(self, context: MiddlewareContext[mt.ReadResourceRequestParams], call_next: CallNext[mt.ReadResourceRequestParams, mt.ReadResourceResult]) -> mt.ReadResourceResult ``` -#### `on_get_prompt` +#### `on_get_prompt` ```python on_get_prompt(self, context: MiddlewareContext[mt.GetPromptRequestParams], call_next: CallNext[mt.GetPromptRequestParams, mt.GetPromptResult]) -> mt.GetPromptResult ``` -#### `on_list_tools` +#### `on_list_tools` ```python on_list_tools(self, context: MiddlewareContext[mt.ListToolsRequest], call_next: CallNext[mt.ListToolsRequest, list[Tool]]) -> list[Tool] ``` -#### `on_list_resources` +#### `on_list_resources` ```python on_list_resources(self, context: MiddlewareContext[mt.ListResourcesRequest], call_next: CallNext[mt.ListResourcesRequest, list[Resource]]) -> list[Resource] ``` -#### `on_list_resource_templates` +#### `on_list_resource_templates` ```python on_list_resource_templates(self, context: MiddlewareContext[mt.ListResourceTemplatesRequest], call_next: CallNext[mt.ListResourceTemplatesRequest, list[ResourceTemplate]]) -> list[ResourceTemplate] ``` -#### `on_list_prompts` +#### `on_list_prompts` ```python on_list_prompts(self, context: MiddlewareContext[mt.ListPromptsRequest], call_next: CallNext[mt.ListPromptsRequest, list[Prompt]]) -> list[Prompt] diff --git a/docs/python-sdk/fastmcp-server-proxy.mdx b/docs/python-sdk/fastmcp-server-proxy.mdx index ca07a9cda..5ad50f8d4 100644 --- a/docs/python-sdk/fastmcp-server-proxy.mdx +++ b/docs/python-sdk/fastmcp-server-proxy.mdx @@ -7,7 +7,7 @@ sidebarTitle: proxy ## Functions -### `default_proxy_roots_handler` +### `default_proxy_roots_handler` ```python default_proxy_roots_handler(context: RequestContext[ClientSession, LifespanContextT]) -> RootsList @@ -19,7 +19,7 @@ A handler that forwards the list roots request from the remote server to the pro ## Classes -### `ProxyToolManager` +### `ProxyToolManager` A ToolManager that sources its tools from a remote client in addition to local and mounted tools. @@ -27,7 +27,7 @@ A ToolManager that sources its tools from a remote client in addition to local a **Methods:** -#### `get_tools` +#### `get_tools` ```python get_tools(self) -> dict[str, Tool] @@ -36,7 +36,7 @@ get_tools(self) -> dict[str, Tool] Gets the unfiltered tool inventory including local, mounted, and proxy tools. -#### `list_tools` +#### `list_tools` ```python list_tools(self) -> list[Tool] @@ -45,7 +45,7 @@ list_tools(self) -> list[Tool] Gets the filtered list of tools including local, mounted, and proxy tools. -#### `call_tool` +#### `call_tool` ```python call_tool(self, key: str, arguments: dict[str, Any]) -> ToolResult @@ -54,7 +54,7 @@ call_tool(self, key: str, arguments: dict[str, Any]) -> ToolResult Calls a tool, trying local/mounted first, then proxy if not found. -### `ProxyResourceManager` +### `ProxyResourceManager` A ResourceManager that sources its resources from a remote client in addition to local and mounted resources. @@ -62,7 +62,7 @@ A ResourceManager that sources its resources from a remote client in addition to **Methods:** -#### `get_resources` +#### `get_resources` ```python get_resources(self) -> dict[str, Resource] @@ -71,7 +71,7 @@ get_resources(self) -> dict[str, Resource] Gets the unfiltered resource inventory including local, mounted, and proxy resources. -#### `get_resource_templates` +#### `get_resource_templates` ```python get_resource_templates(self) -> dict[str, ResourceTemplate] @@ -80,7 +80,7 @@ get_resource_templates(self) -> dict[str, ResourceTemplate] Gets the unfiltered template inventory including local, mounted, and proxy templates. -#### `list_resources` +#### `list_resources` ```python list_resources(self) -> list[Resource] @@ -89,7 +89,7 @@ list_resources(self) -> list[Resource] Gets the filtered list of resources including local, mounted, and proxy resources. -#### `list_resource_templates` +#### `list_resource_templates` ```python list_resource_templates(self) -> list[ResourceTemplate] @@ -98,7 +98,7 @@ list_resource_templates(self) -> list[ResourceTemplate] Gets the filtered list of templates including local, mounted, and proxy templates. -#### `read_resource` +#### `read_resource` ```python read_resource(self, uri: AnyUrl | str) -> str | bytes @@ -107,7 +107,7 @@ read_resource(self, uri: AnyUrl | str) -> str | bytes Reads a resource, trying local/mounted first, then proxy if not found. -### `ProxyPromptManager` +### `ProxyPromptManager` A PromptManager that sources its prompts from a remote client in addition to local and mounted prompts. @@ -115,7 +115,7 @@ A PromptManager that sources its prompts from a remote client in addition to loc **Methods:** -#### `get_prompts` +#### `get_prompts` ```python get_prompts(self) -> dict[str, Prompt] @@ -124,7 +124,7 @@ get_prompts(self) -> dict[str, Prompt] Gets the unfiltered prompt inventory including local, mounted, and proxy prompts. -#### `list_prompts` +#### `list_prompts` ```python list_prompts(self) -> list[Prompt] @@ -133,7 +133,7 @@ list_prompts(self) -> list[Prompt] Gets the filtered list of prompts including local, mounted, and proxy prompts. -#### `render_prompt` +#### `render_prompt` ```python render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPromptResult @@ -142,7 +142,7 @@ render_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> GetPr Renders a prompt, trying local/mounted first, then proxy if not found. -### `ProxyTool` +### `ProxyTool` A Tool that represents and executes a tool on a remote server. @@ -150,7 +150,7 @@ A Tool that represents and executes a tool on a remote server. **Methods:** -#### `from_mcp_tool` +#### `from_mcp_tool` ```python from_mcp_tool(cls, client: Client, mcp_tool: mcp.types.Tool) -> ProxyTool @@ -159,7 +159,7 @@ from_mcp_tool(cls, client: Client, mcp_tool: mcp.types.Tool) -> ProxyTool Factory method to create a ProxyTool from a raw MCP tool schema. -#### `run` +#### `run` ```python run(self, arguments: dict[str, Any], context: Context | None = None) -> ToolResult @@ -168,7 +168,7 @@ run(self, arguments: dict[str, Any], context: Context | None = None) -> ToolResu Executes the tool by making a call through the client. -### `ProxyResource` +### `ProxyResource` A Resource that represents and reads a resource from a remote server. @@ -176,7 +176,7 @@ A Resource that represents and reads a resource from a remote server. **Methods:** -#### `from_mcp_resource` +#### `from_mcp_resource` ```python from_mcp_resource(cls, client: Client, mcp_resource: mcp.types.Resource) -> ProxyResource @@ -185,7 +185,7 @@ from_mcp_resource(cls, client: Client, mcp_resource: mcp.types.Resource) -> Prox Factory method to create a ProxyResource from a raw MCP resource schema. -#### `read` +#### `read` ```python read(self) -> str | bytes @@ -194,7 +194,7 @@ read(self) -> str | bytes Read the resource content from the remote server. -### `ProxyTemplate` +### `ProxyTemplate` A ResourceTemplate that represents and creates resources from a remote server template. @@ -202,7 +202,7 @@ A ResourceTemplate that represents and creates resources from a remote server te **Methods:** -#### `from_mcp_template` +#### `from_mcp_template` ```python from_mcp_template(cls, client: Client, mcp_template: mcp.types.ResourceTemplate) -> ProxyTemplate @@ -211,7 +211,7 @@ from_mcp_template(cls, client: Client, mcp_template: mcp.types.ResourceTemplate) Factory method to create a ProxyTemplate from a raw MCP template schema. -#### `create_resource` +#### `create_resource` ```python create_resource(self, uri: str, params: dict[str, Any], context: Context | None = None) -> ProxyResource @@ -220,7 +220,7 @@ create_resource(self, uri: str, params: dict[str, Any], context: Context | None Create a resource from the template by calling the remote server. -### `ProxyPrompt` +### `ProxyPrompt` A Prompt that represents and renders a prompt from a remote server. @@ -228,7 +228,7 @@ A Prompt that represents and renders a prompt from a remote server. **Methods:** -#### `from_mcp_prompt` +#### `from_mcp_prompt` ```python from_mcp_prompt(cls, client: Client, mcp_prompt: mcp.types.Prompt) -> ProxyPrompt @@ -237,7 +237,7 @@ from_mcp_prompt(cls, client: Client, mcp_prompt: mcp.types.Prompt) -> ProxyPromp Factory method to create a ProxyPrompt from a raw MCP prompt schema. -#### `render` +#### `render` ```python render(self, arguments: dict[str, Any]) -> list[PromptMessage] @@ -246,14 +246,14 @@ render(self, arguments: dict[str, Any]) -> list[PromptMessage] Render the prompt by making a call through the client. -### `FastMCPProxy` +### `FastMCPProxy` A FastMCP server that acts as a proxy to a remote MCP-compliant server. It uses specialized managers that fulfill requests via a client factory. -### `ProxyClient` +### `ProxyClient` A proxy client that forwards advanced interactions between a remote MCP server and the proxy's connected clients. @@ -262,7 +262,7 @@ Supports forwarding roots, sampling, elicitation, logging, and progress. **Methods:** -#### `default_sampling_handler` +#### `default_sampling_handler` ```python default_sampling_handler(cls, messages: list[mcp.types.SamplingMessage], params: mcp.types.CreateMessageRequestParams, context: RequestContext[ClientSession, LifespanContextT]) -> mcp.types.CreateMessageResult @@ -271,7 +271,7 @@ default_sampling_handler(cls, messages: list[mcp.types.SamplingMessage], params: A handler that forwards the sampling request from the remote server to the proxy's connected clients and relays the response back to the remote server. -#### `default_elicitation_handler` +#### `default_elicitation_handler` ```python default_elicitation_handler(cls, message: str, response_type: type, params: mcp.types.ElicitRequestParams, context: RequestContext[ClientSession, LifespanContextT]) -> ElicitResult @@ -280,7 +280,7 @@ default_elicitation_handler(cls, message: str, response_type: type, params: mcp. A handler that forwards the elicitation request from the remote server to the proxy's connected clients and relays the response back to the remote server. -#### `default_log_handler` +#### `default_log_handler` ```python default_log_handler(cls, message: LogMessage) -> None @@ -289,7 +289,7 @@ default_log_handler(cls, message: LogMessage) -> None A handler that forwards the log notification from the remote server to the proxy's connected clients. -#### `default_progress_handler` +#### `default_progress_handler` ```python default_progress_handler(cls, progress: float, total: float | None, message: str | None) -> None @@ -298,7 +298,7 @@ default_progress_handler(cls, progress: float, total: float | None, message: str A handler that forwards the progress notification from the remote server to the proxy's connected clients. -### `StatefulProxyClient` +### `StatefulProxyClient` A proxy client that provides a stateful client factory for the proxy server. @@ -312,7 +312,16 @@ Note that it is essential to ensure that the proxy server itself is also statefu **Methods:** -#### `new_stateful` +#### `clear` + +```python +clear(self) +``` + +Clear all cached clients and force disconnect them. + + +#### `new_stateful` ```python new_stateful(self) -> Client[ClientTransportT] diff --git a/docs/python-sdk/fastmcp-server-server.mdx b/docs/python-sdk/fastmcp-server-server.mdx index 611980c70..09f3341d7 100644 --- a/docs/python-sdk/fastmcp-server-server.mdx +++ b/docs/python-sdk/fastmcp-server-server.mdx @@ -10,7 +10,7 @@ FastMCP - A more ergonomic interface for MCP servers. ## Functions -### `default_lifespan` +### `default_lifespan` ```python default_lifespan(server: FastMCP[LifespanResultT]) -> AsyncIterator[Any] @@ -26,7 +26,7 @@ Default lifespan context manager that does nothing. - An empty context object -### `add_resource_prefix` +### `add_resource_prefix` ```python add_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> str @@ -64,7 +64,7 @@ add_resource_prefix("resource:///absolute/path", "prefix") - `ValueError`: If the URI doesn't match the expected protocol\://path format -### `remove_resource_prefix` +### `remove_resource_prefix` ```python remove_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> str @@ -103,7 +103,7 @@ remove_resource_prefix("resource://prefix//absolute/path", "prefix") - `ValueError`: If the URI doesn't match the expected protocol\://path format -### `has_resource_prefix` +### `has_resource_prefix` ```python has_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> bool @@ -143,29 +143,29 @@ False ## Classes -### `FastMCP` +### `FastMCP` **Methods:** -#### `settings` +#### `settings` ```python settings(self) -> Settings ``` -#### `name` +#### `name` ```python name(self) -> str ``` -#### `instructions` +#### `instructions` ```python instructions(self) -> str | None ``` -#### `run_async` +#### `run_async` ```python run_async(self, transport: Transport | None = None, show_banner: bool = True, **transport_kwargs: Any) -> None @@ -177,7 +177,7 @@ Run the FastMCP server asynchronously. - `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http") -#### `run` +#### `run` ```python run(self, transport: Transport | None = None, show_banner: bool = True, **transport_kwargs: Any) -> None @@ -189,13 +189,13 @@ Run the FastMCP server. Note this is a synchronous function. - `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http") -#### `add_middleware` +#### `add_middleware` ```python add_middleware(self, middleware: Middleware) -> None ``` -#### `get_tools` +#### `get_tools` ```python get_tools(self) -> dict[str, Tool] @@ -204,13 +204,13 @@ get_tools(self) -> dict[str, Tool] Get all registered tools, indexed by registered key. -#### `get_tool` +#### `get_tool` ```python get_tool(self, key: str) -> Tool ``` -#### `get_resources` +#### `get_resources` ```python get_resources(self) -> dict[str, Resource] @@ -219,13 +219,13 @@ get_resources(self) -> dict[str, Resource] Get all registered resources, indexed by registered key. -#### `get_resource` +#### `get_resource` ```python get_resource(self, key: str) -> Resource ``` -#### `get_resource_templates` +#### `get_resource_templates` ```python get_resource_templates(self) -> dict[str, ResourceTemplate] @@ -234,7 +234,7 @@ get_resource_templates(self) -> dict[str, ResourceTemplate] Get all registered resource templates, indexed by registered key. -#### `get_resource_template` +#### `get_resource_template` ```python get_resource_template(self, key: str) -> ResourceTemplate @@ -243,7 +243,7 @@ get_resource_template(self, key: str) -> ResourceTemplate Get a registered resource template by key. -#### `get_prompts` +#### `get_prompts` ```python get_prompts(self) -> dict[str, Prompt] @@ -252,13 +252,13 @@ get_prompts(self) -> dict[str, Prompt] List all available prompts. -#### `get_prompt` +#### `get_prompt` ```python get_prompt(self, key: str) -> Prompt ``` -#### `custom_route` +#### `custom_route` ```python custom_route(self, path: str, methods: list[str], name: str | None = None, include_in_schema: bool = True) -> Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]] @@ -279,7 +279,7 @@ Starlette's reverse URL lookup feature) - `include_in_schema`: Whether to include in OpenAPI schema, defaults to True -#### `add_tool` +#### `add_tool` ```python add_tool(self, tool: Tool) -> Tool @@ -297,7 +297,7 @@ with the Context type annotation. See the @tool decorator for examples. - The tool instance that was added to the server. -#### `remove_tool` +#### `remove_tool` ```python remove_tool(self, name: str) -> None @@ -312,7 +312,7 @@ Remove a tool from the server. - `NotFoundError`: If the tool is not found -#### `add_tool_transformation` +#### `add_tool_transformation` ```python add_tool_transformation(self, tool_name: str, transformation: ToolTransformConfig) -> None @@ -321,7 +321,7 @@ add_tool_transformation(self, tool_name: str, transformation: ToolTransformConfi Add a tool transformation. -#### `remove_tool_transformation` +#### `remove_tool_transformation` ```python remove_tool_transformation(self, tool_name: str) -> None @@ -330,19 +330,19 @@ remove_tool_transformation(self, tool_name: str) -> None Remove a tool transformation. -#### `tool` +#### `tool` ```python tool(self, name_or_fn: AnyFunction) -> FunctionTool ``` -#### `tool` +#### `tool` ```python tool(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionTool] ``` -#### `tool` +#### `tool` ```python tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool @@ -369,6 +369,7 @@ This decorator supports multiple calling patterns: - `output_schema`: Optional JSON schema for the tool's output - `annotations`: Optional annotations about the tool's behavior - `exclude_args`: Optional list of argument names to exclude from the tool schema +- `meta`: Optional meta information about the tool - `enabled`: Optional boolean to enable or disable the tool **Examples:** @@ -397,7 +398,7 @@ server.tool(my_function, name="custom_name") ``` -#### `add_resource` +#### `add_resource` ```python add_resource(self, resource: Resource) -> Resource @@ -412,7 +413,7 @@ Add a resource to the server. - The resource instance that was added to the server. -#### `add_template` +#### `add_template` ```python add_template(self, template: ResourceTemplate) -> ResourceTemplate @@ -427,7 +428,7 @@ Add a resource template to the server. - The template instance that was added to the server. -#### `add_resource_fn` +#### `add_resource_fn` ```python add_resource_fn(self, fn: AnyFunction, uri: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None) -> None @@ -447,7 +448,7 @@ has parameters, it will be registered as a template resource. - `tags`: Optional set of tags for categorizing the resource -#### `resource` +#### `resource` ```python resource(self, uri: str) -> Callable[[AnyFunction], Resource | ResourceTemplate] @@ -475,6 +476,8 @@ has parameters, it will be registered as a template resource. - `mime_type`: Optional MIME type for the resource - `tags`: Optional set of tags for categorizing the resource - `enabled`: Optional boolean to enable or disable the resource +- `annotations`: Optional annotations about the resource's behavior +- `meta`: Optional meta information about the resource **Examples:** @@ -505,7 +508,7 @@ async def get_weather(city: str) -> str: ``` -#### `add_prompt` +#### `add_prompt` ```python add_prompt(self, prompt: Prompt) -> Prompt @@ -520,19 +523,19 @@ Add a prompt to the server. - The prompt instance that was added to the server. -#### `prompt` +#### `prompt` ```python prompt(self, name_or_fn: AnyFunction) -> FunctionPrompt ``` -#### `prompt` +#### `prompt` ```python prompt(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionPrompt] ``` -#### `prompt` +#### `prompt` ```python prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt @@ -557,6 +560,7 @@ Decorator to register a prompt. description: Optional description of what the prompt does tags: Optional set of tags for categorizing the prompt enabled: Optional boolean to enable or disable the prompt + meta: Optional meta information about the prompt Examples: @@ -609,7 +613,7 @@ Decorator to register a prompt. ``` -#### `run_stdio_async` +#### `run_stdio_async` ```python run_stdio_async(self, show_banner: bool = True) -> None @@ -618,7 +622,7 @@ run_stdio_async(self, show_banner: bool = True) -> None Run the server using stdio transport. -#### `run_http_async` +#### `run_http_async` ```python run_http_async(self, show_banner: bool = True, transport: Literal['http', 'streamable-http', 'sse'] = 'http', host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None, middleware: list[ASGIMiddleware] | None = None, stateless_http: bool | None = None) -> None @@ -637,7 +641,7 @@ Run the server using HTTP transport. - `stateless_http`: Whether to use stateless HTTP (defaults to settings.stateless_http) -#### `run_sse_async` +#### `run_sse_async` ```python run_sse_async(self, host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None) -> None @@ -646,7 +650,7 @@ run_sse_async(self, host: str | None = None, port: int | None = None, log_level: Run the server using SSE transport. -#### `sse_app` +#### `sse_app` ```python sse_app(self, path: str | None = None, message_path: str | None = None, middleware: list[ASGIMiddleware] | None = None) -> StarletteWithLifespan @@ -660,7 +664,7 @@ Create a Starlette app for the SSE server. - `middleware`: A list of middleware to apply to the app -#### `streamable_http_app` +#### `streamable_http_app` ```python streamable_http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None) -> StarletteWithLifespan @@ -673,7 +677,7 @@ Create a Starlette app for the StreamableHTTP server. - `middleware`: A list of middleware to apply to the app -#### `http_app` +#### `http_app` ```python http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http') -> StarletteWithLifespan @@ -690,13 +694,13 @@ Create a Starlette app using the specified HTTP transport. - A Starlette application configured with the specified transport -#### `run_streamable_http_async` +#### `run_streamable_http_async` ```python run_streamable_http_async(self, host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None) -> None ``` -#### `mount` +#### `mount` ```python mount(self, server: FastMCP[LifespanResultT], prefix: str | None = None, as_proxy: bool | None = None) -> None @@ -750,7 +754,7 @@ automatically determined based on whether the server has a custom lifespan - `prompt_separator`: Deprecated. Separator character for prompt names. -#### `import_server` +#### `import_server` ```python import_server(self, server: FastMCP[LifespanResultT], prefix: str | None = None, tool_separator: str | None = None, resource_separator: str | None = None, prompt_separator: str | None = None) -> None @@ -791,7 +795,7 @@ applied using the protocol\://prefix/path format - `prompt_separator`: Deprecated. Separator for prompt names. -#### `from_openapi` +#### `from_openapi` ```python from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, route_maps: list[RouteMap] | list[RouteMapNew] | None = None, route_map_fn: OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | None = None, mcp_component_fn: OpenAPIComponentFn | OpenAPIComponentFnNew | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI | FastMCPOpenAPINew @@ -800,7 +804,7 @@ from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, route Create a FastMCP server from an OpenAPI specification. -#### `from_fastapi` +#### `from_fastapi` ```python from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | list[RouteMapNew] | None = None, route_map_fn: OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | None = None, mcp_component_fn: OpenAPIComponentFn | OpenAPIComponentFnNew | None = None, mcp_names: dict[str, str] | None = None, httpx_client_kwargs: dict[str, Any] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI | FastMCPOpenAPINew @@ -809,7 +813,7 @@ from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] Create a FastMCP server from a FastAPI application. -#### `as_proxy` +#### `as_proxy` ```python as_proxy(cls, backend: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy @@ -823,7 +827,7 @@ instance or any value accepted as the `transport` argument of `fastmcp.client.Client` constructor. -#### `from_client` +#### `from_client` ```python from_client(cls, client: Client[ClientTransportT], **settings: Any) -> FastMCPProxy @@ -832,4 +836,4 @@ from_client(cls, client: Client[ClientTransportT], **settings: Any) -> FastMCPPr Create a FastMCP proxy server from a FastMCP client. -### `MountedServer` +### `MountedServer` diff --git a/docs/python-sdk/fastmcp-tools-tool.mdx b/docs/python-sdk/fastmcp-tools-tool.mdx index ce27bb86f..aaa3cbf53 100644 --- a/docs/python-sdk/fastmcp-tools-tool.mdx +++ b/docs/python-sdk/fastmcp-tools-tool.mdx @@ -51,16 +51,16 @@ disable(self) -> None to_mcp_tool(self, **overrides: Any) -> MCPTool ``` -#### `from_function` +#### `from_function` ```python -from_function(fn: Callable[..., Any], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, exclude_args: list[str] | None = None, output_schema: dict[str, Any] | None | NotSetT | Literal[False] = NotSet, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> FunctionTool +from_function(fn: Callable[..., Any], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, exclude_args: list[str] | None = None, output_schema: dict[str, Any] | None | NotSetT | Literal[False] = NotSet, serializer: Callable[[Any], str] | None = None, meta: dict[str, Any] | None = None, enabled: bool | None = None) -> FunctionTool ``` Create a Tool from a function. -#### `run` +#### `run` ```python run(self, arguments: dict[str, Any]) -> ToolResult @@ -75,26 +75,26 @@ implemented by subclasses. (list of ContentBlocks, dict of structured output). -#### `from_tool` +#### `from_tool` ```python -from_tool(cls, tool: Tool, transform_fn: Callable[..., Any] | None = None, name: str | None = None, title: str | None | NotSetT = NotSet, transform_args: dict[str, ArgTransform] | None = None, description: str | None | NotSetT = NotSet, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, output_schema: dict[str, Any] | None | Literal[False] = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> TransformedTool +from_tool(cls, tool: Tool, transform_fn: Callable[..., Any] | None = None, name: str | None = None, title: str | None | NotSetT = NotSet, transform_args: dict[str, ArgTransform] | None = None, description: str | None | NotSetT = NotSet, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, output_schema: dict[str, Any] | None | Literal[False] = None, serializer: Callable[[Any], str] | None = None, meta: dict[str, Any] | None | NotSetT = NotSet, enabled: bool | None = None) -> TransformedTool ``` -### `FunctionTool` +### `FunctionTool` **Methods:** -#### `from_function` +#### `from_function` ```python -from_function(cls, fn: Callable[..., Any], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, exclude_args: list[str] | None = None, output_schema: dict[str, Any] | None | NotSetT | Literal[False] = NotSet, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> FunctionTool +from_function(cls, fn: Callable[..., Any], name: str | None = None, title: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, exclude_args: list[str] | None = None, output_schema: dict[str, Any] | None | NotSetT | Literal[False] = NotSet, serializer: Callable[[Any], str] | None = None, meta: dict[str, Any] | None = None, enabled: bool | None = None) -> FunctionTool ``` Create a Tool from a function. -#### `run` +#### `run` ```python run(self, arguments: dict[str, Any]) -> ToolResult @@ -103,11 +103,11 @@ run(self, arguments: dict[str, Any]) -> ToolResult Run the tool with arguments. -### `ParsedFunction` +### `ParsedFunction` **Methods:** -#### `from_function` +#### `from_function` ```python from_function(cls, fn: Callable[..., Any], exclude_args: list[str] | None = None, validate: bool = True, wrap_non_object_output_schema: bool = True) -> ParsedFunction diff --git a/docs/python-sdk/fastmcp-tools-tool_transform.mdx b/docs/python-sdk/fastmcp-tools-tool_transform.mdx index b2ad153fb..51bce981f 100644 --- a/docs/python-sdk/fastmcp-tools-tool_transform.mdx +++ b/docs/python-sdk/fastmcp-tools-tool_transform.mdx @@ -7,7 +7,7 @@ sidebarTitle: tool_transform ## Functions -### `forward` +### `forward` ```python forward(**kwargs) -> ToolResult @@ -36,7 +36,7 @@ tool has args `a` and `b`, and an `transform_args` was provided that maps `x` to - `TypeError`: If provided arguments don't match the transformed schema. -### `forward_raw` +### `forward_raw` ```python forward_raw(**kwargs) -> ToolResult @@ -62,7 +62,7 @@ y=2)` will call the parent tool with `x=1` and `y=2`. - `RuntimeError`: If called outside a transformed tool context. -### `apply_transformations_to_tools` +### `apply_transformations_to_tools` ```python apply_transformations_to_tools(tools: dict[str, Tool], transformations: dict[str, ToolTransformConfig]) -> dict[str, Tool] @@ -75,7 +75,7 @@ are left unchanged. ## Classes -### `ArgTransform` +### `ArgTransform` Configuration for transforming a parent tool's argument. @@ -137,7 +137,7 @@ ArgTransform(name="new_name", description="New desc", default=None, type=int) ``` -### `ArgTransformConfig` +### `ArgTransformConfig` A model for requesting a single argument transform. @@ -145,7 +145,7 @@ A model for requesting a single argument transform. **Methods:** -#### `to_arg_transform` +#### `to_arg_transform` ```python to_arg_transform(self) -> ArgTransform @@ -154,7 +154,7 @@ to_arg_transform(self) -> ArgTransform Convert the argument transform to a FastMCP argument transform. -### `TransformedTool` +### `TransformedTool` A tool that is transformed from another tool. @@ -171,7 +171,7 @@ inherited from the parent tool but can be overridden or disabled. **Methods:** -#### `run` +#### `run` ```python run(self, arguments: dict[str, Any]) -> ToolResult @@ -190,10 +190,10 @@ functions. - ToolResult object containing content and optional structured output. -#### `from_tool` +#### `from_tool` ```python -from_tool(cls, tool: Tool, name: str | None = None, title: str | None | NotSetT = NotSet, description: str | None | NotSetT = NotSet, tags: set[str] | None = None, transform_fn: Callable[..., Any] | None = None, transform_args: dict[str, ArgTransform] | None = None, annotations: ToolAnnotations | None = None, output_schema: dict[str, Any] | None | Literal[False] = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> TransformedTool +from_tool(cls, tool: Tool, name: str | None = None, title: str | None | NotSetT = NotSet, description: str | None | NotSetT = NotSet, tags: set[str] | None = None, transform_fn: Callable[..., Any] | None = None, transform_args: dict[str, ArgTransform] | None = None, annotations: ToolAnnotations | None = None, output_schema: dict[str, Any] | None | Literal[False] = None, serializer: Callable[[Any], str] | None = None, meta: dict[str, Any] | None | NotSetT = NotSet, enabled: bool | None = None) -> TransformedTool ``` Create a transformed tool from a parent tool. @@ -218,6 +218,10 @@ Only specified arguments are transformed, others pass through unchanged\: - dict\: Use custom output schema - False\: Disable output schema and structured outputs - `serializer`: New serializer. Defaults to parent's serializer. +- `meta`: Control meta information\: +- NotSet (default)\: Inherit from parent tool +- dict\: Use custom meta information +- None\: Remove meta information **Returns:** - TransformedTool with the specified transformations. @@ -268,7 +272,7 @@ async def custom_output(**kwargs) -> ToolResult: ``` -### `ToolTransformConfig` +### `ToolTransformConfig` Provides a way to transform a tool. @@ -276,7 +280,7 @@ Provides a way to transform a tool. **Methods:** -#### `apply` +#### `apply` ```python apply(self, tool: Tool) -> TransformedTool diff --git a/docs/python-sdk/fastmcp-utilities-components.mdx b/docs/python-sdk/fastmcp-utilities-components.mdx index 7c0c1a29a..01cbdfda8 100644 --- a/docs/python-sdk/fastmcp-utilities-components.mdx +++ b/docs/python-sdk/fastmcp-utilities-components.mdx @@ -7,7 +7,9 @@ sidebarTitle: components ## Classes -### `FastMCPComponent` +### `FastMCPMeta` + +### `FastMCPComponent` Base class for FastMCP tools, prompts, resources, and resource templates. @@ -15,7 +17,7 @@ Base class for FastMCP tools, prompts, resources, and resource templates. **Methods:** -#### `key` +#### `key` ```python key(self) -> str @@ -27,13 +29,25 @@ keys having a certain value, as the same tool loaded from different hierarchies of servers may have different keys. -#### `with_key` +#### `get_meta` + +```python +get_meta(self, include_fastmcp_meta: bool | None = None) -> dict[str, Any] | None +``` + +Get the meta information about the component. + +If include_fastmcp_meta is True, a `_fastmcp` key will be added to the +meta, containing a `tags` field with the tags of the component. + + +#### `with_key` ```python with_key(self, key: str) -> Self ``` -#### `enable` +#### `enable` ```python enable(self) -> None @@ -42,7 +56,7 @@ enable(self) -> None Enable the component. -#### `disable` +#### `disable` ```python disable(self) -> None @@ -51,7 +65,7 @@ disable(self) -> None Disable the component. -#### `copy` +#### `copy` ```python copy(self) -> Self @@ -60,7 +74,7 @@ copy(self) -> Self Create a copy of the component. -### `MirroredComponent` +### `MirroredComponent` Base class for components that are mirrored from a remote server. @@ -71,7 +85,7 @@ to create a local version you can modify. **Methods:** -#### `enable` +#### `enable` ```python enable(self) -> None @@ -80,7 +94,7 @@ enable(self) -> None Enable the component. -#### `disable` +#### `disable` ```python disable(self) -> None @@ -89,7 +103,7 @@ disable(self) -> None Disable the component. -#### `copy` +#### `copy` ```python copy(self) -> Self diff --git a/docs/python-sdk/fastmcp-utilities-mcp_config.mdx b/docs/python-sdk/fastmcp-utilities-mcp_config.mdx index eac19c909..1777e0a0c 100644 --- a/docs/python-sdk/fastmcp-utilities-mcp_config.mdx +++ b/docs/python-sdk/fastmcp-utilities-mcp_config.mdx @@ -7,20 +7,20 @@ sidebarTitle: mcp_config ## Functions -### `composite_server_from_mcp_config` +### `composite_server_from_mcp_config` ```python -composite_server_from_mcp_config(config: MCPConfig, name_as_prefix: bool = True) -> FastMCP +composite_server_from_mcp_config(config: MCPConfig, name_as_prefix: bool = True) -> FastMCP[None] ``` A utility function to create a composite server from an MCPConfig. -### `mount_mcp_config_into_server` +### `mount_mcp_config_into_server` ```python -mount_mcp_config_into_server(config: MCPConfig, server: FastMCP, name_as_prefix: bool = True) -> None +mount_mcp_config_into_server(config: MCPConfig, server: FastMCP[Any], name_as_prefix: bool = True) -> None ``` diff --git a/docs/python-sdk/fastmcp-utilities-openapi.mdx b/docs/python-sdk/fastmcp-utilities-openapi.mdx index 970ebaaf1..a9c7ffa37 100644 --- a/docs/python-sdk/fastmcp-utilities-openapi.mdx +++ b/docs/python-sdk/fastmcp-utilities-openapi.mdx @@ -47,7 +47,7 @@ For example: `{"id": "123", "type": "user"}` becomes `param[id]=123¶m[type]= - Dictionary with bracketed parameter names as keys -### `parse_openapi_to_http_routes` +### `parse_openapi_to_http_routes` ```python parse_openapi_to_http_routes(openapi_dict: dict[str, Any]) -> list[HTTPRoute] @@ -60,7 +60,7 @@ using the openapi-pydantic library. Supports both OpenAPI 3.0.x and 3.1.x versions. -### `clean_schema_for_display` +### `clean_schema_for_display` ```python clean_schema_for_display(schema: JsonSchema | None) -> JsonSchema | None @@ -70,7 +70,7 @@ clean_schema_for_display(schema: JsonSchema | None) -> JsonSchema | None Clean up a schema dictionary for display by removing internal/complex fields. -### `generate_example_from_schema` +### `generate_example_from_schema` ```python generate_example_from_schema(schema: JsonSchema | None) -> Any @@ -81,7 +81,7 @@ Generate a simple example value from a JSON schema dictionary. Very basic implementation focusing on types. -### `format_json_for_description` +### `format_json_for_description` ```python format_json_for_description(data: Any, indent: int = 2) -> str @@ -91,7 +91,7 @@ format_json_for_description(data: Any, indent: int = 2) -> str Formats Python data as a JSON string block for markdown. -### `format_description_with_responses` +### `format_description_with_responses` ```python format_description_with_responses(base_description: str, responses: dict[str, Any], parameters: list[ParameterInfo] | None = None, request_body: RequestBodyInfo | None = None) -> str @@ -114,10 +114,10 @@ including its description, whether it is required, and its content schema. - and the request body. -### `extract_output_schema_from_responses` +### `extract_output_schema_from_responses` ```python -extract_output_schema_from_responses(responses: dict[str, ResponseInfo], schema_definitions: dict[str, Any] | None = None) -> dict[str, Any] | None +extract_output_schema_from_responses(responses: dict[str, ResponseInfo], schema_definitions: dict[str, Any] | None = None, openapi_version: str | None = None) -> dict[str, Any] | None ``` @@ -130,6 +130,7 @@ object type, it wraps it to comply with MCP requirements. **Args:** - `responses`: Dictionary of ResponseInfo objects keyed by status code - `schema_definitions`: Optional schema definitions to include in the output schema +- `openapi_version`: OpenAPI version string, used to optimize nullable field handling **Returns:** - MCP-compliant output schema with potential wrapping, or None if no suitable schema found @@ -161,7 +162,7 @@ Represents response information in our IR. Intermediate Representation for a single OpenAPI operation. -### `OpenAPIParser` +### `OpenAPIParser` Unified parser for OpenAPI schemas with generic type parameters to handle both 3.0 and 3.1. @@ -169,7 +170,7 @@ Unified parser for OpenAPI schemas with generic type parameters to handle both 3 **Methods:** -#### `parse` +#### `parse` ```python parse(self) -> list[HTTPRoute] diff --git a/docs/python-sdk/fastmcp-utilities-tests.mdx b/docs/python-sdk/fastmcp-utilities-tests.mdx index 5766b4d02..13d156215 100644 --- a/docs/python-sdk/fastmcp-utilities-tests.mdx +++ b/docs/python-sdk/fastmcp-utilities-tests.mdx @@ -7,7 +7,7 @@ sidebarTitle: tests ## Functions -### `temporary_settings` +### `temporary_settings` ```python temporary_settings(**kwargs: Any) @@ -20,7 +20,7 @@ Temporarily override FastMCP setting values. - `**kwargs`: The settings to override, including nested settings. -### `run_server_in_process` +### `run_server_in_process` ```python run_server_in_process(server_fn: Callable[..., None], *args, **kwargs) -> Generator[str, None, None] @@ -41,7 +41,7 @@ not pickleable, so we need a function that creates and runs one. - The server URL. -### `caplog_for_fastmcp` +### `caplog_for_fastmcp` ```python caplog_for_fastmcp(caplog) @@ -50,3 +50,34 @@ caplog_for_fastmcp(caplog) Context manager to capture logs from FastMCP loggers even when propagation is disabled. + +## Classes + +### `HeadlessOAuth` + + +OAuth provider that bypasses browser interaction for testing. + +This simulates the complete OAuth flow programmatically by making HTTP requests +instead of opening a browser and running a callback server. Useful for automated testing. + + +**Methods:** + +#### `redirect_handler` + +```python +redirect_handler(self, authorization_url: str) -> None +``` + +Make HTTP request to authorization URL and store response for callback handler. + + +#### `callback_handler` + +```python +callback_handler(self) -> tuple[str, str | None] +``` + +Parse stored response and return (auth_code, state). + diff --git a/docs/python-sdk/fastmcp-utilities-types.mdx b/docs/python-sdk/fastmcp-utilities-types.mdx index 4d08be539..52044dd68 100644 --- a/docs/python-sdk/fastmcp-utilities-types.mdx +++ b/docs/python-sdk/fastmcp-utilities-types.mdx @@ -23,7 +23,7 @@ However, this isn't feasible for user-generated functions. Instead, we use a cache to minimize the cost of creating them as much as possible. -### `issubclass_safe` +### `issubclass_safe` ```python issubclass_safe(cls: type, base: type) -> bool @@ -33,7 +33,7 @@ issubclass_safe(cls: type, base: type) -> bool Check if cls is a subclass of base, even if cls is a type variable. -### `is_class_member_of_type` +### `is_class_member_of_type` ```python is_class_member_of_type(cls: type, base: type) -> bool @@ -46,7 +46,7 @@ Base can be a type, a UnionType, or an Annotated type. Generic types are not considered members (e.g. T is not a member of list\[T]). -### `find_kwarg_by_type` +### `find_kwarg_by_type` ```python find_kwarg_by_type(fn: Callable, kwarg_type: type) -> str | None @@ -58,7 +58,7 @@ Find the name of the kwarg that is of type kwarg_type. Includes union types that contain the kwarg_type, as well as Annotated types. -### `replace_type` +### `replace_type` ```python replace_type(type_, type_map: dict[type, type]) @@ -93,7 +93,7 @@ list[list[str]] Base model for FastMCP models. -### `Image` +### `Image` Helper class for returning images from tools. @@ -101,7 +101,7 @@ Helper class for returning images from tools. **Methods:** -#### `to_image_content` +#### `to_image_content` ```python to_image_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.ImageContent @@ -110,7 +110,7 @@ to_image_content(self, mime_type: str | None = None, annotations: Annotations | Convert to MCP ImageContent. -### `Audio` +### `Audio` Helper class for returning audio from tools. @@ -118,13 +118,13 @@ Helper class for returning audio from tools. **Methods:** -#### `to_audio_content` +#### `to_audio_content` ```python to_audio_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.AudioContent ``` -### `File` +### `File` Helper class for returning audio from tools. @@ -132,7 +132,7 @@ Helper class for returning audio from tools. **Methods:** -#### `to_resource_content` +#### `to_resource_content` ```python to_resource_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.EmbeddedResource diff --git a/docs/servers/auth/authentication.mdx b/docs/servers/auth/authentication.mdx index fe41caea4..0c6ca4380 100644 --- a/docs/servers/auth/authentication.mdx +++ b/docs/servers/auth/authentication.mdx @@ -3,6 +3,7 @@ title: Authentication sidebarTitle: Overview description: Secure your FastMCP server with flexible authentication patterns, from simple API keys to full OAuth 2.1 integration with external identity providers. icon: user-shield +tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx" @@ -67,9 +68,9 @@ Token verification is the conceptually simplest approach to authentication, wher - Ensuring tokens are securely transmitted to your server - Managing token lifecycle in your issuing system -### Remote Authentication +### Remote OAuth -This is the **recommended pattern for most FastMCP users** and follows the 2025-6-18 MCP protocol update. Your FastMCP server acts as a **Resource Server** and integrates with an external, trusted **Authorization Server** like WorkOS, Auth0, or Okta. You can learn more about this pattern in the [remote authentication documentation](/servers/auth/remote-authentication). +This is the **recommended pattern for most FastMCP users** and follows the 2025-6-18 MCP protocol update. Your FastMCP server acts as a **Resource Server** and integrates with an external, trusted **Authorization Server** like WorkOS, Auth0, or Okta. You can learn more about this pattern in the [remote OAuth documentation](/servers/auth/remote-oauth). **Use this when:** - You want to integrate with external identity providers @@ -126,7 +127,7 @@ jwt_verifier = JWTVerifier(...) mcp = FastMCP(name="My Server", auth=jwt_verifier) ``` -```python Remote Authentication +```python Remote OAuth from fastmcp import FastMCP from fastmcp.server.auth.providers.workos import AuthKitProvider diff --git a/docs/servers/auth/full-oauth-server.mdx b/docs/servers/auth/full-oauth-server.mdx index c512b2bf6..f04e055ac 100644 --- a/docs/servers/auth/full-oauth-server.mdx +++ b/docs/servers/auth/full-oauth-server.mdx @@ -3,6 +3,7 @@ title: Full OAuth Server sidebarTitle: Full OAuth Server description: Build a self-contained authentication system where your FastMCP server manages users, issues tokens, and validates them. icon: users-between-lines +tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx" @@ -12,7 +13,7 @@ import { VersionBadge } from "/snippets/version-badge.mdx" **This is an extremely advanced pattern.** Building a secure, production-ready OAuth 2.1 server is a complex undertaking that requires deep expertise in authentication protocols, cryptography, and security best practices. -This pattern exists primarily to support the MCP protocol specification's requirements. **Most users should strongly prefer the [Remote Authentication pattern](/servers/auth/remote-authentication)** to integrate with a dedicated identity provider like WorkOS, Auth0, or Okta. +This pattern exists primarily to support the MCP protocol specification's requirements. **Most users should strongly prefer the [Remote OAuth pattern](/servers/auth/remote-oauth)** to integrate with a dedicated identity provider like WorkOS, Auth0, or Okta. In the **Full OAuth Server** pattern, your FastMCP server acts as both the **Authorization Server (AS)** and the **Resource Server (RS)**. It becomes responsible for the entire authentication lifecycle: diff --git a/docs/servers/auth/remote-authentication.mdx b/docs/servers/auth/remote-oauth.mdx similarity index 93% rename from docs/servers/auth/remote-authentication.mdx rename to docs/servers/auth/remote-oauth.mdx index a0d8c71e9..bb258a77f 100644 --- a/docs/servers/auth/remote-authentication.mdx +++ b/docs/servers/auth/remote-oauth.mdx @@ -1,15 +1,16 @@ --- -title: Remote Authentication -sidebarTitle: Remote Authentication +title: Remote OAuth +sidebarTitle: Remote OAuth description: Integrate with external identity providers like WorkOS, Auth0, or Okta by trusting them to handle user authentication. icon: camera-cctv +tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx" -**Remote Authentication** is the recommended pattern for securing most production applications. In this model, your FastMCP server acts as a **Resource Server (RS)** and integrates with an external, trusted **Authorization Server (AS)**, such as WorkOS, Auth0, or a corporate SSO system. +**Remote OAuth** is the recommended pattern for securing most production applications. In this model, your FastMCP server acts as a **Resource Server (RS)** and integrates with an external, trusted **Authorization Server (AS)**, such as WorkOS, Auth0, or a corporate SSO system. This approach lets you leverage robust, feature-rich identity platforms for user management, multi-factor authentication, and social logins, while your FastMCP server focuses on its core job: providing tools and resources. @@ -119,7 +120,7 @@ mcp = FastMCP(name="My Secure Server", auth=MyIdPAuthProvider()) ## Example: WorkOS AuthKit Provider -FastMCP provides a built-in provider for **WorkOS AuthKit** that handles this entire pattern for you. It's a perfect example of the remote authentication pattern in action. +FastMCP provides a built-in provider for **WorkOS AuthKit** that handles this entire pattern for you. It's a perfect example of the remote OAuth pattern in action. **Prerequisites:** 1. A WorkOS account with an AuthKit project. diff --git a/docs/servers/auth/token-verification.mdx b/docs/servers/auth/token-verification.mdx index aedef6e38..0d5922c23 100644 --- a/docs/servers/auth/token-verification.mdx +++ b/docs/servers/auth/token-verification.mdx @@ -3,6 +3,7 @@ title: Token Verification sidebarTitle: Token Verification description: Protect your server by validating bearer tokens. icon: key +tag: NEW --- import { VersionBadge } from "/snippets/version-badge.mdx"