π The fast, Pythonic way to build MCP servers and clients.
update path and mdxify
zzstoatzz5afe5b793e09
diff --git a/docs/docs.json b/docs/docs.jsonindex 0c0b83e53..0c0677a67 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -1,178 +1,279 @@{- "$schema": "https://mintlify.com/docs.json",- "appearance": {- "default": "system",- "strict": false+ "$schema": "https://mintlify.com/docs.json",+ "appearance": {+ "default": "system",+ "strict": false+ },+ "background": {+ "color": {+ "dark": "#222831",+ "light": "#EEEEEE"},- "background": {- "color": {- "dark": "#222831",- "light": "#EEEEEE"- },- "decoration": "windows"- },- "banner": {- "content": "[FastMCP Cloud](https://fastmcp.link/x0Kyhy2) is coming!"- },- "colors": {- "dark": "#f72585",- "light": "#4cc9f0",- "primary": "#2d00f7"- },- "description": "The fast, Pythonic way to build MCP servers and clients.",- "favicon": {- "dark": "/assets/favicon.ico",- "light": "/assets/favicon.ico"- },- "footer": {- "socials": {- "bluesky": "https://bsky.app/profile/jlowin.dev",- "github": "https://github.com/jlowin/fastmcp",- "x": "https://x.com/jlowin"- }- },- "integrations": {- "ga4": {- "measurementId": "G-64R5W1TJXG"- }- },- "name": "FastMCP",- "navbar": {- "primary": {- "href": "https://github.com/jlowin/fastmcp",- "type": "github"- }- },- "navigation": {- "anchors": [- {- "anchor": "Documentation",- "groups": [- {- "group": "Get Started",- "pages": [- "getting-started/welcome",- "getting-started/installation",- "getting-started/quickstart",- "updates"- ]- },- {- "group": "Servers",- "pages": [- "servers/fastmcp",- {- "group": "Core Components",- "icon": "toolbox",- "pages": [- "servers/tools",- "servers/resources",- "servers/prompts",- "servers/context"- ]- },- {- "group": "Authentication",- "icon": "shield-check",- "pages": [- "servers/auth/bearer"- ]- },- "servers/middleware",- "servers/openapi",- "servers/proxy",- "servers/composition",- {- "group": "Deployment",- "icon": "upload",- "pages": [- "deployment/running-server",- "deployment/asgi"- ]- }- ]- },- {- "group": "Clients",- "pages": [- "clients/client",- "clients/transports",- {- "group": "Authentication",- "icon": "user-shield",- "pages": [- "clients/auth/oauth",- "clients/auth/bearer"- ]- },- "clients/advanced-features"- ]- },- {- "group": "Integrations",- "pages": [- "integrations/anthropic",- "integrations/claude-desktop",- "integrations/openai",- "integrations/gemini",- "integrations/contrib"- ]- },- {- "group": "Patterns",- "pages": [- "patterns/tool-transformation",- "patterns/decorating-methods",- "patterns/http-requests",- "patterns/testing",- "patterns/cli"- ]- }- ],- "icon": "book"- },- {- "anchor": "Tutorials",- "groups": [- {- "group": "MCP",- "pages": [- "tutorials/mcp",- "tutorials/create-mcp-server",- "tutorials/rest-api"- ]- }- ],- "icon": "graduation-cap"- },- {- "anchor": "Changelog",- "icon": "list-check",+ "decoration": "windows"+ },+ "banner": {+ "content": "[FastMCP Cloud](https://fastmcp.link/x0Kyhy2) is coming!"+ },+ "colors": {+ "dark": "#f72585",+ "light": "#4cc9f0",+ "primary": "#2d00f7"+ },+ "description": "The fast, Pythonic way to build MCP servers and clients.",+ "favicon": {+ "dark": "/assets/favicon.ico",+ "light": "/assets/favicon.ico"+ },+ "footer": {+ "socials": {+ "bluesky": "https://bsky.app/profile/jlowin.dev",+ "github": "https://github.com/jlowin/fastmcp",+ "x": "https://x.com/jlowin"+ }+ },+ "integrations": {+ "ga4": {+ "measurementId": "G-64R5W1TJXG"+ }+ },+ "name": "FastMCP",+ "navbar": {+ "primary": {+ "href": "https://github.com/jlowin/fastmcp",+ "type": "github"+ }+ },+ "navigation": {+ "anchors": [+ {+ "anchor": "Documentation",+ "groups": [+ {+ "group": "Get Started",+ "pages": [+ "getting-started/welcome",+ "getting-started/installation",+ "getting-started/quickstart",+ "updates"+ ]+ },+ {+ "group": "Servers",+ "pages": [+ "servers/fastmcp",+ {+ "group": "Core Components",+ "icon": "toolbox",+ "pages": [+ "servers/tools",+ "servers/resources",+ "servers/prompts",+ "servers/context"+ ]+ },+ {+ "group": "Authentication",+ "icon": "shield-check","pages": [- "changelog"+ "servers/auth/bearer"]- },- {- "anchor": "Community",- "icon": "users",+ },+ "servers/middleware",+ "servers/openapi",+ "servers/proxy",+ "servers/composition",+ {+ "group": "Deployment",+ "icon": "upload","pages": [- "community/showcase"+ "deployment/running-server",+ "deployment/asgi"]- }+ }+ ]+ },+ {+ "group": "Clients",+ "pages": [+ "clients/client",+ "clients/transports",+ {+ "group": "Authentication",+ "icon": "user-shield",+ "pages": [+ "clients/auth/oauth",+ "clients/auth/bearer"+ ]+ },+ "clients/advanced-features"+ ]+ },+ {+ "group": "Integrations",+ "pages": [+ "integrations/anthropic",+ "integrations/claude-desktop",+ "integrations/openai",+ "integrations/gemini",+ "integrations/contrib"+ ]+ },+ {+ "group": "Patterns",+ "pages": [+ "patterns/tool-transformation",+ "patterns/decorating-methods",+ "patterns/http-requests",+ "patterns/testing",+ "patterns/cli"+ ]+ }+ ],+ "icon": "book"+ },+ {+ "anchor": "Tutorials",+ "groups": [+ {+ "group": "MCP",+ "pages": [+ "tutorials/mcp",+ "tutorials/create-mcp-server",+ "tutorials/rest-api"+ ]+ }+ ],+ "icon": "graduation-cap"+ },+ {+ "anchor": "Changelog",+ "icon": "list-check",+ "pages": [+ "changelog"]+ },+ {+ "anchor": "Community",+ "icon": "users",+ "pages": [+ "community/showcase"+ ]+ },+ {+ "anchor": "SDK Reference",+ "icon": "code",+ "pages": [+ "python-sdk/fastmcp-exceptions",+ "python-sdk/fastmcp-settings",+ {+ "group": "fastmcp.cli",+ "pages": [+ "python-sdk/fastmcp-cli-__init__",+ "python-sdk/fastmcp-cli-claude",+ "python-sdk/fastmcp-cli-cli",+ "python-sdk/fastmcp-cli-run"+ ]+ },+ {+ "group": "fastmcp.client",+ "pages": [+ {+ "group": "auth",+ "pages": [+ "python-sdk/fastmcp-client-auth-bearer",+ "python-sdk/fastmcp-client-auth-oauth"+ ]+ },+ "python-sdk/fastmcp-client-client",+ "python-sdk/fastmcp-client-logging",+ "python-sdk/fastmcp-client-oauth_callback",+ "python-sdk/fastmcp-client-progress",+ "python-sdk/fastmcp-client-roots",+ "python-sdk/fastmcp-client-sampling",+ "python-sdk/fastmcp-client-transports"+ ]+ },+ {+ "group": "fastmcp.prompts",+ "pages": [+ "python-sdk/fastmcp-prompts-prompt",+ "python-sdk/fastmcp-prompts-prompt_manager"+ ]+ },+ {+ "group": "fastmcp.resources",+ "pages": [+ "python-sdk/fastmcp-resources-resource",+ "python-sdk/fastmcp-resources-resource_manager",+ "python-sdk/fastmcp-resources-template",+ "python-sdk/fastmcp-resources-types"+ ]+ },+ {+ "group": "fastmcp.server",+ "pages": [+ {+ "group": "auth",+ "pages": [+ "python-sdk/fastmcp-server-auth-auth",+ {+ "group": "providers",+ "pages": [+ "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-context",+ "python-sdk/fastmcp-server-dependencies",+ "python-sdk/fastmcp-server-http",+ "python-sdk/fastmcp-server-middleware",+ "python-sdk/fastmcp-server-openapi",+ "python-sdk/fastmcp-server-proxy",+ "python-sdk/fastmcp-server-server"+ ]+ },+ {+ "group": "fastmcp.tools",+ "pages": [+ "python-sdk/fastmcp-tools-tool",+ "python-sdk/fastmcp-tools-tool_manager",+ "python-sdk/fastmcp-tools-tool_transform"+ ]+ },+ {+ "group": "fastmcp.utilities",+ "pages": [+ "python-sdk/fastmcp-utilities-__init__",+ "python-sdk/fastmcp-utilities-cache",+ "python-sdk/fastmcp-utilities-components",+ "python-sdk/fastmcp-utilities-exceptions",+ "python-sdk/fastmcp-utilities-http",+ "python-sdk/fastmcp-utilities-json_schema",+ "python-sdk/fastmcp-utilities-logging",+ "python-sdk/fastmcp-utilities-mcp_config",+ "python-sdk/fastmcp-utilities-openapi",+ "python-sdk/fastmcp-utilities-types"+ ]+ }+ ]+ }+ ]+ },+ "redirects": [+ {+ "destination": "/servers/proxy",+ "source": "/patterns/proxy"},- "redirects": [- {- "destination": "/servers/proxy",- "source": "/patterns/proxy"- },- {- "destination": "/servers/composition",- "source": "/patterns/composition"- }- ],- "search": {- "prompt": "Search the docs..."- },- "theme": "mint"-}\ No newline at end of file+ {+ "destination": "/servers/composition",+ "source": "/patterns/composition"+ }+ ],+ "search": {+ "prompt": "Search the docs..."+ },+ "theme": "mint"+}diff --git a/docs/python-sdk/fastmcp-cli-__init__.mdx b/docs/python-sdk/fastmcp-cli-__init__.mdxnew file mode 100644index 000000000..d2873740a--- /dev/null+++ b/docs/python-sdk/fastmcp-cli-__init__.mdx@@ -0,0 +1,9 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.cli`+++FastMCP CLI package.diff --git a/docs/python-sdk/fastmcp-cli-claude.mdx b/docs/python-sdk/fastmcp-cli-claude.mdxnew file mode 100644index 000000000..13fe7d600--- /dev/null+++ b/docs/python-sdk/fastmcp-cli-claude.mdx@@ -0,0 +1,43 @@+---+title: claude+sidebarTitle: claude+---++# `fastmcp.cli.claude`+++Claude app integration utilities.++## Functions++### `get_claude_config_path`++```python+get_claude_config_path() -> Path | None+```+++Get the Claude config directory based on platform.+++### `update_claude_config`++```python+update_claude_config(file_spec: str, server_name: str) -> bool+```+++Add or update a FastMCP server in Claude's configuration.++**Args:**+- `file_spec`: Path to the server file, optionally with :object suffix+- `server_name`: Name for the server in Claude's config+- `with_editable`: Optional directory to install in editable mode+- `with_packages`: Optional list of additional packages to install+- `env_vars`: Optional dictionary of environment variables. These are merged with+any existing variables, with new values taking precedence.++**Raises:**+- `RuntimeError`: If Claude Desktop's config directory is not found, indicating+Claude Desktop may not be installed or properly set up.+diff --git a/docs/python-sdk/fastmcp-cli-cli.mdx b/docs/python-sdk/fastmcp-cli-cli.mdxnew file mode 100644index 000000000..1ebb968b2--- /dev/null+++ b/docs/python-sdk/fastmcp-cli-cli.mdx@@ -0,0 +1,65 @@+---+title: cli+sidebarTitle: cli+---++# `fastmcp.cli.cli`+++FastMCP CLI tools.++## Functions++### `version`++```python+version(ctx: Context)+```++### `dev`++```python+dev(server_spec: str = typer.Argument(..., help='Python file to run, optionally with :object suffix'), with_editable: Annotated[Path | None, typer.Option('--with-editable', '-e', help='Directory containing pyproject.toml to install in editable mode', exists=True, file_okay=False, resolve_path=True)] = None, with_packages: Annotated[list[str], typer.Option('--with', help='Additional packages to install')] = [], inspector_version: Annotated[str | None, typer.Option('--inspector-version', help='Version of the MCP Inspector to use')] = None, ui_port: Annotated[int | None, typer.Option('--ui-port', help='Port for the MCP Inspector UI')] = None, server_port: Annotated[int | None, typer.Option('--server-port', help='Port for the MCP Inspector Proxy server')] = None) -> None+```+++Run a MCP server with the MCP Inspector.+++### `run`++```python+run(ctx: typer.Context, server_spec: str = typer.Argument(..., help='Python file, object specification (file:obj), or URL'), transport: Annotated[str | None, typer.Option('--transport', '-t', help='Transport protocol to use (stdio, streamable-http, or sse)')] = None, host: Annotated[str | None, typer.Option('--host', help='Host to bind to when using http transport (default: 127.0.0.1)')] = None, port: Annotated[int | None, typer.Option('--port', '-p', help='Port to bind to when using http transport (default: 8000)')] = None, log_level: Annotated[str | None, typer.Option('--log-level', '-l', help='Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)')] = None) -> None+```+++Run a MCP server or connect to a remote one.++The server can be specified in three ways:+1. Module approach: server.py - runs the module directly, looking for an object named mcp/server/app.++2. Import approach: server.py:app - imports and runs the specified server object.++3. URL approach: http://server-url - connects to a remote server and creates a proxy.++++Note: This command runs the server directly. You are responsible for ensuring+all dependencies are available.++Server arguments can be passed after -- :+fastmcp run server.py -- --config config.json --debug+++### `install`++```python+install(server_spec: str = typer.Argument(..., help='Python file to run, optionally with :object suffix'), server_name: Annotated[str | None, typer.Option('--name', '-n', help="Custom name for the server (defaults to server's name attribute or file name)")] = None, with_editable: Annotated[Path | None, typer.Option('--with-editable', '-e', help='Directory containing pyproject.toml to install in editable mode', exists=True, file_okay=False, resolve_path=True)] = None, with_packages: Annotated[list[str], typer.Option('--with', help='Additional packages to install')] = [], env_vars: Annotated[list[str], typer.Option('--env-var', '-v', help='Environment variables in KEY=VALUE format')] = [], env_file: Annotated[Path | None, typer.Option('--env-file', '-f', help='Load environment variables from a .env file', exists=True, file_okay=True, dir_okay=False, resolve_path=True)] = None) -> None+```+++Install a MCP server in the Claude desktop app.++Environment variables are preserved once added and only updated if new values+are explicitly provided.+diff --git a/docs/python-sdk/fastmcp-cli-run.mdx b/docs/python-sdk/fastmcp-cli-run.mdxnew file mode 100644index 000000000..bdb07beac--- /dev/null+++ b/docs/python-sdk/fastmcp-cli-run.mdx@@ -0,0 +1,106 @@+---+title: run+sidebarTitle: run+---++# `fastmcp.cli.run`+++FastMCP run command implementation.++## Functions++### `is_url`++```python+is_url(path: str) -> bool+```+++Check if a string is a URL.+++### `parse_file_path`++```python+parse_file_path(server_spec: str) -> tuple[Path, str | None]+```+++Parse a file path that may include a server object specification.++**Args:**+- `server_spec`: Path to file, optionally with :object suffix++**Returns:**+- Tuple of (file_path, server_object)+++### `import_server`++```python+import_server(file: Path, server_object: str | None = None) -> Any+```+++Import a MCP server from a file.++**Args:**+- `file`: Path to the file+- `server_object`: Optional object name in format "module:object" or just "object"++**Returns:**+- The server object+++### `create_client_server`++```python+create_client_server(url: str) -> Any+```+++Create a FastMCP server from a client URL.++**Args:**+- `url`: The URL to connect to++**Returns:**+- A FastMCP server instance+++### `import_server_with_args`++```python+import_server_with_args(file: Path, server_object: str | None = None, server_args: list[str] | None = None) -> Any+```+++Import a server with optional command line arguments.++**Args:**+- `file`: Path to the server file+- `server_object`: Optional server object name+- `server_args`: Optional command line arguments to inject++**Returns:**+- The imported server object+++### `run_command`++```python+run_command(server_spec: str, transport: str | None = None, host: str | None = None, port: int | None = None, log_level: str | None = None, server_args: list[str] | None = None) -> None+```+++Run a MCP server or connect to a remote one.++**Args:**+- `server_spec`: Python file, object specification (file:obj), or URL+- `transport`: Transport protocol to use+- `host`: Host to bind to when using http transport+- `port`: Port to bind to when using http transport+- `log_level`: Log level+- `server_args`: Additional arguments to pass to the server+diff --git a/docs/python-sdk/fastmcp-client-__init__.mdx b/docs/python-sdk/fastmcp-client-__init__.mdxnew file mode 100644index 000000000..bc145d4b7--- /dev/null+++ b/docs/python-sdk/fastmcp-client-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.client`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-client-auth-__init__.mdx b/docs/python-sdk/fastmcp-client-auth-__init__.mdxnew file mode 100644index 000000000..28242780d--- /dev/null+++ b/docs/python-sdk/fastmcp-client-auth-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.client.auth`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-client-auth-bearer.mdx b/docs/python-sdk/fastmcp-client-auth-bearer.mdxnew file mode 100644index 000000000..ab0c15240--- /dev/null+++ b/docs/python-sdk/fastmcp-client-auth-bearer.mdx@@ -0,0 +1,18 @@+---+title: bearer+sidebarTitle: bearer+---++# `fastmcp.client.auth.bearer`++## Classes++### `BearerAuth`++**Methods:**++#### `auth_flow`++```python+auth_flow(self, request)+```diff --git a/docs/python-sdk/fastmcp-client-auth-oauth.mdx b/docs/python-sdk/fastmcp-client-auth-oauth.mdxnew file mode 100644index 000000000..d299c1a95--- /dev/null+++ b/docs/python-sdk/fastmcp-client-auth-oauth.mdx@@ -0,0 +1,103 @@+---+title: oauth+sidebarTitle: oauth+---++# `fastmcp.client.auth.oauth`++## Functions++### `default_cache_dir`++```python+default_cache_dir() -> Path+```++### `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) -> _MCPOAuthClientProvider+```+++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++### `ServerOAuthMetadata`+++More flexible OAuth metadata model that accepts broader ranges of values+than the restrictive MCP standard model.++This handles real-world OAuth servers like PayPal that may support+additional methods not in the MCP specification.+++### `OAuthClientProvider`+++OAuth client provider with more flexible OAuth metadata discovery.+++### `FileTokenStorage`+++File-based token storage implementation for OAuth credentials and tokens.+Implements the mcp.client.auth.TokenStorage protocol.++Each instance is tied to a specific server URL for proper token isolation.+++**Methods:**++#### `get_base_url`++```python+get_base_url(url: str) -> str+```++Extract the base URL (scheme + host) from a URL.+++#### `get_cache_key`++```python+get_cache_key(self) -> str+```++Generate a safe filesystem key from the server's base URL.+++#### `clear`++```python+clear(self) -> None+```++Clear all cached data for this server.+++#### `clear_all`++```python+clear_all(cls, cache_dir: Path | None = None) -> None+```++Clear all cached data for all servers.+diff --git a/docs/python-sdk/fastmcp-client-client.mdx b/docs/python-sdk/fastmcp-client-client.mdxnew file mode 100644index 000000000..4c3f252bf--- /dev/null+++ b/docs/python-sdk/fastmcp-client-client.mdx@@ -0,0 +1,94 @@+---+title: client+sidebarTitle: client+---++# `fastmcp.client.client`++## Classes++### `Client`++++ MCP client that delegates connection management to a Transport instance.++ The Client class is responsible for MCP protocol logic, while the Transport+ handles connection establishment and management. Client provides methods for+ working with resources, prompts, tools and other MCP capabilities.++ Args:+ transport: Connection source specification, which can be:+ - ClientTransport: Direct transport instance+ - FastMCP: In-process FastMCP server+ - AnyUrl | str: URL to connect to+ - Path: File path for local socket+ - MCPConfig: MCP server configuration+ - dict: Transport configuration+ roots: Optional RootsList or RootsHandler for filesystem access+ sampling_handler: Optional handler for sampling requests+ log_handler: Optional handler for log messages+ message_handler: Optional handler for protocol messages+ progress_handler: Optional handler for progress notifications+ timeout: Optional timeout for requests (seconds or timedelta)+ init_timeout: Optional timeout for initial connection (seconds or timedelta).+ Set to 0 to disable. If None, uses the value in the FastMCP global settings.++ Examples:+ ```python # Connect to FastMCP server client =+ Client("http://localhost:8080")++ async with client:+ # List available resources resources = await client.list_resources()++ # Call a tool result = await client.call_tool("my_tool", {"param":+ "value"})+ ```+++**Methods:**++#### `session`++```python+session(self) -> ClientSession+```++Get the current active session. Raises RuntimeError if not connected.+++#### `initialize_result`++```python+initialize_result(self) -> mcp.types.InitializeResult+```++Get the result of the initialization request.+++#### `set_roots`++```python+set_roots(self, roots: RootsList | RootsHandler) -> None+```++Set the roots for the client. This does not automatically call `send_roots_list_changed`.+++#### `set_sampling_callback`++```python+set_sampling_callback(self, sampling_callback: SamplingHandler) -> None+```++Set the sampling callback for the client.+++#### `is_connected`++```python+is_connected(self) -> bool+```++Check if the client is currently connected.+diff --git a/docs/python-sdk/fastmcp-client-logging.mdx b/docs/python-sdk/fastmcp-client-logging.mdxnew file mode 100644index 000000000..84d201db7--- /dev/null+++ b/docs/python-sdk/fastmcp-client-logging.mdx@@ -0,0 +1,14 @@+---+title: logging+sidebarTitle: logging+---++# `fastmcp.client.logging`++## Functions++### `create_log_callback`++```python+create_log_callback(handler: LogHandler | None = None) -> LoggingFnT+```diff --git a/docs/python-sdk/fastmcp-client-oauth_callback.mdx b/docs/python-sdk/fastmcp-client-oauth_callback.mdxnew file mode 100644index 000000000..6eab9de3a--- /dev/null+++ b/docs/python-sdk/fastmcp-client-oauth_callback.mdx@@ -0,0 +1,63 @@+---+title: oauth_callback+sidebarTitle: oauth_callback+---++# `fastmcp.client.oauth_callback`++++OAuth callback server for handling authorization code flows.++This module provides a reusable callback server that can handle OAuth redirects+and display styled responses to users.+++## Functions++### `create_callback_html`++```python+create_callback_html(message: str, is_success: bool = True, title: str = 'FastMCP OAuth', server_url: str | None = None) -> str+```+++Create a styled HTML response for OAuth callbacks.+++### `create_oauth_callback_server`++```python+create_oauth_callback_server(port: int, callback_path: str = '/callback', server_url: str | None = None, response_future: asyncio.Future | None = None) -> Server+```+++Create an OAuth callback server.++**Args:**+- `port`: The port to run the server on+- `callback_path`: The path to listen for OAuth redirects on+- `server_url`: Optional server URL to display in success messages+- `response_future`: Optional future to resolve when OAuth callback is received++**Returns:**+- Configured uvicorn Server instance (not yet running)+++## Classes++### `CallbackResponse`++**Methods:**++#### `from_dict`++```python+from_dict(cls, data: dict[str, str]) -> CallbackResponse+```++#### `to_dict`++```python+to_dict(self) -> dict[str, str]+```diff --git a/docs/python-sdk/fastmcp-client-progress.mdx b/docs/python-sdk/fastmcp-client-progress.mdxnew file mode 100644index 000000000..aecd0f37b--- /dev/null+++ b/docs/python-sdk/fastmcp-client-progress.mdx@@ -0,0 +1,8 @@+---+title: progress+sidebarTitle: progress+---++# `fastmcp.client.progress`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-client-roots.mdx b/docs/python-sdk/fastmcp-client-roots.mdxnew file mode 100644index 000000000..820e1d0a7--- /dev/null+++ b/docs/python-sdk/fastmcp-client-roots.mdx@@ -0,0 +1,20 @@+---+title: roots+sidebarTitle: roots+---++# `fastmcp.client.roots`++## Functions++### `convert_roots_list`++```python+convert_roots_list(roots: RootsList) -> list[mcp.types.Root]+```++### `create_roots_callback`++```python+create_roots_callback(handler: RootsList | RootsHandler) -> ListRootsFnT+```diff --git a/docs/python-sdk/fastmcp-client-sampling.mdx b/docs/python-sdk/fastmcp-client-sampling.mdxnew file mode 100644index 000000000..be78badeb--- /dev/null+++ b/docs/python-sdk/fastmcp-client-sampling.mdx@@ -0,0 +1,14 @@+---+title: sampling+sidebarTitle: sampling+---++# `fastmcp.client.sampling`++## Functions++### `create_sampling_callback`++```python+create_sampling_callback(sampling_handler: SamplingHandler) -> SamplingFnT+```diff --git a/docs/python-sdk/fastmcp-client-transports.mdx b/docs/python-sdk/fastmcp-client-transports.mdxnew file mode 100644index 000000000..a4f9d22e6--- /dev/null+++ b/docs/python-sdk/fastmcp-client-transports.mdx@@ -0,0 +1,191 @@+---+title: transports+sidebarTitle: transports+---++# `fastmcp.client.transports`++## Functions++### `infer_transport`++```python+infer_transport(transport: ClientTransport | FastMCP | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str) -> ClientTransport+```++++ Infer the appropriate transport type from the given transport argument.++ This function attempts to infer the correct transport type from the provided+ argument, handling various input types and converting them to the appropriate+ ClientTransport subclass.++ The function supports these input types:+ - ClientTransport: Used directly without modification+ - FastMCP or FastMCP1Server: Creates an in-memory FastMCPTransport+ - Path or str (file path): Creates PythonStdioTransport (.py) or NodeStdioTransport (.js)+ - AnyUrl or str (URL): Creates StreamableHttpTransport (default) or SSETransport (for /sse endpoints)+ - MCPConfig or dict: Creates MCPConfigTransport, potentially connecting to multiple servers++ For HTTP URLs, they are assumed to be Streamable HTTP URLs unless they end in `/sse`.++ For MCPConfig with multiple servers, a composite client is created where each server+ is mounted with its name as prefix. This allows accessing tools and resources from multiple+ servers through a single unified client interface, using naming patterns like+ `servername_toolname` for tools and `protocol://servername/path` for resources.+ If the MCPConfig contains only one server, a direct connection is established without prefixing.++ Examples:+ ```python+ # Connect to a local Python script+ transport = infer_transport("my_script.py")++ # Connect to a remote server via HTTP+ transport = infer_transport("http://example.com/mcp")++ # Connect to multiple servers using MCPConfig+ config = {+ "mcpServers": {+ "weather": {"url": "http://weather.example.com/mcp"},+ "calendar": {"url": "http://calendar.example.com/mcp"}+ }+ }+ transport = infer_transport(config)+ ```+++## Classes++### `SessionKwargs`+++Keyword arguments for the MCP ClientSession constructor.+++### `ClientTransport`+++Abstract base class for different MCP client transport mechanisms.++A Transport is responsible for establishing and managing connections+to an MCP server, and providing a ClientSession within an async context.+++### `WSTransport`+++Transport implementation that connects to an MCP server via WebSockets.+++### `SSETransport`+++Transport implementation that connects to an MCP server via Server-Sent Events.+++### `StreamableHttpTransport`+++Transport implementation that connects to an MCP server via Streamable HTTP Requests.+++### `StdioTransport`+++Base transport for connecting to an MCP server via subprocess with stdio.++This is a base class that can be subclassed for specific command-based+transports like Python, Node, Uvx, etc.+++### `PythonStdioTransport`+++Transport for running Python scripts.+++### `FastMCPStdioTransport`+++Transport for running FastMCP servers using the FastMCP CLI.+++### `NodeStdioTransport`+++Transport for running Node.js scripts.+++### `UvxStdioTransport`+++Transport for running commands via the uvx tool.+++### `NpxStdioTransport`+++Transport for running commands via the npx tool.+++### `FastMCPTransport`+++In-memory transport for FastMCP servers.++This transport connects directly to a FastMCP server instance in the same+Python process. It works with both FastMCP 2.x servers and FastMCP 1.0+servers from the low-level MCP SDK. This is particularly useful for unit+tests or scenarios where client and server run in the same runtime.+++### `MCPConfigTransport`+++Transport for connecting to one or more MCP servers defined in an MCPConfig.++ This transport provides a unified interface to multiple MCP servers defined in an MCPConfig+ object or dictionary matching the MCPConfig schema. It supports two key scenarios:++ 1. If the MCPConfig contains exactly one server, it creates a direct transport to that server.+ 2. If the MCPConfig contains multiple servers, it creates a composite client by mounting+ all servers on a single FastMCP instance, with each server's name used as its mounting prefix.++ In the multi-server case, tools are accessible with the prefix pattern `{server_name}_{tool_name}`+ and resources with the pattern `protocol://{server_name}/path/to/resource`.++ This is particularly useful for creating clients that need to interact with multiple specialized+ MCP servers through a single interface, simplifying client code.++ Examples:+ ```python+ from fastmcp import Client+ from fastmcp.utilities.mcp_config import MCPConfig++ # Create a config with multiple servers+ config = {+ "mcpServers": {+ "weather": {+ "url": "https://weather-api.example.com/mcp",+ "transport": "streamable-http"+ },+ "calendar": {+ "url": "https://calendar-api.example.com/mcp",+ "transport": "streamable-http"+ }+ }+ }++ # Create a client with the config+ client = Client(config)++ async with client:+ # Access tools with prefixes+ weather = await client.call_tool("weather_get_forecast", {"city": "London"})+ events = await client.call_tool("calendar_list_events", {"date": "2023-06-01"})++ # Access resources with prefixed URIs+ icons = await client.read_resource("weather://weather/icons/sunny")+ ```+diff --git a/docs/python-sdk/fastmcp-exceptions.mdx b/docs/python-sdk/fastmcp-exceptions.mdxnew file mode 100644index 000000000..9726d1cde--- /dev/null+++ b/docs/python-sdk/fastmcp-exceptions.mdx@@ -0,0 +1,65 @@+---+title: exceptions+sidebarTitle: exceptions+---++# `fastmcp.exceptions`+++Custom exceptions for FastMCP.++## Classes++### `FastMCPError`+++Base error for FastMCP.+++### `ValidationError`+++Error in validating parameters or return values.+++### `ResourceError`+++Error in resource operations.+++### `ToolError`+++Error in tool operations.+++### `PromptError`+++Error in prompt operations.+++### `InvalidSignature`+++Invalid signature for use with FastMCP.+++### `ClientError`+++Error in client operations.+++### `NotFoundError`+++Object not found.+++### `DisabledError`+++Object is disabled.+diff --git a/docs/python-sdk/fastmcp-prompts-__init__.mdx b/docs/python-sdk/fastmcp-prompts-__init__.mdxnew file mode 100644index 000000000..8ef80b59e--- /dev/null+++ b/docs/python-sdk/fastmcp-prompts-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.prompts`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-prompts-prompt.mdx b/docs/python-sdk/fastmcp-prompts-prompt.mdxnew file mode 100644index 000000000..60028f316--- /dev/null+++ b/docs/python-sdk/fastmcp-prompts-prompt.mdx@@ -0,0 +1,84 @@+---+title: prompt+sidebarTitle: prompt+---++# `fastmcp.prompts.prompt`+++Base classes for FastMCP prompts.++## Functions++### `Message`++```python+Message(content: str | MCPContent, role: Role | None = None, **kwargs: Any) -> PromptMessage+```+++A user-friendly constructor for PromptMessage.+++## Classes++### `PromptArgument`+++An argument that can be passed to a prompt.+++### `Prompt`+++A prompt template that can be rendered with parameters.+++**Methods:**++#### `to_mcp_prompt`++```python+to_mcp_prompt(self, **overrides: Any) -> MCPPrompt+```++Convert the prompt to an MCP prompt.+++#### `from_function`++```python+from_function(fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, description: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionPrompt+```++Create a Prompt from a function.++The function can return:+- A string (converted to a message)+- A Message object+- A dict (converted to a message)+- A sequence of any of the above+++### `FunctionPrompt`+++A prompt that is a function.+++**Methods:**++#### `from_function`++```python+from_function(cls, fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, description: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionPrompt+```++Create a Prompt from a function.++The function can return:+- A string (converted to a message)+- A Message object+- A dict (converted to a message)+- A sequence of any of the above+diff --git a/docs/python-sdk/fastmcp-prompts-prompt_manager.mdx b/docs/python-sdk/fastmcp-prompts-prompt_manager.mdxnew file mode 100644index 000000000..041337c28--- /dev/null+++ b/docs/python-sdk/fastmcp-prompts-prompt_manager.mdx@@ -0,0 +1,43 @@+---+title: prompt_manager+sidebarTitle: prompt_manager+---++# `fastmcp.prompts.prompt_manager`++## Classes++### `PromptManager`+++Manages FastMCP prompts.+++**Methods:**++#### `mount`++```python+mount(self, server: MountedServer) -> None+```++Adds a mounted server as a source for prompts.+++#### `add_prompt_from_fn`++```python+add_prompt_from_fn(self, fn: Callable[..., PromptResult | Awaitable[PromptResult]], name: str | None = None, description: str | None = None, tags: set[str] | None = None) -> FunctionPrompt+```++Create a prompt from a function.+++#### `add_prompt`++```python+add_prompt(self, prompt: Prompt) -> Prompt+```++Add a prompt to the manager.+diff --git a/docs/python-sdk/fastmcp-resources-__init__.mdx b/docs/python-sdk/fastmcp-resources-__init__.mdxnew file mode 100644index 000000000..cc5fd2786--- /dev/null+++ b/docs/python-sdk/fastmcp-resources-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.resources`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-resources-resource.mdx b/docs/python-sdk/fastmcp-resources-resource.mdxnew file mode 100644index 000000000..dcfc51f00--- /dev/null+++ b/docs/python-sdk/fastmcp-resources-resource.mdx@@ -0,0 +1,90 @@+---+title: resource+sidebarTitle: resource+---++# `fastmcp.resources.resource`+++Base classes and interfaces for FastMCP resources.++## Classes++### `Resource`+++Base class for all resources.+++**Methods:**++#### `from_function`++```python+from_function(fn: Callable[[], Any], uri: str | AnyUrl, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResource+```++#### `set_default_mime_type`++```python+set_default_mime_type(cls, mime_type: str | None) -> str+```++Set default MIME type if not provided.+++#### `set_default_name`++```python+set_default_name(self) -> Self+```++Set default name from URI if not provided.+++#### `to_mcp_resource`++```python+to_mcp_resource(self, **overrides: Any) -> MCPResource+```++Convert the resource to an MCPResource.+++#### `key`++```python+key(self) -> str+```++The key of the component. This is used for internal bookkeeping+and may reflect e.g. prefixes or other identifiers. You should not depend on+keys having a certain value, as the same tool loaded from different+hierarchies of servers may have different keys.+++### `FunctionResource`+++A resource that defers data loading by wrapping a function.++The function is only called when the resource is read, allowing for lazy loading+of potentially expensive data. This is particularly useful when listing resources,+as the function won't be called until the resource is actually accessed.++The function can return:+- str for text content (default)+- bytes for binary content+- other types will be converted to JSON+++**Methods:**++#### `from_function`++```python+from_function(cls, fn: Callable[[], Any], uri: str | AnyUrl, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResource+```++Create a FunctionResource from a function.+diff --git a/docs/python-sdk/fastmcp-resources-resource_manager.mdx b/docs/python-sdk/fastmcp-resources-resource_manager.mdxnew file mode 100644index 000000000..9adb43e83--- /dev/null+++ b/docs/python-sdk/fastmcp-resources-resource_manager.mdx@@ -0,0 +1,111 @@+---+title: resource_manager+sidebarTitle: resource_manager+---++# `fastmcp.resources.resource_manager`+++Resource manager functionality.++## Classes++### `ResourceManager`+++Manages FastMCP resources.+++**Methods:**++#### `mount`++```python+mount(self, server: MountedServer) -> None+```++Adds a mounted server as a source for resources and templates.+++#### `add_resource_or_template_from_fn`++```python+add_resource_or_template_from_fn(self, fn: Callable[..., Any], uri: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None) -> Resource | ResourceTemplate+```++Add a resource or template to the manager from a function.++**Args:**+- `fn`: The function to register as a resource or template+- `uri`: The URI for the resource or template+- `name`: Optional name for the resource or template+- `description`: Optional description of the resource or template+- `mime_type`: Optional MIME type for the resource or template+- `tags`: Optional set of tags for categorizing the resource or template++**Returns:**+- The added resource or template. If a resource or template with the same URI already exists,+- returns the existing resource or template.+++#### `add_resource_from_fn`++```python+add_resource_from_fn(self, fn: Callable[..., Any], uri: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None) -> Resource+```++Add a resource to the manager from a function.++**Args:**+- `fn`: The function to register as a resource+- `uri`: The URI for the resource+- `name`: Optional name for the resource+- `description`: Optional description of the resource+- `mime_type`: Optional MIME type for the resource+- `tags`: Optional set of tags for categorizing the resource++**Returns:**+- The added resource. If a resource with the same URI already exists,+- returns the existing resource.+++#### `add_resource`++```python+add_resource(self, resource: Resource) -> Resource+```++Add a resource to the manager.++**Args:**+- `resource`: A Resource instance to add. The resource's .key attribute+will be used as the storage key. To overwrite it, call+Resource.with_key() before calling this method.+++#### `add_template_from_fn`++```python+add_template_from_fn(self, fn: Callable[..., Any], uri_template: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None) -> ResourceTemplate+```++Create a template from a function.+++#### `add_template`++```python+add_template(self, template: ResourceTemplate) -> ResourceTemplate+```++Add a template to the manager.++**Args:**+- `template`: A ResourceTemplate instance to add. The template's .key attribute+will be used as the storage key. To overwrite it, call+ResourceTemplate.with_key() before calling this method.++**Returns:**+- The added template. If a template with the same URI already exists,+- returns the existing template.+diff --git a/docs/python-sdk/fastmcp-resources-template.mdx b/docs/python-sdk/fastmcp-resources-template.mdxnew file mode 100644index 000000000..c1810f097--- /dev/null+++ b/docs/python-sdk/fastmcp-resources-template.mdx@@ -0,0 +1,104 @@+---+title: template+sidebarTitle: template+---++# `fastmcp.resources.template`+++Resource template functionality.++## Functions++### `build_regex`++```python+build_regex(template: str) -> re.Pattern+```++### `match_uri_template`++```python+match_uri_template(uri: str, uri_template: str) -> dict[str, str] | None+```++## Classes++### `ResourceTemplate`+++A template for dynamically creating resources.+++**Methods:**++#### `from_function`++```python+from_function(fn: Callable[..., Any], uri_template: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResourceTemplate+```++#### `set_default_mime_type`++```python+set_default_mime_type(cls, mime_type: str | None) -> str+```++Set default MIME type if not provided.+++#### `matches`++```python+matches(self, uri: str) -> dict[str, Any] | None+```++Check if URI matches template and extract parameters.+++#### `to_mcp_template`++```python+to_mcp_template(self, **overrides: Any) -> MCPResourceTemplate+```++Convert the resource template to an MCPResourceTemplate.+++#### `from_mcp_template`++```python+from_mcp_template(cls, mcp_template: MCPResourceTemplate) -> ResourceTemplate+```++Creates a FastMCP ResourceTemplate from a raw MCP ResourceTemplate object.+++#### `key`++```python+key(self) -> str+```++The key of the component. This is used for internal bookkeeping+and may reflect e.g. prefixes or other identifiers. You should not depend on+keys having a certain value, as the same tool loaded from different+hierarchies of servers may have different keys.+++### `FunctionResourceTemplate`+++A template for dynamically creating resources.+++**Methods:**++#### `from_function`++```python+from_function(cls, fn: Callable[..., Any], uri_template: str, name: str | None = None, description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, enabled: bool | None = None) -> FunctionResourceTemplate+```++Create a template from a function.+diff --git a/docs/python-sdk/fastmcp-resources-types.mdx b/docs/python-sdk/fastmcp-resources-types.mdxnew file mode 100644index 000000000..675b44cc1--- /dev/null+++ b/docs/python-sdk/fastmcp-resources-types.mdx@@ -0,0 +1,83 @@+---+title: types+sidebarTitle: types+---++# `fastmcp.resources.types`+++Concrete resource implementations.++## Classes++### `TextResource`+++A resource that reads from a string.+++### `BinaryResource`+++A resource that reads from bytes.+++### `FileResource`+++A resource that reads from a file.++Set is_binary=True to read file as binary data instead of text.+++**Methods:**++#### `validate_absolute_path`++```python+validate_absolute_path(cls, path: Path) -> Path+```++Ensure path is absolute.+++#### `set_binary_from_mime_type`++```python+set_binary_from_mime_type(cls, is_binary: bool, info: ValidationInfo) -> bool+```++Set is_binary based on mime_type if not explicitly set.+++### `HttpResource`+++A resource that reads from an HTTP endpoint.+++### `DirectoryResource`+++A resource that lists files in a directory.+++**Methods:**++#### `validate_absolute_path`++```python+validate_absolute_path(cls, path: Path) -> Path+```++Ensure path is absolute.+++#### `list_files`++```python+list_files(self) -> list[Path]+```++List files in the directory.+diff --git a/docs/python-sdk/fastmcp-server-__init__.mdx b/docs/python-sdk/fastmcp-server-__init__.mdxnew file mode 100644index 000000000..157a018ce--- /dev/null+++ b/docs/python-sdk/fastmcp-server-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.server`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-server-auth-__init__.mdx b/docs/python-sdk/fastmcp-server-auth-__init__.mdxnew file mode 100644index 000000000..c86f07005--- /dev/null+++ b/docs/python-sdk/fastmcp-server-auth-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.server.auth`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-server-auth-auth.mdx b/docs/python-sdk/fastmcp-server-auth-auth.mdxnew file mode 100644index 000000000..8a20aa716--- /dev/null+++ b/docs/python-sdk/fastmcp-server-auth-auth.mdx@@ -0,0 +1,10 @@+---+title: auth+sidebarTitle: auth+---++# `fastmcp.server.auth.auth`++## Classes++### `OAuthProvider`diff --git a/docs/python-sdk/fastmcp-server-auth-providers-__init__.mdx b/docs/python-sdk/fastmcp-server-auth-providers-__init__.mdxnew file mode 100644index 000000000..9de7cce8a--- /dev/null+++ b/docs/python-sdk/fastmcp-server-auth-providers-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.server.auth.providers`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdx b/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdxnew file mode 100644index 000000000..d619de127--- /dev/null+++ b/docs/python-sdk/fastmcp-server-auth-providers-bearer.mdx@@ -0,0 +1,69 @@+---+title: bearer+sidebarTitle: bearer+---++# `fastmcp.server.auth.providers.bearer`++## Classes++### `JWKData`+++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 | 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 (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. 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.+diff --git a/docs/python-sdk/fastmcp-server-auth-providers-bearer_env.mdx b/docs/python-sdk/fastmcp-server-auth-providers-bearer_env.mdxnew file mode 100644index 000000000..f64c65c84--- /dev/null+++ b/docs/python-sdk/fastmcp-server-auth-providers-bearer_env.mdx@@ -0,0 +1,22 @@+---+title: bearer_env+sidebarTitle: bearer_env+---++# `fastmcp.server.auth.providers.bearer_env`++## Classes++### `EnvBearerAuthProviderSettings`+++Settings for the BearerAuthProvider.+++### `EnvBearerAuthProvider`+++A BearerAuthProvider that loads settings from environment variables. Any+providing setting will always take precedence over the environment+variables.+diff --git a/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx b/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdxnew file mode 100644index 000000000..ef34ce2fb--- /dev/null+++ b/docs/python-sdk/fastmcp-server-auth-providers-in_memory.mdx@@ -0,0 +1,15 @@+---+title: in_memory+sidebarTitle: in_memory+---++# `fastmcp.server.auth.providers.in_memory`++## Classes++### `InMemoryOAuthProvider`+++An in-memory OAuth provider for testing purposes.+It simulates the OAuth 2.1 flow locally without external calls.+diff --git a/docs/python-sdk/fastmcp-server-context.mdx b/docs/python-sdk/fastmcp-server-context.mdxnew file mode 100644index 000000000..ea1d92643--- /dev/null+++ b/docs/python-sdk/fastmcp-server-context.mdx@@ -0,0 +1,118 @@+---+title: context+sidebarTitle: context+---++# `fastmcp.server.context`++## Functions++### `set_context`++```python+set_context(context: Context) -> Generator[Context, None, None]+```++## Classes++### `Context`+++Context object providing access to MCP capabilities.++This provides a cleaner interface to MCP's RequestContext functionality.+It gets injected into tool and resource functions that request it via type hints.++To use context in a tool function, add a parameter with the Context type annotation:++```python+def my_tool(x: int, ctx: Context) -> str:+ # Log messages to the client+ ctx.info(f"Processing {x}")+ ctx.debug("Debug info")+ ctx.warning("Warning message")+ ctx.error("Error message")++ # Report progress+ ctx.report_progress(50, 100, "Processing")++ # Access resources+ data = ctx.read_resource("resource://data")++ # Get request info+ request_id = ctx.request_id+ client_id = ctx.client_id++ return str(x)+```++The context parameter name can be anything as long as it's annotated with Context.+The context is optional - tools that don't need it can omit the parameter.+++**Methods:**++#### `request_context`++```python+request_context(self) -> RequestContext+```++Access to the underlying request context.++If called outside of a request context, this will raise a ValueError.+++#### `client_id`++```python+client_id(self) -> str | None+```++Get the client ID if available.+++#### `request_id`++```python+request_id(self) -> str+```++Get the unique ID for this request.+++#### `session_id`++```python+session_id(self) -> str | None+```++Get the MCP session ID for HTTP 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.+++#### `session`++```python+session(self)+```++Access to the underlying session for advanced usage.+++#### `get_http_request`++```python+get_http_request(self) -> Request+```++Get the active starlette request.+diff --git a/docs/python-sdk/fastmcp-server-dependencies.mdx b/docs/python-sdk/fastmcp-server-dependencies.mdxnew file mode 100644index 000000000..0d6c37074--- /dev/null+++ b/docs/python-sdk/fastmcp-server-dependencies.mdx@@ -0,0 +1,36 @@+---+title: dependencies+sidebarTitle: dependencies+---++# `fastmcp.server.dependencies`++## Functions++### `get_context`++```python+get_context() -> Context+```++### `get_http_request`++```python+get_http_request() -> Request+```++### `get_http_headers`++```python+get_http_headers(include_all: bool = False) -> dict[str, str]+```+++Extract headers from the current HTTP request if available.++Never raises an exception, even if there is no active HTTP request (in which case+an empty dict is returned).++By default, strips problematic headers like `content-length` that cause issues if forwarded to downstream clients.+If `include_all` is True, all headers are returned.+diff --git a/docs/python-sdk/fastmcp-server-http.mdx b/docs/python-sdk/fastmcp-server-http.mdxnew file mode 100644index 000000000..63f2768cb--- /dev/null+++ b/docs/python-sdk/fastmcp-server-http.mdx@@ -0,0 +1,113 @@+---+title: http+sidebarTitle: http+---++# `fastmcp.server.http`++## Functions++### `set_http_request`++```python+set_http_request(request: Request) -> Generator[Request, None, None]+```++### `setup_auth_middleware_and_routes`++```python+setup_auth_middleware_and_routes(auth: OAuthProvider) -> tuple[list[Middleware], list[BaseRoute], list[str]]+```+++Set up authentication middleware and routes if auth is enabled.++**Args:**+- `auth`: The OAuthProvider authorization server provider++**Returns:**+- Tuple of (middleware, auth_routes, required_scopes)+++### `create_base_app`++```python+create_base_app(routes: list[BaseRoute], middleware: list[Middleware], debug: bool = False, lifespan: Callable | None = None) -> StarletteWithLifespan+```+++Create a base Starlette app with common middleware and routes.++**Args:**+- `routes`: List of routes to include in the app+- `middleware`: List of middleware to include in the app+- `debug`: Whether to enable debug mode+- `lifespan`: Optional lifespan manager for the app++**Returns:**+- A Starlette application+++### `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+```+++Return an instance of the SSE server app.++**Args:**+- `server`: The FastMCP server instance+- `message_path`: Path for SSE messages+- `sse_path`: Path for SSE connections+- `auth`: Optional auth provider+- `debug`: Whether to enable debug mode+- `routes`: Optional list of custom routes+- `middleware`: Optional list of middleware++Returns:+ A Starlette application with RequestContextMiddleware+++### `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+```+++Return an instance of the StreamableHTTP server app.++**Args:**+- `server`: The FastMCP server instance+- `streamable_http_path`: Path for StreamableHTTP connections+- `event_store`: Optional event store for session management+- `auth`: Optional auth provider+- `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+- `routes`: Optional list of custom routes+- `middleware`: Optional list of middleware++**Returns:**+- A Starlette application with StreamableHTTP support+++## Classes++### `StarletteWithLifespan`++**Methods:**++#### `lifespan`++```python+lifespan(self) -> Lifespan+```++### `RequestContextMiddleware`+++Middleware that stores each request in a ContextVar+diff --git a/docs/python-sdk/fastmcp-server-middleware.mdx b/docs/python-sdk/fastmcp-server-middleware.mdxnew file mode 100644index 000000000..ec8eab242--- /dev/null+++ b/docs/python-sdk/fastmcp-server-middleware.mdx@@ -0,0 +1,56 @@+---+title: middleware+sidebarTitle: middleware+---++# `fastmcp.server.middleware`++## Functions++### `make_middleware_wrapper`++```python+make_middleware_wrapper(middleware: Middleware, call_next: CallNext[T, R]) -> CallNext[T, R]+```+++Create a wrapper that applies a single middleware to a context. The+closure bakes in the middleware and call_next function, so it can be+passed to other functions that expect a call_next function.+++## Classes++### `CallNext`++### `CallToolResult`++### `ListToolsResult`++### `ListResourcesResult`++### `ListResourceTemplatesResult`++### `ListPromptsResult`++### `ServerResultProtocol`++### `MiddlewareContext`+++Unified context for all middleware operations.+++**Methods:**++#### `copy`++```python+copy(self, **kwargs: Any) -> MiddlewareContext[T]+```++### `Middleware`+++Base class for FastMCP middleware with dispatching hooks.+diff --git a/docs/python-sdk/fastmcp-server-openapi.mdx b/docs/python-sdk/fastmcp-server-openapi.mdxnew file mode 100644index 000000000..d2490cea7--- /dev/null+++ b/docs/python-sdk/fastmcp-server-openapi.mdx@@ -0,0 +1,58 @@+---+title: openapi+sidebarTitle: openapi+---++# `fastmcp.server.openapi`+++FastMCP server implementation for OpenAPI integration.++## Classes++### `MCPType`+++Type of FastMCP component to create from a route.+++### `RouteType`+++Deprecated: Use MCPType instead.++This enum is kept for backward compatibility and will be removed in a future version.+++### `RouteMap`+++Mapping configuration for HTTP routes to FastMCP component types.+++### `OpenAPITool`+++Tool implementation for OpenAPI endpoints.+++### `OpenAPIResource`+++Resource implementation for OpenAPI endpoints.+++### `OpenAPIResourceTemplate`+++Resource template implementation for OpenAPI endpoints.+++### `FastMCPOpenAPI`+++FastMCP server implementation that creates components from an OpenAPI schema.++This class parses an OpenAPI specification and creates appropriate FastMCP components+(Tools, Resources, ResourceTemplates) based on route mappings.+diff --git a/docs/python-sdk/fastmcp-server-proxy.mdx b/docs/python-sdk/fastmcp-server-proxy.mdxnew file mode 100644index 000000000..bad549605--- /dev/null+++ b/docs/python-sdk/fastmcp-server-proxy.mdx@@ -0,0 +1,101 @@+---+title: proxy+sidebarTitle: proxy+---++# `fastmcp.server.proxy`++## Classes++### `ProxyToolManager`+++A ToolManager that sources its tools from a remote client in addition to local and mounted tools.+++### `ProxyResourceManager`+++A ResourceManager that sources its resources from a remote client in addition to local and mounted resources.+++### `ProxyPromptManager`+++A PromptManager that sources its prompts from a remote client in addition to local and mounted prompts.+++### `ProxyTool`+++A Tool that represents and executes a tool on a remote server.+++**Methods:**++#### `from_mcp_tool`++```python+from_mcp_tool(cls, client: Client, mcp_tool: mcp.types.Tool) -> ProxyTool+```++Factory method to create a ProxyTool from a raw MCP tool schema.+++### `ProxyResource`+++A Resource that represents and reads a resource from a remote server.+++**Methods:**++#### `from_mcp_resource`++```python+from_mcp_resource(cls, client: Client, mcp_resource: mcp.types.Resource) -> ProxyResource+```++Factory method to create a ProxyResource from a raw MCP resource schema.+++### `ProxyTemplate`+++A ResourceTemplate that represents and creates resources from a remote server template.+++**Methods:**++#### `from_mcp_template`++```python+from_mcp_template(cls, client: Client, mcp_template: mcp.types.ResourceTemplate) -> ProxyTemplate+```++Factory method to create a ProxyTemplate from a raw MCP template schema.+++### `ProxyPrompt`+++A Prompt that represents and renders a prompt from a remote server.+++**Methods:**++#### `from_mcp_prompt`++```python+from_mcp_prompt(cls, client: Client, mcp_prompt: mcp.types.Prompt) -> ProxyPrompt+```++Factory method to create a ProxyPrompt from a raw MCP prompt schema.+++### `FastMCPProxy`+++A FastMCP server that acts as a proxy to a remote MCP-compliant server.+It uses specialized managers that fulfill requests via an HTTP client.+diff --git a/docs/python-sdk/fastmcp-server-server.mdx b/docs/python-sdk/fastmcp-server-server.mdxnew file mode 100644index 000000000..8f631c002--- /dev/null+++ b/docs/python-sdk/fastmcp-server-server.mdx@@ -0,0 +1,542 @@+---+title: server+sidebarTitle: server+---++# `fastmcp.server.server`+++FastMCP - A more ergonomic interface for MCP servers.++## Functions++### `add_resource_prefix`++```python+add_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> str+```+++Add a prefix to a resource URI.++ Args:+ uri: The original resource URI+ prefix: The prefix to add++ Returns:+ The resource URI with the prefix added++ Examples:+ >>> add_resource_prefix("resource://path/to/resource", "prefix")+ "resource://prefix/path/to/resource" # with new style+ >>> add_resource_prefix("resource://path/to/resource", "prefix")+ "prefix+resource://path/to/resource" # with legacy style+ >>> add_resource_prefix("resource:///absolute/path", "prefix")+ "resource://prefix//absolute/path" # with new style++ Raises:+ ValueError: If the URI doesn't match the expected protocol://path format+++### `remove_resource_prefix`++```python+remove_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> str+```+++Remove a prefix from a resource URI.++ Args:+ uri: The resource URI with a prefix+ prefix: The prefix to remove+ prefix_format: The format of the prefix to remove+ Returns:+ The resource URI with the prefix removed++ Examples:+ >>> remove_resource_prefix("resource://prefix/path/to/resource", "prefix")+ "resource://path/to/resource" # with new style+ >>> remove_resource_prefix("prefix+resource://path/to/resource", "prefix")+ "resource://path/to/resource" # with legacy style+ >>> remove_resource_prefix("resource://prefix//absolute/path", "prefix")+ "resource:///absolute/path" # with new style++ Raises:+ ValueError: If the URI doesn't match the expected protocol://path format+++### `has_resource_prefix`++```python+has_resource_prefix(uri: str, prefix: str, prefix_format: Literal['protocol', 'path'] | None = None) -> bool+```+++Check if a resource URI has a specific prefix.++ Args:+ uri: The resource URI to check+ prefix: The prefix to look for++ Returns:+ True if the URI has the specified prefix, False otherwise++ Examples:+ >>> has_resource_prefix("resource://prefix/path/to/resource", "prefix")+ True # with new style+ >>> has_resource_prefix("prefix+resource://path/to/resource", "prefix")+ True # with legacy style+ >>> has_resource_prefix("resource://other/path/to/resource", "prefix")+ False++ Raises:+ ValueError: If the URI doesn't match the expected protocol://path format+++## Classes++### `FastMCP`++**Methods:**++#### `settings`++```python+settings(self) -> Settings+```++#### `name`++```python+name(self) -> str+```++#### `instructions`++```python+instructions(self) -> str | None+```++#### `run`++```python+run(self, transport: Literal['stdio', 'streamable-http', 'sse'] | None = None, **transport_kwargs: Any) -> None+```++Run the FastMCP server. Note this is a synchronous function.++**Args:**+- `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http")+++#### `add_middleware`++```python+add_middleware(self, middleware: Middleware) -> None+```++#### `custom_route`++```python+custom_route(self, path: str, methods: list[str], name: str | None = None, include_in_schema: bool = True)+```++Decorator to register a custom HTTP route on the FastMCP server.++Allows adding arbitrary HTTP endpoints outside the standard MCP protocol,+which can be useful for OAuth callbacks, health checks, or admin APIs.+The handler function must be an async function that accepts a Starlette+Request and returns a Response.++**Args:**+- `path`: URL path for the route (e.g., "/oauth/callback")+- `methods`: List of HTTP methods to support (e.g., ["GET", "POST"])+- `name`: Optional name for the route (to reference this route with+Starlette's reverse URL lookup feature)+- `include_in_schema`: Whether to include in OpenAPI schema, defaults to True+++#### `add_tool`++```python+add_tool(self, tool: Tool) -> None+```++Add a tool to the server.++The tool function can optionally request a Context object by adding a parameter+with the Context type annotation. See the @tool decorator for examples.++**Args:**+- `tool`: The Tool instance to register+++#### `remove_tool`++```python+remove_tool(self, name: str) -> None+```++Remove a tool from the server.++**Args:**+- `name`: The name of the tool to remove++**Raises:**+- `NotFoundError`: If the tool is not found+++#### `tool`++```python+tool(self, name_or_fn: AnyFunction) -> FunctionTool+```++#### `tool`++```python+tool(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionTool]+```++#### `tool`++```python+tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool+```++Decorator to register a tool.++Tools can optionally request a Context object by adding a parameter with the+Context type annotation. The context provides access to MCP capabilities like+logging, progress reporting, and resource access.++This decorator supports multiple calling patterns:+- @server.tool (without parentheses)+- @server.tool (with empty parentheses)+- @server.tool("custom_name") (with name as first argument)+- @server.tool(name="custom_name") (with name as keyword argument)+- server.tool(function, name="custom_name") (direct function call)++**Args:**+- `name_or_fn`: Either a function (when used as @tool), a string name, or None+- `name`: Optional name for the tool (keyword-only, alternative to name_or_fn)+- `description`: Optional description of what the tool does+- `tags`: Optional set of tags for categorizing the tool+- `annotations`: Optional annotations about the tool's behavior (e.g. {"is_async": True})+- `exclude_args`: Optional list of argument names to exclude from the tool schema+- `enabled`: Optional boolean to enable or disable the tool+++#### `add_resource`++```python+add_resource(self, resource: Resource) -> None+```++Add a resource to the server.++**Args:**+- `resource`: A Resource instance to add+++#### `add_template`++```python+add_template(self, template: ResourceTemplate) -> None+```++Add a resource template to the server.++**Args:**+- `template`: A ResourceTemplate instance to add+++#### `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+```++Add a resource or template to the server from a function.++If the URI contains parameters (e.g. "resource://{param}") or the function+has parameters, it will be registered as a template resource.++**Args:**+- `fn`: The function to register as a resource+- `uri`: The URI for the resource+- `name`: Optional name for the resource+- `description`: Optional description of the resource+- `mime_type`: Optional MIME type for the resource+- `tags`: Optional set of tags for categorizing the resource+++#### `resource`++```python+resource(self, uri: str) -> Callable[[AnyFunction], Resource | ResourceTemplate]+```++Decorator to register a function as a resource.++The function will be called when the resource is read to generate its content.+The function can return:+- str for text content+- bytes for binary content+- other types will be converted to JSON++Resources can optionally request a Context object by adding a parameter with the+Context type annotation. The context provides access to MCP capabilities like+logging, progress reporting, and session information.++If the URI contains parameters (e.g. "resource://{param}") or the function+has parameters, it will be registered as a template resource.++**Args:**+- `uri`: URI for the resource (e.g. "resource://my-resource" or "resource://{param}")+- `name`: Optional name for the resource+- `description`: Optional description of the 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+++#### `add_prompt`++```python+add_prompt(self, prompt: Prompt) -> None+```++Add a prompt to the server.++**Args:**+- `prompt`: A Prompt instance to add+++#### `prompt`++```python+prompt(self, name_or_fn: AnyFunction) -> FunctionPrompt+```++#### `prompt`++```python+prompt(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionPrompt]+```++#### `prompt`++```python+prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt+```++Decorator to register a prompt.++ Prompts can optionally request a Context object by adding a parameter with the+ Context type annotation. The context provides access to MCP capabilities like+ logging, progress reporting, and session information.++ This decorator supports multiple calling patterns:+ - @server.prompt (without parentheses)+ - @server.prompt() (with empty parentheses)+ - @server.prompt("custom_name") (with name as first argument)+ - @server.prompt(name="custom_name") (with name as keyword argument)+ - server.prompt(function, name="custom_name") (direct function call)++ Args:+ name_or_fn: Either a function (when used as @prompt), a string name, or None+ name: Optional name for the prompt (keyword-only, alternative to name_or_fn)+ 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++ Example:+ @server.prompt+ def analyze_table(table_name: str) -> list\[Message]:+ schema = read_table_schema(table_name)+ return [+ {+ "role": "user",+ "content": f"Analyze this schema:+{schema}"+ }+ ]++ @server.prompt()+ def analyze_with_context(table_name: str, ctx: Context) -> list\[Message]:+ ctx.info(f"Analyzing table {table_name}")+ schema = read_table_schema(table_name)+ return [+ {+ "role": "user",+ "content": f"Analyze this schema:+{schema}"+ }+ ]++ @server.prompt("custom_name")+ def analyze_file(path: str) -> list\[Message]:+ content = await read_file(path)+ return [+ {+ "role": "user",+ "content": {+ "type": "resource",+ "resource": {+ "uri": f"file://{path}",+ "text": content+ }+ }+ }+ ]++ @server.prompt(name="custom_name")+ def another_prompt(data: str) -> list\[Message]:+ return [{"role": "user", "content": data}]++ # Direct function call+ server.prompt(my_function, name="custom_name")+++#### `sse_app`++```python+sse_app(self, path: str | None = None, message_path: str | None = None, middleware: list[ASGIMiddleware] | None = None) -> StarletteWithLifespan+```++Create a Starlette app for the SSE server.++**Args:**+- `path`: The path to the SSE endpoint+- `message_path`: The path to the message endpoint+- `middleware`: A list of middleware to apply to the app+++#### `streamable_http_app`++```python+streamable_http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None) -> StarletteWithLifespan+```++Create a Starlette app for the StreamableHTTP server.++**Args:**+- `path`: The path to the StreamableHTTP endpoint+- `middleware`: A list of middleware to apply to the 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['streamable-http', 'sse'] = 'streamable-http') -> StarletteWithLifespan+```++Create a Starlette app using the specified HTTP transport.++**Args:**+- `path`: The path for the HTTP endpoint+- `middleware`: A list of middleware to apply to the app+- `transport`: Transport protocol to use - either "streamable-http" (default) or "sse"++**Returns:**+- A Starlette application configured with the specified transport+++#### `mount`++```python+mount(self, server: FastMCP[LifespanResultT], prefix: str | None = None, as_proxy: bool | None = None) -> None+```++Mount another FastMCP server on this server with an optional prefix.++Unlike importing (with import_server), mounting establishes a dynamic connection+between servers. When a client interacts with a mounted server's objects through+the parent server, requests are forwarded to the mounted server in real-time.+This means changes to the mounted server are immediately reflected when accessed+through the parent.++When a server is mounted with a prefix:+- Tools from the mounted server are accessible with prefixed names.+ Example: If server has a tool named "get_weather", it will be available as "prefix_get_weather".+- Resources are accessible with prefixed URIs.+ Example: If server has a resource with URI "weather://forecast", it will be available as+ "weather://prefix/forecast".+- Templates are accessible with prefixed URI templates.+ Example: If server has a template with URI "weather://location/{id}", it will be available+ as "weather://prefix/location/{id}".+- Prompts are accessible with prefixed names.+ Example: If server has a prompt named "weather_prompt", it will be available as+ "prefix_weather_prompt".++When a server is mounted without a prefix (prefix=None), its tools, resources, templates,+and prompts are accessible with their original names. Multiple servers can be mounted+without prefixes, and they will be tried in order until a match is found.++There are two modes for mounting servers:+1. Direct mounting (default when server has no custom lifespan): The parent server+ directly accesses the mounted server's objects in-memory for better performance.+ In this mode, no client lifecycle events occur on the mounted server, including+ lifespan execution.++2. Proxy mounting (default when server has a custom lifespan): The parent server+ treats the mounted server as a separate entity and communicates with it via a+ Client transport. This preserves all client-facing behaviors, including lifespan+ execution, but with slightly higher overhead.++**Args:**+- `server`: The FastMCP server to mount.+- `prefix`: Optional prefix to use for the mounted server's objects. If None,+the server's objects are accessible with their original names.+- `as_proxy`: Whether to treat the mounted server as a proxy. If None (default),+automatically determined based on whether the server has a custom lifespan+(True if it has a custom lifespan, False otherwise).+- `tool_separator`: Deprecated. Separator character for tool names.+- `resource_separator`: Deprecated. Separator character for resource URIs.+- `prompt_separator`: Deprecated. Separator character for prompt names.+++#### `from_openapi`++```python+from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI+```++Create a FastMCP server from an OpenAPI specification.+++#### `from_fastapi`++```python+from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | 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+```++Create a FastMCP server from a FastAPI application.+++#### `as_proxy`++```python+as_proxy(cls, backend: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy+```++Create a FastMCP proxy server for the given backend.++The ``backend`` argument can be either an existing :class:`~fastmcp.client.Client`+instance or any value accepted as the ``transport`` argument of+:class:`~fastmcp.client.Client`. This mirrors the convenience of the+``Client`` constructor.+++#### `from_client`++```python+from_client(cls, client: Client[ClientTransportT], **settings: Any) -> FastMCPProxy+```++Create a FastMCP proxy server from a FastMCP client.+++### `MountedServer`diff --git a/docs/python-sdk/fastmcp-settings.mdx b/docs/python-sdk/fastmcp-settings.mdxnew file mode 100644index 000000000..fd3e3d791--- /dev/null+++ b/docs/python-sdk/fastmcp-settings.mdx@@ -0,0 +1,59 @@+---+title: settings+sidebarTitle: settings+---++# `fastmcp.settings`++## Classes++### `ExtendedEnvSettingsSource`+++A special EnvSettingsSource that allows for multiple env var prefixes to be used.++Raises a deprecation warning if the old `FASTMCP_SERVER_` prefix is used.+++**Methods:**++#### `get_field_value`++```python+get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]+```++### `ExtendedSettingsConfigDict`++### `Settings`+++FastMCP settings.+++**Methods:**++#### `settings_customise_sources`++```python+settings_customise_sources(cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource) -> tuple[PydanticBaseSettingsSource, ...]+```++#### `settings`++```python+settings(self) -> Self+```++This property is for backwards compatibility with FastMCP < 2.8.0,+which accessed fastmcp.settings.settings+++#### `setup_logging`++```python+setup_logging(self) -> Self+```++Finalize the settings.+diff --git a/docs/python-sdk/fastmcp-tools-__init__.mdx b/docs/python-sdk/fastmcp-tools-__init__.mdxnew file mode 100644index 000000000..5b7c8b04d--- /dev/null+++ b/docs/python-sdk/fastmcp-tools-__init__.mdx@@ -0,0 +1,8 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.tools`++*This module is empty or contains only private/internal implementations.*diff --git a/docs/python-sdk/fastmcp-tools-tool.mdx b/docs/python-sdk/fastmcp-tools-tool.mdxnew file mode 100644index 000000000..7cae406aa--- /dev/null+++ b/docs/python-sdk/fastmcp-tools-tool.mdx@@ -0,0 +1,68 @@+---+title: tool+sidebarTitle: tool+---++# `fastmcp.tools.tool`++## Functions++### `default_serializer`++```python+default_serializer(data: Any) -> str+```++## Classes++### `Tool`+++Internal tool registration info.+++**Methods:**++#### `to_mcp_tool`++```python+to_mcp_tool(self, **overrides: Any) -> MCPTool+```++#### `from_function`++```python+from_function(fn: Callable[..., Any], name: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, exclude_args: list[str] | None = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> FunctionTool+```++Create a Tool from a function.+++#### `from_tool`++```python+from_tool(cls, tool: Tool, transform_fn: Callable[..., Any] | None = None, name: str | None = None, transform_args: dict[str, ArgTransform] | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> TransformedTool+```++### `FunctionTool`++**Methods:**++#### `from_function`++```python+from_function(cls, fn: Callable[..., Any], name: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, exclude_args: list[str] | None = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> FunctionTool+```++Create a Tool from a function.+++### `ParsedFunction`++**Methods:**++#### `from_function`++```python+from_function(cls, fn: Callable[..., Any], exclude_args: list[str] | None = None, validate: bool = True) -> ParsedFunction+```diff --git a/docs/python-sdk/fastmcp-tools-tool_manager.mdx b/docs/python-sdk/fastmcp-tools-tool_manager.mdxnew file mode 100644index 000000000..fad031d72--- /dev/null+++ b/docs/python-sdk/fastmcp-tools-tool_manager.mdx@@ -0,0 +1,58 @@+---+title: tool_manager+sidebarTitle: tool_manager+---++# `fastmcp.tools.tool_manager`++## Classes++### `ToolManager`+++Manages FastMCP tools.+++**Methods:**++#### `mount`++```python+mount(self, server: MountedServer) -> None+```++Adds a mounted server as a source for tools.+++#### `add_tool_from_fn`++```python+add_tool_from_fn(self, fn: Callable[..., Any], name: str | None = None, description: str | None = None, tags: set[str] | None = None, annotations: ToolAnnotations | None = None, serializer: Callable[[Any], str] | None = None, exclude_args: list[str] | None = None) -> Tool+```++Add a tool to the server.+++#### `add_tool`++```python+add_tool(self, tool: Tool) -> Tool+```++Register a tool with the server.+++#### `remove_tool`++```python+remove_tool(self, key: str) -> None+```++Remove a tool from the server.++**Args:**+- `key`: The key of the tool to remove++**Raises:**+- `NotFoundError`: If the tool is not found+diff --git a/docs/python-sdk/fastmcp-tools-tool_transform.mdx b/docs/python-sdk/fastmcp-tools-tool_transform.mdxnew file mode 100644index 000000000..c0d10e34d--- /dev/null+++ b/docs/python-sdk/fastmcp-tools-tool_transform.mdx@@ -0,0 +1,117 @@+---+title: tool_transform+sidebarTitle: tool_transform+---++# `fastmcp.tools.tool_transform`++## Classes++### `ArgTransform`+++Configuration for transforming a parent tool's argument.++ This class allows fine-grained control over how individual arguments are transformed+ when creating a new tool from an existing one. You can rename arguments, change their+ descriptions, add default values, or hide them from clients while passing constants.++ Attributes:+ name: New name for the argument. Use None to keep original name, or ... for no change.+ description: New description for the argument. Use None to remove description, or ... for no change.+ default: New default value for the argument. Use ... for no change.+ default_factory: Callable that returns a default value. Cannot be used with default.+ type: New type for the argument. Use ... for no change.+ hide: If True, hide this argument from clients but pass a constant value to parent.+ required: If True, make argument required (remove default). Use ... for no change.+ examples: Examples for the argument. Use ... for no change.++ Examples:+ # Rename argument 'old_name' to 'new_name'+ ArgTransform(name="new_name")++ # Change description only+ ArgTransform(description="Updated description")++ # Add a default value (makes argument optional)+ ArgTransform(default=42)++ # Add a default factory (makes argument optional)+ ArgTransform(default_factory=lambda: time.time())++ # Change the type+ ArgTransform(type=str)++ # Hide the argument entirely from clients+ ArgTransform(hide=True)++ # Hide argument but pass a constant value to parent+ ArgTransform(hide=True, default="constant_value")++ # Hide argument but pass a factory-generated value to parent+ ArgTransform(hide=True, default_factory=lambda: uuid.uuid4().hex)++ # Make an optional parameter required (removes any default)+ ArgTransform(required=True)++ # Combine multiple transformations+ ArgTransform(name="new_name", description="New desc", default=None, type=int)+++### `TransformedTool`+++A tool that is transformed from another tool.++This class represents a tool that has been created by transforming another tool.+It supports argument renaming, schema modification, custom function injection,+and provides context for the forward() and forward_raw() functions.++The transformation can be purely schema-based (argument renaming, dropping, etc.)+or can include a custom function that uses forward() to call the parent tool+with transformed arguments.+++**Methods:**++#### `from_tool`++```python+from_tool(cls, tool: Tool, name: str | None = None, description: str | None = None, tags: set[str] | None = None, transform_fn: Callable[..., Any] | None = None, transform_args: dict[str, ArgTransform] | None = None, annotations: ToolAnnotations | None = None, serializer: Callable[[Any], str] | None = None, enabled: bool | None = None) -> TransformedTool+```++Create a transformed tool from a parent tool.++**Args:**+- `tool`: The parent tool to transform.+- `transform_fn`: Optional custom function. Can use forward() and forward_raw()+to call the parent tool. Functions with **kwargs receive transformed+argument names.+- `name`: New name for the tool. Defaults to parent tool's name.+- `transform_args`: Optional transformations for parent tool arguments.+Only specified arguments are transformed, others pass through unchanged:+- str: Simple rename+- ArgTransform: Complex transformation (rename/description/default/drop)+- None: Drop the argument+- `description`: New description. Defaults to parent's description.+- `tags`: New tags. Defaults to parent's tags.+- `annotations`: New annotations. Defaults to parent's annotations.+- `serializer`: New serializer. Defaults to parent's serializer.++**Returns:**+- TransformedTool with the specified transformations.++Examples:+- # Transform specific arguments only+- Tool.from_tool(parent, transform_args={"old": "new"}) # Others unchanged+- # Custom function with partial transforms+- async def custom(x: int, y: int) -> str:+result = await forward(x=x, y=y)+return f"Custom: {result}"+- Tool.from_tool(parent, transform_fn=custom, transform_args={"a": "x", "b": "y"})+- # Using **kwargs (gets all args, transformed and untransformed)+- async def flexible(**kwargs) -> str:+result = await forward(**kwargs)+return f"Got: {kwargs}"+- Tool.from_tool(parent, transform_fn=flexible, transform_args={"a": "x"})+diff --git a/docs/python-sdk/fastmcp-utilities-__init__.mdx b/docs/python-sdk/fastmcp-utilities-__init__.mdxnew file mode 100644index 000000000..12e12b4ed--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-__init__.mdx@@ -0,0 +1,9 @@+---+title: __init__+sidebarTitle: __init__+---++# `fastmcp.utilities`+++FastMCP utility modules.diff --git a/docs/python-sdk/fastmcp-utilities-cache.mdx b/docs/python-sdk/fastmcp-utilities-cache.mdxnew file mode 100644index 000000000..ab41395d9--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-cache.mdx@@ -0,0 +1,30 @@+---+title: cache+sidebarTitle: cache+---++# `fastmcp.utilities.cache`++## Classes++### `TimedCache`++**Methods:**++#### `set`++```python+set(self, key: Any, value: Any) -> None+```++#### `get`++```python+get(self, key: Any) -> Any+```++#### `clear`++```python+clear(self) -> None+```diff --git a/docs/python-sdk/fastmcp-utilities-components.mdx b/docs/python-sdk/fastmcp-utilities-components.mdxnew file mode 100644index 000000000..61434c7d5--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-components.mdx@@ -0,0 +1,52 @@+---+title: components+sidebarTitle: components+---++# `fastmcp.utilities.components`++## Classes++### `FastMCPComponent`+++Base class for FastMCP tools, prompts, resources, and resource templates.+++**Methods:**++#### `key`++```python+key(self) -> str+```++The key of the component. This is used for internal bookkeeping+and may reflect e.g. prefixes or other identifiers. You should not depend on+keys having a certain value, as the same tool loaded from different+hierarchies of servers may have different keys.+++#### `with_key`++```python+with_key(self, key: str) -> Self+```++#### `enable`++```python+enable(self) -> None+```++Enable the component.+++#### `disable`++```python+disable(self) -> None+```++Disable the component.+diff --git a/docs/python-sdk/fastmcp-utilities-exceptions.mdx b/docs/python-sdk/fastmcp-utilities-exceptions.mdxnew file mode 100644index 000000000..2d480a146--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-exceptions.mdx@@ -0,0 +1,20 @@+---+title: exceptions+sidebarTitle: exceptions+---++# `fastmcp.utilities.exceptions`++## Functions++### `iter_exc`++```python+iter_exc(group: BaseExceptionGroup)+```++### `get_catch_handlers`++```python+get_catch_handlers() -> Mapping[type[BaseException] | Iterable[type[BaseException]], Callable[[BaseExceptionGroup[Any]], Any]]+```diff --git a/docs/python-sdk/fastmcp-utilities-http.mdx b/docs/python-sdk/fastmcp-utilities-http.mdxnew file mode 100644index 000000000..6e5e4b75f--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-http.mdx@@ -0,0 +1,18 @@+---+title: http+sidebarTitle: http+---++# `fastmcp.utilities.http`++## Functions++### `find_available_port`++```python+find_available_port() -> int+```+++Find an available port by letting the OS assign one.+diff --git a/docs/python-sdk/fastmcp-utilities-json_schema.mdx b/docs/python-sdk/fastmcp-utilities-json_schema.mdxnew file mode 100644index 000000000..bedf79119--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-json_schema.mdx@@ -0,0 +1,25 @@+---+title: json_schema+sidebarTitle: json_schema+---++# `fastmcp.utilities.json_schema`++## Functions++### `compress_schema`++```python+compress_schema(schema: dict, prune_params: list[str] | None = None, prune_defs: bool = True, prune_additional_properties: bool = True, prune_titles: bool = False) -> dict+```+++Remove the given parameters from the schema.++**Args:**+- `schema`: The schema to compress+- `prune_params`: List of parameter names to remove from properties+- `prune_defs`: Whether to remove unused definitions+- `prune_additional_properties`: Whether to remove additionalProperties: false+- `prune_titles`: Whether to remove title fields from the schema+diff --git a/docs/python-sdk/fastmcp-utilities-logging.mdx b/docs/python-sdk/fastmcp-utilities-logging.mdxnew file mode 100644index 000000000..90e294f6a--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-logging.mdx@@ -0,0 +1,41 @@+---+title: logging+sidebarTitle: logging+---++# `fastmcp.utilities.logging`+++Logging utilities for FastMCP.++## Functions++### `get_logger`++```python+get_logger(name: str) -> logging.Logger+```+++Get a logger nested under FastMCP namespace.++**Args:**+- `name`: the name of the logger, which will be prefixed with 'FastMCP.'++**Returns:**+- a configured logger instance+++### `configure_logging`++```python+configure_logging(level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | int = 'INFO', logger: logging.Logger | None = None, enable_rich_tracebacks: bool = True) -> None+```+++Configure logging for FastMCP.++**Args:**+- `logger`: the logger to configure+- `level`: the log level to use+diff --git a/docs/python-sdk/fastmcp-utilities-mcp_config.mdx b/docs/python-sdk/fastmcp-utilities-mcp_config.mdxnew file mode 100644index 000000000..b74dfcfa0--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-mcp_config.mdx@@ -0,0 +1,50 @@+---+title: mcp_config+sidebarTitle: mcp_config+---++# `fastmcp.utilities.mcp_config`++## Functions++### `infer_transport_type_from_url`++```python+infer_transport_type_from_url(url: str | AnyUrl) -> Literal['streamable-http', 'sse']+```+++Infer the appropriate transport type from the given URL.+++## Classes++### `StdioMCPServer`++**Methods:**++#### `to_transport`++```python+to_transport(self) -> StdioTransport+```++### `RemoteMCPServer`++**Methods:**++#### `to_transport`++```python+to_transport(self) -> StreamableHttpTransport | SSETransport+```++### `MCPConfig`++**Methods:**++#### `from_dict`++```python+from_dict(cls, config: dict[str, Any]) -> MCPConfig+```diff --git a/docs/python-sdk/fastmcp-utilities-openapi.mdx b/docs/python-sdk/fastmcp-utilities-openapi.mdxnew file mode 100644index 000000000..7b7d0aa62--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-openapi.mdx@@ -0,0 +1,118 @@+---+title: openapi+sidebarTitle: openapi+---++# `fastmcp.utilities.openapi`++## Functions++### `parse_openapi_to_http_routes`++```python+parse_openapi_to_http_routes(openapi_dict: dict[str, Any]) -> list[HTTPRoute]+```+++Parses an OpenAPI schema dictionary into a list of HTTPRoute objects+using the openapi-pydantic library.++Supports both OpenAPI 3.0.x and 3.1.x versions.+++### `clean_schema_for_display`++```python+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`++```python+generate_example_from_schema(schema: JsonSchema | None) -> Any+```+++Generate a simple example value from a JSON schema dictionary.+Very basic implementation focusing on types.+++### `format_json_for_description`++```python+format_json_for_description(data: Any, indent: int = 2) -> str+```+++Formats Python data as a JSON string block for markdown.+++### `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+```+++Formats the base description string with response, parameter, and request body information.++**Args:**+- `base_description`: The initial description to be formatted.+- `responses`: A dictionary of response information, keyed by status code.+- `parameters`: A list of parameter information,+including path and query parameters. Each parameter includes details such as name,+location, whether it is required, and a description.+- `request_body`: Information about the request body,+including its description, whether it is required, and its content schema.++**Returns:**+- The formatted description string with additional details about responses, parameters,+- and the request body.+++## Classes++### `ParameterInfo`+++Represents a single parameter for an HTTP operation in our IR.+++### `RequestBodyInfo`+++Represents the request body for an HTTP operation in our IR.+++### `ResponseInfo`+++Represents response information in our IR.+++### `HTTPRoute`+++Intermediate Representation for a single OpenAPI operation.+++### `OpenAPIParser`+++Unified parser for OpenAPI schemas with generic type parameters to handle both 3.0 and 3.1.+++**Methods:**++#### `parse`++```python+parse(self) -> list[HTTPRoute]+```++Parse the OpenAPI schema into HTTP routes.+diff --git a/docs/python-sdk/fastmcp-utilities-types.mdx b/docs/python-sdk/fastmcp-utilities-types.mdxnew file mode 100644index 000000000..3810bb878--- /dev/null+++ b/docs/python-sdk/fastmcp-utilities-types.mdx@@ -0,0 +1,112 @@+---+title: types+sidebarTitle: types+---++# `fastmcp.utilities.types`+++Common types used across FastMCP.++## Functions++### `get_cached_typeadapter`++```python+get_cached_typeadapter(cls: T) -> TypeAdapter[T]+```+++TypeAdapters are heavy objects, and in an application context we'd typically+create them once in a global scope and reuse them as often as possible.+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`++```python+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`++```python+is_class_member_of_type(cls: type, base: type) -> bool+```+++Check if cls is a member of base, even if cls is a type variable.++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`++```python+find_kwarg_by_type(fn: Callable, kwarg_type: type) -> str | None+```+++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.+++## Classes++### `FastMCPBaseModel`+++Base model for FastMCP models.+++### `Image`+++Helper class for returning images from tools.+++**Methods:**++#### `to_image_content`++```python+to_image_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> ImageContent+```++Convert to MCP ImageContent.+++### `Audio`+++Helper class for returning audio from tools.+++**Methods:**++#### `to_audio_content`++```python+to_audio_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> AudioContent+```++### `File`+++Helper class for returning audio from tools.+++**Methods:**++#### `to_resource_content`++```python+to_resource_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> EmbeddedResource+```diff --git a/justfile b/justfileindex 6d897b2e9..a27c2877f 100644--- a/justfile+++ b/justfile@@ -1,6 +1,8 @@+# Build the projectbuild:uv sync+# Run teststest: builduv run --frozen pytest -xvs tests@@ -8,5 +10,18 @@ test: buildtypecheck:uv run --frozen pyright+# Serve documentation locallydocs:- cd docs && npx mintlify dev+ cd docs && npx mint@latest dev++# Generate API reference documentation for all modules+api-ref-all:+ uvx --with-editable . --refresh-package mdxify mdxify@latest --all --root-module fastmcp++# Generate API reference for specific modules (e.g., just api-ref prefect.flows prefect.tasks)+api-ref *MODULES:+ uvx --with-editable . --refresh-package mdxify mdxify@latest {{MODULES}} --root-module fastmcp++# Clean up API reference documentation+api-ref-clean:+ rm -rf docs/python-sdk\ No newline at end of file