chore: Update SDK documentation (#4096)

This commit is contained in:
marvin-context-protocol[bot] 2026-05-14 22:06:38 -04:00 committed by GitHub
commit 73df4dcaee
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
231 changed files with 208 additions and 18203 deletions

View file

@ -1,114 +1,18 @@
[
"python-sdk/fastmcp-apps",
"python-sdk/fastmcp-cli",
"python-sdk/fastmcp-client",
"python-sdk/fastmcp-decorators",
"python-sdk/fastmcp-dependencies",
"python-sdk/fastmcp-exceptions",
"python-sdk/fastmcp-mcp_config",
"python-sdk/fastmcp-prompts",
"python-sdk/fastmcp-resources",
"python-sdk/fastmcp-server",
"python-sdk/fastmcp-settings",
"python-sdk/fastmcp-telemetry",
"python-sdk/fastmcp-tools",
"python-sdk/fastmcp-types",
{
"group": "fastmcp.apps",
"pages": [
"python-sdk/fastmcp-apps-__init__",
"python-sdk/fastmcp-apps-app",
"python-sdk/fastmcp-apps-approval",
"python-sdk/fastmcp-apps-choice",
"python-sdk/fastmcp-apps-config",
"python-sdk/fastmcp-apps-file_upload",
"python-sdk/fastmcp-apps-form",
"python-sdk/fastmcp-apps-generative"
]
},
{
"group": "fastmcp.cli",
"pages": [
"python-sdk/fastmcp-cli-__init__",
"python-sdk/fastmcp-cli-apps_dev",
"python-sdk/fastmcp-cli-auth",
"python-sdk/fastmcp-cli-cimd",
"python-sdk/fastmcp-cli-cli",
"python-sdk/fastmcp-cli-client",
"python-sdk/fastmcp-cli-discovery",
"python-sdk/fastmcp-cli-generate",
{
"group": "install",
"pages": [
"python-sdk/fastmcp-cli-install-__init__",
"python-sdk/fastmcp-cli-install-claude_code",
"python-sdk/fastmcp-cli-install-claude_desktop",
"python-sdk/fastmcp-cli-install-cursor",
"python-sdk/fastmcp-cli-install-gemini_cli",
"python-sdk/fastmcp-cli-install-goose",
"python-sdk/fastmcp-cli-install-mcp_json",
"python-sdk/fastmcp-cli-install-shared",
"python-sdk/fastmcp-cli-install-stdio"
]
},
"python-sdk/fastmcp-cli-run",
"python-sdk/fastmcp-cli-tasks"
]
},
{
"group": "fastmcp.client",
"pages": [
"python-sdk/fastmcp-client-__init__",
{
"group": "auth",
"pages": [
"python-sdk/fastmcp-client-auth-__init__",
"python-sdk/fastmcp-client-auth-bearer",
"python-sdk/fastmcp-client-auth-oauth"
]
},
"python-sdk/fastmcp-client-client",
"python-sdk/fastmcp-client-elicitation",
"python-sdk/fastmcp-client-logging",
"python-sdk/fastmcp-client-messages",
{
"group": "mixins",
"pages": [
"python-sdk/fastmcp-client-mixins-__init__",
"python-sdk/fastmcp-client-mixins-prompts",
"python-sdk/fastmcp-client-mixins-resources",
"python-sdk/fastmcp-client-mixins-task_management",
"python-sdk/fastmcp-client-mixins-tools"
]
},
"python-sdk/fastmcp-client-oauth_callback",
"python-sdk/fastmcp-client-progress",
"python-sdk/fastmcp-client-roots",
{
"group": "sampling",
"pages": [
"python-sdk/fastmcp-client-sampling-__init__",
{
"group": "handlers",
"pages": [
"python-sdk/fastmcp-client-sampling-handlers-__init__",
"python-sdk/fastmcp-client-sampling-handlers-anthropic",
"python-sdk/fastmcp-client-sampling-handlers-google_genai",
"python-sdk/fastmcp-client-sampling-handlers-openai"
]
}
]
},
"python-sdk/fastmcp-client-tasks",
"python-sdk/fastmcp-client-telemetry",
{
"group": "transports",
"pages": [
"python-sdk/fastmcp-client-transports-__init__",
"python-sdk/fastmcp-client-transports-base",
"python-sdk/fastmcp-client-transports-config",
"python-sdk/fastmcp-client-transports-http",
"python-sdk/fastmcp-client-transports-inference",
"python-sdk/fastmcp-client-transports-memory",
"python-sdk/fastmcp-client-transports-sse",
"python-sdk/fastmcp-client-transports-stdio"
]
}
]
},
{
"group": "fastmcp.experimental",
"pages": [
@ -129,238 +33,6 @@
}
]
},
{
"group": "fastmcp.prompts",
"pages": [
"python-sdk/fastmcp-prompts-__init__",
"python-sdk/fastmcp-prompts-base",
"python-sdk/fastmcp-prompts-function_prompt"
]
},
{
"group": "fastmcp.resources",
"pages": [
"python-sdk/fastmcp-resources-__init__",
"python-sdk/fastmcp-resources-base",
"python-sdk/fastmcp-resources-function_resource",
"python-sdk/fastmcp-resources-template",
"python-sdk/fastmcp-resources-types"
]
},
{
"group": "fastmcp.server",
"pages": [
"python-sdk/fastmcp-server-__init__",
"python-sdk/fastmcp-server-app",
"python-sdk/fastmcp-server-apps",
{
"group": "auth",
"pages": [
"python-sdk/fastmcp-server-auth-__init__",
"python-sdk/fastmcp-server-auth-auth",
"python-sdk/fastmcp-server-auth-authorization",
"python-sdk/fastmcp-server-auth-cimd",
{
"group": "handlers",
"pages": [
"python-sdk/fastmcp-server-auth-handlers-__init__",
"python-sdk/fastmcp-server-auth-handlers-authorize"
]
},
"python-sdk/fastmcp-server-auth-jwt_issuer",
"python-sdk/fastmcp-server-auth-middleware",
{
"group": "oauth_proxy",
"pages": [
"python-sdk/fastmcp-server-auth-oauth_proxy-__init__",
"python-sdk/fastmcp-server-auth-oauth_proxy-consent",
"python-sdk/fastmcp-server-auth-oauth_proxy-models",
"python-sdk/fastmcp-server-auth-oauth_proxy-proxy",
"python-sdk/fastmcp-server-auth-oauth_proxy-ui"
]
},
"python-sdk/fastmcp-server-auth-oidc_proxy",
{
"group": "providers",
"pages": [
"python-sdk/fastmcp-server-auth-providers-__init__",
"python-sdk/fastmcp-server-auth-providers-auth0",
"python-sdk/fastmcp-server-auth-providers-aws",
"python-sdk/fastmcp-server-auth-providers-azure",
"python-sdk/fastmcp-server-auth-providers-clerk",
"python-sdk/fastmcp-server-auth-providers-debug",
"python-sdk/fastmcp-server-auth-providers-descope",
"python-sdk/fastmcp-server-auth-providers-discord",
"python-sdk/fastmcp-server-auth-providers-github",
"python-sdk/fastmcp-server-auth-providers-google",
"python-sdk/fastmcp-server-auth-providers-in_memory",
"python-sdk/fastmcp-server-auth-providers-introspection",
"python-sdk/fastmcp-server-auth-providers-jwt",
"python-sdk/fastmcp-server-auth-providers-keycloak",
"python-sdk/fastmcp-server-auth-providers-oci",
"python-sdk/fastmcp-server-auth-providers-propelauth",
"python-sdk/fastmcp-server-auth-providers-scalekit",
"python-sdk/fastmcp-server-auth-providers-supabase",
"python-sdk/fastmcp-server-auth-providers-workos"
]
},
"python-sdk/fastmcp-server-auth-redirect_validation",
"python-sdk/fastmcp-server-auth-ssrf"
]
},
"python-sdk/fastmcp-server-context",
"python-sdk/fastmcp-server-dependencies",
"python-sdk/fastmcp-server-elicitation",
"python-sdk/fastmcp-server-event_store",
"python-sdk/fastmcp-server-http",
"python-sdk/fastmcp-server-lifespan",
"python-sdk/fastmcp-server-low_level",
{
"group": "middleware",
"pages": [
"python-sdk/fastmcp-server-middleware-__init__",
"python-sdk/fastmcp-server-middleware-authorization",
"python-sdk/fastmcp-server-middleware-caching",
"python-sdk/fastmcp-server-middleware-dereference",
"python-sdk/fastmcp-server-middleware-error_handling",
"python-sdk/fastmcp-server-middleware-logging",
"python-sdk/fastmcp-server-middleware-middleware",
"python-sdk/fastmcp-server-middleware-ping",
"python-sdk/fastmcp-server-middleware-rate_limiting",
"python-sdk/fastmcp-server-middleware-response_limiting",
"python-sdk/fastmcp-server-middleware-timing",
"python-sdk/fastmcp-server-middleware-tool_injection"
]
},
{
"group": "mixins",
"pages": [
"python-sdk/fastmcp-server-mixins-__init__",
"python-sdk/fastmcp-server-mixins-lifespan",
"python-sdk/fastmcp-server-mixins-mcp_operations",
"python-sdk/fastmcp-server-mixins-transport"
]
},
{
"group": "openapi",
"pages": [
"python-sdk/fastmcp-server-openapi-__init__",
"python-sdk/fastmcp-server-openapi-components",
"python-sdk/fastmcp-server-openapi-routing",
"python-sdk/fastmcp-server-openapi-server"
]
},
{
"group": "providers",
"pages": [
"python-sdk/fastmcp-server-providers-__init__",
"python-sdk/fastmcp-server-providers-addressing",
"python-sdk/fastmcp-server-providers-aggregate",
"python-sdk/fastmcp-server-providers-base",
"python-sdk/fastmcp-server-providers-fastmcp_provider",
"python-sdk/fastmcp-server-providers-filesystem",
"python-sdk/fastmcp-server-providers-filesystem_discovery",
{
"group": "local_provider",
"pages": [
"python-sdk/fastmcp-server-providers-local_provider-__init__",
{
"group": "decorators",
"pages": [
"python-sdk/fastmcp-server-providers-local_provider-decorators-__init__",
"python-sdk/fastmcp-server-providers-local_provider-decorators-prompts",
"python-sdk/fastmcp-server-providers-local_provider-decorators-resources",
"python-sdk/fastmcp-server-providers-local_provider-decorators-tools"
]
},
"python-sdk/fastmcp-server-providers-local_provider-local_provider"
]
},
{
"group": "openapi",
"pages": [
"python-sdk/fastmcp-server-providers-openapi-__init__",
"python-sdk/fastmcp-server-providers-openapi-components",
"python-sdk/fastmcp-server-providers-openapi-provider",
"python-sdk/fastmcp-server-providers-openapi-routing"
]
},
"python-sdk/fastmcp-server-providers-prefab_synthesis",
"python-sdk/fastmcp-server-providers-proxy",
{
"group": "skills",
"pages": [
"python-sdk/fastmcp-server-providers-skills-__init__",
"python-sdk/fastmcp-server-providers-skills-claude_provider",
"python-sdk/fastmcp-server-providers-skills-directory_provider",
"python-sdk/fastmcp-server-providers-skills-skill_provider",
"python-sdk/fastmcp-server-providers-skills-vendor_providers"
]
},
"python-sdk/fastmcp-server-providers-wrapped_provider"
]
},
"python-sdk/fastmcp-server-proxy",
{
"group": "sampling",
"pages": [
"python-sdk/fastmcp-server-sampling-__init__",
"python-sdk/fastmcp-server-sampling-run",
"python-sdk/fastmcp-server-sampling-sampling_tool"
]
},
"python-sdk/fastmcp-server-server",
{
"group": "tasks",
"pages": [
"python-sdk/fastmcp-server-tasks-__init__",
"python-sdk/fastmcp-server-tasks-capabilities",
"python-sdk/fastmcp-server-tasks-config",
"python-sdk/fastmcp-server-tasks-context",
"python-sdk/fastmcp-server-tasks-elicitation",
"python-sdk/fastmcp-server-tasks-handlers",
"python-sdk/fastmcp-server-tasks-keys",
"python-sdk/fastmcp-server-tasks-notifications",
"python-sdk/fastmcp-server-tasks-requests",
"python-sdk/fastmcp-server-tasks-routing",
"python-sdk/fastmcp-server-tasks-subscriptions"
]
},
"python-sdk/fastmcp-server-telemetry",
{
"group": "transforms",
"pages": [
"python-sdk/fastmcp-server-transforms-__init__",
"python-sdk/fastmcp-server-transforms-catalog",
"python-sdk/fastmcp-server-transforms-namespace",
"python-sdk/fastmcp-server-transforms-prompts_as_tools",
"python-sdk/fastmcp-server-transforms-resources_as_tools",
{
"group": "search",
"pages": [
"python-sdk/fastmcp-server-transforms-search-__init__",
"python-sdk/fastmcp-server-transforms-search-base",
"python-sdk/fastmcp-server-transforms-search-bm25",
"python-sdk/fastmcp-server-transforms-search-regex"
]
},
"python-sdk/fastmcp-server-transforms-tool_transform",
"python-sdk/fastmcp-server-transforms-version_filter",
"python-sdk/fastmcp-server-transforms-visibility"
]
}
]
},
{
"group": "fastmcp.tools",
"pages": [
"python-sdk/fastmcp-tools-__init__",
"python-sdk/fastmcp-tools-base",
"python-sdk/fastmcp-tools-function_parsing",
"python-sdk/fastmcp-tools-function_tool",
"python-sdk/fastmcp-tools-tool_transform"
]
},
{
"group": "fastmcp.utilities",
"pages": [
@ -407,18 +79,7 @@
]
},
"python-sdk/fastmcp-utilities-mime",
{
"group": "openapi",
"pages": [
"python-sdk/fastmcp-utilities-openapi-__init__",
"python-sdk/fastmcp-utilities-openapi-director",
"python-sdk/fastmcp-utilities-openapi-formatters",
"python-sdk/fastmcp-utilities-openapi-json_schema_converter",
"python-sdk/fastmcp-utilities-openapi-models",
"python-sdk/fastmcp-utilities-openapi-parser",
"python-sdk/fastmcp-utilities-openapi-schemas"
]
},
"python-sdk/fastmcp-utilities-openapi",
"python-sdk/fastmcp-utilities-pagination",
"python-sdk/fastmcp-utilities-skills",
"python-sdk/fastmcp-utilities-tests",

View file

@ -1,146 +0,0 @@
---
title: app
sidebarTitle: app
---
# `fastmcp.apps.app`
FastMCPApp — a Provider that represents a composable MCP application.
FastMCPApp binds entry-point tools (model calls these) together with backend
tools (the UI calls these via CallTool). Backend tools are tagged with
``meta["fastmcp"]["app"]`` so they can be found through the provider chain
even when transforms (namespace, visibility, etc.) have renamed or hidden
them — the server sets a context var that tells ``Provider.get_tool`` to
fall back to a direct lookup for app-visible tools.
Usage::
from fastmcp import FastMCP, FastMCPApp
app = FastMCPApp("Dashboard")
@app.ui()
def show_dashboard() -> Component:
return Column(...)
@app.tool()
def save_contact(name: str, email: str) -> str:
return name
server = FastMCP("Platform")
server.add_provider(app)
## Classes
### `FastMCPApp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L142" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that represents an MCP application.
Binds together entry-point tools (``@app.ui``), backend tools
(``@app.tool``), and the Prefab renderer resource. Backend tools
are tagged with ``meta["fastmcp"]["app"]`` so ``Provider.get_tool``
can find them by original name even when transforms have been applied.
**Methods:**
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: F) -> F
```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L176" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: str | None = None) -> Callable[[F], F]
```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L187" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self, name_or_fn: str | AnyFunction | None = None) -> Any
```
Register a backend tool that the UI calls via CallTool.
Backend tools default to ``visibility=["app"]``. Pass ``model=True``
to also expose the tool to the model (``visibility=["app", "model"]``).
Supports multiple calling patterns::
@app.tool
def save(name: str): ...
@app.tool()
def save(name: str): ...
@app.tool("custom_name")
def save(name: str): ...
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L252" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ui(self, name_or_fn: F) -> F
```
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L267" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ui(self, name_or_fn: str | None = None) -> Callable[[F], F]
```
#### `ui` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L281" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ui(self, name_or_fn: str | AnyFunction | None = None) -> Any
```
Register a UI entry-point tool that the model calls.
Entry-point tools default to ``visibility=["model"]`` and auto-wire
the Prefab renderer resource and CSP. They are tagged with the app
name so structured content includes ``_meta.fastmcp.app``.
Supports multiple calling patterns::
@app.ui
def dashboard() -> Component: ...
@app.ui()
def dashboard() -> Component: ...
@app.ui("my_dashboard")
def dashboard() -> Component: ...
#### `add_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L355" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_tool(self, tool: Tool | Callable[..., Any]) -> Tool
```
Add a tool to this app programmatically.
The tool is tagged with this app's name for routing.
#### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L409" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan(self) -> AsyncIterator[None]
```
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/app.py#L417" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run(self, transport: Literal['stdio', 'http', 'sse', 'streamable-http'] | None = None, **kwargs: Any) -> None
```
Create a temporary FastMCP server and run this app standalone.

View file

@ -1,58 +0,0 @@
---
title: approval
sidebarTitle: approval
---
# `fastmcp.apps.approval`
Approval — a Provider that adds human-in-the-loop approval to any server.
The LLM presents a summary of what it's about to do, and the user
approves or rejects via buttons. The result is sent back into the
conversation as a message, prompting the LLM's next turn.
Requires ``fastmcp[apps]`` (prefab-ui).
Usage::
from fastmcp import FastMCP
from fastmcp.apps.approval import Approval
mcp = FastMCP("My Server")
mcp.add_provider(Approval())
## Classes
### `Approval` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/approval.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that adds human-in-the-loop approval to a server.
The LLM calls the ``request_approval`` tool with a summary and
optional details. The user sees an approval card with Approve and
Reject buttons. Clicking either sends a message back into the
conversation (via ``SendMessage``), triggering the LLM's next turn.
The message appears as if the user sent it, so the LLM sees
something like ``'"Deploy v3.2 to production" is APPROVED'``.
Example::
from fastmcp import FastMCP
from fastmcp.apps.approval import Approval
mcp = FastMCP("My Server")
mcp.add_provider(Approval())
Customized::
Approval(
title="Deploy Gate",
approve_text="Ship it",
approve_variant="default",
reject_text="Abort",
reject_variant="destructive",
)

View file

@ -1,44 +0,0 @@
---
title: choice
sidebarTitle: choice
---
# `fastmcp.apps.choice`
Choice — a Provider that lets the user pick from a set of options.
The LLM presents options, the user clicks one, and the selection
flows back into the conversation as a message.
Requires ``fastmcp[apps]`` (prefab-ui).
Usage::
from fastmcp import FastMCP
from fastmcp.apps.choice import Choice
mcp = FastMCP("My Server")
mcp.add_provider(Choice())
## Classes
### `Choice` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/choice.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that lets the user choose from a set of options.
The LLM calls ``choose`` with a prompt and a list of options.
The user sees a card with one button per option. Clicking a button
sends the selection back into the conversation via ``SendMessage``,
triggering the LLM's next turn.
Example::
from fastmcp import FastMCP
from fastmcp.apps.choice import Choice
mcp = FastMCP("My Server")
mcp.add_provider(Choice())

View file

@ -1,90 +0,0 @@
---
title: config
sidebarTitle: config
---
# `fastmcp.apps.config`
MCP Apps support — extension negotiation and typed UI metadata models.
Provides constants and Pydantic models for the MCP Apps extension
(io.modelcontextprotocol/ui), enabling tools and resources to carry
UI metadata for clients that support interactive app rendering.
## Functions
### `app_config_to_meta_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/config.py#L173" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
app_config_to_meta_dict(app: AppConfig | dict[str, Any]) -> dict[str, Any]
```
Convert an AppConfig or dict to the wire-format dict for ``meta["ui"]``.
## Classes
### `ResourceCSP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/config.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Content Security Policy for MCP App resources.
Declares which external origins the app is allowed to connect to or
load resources from. Hosts use these declarations to build the
``Content-Security-Policy`` header for the sandboxed iframe.
### `ResourcePermissions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/config.py#L52" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Iframe sandbox permissions for MCP App resources.
Each field, when set (typically to ``{}``), requests that the host
grant the corresponding Permission Policy feature to the sandboxed
iframe. Hosts MAY honour these; apps should use JS feature detection
as a fallback.
### `AppConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/config.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Configuration for MCP App tools and resources.
Controls how a tool or resource participates in the MCP Apps extension.
On tools, ``resource_uri`` and ``visibility`` specify which UI resource
to render and where the tool appears. On resources, those fields must
be left unset (the resource itself is the UI).
All fields use ``exclude_none`` serialization so only explicitly-set
values appear on the wire. Aliases match the MCP Apps wire format
(camelCase).
### `PrefabAppConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/config.py#L117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
App configuration for Prefab tools with sensible defaults.
Like ``app=True`` but customizable. Auto-wires the Prefab renderer
URI and merges the renderer's CSP with any additional domains you
specify. The renderer resource is registered automatically.
Example::
@mcp.tool(app=PrefabAppConfig()) # same as app=True
@mcp.tool(app=PrefabAppConfig(
csp=ResourceCSP(frame_domains=["https://example.com"]),
))
**Methods:**
#### `model_post_init` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/config.py#L133" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
model_post_init(self, __context: Any) -> None
```

View file

@ -1,144 +0,0 @@
---
title: file_upload
sidebarTitle: file_upload
---
# `fastmcp.apps.file_upload`
FileUpload — a Provider that adds drag-and-drop file upload to any server.
Lets users upload files directly to the server through an interactive UI,
bypassing the LLM context window entirely. The LLM can then read and work
with uploaded files through model-visible tools.
Requires ``fastmcp[apps]`` (prefab-ui).
Usage::
from fastmcp import FastMCP
from fastmcp.apps import FileUpload
mcp = FastMCP("My Server")
mcp.add_provider(FileUpload())
For custom persistence, override the storage methods::
class S3Upload(FileUpload):
def on_store(self, files, ctx):
# write to S3, return summaries
...
def on_list(self, ctx):
# list from S3
...
def on_read(self, name, ctx):
# read from S3
...
## Classes
### `FileUpload` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/file_upload.py#L102" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that adds file upload capabilities to a server.
Registers a drag-and-drop UI tool, a backend storage tool, and
model-visible tools for listing and reading uploaded files.
Files are scoped by MCP session and stored in memory by default.
Override ``on_store``, ``on_list``, and ``on_read`` for custom
persistence (filesystem, S3, database, etc.). Each method receives
the current ``Context``, giving access to session ID, auth tokens,
and request metadata for partitioning and authorization.
**Session scoping:** The default storage uses ``ctx.session_id`` to
isolate files by session. This works with stdio, SSE, and stateful
HTTP transports. In **stateless HTTP** mode, each request creates a
new session, so files won't persist across requests. For stateless
deployments, override the storage methods to partition by a stable
identifier from the auth context::
class UserScopedUpload(FileUpload):
def on_store(self, files, ctx):
user_id = ctx.access_token["sub"]
...
Example::
from fastmcp import FastMCP
from fastmcp.apps.file_upload import FileUpload
mcp = FastMCP("My Server")
mcp.add_provider(FileUpload())
**Methods:**
#### `on_store` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/file_upload.py#L183" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_store(self, files: list[dict[str, Any]], ctx: Context) -> list[dict[str, Any]]
```
Store uploaded files and return summaries.
**Args:**
- `files`: List of file dicts, each with ``name``, ``size``,
``type``, and ``data`` (base64-encoded content).
- `ctx`: The current request context. Use for session ID,
auth tokens, or any metadata needed for partitioning.
Override this method for custom persistence. The default
implementation stores files in memory, scoped by
``_get_scope_key(ctx)``.
**Returns:**
- List of file summary dicts (``name``, ``type``, ``size``,
- ``size_display``, ``uploaded_at``).
#### `on_list` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/file_upload.py#L216" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_list(self, ctx: Context) -> list[dict[str, Any]]
```
List all stored files.
**Args:**
- `ctx`: The current request context.
Override this method for custom persistence. The default
implementation returns files from the current scope.
**Returns:**
- List of file summary dicts.
#### `on_read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/file_upload.py#L232" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_read(self, name: str, ctx: Context) -> dict[str, Any]
```
Read a file's contents by name.
**Args:**
- `name`: The filename to read.
- `ctx`: The current request context.
Override this method for custom persistence. The default
implementation reads from the current scope's in-memory store.
Text files are decoded from base64; binary files return a
truncated base64 preview.
**Returns:**
- Dict with file metadata and ``content`` (text) or
- ``content_base64`` (binary preview).
**Raises:**
- `ValueError`: If the file is not found.

View file

@ -1,69 +0,0 @@
---
title: form
sidebarTitle: form
---
# `fastmcp.apps.form`
FormInput — a Provider that collects structured input from the user.
Define a Pydantic model for the data you need, and ``FormInput``
generates a form UI. The user fills it out, the submission is
validated, and an optional callback processes the result.
Requires ``fastmcp[apps]`` (prefab-ui).
Usage::
from pydantic import BaseModel
from fastmcp import FastMCP
from fastmcp.apps.form import FormInput
class ShippingAddress(BaseModel):
street: str
city: str
state: str
zip_code: str
mcp = FastMCP("My Server")
mcp.add_provider(FormInput(model=ShippingAddress))
## Classes
### `FormInput` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/form.py#L88" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that collects structured input via a Pydantic model.
Define a model for the data you need, and ``FormInput`` generates
a form from it using ``Form.from_model()``. Field types, labels,
descriptions, and validation are all derived from the model.
Optionally provide an ``on_submit`` callback to process the
validated data. The callback receives a model instance and returns
a string that goes back to the LLM. Without a callback, the
validated JSON is sent directly.
Example::
from pydantic import BaseModel
from fastmcp import FastMCP
from fastmcp.apps.form import FormInput
class Contact(BaseModel):
name: str
email: str
mcp = FastMCP("My Server")
mcp.add_provider(FormInput(model=Contact))
With a callback::
def save_contact(contact: Contact) -> str:
db.insert(contact.model_dump())
return f"Saved {contact.name}"
mcp.add_provider(FormInput(model=Contact, on_submit=save_contact))

View file

@ -1,56 +0,0 @@
---
title: generative
sidebarTitle: generative
---
# `fastmcp.apps.generative`
GenerativeUI — a Provider that adds LLM-generated UI capabilities.
Registers tools and resources from ``prefab_ui.generative`` so that an
LLM can write Prefab Python code, execute it in a sandbox, and render
the result as a streaming interactive UI.
Requires ``fastmcp[apps]`` (prefab-ui).
Usage::
from fastmcp import FastMCP
from fastmcp.apps.generative import GenerativeUI
mcp = FastMCP("My Server")
mcp.add_provider(GenerativeUI())
## Classes
### `GenerativeUI` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/generative.py#L53" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Provider that adds generative UI capabilities to a server.
Registers:
- A ``generate_ui`` tool that accepts Prefab Python code, executes
it in a Pyodide sandbox, and returns the rendered PrefabApp.
Supports streaming via ``ontoolinputpartial``.
- A ``components`` tool that searches the Prefab component library.
- The generative renderer resource with CSP for Pyodide CDN access.
Example::
from fastmcp import FastMCP
from fastmcp.apps.generative import GenerativeUI
mcp = FastMCP("My Server")
mcp.add_provider(GenerativeUI())
**Methods:**
#### `lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/apps/generative.py#L196" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
lifespan(self) -> AsyncIterator[None]
```

View file

@ -1,6 +1,6 @@
---
title: __init__
sidebarTitle: __init__
title: apps
sidebarTitle: apps
---
# `fastmcp.apps`

View file

@ -1,47 +0,0 @@
---
title: apps_dev
sidebarTitle: apps_dev
---
# `fastmcp.cli.apps_dev`
Dev server for previewing FastMCPApp UIs locally.
Starts the user's MCP server on a configurable port, then starts a lightweight
Starlette dev server that:
- Serves a Prefab-based tool picker at GET /
- Proxies /mcp to the user's server (avoids browser CORS restrictions)
- Serves the AppBridge host page at GET /launch
The host page uses @modelcontextprotocol/ext-apps to connect to the MCP server
and render the selected UI tool inside an iframe.
Startup sequence
----------------
1. Download ext-apps app-bridge.js from npm and patch its bare
``@modelcontextprotocol/sdk/…`` imports to use concrete esm.sh URLs.
2. Detect the exact Zod v4 module URL that esm.sh serves for that SDK version
and build an import-map entry that redirects the broken ``v4.mjs`` (which
only re-exports ``{z, default}``) to ``v4/classic/index.mjs`` (which
correctly exports every named Zod v4 function). Import maps apply to the
full module graph in the document, including cross-origin esm.sh modules.
3. Serve both the patched JS and the import-map JSON from the dev server.
## Functions
### `run_dev_apps` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/apps_dev.py#L1690" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run_dev_apps(server_spec: str) -> None
```
Start the full dev environment for a FastMCPApp server.
Starts the user's MCP server on *mcp_port*, starts the Prefab dev UI
on *dev_port* (with an /mcp proxy to the user's server), then opens
the browser.

View file

@ -1,9 +0,0 @@
---
title: auth
sidebarTitle: auth
---
# `fastmcp.cli.auth`
Authentication-related CLI commands.

View file

@ -1,43 +0,0 @@
---
title: cimd
sidebarTitle: cimd
---
# `fastmcp.cli.cimd`
CIMD (Client ID Metadata Document) CLI commands.
## Functions
### `create_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cimd.py#L32" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_command() -> None
```
Generate a CIMD document for hosting.
Create a Client ID Metadata Document that you can host at an HTTPS URL.
The URL where you host this document becomes your client_id.
After creating the document, host it at an HTTPS URL with a non-root path,
for example: https://myapp.example.com/oauth/client.json
### `validate_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cimd.py#L144" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_command(url: Annotated[str, cyclopts.Parameter(help='URL of the CIMD document to validate')]) -> None
```
Validate a hosted CIMD document.
Fetches the document from the given URL and validates:
- URL is valid CIMD URL (HTTPS, non-root path)
- Document is valid JSON
- Document conforms to CIMD schema
- client_id in document matches the URL

View file

@ -1,146 +0,0 @@
---
title: cli
sidebarTitle: cli
---
# `fastmcp.cli.cli`
FastMCP CLI tools using Cyclopts.
## Functions
### `with_argv` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L73" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
with_argv(args: list[str] | None)
```
Temporarily replace sys.argv if args provided.
This context manager is used at the CLI boundary to inject
server arguments when needed, without mutating sys.argv deep
in the source loading logic.
Args are provided without the script name, so we preserve sys.argv[0]
and replace the rest.
### `version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L96" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
version()
```
Display version information and platform details.
### `inspector` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L142" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
inspector(server_spec: str | None = None) -> None
```
Run an MCP server with the MCP Inspector for development.
**Args:**
- `server_spec`: Python file to run, optionally with \:object suffix, or None to auto-detect fastmcp.json
### `apps` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L337" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
apps(server_spec: str) -> None
```
Preview a FastMCPApp UI in the browser.
Starts the MCP server from SERVER_SPEC on --mcp-port, launches a local
dev UI on --dev-port with a tool picker and AppBridge host, then opens
the browser automatically.
Requires fastmcp[apps] to be installed (prefab-ui).
### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L385" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run(server_spec: str | None = None, *server_args: str) -> None
```
Run an MCP server or connect to a remote one.
The server can be specified in several ways:
1. Module approach: "server.py" - runs the module directly, looking for an object named 'mcp', 'server', or '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
4. MCPConfig file: "mcp.json" - runs as a proxy server for the MCP Servers in the MCPConfig file
5. FastMCP config: "fastmcp.json" - runs server using FastMCP configuration
6. No argument: looks for fastmcp.json in current directory
7. Module mode: "-m my_module" - runs the module directly via python -m
Server arguments can be passed after -- :
fastmcp run server.py -- --config config.json --debug
**Args:**
- `server_spec`: Python file, object specification (file\:obj), config file, URL, or None to auto-detect
### `inspect` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L764" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
inspect(server_spec: str | None = None) -> None
```
Inspect an MCP server and display information or generate a JSON report.
This command analyzes an MCP server. Without flags, it displays a text summary.
Use --format to output complete JSON data.
**Examples:**
# Show text summary
fastmcp inspect server.py
# Output FastMCP format JSON to stdout
fastmcp inspect server.py --format fastmcp
# Save MCP protocol format to file (format required with -o)
fastmcp inspect server.py --format mcp -o manifest.json
# Inspect from fastmcp.json configuration
fastmcp inspect fastmcp.json
fastmcp inspect # auto-detect fastmcp.json
**Args:**
- `server_spec`: Python file to inspect, optionally with \:object suffix, or fastmcp.json
### `prepare` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/cli.py#L1006" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prepare(config_path: Annotated[str | None, cyclopts.Parameter(help='Path to fastmcp.json configuration file')] = None, output_dir: Annotated[str | None, cyclopts.Parameter(help='Directory to create the persistent environment in')] = None, skip_source: Annotated[bool, cyclopts.Parameter(help='Skip source preparation (e.g., git clone)')] = False) -> None
```
Prepare a FastMCP project by creating a persistent uv environment.
This command creates a persistent uv project with all dependencies installed:
- Creates a pyproject.toml with dependencies from the config
- Installs all Python packages into a .venv
- Prepares the source (git clone, download, etc.) unless --skip-source
After running this command, you can use:
fastmcp run &lt;config&gt; --project &lt;output-dir&gt;
This is useful for:
- CI/CD pipelines with separate build and run stages
- Docker images where you prepare during build
- Production deployments where you want fast startup times

View file

@ -1,135 +0,0 @@
---
title: client
sidebarTitle: client
---
# `fastmcp.cli.client`
Client-side CLI commands for querying and invoking MCP servers.
## Functions
### `resolve_server_spec` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L43" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resolve_server_spec(server_spec: str | None) -> str | dict[str, Any] | ClientTransport
```
Turn CLI inputs into something ``Client()`` accepts.
Exactly one of ``server_spec`` or ``command`` should be provided.
Resolution order for ``server_spec``:
1. URLs (``http://``, ``https://``) — passed through as-is.
If ``--transport`` is ``sse``, the URL is rewritten to end with ``/sse``
so ``infer_transport`` picks the right transport.
2. Existing file paths, or strings ending in ``.py``/``.js``/``.json``.
3. Anything else — name-based resolution via ``resolve_name``.
When ``command`` is provided, the string is shell-split into a
``StdioTransport(command, args)``.
### `coerce_value` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L264" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
coerce_value(raw: str, schema: dict[str, Any]) -> Any
```
Coerce a string CLI value according to a JSON-Schema type hint.
### `parse_tool_arguments` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L298" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
parse_tool_arguments(raw_args: tuple[str, ...], input_json: str | None, input_schema: dict[str, Any]) -> dict[str, Any]
```
Build a tool-call argument dict from CLI inputs.
A single JSON object argument is treated as the full argument dict.
``--input-json`` provides the base dict; ``key=value`` pairs override.
Values are coerced using the tool's ``inputSchema``.
### `format_tool_signature` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L370" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
format_tool_signature(tool: mcp.types.Tool) -> str
```
Build ``name(param: type, ...) -> return_type`` from a tool's JSON schemas.
### `list_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L641" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_command(server_spec: Annotated[str | None, cyclopts.Parameter(help='Server URL, Python file, MCPConfig JSON, or .js file')] = None) -> None
```
List tools available on an MCP server.
**Examples:**
fastmcp list http://localhost:8000/mcp
fastmcp list server.py
fastmcp list mcp.json --json
fastmcp list --command 'npx -y @mcp/server' --resources
fastmcp list http://server/mcp --transport sse
### `call_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L796" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
call_command(server_spec: Annotated[str | None, cyclopts.Parameter(help='Server URL, Python file, MCPConfig JSON, or .js file')] = None, target: Annotated[str, cyclopts.Parameter(help='Tool name, resource URI, or prompt name (with --prompt)')] = '', *arguments: str) -> None
```
Call a tool, read a resource, or get a prompt on an MCP server.
By default the target is treated as a tool name. If the target
contains ``://`` it is treated as a resource URI. Pass ``--prompt``
to treat it as a prompt name.
Arguments are passed as key=value pairs. Use --input-json for complex
or nested arguments.
**Examples:**
```
fastmcp call server.py greet name=World
fastmcp call server.py resource://docs/readme
fastmcp call server.py analyze --prompt data='[1,2,3]'
fastmcp call http://server/mcp create --input-json '{"tags": ["a","b"]}'
```
### `discover_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/client.py#L897" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
discover_command() -> None
```
Discover MCP servers configured in editor and project configs.
Scans Claude Desktop, Claude Code, Cursor, Gemini CLI, Goose, and
project-level mcp.json files for MCP server definitions.
Discovered server names can be used directly with ``fastmcp list``
and ``fastmcp call`` instead of specifying a URL or file path.
**Examples:**
fastmcp discover
fastmcp discover --source claude-code
fastmcp discover --source cursor --source gemini --json
fastmcp list weather
fastmcp call cursor:weather get_forecast city=London

View file

@ -1,71 +0,0 @@
---
title: discovery
sidebarTitle: discovery
---
# `fastmcp.cli.discovery`
Discover MCP servers configured in editor config files.
Scans filesystem-readable config files from editors like Claude Desktop,
Claude Code, Cursor, Gemini CLI, and Goose, as well as project-level
``mcp.json`` files. Each discovered server can be resolved by name
(or ``source:name``) so the CLI can connect without requiring a URL
or file path.
## Functions
### `discover_servers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/discovery.py#L314" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
discover_servers(start_dir: Path | None = None) -> list[DiscoveredServer]
```
Run all scanners and return the combined results.
Duplicate names across sources are preserved — callers can
use :pyattr:`DiscoveredServer.qualified_name` to disambiguate.
### `resolve_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/discovery.py#L331" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resolve_name(name: str, start_dir: Path | None = None) -> ClientTransport
```
Resolve a server name (or ``source:name``) to a transport.
Raises :class:`ValueError` when the name is not found or is ambiguous.
## Classes
### `DiscoveredServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/discovery.py#L37" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A single MCP server found in an editor or project config.
**Methods:**
#### `qualified_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/discovery.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
qualified_name(self) -> str
```
Fully qualified ``source:name`` identifier.
#### `transport_summary` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/discovery.py#L51" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
transport_summary(self) -> str
```
Human-readable one-liner describing the transport.

View file

@ -1,66 +0,0 @@
---
title: generate
sidebarTitle: generate
---
# `fastmcp.cli.generate`
Generate a standalone CLI script and agent skill from an MCP server.
## Functions
### `serialize_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/generate.py#L122" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
serialize_transport(resolved: str | dict[str, Any] | ClientTransport) -> tuple[str, set[str]]
```
Serialize a resolved transport to a Python expression string.
Returns ``(expression, extra_imports)`` where *extra_imports* is a set of
import lines needed by the expression.
### `generate_cli_script` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/generate.py#L283" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_cli_script(server_name: str, server_spec: str, transport_code: str, extra_imports: set[str], tools: list[mcp.types.Tool]) -> str
```
Generate the full CLI script source code.
### `generate_skill_content` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/generate.py#L619" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_skill_content(server_name: str, cli_filename: str, tools: list[mcp.types.Tool]) -> str
```
Generate a SKILL.md file for a generated CLI script.
### `generate_cli_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/generate.py#L670" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_cli_command(server_spec: Annotated[str, cyclopts.Parameter(help='Server URL, Python file, MCPConfig JSON, discovered name, or .js file')], output: Annotated[str, cyclopts.Parameter(help='Output file path (default: cli.py)')] = 'cli.py') -> None
```
Generate a standalone CLI script from an MCP server.
Connects to the server, reads its tools/resources/prompts, and writes
a Python script that can invoke them directly. Also generates a SKILL.md
agent skill file unless --no-skill is passed.
**Examples:**
fastmcp generate-cli weather
fastmcp generate-cli weather my_cli.py
fastmcp generate-cli http://localhost:8000/mcp
fastmcp generate-cli server.py output.py -f
fastmcp generate-cli weather --no-skill

View file

@ -1,9 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.cli.install`
Install subcommands for FastMCP CLI using Cyclopts.

View file

@ -1,71 +0,0 @@
---
title: claude_code
sidebarTitle: claude_code
---
# `fastmcp.cli.install.claude_code`
Claude Code integration for FastMCP install using Cyclopts.
## Functions
### `find_claude_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_code.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
find_claude_command() -> str | None
```
Find the Claude Code CLI command.
Checks common installation locations since 'claude' is often a shell alias
that doesn't work with subprocess calls.
### `check_claude_code_available` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_code.py#L68" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
check_claude_code_available() -> bool
```
Check if Claude Code CLI is available.
### `install_claude_code` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_code.py#L73" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_claude_code(file: Path, server_object: str | None, name: str) -> bool
```
Install FastMCP server in Claude Code.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `name`: Name for the server in Claude Code
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `env_vars`: Optional dictionary of environment variables
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
**Returns:**
- True if installation was successful, False otherwise
### `claude_code_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_code.py#L155" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
claude_code_command(server_spec: str) -> None
```
Install an MCP server in Claude Code.
**Args:**
- `server_spec`: Python file to install, optionally with \:object suffix

View file

@ -1,62 +0,0 @@
---
title: claude_desktop
sidebarTitle: claude_desktop
---
# `fastmcp.cli.install.claude_desktop`
Claude Desktop integration for FastMCP install using Cyclopts.
## Functions
### `get_claude_config_path` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_desktop.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_claude_config_path(config_path: Path | None = None) -> Path | None
```
Get the Claude config directory based on platform.
**Args:**
- `config_path`: Optional custom path to the Claude Desktop config directory
### `install_claude_desktop` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_desktop.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_claude_desktop(file: Path, server_object: str | None, name: str) -> bool
```
Install FastMCP server in Claude Desktop.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `name`: Name for the server in Claude's config
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `env_vars`: Optional dictionary of environment variables
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
- `config_path`: Optional custom path to Claude Desktop config directory
**Returns:**
- True if installation was successful, False otherwise
### `claude_desktop_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/claude_desktop.py#L139" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
claude_desktop_command(server_spec: str) -> None
```
Install an MCP server in Claude Desktop.
**Args:**
- `server_spec`: Python file to install, optionally with \:object suffix

View file

@ -1,107 +0,0 @@
---
title: cursor
sidebarTitle: cursor
---
# `fastmcp.cli.install.cursor`
Cursor integration for FastMCP install using Cyclopts.
## Functions
### `generate_cursor_deeplink` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/cursor.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_cursor_deeplink(server_name: str, server_config: StdioMCPServer) -> str
```
Generate a Cursor deeplink for installing the MCP server.
**Args:**
- `server_name`: Name of the server
- `server_config`: Server configuration
**Returns:**
- Deeplink URL that can be clicked to install the server
### `open_deeplink` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/cursor.py#L47" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
open_deeplink(deeplink: str) -> bool
```
Attempt to open a Cursor deeplink URL using the system's default handler.
**Args:**
- `deeplink`: The deeplink URL to open
**Returns:**
- True if the command succeeded, False otherwise
### `install_cursor_workspace` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/cursor.py#L59" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_cursor_workspace(file: Path, server_object: str | None, name: str, workspace_path: Path) -> bool
```
Install FastMCP server to workspace-specific Cursor configuration.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `name`: Name for the server in Cursor
- `workspace_path`: Path to the workspace directory
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `env_vars`: Optional dictionary of environment variables
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
**Returns:**
- True if installation was successful, False otherwise
### `install_cursor` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/cursor.py#L143" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_cursor(file: Path, server_object: str | None, name: str) -> bool
```
Install FastMCP server in Cursor.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `name`: Name for the server in Cursor
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `env_vars`: Optional dictionary of environment variables
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
- `workspace`: Optional workspace directory for project-specific installation
**Returns:**
- True if installation was successful, False otherwise
### `cursor_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/cursor.py#L228" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
cursor_command(server_spec: str) -> None
```
Install an MCP server in Cursor.
**Args:**
- `server_spec`: Python file to install, optionally with \:object suffix

View file

@ -1,68 +0,0 @@
---
title: gemini_cli
sidebarTitle: gemini_cli
---
# `fastmcp.cli.install.gemini_cli`
Gemini CLI integration for FastMCP install using Cyclopts.
## Functions
### `find_gemini_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/gemini_cli.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
find_gemini_command() -> str | None
```
Find the Gemini CLI command.
### `check_gemini_cli_available` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/gemini_cli.py#L64" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
check_gemini_cli_available() -> bool
```
Check if Gemini CLI is available.
### `install_gemini_cli` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/gemini_cli.py#L69" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_gemini_cli(file: Path, server_object: str | None, name: str) -> bool
```
Install FastMCP server in Gemini CLI.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `name`: Name for the server in Gemini CLI
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `env_vars`: Optional dictionary of environment variables
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
**Returns:**
- True if installation was successful, False otherwise
### `gemini_cli_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/gemini_cli.py#L152" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
gemini_cli_command(server_spec: str) -> None
```
Install an MCP server in Gemini CLI.
**Args:**
- `server_spec`: Python file to install, optionally with \:object suffix

View file

@ -1,67 +0,0 @@
---
title: goose
sidebarTitle: goose
---
# `fastmcp.cli.install.goose`
Goose integration for FastMCP install using Cyclopts.
## Functions
### `generate_goose_deeplink` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/goose.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_goose_deeplink(name: str, command: str, args: list[str]) -> str
```
Generate a Goose deeplink for installing an MCP extension.
**Args:**
- `name`: Human-readable display name for the extension.
- `command`: The executable command (e.g. "uv").
- `args`: Arguments to the command.
- `description`: Short description shown in Goose.
**Returns:**
- A goose://extension?... deeplink URL.
### `install_goose` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/goose.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_goose(file: Path, server_object: str | None, name: str) -> bool
```
Install FastMCP server in Goose via deeplink.
**Args:**
- `file`: Path to the server file.
- `server_object`: Optional server object name (for \:object suffix).
- `name`: Name for the extension in Goose.
- `with_packages`: Optional list of additional packages to install.
- `python_version`: Optional Python version to use.
**Returns:**
- True if installation was successful, False otherwise.
### `goose_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/goose.py#L135" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
goose_command(server_spec: str) -> None
```
Install an MCP server in Goose.
Uses uvx to run the server. Environment variables are not included
in the deeplink; use `fastmcp install mcp-json` to generate a full
config for manual installation.
**Args:**
- `server_spec`: Python file to install, optionally with \:object suffix

View file

@ -1,49 +0,0 @@
---
title: mcp_json
sidebarTitle: mcp_json
---
# `fastmcp.cli.install.mcp_json`
MCP configuration JSON generation for FastMCP install using Cyclopts.
## Functions
### `install_mcp_json` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/mcp_json.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_mcp_json(file: Path, server_object: str | None, name: str) -> bool
```
Generate MCP configuration JSON for manual installation.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `name`: Name for the server in MCP config
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `env_vars`: Optional dictionary of environment variables
- `copy`: If True, copy to clipboard instead of printing to stdout
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
**Returns:**
- True if generation was successful, False otherwise
### `mcp_json_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/mcp_json.py#L98" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
mcp_json_command(server_spec: str) -> None
```
Generate MCP configuration JSON for manual installation.
**Args:**
- `server_spec`: Python file to install, optionally with \:object suffix

View file

@ -1,62 +0,0 @@
---
title: shared
sidebarTitle: shared
---
# `fastmcp.cli.install.shared`
Shared utilities for install commands.
## Functions
### `validate_server_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/shared.py#L28" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_server_name(name: str) -> str
```
Validate that a server name is safe for use as a subprocess argument.
Raises SystemExit if the name contains shell metacharacters.
### `parse_env_var` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/shared.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
parse_env_var(env_var: str) -> tuple[str, str]
```
Parse environment variable string in format KEY=VALUE.
### `process_common_args` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/shared.py#L53" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
process_common_args(server_spec: str, server_name: str | None, with_packages: list[str] | None, env_vars: list[str] | None, env_file: Path | None) -> tuple[Path, str | None, str, list[str], dict[str, str] | None]
```
Process common arguments shared by all install commands.
Handles both fastmcp.json config files and traditional file.py:object syntax.
### `open_deeplink` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/shared.py#L169" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
open_deeplink(url: str) -> bool
```
Attempt to open a deeplink URL using the system's default handler.
**Args:**
- `url`: The deeplink URL to open.
- `expected_scheme`: The URL scheme to validate (e.g. "cursor", "goose").
**Returns:**
- True if the command succeeded, False otherwise.

View file

@ -1,50 +0,0 @@
---
title: stdio
sidebarTitle: stdio
---
# `fastmcp.cli.install.stdio`
Stdio command generation for FastMCP install using Cyclopts.
## Functions
### `install_stdio` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/stdio.py#L21" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
install_stdio(file: Path, server_object: str | None) -> bool
```
Generate the stdio command for running a FastMCP server.
**Args:**
- `file`: Path to the server file
- `server_object`: Optional server object name (for \:object suffix)
- `with_editable`: Optional list of directories to install in editable mode
- `with_packages`: Optional list of additional packages to install
- `copy`: If True, copy to clipboard instead of printing to stdout
- `python_version`: Optional Python version to use
- `with_requirements`: Optional requirements file to install from
- `project`: Optional project directory to run within
**Returns:**
- True if generation was successful, False otherwise
### `stdio_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/install/stdio.py#L78" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
stdio_command(server_spec: str) -> None
```
Generate the stdio command for running a FastMCP server.
Outputs the shell command that an MCP host would use to start this server
over stdio transport. Useful for manual configuration or debugging.
**Args:**
- `server_spec`: Python file to run, optionally with \:object suffix

View file

@ -1,136 +0,0 @@
---
title: run
sidebarTitle: run
---
# `fastmcp.cli.run`
FastMCP run command implementation with enhanced type hints.
## Functions
### `is_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L84" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_url(path: str) -> bool
```
Check if a string is a URL.
### `create_client_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L90" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```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
### `create_mcp_config_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L110" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_mcp_config_server(mcp_config_path: Path) -> FastMCP[None]
```
Create a FastMCP server from a MCPConfig.
### `load_mcp_server_config` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L119" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_mcp_server_config(config_path: Path) -> MCPServerConfig
```
Load a FastMCP configuration from a fastmcp.json file.
**Args:**
- `config_path`: Path to fastmcp.json file
**Returns:**
- MCPServerConfig object
### `run_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L136" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run_command(server_spec: str, transport: TransportType | None = None, host: str | None = None, port: int | None = None, path: str | None = None, log_level: LogLevelType | None = None, server_args: list[str] | None = None, show_banner: bool = True, use_direct_import: bool = False, skip_source: bool = False, stateless: bool = False) -> None
```
Run a MCP server or connect to a remote one.
**Args:**
- `server_spec`: Python file, object specification (file\:obj), config file, 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
- `path`: Path to bind to when using http transport
- `log_level`: Log level
- `server_args`: Additional arguments to pass to the server
- `show_banner`: Whether to show the server banner
- `use_direct_import`: Whether to use direct import instead of subprocess
- `skip_source`: Whether to skip source preparation step
- `stateless`: Whether to run in stateless mode (no session)
### `run_module_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L272" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run_module_command(module_name: str) -> None
```
Run a Python module directly using ``python -m <module>``.
When ``-m`` is used, the module manages its own server startup.
No server-object discovery or transport overrides are applied.
**Args:**
- `module_name`: Dotted module name (e.g. ``my_package``).
- `env_command_builder`: An optional callable that wraps a command list
with environment setup (e.g. ``UVEnvironment.build_command``).
- `extra_args`: Extra arguments forwarded after the module name.
### `run_v1_server_async` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L311" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run_v1_server_async(server: FastMCP1x, host: str | None = None, port: int | None = None, transport: TransportType | None = None) -> None
```
Run a FastMCP 1.x server using async methods.
**Args:**
- `server`: FastMCP 1.x server instance
- `host`: Host to bind to
- `port`: Port to bind to
- `transport`: Transport protocol to use
### `run_with_reload` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/run.py#L376" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run_with_reload(cmd: list[str], reload_dirs: list[Path] | None = None, is_stdio: bool = False) -> None
```
Run a command with file watching and auto-reload.
**Args:**
- `cmd`: Command to run as subprocess (should include --no-reload)
- `reload_dirs`: Directories to watch for changes (default\: cwd)
- `is_stdio`: Whether this is stdio transport

View file

@ -1,41 +0,0 @@
---
title: tasks
sidebarTitle: tasks
---
# `fastmcp.cli.tasks`
FastMCP tasks CLI for Docket task management.
## Functions
### `check_distributed_backend` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/tasks.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
check_distributed_backend() -> None
```
Check if Docket is configured with a distributed backend.
The CLI worker runs as a separate process, so it needs Redis/Valkey
to coordinate with the main server process.
**Raises:**
- `SystemExit`: If using memory\:// URL
### `worker` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/cli/tasks.py#L61" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
worker(server_spec: Annotated[str | None, cyclopts.Parameter(help='Python file to run, optionally with :object suffix, or None to auto-detect fastmcp.json')] = None) -> None
```
Start an additional worker to process background tasks.
Connects to your Docket backend and processes tasks in parallel with
any other running workers. Configure via environment variables
(FASTMCP_DOCKET_*).

View file

@ -1,6 +1,6 @@
---
title: __init__
sidebarTitle: __init__
title: cli
sidebarTitle: cli
---
# `fastmcp.cli`

View file

@ -1,8 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.client.auth`
*This module is empty or contains only private/internal implementations.*

View file

@ -1,18 +0,0 @@
---
title: bearer
sidebarTitle: bearer
---
# `fastmcp.client.auth.bearer`
## Classes
### `BearerAuth` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/bearer.py#L11" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `auth_flow` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/bearer.py#L15" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
auth_flow(self, request)
```

View file

@ -1,110 +0,0 @@
---
title: oauth
sidebarTitle: oauth
---
# `fastmcp.client.auth.oauth`
## Functions
### `check_if_auth_required` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
check_if_auth_required(mcp_url: str, httpx_kwargs: dict[str, Any] | None = None) -> bool
```
Check if the MCP endpoint requires authentication by making a test request.
**Returns:**
- True if auth appears to be required, False otherwise
## Classes
### `ClientNotFoundError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L37" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Raised when OAuth client credentials are not found on the server.
### `TokenStorageAdapter` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L71" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `clear` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L102" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
clear(self) -> None
```
#### `get_tokens` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L111" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_tokens(self) -> OAuthToken | None
```
#### `set_tokens` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L115" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_tokens(self, tokens: OAuthToken) -> None
```
#### `get_token_expiry` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L135" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_token_expiry(self) -> float | None
```
#### `get_client_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L145" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_client_info(self) -> OAuthClientInformationFull | None
```
#### `set_client_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L151" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_client_info(self, client_info: OAuthClientInformationFull) -> None
```
### `OAuth` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OAuth client provider for MCP servers with browser-based authentication.
This class provides OAuth authentication for FastMCP clients by opening
a browser for user authorization and running a local callback server.
**Methods:**
#### `redirect_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L320" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
redirect_handler(self, authorization_url: str) -> None
```
Open browser for authorization, with pre-flight check for invalid client.
#### `callback_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L341" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
callback_handler(self) -> tuple[str, str | None]
```
Handle OAuth callback and return (auth_code, state).
#### `async_auth_flow` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/auth/oauth.py#L380" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
async_auth_flow(self, request: httpx.Request) -> AsyncGenerator[httpx.Request, httpx.Response]
```
HTTPX auth flow with automatic retry on stale cached credentials.
If the OAuth flow fails due to invalid/stale client credentials,
clears the cache and retries once with fresh registration.

View file

@ -1,286 +0,0 @@
---
title: client
sidebarTitle: client
---
# `fastmcp.client.client`
## Classes
### `ClientSessionState` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L96" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Holds all session-related state for a Client instance.
This allows clean separation of configuration (which is copied) from
session state (which should be fresh for each new client instance).
### `CallToolResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L113" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Parsed result from a tool call.
### `Client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L123" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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.
This client supports reentrant context managers (multiple concurrent
`async with client:` blocks) using reference counting and background session
management. This allows efficient session reuse in any scenario with
nested or concurrent client usage.
MCP SDK 1.10 introduced automatic list_tools() calls during call_tool()
execution. This created a race condition where events could be reset while
other tasks were waiting on them, causing deadlocks. The issue was exposed
in proxy scenarios but affects any reentrant usage.
The solution uses reference counting to track active context managers,
a background task to manage the session lifecycle, events to coordinate
between tasks, and ensures all session state changes happen within a lock.
Events are only created when needed, never reset outside locks.
This design prevents race conditions where tasks wait on events that get
replaced by other tasks, ensuring reliable coordination in concurrent scenarios.
**Args:**
- `transport`:
Connection source specification, which can be\:
- ClientTransport\: Direct transport instance
- FastMCP\: In-process FastMCP server
- AnyUrl or 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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L370" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
session(self) -> ClientSession
```
Get the current active session. Raises RuntimeError if not connected.
#### `initialize_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L380" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
initialize_result(self) -> mcp.types.InitializeResult | None
```
Get the result of the initialization request.
#### `set_roots` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L384" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L388" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_sampling_callback(self, sampling_callback: SamplingHandler, sampling_capabilities: mcp.types.SamplingCapability | None = None) -> None
```
Set the sampling callback for the client.
#### `set_elicitation_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L403" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_elicitation_callback(self, elicitation_callback: ElicitationHandler) -> None
```
Set the elicitation callback for the client.
#### `is_connected` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L411" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_connected(self) -> bool
```
Check if the client is currently connected.
#### `new` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L415" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
new(self) -> Client[ClientTransportT]
```
Create a new client instance with the same configuration but fresh session state.
This creates a new client with the same transport, handlers, and configuration,
but with no active session. Useful for creating independent sessions that don't
share state with the original client.
**Returns:**
- A new Client instance with the same configuration but disconnected state.
#### `initialize` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L476" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
initialize(self, timeout: datetime.timedelta | float | int | None = None) -> mcp.types.InitializeResult
```
Send an initialize request to the server.
This method performs the MCP initialization handshake with the server,
exchanging capabilities and server information. It is idempotent - calling
it multiple times returns the cached result from the first call.
The initialization happens automatically when entering the client context
manager unless `auto_initialize=False` was set during client construction.
Manual calls to this method are only needed when auto-initialization is disabled.
**Args:**
- `timeout`: Optional timeout for the initialization request (seconds or timedelta).
If None, uses the client's init_timeout setting.
**Returns:**
- The server's initialization response containing server info,
capabilities, protocol version, and optional instructions.
**Raises:**
- `RuntimeError`: If the client is not connected or initialization times out.
#### `close` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L791" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close(self)
```
#### `ping` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L797" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
ping(self) -> bool
```
Send a ping request.
#### `cancel` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L802" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
cancel(self, request_id: str | int, reason: str | None = None) -> None
```
Send a cancellation notification for an in-progress request.
#### `progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L819" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
progress(self, progress_token: str | int, progress: float, total: float | None = None, message: str | None = None) -> None
```
Send a progress notification.
#### `set_logging_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L831" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_logging_level(self, level: mcp.types.LoggingLevel) -> None
```
Send a logging/setLevel request.
#### `send_roots_list_changed` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L835" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
send_roots_list_changed(self) -> None
```
Send a roots/list_changed notification.
#### `complete_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L841" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
complete_mcp(self, ref: mcp.types.ResourceTemplateReference | mcp.types.PromptReference, argument: dict[str, str], context_arguments: dict[str, Any] | None = None) -> mcp.types.CompleteResult
```
Send a completion request and return the complete MCP protocol result.
**Args:**
- `ref`: The reference to complete.
- `argument`: Arguments to pass to the completion request.
- `context_arguments`: Optional context arguments to
include with the completion request. Defaults to None.
**Returns:**
- mcp.types.CompleteResult: The complete response object from the protocol,
containing the completion and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `complete` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L872" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
complete(self, ref: mcp.types.ResourceTemplateReference | mcp.types.PromptReference, argument: dict[str, str], context_arguments: dict[str, Any] | None = None) -> mcp.types.Completion
```
Send a completion request to the server.
**Args:**
- `ref`: The reference to complete.
- `argument`: Arguments to pass to the completion request.
- `context_arguments`: Optional context arguments to
include with the completion request. Defaults to None.
**Returns:**
- mcp.types.Completion: The completion object.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `generate_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/client.py#L899" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate_name(cls, name: str | None = None) -> str
```

View file

@ -1,18 +0,0 @@
---
title: elicitation
sidebarTitle: elicitation
---
# `fastmcp.client.elicitation`
## Functions
### `create_elicitation_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/elicitation.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_elicitation_callback(elicitation_handler: ElicitationHandler) -> ElicitationFnT
```
## Classes
### `ElicitResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/elicitation.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

View file

@ -1,24 +0,0 @@
---
title: logging
sidebarTitle: logging
---
# `fastmcp.client.logging`
## Functions
### `default_log_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/logging.py#L17" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
default_log_handler(message: LogMessage) -> None
```
Default handler that properly routes server log messages to appropriate log levels.
### `create_log_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/logging.py#L47" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_log_callback(handler: LogHandler | None = None) -> LoggingFnT
```

View file

@ -1,107 +0,0 @@
---
title: messages
sidebarTitle: messages
---
# `fastmcp.client.messages`
## Classes
### `MessageHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L16" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
This class is used to handle MCP messages sent to the client. It is used to handle all messages,
requests, notifications, and exceptions. Users can override any of the hooks
**Methods:**
#### `dispatch` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
dispatch(self, message: Message) -> None
```
#### `on_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_message(self, message: Message) -> None
```
#### `on_request` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_request(self, message: RequestResponder[mcp.types.ServerRequest, mcp.types.ClientResult]) -> None
```
#### `on_ping` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L84" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_ping(self, message: mcp.types.PingRequest) -> None
```
#### `on_list_roots` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L87" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_list_roots(self, message: mcp.types.ListRootsRequest) -> None
```
#### `on_create_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L90" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_create_message(self, message: mcp.types.CreateMessageRequest) -> None
```
#### `on_notification` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L93" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_notification(self, message: mcp.types.ServerNotification) -> None
```
#### `on_exception` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L96" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_exception(self, message: Exception) -> None
```
#### `on_progress` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L99" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_progress(self, message: mcp.types.ProgressNotification) -> None
```
#### `on_logging_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L102" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_logging_message(self, message: mcp.types.LoggingMessageNotification) -> None
```
#### `on_tool_list_changed` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L107" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_tool_list_changed(self, message: mcp.types.ToolListChangedNotification) -> None
```
#### `on_resource_list_changed` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L112" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_resource_list_changed(self, message: mcp.types.ResourceListChangedNotification) -> None
```
#### `on_prompt_list_changed` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_prompt_list_changed(self, message: mcp.types.PromptListChangedNotification) -> None
```
#### `on_resource_updated` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L122" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_resource_updated(self, message: mcp.types.ResourceUpdatedNotification) -> None
```
#### `on_cancelled` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/messages.py#L127" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_cancelled(self, message: mcp.types.CancelledNotification) -> None
```

View file

@ -1,9 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.client.mixins`
Client mixins for FastMCP.

View file

@ -1,122 +0,0 @@
---
title: prompts
sidebarTitle: prompts
---
# `fastmcp.client.mixins.prompts`
Prompt-related methods for FastMCP Client.
## Classes
### `ClientPromptsMixin` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L31" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Mixin providing prompt-related methods for Client.
**Methods:**
#### `list_prompts_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_prompts_mcp(self: Client) -> mcp.types.ListPromptsResult
```
Send a prompts/list request and return the complete MCP protocol result.
**Args:**
- `cursor`: Optional pagination cursor from a previous request's nextCursor.
**Returns:**
- mcp.types.ListPromptsResult: The complete response object from the protocol,
containing the list of prompts and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `list_prompts` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L65" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_prompts(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.Prompt]
```
Retrieve all prompts available on the server.
This method automatically fetches all pages if the server paginates results,
returning the complete list. For manual pagination control (e.g., to handle
large result sets incrementally), use list_prompts_mcp() with the cursor parameter.
**Args:**
- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250.
**Returns:**
- list\[mcp.types.Prompt]: A list of all Prompt objects.
**Raises:**
- `RuntimeError`: If the page limit is reached before pagination completes.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `get_prompt_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L113" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt_mcp(self: Client, name: str, arguments: dict[str, Any] | None = None, meta: dict[str, Any] | None = None) -> mcp.types.GetPromptResult
```
Send a prompts/get request and return the complete MCP protocol result.
**Args:**
- `name`: The name of the prompt to retrieve.
- `arguments`: Arguments to pass to the prompt. Defaults to None.
- `meta`: Request metadata (e.g., for SEP-1686 tasks). Defaults to None.
**Returns:**
- mcp.types.GetPromptResult: The complete response object from the protocol,
containing the prompt messages and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L183" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt(self: Client, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.GetPromptResult
```
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L194" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt(self: Client, name: str, arguments: dict[str, Any] | None = None) -> PromptTask
```
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/prompts.py#L206" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_prompt(self: Client, name: str, arguments: dict[str, Any] | None = None) -> mcp.types.GetPromptResult | PromptTask
```
Retrieve a rendered prompt message list from the server.
**Args:**
- `name`: The name of the prompt to retrieve.
- `arguments`: Arguments to pass to the prompt. Defaults to None.
- `version`: Specific prompt version to get. If None, gets highest version.
- `meta`: Optional request-level metadata.
- `task`: If True, execute as background task (SEP-1686). Defaults to False.
- `task_id`: Optional client-provided task ID (auto-generated if not provided).
- `ttl`: Time to keep results available in milliseconds (default 60s).
**Returns:**
- mcp.types.GetPromptResult | PromptTask: The complete response object if task=False,
or a PromptTask object if task=True.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError

View file

@ -1,164 +0,0 @@
---
title: resources
sidebarTitle: resources
---
# `fastmcp.client.mixins.resources`
Resource-related methods for FastMCP Client.
## Classes
### `ClientResourcesMixin` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Mixin providing resource-related methods for Client.
**Methods:**
#### `list_resources_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L35" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resources_mcp(self: Client) -> mcp.types.ListResourcesResult
```
Send a resources/list request and return the complete MCP protocol result.
**Args:**
- `cursor`: Optional pagination cursor from a previous request's nextCursor.
**Returns:**
- mcp.types.ListResourcesResult: The complete response object from the protocol,
containing the list of resources and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `list_resources` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L64" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resources(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.Resource]
```
Retrieve all resources available on the server.
This method automatically fetches all pages if the server paginates results,
returning the complete list. For manual pagination control (e.g., to handle
large result sets incrementally), use list_resources_mcp() with the cursor parameter.
**Args:**
- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250.
**Returns:**
- list\[mcp.types.Resource]: A list of all Resource objects.
**Raises:**
- `RuntimeError`: If the page limit is reached before pagination completes.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `list_resource_templates_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L111" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resource_templates_mcp(self: Client) -> mcp.types.ListResourceTemplatesResult
```
Send a resources/listResourceTemplates request and return the complete MCP protocol result.
**Args:**
- `cursor`: Optional pagination cursor from a previous request's nextCursor.
**Returns:**
- mcp.types.ListResourceTemplatesResult: The complete response object from the protocol,
containing the list of resource templates and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `list_resource_templates` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_resource_templates(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.ResourceTemplate]
```
Retrieve all resource templates available on the server.
This method automatically fetches all pages if the server paginates results,
returning the complete list. For manual pagination control (e.g., to handle
large result sets incrementally), use list_resource_templates_mcp() with the
cursor parameter.
**Args:**
- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250.
**Returns:**
- list\[mcp.types.ResourceTemplate]: A list of all ResourceTemplate objects.
**Raises:**
- `RuntimeError`: If the page limit is reached before pagination completes.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `read_resource_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L189" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_resource_mcp(self: Client, uri: AnyUrl | str, meta: dict[str, Any] | None = None) -> mcp.types.ReadResourceResult
```
Send a resources/read request and return the complete MCP protocol result.
**Args:**
- `uri`: The URI of the resource to read. Can be a string or an AnyUrl object.
- `meta`: Request metadata (e.g., for SEP-1686 tasks). Defaults to None.
**Returns:**
- mcp.types.ReadResourceResult: The complete response object from the protocol,
containing the resource contents and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L245" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_resource(self: Client, uri: AnyUrl | str) -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents]
```
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L255" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_resource(self: Client, uri: AnyUrl | str) -> ResourceTask
```
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/resources.py#L266" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read_resource(self: Client, uri: AnyUrl | str) -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] | ResourceTask
```
Read the contents of a resource or resolved template.
**Args:**
- `uri`: The URI of the resource to read. Can be a string or an AnyUrl object.
- `version`: Specific version to read. If None, reads highest version.
- `meta`: Optional request-level metadata.
- `task`: If True, execute as background task (SEP-1686). Defaults to False.
- `task_id`: Optional client-provided task ID (auto-generated if not provided).
- `ttl`: Time to keep results available in milliseconds (default 60s).
**Returns:**
- list\[mcp.types.TextResourceContents | mcp.types.BlobResourceContents] | ResourceTask:
A list of content objects if task=False, or a ResourceTask object if task=True.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError

View file

@ -1,110 +0,0 @@
---
title: task_management
sidebarTitle: task_management
---
# `fastmcp.client.mixins.task_management`
Task management methods for FastMCP Client.
## Classes
### `ClientTaskManagementMixin` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/task_management.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Mixin providing task management methods for Client.
**Methods:**
#### `get_task_status` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/task_management.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_task_status(self: Client, task_id: str) -> GetTaskResult
```
Query the status of a background task.
Sends a 'tasks/get' MCP protocol request over the existing transport.
**Args:**
- `task_id`: The task ID returned from call_tool_as_task
**Returns:**
- Status information including taskId, status, pollInterval, etc.
**Raises:**
- `RuntimeError`: If client not connected
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `get_task_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/task_management.py#L56" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_task_result(self: Client, task_id: str) -> Any
```
Retrieve the raw result of a completed background task.
Sends a 'tasks/result' MCP protocol request over the existing transport.
Returns the raw result - callers should parse it appropriately.
**Args:**
- `task_id`: The task ID returned from call_tool_as_task
**Returns:**
- The raw result (could be tool, prompt, or resource result)
**Raises:**
- `RuntimeError`: If client not connected, task not found, or task failed
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `list_tasks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/task_management.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_tasks(self: Client, cursor: str | None = None, limit: int = 50) -> dict[str, Any]
```
List background tasks.
Sends a 'tasks/list' MCP protocol request to the server. If the server
returns an empty list (indicating client-side tracking), falls back to
querying status for locally tracked task IDs.
**Args:**
- `cursor`: Optional pagination cursor
- `limit`: Maximum number of tasks to return (default 50)
**Returns:**
- Response with structure:
- tasks: List of task status dicts with taskId, status, etc.
- nextCursor: Optional cursor for next page
**Raises:**
- `RuntimeError`: If client not connected
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `cancel_task` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/task_management.py#L135" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
cancel_task(self: Client, task_id: str) -> mcp.types.CancelTaskResult
```
Cancel a task, transitioning it to cancelled state.
Sends a 'tasks/cancel' MCP protocol request. Task will halt execution
and transition to cancelled state.
**Args:**
- `task_id`: The task ID to cancel
**Returns:**
- The task status showing cancelled state
**Raises:**
- `RuntimeError`: If task doesn't exist
- `McpError`: If the request results in a TimeoutError | JSONRPCError

View file

@ -1,144 +0,0 @@
---
title: tools
sidebarTitle: tools
---
# `fastmcp.client.mixins.tools`
Tool-related methods for FastMCP Client.
## Classes
### `ClientToolsMixin` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L35" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Mixin providing tool-related methods for Client.
**Methods:**
#### `list_tools_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L40" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_tools_mcp(self: Client) -> mcp.types.ListToolsResult
```
Send a tools/list request and return the complete MCP protocol result.
**Args:**
- `cursor`: Optional pagination cursor from a previous request's nextCursor.
**Returns:**
- mcp.types.ListToolsResult: The complete response object from the protocol,
containing the list of tools and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `list_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L69" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_tools(self: Client, max_pages: int = AUTO_PAGINATION_MAX_PAGES) -> list[mcp.types.Tool]
```
Retrieve all tools available on the server.
This method automatically fetches all pages if the server paginates results,
returning the complete list. For manual pagination control (e.g., to handle
large result sets incrementally), use list_tools_mcp() with the cursor parameter.
**Args:**
- `max_pages`: Maximum number of pages to fetch before raising. Defaults to 250.
**Returns:**
- list\[mcp.types.Tool]: A list of all Tool objects.
**Raises:**
- `RuntimeError`: If the page limit is reached before pagination completes.
- `McpError`: If the request results in a TimeoutError | JSONRPCError
#### `call_tool_mcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L118" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
call_tool_mcp(self: Client, name: str, arguments: dict[str, Any], progress_handler: ProgressHandler | None = None, timeout: datetime.timedelta | float | int | None = None, meta: dict[str, Any] | None = None) -> mcp.types.CallToolResult
```
Send a tools/call request and return the complete MCP protocol result.
This method returns the raw CallToolResult object, which includes an isError flag
and other metadata. It does not raise an exception if the tool call results in an error.
**Args:**
- `name`: The name of the tool to call.
- `arguments`: Arguments to pass to the tool.
- `timeout`: The timeout for the tool call. Defaults to None.
- `progress_handler`: The progress handler to use for the tool call. Defaults to None.
- `meta`: Additional metadata to include with the request.
This is useful for passing contextual information (like user IDs, trace IDs, or preferences)
that shouldn't be tool arguments but may influence server-side processing. The server
can access this via `context.request_context.meta`. Defaults to None.
**Returns:**
- mcp.types.CallToolResult: The complete response object from the protocol,
containing the tool result and any additional metadata.
**Raises:**
- `RuntimeError`: If called while the client is not connected.
- `McpError`: If the tool call requests results in a TimeoutError | JSONRPCError
#### `call_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L211" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
call_tool(self: Client, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult
```
#### `call_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L225" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
call_tool(self: Client, name: str, arguments: dict[str, Any] | None = None) -> ToolTask
```
#### `call_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/mixins/tools.py#L240" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
call_tool(self: Client, name: str, arguments: dict[str, Any] | None = None) -> CallToolResult | ToolTask
```
Call a tool on the server.
Unlike call_tool_mcp, this method raises a ToolError if the tool call results in an error.
**Args:**
- `name`: The name of the tool to call.
- `arguments`: Arguments to pass to the tool. Defaults to None.
- `version`: Specific tool version to call. If None, calls highest version.
- `timeout`: The timeout for the tool call. Defaults to None.
- `progress_handler`: The progress handler to use for the tool call. Defaults to None.
- `raise_on_error`: Whether to raise an exception if the tool call results in an error. Defaults to True.
- `meta`: Additional metadata to include with the request.
This is useful for passing contextual information (like user IDs, trace IDs, or preferences)
that shouldn't be tool arguments but may influence server-side processing. The server
can access this via `context.request_context.meta`. Defaults to None.
- `task`: If True, execute as background task (SEP-1686). Defaults to False.
- `task_id`: Optional client-provided task ID (auto-generated if not provided).
- `ttl`: Time to keep results available in milliseconds (default 60s).
**Returns:**
- CallToolResult | ToolTask: The content returned by the tool if task=False,
or a ToolTask object if task=True. If the tool returns structured
outputs, they are returned as a dataclass (if an output schema
is available) or a dictionary; otherwise, a list of content
blocks is returned. Note: to receive both structured and
unstructured outputs, use call_tool_mcp instead and access the
raw result object.
**Raises:**
- `ToolError`: If the tool call results in an error.
- `McpError`: If the tool call request results in a TimeoutError | JSONRPCError
- `RuntimeError`: If called while the client is not connected.

View file

@ -1,70 +0,0 @@
---
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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/oauth_callback.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/oauth_callback.py#L103" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_oauth_callback_server(port: int, callback_path: str = '/callback', server_url: str | None = None, result_container: OAuthCallbackResult | None = None, result_ready: anyio.Event | 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
- `result_container`: Optional container to store callback results
- `result_ready`: Optional event to signal when callback is received
**Returns:**
- Configured uvicorn Server instance (not yet running)
## Classes
### `CallbackResponse` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/oauth_callback.py#L80" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `from_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/oauth_callback.py#L87" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_dict(cls, data: dict[str, str]) -> CallbackResponse
```
#### `to_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/oauth_callback.py#L90" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_dict(self) -> dict[str, str]
```
### `OAuthCallbackResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/oauth_callback.py#L95" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Container for OAuth callback results, used with anyio.Event for async coordination.

View file

@ -1,25 +0,0 @@
---
title: progress
sidebarTitle: progress
---
# `fastmcp.client.progress`
## Functions
### `default_progress_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/progress.py#L12" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
default_progress_handler(progress: float, total: float | None, message: str | None) -> None
```
Default handler for progress notifications.
Logs progress updates at debug level, properly handling missing total or message values.
**Args:**
- `progress`: Current progress value
- `total`: Optional total expected value
- `message`: Optional status message

View file

@ -1,20 +0,0 @@
---
title: roots
sidebarTitle: roots
---
# `fastmcp.client.roots`
## Functions
### `convert_roots_list` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/roots.py#L19" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
convert_roots_list(roots: RootsList) -> list[mcp.types.Root]
```
### `create_roots_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/roots.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_roots_callback(handler: RootsList | RootsHandler) -> ListRootsFnT
```

View file

@ -1,14 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.client.sampling`
## Functions
### `create_sampling_callback` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/sampling/__init__.py#L44" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_sampling_callback(sampling_handler: SamplingHandler) -> SamplingFnT
```

View file

@ -1,8 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.client.sampling.handlers`
*This module is empty or contains only private/internal implementations.*

View file

@ -1,17 +0,0 @@
---
title: anthropic
sidebarTitle: anthropic
---
# `fastmcp.client.sampling.handlers.anthropic`
Anthropic sampling handler for FastMCP.
## Classes
### `AnthropicSamplingHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/sampling/handlers/anthropic.py#L72" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Sampling handler that uses the Anthropic API.

View file

@ -1,17 +0,0 @@
---
title: google_genai
sidebarTitle: google_genai
---
# `fastmcp.client.sampling.handlers.google_genai`
Google GenAI sampling handler with tool support for FastMCP 3.0.
## Classes
### `GoogleGenaiSamplingHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/sampling/handlers/google_genai.py#L56" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Sampling handler that uses the Google GenAI API with tool support.

View file

@ -1,17 +0,0 @@
---
title: openai
sidebarTitle: openai
---
# `fastmcp.client.sampling.handlers.openai`
OpenAI sampling handler for FastMCP.
## Classes
### `OpenAISamplingHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/sampling/handlers/openai.py#L95" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Sampling handler that uses the OpenAI API.

View file

@ -1,219 +0,0 @@
---
title: tasks
sidebarTitle: tasks
---
# `fastmcp.client.tasks`
SEP-1686 client Task classes.
## Classes
### `TaskNotificationHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
MessageHandler that routes task status notifications to Task objects.
**Methods:**
#### `dispatch` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
dispatch(self, message: Message) -> None
```
Dispatch messages, including task status notifications.
### `Task` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L48" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Abstract base class for MCP background tasks (SEP-1686).
Provides a uniform API whether the server accepts background execution
or executes synchronously (graceful degradation per SEP-1686).
**Methods:**
#### `task_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
task_id(self) -> str
```
Get the task ID.
#### `returned_immediately` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L111" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
returned_immediately(self) -> bool
```
Check if server executed the task immediately.
**Returns:**
- True if server executed synchronously (graceful degradation or no task support)
- False if server accepted background execution
#### `on_status_change` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L146" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
on_status_change(self, callback: Callable[[GetTaskResult], None | Awaitable[None]]) -> None
```
Register callback for status change notifications.
The callback will be invoked when a notifications/tasks/status is received
for this task (optional server feature per SEP-1686 lines 436-444).
Supports both sync and async callbacks (auto-detected).
**Args:**
- `callback`: Function to call with GetTaskResult when status changes.
Can return None (sync) or Awaitable[None] (async).
#### `status` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L172" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
status(self) -> GetTaskResult
```
Get current task status.
If server executed immediately, returns synthetic completed status.
Otherwise queries the server for current status.
#### `result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L203" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
result(self) -> TaskResultT
```
Wait for and return the task result.
Must be implemented by subclasses to return the appropriate result type.
#### `wait` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L210" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
wait(self) -> GetTaskResult
```
Wait for task to reach a specific state or complete.
Uses event-based waiting when notifications are available (fast),
with fallback to polling (reliable). Optimally wakes up immediately
on status changes when server sends notifications/tasks/status.
**Args:**
- `state`: Desired state ('working', 'input_required', 'completed', 'failed', 'cancelled').
If None, waits until the task exits the 'working' state (completed, failed, cancelled, input_required, etc.)
- `timeout`: Maximum time to wait in seconds
**Returns:**
- Final task status
**Raises:**
- `TimeoutError`: If desired state not reached within timeout
#### `cancel` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L288" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
cancel(self) -> None
```
Cancel this task, transitioning it to cancelled state.
Sends a tasks/cancel protocol request. The server will attempt to halt
execution and move the task to cancelled state.
Note: If server executed immediately (graceful degradation), this is a no-op
as there's no server-side task to cancel.
### `ToolTask` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L310" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Represents a tool call that may execute in background or immediately.
Provides a uniform API whether the server accepts background execution
or executes synchronously (graceful degradation per SEP-1686).
**Methods:**
#### `result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L355" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
result(self) -> CallToolResult
```
Wait for and return the tool result.
If server executed immediately, returns the immediate result.
Otherwise waits for background task to complete and retrieves result.
**Returns:**
- The parsed tool result (same as call_tool returns)
### `PromptTask` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L429" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Represents a prompt call that may execute in background or immediately.
Provides a uniform API whether the server accepts background execution
or executes synchronously (graceful degradation per SEP-1686).
**Methods:**
#### `result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L460" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
result(self) -> mcp.types.GetPromptResult
```
Wait for and return the prompt result.
If server executed immediately, returns the immediate result.
Otherwise waits for background task to complete and retrieves result.
**Returns:**
- The prompt result with messages and description
### `ResourceTask` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L494" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Represents a resource read that may execute in background or immediately.
Provides a uniform API whether the server accepts background execution
or executes synchronously (graceful degradation per SEP-1686).
**Methods:**
#### `result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/tasks.py#L530" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
result(self) -> list[mcp.types.TextResourceContents | mcp.types.BlobResourceContents]
```
Wait for and return the resource contents.
If server executed immediately, returns the immediate result.
Otherwise waits for background task to complete and retrieves result.
**Returns:**
- list\[ReadResourceContents]: The resource contents

View file

@ -1,23 +0,0 @@
---
title: telemetry
sidebarTitle: telemetry
---
# `fastmcp.client.telemetry`
Client-side telemetry helpers.
## Functions
### `client_span` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/telemetry.py#L13" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
client_span(name: str, method: str, component_key: str, session_id: str | None = None, resource_uri: str | None = None, tool_name: str | None = None, prompt_name: str | None = None) -> Generator[Span, None, None]
```
Create a CLIENT span with standard MCP attributes.
Automatically records any exception on the span and sets error status.

View file

@ -1,8 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.client.transports`
*This module is empty or contains only private/internal implementations.*

View file

@ -1,62 +0,0 @@
---
title: base
sidebarTitle: base
---
# `fastmcp.client.transports.base`
## Classes
### `SessionKwargs` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/base.py#L23" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Keyword arguments for the MCP ClientSession constructor.
### `ClientTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/base.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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.
**Methods:**
#### `connect_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/base.py#L47" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession]
```
Establishes a connection and yields an active ClientSession.
The ClientSession is *not* expected to be initialized in this context manager.
The session is guaranteed to be valid only within the scope of the
async context manager. Connection setup and teardown are handled
within this context.
**Args:**
- `**session_kwargs`: Keyword arguments to pass to the ClientSession
constructor (e.g., callbacks, timeouts).
#### `close` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/base.py#L73" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close(self)
```
Close the transport.
#### `get_session_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/base.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_session_id(self) -> str | None
```
Get the session ID for this transport, if available.

View file

@ -1,72 +0,0 @@
---
title: config
sidebarTitle: config
---
# `fastmcp.client.transports.config`
## Classes
### `MCPConfigTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/config.py#L25" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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, by default, used as its mounting prefix.
In the multiserver 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
# Create a config with multiple servers
config = {
"mcpServers": {
"weather": {
"url": "https://weather-api.example.com/mcp",
"transport": "http"
},
"calendar": {
"url": "https://calendar-api.example.com/mcp",
"transport": "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")
```
**Methods:**
#### `connect_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/config.py#L88" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession]
```
#### `close` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/config.py#L205" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close(self)
```

View file

@ -1,37 +0,0 @@
---
title: http
sidebarTitle: http
---
# `fastmcp.client.transports.http`
Streamable HTTP transport for FastMCP Client.
## Classes
### `StreamableHttpTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/http.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport implementation that connects to an MCP server via Streamable HTTP Requests.
**Methods:**
#### `connect_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/http.py#L150" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession]
```
#### `get_session_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/http.py#L207" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_session_id(self) -> str | None
```
#### `close` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/http.py#L215" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close(self)
```

View file

@ -1,56 +0,0 @@
---
title: inference
sidebarTitle: inference
---
# `fastmcp.client.transports.inference`
## Functions
### `infer_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/inference.py#L61" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```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)
```

View file

@ -1,27 +0,0 @@
---
title: memory
sidebarTitle: memory
---
# `fastmcp.client.transports.memory`
## Classes
### `FastMCPTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/memory.py#L14" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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.
**Methods:**
#### `connect_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/memory.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession]
```

View file

@ -1,25 +0,0 @@
---
title: sse
sidebarTitle: sse
---
# `fastmcp.client.transports.sse`
Server-Sent Events (SSE) transport for FastMCP Client.
## Classes
### `SSETransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/sse.py#L25" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport implementation that connects to an MCP server via Server-Sent Events.
**Methods:**
#### `connect_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/sse.py#L117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession]
```

View file

@ -1,79 +0,0 @@
---
title: stdio
sidebarTitle: stdio
---
# `fastmcp.client.transports.stdio`
## Classes
### `StdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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.
**Methods:**
#### `connect_session` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L72" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect_session(self, **session_kwargs: Unpack[SessionKwargs]) -> AsyncIterator[ClientSession]
```
#### `connect` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L84" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
connect(self, **session_kwargs: Unpack[SessionKwargs]) -> ClientSession | None
```
#### `disconnect` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L127" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
disconnect(self)
```
#### `close` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L162" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close(self)
```
### `PythonStdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L232" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport for running Python scripts.
### `FastMCPStdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L285" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport for running FastMCP servers using the FastMCP CLI.
### `NodeStdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L314" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport for running Node.js scripts.
### `UvStdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L367" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport for running commands via the uv tool.
### `UvxStdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L446" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport for running commands via the uvx tool.
### `NpxStdioTransport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/client/transports/stdio.py#L511" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transport for running commands via the npx tool.

View file

@ -1,6 +1,6 @@
---
title: __init__
sidebarTitle: __init__
title: client
sidebarTitle: client
---
# `fastmcp.client`

View file

@ -10,7 +10,7 @@ Shared decorator utilities for FastMCP.
## Functions
### `resolve_task_config` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/decorators.py#L17" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `resolve_task_config` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/decorators.py#L17" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resolve_task_config(task: bool | TaskConfig | None) -> bool | TaskConfig
@ -20,7 +20,7 @@ resolve_task_config(task: bool | TaskConfig | None) -> bool | TaskConfig
Resolve task config, defaulting None to False.
### `get_fastmcp_meta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/decorators.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `get_fastmcp_meta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/decorators.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_fastmcp_meta(fn: Any) -> Any | None
@ -32,7 +32,7 @@ Extract FastMCP metadata from a function, handling bound methods and wrappers.
## Classes
### `HasFastMCPMeta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/decorators.py#L23" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `HasFastMCPMeta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/decorators.py#L23" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for callables decorated with FastMCP metadata.

View file

@ -10,7 +10,7 @@ Custom exceptions for FastMCP.
## Classes
### `FastMCPDeprecationWarning` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L8" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `FastMCPDeprecationWarning` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L13" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Deprecation warning for FastMCP APIs.
@ -20,61 +20,61 @@ still apply, but FastMCP can selectively enable its own warnings
without affecting other libraries in the process.
### `FastMCPError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L17" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `FastMCPError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base error for FastMCP.
### `ValidationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L25" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ValidationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L30" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in validating parameters or return values.
### `ResourceError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ResourceError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in resource operations.
### `ToolError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ToolError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in tool operations.
### `PromptError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L37" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `PromptError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in prompt operations.
### `InvalidSignature` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `InvalidSignature` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Invalid signature for use with FastMCP.
### `ClientError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L45" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ClientError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L50" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error in client operations.
### `NotFoundError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `NotFoundError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Object not found.
### `DisabledError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L53" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `DisabledError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L58" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Object is disabled.
### `AuthorizationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/exceptions.py#L57" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `AuthorizationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/exceptions.py#L62" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Error when authorization check fails.

View file

@ -7,7 +7,7 @@ sidebarTitle: code_mode
## Classes
### `SandboxProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `SandboxProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Interface for executing LLM-generated Python code in a sandbox.
@ -20,13 +20,13 @@ sandbox — never with plain ``exec()``. Use ``MontySandboxProvider``
**Methods:**
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run(self, code: str) -> Any
```
### `MontySandboxProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `MontySandboxProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Sandbox provider backed by `pydantic-monty`.
@ -41,13 +41,13 @@ leave that limit uncapped.
**Methods:**
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L112" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L112" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run(self, code: str) -> Any
```
### `Search` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L178" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `Search` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L178" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Discovery tool factory that searches the catalog by query.
@ -64,7 +64,7 @@ Defaults to BM25 ranking.
The LLM can override this per call. ``None`` means no limit.
### `GetSchemas` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L260" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `GetSchemas` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L260" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Discovery tool factory that returns schemas for tools by name.
@ -78,7 +78,7 @@ types, and required markers.
``"full"`` returns the complete JSON schema.
### `GetTags` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L321" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `GetTags` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L321" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Discovery tool factory that lists tool tags from the catalog.
@ -93,7 +93,7 @@ without tags appear under ``"untagged"``.
``"full"`` lists all tools under each tag.
### `ListTools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L388" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `ListTools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L388" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Discovery tool factory that lists all tools in the catalog.
@ -106,7 +106,7 @@ Discovery tool factory that lists all tools in the catalog.
``"full"`` returns the complete JSON schema.
### `CodeMode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L437" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `CodeMode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L437" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Transform that collapses all tools into discovery + execute meta-tools.
@ -123,13 +123,13 @@ environment with ``call_tool(name, params)`` in scope.
**Methods:**
#### `transform_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L487" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `transform_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L487" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
transform_tools(self, tools: Sequence[Tool]) -> Sequence[Tool]
```
#### `get_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/experimental/transforms/code_mode.py#L490" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `get_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L490" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_tool(self, name: str, call_next: GetToolNext) -> Tool | None

View file

@ -32,7 +32,7 @@ Example configuration:
## Functions
### `infer_transport_type_from_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L56" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `infer_transport_type_from_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
infer_transport_type_from_url(url: str | AnyUrl) -> Literal['http', 'sse']
@ -42,7 +42,7 @@ infer_transport_type_from_url(url: str | AnyUrl) -> Literal['http', 'sse']
Infer the appropriate transport type from the given URL.
### `update_config_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L345" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `update_config_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L361" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
update_config_file(file_path: Path, server_name: str, server_config: CanonicalMCPServerTypes) -> None
@ -57,7 +57,7 @@ worry about transforming server objects here.
## Classes
### `StdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L155" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `StdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L168" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
MCP server configuration for stdio transport.
@ -67,19 +67,19 @@ This is the canonical configuration format for MCP servers using stdio transport
**Methods:**
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L188" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L201" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_transport(self) -> StdioTransport
```
### `TransformingStdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L200" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `TransformingStdioMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L213" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Stdio server with tool transforms.
### `RemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L204" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `RemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L217" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
MCP server configuration for HTTP/SSE transport.
@ -89,19 +89,19 @@ This is the canonical configuration format for MCP servers using remote transpor
**Methods:**
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L240" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `to_transport` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L253" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_transport(self) -> StreamableHttpTransport | SSETransport
```
### `TransformingRemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L265" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `TransformingRemoteMCPServer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L281" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A Remote server with tool transforms.
### `MCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L276" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `MCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L292" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A configuration object for MCP Servers that conforms to the canonical MCP configuration format
@ -113,7 +113,7 @@ For an MCPConfig that is strictly canonical, see the `CanonicalMCPConfig` class.
**Methods:**
#### `wrap_servers_at_root` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L290" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `wrap_servers_at_root` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L306" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
wrap_servers_at_root(cls, values: dict[str, Any]) -> dict[str, Any]
@ -122,7 +122,7 @@ wrap_servers_at_root(cls, values: dict[str, Any]) -> dict[str, Any]
If there's no mcpServers key but there are server configs at root, wrap them.
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L303" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L319" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_server(self, name: str, server: MCPServerTypes) -> None
@ -131,7 +131,7 @@ add_server(self, name: str, server: MCPServerTypes) -> None
Add or update a server in the configuration.
#### `from_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L308" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `from_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L324" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_dict(cls, config: dict[str, Any]) -> Self
@ -140,7 +140,7 @@ from_dict(cls, config: dict[str, Any]) -> Self
Parse MCP configuration from dictionary format.
#### `to_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L312" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `to_dict` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L328" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_dict(self) -> dict[str, Any]
@ -149,7 +149,7 @@ to_dict(self) -> dict[str, Any]
Convert MCPConfig to dictionary format, preserving all fields.
#### `write_to_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L316" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `write_to_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L332" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
write_to_file(self, file_path: Path) -> None
@ -158,7 +158,7 @@ write_to_file(self, file_path: Path) -> None
Write configuration to JSON file.
#### `from_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L322" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `from_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L338" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_file(cls, file_path: Path) -> Self
@ -167,7 +167,7 @@ from_file(cls, file_path: Path) -> Self
Load configuration from JSON file.
### `CanonicalMCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L330" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
### `CanonicalMCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L346" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Canonical MCP configuration format.
@ -178,7 +178,7 @@ The format is designed to be client-agnostic and extensible for future use cases
**Methods:**
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/mcp_config.py#L340" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
#### `add_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L356" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_server(self, name: str, server: CanonicalMCPServerTypes) -> None

View file

@ -1,145 +0,0 @@
---
title: base
sidebarTitle: base
---
# `fastmcp.prompts.base`
Base classes for FastMCP prompts.
## Classes
### `Message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L44" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Wrapper for prompt message with auto-serialization.
Accepts any content - strings pass through, other types
(dict, list, BaseModel) are JSON-serialized to text.
**Methods:**
#### `to_mcp_prompt_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L99" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_prompt_message(self) -> PromptMessage
```
Convert to MCP PromptMessage.
### `PromptArgument` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
An argument that can be passed to a prompt.
### `PromptResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L116" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Canonical result type for prompt rendering.
Provides explicit control over prompt responses: multiple messages,
roles, and metadata at both the message and result level.
**Methods:**
#### `to_mcp_prompt_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L188" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_prompt_result(self) -> GetPromptResult
```
Convert to MCP GetPromptResult.
### `Prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L198" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A prompt template that can be rendered with parameters.
**Methods:**
#### `to_mcp_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L210" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_prompt(self, **overrides: Any) -> SDKPrompt
```
Convert the prompt to an MCP prompt.
#### `from_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L236" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_function(cls, fn: Callable[..., Any]) -> FunctionPrompt
```
Create a Prompt from a function.
The function can return:
- str: wrapped as single user Message
- list\[Message | str]: converted to list\[Message]
- PromptResult: used directly
#### `render` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L272" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
render(self, arguments: dict[str, Any] | None = None) -> str | list[Message | str] | PromptResult
```
Render the prompt with arguments.
Subclasses must implement this method. Return one of:
- str: Wrapped as single user Message
- list\[Message | str]: Converted to list\[Message]
- PromptResult: Used directly
#### `convert_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L285" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
convert_result(self, raw_value: Any) -> PromptResult
```
Convert a raw return value to PromptResult.
**Raises:**
- `TypeError`: for unsupported types
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L375" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_with_docket(self, docket: Docket) -> None
```
Register this prompt with docket for background execution.
#### `add_to_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L381" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_to_docket(self, docket: Docket, arguments: dict[str, Any] | None, **kwargs: Any) -> Execution
```
Schedule this prompt for background execution via docket.
**Args:**
- `docket`: The Docket instance
- `arguments`: Prompt arguments
- `fn_key`: Function lookup key in Docket registry (defaults to self.key)
- `task_key`: Redis storage key for the result
- `**kwargs`: Additional kwargs passed to docket.add()
#### `get_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/base.py#L404" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_span_attributes(self) -> dict[str, Any]
```

View file

@ -1,103 +0,0 @@
---
title: function_prompt
sidebarTitle: function_prompt
---
# `fastmcp.prompts.function_prompt`
Standalone @prompt decorator for FastMCP.
## Functions
### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L433" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
prompt(name_or_fn: str | Callable[..., Any] | None = None) -> Any
```
Standalone decorator to mark a function as an MCP prompt.
Returns the original function with metadata attached. Register with a server
using mcp.add_prompt().
## Classes
### `DecoratedPrompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for functions decorated with @prompt.
### `PromptMeta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L63" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Metadata attached to functions by the @prompt decorator.
### `FunctionPrompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A prompt that is a function.
**Methods:**
#### `from_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_function(cls, fn: Callable[..., Any]) -> FunctionPrompt
```
Create a Prompt from a function.
**Args:**
- `fn`: The function to wrap
- `metadata`: PromptMeta object with all configuration. If provided,
individual parameters must not be passed.
- `name, title, etc.`: Individual parameters for backwards compatibility.
Cannot be used together with metadata parameter.
The function can return:
- str: wrapped as single user Message
- list\[Message | str]: converted to list\[Message]
- PromptResult: used directly
#### `render` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L318" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
render(self, arguments: dict[str, Any] | None = None) -> PromptResult
```
Render the prompt with arguments.
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L370" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_with_docket(self, docket: Docket) -> None
```
Register this prompt with docket for background execution.
#### `add_to_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/prompts/function_prompt.py#L376" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_to_docket(self, docket: Docket, arguments: dict[str, Any] | None, **kwargs: Any) -> Execution
```
Schedule this prompt for background execution via docket.
FunctionPrompt splats the arguments dict since .fn expects **kwargs.
**Args:**
- `docket`: The Docket instance
- `arguments`: Prompt arguments
- `fn_key`: Function lookup key in Docket registry (defaults to self.key)
- `task_key`: Redis storage key for the result
- `**kwargs`: Additional kwargs passed to docket.add()

View file

@ -1,6 +1,6 @@
---
title: __init__
sidebarTitle: __init__
title: prompts
sidebarTitle: prompts
---
# `fastmcp.prompts`

View file

@ -1,180 +0,0 @@
---
title: base
sidebarTitle: base
---
# `fastmcp.resources.base`
Base classes and interfaces for FastMCP resources.
## Classes
### `ResourceContent` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L39" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Wrapper for resource content with optional MIME type and metadata.
Accepts any value for content - strings and bytes pass through directly,
other types (dict, list, BaseModel, etc.) are automatically JSON-serialized.
**Methods:**
#### `to_mcp_resource_contents` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_resource_contents(self, uri: AnyUrl | str) -> mcp.types.TextResourceContents | mcp.types.BlobResourceContents
```
Convert to MCP resource contents type.
**Args:**
- `uri`: The URI of the resource (required by MCP types)
**Returns:**
- TextResourceContents for str content, BlobResourceContents for bytes
### `ResourceResult` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L121" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Canonical result type for resource reads.
Provides explicit control over resource responses: multiple content items,
per-item MIME types, and metadata at both the item and result level.
**Methods:**
#### `to_mcp_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L202" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_result(self, uri: AnyUrl | str) -> mcp.types.ReadResourceResult
```
Convert to MCP ReadResourceResult.
**Args:**
- `uri`: The URI of the resource (required by MCP types)
**Returns:**
- MCP ReadResourceResult with converted contents
### `Resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L218" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base class for all resources.
**Methods:**
#### `from_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L243" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_function(cls, fn: Callable[..., Any], uri: str | AnyUrl) -> FunctionResource
```
#### `set_default_mime_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L282" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_default_mime_type(cls, mime_type: str | None) -> str
```
Set default MIME type if not provided.
#### `set_default_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_default_name(self) -> Self
```
Set default name from URI if not provided.
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L299" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> str | bytes | ResourceResult
```
Read the resource content.
Subclasses implement this to return resource data. Supported return types:
- str: Text content
- bytes: Binary content
- ResourceResult: Full control over contents and result-level meta
#### `convert_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L311" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
convert_result(self, raw_value: Any) -> ResourceResult
```
Convert a raw result to ResourceResult.
This is used in two contexts:
1. In _read() to convert user function return values to ResourceResult
2. In tasks_result_handler() to convert Docket task results to ResourceResult
Handles ResourceResult passthrough and converts raw values using
ResourceResult's normalization. When the raw value is a plain
string or bytes, the resource's own ``mime_type`` is forwarded so
that ``ui://`` resources (and others with non-default MIME types)
don't fall back to ``text/plain``.
The resource's component-level ``meta`` (e.g. ``ui`` metadata for
MCP Apps CSP/permissions) is propagated to each content item so
that hosts can read it from the ``resources/read`` response.
#### `to_mcp_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L405" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_resource(self, **overrides: Any) -> SDKResource
```
Convert the resource to an SDKResource.
#### `key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L428" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
key(self) -> str
```
The globally unique lookup key for this resource.
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L433" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_with_docket(self, docket: Docket) -> None
```
Register this resource with docket for background execution.
#### `add_to_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L439" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_to_docket(self, docket: Docket, **kwargs: Any) -> Execution
```
Schedule this resource for background execution via docket.
**Args:**
- `docket`: The Docket instance
- `fn_key`: Function lookup key in Docket registry (defaults to self.key)
- `task_key`: Redis storage key for the result
- `**kwargs`: Additional kwargs passed to docket.add()
#### `get_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/base.py#L460" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_span_attributes(self) -> dict[str, Any]
```

View file

@ -1,90 +0,0 @@
---
title: function_resource
sidebarTitle: function_resource
---
# `fastmcp.resources.function_resource`
Standalone @resource decorator for FastMCP.
## Functions
### `resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L239" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
resource(uri: str) -> Callable[[F], F]
```
Standalone decorator to mark a function as an MCP resource.
Returns the original function with metadata attached. Register with a server
using mcp.add_resource().
## Classes
### `DecoratedResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Protocol for functions decorated with @resource.
### `ResourceMeta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L50" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Metadata attached to functions by the @resource decorator.
### `FunctionResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L69" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
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` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_function(cls, fn: Callable[..., Any], uri: str | AnyUrl | None = None) -> FunctionResource
```
Create a FunctionResource from a function.
**Args:**
- `fn`: The function to wrap
- `uri`: The URI for the resource (required if metadata not provided)
- `metadata`: ResourceMeta object with all configuration. If provided,
individual parameters must not be passed.
- `name, title, etc.`: Individual parameters for backwards compatibility.
Cannot be used together with metadata parameter.
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L211" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> str | bytes | ResourceResult
```
Read the resource by calling the wrapped function.
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/function_resource.py#L232" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_with_docket(self, docket: Docket) -> None
```
Register this resource with docket for background execution.

View file

@ -1,261 +0,0 @@
---
title: template
sidebarTitle: template
---
# `fastmcp.resources.template`
Resource template functionality.
## Functions
### `extract_query_params` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L39" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
extract_query_params(uri_template: str) -> set[str]
```
Extract query parameter names from RFC 6570 `{?param1,param2}` syntax.
### `build_regex` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L47" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
build_regex(template: str) -> re.Pattern[str] | None
```
Build regex pattern for URI template, handling RFC 6570 syntax.
Supports:
- `{var}` - simple path parameter
- `{var*}` - wildcard path parameter (captures multiple segments)
- `{?var1,var2}` - query parameters (ignored in path matching)
Hyphens in parameter names are normalized to underscores in regex group
names so that matched groups are valid Python identifiers.
Returns None if the template produces an invalid regex (e.g. parameter
names with leading digits or duplicates from a remote server).
### `match_uri_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L84" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
match_uri_template(uri: str, uri_template: str) -> dict[str, str] | None
```
Match URI against template and extract both path and query parameters.
Supports RFC 6570 URI templates:
- Path params: `{var}`, `{var*}`
- Query params: `{?var1,var2}`
### `expand_uri_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L123" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
expand_uri_template(uri_template: str, params: dict[str, Any]) -> str
```
Expand a URI template with parameters — inverse of `match_uri_template`.
Supports the same RFC 6570 subset:
- Path params: `{var}`, `{var*}`
- Query params: `{?var1,var2}`
## Classes
### `ResourceTemplate` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L163" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A template for dynamically creating resources.
**Methods:**
#### `from_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L190" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_function(fn: Callable[..., Any], uri_template: str, name: str | None = None, version: str | int | None = None, title: str | None = None, description: str | None = None, icons: list[Icon] | None = None, mime_type: str | None = None, tags: set[str] | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None, task: bool | TaskConfig | None = None, auth: AuthCheck | list[AuthCheck] | None = None) -> FunctionResourceTemplate
```
#### `set_default_mime_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L223" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_default_mime_type(cls, mime_type: str | None) -> str
```
Set default MIME type if not provided.
#### `matches` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L229" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
matches(self, uri: str) -> dict[str, Any] | None
```
Check if URI matches template and extract parameters.
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L233" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult
```
Read the resource content.
#### `convert_result` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L239" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
convert_result(self, raw_value: Any) -> ResourceResult
```
Convert a raw result to ResourceResult.
This is used in two contexts:
1. In _read() to convert user function return values to ResourceResult
2. In tasks_result_handler() to convert Docket task results to ResourceResult
Handles ResourceResult passthrough and converts raw values using
ResourceResult's normalization.
#### `create_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L303" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_resource(self, uri: str, params: dict[str, Any]) -> Resource
```
Create a resource from the template with the given parameters.
The base implementation does not support background tasks.
Use FunctionResourceTemplate for task support.
#### `to_mcp_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L314" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
to_mcp_template(self, **overrides: Any) -> SDKResourceTemplate
```
Convert the resource template to an SDKResourceTemplate.
#### `from_mcp_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L334" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_mcp_template(cls, mcp_template: SDKResourceTemplate) -> ResourceTemplate
```
Creates a FastMCP ResourceTemplate from a raw MCP ResourceTemplate object.
#### `key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L347" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
key(self) -> str
```
The globally unique lookup key for this template.
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L352" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_with_docket(self, docket: Docket) -> None
```
Register this template with docket for background execution.
#### `add_to_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L358" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_to_docket(self, docket: Docket, params: dict[str, Any], **kwargs: Any) -> Execution
```
Schedule this template for background execution via docket.
**Args:**
- `docket`: The Docket instance
- `params`: Template parameters
- `fn_key`: Function lookup key in Docket registry (defaults to self.key)
- `task_key`: Redis storage key for the result
- `**kwargs`: Additional kwargs passed to docket.add()
#### `get_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L381" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_span_attributes(self) -> dict[str, Any]
```
### `FunctionResourceTemplate` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L388" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A template for dynamically creating resources.
**Methods:**
#### `create_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L434" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_resource(self, uri: str, params: dict[str, Any]) -> Resource
```
Create a resource from the template with the given parameters.
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L453" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self, arguments: dict[str, Any]) -> str | bytes | ResourceResult
```
Read the resource content.
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L492" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_with_docket(self, docket: Docket) -> None
```
Register this template with docket for background execution.
#### `add_to_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L498" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
add_to_docket(self, docket: Docket, params: dict[str, Any], **kwargs: Any) -> Execution
```
Schedule this template for background execution via docket.
FunctionResourceTemplate splats the params dict since .fn expects **kwargs.
**Args:**
- `docket`: The Docket instance
- `params`: Template parameters
- `fn_key`: Function lookup key in Docket registry (defaults to self.key)
- `task_key`: Redis storage key for the result
- `**kwargs`: Additional kwargs passed to docket.add()
#### `from_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/template.py#L524" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_function(cls, fn: Callable[..., Any], uri_template: str, name: str | None = None, version: str | int | None = None, title: str | None = None, description: str | None = None, icons: list[Icon] | None = None, mime_type: str | None = None, tags: set[str] | None = None, annotations: Annotations | None = None, meta: dict[str, Any] | None = None, task: bool | TaskConfig | None = None, auth: AuthCheck | list[AuthCheck] | None = None) -> FunctionResourceTemplate
```
Create a template from a function.

View file

@ -1,134 +0,0 @@
---
title: types
sidebarTitle: types
---
# `fastmcp.resources.types`
Concrete resource implementations.
## Classes
### `TextResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L21" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A resource that reads from a string.
**Methods:**
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L26" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> ResourceResult
```
Read the text content.
### `BinaryResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L37" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A resource that reads from bytes.
**Methods:**
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> ResourceResult
```
Read the binary content.
### `FileResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L53" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A resource that reads from a file.
Set is_binary=True to read file as binary data instead of text.
**Methods:**
#### `validate_absolute_path` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L83" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_absolute_path(cls, path: Path) -> Path
```
Ensure path is absolute.
#### `set_binary_from_mime_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L91" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_binary_from_mime_type(cls, is_binary: bool, info: ValidationInfo) -> bool
```
Set is_binary based on mime_type if not explicitly set.
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L99" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> ResourceResult
```
Read the file content.
### `HttpResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L113" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A resource that reads from an HTTP endpoint.
**Methods:**
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L122" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> ResourceResult
```
Read the HTTP content.
### `DirectoryResource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L134" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
A resource that lists files in a directory.
**Methods:**
#### `validate_absolute_path` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L154" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_absolute_path(cls, path: Path) -> Path
```
Ensure path is absolute.
#### `list_files` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L160" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
list_files(self) -> list[Path]
```
List files in the directory.
#### `read` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/resources/types.py#L176" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
read(self) -> ResourceResult
```
Read the directory listing.

View file

@ -1,6 +1,6 @@
---
title: __init__
sidebarTitle: __init__
title: resources
sidebarTitle: resources
---
# `fastmcp.resources`

View file

@ -1,13 +0,0 @@
---
title: app
sidebarTitle: app
---
# `fastmcp.server.app`
Backward-compatible re-exports from fastmcp.apps.app.
.. deprecated:: 3.2.0
Import from ``fastmcp.apps.app`` or ``fastmcp`` instead.

View file

@ -1,13 +0,0 @@
---
title: apps
sidebarTitle: apps
---
# `fastmcp.server.apps`
Backward-compatible re-exports from fastmcp.apps.
.. deprecated:: 3.2.0
Import from ``fastmcp.apps`` instead.

View file

@ -1,8 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.server.auth`
*This module is empty or contains only private/internal implementations.*

View file

@ -1,382 +0,0 @@
---
title: auth
sidebarTitle: auth
---
# `fastmcp.server.auth.auth`
## Classes
### `AccessToken` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
AccessToken that includes all JWT claims.
### `TokenHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L60" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
TokenHandler that returns MCP-compliant error responses.
This handler addresses two SDK issues:
1. Error code: The SDK returns `unauthorized_client` for client authentication
failures, but RFC 6749 Section 5.2 requires `invalid_client` with HTTP 401.
This distinction matters for client re-registration behavior.
2. Status code: The SDK returns HTTP 400 for all token errors including
`invalid_grant` (expired/invalid tokens). However, the MCP spec requires:
"Invalid or expired tokens MUST receive a HTTP 401 response."
This handler transforms responses to be compliant with both OAuth 2.1 and MCP specs.
**Methods:**
#### `handle` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
handle(self, request: Any)
```
Wrap SDK handle() and transform auth error responses.
### `PrivateKeyJWTClientAuthenticator` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L126" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Client authenticator with private_key_jwt support for CIMD clients.
Extends the SDK's ClientAuthenticator to add support for the `private_key_jwt`
authentication method per RFC 7523. This is required for CIMD (Client ID Metadata
Document) clients that use asymmetric keys for authentication.
The authenticator:
1. Delegates to SDK for standard methods (client_secret_basic, client_secret_post, none)
2. Adds private_key_jwt handling for CIMD clients
3. Validates JWT assertions against client's JWKS
**Methods:**
#### `authenticate_request` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L156" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
authenticate_request(self, request: Request) -> OAuthClientInformationFull
```
Authenticate a client from an HTTP request.
Extends SDK authentication to support private_key_jwt for CIMD clients.
Delegates to SDK for client_secret_basic (Authorization header) and
client_secret_post (form body) authentication.
### `AuthProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L207" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base class for all FastMCP authentication providers.
This class provides a unified interface for all authentication providers,
whether they are simple token verifiers or full OAuth authorization servers.
All providers must be able to verify tokens and can optionally provide
custom authentication routes.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L247" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a bearer token and return access info if valid.
All auth providers must implement token verification.
**Args:**
- `token`: The token string to validate
**Returns:**
- AccessToken object if valid, None if invalid or expired
#### `set_mcp_path` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L260" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_mcp_path(self, mcp_path: str | None) -> None
```
Set the MCP endpoint path and compute resource URL.
This method is called by get_routes() to configure the expected
resource URL before route creation. Subclasses can override to
perform additional initialization that depends on knowing the
MCP endpoint path.
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
#### `get_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L274" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get all routes for this authentication provider.
This includes both well-known discovery routes and operational routes.
Each provider is responsible for creating whatever routes it needs:
- TokenVerifier: typically no routes (default implementation)
- RemoteAuthProvider: protected resource metadata routes
- OAuthProvider: full OAuth authorization server routes
- Custom providers: whatever routes they need
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
This is used to advertise the resource URL in metadata, but the
provider does not create the actual MCP endpoint route.
**Returns:**
- List of all routes for this provider (excluding the MCP endpoint itself)
#### `get_well_known_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L297" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_well_known_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get well-known discovery routes for this authentication provider.
This is a utility method that filters get_routes() to return only
well-known discovery routes (those starting with /.well-known/).
Well-known routes provide OAuth metadata and discovery endpoints that
clients use to discover authentication capabilities. These routes should
be mounted at the root level of the application to comply with RFC 8414
and RFC 9728.
Common well-known routes:
- /.well-known/oauth-authorization-server (authorization server metadata)
- /.well-known/oauth-protected-resource/* (protected resource metadata)
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
This is used to construct path-scoped well-known URLs.
**Returns:**
- List of well-known discovery routes (typically mounted at root level)
#### `get_middleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L329" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_middleware(self) -> list
```
Get HTTP application-level middleware for this auth provider.
**Returns:**
- List of Starlette Middleware instances to apply to the HTTP app
### `TokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L366" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Base class for token verifiers (Resource Servers).
This class provides token verification capability without OAuth server functionality.
Token verifiers typically don't provide authentication routes by default.
**Methods:**
#### `scopes_supported` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L398" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
scopes_supported(self) -> list[str]
```
Scopes to advertise in OAuth metadata.
Defaults to required_scopes. Override in subclasses when the
advertised scopes differ from the validation scopes (e.g., Azure AD
where tokens contain short-form scopes but clients request full URI
scopes).
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L408" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a bearer token and return access info if valid.
### `RemoteAuthProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L413" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Authentication provider for resource servers that verify tokens from known authorization servers.
This provider composes a TokenVerifier with authorization server metadata to create
standardized OAuth 2.0 Protected Resource endpoints (RFC 9728). Perfect for:
- JWT verification with known issuers
- Remote token introspection services
- Any resource server that knows where its tokens come from
Use this when you have token verification logic and want to advertise
the authorization servers that issue valid tokens.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L468" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify token using the configured token verifier.
#### `get_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L472" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get routes for this provider.
Creates protected resource metadata routes (RFC 9728).
### `MultiAuth` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L510" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Composes an optional auth server with additional token verifiers.
Use this when a single server needs to accept tokens from multiple sources.
For example, an OAuth proxy for interactive clients combined with a JWT
verifier for machine-to-machine tokens.
Token verification tries the server first (if present), then each verifier
in order, returning the first successful result. Routes and OAuth metadata
come from the server; verifiers contribute only token verification.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L591" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a token by trying the server, then each verifier in order.
Each source is tried independently. If a source raises an exception,
it is logged and treated as a non-match so that remaining sources
still get a chance to verify the token.
#### `set_mcp_path` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L612" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_mcp_path(self, mcp_path: str | None) -> None
```
Propagate MCP path to the server and all verifiers.
#### `get_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L620" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_routes(self, mcp_path: str | None = None) -> list[Route]
```
Delegate route creation to the server.
#### `get_well_known_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L626" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_well_known_routes(self, mcp_path: str | None = None) -> list[Route]
```
Delegate well-known route creation to the server.
This ensures that server-specific well-known route logic (e.g.,
OAuthProvider's RFC 8414 path-aware discovery) is preserved.
### `OAuthProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L637" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OAuth Authorization Server provider.
This class provides full OAuth server functionality including client registration,
authorization flows, token issuance, and token verification.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L708" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a bearer token and return access info if valid.
This method implements the TokenVerifier protocol by delegating
to our existing load_access_token method.
**Args:**
- `token`: The token string to validate
**Returns:**
- AccessToken object if valid, None if invalid or expired
#### `get_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L723" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get OAuth authorization server routes and optional protected resource routes.
This method creates the full set of OAuth routes including:
- Standard OAuth authorization server routes (/.well-known/oauth-authorization-server, /authorize, /token, etc.)
- Optional protected resource routes
**Returns:**
- List of OAuth routes
#### `get_well_known_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/auth.py#L802" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_well_known_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get well-known discovery routes with RFC 8414 path-aware support.
Overrides the base implementation to support path-aware authorization
server metadata discovery per RFC 8414. If issuer_url has a path component,
the authorization server metadata route is adjusted to include that path.
For example, if issuer_url is "http://example.com/api", the discovery
endpoint will be at "/.well-known/oauth-authorization-server/api" instead
of just "/.well-known/oauth-authorization-server".
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
**Returns:**
- List of well-known discovery routes

View file

@ -1,129 +0,0 @@
---
title: authorization
sidebarTitle: authorization
---
# `fastmcp.server.auth.authorization`
Authorization checks for FastMCP components.
This module provides callable-based authorization for tools, resources, and prompts.
Auth checks are functions that receive an AuthContext and return True to allow access
or False to deny.
Auth checks can also raise exceptions:
- AuthorizationError: Propagates with the custom message for explicit denial
- Other exceptions: Masked for security (logged, treated as auth failure)
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth import require_scopes
mcp = FastMCP()
@mcp.tool(auth=require_scopes("write"))
def protected_tool(): ...
@mcp.resource("data://secret", auth=require_scopes("read"))
def secret_data(): ...
@mcp.prompt(auth=require_scopes("admin"))
def admin_prompt(): ...
```
## Functions
### `require_scopes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/authorization.py#L78" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
require_scopes(*scopes: str) -> AuthCheck
```
Require specific OAuth scopes.
Returns an auth check that requires ALL specified scopes to be present
in the token (AND logic).
**Args:**
- `*scopes`: One or more scope strings that must all be present.
### `restrict_tag` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/authorization.py#L106" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
restrict_tag(tag: str) -> AuthCheck
```
Restrict components with a specific tag to require certain scopes.
If the component has the specified tag, the token must have ALL the
required scopes. If the component doesn't have the tag, access is allowed.
**Args:**
- `tag`: The tag that triggers the scope requirement.
- `scopes`: List of scopes required when the tag is present.
### `run_auth_checks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/authorization.py#L134" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
run_auth_checks(checks: AuthCheck | list[AuthCheck], ctx: AuthContext) -> bool
```
Run auth checks with AND logic.
All checks must pass for authorization to succeed. Checks can be
synchronous or asynchronous functions.
Auth checks can:
- Return True to allow access
- Return False to deny access
- Raise AuthorizationError to deny with a custom message (propagates)
- Raise other exceptions (masked for security, treated as denial)
**Args:**
- `checks`: A single check function or list of check functions.
Each check can be sync (returns bool) or async (returns Awaitable[bool]).
- `ctx`: The auth context to pass to each check.
**Returns:**
- True if all checks pass, False if any check fails.
**Raises:**
- `AuthorizationError`: If an auth check explicitly raises it.
## Classes
### `AuthContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/authorization.py#L48" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Context passed to auth check callables.
This object is passed to each auth check function and provides
access to the current authentication token and the component being accessed.
**Attributes:**
- `token`: The current access token, or None if unauthenticated.
- `component`: The component (tool, resource, or prompt) being accessed.
- `tool`: Backwards-compatible alias for component when it's a Tool.
**Methods:**
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/authorization.py#L64" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
tool(self) -> Tool | None
```
Backwards-compatible access to the component as a Tool.
Returns the component if it's a Tool, None otherwise.

View file

@ -1,245 +0,0 @@
---
title: cimd
sidebarTitle: cimd
---
# `fastmcp.server.auth.cimd`
CIMD (Client ID Metadata Document) support for FastMCP.
.. warning::
**Beta Feature**: CIMD support is currently in beta. The API may change
in future releases. Please report any issues you encounter.
CIMD is a simpler alternative to Dynamic Client Registration where clients
host a static JSON document at an HTTPS URL, and that URL becomes their
client_id. See the IETF draft: draft-parecki-oauth-client-id-metadata-document
This module provides:
- CIMDDocument: Pydantic model for CIMD document validation
- CIMDFetcher: Fetch and validate CIMD documents with SSRF protection
- CIMDClientManager: Manages CIMD client operations
## Classes
### `CIMDDocument` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L45" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
CIMD document per draft-parecki-oauth-client-id-metadata-document.
The client metadata document is a JSON document containing OAuth client
metadata. The client_id property MUST match the URL where this document
is hosted.
Key constraint: token_endpoint_auth_method MUST NOT use shared secrets
(client_secret_post, client_secret_basic, client_secret_jwt).
redirect_uris is required and must contain at least one entry.
**Methods:**
#### `validate_auth_method` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_auth_method(cls, v: str) -> str
```
Ensure no shared-secret auth methods are used.
#### `validate_redirect_uris` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L137" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_redirect_uris(cls, v: list[str]) -> list[str]
```
Ensure redirect_uris is non-empty and each entry is a valid URI.
### `CIMDValidationError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L154" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Raised when CIMD document validation fails.
### `CIMDFetchError` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L158" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Raised when CIMD document fetching fails.
### `CIMDFetcher` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L186" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Fetch and validate CIMD documents with SSRF protection.
Delegates HTTP fetching to ssrf_safe_fetch_response, which provides DNS
pinning, IP validation, size limits, and timeout enforcement. Documents are
cached using HTTP caching semantics (Cache-Control/ETag/Last-Modified), with
a TTL fallback when response headers do not define caching behavior.
**Methods:**
#### `is_cimd_client_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L270" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_cimd_client_id(self, client_id: str) -> bool
```
Check if a client_id looks like a CIMD URL.
CIMD URLs must be HTTPS with a host and non-root path.
#### `fetch` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L287" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
fetch(self, client_id_url: str) -> CIMDDocument
```
Fetch and validate a CIMD document with SSRF protection.
Uses ssrf_safe_fetch_response for the HTTP layer, which provides:
- HTTPS only, DNS resolution with IP validation
- DNS pinning (connects to validated IP directly)
- Blocks private/loopback/link-local/multicast IPs
- Response size limit and timeout enforcement
- Redirects disabled
**Args:**
- `client_id_url`: The URL to fetch (also the expected client_id)
**Returns:**
- Validated CIMDDocument
**Raises:**
- `CIMDValidationError`: If document is invalid or URL blocked
- `CIMDFetchError`: If document cannot be fetched
#### `validate_redirect_uri` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L422" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_redirect_uri(self, doc: CIMDDocument, redirect_uri: str) -> bool
```
Validate that a redirect_uri is allowed by the CIMD document.
Uses component-level matching (scheme, host, port, path) which correctly
handles RFC 8252 §7.3 loopback port flexibility and wildcard patterns.
**Args:**
- `doc`: The CIMD document
- `redirect_uri`: The redirect URI to validate
**Returns:**
- True if valid, False otherwise
### `CIMDAssertionValidator` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L450" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Validates JWT assertions for private_key_jwt CIMD clients.
Implements RFC 7523 (JSON Web Token (JWT) Profile for OAuth 2.0 Client
Authentication and Authorization Grants) for CIMD client authentication.
JTI replay protection uses TTL-based caching to ensure proper security:
- JTIs are cached with expiration matching the JWT's exp claim
- Expired JTIs are automatically cleaned up
- Maximum assertion lifetime is enforced (5 minutes)
**Methods:**
#### `validate_assertion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L493" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_assertion(self, assertion: str, client_id: str, token_endpoint: str, cimd_doc: CIMDDocument) -> bool
```
Validate JWT assertion from client.
**Args:**
- `assertion`: The JWT assertion string
- `client_id`: Expected client_id (must match iss and sub claims)
- `token_endpoint`: Token endpoint URL (must match aud claim)
- `cimd_doc`: CIMD document containing JWKS for key verification
**Returns:**
- True if valid
**Raises:**
- `ValueError`: If validation fails
### `CIMDClientManager` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L675" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Manages all CIMD client operations for OAuth proxy.
This class encapsulates:
- CIMD client detection
- Document fetching and validation
- Synthetic OAuth client creation
- Private key JWT assertion validation
This allows the OAuth proxy to delegate all CIMD-specific logic to a
single, focused manager class.
**Methods:**
#### `is_cimd_client_id` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L709" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
is_cimd_client_id(self, client_id: str) -> bool
```
Check if client_id is a CIMD URL.
**Args:**
- `client_id`: Client ID to check
**Returns:**
- True if client_id is an HTTPS URL (CIMD format)
#### `get_client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L720" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_client(self, client_id_url: str)
```
Fetch CIMD document and create synthetic OAuth client.
**Args:**
- `client_id_url`: HTTPS URL pointing to CIMD document
**Returns:**
- OAuthProxyClient with CIMD document attached, or None if fetch fails
#### `validate_private_key_jwt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/cimd.py#L769" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_private_key_jwt(self, assertion: str, client, token_endpoint: str) -> bool
```
Validate JWT assertion for private_key_jwt auth.
**Args:**
- `assertion`: JWT assertion string from client
- `client`: OAuth proxy client (must have cimd_document)
- `token_endpoint`: Token endpoint URL for aud validation
**Returns:**
- True if assertion is valid
**Raises:**
- `ValueError`: If client doesn't have CIMD document or validation fails

View file

@ -1,8 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.server.auth.handlers`
*This module is empty or contains only private/internal implementations.*

View file

@ -1,83 +0,0 @@
---
title: authorize
sidebarTitle: authorize
---
# `fastmcp.server.auth.handlers.authorize`
Enhanced authorization handler with improved error responses.
This module provides an enhanced authorization handler that wraps the MCP SDK's
AuthorizationHandler to provide better error messages when clients attempt to
authorize with unregistered client IDs.
The enhancement adds:
- Content negotiation: HTML for browsers, JSON for API clients
- Enhanced JSON responses with registration endpoint hints
- Styled HTML error pages with registration links/forms
- Link headers pointing to registration endpoints
## Functions
### `create_unregistered_client_html` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/handlers/authorize.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_unregistered_client_html(client_id: str, registration_endpoint: str, discovery_endpoint: str, server_name: str | None = None, server_icon_url: str | None = None, title: str = 'Client Not Registered') -> str
```
Create styled HTML error page for unregistered client attempts.
**Args:**
- `client_id`: The unregistered client ID that was provided
- `registration_endpoint`: URL of the registration endpoint
- `discovery_endpoint`: URL of the OAuth metadata discovery endpoint
- `server_name`: Optional server name for branding
- `server_icon_url`: Optional server icon URL
- `title`: Page title
**Returns:**
- HTML string for the error page
## Classes
### `AuthorizationHandler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/handlers/authorize.py#L161" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Authorization handler with enhanced error responses for unregistered clients.
This handler extends the MCP SDK's AuthorizationHandler to provide better UX
when clients attempt to authorize without being registered. It implements
content negotiation to return:
- HTML error pages for browser requests
- Enhanced JSON with registration hints for API clients
- Link headers pointing to registration endpoints
This maintains OAuth 2.1 compliance (returns 400 for invalid client_id)
while providing actionable guidance to fix the error.
**Methods:**
#### `handle` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/handlers/authorize.py#L196" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
handle(self, request: Request) -> Response
```
Handle authorization request with enhanced error responses.
This method extends the SDK's authorization handler and intercepts
errors for unregistered clients to provide better error responses
based on the client's Accept header.
**Args:**
- `request`: The authorization request
**Returns:**
- Response (redirect on success, error response on failure)

View file

@ -1,108 +0,0 @@
---
title: jwt_issuer
sidebarTitle: jwt_issuer
---
# `fastmcp.server.auth.jwt_issuer`
JWT token issuance and verification for FastMCP OAuth Proxy.
This module implements the token factory pattern for OAuth proxies, where the proxy
issues its own JWT tokens to clients instead of forwarding upstream provider tokens.
This maintains proper OAuth 2.0 token audience boundaries.
## Functions
### `derive_jwt_key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/jwt_issuer.py#L39" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
derive_jwt_key() -> bytes
```
Derive JWT signing key from a high-entropy or low-entropy key material and server salt.
## Classes
### `JWTIssuer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/jwt_issuer.py#L79" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Issues and validates FastMCP-signed JWT tokens using HS256.
This issuer creates JWT tokens for MCP clients with proper audience claims,
maintaining OAuth 2.0 token boundaries. Tokens are signed with HS256 using
a key derived from the upstream client secret.
**Methods:**
#### `issue_access_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/jwt_issuer.py#L105" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
issue_access_token(self, client_id: str, scopes: list[str], jti: str, expires_in: int = 3600, upstream_claims: dict[str, Any] | None = None) -> str
```
Issue a minimal FastMCP access token.
FastMCP tokens are reference tokens containing only the minimal claims
needed for validation and lookup. The JTI maps to the upstream token
which contains actual user identity and authorization data.
**Args:**
- `client_id`: MCP client ID
- `scopes`: Token scopes
- `jti`: Unique token identifier (maps to upstream token)
- `expires_in`: Token lifetime in seconds
- `upstream_claims`: Optional claims from upstream IdP token to include
**Returns:**
- Signed JWT token
#### `issue_refresh_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/jwt_issuer.py#L157" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
issue_refresh_token(self, client_id: str, scopes: list[str], jti: str, expires_in: int, upstream_claims: dict[str, Any] | None = None) -> str
```
Issue a minimal FastMCP refresh token.
FastMCP refresh tokens are reference tokens containing only the minimal
claims needed for validation and lookup. The JTI maps to the upstream
token which contains actual user identity and authorization data.
**Args:**
- `client_id`: MCP client ID
- `scopes`: Token scopes
- `jti`: Unique token identifier (maps to upstream token)
- `expires_in`: Token lifetime in seconds (should match upstream refresh expiry)
- `upstream_claims`: Optional claims from upstream IdP token to include
**Returns:**
- Signed JWT token
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/jwt_issuer.py#L210" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str, expected_token_use: str = 'access') -> dict[str, Any]
```
Verify and decode a FastMCP token.
Validates JWT signature, expiration, issuer, audience, and token type.
**Args:**
- `token`: JWT token to verify
- `expected_token_use`: Expected token type ("access" or "refresh").
Defaults to "access", which rejects refresh tokens.
**Returns:**
- Decoded token payload
**Raises:**
- `JoseError`: If token is invalid, expired, or has wrong claims

View file

@ -1,26 +0,0 @@
---
title: middleware
sidebarTitle: middleware
---
# `fastmcp.server.auth.middleware`
Enhanced authentication middleware with better error messages.
This module provides enhanced versions of MCP SDK authentication middleware
that return more helpful error messages for developers troubleshooting
authentication issues.
## Classes
### `RequireAuthMiddleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/middleware.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Enhanced authentication middleware with detailed error messages.
Extends the SDK's RequireAuthMiddleware to provide more actionable
error messages when authentication fails. This helps developers
understand what went wrong and how to fix it.

View file

@ -1,16 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.server.auth.oauth_proxy`
OAuth Proxy Provider for FastMCP.
This package provides OAuth proxy functionality split across multiple modules:
- models: Pydantic models and constants
- ui: HTML generation functions
- consent: Consent management mixin
- proxy: Main OAuthProxy class

View file

@ -1,28 +0,0 @@
---
title: consent
sidebarTitle: consent
---
# `fastmcp.server.auth.oauth_proxy.consent`
OAuth Proxy Consent Management.
This module contains consent management functionality for the OAuth proxy.
The ConsentMixin class provides methods for handling user consent flows,
cookie management, and consent page rendering.
## Classes
### `ConsentMixin` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/consent.py#L39" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Mixin class providing consent management functionality for OAuthProxy.
This mixin contains all methods related to:
- Cookie signing and verification
- Consent page rendering
- Consent approval/denial handling
- URI normalization for consent tracking

View file

@ -1,105 +0,0 @@
---
title: models
sidebarTitle: models
---
# `fastmcp.server.auth.oauth_proxy.models`
OAuth Proxy Models and Constants.
This module contains all Pydantic models and constants used by the OAuth proxy.
## Classes
### `OAuthTransaction` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OAuth transaction state for consent flow.
Stored server-side to track active authorization flows with client context.
Includes CSRF tokens for consent protection per MCP security best practices.
### `ClientCode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L63" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Client authorization code with PKCE and upstream tokens.
Stored server-side after upstream IdP callback. Contains the upstream
tokens bound to the client's PKCE challenge for secure token exchange.
### `UpstreamTokenSet` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L81" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Stored upstream OAuth tokens from identity provider.
These tokens are obtained from the upstream provider (Google, GitHub, etc.)
and stored in plaintext within this model. Encryption is handled transparently
at the storage layer via FernetEncryptionWrapper. Tokens are never exposed to MCP clients.
### `JTIMapping` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L103" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Maps FastMCP token JTI to upstream token ID.
This allows stateless JWT validation while still being able to look up
the corresponding upstream token when tools need to access upstream APIs.
### `RefreshTokenMetadata` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L115" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Metadata for a refresh token, stored keyed by token hash.
We store only metadata (not the token itself) for security - if storage
is compromised, attackers get hashes they can't reverse into usable tokens.
### `ProxyDCRClient` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L137" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Client for DCR proxy with configurable redirect URI validation.
This special client class is critical for the OAuth proxy to work correctly
with Dynamic Client Registration (DCR). Here's why it exists:
Problem:
--------
When MCP clients use OAuth, they dynamically register with random localhost
ports (e.g., http://localhost:55454/callback). The OAuth proxy needs to:
1. Accept these dynamic redirect URIs from clients based on configured patterns
2. Use its own fixed redirect URI with the upstream provider (Google, GitHub, etc.)
3. Forward the authorization code back to the client's dynamic URI
Solution:
---------
This class validates redirect URIs against configurable patterns,
while the proxy internally uses its own fixed redirect URI with the upstream
provider. This allows the flow to work even when clients reconnect with
different ports or when tokens are cached.
Without proper validation, clients could get "Redirect URI not registered" errors
when trying to authenticate with cached tokens, or security vulnerabilities could
arise from accepting arbitrary redirect URIs.
**Methods:**
#### `validate_redirect_uri` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/models.py#L168" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
validate_redirect_uri(self, redirect_uri: AnyUrl | None) -> AnyUrl
```
Validate redirect URI against proxy patterns and optionally CIMD redirect_uris.
For CIMD clients: validates against BOTH the CIMD document's redirect_uris
AND the proxy's allowed patterns (if configured). Both must pass.
For DCR clients: validates against proxy patterns first, falling back to
base validation (registered redirect_uris) if patterns don't match.

View file

@ -1,326 +0,0 @@
---
title: proxy
sidebarTitle: proxy
---
# `fastmcp.server.auth.oauth_proxy.proxy`
OAuth Proxy Provider for FastMCP.
This provider acts as a transparent proxy to an upstream OAuth Authorization Server,
handling Dynamic Client Registration locally while forwarding all other OAuth flows.
This enables authentication with upstream providers that don't support DCR or have
restricted client registration policies.
Key features:
- Proxies authorization and token endpoints to upstream server
- Implements local Dynamic Client Registration with fixed upstream credentials
- Validates tokens using upstream JWKS
- Maintains minimal local state for bookkeeping
- Enhanced logging with request correlation
This implementation is based on the OAuth 2.1 specification and is designed for
production use with enterprise identity providers.
## Classes
### `OAuthProxy` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L124" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OAuth provider that presents a DCR-compliant interface while proxying to non-DCR IDPs.
Purpose
-------
MCP clients expect OAuth providers to support Dynamic Client Registration (DCR),
where clients can register themselves dynamically and receive unique credentials.
Most enterprise IDPs (Google, GitHub, Azure AD, etc.) don't support DCR and require
pre-registered OAuth applications with fixed credentials.
This proxy bridges that gap by:
- Presenting a full DCR-compliant OAuth interface to MCP clients
- Translating DCR registration requests to use pre-configured upstream credentials
- Proxying all OAuth flows to the upstream IDP with appropriate translations
- Managing the state and security requirements of both protocols
Architecture Overview
--------------------
The proxy maintains a single OAuth app registration with the upstream provider
while allowing unlimited MCP clients to register and authenticate dynamically.
It implements the complete OAuth 2.1 + DCR specification for clients while
translating to whatever OAuth variant the upstream provider requires.
Key Translation Challenges Solved
---------------------------------
1. Dynamic Client Registration:
- MCP clients expect to register dynamically and get unique credentials
- Upstream IDPs require pre-registered apps with fixed credentials
- Solution: Accept DCR requests, return shared upstream credentials
2. Dynamic Redirect URIs:
- MCP clients use random localhost ports that change between sessions
- Upstream IDPs require fixed, pre-registered redirect URIs
- Solution: Use proxy's fixed callback URL with upstream, forward to client's dynamic URI
3. Authorization Code Mapping:
- Upstream returns codes for the proxy's redirect URI
- Clients expect codes for their own redirect URIs
- Solution: Exchange upstream code server-side, issue new code to client
4. State Parameter Collision:
- Both client and proxy need to maintain state through the flow
- Only one state parameter available in OAuth
- Solution: Use transaction ID as state with upstream, preserve client's state
5. Token Management:
- Clients may expect different token formats/claims than upstream provides
- Need to track tokens for revocation and refresh
- Solution: Store token relationships, forward upstream tokens transparently
OAuth Flow Implementation
------------------------
1. Client Registration (DCR):
- Accept any client registration request
- Store ProxyDCRClient that accepts dynamic redirect URIs
2. Authorization:
- Store transaction mapping client details to proxy flow
- Redirect to upstream with proxy's fixed redirect URI
- Use transaction ID as state parameter with upstream
3. Upstream Callback:
- Exchange upstream authorization code for tokens (server-side)
- Generate new authorization code bound to client's PKCE challenge
- Redirect to client's original dynamic redirect URI
4. Token Exchange:
- Validate client's code and PKCE verifier
- Return previously obtained upstream tokens
- Clean up one-time use authorization code
5. Token Refresh:
- Forward refresh requests to upstream using authlib
- Handle token rotation if upstream issues new refresh token
- Update local token mappings
State Management
---------------
The proxy maintains minimal but crucial state via pluggable storage (client_storage):
- _oauth_transactions: Active authorization flows with client context
- _client_codes: Authorization codes with PKCE challenges and upstream tokens
- _jti_mapping_store: Maps FastMCP token JTIs to upstream token IDs
- _refresh_token_store: Refresh token metadata (keyed by token hash)
All state is stored in the configured client_storage backend (Redis, disk, etc.)
enabling horizontal scaling across multiple instances.
Security Considerations
----------------------
- Refresh tokens stored by hash only (defense in depth if storage compromised)
- PKCE enforced end-to-end (client to proxy, proxy to upstream)
- Authorization codes are single-use with short expiry
- Transaction IDs are cryptographically random
- All state is cleaned up after use to prevent replay
- Token validation delegates to upstream provider
Provider Compatibility
---------------------
Works with any OAuth 2.0 provider that supports:
- Authorization code flow
- Fixed redirect URI (configured in provider's app settings)
- Standard token endpoint
Handles provider-specific requirements:
- Google: Ensures minimum scope requirements
- GitHub: Compatible with OAuth Apps and GitHub Apps
- Azure AD: Handles tenant-specific endpoints
- Generic: Works with any spec-compliant provider
**Methods:**
#### `set_mcp_path` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L606" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
set_mcp_path(self, mcp_path: str | None) -> None
```
Set the MCP endpoint path and create JWTIssuer with correct audience.
This method is called by get_routes() to configure the resource URL
and create the JWTIssuer. The JWT audience is set to the full resource
URL (e.g., http://localhost:8000/mcp) to ensure tokens are bound to
this specific MCP endpoint.
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
#### `jwt_issuer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L630" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
jwt_issuer(self) -> JWTIssuer
```
Get the JWT issuer, ensuring it has been initialized.
The JWT issuer is created when set_mcp_path() is called (via get_routes()).
This property ensures a clear error if used before initialization.
#### `get_client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L702" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_client(self, client_id: str) -> OAuthClientInformationFull | None
```
Get client information by ID. This is generally the random ID
provided to the DCR client during registration, not the upstream client ID.
For unregistered clients, returns None (which will raise an error in the SDK).
CIMD clients (URL-based client IDs) are looked up and cached automatically.
#### `register_client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L764" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_client(self, client_info: OAuthClientInformationFull) -> None
```
Register a client locally
When a client registers, we create a ProxyDCRClient that is more
forgiving about validating redirect URIs, since the DCR client's
redirect URI will likely be localhost or unknown to the proxied IDP. The
proxied IDP only knows about this server's fixed redirect URI.
#### `authorize` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L817" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str
```
Start OAuth transaction and route through consent interstitial.
Flow:
1. Validate client's resource matches server's resource URL (security check)
2. Store transaction with client details and PKCE (if forwarding)
3. Return local /consent URL; browser visits consent first
4. Consent handler redirects to upstream IdP if approved/already approved
If consent is disabled (require_authorization_consent=False or "external"),
skip the consent screen and redirect directly to the upstream IdP. In
"remember" mode, still route through /consent so the cookie lookup and
Sec-Fetch-Site gating can run.
#### `load_authorization_code` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L940" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_authorization_code(self, client: OAuthClientInformationFull, authorization_code: str) -> AuthorizationCode | None
```
Load authorization code for validation.
Look up our client code and return authorization code object
with PKCE challenge for validation.
#### `exchange_authorization_code` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L988" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
exchange_authorization_code(self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode) -> OAuthToken
```
Exchange authorization code for FastMCP-issued tokens.
Implements the token factory pattern:
1. Retrieves upstream tokens from stored authorization code
2. Extracts user identity from upstream token
3. Encrypts and stores upstream tokens
4. Issues FastMCP-signed JWT tokens
5. Returns FastMCP tokens (NOT upstream tokens)
PKCE validation is handled by the MCP framework before this method is called.
#### `load_refresh_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L1249" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_refresh_token(self, client: OAuthClientInformationFull, refresh_token: str) -> RefreshToken | None
```
Load refresh token metadata from distributed storage.
Looks up by token hash and reconstructs the RefreshToken object.
Validates that the token belongs to the requesting client.
#### `exchange_refresh_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L1278" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
exchange_refresh_token(self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken
```
Exchange FastMCP refresh token for new FastMCP access token.
Implements two-tier refresh:
1. Verify FastMCP refresh token
2. Look up upstream token via JTI mapping
3. Refresh upstream token with upstream provider
4. Update stored upstream token
5. Issue new FastMCP access token
6. Keep same FastMCP refresh token (unless upstream rotates)
#### `load_access_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L1634" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_access_token(self, token: str) -> AccessToken | None
```
Validate FastMCP JWT by swapping for upstream token.
This implements the token swap pattern:
1. Verify FastMCP JWT signature (proves it's our token)
2. Look up upstream token via JTI mapping
3. Decrypt upstream token
4. Validate upstream token with provider (GitHub API, JWT validation, etc.)
5. If upstream validation fails, attempt transparent refresh
6. Return upstream validation result
The FastMCP JWT is a reference token - all authorization data comes
from validating the upstream token via the TokenVerifier.
#### `revoke_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L1797" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
revoke_token(self, token: AccessToken | RefreshToken) -> None
```
Revoke token locally and with upstream server if supported.
For refresh tokens, removes from local storage by hash.
For all tokens, attempts upstream revocation if endpoint is configured.
Access token JTI mappings expire via TTL.
#### `get_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/proxy.py#L1843" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get OAuth routes with custom handlers for better error UX.
This method creates standard OAuth routes and replaces:
- /authorize endpoint: Enhanced error responses for unregistered clients
- /token endpoint: OAuth 2.1 compliant error codes
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
This is used to advertise the resource URL in metadata.

View file

@ -1,50 +0,0 @@
---
title: ui
sidebarTitle: ui
---
# `fastmcp.server.auth.oauth_proxy.ui`
OAuth Proxy UI Generation Functions.
This module contains HTML generation functions for consent and error pages.
## Functions
### `create_consent_html` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/ui.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_consent_html(client_id: str, redirect_uri: str, scopes: list[str], txn_id: str, csrf_token: str, client_name: str | None = None, title: str = 'Application Access Request', server_name: str | None = None, server_icon_url: str | None = None, server_website_url: str | None = None, client_website_url: str | None = None, csp_policy: str | None = None, is_cimd_client: bool = False, cimd_domain: str | None = None) -> str
```
Create a styled HTML consent page for OAuth authorization requests.
**Args:**
- `csp_policy`: Content Security Policy override.
If None, uses the built-in CSP policy with appropriate directives.
If empty string "", disables CSP entirely (no meta tag is rendered).
If a non-empty string, uses that as the CSP policy value.
### `create_error_html` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oauth_proxy/ui.py#L215" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_error_html(error_title: str, error_message: str, error_details: dict[str, str] | None = None, server_name: str | None = None, server_icon_url: str | None = None) -> str
```
Create a styled HTML error page for OAuth errors.
**Args:**
- `error_title`: The error title (e.g., "OAuth Error", "Authorization Failed")
- `error_message`: The main error message to display
- `error_details`: Optional dictionary of error details to show (e.g., `{"Error Code"\: "invalid_client"}`)
- `server_name`: Optional server name to display
- `server_icon_url`: Optional URL to server icon/logo
**Returns:**
- Complete HTML page as a string

View file

@ -1,82 +0,0 @@
---
title: oidc_proxy
sidebarTitle: oidc_proxy
---
# `fastmcp.server.auth.oidc_proxy`
OIDC Proxy Provider for FastMCP.
This provider acts as a transparent proxy to an upstream OIDC compliant Authorization
Server. It leverages the OAuthProxy class to handle Dynamic Client Registration and
forwarding of all OAuth flows.
This implementation is based on:
OpenID Connect Discovery 1.0 - https://openid.net/specs/openid-connect-discovery-1_0.html
OAuth 2.0 Authorization Server Metadata - https://datatracker.ietf.org/doc/html/rfc8414
## Classes
### `OIDCConfiguration` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oidc_proxy.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OIDC Configuration.
**Methods:**
#### `get_oidc_configuration` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oidc_proxy.py#L144" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_oidc_configuration(cls, config_url: AnyHttpUrl) -> Self
```
Get the OIDC configuration for the specified config URL.
**Args:**
- `config_url`: The OIDC config URL
- `strict`: The strict flag for the configuration
- `timeout_seconds`: HTTP request timeout in seconds
### `OIDCProxy` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oidc_proxy.py#L174" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OAuth provider that wraps OAuthProxy to provide configuration via an OIDC configuration URL.
This provider makes it easier to add OAuth protection for any upstream provider
that is OIDC compliant.
**Methods:**
#### `get_oidc_configuration` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oidc_proxy.py#L463" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_oidc_configuration(self, config_url: AnyHttpUrl, strict: bool | None, timeout_seconds: int | None) -> OIDCConfiguration
```
Gets the OIDC configuration for the specified configuration URL.
**Args:**
- `config_url`: The OIDC configuration URL
- `strict`: The strict flag for the configuration
- `timeout_seconds`: HTTP request timeout in seconds
#### `get_token_verifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/oidc_proxy.py#L480" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_token_verifier(self) -> TokenVerifier
```
Creates the token verifier for the specified OIDC configuration and arguments.
**Args:**
- `algorithm`: Optional token verifier algorithm
- `audience`: Optional token verifier audience
- `required_scopes`: Optional token verifier required_scopes
- `timeout_seconds`: HTTP request timeout in seconds

View file

@ -1,8 +0,0 @@
---
title: __init__
sidebarTitle: __init__
---
# `fastmcp.server.auth.providers`
*This module is empty or contains only private/internal implementations.*

View file

@ -1,41 +0,0 @@
---
title: auth0
sidebarTitle: auth0
---
# `fastmcp.server.auth.providers.auth0`
Auth0 OAuth provider for FastMCP.
This module provides a complete Auth0 integration that's ready to use with
just the configuration URL, client ID, client secret, audience, and base URL.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.auth0 import Auth0Provider
# Simple Auth0 OAuth protection
auth = Auth0Provider(
config_url="https://auth0.config.url",
client_id="your-auth0-client-id",
client_secret="your-auth0-client-secret",
audience="your-auth0-api-audience",
base_url="http://localhost:8000",
)
mcp = FastMCP("My Protected Server", auth=auth)
```
## Classes
### `Auth0Provider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/auth0.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
An Auth0 provider implementation for FastMCP.
This provider is a complete Auth0 integration that's ready to use with
just the configuration URL, client ID, client secret, audience, and base URL.

View file

@ -1,87 +0,0 @@
---
title: aws
sidebarTitle: aws
---
# `fastmcp.server.auth.providers.aws`
AWS Cognito OAuth provider for FastMCP.
This module provides a complete AWS Cognito OAuth integration that's ready to use
with a user pool ID, domain prefix, client ID and client secret. It handles all
the complexity of AWS Cognito's OAuth flow, token validation, and user management.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.aws_cognito import AWSCognitoProvider
# Simple AWS Cognito OAuth protection
auth = AWSCognitoProvider(
user_pool_id="your-user-pool-id",
aws_region="eu-central-1",
client_id="your-cognito-client-id",
client_secret="your-cognito-client-secret"
)
mcp = FastMCP("My Protected Server", auth=auth)
```
## Classes
### `AWSCognitoTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/aws.py#L40" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Token verifier for Cognito access tokens.
Cognito access tokens use a ``client_id`` claim instead of the
standard ``aud`` claim. This subclass passes ``audience=None``
to the parent (skipping the ``aud`` check) and validates the
``client_id`` claim directly.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/aws.py#L53" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify token and filter claims to Cognito-specific subset.
### `AWSCognitoProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/aws.py#L90" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Complete AWS Cognito OAuth provider for FastMCP.
This provider makes it trivial to add AWS Cognito OAuth protection to any
FastMCP server using OIDC Discovery. Just provide your Cognito User Pool details,
client credentials, and a base URL, and you're ready to go.
Features:
- Automatic OIDC Discovery from AWS Cognito User Pool
- Automatic JWT token validation via Cognito's public keys
- Cognito-specific claim filtering (sub, username, cognito:groups)
- Support for Cognito User Pools
**Methods:**
#### `get_token_verifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/aws.py#L209" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_token_verifier(self) -> AWSCognitoTokenVerifier
```
Creates a Cognito-specific token verifier with claim filtering.
**Args:**
- `algorithm`: Optional token verifier algorithm
- `audience`: Optional token verifier audience
- `required_scopes`: Optional token verifier required_scopes
- `timeout_seconds`: HTTP request timeout in seconds

View file

@ -1,221 +0,0 @@
---
title: azure
sidebarTitle: azure
---
# `fastmcp.server.auth.providers.azure`
Azure (Microsoft Entra) OAuth provider for FastMCP.
This provider implements Azure/Microsoft Entra ID OAuth authentication
using the OAuth Proxy pattern for non-DCR OAuth flows.
## Functions
### `EntraOBOToken` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L818" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
EntraOBOToken(scopes: list[str]) -> str
```
Exchange the user's Entra token for a downstream API token via OBO.
This dependency performs a Microsoft Entra On-Behalf-Of (OBO) token exchange,
allowing your MCP server to call downstream APIs (like Microsoft Graph) on
behalf of the authenticated user.
**Args:**
- `scopes`: The scopes to request for the downstream API. For Microsoft Graph,
use scopes like ["https\://graph.microsoft.com/Mail.Read"] or
["https\://graph.microsoft.com/.default"].
**Returns:**
- A dependency that resolves to the downstream API access token string
**Raises:**
- `ImportError`: If fastmcp[azure] is not installed
- `RuntimeError`: If no access token is available, provider is not Azure,
or OBO exchange fails
## Classes
### `AzureProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L39" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Azure (Microsoft Entra) OAuth provider for FastMCP.
This provider implements Azure/Microsoft Entra ID authentication using the
OAuth Proxy pattern. It supports both organizational accounts and personal
Microsoft accounts depending on the tenant configuration.
Scope Handling:
- required_scopes: Provide unprefixed scope names (e.g., ["read", "write"])
→ Automatically prefixed with identifier_uri during initialization
→ Validated on all tokens and advertised to MCP clients
- additional_authorize_scopes: Provide full format (e.g., ["User.Read"])
→ NOT prefixed, NOT validated, NOT advertised to clients
→ Used to request Microsoft Graph or other upstream API permissions
Features:
- OAuth proxy to Azure/Microsoft identity platform
- JWT validation using tenant issuer and JWKS
- Supports tenant configurations: specific tenant ID, "organizations", or "consumers"
- Custom API scopes and Microsoft Graph scopes in a single provider
Setup:
1. Create an App registration in Azure Portal
2. Configure Web platform redirect URI: http://localhost:8000/auth/callback (or your custom path)
3. Add an Application ID URI under "Expose an API" (defaults to api://{client_id})
4. Add custom scopes (e.g., "read", "write") under "Expose an API"
5. Set access token version to 2 in the App manifest: "requestedAccessTokenVersion": 2
6. Create a client secret
7. Get Application (client) ID, Directory (tenant) ID, and client secret
**Methods:**
#### `from_b2c` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L281" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
from_b2c(cls, **kwargs: Any) -> AzureProvider
```
Create an AzureProvider pre-configured for Azure AD B2C.
Derives authority host, tenant path, and identifier URI from
`tenant_name` and `policy_name`, then delegates to the standard
constructor. Returns a plain `AzureProvider` instance.
B2C issuer validation is disabled by default (`token_issuer=None`)
because B2C issuers embed the tenant GUID. Pass an explicit
`token_issuer` string once you know the real `iss` value.
Azure AD B2C does **not** support OBO.
**Args:**
- `tenant_name`: Short B2C tenant name without `.onmicrosoft.com`
(e.g. `"mytenant"`).
- `policy_name`: User-flow or custom-policy name
(e.g. `"B2C_1_susi"`).
- `client_id`: Application (client) ID from the B2C app registration.
- `client_secret`: Client secret from the B2C app registration.
- `required_scopes`: Custom API scope names without prefix
(e.g. `["mcp-access"]`).
- `base_url`: Public base URL of this server.
- `custom_domain`: Custom domain for the B2C authority
(e.g. `"auth.mycompany.com"`). Defaults to
`{tenant_name}.b2clogin.com`.
- `identifier_uri`: Application ID URI. Defaults to
`https\://{tenant_name}.onmicrosoft.com/{client_id}`.
- `token_issuer`: Expected `iss` claim. `None` (default) disables
issuer validation.
- `**kwargs`: Forwarded to `AzureProvider.__init__`.
#### `authorize` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L359" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str
```
Start OAuth transaction and redirect to Azure AD.
Override parent's authorize method to filter out the 'resource' parameter
which is not supported by Azure AD v2.0 endpoints. The v2.0 endpoints use
scopes to determine the resource/audience instead of a separate parameter.
**Args:**
- `client`: OAuth client information
- `params`: Authorization parameters from the client
**Returns:**
- Authorization URL to redirect the user to Azure AD
#### `get_obo_credential` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L585" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_obo_credential(self, user_assertion: str) -> OnBehalfOfCredential
```
Get a cached or new OnBehalfOfCredential for OBO token exchange.
Credentials are cached by user assertion so the Azure SDK's internal
token cache can avoid redundant OBO exchanges when the same user
calls multiple tools with the same scopes.
**Args:**
- `user_assertion`: The user's access token to exchange via OBO.
**Returns:**
- A configured OnBehalfOfCredential ready for get_token() calls.
**Raises:**
- `NotImplementedError`: If OBO is not supported (e.g. Azure AD B2C).
- `ImportError`: If azure-identity is not installed (requires fastmcp[azure]).
#### `close_obo_credentials` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L642" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
close_obo_credentials(self) -> None
```
Close all cached OBO credentials.
### `AzureJWTVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L653" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
JWT verifier pre-configured for Azure AD / Microsoft Entra ID.
Auto-configures JWKS URI, issuer, audience, and scope handling from your
Azure app registration details. Designed for Managed Identity and other
token-verification-only scenarios where AzureProvider's full OAuth proxy
isn't needed.
Handles Azure's scope format automatically:
- Validates tokens using short-form scopes (what Azure puts in ``scp`` claims)
- Advertises full-URI scopes in OAuth metadata (what clients need to request)
Example::
from fastmcp.server.auth import RemoteAuthProvider
from fastmcp.server.auth.providers.azure import AzureJWTVerifier
from pydantic import AnyHttpUrl
verifier = AzureJWTVerifier(
client_id="your-client-id",
tenant_id="your-tenant-id",
required_scopes=["access_as_user"],
)
auth = RemoteAuthProvider(
token_verifier=verifier,
authorization_servers=[
AnyHttpUrl("https://login.microsoftonline.com/your-tenant-id/v2.0")
],
base_url="https://my-server.com",
)
**Methods:**
#### `scopes_supported` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/azure.py#L733" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
scopes_supported(self) -> list[str]
```
Return scopes with Azure URI prefix for OAuth metadata.
Azure tokens contain short-form scopes (e.g., ``read``) in the ``scp``
claim, but clients must request full URI scopes (e.g.,
``api://client-id/read``) from the Azure authorization endpoint. This
property returns the full-URI form for OAuth metadata while
``required_scopes`` retains the short form for token validation.

View file

@ -1,94 +0,0 @@
---
title: clerk
sidebarTitle: clerk
---
# `fastmcp.server.auth.providers.clerk`
Clerk OAuth provider for FastMCP.
This module provides a complete Clerk OAuth integration that's ready to use
with a Clerk domain, client ID, and client secret. It handles all the complexity
of Clerk's OAuth/OIDC flow, token validation, and user management.
Clerk uses standard OIDC endpoints derived from the instance domain
(e.g., ``https://<instance>.clerk.accounts.dev``). Token verification is
performed via the introspection endpoint (RFC 7662) for security-critical
checks (active status, audience, scopes), followed by the userinfo endpoint
for profile enrichment. Userinfo failure is non-fatal.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.clerk import ClerkProvider
auth = ClerkProvider(
domain="saving-primate-16.clerk.accounts.dev",
client_id="your-clerk-client-id",
client_secret="your-clerk-client-secret",
base_url="https://my-server.com",
)
mcp = FastMCP("My Protected Server", auth=auth)
```
## Classes
### `ClerkTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/clerk.py#L47" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Token verifier for Clerk OAuth tokens.
Clerk issues standard OIDC tokens. Verification uses the introspection
endpoint (RFC 7662) as the primary security gate — it confirms the token
is active and provides metadata (scopes, expiry, audience). The userinfo
endpoint is called second for profile enrichment (name, email, picture)
and its failure is non-fatal.
When a ``client_id`` is configured, the audience from introspection is
validated against it. When ``required_scopes`` are configured,
introspection must return the token's scopes — the verifier will not
assume scopes when introspection is unavailable.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/clerk.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a Clerk OAuth token via introspection and userinfo.
Calls the introspection endpoint first to validate the token and
retrieve auth metadata (active status, scopes, expiry, audience).
If the token passes security checks, the userinfo endpoint is called
for profile enrichment. Userinfo failure is non-fatal.
When a ``client_id`` is configured, the token's audience must match it.
When ``required_scopes`` are configured, introspection must confirm
them; tokens are rejected if scope information is unavailable.
### `ClerkProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/clerk.py#L240" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Complete Clerk OAuth provider for FastMCP.
This provider makes it trivial to add Clerk OAuth protection to any
FastMCP server. Provide your Clerk instance domain, OAuth app credentials,
and a base URL, and you're ready to go.
Clerk uses standard OIDC endpoints derived from the instance domain.
All endpoint URLs are constructed automatically from the domain parameter.
Features:
- Transparent OAuth proxy to Clerk
- Automatic token validation via Clerk's userinfo & introspection APIs
- User information extraction from Clerk's OIDC claims
- PKCE support (S256)
- Minimal configuration required

View file

@ -1,70 +0,0 @@
---
title: debug
sidebarTitle: debug
---
# `fastmcp.server.auth.providers.debug`
Debug token verifier for testing and special cases.
This module provides a flexible token verifier that delegates validation
to a custom callable. Useful for testing, development, or scenarios where
standard verification isn't possible (like opaque tokens without introspection).
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.debug import DebugTokenVerifier
# Accept all tokens (default - useful for testing)
auth = DebugTokenVerifier()
# Custom sync validation logic
auth = DebugTokenVerifier(validate=lambda token: token.startswith("valid-"))
# Custom async validation logic
async def check_cache(token: str) -> bool:
return await redis.exists(f"token:{token}")
auth = DebugTokenVerifier(validate=check_cache)
mcp = FastMCP("My Server", auth=auth)
```
## Classes
### `DebugTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/debug.py#L40" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Token verifier with custom validation logic.
This verifier delegates token validation to a user-provided callable.
By default, it accepts all non-empty tokens (useful for testing).
Use cases:
- Testing: Accept any token without real verification
- Development: Custom validation logic for prototyping
- Opaque tokens: When you have tokens with no introspection endpoint
WARNING: This bypasses standard security checks. Only use in controlled
environments or when you understand the security implications.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/debug.py#L77" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify token using custom validation logic.
**Args:**
- `token`: The token string to validate
**Returns:**
- AccessToken if validation succeeds, None otherwise

View file

@ -1,60 +0,0 @@
---
title: descope
sidebarTitle: descope
---
# `fastmcp.server.auth.providers.descope`
Descope authentication provider for FastMCP.
This module provides DescopeProvider - a complete authentication solution that integrates
with Descope's OAuth 2.1 and OpenID Connect services, supporting Dynamic Client Registration (DCR)
for seamless MCP client authentication.
## Classes
### `DescopeProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/descope.py#L25" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Descope metadata provider for DCR (Dynamic Client Registration).
This provider implements Descope integration using metadata forwarding.
This is the recommended approach for Descope DCR
as it allows Descope to handle the OAuth flow directly while FastMCP acts
as a resource server.
IMPORTANT SETUP REQUIREMENTS:
1. Create an MCP Server in Descope Console:
- Go to the [MCP Servers page](https://app.descope.com/mcp-servers) of the Descope Console
- Create a new MCP Server
- Ensure that **Dynamic Client Registration (DCR)** is enabled
- Note your Well-Known URL
2. Note your Well-Known URL:
- Save your Well-Known URL from [MCP Server Settings](https://app.descope.com/mcp-servers)
- Format: ``https://.../v1/apps/agentic/P.../M.../.well-known/openid-configuration``
For detailed setup instructions, see:
https://docs.descope.com/identity-federation/inbound-apps/creating-inbound-apps#method-2-dynamic-client-registration-dcr
**Methods:**
#### `get_routes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/descope.py#L165" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_routes(self, mcp_path: str | None = None) -> list[Route]
```
Get OAuth routes including Descope authorization server metadata forwarding.
This returns the standard protected resource routes plus an authorization server
metadata endpoint that forwards Descope's OAuth metadata to clients.
**Args:**
- `mcp_path`: The path where the MCP endpoint is mounted (e.g., "/mcp")
This is used to advertise the resource URL in metadata.

View file

@ -1,66 +0,0 @@
---
title: discord
sidebarTitle: discord
---
# `fastmcp.server.auth.providers.discord`
Discord OAuth provider for FastMCP.
This module provides a complete Discord OAuth integration that's ready to use
with just a client ID and client secret. It handles all the complexity of
Discord's OAuth flow, token validation, and user management.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.discord import DiscordProvider
# Simple Discord OAuth protection
auth = DiscordProvider(
client_id="your-discord-client-id",
client_secret="your-discord-client-secret"
)
mcp = FastMCP("My Protected Server", auth=auth)
```
## Classes
### `DiscordTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/discord.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Token verifier for Discord OAuth tokens.
Discord OAuth tokens are opaque (not JWTs), so we verify them
by calling Discord's tokeninfo API to check if they're valid and get user info.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/discord.py#L72" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify Discord OAuth token by calling Discord's tokeninfo API.
### `DiscordProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/discord.py#L165" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Complete Discord OAuth provider for FastMCP.
This provider makes it trivial to add Discord OAuth protection to any
FastMCP server. Just provide your Discord OAuth app credentials and
a base URL, and you're ready to go.
Features:
- Transparent OAuth proxy to Discord
- Automatic token validation via Discord's API
- User information extraction from Discord APIs
- Minimal configuration required

View file

@ -1,70 +0,0 @@
---
title: github
sidebarTitle: github
---
# `fastmcp.server.auth.providers.github`
GitHub OAuth provider for FastMCP.
This module provides a complete GitHub OAuth integration that's ready to use
with just a client ID and client secret. It handles all the complexity of
GitHub's OAuth flow, token validation, and user management.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.github import GitHubProvider
# Simple GitHub OAuth protection
auth = GitHubProvider(
client_id="your-github-client-id",
client_secret="your-github-client-secret"
)
mcp = FastMCP("My Protected Server", auth=auth)
```
## Classes
### `GitHubTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/github.py#L41" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Token verifier for GitHub OAuth tokens.
GitHub OAuth tokens are opaque (not JWTs), so we verify them
by calling GitHub's API to check if they're valid and get user info.
Caching is disabled by default. Set ``cache_ttl_seconds`` to a positive
integer to cache successful verification results and avoid repeated
GitHub API calls for the same token.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/github.py#L82" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify GitHub OAuth token by calling GitHub API.
### `GitHubProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/github.py#L178" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Complete GitHub OAuth provider for FastMCP.
This provider makes it trivial to add GitHub OAuth protection to any
FastMCP server. Just provide your GitHub OAuth app credentials and
a base URL, and you're ready to go.
Features:
- Transparent OAuth proxy to GitHub
- Automatic token validation via GitHub API
- User information extraction
- Minimal configuration required

View file

@ -1,74 +0,0 @@
---
title: google
sidebarTitle: google
---
# `fastmcp.server.auth.providers.google`
Google OAuth provider for FastMCP.
This module provides a complete Google OAuth integration that's ready to use
with just a client ID and client secret. It handles all the complexity of
Google's OAuth flow, token validation, and user management.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.google import GoogleProvider
# Simple Google OAuth protection
auth = GoogleProvider(
client_id="your-google-client-id.apps.googleusercontent.com",
client_secret="your-google-client-secret"
)
mcp = FastMCP("My Protected Server", auth=auth)
```
## Classes
### `GoogleTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/google.py#L57" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Token verifier for Google OAuth tokens.
Google OAuth tokens are opaque (not JWTs), so we verify them by calling
Google's tokeninfo endpoint with the access token as a query parameter.
This returns the OAuth app ID (``aud``), granted scopes, and expiry time.
User profile data (name, picture, etc.) is fetched separately from the
v2 userinfo endpoint when the token is valid.
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/google.py#L92" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a Google OAuth token using the tokeninfo endpoint.
Calls ``https://oauth2.googleapis.com/tokeninfo?access_token=TOKEN``
to validate the token and retrieve the OAuth app ID (``aud``), granted
scopes, and expiry time. On success, fetches user profile data from
the v2 userinfo endpoint to populate name, picture, and locale claims.
### `GoogleProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/google.py#L204" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Complete Google OAuth provider for FastMCP.
This provider makes it trivial to add Google OAuth protection to any
FastMCP server. Just provide your Google OAuth app credentials and
a base URL, and you're ready to go.
Features:
- Transparent OAuth proxy to Google
- Automatic token validation via Google's tokeninfo API
- User information extraction from Google APIs
- Minimal configuration required

View file

@ -1,96 +0,0 @@
---
title: in_memory
sidebarTitle: in_memory
---
# `fastmcp.server.auth.providers.in_memory`
## Classes
### `InMemoryOAuthProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L31" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
An in-memory OAuth provider for testing purposes.
It simulates the OAuth 2.1 flow locally without external calls.
**Methods:**
#### `get_client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L67" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
get_client(self, client_id: str) -> OAuthClientInformationFull | None
```
#### `register_client` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L70" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
register_client(self, client_info: OAuthClientInformationFull) -> None
```
#### `authorize` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L94" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
authorize(self, client: OAuthClientInformationFull, params: AuthorizationParams) -> str
```
Simulates user authorization and generates an authorization code.
Returns a redirect URI with the code and state.
#### `load_authorization_code` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L151" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_authorization_code(self, client: OAuthClientInformationFull, authorization_code: str) -> AuthorizationCode | None
```
#### `exchange_authorization_code` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
exchange_authorization_code(self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode) -> OAuthToken
```
#### `load_refresh_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L217" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_refresh_token(self, client: OAuthClientInformationFull, refresh_token: str) -> RefreshToken | None
```
#### `exchange_refresh_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L232" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
exchange_refresh_token(self, client: OAuthClientInformationFull, refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken
```
#### `load_access_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_access_token(self, token: str) -> AccessToken | None
```
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L300" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a bearer token and return access info if valid.
This method implements the TokenVerifier protocol by delegating
to our existing load_access_token method.
**Args:**
- `token`: The token string to validate
**Returns:**
- AccessToken object if valid, None if invalid or expired
#### `revoke_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/in_memory.py#L357" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
revoke_token(self, token: AccessToken | RefreshToken) -> None
```
Revokes an access or refresh token and its counterpart.

View file

@ -1,82 +0,0 @@
---
title: introspection
sidebarTitle: introspection
---
# `fastmcp.server.auth.providers.introspection`
OAuth 2.0 Token Introspection (RFC 7662) provider for FastMCP.
This module provides token verification for opaque tokens using the OAuth 2.0
Token Introspection protocol defined in RFC 7662. It allows FastMCP servers to
validate tokens issued by authorization servers that don't use JWT format.
Example:
```python
from fastmcp import FastMCP
from fastmcp.server.auth.providers.introspection import IntrospectionTokenVerifier
# Verify opaque tokens via RFC 7662 introspection
verifier = IntrospectionTokenVerifier(
introspection_url="https://auth.example.com/oauth/introspect",
client_id="your-client-id",
client_secret="your-client-secret",
required_scopes=["read", "write"]
)
mcp = FastMCP("My Protected Server", auth=verifier)
```
## Classes
### `IntrospectionTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/introspection.py#L45" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
OAuth 2.0 Token Introspection verifier (RFC 7662).
This verifier validates opaque tokens by calling an OAuth 2.0 token introspection
endpoint. Unlike JWT verification which is stateless, token introspection requires
a network call to the authorization server for each token validation.
The verifier authenticates to the introspection endpoint using either:
- HTTP Basic Auth (client_secret_basic, default): credentials in Authorization header
- POST body authentication (client_secret_post): credentials in request body
Both methods are specified in RFC 6749 (OAuth 2.0) and RFC 7662 (Token Introspection).
Use this when:
- Your authorization server issues opaque (non-JWT) tokens
- You need to validate tokens from Auth0, Okta, Keycloak, or other OAuth servers
- Your tokens require real-time revocation checking
- Your authorization server supports RFC 7662 introspection
Caching is disabled by default to preserve real-time revocation semantics.
Set ``cache_ttl_seconds`` to enable caching and reduce load on the
introspection endpoint (e.g., ``cache_ttl_seconds=300`` for 5 minutes).
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/introspection.py#L179" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a bearer token using OAuth 2.0 Token Introspection (RFC 7662).
This method makes a POST request to the introspection endpoint with the token,
authenticated using the configured client authentication method (client_secret_basic
or client_secret_post).
Results are cached in-memory to reduce load on the introspection endpoint.
Cache TTL and size are configurable via constructor parameters.
**Args:**
- `token`: The opaque token string to validate
**Returns:**
- AccessToken object if valid and active, None if invalid, inactive, or expired

View file

@ -1,146 +0,0 @@
---
title: jwt
sidebarTitle: jwt
---
# `fastmcp.server.auth.providers.jwt`
TokenVerifier implementations for FastMCP.
## Classes
### `JWKData` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
JSON Web Key data structure.
### `JWKSData` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L40" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
JSON Web Key Set data structure.
### `RSAKeyPair` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L47" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
RSA key pair for JWT testing.
**Methods:**
#### `generate` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L54" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
generate(cls) -> RSAKeyPair
```
Generate an RSA key pair for testing.
**Returns:**
- Generated key pair
#### `create_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L89" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
create_token(self, subject: str = 'fastmcp-user', issuer: str = 'https://fastmcp.example.com', audience: str | list[str] | None = None, scopes: list[str] | None = None, expires_in_seconds: int = 3600, additional_claims: dict[str, Any] | None = None, kid: str | None = None) -> str
```
Generate a test JWT token for testing purposes.
**Args:**
- `subject`: Subject claim (usually user ID)
- `issuer`: Issuer claim
- `audience`: Audience claim - can be a string or list of strings (optional)
- `scopes`: List of scopes to include
- `expires_in_seconds`: Token expiration time in seconds
- `additional_claims`: Any additional claims to include
- `kid`: Key ID to include in header
### `JWTVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L156" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
JWT token verifier supporting both asymmetric (RSA/ECDSA) and symmetric (HMAC) algorithms.
This verifier validates JWT tokens using various signing algorithms:
- **Asymmetric algorithms** (RS256/384/512, ES256/384/512, PS256/384/512):
Uses public/private key pairs. Ideal for external clients and services where
only the authorization server has the private key.
- **Symmetric algorithms** (HS256/384/512): Uses a shared secret for both
signing and verification. Perfect for internal microservices and trusted
environments where the secret can be securely shared.
Use this when:
- You have JWT tokens issued by an external service (asymmetric)
- You need JWKS support for automatic key rotation (asymmetric)
- You have internal microservices sharing a secret key (symmetric)
- Your tokens contain standard OAuth scopes and claims
**Methods:**
#### `load_access_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L397" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
load_access_token(self, token: str) -> AccessToken | None
```
Validate a JWT bearer token and return an AccessToken when the token is valid.
**Args:**
- `token`: The JWT bearer token string to validate.
**Returns:**
- AccessToken | None: An AccessToken populated from token claims if the token is valid; `None` if the token is expired, has an invalid signature or format, fails issuer/audience/scope validation, or any other validation error occurs.
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L523" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify a bearer token and return access info if valid.
This method implements the TokenVerifier protocol by delegating
to our existing load_access_token method.
**Args:**
- `token`: The JWT token string to validate
**Returns:**
- AccessToken object if valid, None if invalid or expired
### `StaticTokenVerifier` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L539" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Simple static token verifier for testing and development.
This verifier validates tokens against a predefined dictionary of valid token
strings and their associated claims. When a token string matches a key in the
dictionary, the verifier returns the corresponding claims as if the token was
validated by a real authorization server.
Use this when:
- You're developing or testing locally without a real OAuth server
- You need predictable tokens for automated testing
- You want to simulate different users/scopes without complex setup
- You're prototyping and need simple API key-style authentication
WARNING: Never use this in production - tokens are stored in plain text!
**Methods:**
#### `verify_token` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/src/fastmcp/server/auth/providers/jwt.py#L573" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```python
verify_token(self, token: str) -> AccessToken | None
```
Verify token against static token dictionary.

Some files were not shown because too many files have changed in this diff Show more