chore: import upstream snapshot with attribution
Upgrade checks / Notify on failure (push) Has been cancelled
Upgrade checks / Close issue on success (push) Has been cancelled
Schema Crash Test / Real-world schema crash test (232K schemas) (push) Has been cancelled
Run static analysis / static_analysis (push) Has been cancelled
Tests / Tests: Python 3.10 on ubuntu-latest (push) Has been cancelled
Tests / Tests: Python 3.13 on ubuntu-latest (push) Has been cancelled
Tests / Tests: Python 3.10 on windows-latest (push) Has been cancelled
Tests / Tests with lowest-direct dependencies (push) Has been cancelled
Tests / MCP conformance tests (push) Has been cancelled
Tests / Integration tests (push) Has been cancelled
Tests / Package install smoke (push) Has been cancelled
Upgrade checks / Static analysis (push) Has been cancelled
Upgrade checks / Tests: Python 3.10 on ubuntu-latest (push) Has been cancelled
Upgrade checks / Tests: Python 3.13 on ubuntu-latest (push) Has been cancelled
Upgrade checks / Tests: Python 3.10 on windows-latest (push) Has been cancelled
Upgrade checks / Integration tests (push) Has been cancelled
Update MCPServerConfig Schema / update-config-schema (push) Has been cancelled
Update SDK Documentation / update-sdk-docs (push) Has been cancelled
Upgrade checks / Notify on failure (push) Has been cancelled
Upgrade checks / Close issue on success (push) Has been cancelled
Schema Crash Test / Real-world schema crash test (232K schemas) (push) Has been cancelled
Run static analysis / static_analysis (push) Has been cancelled
Tests / Tests: Python 3.10 on ubuntu-latest (push) Has been cancelled
Tests / Tests: Python 3.13 on ubuntu-latest (push) Has been cancelled
Tests / Tests: Python 3.10 on windows-latest (push) Has been cancelled
Tests / Tests with lowest-direct dependencies (push) Has been cancelled
Tests / MCP conformance tests (push) Has been cancelled
Tests / Integration tests (push) Has been cancelled
Tests / Package install smoke (push) Has been cancelled
Upgrade checks / Static analysis (push) Has been cancelled
Upgrade checks / Tests: Python 3.10 on ubuntu-latest (push) Has been cancelled
Upgrade checks / Tests: Python 3.13 on ubuntu-latest (push) Has been cancelled
Upgrade checks / Tests: Python 3.10 on windows-latest (push) Has been cancelled
Upgrade checks / Integration tests (push) Has been cancelled
Update MCPServerConfig Schema / update-config-schema (push) Has been cancelled
Update SDK Documentation / update-sdk-docs (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
---
|
||||
title: __init__
|
||||
sidebarTitle: __init__
|
||||
---
|
||||
|
||||
# `fastmcp.apps`
|
||||
|
||||
|
||||
FastMCP Apps — interactive UIs for MCP tools.
|
||||
|
||||
This package contains the app-related components:
|
||||
|
||||
- ``FastMCPApp`` — composable provider for interactive apps with backend tools
|
||||
- ``AppConfig`` — configuration for MCP App tools and resources
|
||||
- ``ResourceCSP`` / ``ResourcePermissions`` — security configuration
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
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/fastmcp_slim/fastmcp/apps/app.py#L144" 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/fastmcp_slim/fastmcp/apps/app.py#L168" 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/fastmcp_slim/fastmcp/apps/app.py#L180" 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/fastmcp_slim/fastmcp/apps/app.py#L191" 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/fastmcp_slim/fastmcp/apps/app.py#L258" 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/fastmcp_slim/fastmcp/apps/app.py#L273" 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/fastmcp_slim/fastmcp/apps/app.py#L287" 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/fastmcp_slim/fastmcp/apps/app.py#L362" 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/fastmcp_slim/fastmcp/apps/app.py#L418" 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/fastmcp_slim/fastmcp/apps/app.py#L426" 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.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
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/fastmcp_slim/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",
|
||||
)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
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/fastmcp_slim/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())
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
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/fastmcp_slim/fastmcp/apps/config.py#L180" 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/fastmcp_slim/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/fastmcp_slim/fastmcp/apps/config.py#L56" 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/fastmcp_slim/fastmcp/apps/config.py#L84" 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/fastmcp_slim/fastmcp/apps/config.py#L124" 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/fastmcp_slim/fastmcp/apps/config.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
model_post_init(self, __context: Any) -> None
|
||||
```
|
||||
@@ -0,0 +1,144 @@
|
||||
---
|
||||
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/fastmcp_slim/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/fastmcp_slim/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/fastmcp_slim/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/fastmcp_slim/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.
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
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/fastmcp_slim/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))
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
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/fastmcp_slim/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/fastmcp_slim/fastmcp/apps/generative.py#L196" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
lifespan(self) -> AsyncIterator[None]
|
||||
```
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: cli
|
||||
sidebarTitle: cli
|
||||
---
|
||||
|
||||
# `fastmcp.cli`
|
||||
|
||||
|
||||
FastMCP CLI package.
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: decorators
|
||||
sidebarTitle: decorators
|
||||
---
|
||||
|
||||
# `fastmcp.decorators`
|
||||
|
||||
|
||||
Shared decorator utilities for FastMCP.
|
||||
|
||||
## Functions
|
||||
|
||||
### `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
|
||||
```
|
||||
|
||||
|
||||
Resolve task config, defaulting None to False.
|
||||
|
||||
|
||||
### `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
|
||||
```
|
||||
|
||||
|
||||
Extract FastMCP metadata from a function, handling bound methods and wrappers.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `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.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
title: dependencies
|
||||
sidebarTitle: dependencies
|
||||
---
|
||||
|
||||
# `fastmcp.dependencies`
|
||||
|
||||
|
||||
Dependency injection exports for FastMCP.
|
||||
|
||||
This module re-exports dependency injection symbols to provide a clean,
|
||||
centralized import location for all dependency-related functionality.
|
||||
|
||||
DI features (Depends, CurrentContext, CurrentFastMCP) work without pydocket
|
||||
using the uncalled-for DI engine. Only task-related dependencies (CurrentDocket,
|
||||
CurrentWorker) and background task execution require fastmcp[tasks].
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
---
|
||||
title: exceptions
|
||||
sidebarTitle: exceptions
|
||||
---
|
||||
|
||||
# `fastmcp.exceptions`
|
||||
|
||||
|
||||
Custom exceptions for FastMCP.
|
||||
|
||||
## Classes
|
||||
|
||||
### `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.
|
||||
|
||||
Subclass of DeprecationWarning so that standard warning filters
|
||||
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/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/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/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/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/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/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/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/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/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/fastmcp_slim/fastmcp/exceptions.py#L62" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Error when authorization check fails.
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
title: code_mode
|
||||
sidebarTitle: code_mode
|
||||
---
|
||||
|
||||
# `fastmcp.experimental.transforms.code_mode`
|
||||
|
||||
## Classes
|
||||
|
||||
### `SandboxProvider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L77" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Interface for executing LLM-generated Python code in a sandbox.
|
||||
|
||||
WARNING: The ``code`` parameter passed to ``run`` contains untrusted,
|
||||
LLM-generated Python. Implementations MUST execute it in an isolated
|
||||
sandbox — never with plain ``exec()``. Use ``MontySandboxProvider``
|
||||
(backed by ``pydantic-monty``) for production workloads.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L86" 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/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L114" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Sandbox provider backed by `pydantic-monty`.
|
||||
|
||||
**Args:**
|
||||
- `limits`: Resource limits for sandbox execution. Supported keys\:
|
||||
``max_duration_secs`` (float), ``max_allocations`` (int),
|
||||
``max_memory`` (int), ``max_recursion_depth`` (int),
|
||||
``gc_interval`` (int). All are optional; omit a key to
|
||||
leave that limit uncapped.
|
||||
|
||||
When the argument is omitted entirely, a conservative baseline
|
||||
is applied (``max_duration_secs=30``, ``max_memory=100 MB``) so
|
||||
the out-of-box configuration is not unbounded. Pass
|
||||
``limits=None`` to explicitly run without any limits, or a dict
|
||||
to set your own.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `run` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L143" 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/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L238" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Discovery tool factory that searches the catalog by query.
|
||||
|
||||
**Args:**
|
||||
- `search_fn`: Async callable ``(tools, query) -> matching_tools``.
|
||||
Defaults to BM25 ranking.
|
||||
- `name`: Name of the synthetic tool exposed to the LLM.
|
||||
- `default_detail`: Default detail level for search results.
|
||||
``"brief"`` returns tool names and descriptions only.
|
||||
``"detailed"`` returns compact markdown with parameter schemas.
|
||||
``"full"`` returns complete JSON tool definitions.
|
||||
- `default_limit`: Maximum number of results to return.
|
||||
The LLM can override this per call. ``None`` means no limit.
|
||||
|
||||
|
||||
### `GetSchemas` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L320" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Discovery tool factory that returns schemas for tools by name.
|
||||
|
||||
**Args:**
|
||||
- `name`: Name of the synthetic tool exposed to the LLM.
|
||||
- `default_detail`: Default detail level for schema results.
|
||||
``"brief"`` returns tool names and descriptions only.
|
||||
``"detailed"`` renders compact markdown with parameter names,
|
||||
types, and required markers.
|
||||
``"full"`` returns the complete JSON schema.
|
||||
|
||||
|
||||
### `GetTags` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L381" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Discovery tool factory that lists tool tags from the catalog.
|
||||
|
||||
Reads ``tool.tags`` from the catalog and groups tools by tag. Tools
|
||||
without tags appear under ``"untagged"``.
|
||||
|
||||
**Args:**
|
||||
- `name`: Name of the synthetic tool exposed to the LLM.
|
||||
- `default_detail`: Default detail level.
|
||||
``"brief"`` returns tag names with tool counts.
|
||||
``"full"`` lists all tools under each tag.
|
||||
|
||||
|
||||
### `ListTools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L448" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Discovery tool factory that lists all tools in the catalog.
|
||||
|
||||
**Args:**
|
||||
- `name`: Name of the synthetic tool exposed to the LLM.
|
||||
- `default_detail`: Default detail level.
|
||||
``"brief"`` returns tool names and one-line descriptions.
|
||||
``"detailed"`` returns compact markdown with parameter schemas.
|
||||
``"full"`` returns the complete JSON schema.
|
||||
|
||||
|
||||
### `CodeMode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L497" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Transform that collapses all tools into discovery + execute meta-tools.
|
||||
|
||||
Discovery tools are composable via the ``discovery_tools`` parameter.
|
||||
Each is a callable that receives catalog access and returns a ``Tool``.
|
||||
By default, ``Search`` and ``GetSchemas`` are included for
|
||||
progressive disclosure: search finds candidates, get_schema retrieves
|
||||
parameter details, and execute runs code.
|
||||
|
||||
The ``execute`` tool is always present and provides a sandboxed Python
|
||||
environment with ``call_tool(name, params)`` in scope.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `transform_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L549" 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/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py#L552" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_tool(self, name: str, call_next: GetToolNext) -> Tool | None
|
||||
```
|
||||
@@ -0,0 +1,188 @@
|
||||
---
|
||||
title: mcp_config
|
||||
sidebarTitle: mcp_config
|
||||
---
|
||||
|
||||
# `fastmcp.mcp_config`
|
||||
|
||||
|
||||
Canonical MCP Configuration Format.
|
||||
|
||||
This module defines the standard configuration format for Model Context Protocol (MCP) servers.
|
||||
It provides a client-agnostic, extensible format that can be used across all MCP implementations.
|
||||
|
||||
The configuration format supports both stdio and remote (HTTP/SSE) transports, with comprehensive
|
||||
field definitions for server metadata, authentication, and execution parameters.
|
||||
|
||||
Example configuration:
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-server": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@my/mcp-server"],
|
||||
"env": {"API_KEY": "secret"},
|
||||
"timeout": 30000,
|
||||
"description": "My MCP server"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `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']
|
||||
```
|
||||
|
||||
|
||||
Infer the appropriate transport type from the given URL.
|
||||
|
||||
|
||||
### `update_config_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L363" 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
|
||||
```
|
||||
|
||||
|
||||
Update an MCP configuration file from a server object, preserving existing fields.
|
||||
|
||||
This is used for updating the mcpServer configurations of third-party tools so we do not
|
||||
worry about transforming server objects here.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `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.
|
||||
|
||||
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/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/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/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.
|
||||
|
||||
This is the canonical configuration format for MCP servers using remote transports.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `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/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/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
|
||||
while adding additional fields for enabling FastMCP-specific features like tool transformations
|
||||
and filtering by tags.
|
||||
|
||||
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/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]
|
||||
```
|
||||
|
||||
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/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
|
||||
```
|
||||
|
||||
Add or update a server in the configuration.
|
||||
|
||||
|
||||
#### `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
|
||||
```
|
||||
|
||||
Parse MCP configuration from dictionary format.
|
||||
|
||||
|
||||
#### `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]
|
||||
```
|
||||
|
||||
Convert MCPConfig to dictionary format, preserving all fields.
|
||||
|
||||
|
||||
#### `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
|
||||
```
|
||||
|
||||
Write configuration to JSON file.
|
||||
|
||||
|
||||
#### `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
|
||||
```
|
||||
|
||||
Load configuration from JSON file.
|
||||
|
||||
|
||||
### `CanonicalMCPConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/mcp_config.py#L348" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Canonical MCP configuration format.
|
||||
|
||||
This defines the standard configuration format for Model Context Protocol servers.
|
||||
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/fastmcp_slim/fastmcp/mcp_config.py#L358" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
add_server(self, name: str, server: CanonicalMCPServerTypes) -> None
|
||||
```
|
||||
|
||||
Add or update a server in the configuration.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: settings
|
||||
sidebarTitle: settings
|
||||
---
|
||||
|
||||
# `fastmcp.settings`
|
||||
|
||||
## Classes
|
||||
|
||||
### `DocketSettings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Docket worker configuration.
|
||||
|
||||
|
||||
### `Settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L136" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
FastMCP settings.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `get_setting` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L148" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_setting(self, attr: str) -> Any
|
||||
```
|
||||
|
||||
Get a setting. If the setting contains one or more `__`, it will be
|
||||
treated as a nested setting.
|
||||
|
||||
|
||||
#### `set_setting` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L161" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
set_setting(self, attr: str, value: Any) -> None
|
||||
```
|
||||
|
||||
Set a setting. If the setting contains one or more `__`, it will be
|
||||
treated as a nested setting.
|
||||
|
||||
|
||||
#### `normalize_log_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/settings.py#L183" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
normalize_log_level(cls, v)
|
||||
```
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
title: telemetry
|
||||
sidebarTitle: telemetry
|
||||
---
|
||||
|
||||
# `fastmcp.telemetry`
|
||||
|
||||
|
||||
OpenTelemetry instrumentation for FastMCP.
|
||||
|
||||
This module provides native OpenTelemetry integration for FastMCP servers and clients.
|
||||
It uses only the opentelemetry-api package, so telemetry is a no-op unless the user
|
||||
installs an OpenTelemetry SDK and configures exporters.
|
||||
|
||||
Example usage with SDK:
|
||||
```python
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
|
||||
|
||||
# Configure the SDK (user responsibility)
|
||||
provider = TracerProvider()
|
||||
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
|
||||
trace.set_tracer_provider(provider)
|
||||
|
||||
# Now FastMCP will emit traces
|
||||
from fastmcp import FastMCP
|
||||
mcp = FastMCP("my-server")
|
||||
```
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `get_tracer` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_tracer(version: str | None = None) -> Tracer
|
||||
```
|
||||
|
||||
|
||||
Get the FastMCP tracer for creating spans.
|
||||
|
||||
**Args:**
|
||||
- `version`: Optional version string for the instrumentation
|
||||
|
||||
**Returns:**
|
||||
- A tracer instance. Returns a no-op tracer if no SDK is configured.
|
||||
|
||||
|
||||
### `inject_trace_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L50" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
inject_trace_context(meta: dict[str, Any] | None = None) -> dict[str, Any] | None
|
||||
```
|
||||
|
||||
|
||||
Inject current trace context into a meta dict for MCP request propagation.
|
||||
|
||||
**Args:**
|
||||
- `meta`: Optional existing meta dict to merge with trace context
|
||||
|
||||
**Returns:**
|
||||
- A new dict containing the original meta (if any) plus trace context keys,
|
||||
- or None if no trace context to inject and meta was None
|
||||
|
||||
|
||||
### `record_span_error` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L76" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
record_span_error(span: Span, exception: BaseException) -> None
|
||||
```
|
||||
|
||||
|
||||
Record an exception on a span and set error status.
|
||||
|
||||
|
||||
### `extract_trace_context` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/telemetry.py#L82" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
extract_trace_context(meta: dict[str, Any] | None) -> Context
|
||||
```
|
||||
|
||||
|
||||
Extract trace context from an MCP request meta dict.
|
||||
|
||||
If already in a valid trace (e.g., from HTTP propagation), the existing
|
||||
trace context is preserved and meta is not used.
|
||||
|
||||
**Args:**
|
||||
- `meta`: The meta dict from an MCP request (ctx.request_context.meta)
|
||||
|
||||
**Returns:**
|
||||
- An OpenTelemetry Context with the extracted trace context,
|
||||
- or the current context if no trace context found or already in a trace
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
title: types
|
||||
sidebarTitle: types
|
||||
---
|
||||
|
||||
# `fastmcp.types`
|
||||
|
||||
|
||||
Reusable type annotations for FastMCP tool parameters.
|
||||
|
||||
These types can be used in tool function signatures to influence how
|
||||
parameters are presented in UIs (e.g. `fastmcp dev apps`) and
|
||||
serialized in JSON Schema.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
from fastmcp import FastMCP
|
||||
from fastmcp.types import Textarea
|
||||
|
||||
mcp = FastMCP("demo")
|
||||
|
||||
@mcp.tool()
|
||||
def run_query(sql: Textarea) -> str:
|
||||
...
|
||||
```
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: __init__
|
||||
sidebarTitle: __init__
|
||||
---
|
||||
|
||||
# `fastmcp.utilities`
|
||||
|
||||
|
||||
FastMCP utility modules.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: async_utils
|
||||
sidebarTitle: async_utils
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.async_utils`
|
||||
|
||||
|
||||
Async utilities for FastMCP.
|
||||
|
||||
## Functions
|
||||
|
||||
### `is_coroutine_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/async_utils.py#L14" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
is_coroutine_function(fn: Any) -> bool
|
||||
```
|
||||
|
||||
|
||||
Check if a callable is a coroutine function, unwrapping functools.partial.
|
||||
|
||||
``inspect.iscoroutinefunction`` returns ``False`` for
|
||||
``functools.partial`` objects wrapping an async function on Python < 3.12.
|
||||
This helper unwraps any layers of ``partial`` before checking.
|
||||
|
||||
|
||||
### `call_sync_fn_in_threadpool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/async_utils.py#L26" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
call_sync_fn_in_threadpool(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any
|
||||
```
|
||||
|
||||
|
||||
Call a sync function in a threadpool to avoid blocking the event loop.
|
||||
|
||||
Uses anyio.to_thread.run_sync which properly propagates contextvars,
|
||||
making this safe for functions that depend on context (like dependency injection).
|
||||
|
||||
|
||||
### `gather` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/async_utils.py#L51" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
gather(*awaitables: Awaitable[T]) -> list[T] | list[T | BaseException]
|
||||
```
|
||||
|
||||
|
||||
Run awaitables concurrently and return results in order.
|
||||
|
||||
Uses anyio TaskGroup for structured concurrency.
|
||||
|
||||
**Args:**
|
||||
- `*awaitables`: Awaitables to run concurrently
|
||||
- `return_exceptions`: If True, exceptions are returned in results.
|
||||
If False, first exception cancels all and raises.
|
||||
|
||||
**Returns:**
|
||||
- List of results in the same order as input awaitables.
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: auth
|
||||
sidebarTitle: auth
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.auth`
|
||||
|
||||
|
||||
Authentication utility helpers.
|
||||
|
||||
## Functions
|
||||
|
||||
### `decode_jwt_header` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/auth.py#L32" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
decode_jwt_header(token: str) -> dict[str, Any]
|
||||
```
|
||||
|
||||
|
||||
Decode JWT header without signature verification.
|
||||
|
||||
Useful for extracting the key ID (kid) for JWKS lookup.
|
||||
|
||||
**Args:**
|
||||
- `token`: JWT token string (header.payload.signature)
|
||||
|
||||
**Returns:**
|
||||
- Decoded header as a dictionary
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If token is not a valid JWT format
|
||||
|
||||
|
||||
### `decode_jwt_payload` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/auth.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
decode_jwt_payload(token: str) -> dict[str, Any]
|
||||
```
|
||||
|
||||
|
||||
Decode JWT payload without signature verification.
|
||||
|
||||
Use only for tokens received directly from trusted sources (e.g., IdP token endpoints).
|
||||
|
||||
**Args:**
|
||||
- `token`: JWT token string (header.payload.signature)
|
||||
|
||||
**Returns:**
|
||||
- Decoded payload as a dictionary
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If token is not a valid JWT format
|
||||
|
||||
|
||||
### `parse_scopes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/auth.py#L66" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
parse_scopes(value: Any) -> list[str] | None
|
||||
```
|
||||
|
||||
|
||||
Parse scopes from environment variables or settings values.
|
||||
|
||||
Accepts either a JSON array string, a comma- or space-separated string,
|
||||
a list of strings, or ``None``. Returns a list of scopes or ``None`` if
|
||||
no value is provided.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: authorization
|
||||
sidebarTitle: authorization
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.authorization`
|
||||
|
||||
|
||||
Authorization checks for FastMCP components.
|
||||
|
||||
Auth checks are callables that receive an ``AuthContext`` and return True to
|
||||
allow access or False to deny it. They can also raise ``AuthorizationError`` to
|
||||
deny with a custom message; other exceptions are masked and treated as denial.
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `require_scopes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L50" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
require_scopes(*scopes: str) -> AuthCheck
|
||||
```
|
||||
|
||||
|
||||
Require all of the given OAuth scopes.
|
||||
|
||||
|
||||
### `restrict_tag` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L62" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
restrict_tag(tag: str) -> AuthCheck
|
||||
```
|
||||
|
||||
|
||||
Require scopes when the accessed component has a specific tag.
|
||||
|
||||
|
||||
### `run_auth_checks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L76" 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.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `AuthContext` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Context passed to auth check callables.
|
||||
|
||||
**Attributes:**
|
||||
- `token`: The current access token, or None if unauthenticated.
|
||||
- `component`: The tool, resource, resource template, or prompt being accessed.
|
||||
- `tool`: Backwards-compatible alias for component when it is a Tool.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/authorization.py#L40" 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.
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: cli
|
||||
sidebarTitle: cli
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.cli`
|
||||
|
||||
## Functions
|
||||
|
||||
### `is_already_in_uv_subprocess` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/cli.py#L28" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
is_already_in_uv_subprocess() -> bool
|
||||
```
|
||||
|
||||
|
||||
Check if we're already running in a FastMCP uv subprocess.
|
||||
|
||||
|
||||
### `load_and_merge_config` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/cli.py#L33" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
load_and_merge_config(server_spec: str | None, **cli_overrides) -> tuple[MCPServerConfig, str]
|
||||
```
|
||||
|
||||
|
||||
Load config from server_spec and apply CLI overrides.
|
||||
|
||||
This consolidates the config parsing logic that was duplicated across
|
||||
run, inspect, and dev commands.
|
||||
|
||||
**Args:**
|
||||
- `server_spec`: Python file, config file, URL, or None to auto-detect
|
||||
- `cli_overrides`: CLI arguments that override config values
|
||||
|
||||
**Returns:**
|
||||
- Tuple of (MCPServerConfig, resolved_server_spec)
|
||||
|
||||
|
||||
### `log_server_banner` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/cli.py#L201" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
log_server_banner(server: FastMCP[Any]) -> None
|
||||
```
|
||||
|
||||
|
||||
Creates and logs a formatted banner with server information and logo.
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
---
|
||||
title: components
|
||||
sidebarTitle: components
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.components`
|
||||
|
||||
## Functions
|
||||
|
||||
### `get_fastmcp_metadata` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L26" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_fastmcp_metadata(meta: dict[str, Any] | None) -> FastMCPMeta
|
||||
```
|
||||
|
||||
|
||||
Extract FastMCP metadata from a component's meta dict.
|
||||
|
||||
Handles both the current `fastmcp` namespace and the legacy `_fastmcp`
|
||||
namespace for compatibility with older FastMCP servers.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `FastMCPMeta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L20" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
### `FastMCPComponent` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L74" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Base class for FastMCP tools, prompts, resources, and resource templates.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `make_key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L125" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
make_key(cls, identifier: str) -> str
|
||||
```
|
||||
|
||||
Construct the lookup key for this component type.
|
||||
|
||||
**Args:**
|
||||
- `identifier`: The raw identifier (name for tools/prompts, uri for resources)
|
||||
|
||||
**Returns:**
|
||||
- A prefixed key like "tool:name" or "resource:uri"
|
||||
|
||||
|
||||
#### `key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L139" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
key(self) -> str
|
||||
```
|
||||
|
||||
The globally unique lookup key for this component.
|
||||
|
||||
Format: "{key_prefix}:{identifier}@{version}" or "{key_prefix}:{identifier}@"
|
||||
e.g. "tool:my_tool@v2", "tool:my_tool@", "resource:file://x.txt@"
|
||||
|
||||
The @ suffix is ALWAYS present to enable unambiguous parsing of keys
|
||||
(URIs may contain @ characters, so we always include the delimiter).
|
||||
|
||||
Subclasses should override this to use their specific identifier.
|
||||
Base implementation uses name.
|
||||
|
||||
Prefer `.key` over ad-hoc `name or uri or uri_template` logic for any
|
||||
cross-component identity work (dedupe, grouping, collision detection,
|
||||
lookup tables). It encodes type, identifier, and version, so variants
|
||||
of the same component don't falsely collide with each other, and
|
||||
cross-type identifiers (e.g. a tool and a resource both named "foo")
|
||||
can't clash.
|
||||
|
||||
|
||||
#### `get_meta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L161" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_meta(self) -> dict[str, Any]
|
||||
```
|
||||
|
||||
Get the meta information about the component.
|
||||
|
||||
Returns a dict that always includes a `fastmcp` key containing:
|
||||
- `tags`: sorted list of component tags
|
||||
- `version`: component version (only if set)
|
||||
|
||||
Internal keys (prefixed with `_`) are stripped from the fastmcp namespace.
|
||||
|
||||
|
||||
#### `enable` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L209" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
enable(self) -> None
|
||||
```
|
||||
|
||||
Removed in 3.0. Use server.enable(keys=[...]) instead.
|
||||
|
||||
|
||||
#### `disable` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L216" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
disable(self) -> None
|
||||
```
|
||||
|
||||
Removed in 3.0. Use server.disable(keys=[...]) instead.
|
||||
|
||||
|
||||
#### `copy` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L223" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
copy(self) -> Self
|
||||
```
|
||||
|
||||
Create a copy of the component.
|
||||
|
||||
|
||||
#### `register_with_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L227" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
register_with_docket(self, docket: Docket) -> None
|
||||
```
|
||||
|
||||
Register this component with docket for background execution.
|
||||
|
||||
No-ops if task_config.mode is "forbidden". Subclasses override to
|
||||
register their callable (self.run, self.read, self.render, or self.fn).
|
||||
|
||||
|
||||
#### `coerce_task_arguments` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L235" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
coerce_task_arguments(self, arguments: dict[str, Any]) -> dict[str, Any]
|
||||
```
|
||||
|
||||
Validate and coerce task arguments before any task state is created.
|
||||
|
||||
Called by ``submit_to_docket`` up front, so invalid inputs raise before
|
||||
the task's Redis metadata and initial status notification exist —
|
||||
otherwise a coercion failure during queueing would orphan a task the
|
||||
client has already observed. The base implementation is a no-op;
|
||||
components that splat arguments into a typed Python callable (e.g.
|
||||
``FunctionTool``) override this to mirror the synchronous validation
|
||||
path.
|
||||
|
||||
|
||||
#### `add_to_docket` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L248" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
add_to_docket(self, docket: Docket, *args: Any, **kwargs: Any) -> Execution
|
||||
```
|
||||
|
||||
Schedule this component for background execution via docket.
|
||||
|
||||
Subclasses override this to handle their specific calling conventions:
|
||||
- Tool: add_to_docket(docket, arguments: dict, **kwargs)
|
||||
- Resource: add_to_docket(docket, **kwargs)
|
||||
- ResourceTemplate: add_to_docket(docket, params: dict, **kwargs)
|
||||
- Prompt: add_to_docket(docket, arguments: dict | None, **kwargs)
|
||||
|
||||
The **kwargs are passed through to docket.add() (e.g., key=task_key).
|
||||
|
||||
|
||||
#### `get_span_attributes` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/components.py#L270" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_span_attributes(self) -> dict[str, Any]
|
||||
```
|
||||
|
||||
Return span attributes for telemetry.
|
||||
|
||||
Subclasses should call super() and merge their specific attributes.
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
---
|
||||
title: docstring_parsing
|
||||
sidebarTitle: docstring_parsing
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.docstring_parsing`
|
||||
|
||||
|
||||
Extract descriptions from function docstrings.
|
||||
|
||||
Uses griffelib to parse Google, NumPy, and Sphinx-style docstrings. The
|
||||
interface is intentionally narrow — a single function returning a
|
||||
`ParsedDocstring` — so the implementation can be swapped without touching
|
||||
callers.
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `parse_docstring` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/docstring_parsing.py#L35" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
parse_docstring(fn: Callable[..., Any]) -> ParsedDocstring
|
||||
```
|
||||
|
||||
|
||||
Parse a function's docstring into a summary and parameter descriptions.
|
||||
|
||||
Tries Google, NumPy, and Sphinx parsers in order, using the first one that
|
||||
successfully extracts parameter descriptions. If none do, returns the full
|
||||
docstring as the description with no parameter descriptions.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `ParsedDocstring` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/docstring_parsing.py#L28" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
The extracted description and per-parameter descriptions from a docstring.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
title: exceptions
|
||||
sidebarTitle: exceptions
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.exceptions`
|
||||
|
||||
## Functions
|
||||
|
||||
### `iter_exc` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L12" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
iter_exc(group: BaseExceptionGroup)
|
||||
```
|
||||
|
||||
### `get_catch_handlers` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/exceptions.py#L42" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_catch_handlers() -> Mapping[type[BaseException] | Iterable[type[BaseException]], Callable[[BaseExceptionGroup[Any]], Any]]
|
||||
```
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
title: http
|
||||
sidebarTitle: http
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.http`
|
||||
|
||||
## Functions
|
||||
|
||||
### `find_available_port` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/http.py#L4" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
find_available_port(host: str = '127.0.0.1') -> int
|
||||
```
|
||||
|
||||
|
||||
Find an available port by letting the OS assign one.
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
---
|
||||
title: inspect
|
||||
sidebarTitle: inspect
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.inspect`
|
||||
|
||||
|
||||
Utilities for inspecting FastMCP instances.
|
||||
|
||||
## Functions
|
||||
|
||||
### `inspect_fastmcp_v2` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L100" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo
|
||||
```
|
||||
|
||||
|
||||
Extract information from a FastMCP v2.x instance.
|
||||
|
||||
**Args:**
|
||||
- `mcp`: The FastMCP v2.x instance to inspect
|
||||
|
||||
**Returns:**
|
||||
- FastMCPInfo dataclass containing the extracted information
|
||||
|
||||
|
||||
### `inspect_fastmcp_v1` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L236" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
inspect_fastmcp_v1(mcp: FastMCP1x) -> FastMCPInfo
|
||||
```
|
||||
|
||||
|
||||
Extract information from a FastMCP v1.x instance using a Client.
|
||||
|
||||
**Args:**
|
||||
- `mcp`: The FastMCP v1.x instance to inspect
|
||||
|
||||
**Returns:**
|
||||
- FastMCPInfo dataclass containing the extracted information
|
||||
|
||||
|
||||
### `inspect_fastmcp` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L378" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
inspect_fastmcp(mcp: FastMCP[Any] | FastMCP1x) -> FastMCPInfo
|
||||
```
|
||||
|
||||
|
||||
Extract information from a FastMCP instance into a dataclass.
|
||||
|
||||
This function automatically detects whether the instance is FastMCP v1.x or v2.x
|
||||
and uses the appropriate extraction method.
|
||||
|
||||
**Args:**
|
||||
- `mcp`: The FastMCP instance to inspect (v1.x or v2.x)
|
||||
|
||||
**Returns:**
|
||||
- FastMCPInfo dataclass containing the extracted information
|
||||
|
||||
|
||||
### `format_fastmcp_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L403" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
format_fastmcp_info(info: FastMCPInfo) -> bytes
|
||||
```
|
||||
|
||||
|
||||
Format FastMCPInfo as FastMCP-specific JSON.
|
||||
|
||||
This includes FastMCP-specific fields like tags, enabled, annotations, etc.
|
||||
|
||||
|
||||
### `format_mcp_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L432" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
format_mcp_info(mcp: FastMCP[Any] | FastMCP1x) -> bytes
|
||||
```
|
||||
|
||||
|
||||
Format server info as standard MCP protocol JSON.
|
||||
|
||||
Uses Client to get the standard MCP protocol format with camelCase fields.
|
||||
Includes version metadata at the top level.
|
||||
|
||||
|
||||
### `format_info` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L465" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
format_info(mcp: FastMCP[Any] | FastMCP1x, format: InspectFormat | Literal['fastmcp', 'mcp'], info: FastMCPInfo | None = None) -> bytes
|
||||
```
|
||||
|
||||
|
||||
Format server information according to the specified format.
|
||||
|
||||
**Args:**
|
||||
- `mcp`: The FastMCP instance
|
||||
- `format`: Output format ("fastmcp" or "mcp")
|
||||
- `info`: Pre-extracted FastMCPInfo (optional, will be extracted if not provided)
|
||||
|
||||
**Returns:**
|
||||
- JSON bytes in the requested format
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `ToolInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L19" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Information about a tool.
|
||||
|
||||
|
||||
### `PromptInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L35" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Information about a prompt.
|
||||
|
||||
|
||||
### `ResourceInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Information about a resource.
|
||||
|
||||
|
||||
### `TemplateInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L65" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Information about a resource template.
|
||||
|
||||
|
||||
### `FastMCPInfo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L82" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Information extracted from a FastMCP instance.
|
||||
|
||||
|
||||
### `InspectFormat` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/inspect.py#L396" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Output format for inspect command.
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
title: json_schema
|
||||
sidebarTitle: json_schema
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.json_schema`
|
||||
|
||||
## Functions
|
||||
|
||||
### `require_discriminator_property` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L116" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
require_discriminator_property(schema: dict[str, Any]) -> dict[str, Any]
|
||||
```
|
||||
|
||||
|
||||
Keep an OpenAPI discriminator's tag mandatory after the keyword is dropped.
|
||||
|
||||
Returns a copy of *schema* with ``discriminator.propertyName`` added to each
|
||||
``anyOf``/``oneOf`` variant's ``required`` list. A Pydantic discriminated
|
||||
union whose tag has a default omits that tag from ``required``; without this,
|
||||
an untagged payload passes the generated schema but fails later in the source
|
||||
model with ``union_tag_not_found``. No-op if there is no string
|
||||
``propertyName``.
|
||||
|
||||
|
||||
### `dereference_refs` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L147" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
dereference_refs(schema: dict[str, Any]) -> dict[str, Any]
|
||||
```
|
||||
|
||||
|
||||
Resolve all $ref references in a JSON schema by inlining definitions.
|
||||
|
||||
This function resolves $ref references that point to $defs, replacing them
|
||||
with the actual definition content while preserving sibling keywords (like
|
||||
description, default, examples) that Pydantic places alongside $ref.
|
||||
|
||||
This is necessary because some MCP clients (e.g., VS Code Copilot) don't
|
||||
properly handle $ref in tool input schemas.
|
||||
|
||||
For self-referencing/circular schemas where full dereferencing is not possible,
|
||||
this function falls back to resolving only the root-level $ref while preserving
|
||||
$defs for nested references.
|
||||
|
||||
Only local ``$ref`` values (those starting with ``#``) are resolved.
|
||||
Remote URIs (``http://``, ``file://``, etc.) are stripped before
|
||||
resolution to prevent SSRF / local-file-inclusion attacks when proxying
|
||||
schemas from untrusted servers.
|
||||
|
||||
**Args:**
|
||||
- `schema`: JSON schema dict that may contain $ref references
|
||||
|
||||
**Returns:**
|
||||
- A new schema dict with $ref resolved where possible and $defs removed
|
||||
- when no longer needed
|
||||
|
||||
|
||||
### `resolve_root_ref` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L294" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
resolve_root_ref(schema: dict[str, Any]) -> dict[str, Any]
|
||||
```
|
||||
|
||||
|
||||
Resolve $ref at root level to meet MCP spec requirements.
|
||||
|
||||
MCP specification requires outputSchema to have "type": "object" at the root level.
|
||||
When Pydantic generates schemas for self-referential models, it uses $ref at the
|
||||
root level pointing to $defs. This function resolves such references by inlining
|
||||
the referenced definition while preserving $defs for nested references.
|
||||
|
||||
**Args:**
|
||||
- `schema`: JSON schema dict that may have $ref at root level
|
||||
|
||||
**Returns:**
|
||||
- A new schema dict with root-level $ref resolved, or the original schema
|
||||
- if no resolution is needed
|
||||
|
||||
|
||||
### `compress_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema.py#L688" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
compress_schema(schema: dict[str, Any], prune_params: list[str] | None = None, prune_additional_properties: bool = False, prune_titles: bool = False, dereference: bool = False) -> dict[str, Any]
|
||||
```
|
||||
|
||||
|
||||
Compress and optimize a JSON schema for MCP compatibility.
|
||||
|
||||
**Args:**
|
||||
- `schema`: The schema to compress
|
||||
- `prune_params`: List of parameter names to remove from properties
|
||||
- `prune_additional_properties`: Whether to remove additionalProperties\: false.
|
||||
Defaults to False to maintain MCP client compatibility, as some clients
|
||||
(e.g., Claude) require additionalProperties\: false for strict validation.
|
||||
- `prune_titles`: Whether to remove title fields from the schema
|
||||
- `dereference`: Whether to dereference $ref by inlining definitions.
|
||||
Defaults to False; dereferencing is typically handled by
|
||||
middleware at serve-time instead.
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
---
|
||||
title: json_schema_type
|
||||
sidebarTitle: json_schema_type
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.json_schema_type`
|
||||
|
||||
|
||||
Convert JSON Schema to Python types with validation.
|
||||
|
||||
The json_schema_to_type function converts a JSON Schema into a Python type that can be used
|
||||
for validation with Pydantic. It supports:
|
||||
|
||||
- Basic types (string, number, integer, boolean, null)
|
||||
- Complex types (arrays, objects)
|
||||
- Format constraints (date-time, email, uri)
|
||||
- Numeric constraints (minimum, maximum, multipleOf)
|
||||
- String constraints (minLength, maxLength, pattern)
|
||||
- Array constraints (minItems, maxItems, uniqueItems)
|
||||
- Object properties with defaults
|
||||
- References and recursive schemas
|
||||
- Enums and constants
|
||||
- Union types
|
||||
|
||||
## Unsupported regex patterns
|
||||
|
||||
Pydantic uses a Rust-based regex engine that does not support all regex
|
||||
features found in real-world JSON Schemas (particularly those from AWS,
|
||||
Azure, and other large OpenAPI providers). Unsupported constructs include
|
||||
lookahead/lookbehind assertions (`(?!...)`, `(?<=...)`), Unicode property
|
||||
escapes (`\p{Graph}`, `\p{Print}`), and very large compiled patterns.
|
||||
|
||||
When a `pattern` constraint cannot be compiled, `json_schema_to_type`
|
||||
degrades gracefully:
|
||||
|
||||
1. The pattern is **dropped** from the Pydantic `StringConstraints` so
|
||||
the type will not raise a `SchemaError`.
|
||||
2. A `UserWarning` is emitted with the unsupported pattern.
|
||||
3. The original pattern is preserved in the type metadata as
|
||||
`x-unsupported-pattern` (visible via `TypeAdapter(T).json_schema()`).
|
||||
4. Other constraints (`minLength`, `maxLength`) are still enforced.
|
||||
|
||||
Example:
|
||||
```python
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string", "minLength": 1},
|
||||
"age": {"type": "integer", "minimum": 0},
|
||||
"email": {"type": "string", "format": "email"}
|
||||
},
|
||||
"required": ["name", "age"]
|
||||
}
|
||||
|
||||
# Name is optional and will be inferred from schema's "title" property if not provided
|
||||
Person = json_schema_to_type(schema)
|
||||
# Creates a validated dataclass with name, age, and optional email fields
|
||||
```
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `json_schema_to_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema_type.py#L164" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
json_schema_to_type(schema: Mapping[str, Any] | bool, name: str | None = None) -> type
|
||||
```
|
||||
|
||||
|
||||
Convert JSON schema to appropriate Python type with validation.
|
||||
|
||||
**Args:**
|
||||
- `schema`: A JSON Schema dictionary defining the type structure and validation rules.
|
||||
Boolean schemas are also accepted (``True`` = any type, ``False`` = unsatisfiable).
|
||||
- `name`: Optional name for object schemas. Only allowed when schema type is "object".
|
||||
If not provided for objects, name will be inferred from schema's "title"
|
||||
property or default to "Root".
|
||||
|
||||
**Returns:**
|
||||
- A Python type (typically a dataclass for objects) with Pydantic validation
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If a name is provided for a non-object schema
|
||||
|
||||
**Examples:**
|
||||
|
||||
Create a dataclass from an object schema:
|
||||
```python
|
||||
schema = {
|
||||
"type": "object",
|
||||
"title": "Person",
|
||||
"properties": {
|
||||
"name": {"type": "string", "minLength": 1},
|
||||
"age": {"type": "integer", "minimum": 0},
|
||||
"email": {"type": "string", "format": "email"}
|
||||
},
|
||||
"required": ["name", "age"]
|
||||
}
|
||||
|
||||
Person = json_schema_to_type(schema)
|
||||
# Creates a dataclass with name, age, and optional email fields:
|
||||
# @dataclass
|
||||
# class Person:
|
||||
# name: str
|
||||
# age: int
|
||||
# email: str | None = None
|
||||
```
|
||||
Person(name="John", age=30)
|
||||
|
||||
Create a scalar type with constraints:
|
||||
```python
|
||||
schema = {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"pattern": "^[A-Z][a-z]+$"
|
||||
}
|
||||
|
||||
NameType = json_schema_to_type(schema)
|
||||
# Creates Annotated[str, StringConstraints(min_length=3, pattern="^[A-Z][a-z]+$")]
|
||||
|
||||
@dataclass
|
||||
class Name:
|
||||
name: NameType
|
||||
```
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `JSONSchema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/json_schema_type.py#L131" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
@@ -0,0 +1,36 @@
|
||||
---
|
||||
title: lifespan
|
||||
sidebarTitle: lifespan
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.lifespan`
|
||||
|
||||
|
||||
Lifespan utilities for combining async context manager lifespans.
|
||||
|
||||
## Functions
|
||||
|
||||
### `combine_lifespans` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/lifespan.py#L12" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
combine_lifespans(*lifespans: Callable[[AppT], AbstractAsyncContextManager[Mapping[str, Any] | None]]) -> Callable[[AppT], AbstractAsyncContextManager[dict[str, Any]]]
|
||||
```
|
||||
|
||||
|
||||
Combine multiple lifespans into a single lifespan.
|
||||
|
||||
Useful when mounting FastMCP into FastAPI and you need to run
|
||||
both your app's lifespan and the MCP server's lifespan.
|
||||
|
||||
Works with both FastAPI-style lifespans (yield None) and FastMCP-style
|
||||
lifespans (yield dict). Results are merged; later lifespans override
|
||||
earlier ones on key conflicts.
|
||||
|
||||
Lifespans are entered in order and exited in reverse order (LIFO).
|
||||
|
||||
**Args:**
|
||||
- `*lifespans`: Lifespan context manager factories to combine.
|
||||
|
||||
**Returns:**
|
||||
- A combined lifespan context manager factory.
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: logging
|
||||
sidebarTitle: logging
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.logging`
|
||||
|
||||
|
||||
Logging utilities for FastMCP.
|
||||
|
||||
## Functions
|
||||
|
||||
### `get_logger` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L14" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_logger(name: str) -> logging.Logger
|
||||
```
|
||||
|
||||
|
||||
Get a logger nested under FastMCP namespace.
|
||||
|
||||
**Args:**
|
||||
- `name`: the name of the logger, which will be prefixed with 'FastMCP.'
|
||||
|
||||
**Returns:**
|
||||
- a configured logger instance
|
||||
|
||||
|
||||
### `configure_logging` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
configure_logging(level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | int = 'INFO', logger: logging.Logger | None = None, enable_rich_tracebacks: bool | None = None, **rich_kwargs: Any) -> None
|
||||
```
|
||||
|
||||
|
||||
Configure logging for FastMCP.
|
||||
|
||||
**Args:**
|
||||
- `logger`: the logger to configure
|
||||
- `level`: the log level to use
|
||||
- `rich_kwargs`: the parameters to use for creating RichHandler
|
||||
|
||||
|
||||
### `temporary_log_level` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/logging.py#L117" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
temporary_log_level(level: str | None, logger: logging.Logger | None = None, enable_rich_tracebacks: bool | None = None, **rich_kwargs: Any)
|
||||
```
|
||||
|
||||
|
||||
Context manager to temporarily set log level and restore it afterwards.
|
||||
|
||||
**Args:**
|
||||
- `level`: The temporary log level to set (e.g., "DEBUG", "INFO")
|
||||
- `logger`: Optional logger to configure (defaults to FastMCP logger)
|
||||
- `enable_rich_tracebacks`: Whether to enable rich tracebacks
|
||||
- `**rich_kwargs`: Additional parameters for RichHandler
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
title: __init__
|
||||
sidebarTitle: __init__
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config`
|
||||
|
||||
|
||||
FastMCP Configuration module.
|
||||
|
||||
This module provides versioned configuration support for FastMCP servers.
|
||||
The current version is v1, which is re-exported here for convenience.
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: __init__
|
||||
sidebarTitle: __init__
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config.v1.environments`
|
||||
|
||||
|
||||
Environment configuration for MCP servers.
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
title: base
|
||||
sidebarTitle: base
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config.v1.environments.base`
|
||||
|
||||
## Classes
|
||||
|
||||
### `Environment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/environments/base.py#L7" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Base class for environment configuration.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `build_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/environments/base.py#L13" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
build_command(self, command: list[str]) -> list[str]
|
||||
```
|
||||
|
||||
Build the full command with environment setup.
|
||||
|
||||
**Args:**
|
||||
- `command`: Base command to wrap with environment setup
|
||||
|
||||
**Returns:**
|
||||
- Full command ready for subprocess execution
|
||||
|
||||
|
||||
#### `prepare` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/environments/base.py#L23" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
prepare(self, output_dir: Path | None = None) -> None
|
||||
```
|
||||
|
||||
Prepare the environment (optional, can be no-op).
|
||||
|
||||
**Args:**
|
||||
- `output_dir`: Directory for persistent environment setup
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: uv
|
||||
sidebarTitle: uv
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config.v1.environments.uv`
|
||||
|
||||
## Classes
|
||||
|
||||
### `UVEnvironment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/environments/uv.py#L14" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Configuration for Python environment setup.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `build_command` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/environments/uv.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
build_command(self, command: list[str]) -> list[str]
|
||||
```
|
||||
|
||||
Build complete uv run command with environment args and command to execute.
|
||||
|
||||
**Args:**
|
||||
- `command`: Command to execute (e.g., ["fastmcp", "run", "server.py"])
|
||||
|
||||
**Returns:**
|
||||
- Complete command ready for subprocess.run, including "uv" prefix if needed.
|
||||
- If no environment configuration is set, returns the command unchanged.
|
||||
|
||||
|
||||
#### `prepare` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/environments/uv.py#L109" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
prepare(self, output_dir: Path | None = None) -> None
|
||||
```
|
||||
|
||||
Prepare the Python environment using uv.
|
||||
|
||||
**Args:**
|
||||
- `output_dir`: Directory where the persistent uv project will be created.
|
||||
If None, creates a temporary directory for ephemeral use.
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
---
|
||||
title: mcp_server_config
|
||||
sidebarTitle: mcp_server_config
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config.v1.mcp_server_config`
|
||||
|
||||
|
||||
FastMCP Configuration File Support.
|
||||
|
||||
This module provides support for fastmcp.json configuration files that allow
|
||||
users to specify server settings in a declarative format instead of using
|
||||
command-line arguments.
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `generate_schema` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L416" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
generate_schema(output_path: Path | str | None = None) -> dict[str, Any] | None
|
||||
```
|
||||
|
||||
|
||||
Generate JSON schema for fastmcp.json files.
|
||||
|
||||
This is used to create the schema file that IDEs can use for
|
||||
validation and auto-completion.
|
||||
|
||||
**Args:**
|
||||
- `output_path`: Optional path to write the schema to. If provided,
|
||||
writes the schema and returns None. If not provided,
|
||||
returns the schema as a dictionary.
|
||||
|
||||
**Returns:**
|
||||
- JSON schema as a dictionary if output_path is None, otherwise None
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `Deployment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Configuration for server deployment and runtime settings.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `apply_runtime_settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L85" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
apply_runtime_settings(self, config_path: Path | None = None) -> None
|
||||
```
|
||||
|
||||
Apply runtime settings like environment variables and working directory.
|
||||
|
||||
**Args:**
|
||||
- `config_path`: Path to config file for resolving relative paths
|
||||
|
||||
Environment variables support interpolation with ${VAR_NAME} syntax.
|
||||
For example: "API_URL": "https://api.${ENVIRONMENT}.example.com"
|
||||
will substitute the value of the ENVIRONMENT variable at runtime.
|
||||
|
||||
|
||||
### `MCPServerConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L134" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Configuration for a FastMCP server.
|
||||
|
||||
This configuration file allows you to specify all settings needed to run
|
||||
a FastMCP server in a declarative format.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `validate_source` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L183" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
validate_source(cls, v: dict | Source) -> SourceType
|
||||
```
|
||||
|
||||
Validate and convert source to proper format.
|
||||
|
||||
Supports:
|
||||
- Dict format: `{"path": "server.py", "entrypoint": "app"}`
|
||||
- FileSystemSource instance (passed through)
|
||||
|
||||
No string parsing happens here - that's only at CLI boundaries.
|
||||
MCPServerConfig works only with properly typed objects.
|
||||
|
||||
|
||||
#### `validate_environment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L199" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
validate_environment(cls, v: dict | Any) -> EnvironmentType
|
||||
```
|
||||
|
||||
Ensure environment has a type field for discrimination.
|
||||
|
||||
For backward compatibility, if no type is specified, default to "uv".
|
||||
|
||||
|
||||
#### `validate_deployment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L210" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
validate_deployment(cls, v: dict | Deployment) -> Deployment
|
||||
```
|
||||
|
||||
Validate and convert deployment to Deployment.
|
||||
|
||||
Accepts:
|
||||
- Deployment instance
|
||||
- dict that can be converted to Deployment
|
||||
|
||||
|
||||
#### `from_file` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L223" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
from_file(cls, file_path: Path) -> MCPServerConfig
|
||||
```
|
||||
|
||||
Load configuration from a JSON file.
|
||||
|
||||
**Args:**
|
||||
- `file_path`: Path to the configuration file
|
||||
|
||||
**Returns:**
|
||||
- MCPServerConfig instance
|
||||
|
||||
**Raises:**
|
||||
- `FileNotFoundError`: If the file doesn't exist
|
||||
- `json.JSONDecodeError`: If the file is not valid JSON
|
||||
- `pydantic.ValidationError`: If the configuration is invalid
|
||||
|
||||
|
||||
#### `from_cli_args` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L246" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
from_cli_args(cls, source: FileSystemSource, transport: Literal['stdio', 'http', 'sse', 'streamable-http'] | None = None, host: str | None = None, port: int | None = None, path: str | None = None, log_level: Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] | None = None, python: str | None = None, dependencies: list[str] | None = None, requirements: str | None = None, project: str | None = None, editable: str | None = None, env: dict[str, str] | None = None, cwd: str | None = None, args: list[str] | None = None) -> MCPServerConfig
|
||||
```
|
||||
|
||||
Create a config from CLI arguments.
|
||||
|
||||
This allows us to have a single code path where everything
|
||||
goes through a config object.
|
||||
|
||||
**Args:**
|
||||
- `source`: Server source (FileSystemSource instance)
|
||||
- `transport`: Transport protocol
|
||||
- `host`: Host for HTTP transport
|
||||
- `port`: Port for HTTP transport
|
||||
- `path`: URL path for server
|
||||
- `log_level`: Logging level
|
||||
- `python`: Python version
|
||||
- `dependencies`: Python packages to install
|
||||
- `requirements`: Path to requirements file
|
||||
- `project`: Path to project directory
|
||||
- `editable`: Path to install in editable mode
|
||||
- `env`: Environment variables
|
||||
- `cwd`: Working directory
|
||||
- `args`: Server arguments
|
||||
|
||||
**Returns:**
|
||||
- MCPServerConfig instance
|
||||
|
||||
|
||||
#### `find_config` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L323" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
find_config(cls, start_path: Path | None = None) -> Path | None
|
||||
```
|
||||
|
||||
Find a fastmcp.json file in the specified directory.
|
||||
|
||||
**Args:**
|
||||
- `start_path`: Directory to look in (defaults to current directory)
|
||||
|
||||
**Returns:**
|
||||
- Path to the configuration file, or None if not found
|
||||
|
||||
|
||||
#### `prepare` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L342" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
prepare(self, skip_source: bool = False, output_dir: Path | None = None) -> None
|
||||
```
|
||||
|
||||
Prepare environment and source for execution.
|
||||
|
||||
When output_dir is provided, creates a persistent uv project.
|
||||
When output_dir is None, does ephemeral caching (for backwards compatibility).
|
||||
|
||||
**Args:**
|
||||
- `skip_source`: Skip source preparation if True
|
||||
- `output_dir`: Directory to create the persistent uv project in (optional)
|
||||
|
||||
|
||||
#### `prepare_environment` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L363" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
prepare_environment(self, output_dir: Path | None = None) -> None
|
||||
```
|
||||
|
||||
Prepare the Python environment.
|
||||
|
||||
**Args:**
|
||||
- `output_dir`: If provided, creates a persistent uv project in this directory.
|
||||
If None, just populates uv's cache for ephemeral use.
|
||||
|
||||
Delegates to the environment's prepare() method
|
||||
|
||||
|
||||
#### `prepare_source` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L374" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
prepare_source(self) -> None
|
||||
```
|
||||
|
||||
Prepare the source for loading.
|
||||
|
||||
Delegates to the source's prepare() method.
|
||||
|
||||
|
||||
#### `run_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py#L381" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
run_server(self, **kwargs: Any) -> None
|
||||
```
|
||||
|
||||
Load and run the server with this configuration.
|
||||
|
||||
**Args:**
|
||||
- `**kwargs`: Additional arguments to pass to server.run_async()
|
||||
These override config settings
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
title: base
|
||||
sidebarTitle: base
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config.v1.sources.base`
|
||||
|
||||
## Classes
|
||||
|
||||
### `Source` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/sources/base.py#L7" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Abstract base class for all source types.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `prepare` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/sources/base.py#L12" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
prepare(self) -> None
|
||||
```
|
||||
|
||||
Prepare the source (download, clone, install, etc).
|
||||
|
||||
For sources that need preparation (e.g., git clone, download),
|
||||
this method performs that preparation. For sources that don't
|
||||
need preparation (e.g., local files), this is a no-op.
|
||||
|
||||
|
||||
#### `load_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/sources/base.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
load_server(self) -> Any
|
||||
```
|
||||
|
||||
Load and return the FastMCP server instance.
|
||||
|
||||
Must be called after prepare() if the source requires preparation.
|
||||
All information needed to load the server should be available
|
||||
as attributes on the source instance.
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
title: filesystem
|
||||
sidebarTitle: filesystem
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mcp_server_config.v1.sources.filesystem`
|
||||
|
||||
## Classes
|
||||
|
||||
### `FileSystemSource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py#L16" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Source for local Python files.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `parse_path_with_object` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py#L29" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
parse_path_with_object(cls, v: str) -> str
|
||||
```
|
||||
|
||||
Parse path:object syntax and extract the object name.
|
||||
|
||||
This validator runs before the model is created, allowing us to
|
||||
handle the "file.py:object" syntax at the model boundary.
|
||||
|
||||
|
||||
#### `load_server` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/sources/filesystem.py#L64" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
load_server(self) -> Any
|
||||
```
|
||||
|
||||
Load server from filesystem.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
---
|
||||
title: mime
|
||||
sidebarTitle: mime
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.mime`
|
||||
|
||||
|
||||
MIME type constants and helpers for MCP Apps UI resources.
|
||||
|
||||
This module has no dependencies on the server or resource packages,
|
||||
so it can be safely imported from anywhere.
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `resolve_ui_mime_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/mime.py#L10" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
resolve_ui_mime_type(uri: str, explicit_mime_type: str | None) -> str | None
|
||||
```
|
||||
|
||||
|
||||
Return the appropriate MIME type for a resource URI.
|
||||
|
||||
For ``ui://`` scheme resources, defaults to ``UI_MIME_TYPE`` when no
|
||||
explicit MIME type is provided.
|
||||
|
||||
**Args:**
|
||||
- `uri`: The resource URI string
|
||||
- `explicit_mime_type`: The MIME type explicitly provided by the user
|
||||
|
||||
**Returns:**
|
||||
- The resolved MIME type (explicit value, UI default, or None)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
---
|
||||
title: openapi
|
||||
sidebarTitle: openapi
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.openapi`
|
||||
|
||||
|
||||
OpenAPI utilities for FastMCP - refactored for better maintainability.
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
title: pagination
|
||||
sidebarTitle: pagination
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.pagination`
|
||||
|
||||
|
||||
Pagination utilities for MCP list operations.
|
||||
|
||||
## Functions
|
||||
|
||||
### `paginate_sequence` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/pagination.py#L50" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
paginate_sequence(items: Sequence[T], cursor: str | None, page_size: int) -> tuple[list[T], str | None]
|
||||
```
|
||||
|
||||
|
||||
Paginate a sequence of items.
|
||||
|
||||
**Args:**
|
||||
- `items`: The full sequence to paginate.
|
||||
- `cursor`: Optional cursor from a previous request. None for first page.
|
||||
- `page_size`: Maximum number of items per page.
|
||||
|
||||
**Returns:**
|
||||
- Tuple of (page_items, next_cursor). next_cursor is None if no more pages.
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If the cursor is invalid.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `CursorState` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/pagination.py#L16" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Internal representation of pagination cursor state.
|
||||
|
||||
The cursor encodes the offset into the result set. This is opaque to clients
|
||||
per the MCP spec - they should not parse or modify cursors.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `encode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/pagination.py#L25" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
encode(self) -> str
|
||||
```
|
||||
|
||||
Encode cursor state to an opaque string.
|
||||
|
||||
|
||||
#### `decode` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/pagination.py#L31" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
decode(cls, cursor: str) -> CursorState
|
||||
```
|
||||
|
||||
Decode cursor from an opaque string.
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If the cursor is invalid or malformed.
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
title: skills
|
||||
sidebarTitle: skills
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.skills`
|
||||
|
||||
|
||||
Client utilities for discovering and downloading skills from MCP servers.
|
||||
|
||||
## Functions
|
||||
|
||||
### `list_skills` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L43" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
list_skills(client: Client) -> list[SkillSummary]
|
||||
```
|
||||
|
||||
|
||||
List all available skills from an MCP server.
|
||||
|
||||
Discovers skills by finding resources with URIs matching the
|
||||
`skill://{name}/SKILL.md` pattern.
|
||||
|
||||
**Args:**
|
||||
- `client`: Connected FastMCP client
|
||||
|
||||
**Returns:**
|
||||
- List of SkillSummary objects with name, description, and URI
|
||||
|
||||
|
||||
### `get_skill_manifest` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L87" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_skill_manifest(client: Client, skill_name: str) -> SkillManifest
|
||||
```
|
||||
|
||||
|
||||
Get the manifest for a specific skill.
|
||||
|
||||
**Args:**
|
||||
- `client`: Connected FastMCP client
|
||||
- `skill_name`: Name of the skill
|
||||
|
||||
**Returns:**
|
||||
- SkillManifest with file listing
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If manifest cannot be read or parsed
|
||||
|
||||
|
||||
### `download_skill` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L127" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
download_skill(client: Client, skill_name: str, target_dir: str | Path) -> Path
|
||||
```
|
||||
|
||||
|
||||
Download a skill and all its files to a local directory.
|
||||
|
||||
Creates a subdirectory named after the skill containing all files.
|
||||
|
||||
**Args:**
|
||||
- `client`: Connected FastMCP client
|
||||
- `skill_name`: Name of the skill to download
|
||||
- `target_dir`: Directory where skill folder will be created
|
||||
- `overwrite`: If True, overwrite existing skill directory. If False
|
||||
(default), raise FileExistsError if directory exists.
|
||||
|
||||
**Returns:**
|
||||
- Path to the downloaded skill directory
|
||||
|
||||
**Raises:**
|
||||
- `ValueError`: If skill cannot be found or downloaded
|
||||
- `FileExistsError`: If skill directory exists and overwrite=False
|
||||
|
||||
|
||||
### `sync_skills` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L218" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
sync_skills(client: Client, target_dir: str | Path) -> list[Path]
|
||||
```
|
||||
|
||||
|
||||
Download all available skills from a server.
|
||||
|
||||
**Args:**
|
||||
- `client`: Connected FastMCP client
|
||||
- `target_dir`: Directory where skill folders will be created
|
||||
- `overwrite`: If True, overwrite existing files
|
||||
|
||||
**Returns:**
|
||||
- List of paths to downloaded skill directories
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `SkillSummary` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L18" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Summary information about a skill available on a server.
|
||||
|
||||
|
||||
### `SkillFile` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L27" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Information about a file within a skill.
|
||||
|
||||
|
||||
### `SkillManifest` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/skills.py#L36" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Full manifest of a skill including all files.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
title: tasks
|
||||
sidebarTitle: tasks
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.tasks`
|
||||
|
||||
|
||||
Task configuration primitives for FastMCP components.
|
||||
|
||||
## Classes
|
||||
|
||||
### `TaskMeta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tasks.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Metadata for task-augmented execution requests.
|
||||
|
||||
**Attributes:**
|
||||
- `ttl`: Client-requested TTL in milliseconds. If None, uses server default.
|
||||
- `fn_key`: Docket routing key. Auto-derived from component name if None.
|
||||
|
||||
|
||||
### `TaskConfig` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tasks.py#L35" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Configuration for MCP background task execution.
|
||||
|
||||
Controls how a component handles task-augmented requests:
|
||||
|
||||
- ``forbidden``: Component does not support task execution.
|
||||
- ``optional``: Component supports both synchronous and task execution.
|
||||
- ``required``: Component requires task execution.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `from_bool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tasks.py#L49" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
from_bool(cls, value: bool) -> TaskConfig
|
||||
```
|
||||
|
||||
Convert a boolean task flag to a TaskConfig.
|
||||
|
||||
|
||||
#### `supports_tasks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tasks.py#L53" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
supports_tasks(self) -> bool
|
||||
```
|
||||
|
||||
Check if this component supports task execution.
|
||||
|
||||
|
||||
#### `validate_function` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tasks.py#L57" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
validate_function(self, fn: Callable[..., Any], name: str) -> None
|
||||
```
|
||||
|
||||
Validate that a function is compatible with this task config.
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: tests
|
||||
sidebarTitle: tests
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.tests`
|
||||
|
||||
## Functions
|
||||
|
||||
### `temporary_settings` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tests.py#L24" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
temporary_settings(**kwargs: Any)
|
||||
```
|
||||
|
||||
|
||||
Temporarily override FastMCP setting values.
|
||||
|
||||
**Args:**
|
||||
- `**kwargs`: The settings to override, including nested settings.
|
||||
|
||||
|
||||
### `run_server_in_process` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tests.py#L75" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
run_server_in_process(server_fn: Callable[..., None], *args: Any, **kwargs: Any) -> Generator[str, None, None]
|
||||
```
|
||||
|
||||
|
||||
Context manager that runs a FastMCP server in a separate process and
|
||||
returns the server URL. When the context manager is exited, the server process is killed.
|
||||
|
||||
**Args:**
|
||||
- `server_fn`: The function that runs a FastMCP server. FastMCP servers are
|
||||
not pickleable, so we need a function that creates and runs one.
|
||||
- `*args`: Arguments to pass to the server function.
|
||||
- `provide_host_and_port`: Whether to provide the host and port to the server function as kwargs.
|
||||
- `host`: Host to bind the server to (default\: "127.0.0.1").
|
||||
- `port`: Port to bind the server to (default\: find available port).
|
||||
- `**kwargs`: Keyword arguments to pass to the server function.
|
||||
|
||||
**Returns:**
|
||||
- The server URL.
|
||||
|
||||
|
||||
### `run_server_async` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tests.py#L143" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
run_server_async(server: FastMCP, port: int | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http', path: str = '/mcp', host: str = '127.0.0.1') -> AsyncGenerator[str, None]
|
||||
```
|
||||
|
||||
|
||||
Start a FastMCP server as an asyncio task for in-process async testing.
|
||||
|
||||
This is the recommended way to test FastMCP servers. It runs the server
|
||||
as an async task in the same process, eliminating subprocess coordination,
|
||||
sleeps, and cleanup issues.
|
||||
|
||||
**Args:**
|
||||
- `server`: FastMCP server instance
|
||||
- `port`: Port to bind to (default\: find available port)
|
||||
- `transport`: Transport type ("http", "streamable-http", or "sse")
|
||||
- `path`: URL path for the server (default\: "/mcp")
|
||||
- `host`: Host to bind to (default\: "127.0.0.1")
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `HeadlessOAuth` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tests.py#L225" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
OAuth provider that bypasses browser interaction for testing.
|
||||
|
||||
This simulates the complete OAuth flow programmatically by making HTTP requests
|
||||
instead of opening a browser and running a callback server. Useful for automated testing.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `redirect_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tests.py#L238" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
redirect_handler(self, authorization_url: str) -> None
|
||||
```
|
||||
|
||||
Make HTTP request to authorization URL and store response for callback handler.
|
||||
|
||||
|
||||
#### `callback_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/tests.py#L244" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
callback_handler(self) -> tuple[str, str | None]
|
||||
```
|
||||
|
||||
Parse stored response and return (auth_code, state).
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: timeout
|
||||
sidebarTitle: timeout
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.timeout`
|
||||
|
||||
|
||||
Timeout normalization utilities.
|
||||
|
||||
## Functions
|
||||
|
||||
### `normalize_timeout_to_timedelta` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/timeout.py#L8" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
normalize_timeout_to_timedelta(value: int | float | datetime.timedelta | None) -> datetime.timedelta | None
|
||||
```
|
||||
|
||||
|
||||
Normalize a timeout value to a timedelta.
|
||||
|
||||
**Args:**
|
||||
- `value`: Timeout value as int/float (seconds), timedelta, or None
|
||||
|
||||
**Returns:**
|
||||
- timedelta if value provided, None otherwise
|
||||
|
||||
|
||||
### `normalize_timeout_to_seconds` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/timeout.py#L28" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
normalize_timeout_to_seconds(value: int | float | datetime.timedelta | None) -> float | None
|
||||
```
|
||||
|
||||
|
||||
Normalize a timeout value to seconds (float).
|
||||
|
||||
**Args:**
|
||||
- `value`: Timeout value as int/float (seconds), timedelta, or None.
|
||||
Zero values are treated as "disabled" and return None.
|
||||
|
||||
**Returns:**
|
||||
- float seconds if value provided and non-zero, None otherwise
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: token_cache
|
||||
sidebarTitle: token_cache
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.token_cache`
|
||||
|
||||
|
||||
In-memory cache for token verification results.
|
||||
|
||||
Provides a generic TTL-based cache for ``AccessToken`` objects, designed to
|
||||
reduce repeated network calls during opaque-token verification. Only
|
||||
*successful* verifications should be cached; errors and failures must be
|
||||
retried on every request.
|
||||
|
||||
Example:
|
||||
```python
|
||||
from fastmcp.utilities.token_cache import TokenCache
|
||||
|
||||
cache = TokenCache(ttl_seconds=300, max_size=10000)
|
||||
|
||||
# On cache miss, call the upstream verifier and store the result.
|
||||
hit, token = cache.get(raw_token)
|
||||
if not hit:
|
||||
token = await _call_upstream(raw_token)
|
||||
if token is not None:
|
||||
cache.set(raw_token, token)
|
||||
```
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `TokenCache` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/token_cache.py#L46" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
TTL-based in-memory cache for ``AccessToken`` objects.
|
||||
|
||||
Features:
|
||||
- SHA-256 hashed cache keys (fixed size, regardless of token length).
|
||||
- Per-entry TTL that respects both the configured ``ttl_seconds`` and the
|
||||
token's own ``expires_at`` claim (whichever is sooner).
|
||||
- Bounded size with FIFO eviction when the cache is full.
|
||||
- Periodic cleanup of expired entries to prevent unbounded growth.
|
||||
- Defensive deep copies on both store and retrieve to prevent
|
||||
callers from mutating cached values.
|
||||
|
||||
Caching is disabled when ``ttl_seconds`` is ``None`` or ``0``, or
|
||||
when ``max_size`` is ``0``. Negative values raise ``ValueError``.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `enabled` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/token_cache.py#L89" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
enabled(self) -> bool
|
||||
```
|
||||
|
||||
Return whether caching is active.
|
||||
|
||||
|
||||
#### `get` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/token_cache.py#L95" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get(self, token: str) -> tuple[bool, AccessToken | None]
|
||||
```
|
||||
|
||||
Look up a cached verification result.
|
||||
|
||||
**Returns:**
|
||||
- ``(True, AccessToken)`` on a cache hit, ``(False, None)`` on a miss
|
||||
- or when caching is disabled. The returned ``AccessToken`` is a deep
|
||||
- copy that is safe to mutate.
|
||||
|
||||
|
||||
#### `set` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/token_cache.py#L118" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
set(self, token: str, result: AccessToken) -> None
|
||||
```
|
||||
|
||||
Store a *successful* verification result.
|
||||
|
||||
Only successful verifications should be cached. Failures (inactive
|
||||
tokens, missing scopes, HTTP errors, timeouts) must **not** be cached
|
||||
so that transient problems do not produce sticky false negatives.
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
---
|
||||
title: types
|
||||
sidebarTitle: types
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.types`
|
||||
|
||||
|
||||
Common types used across FastMCP.
|
||||
|
||||
## Functions
|
||||
|
||||
### `get_fn_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L34" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_fn_name(fn: Callable[..., Any]) -> str
|
||||
```
|
||||
|
||||
### `get_cached_typeadapter` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L45" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_cached_typeadapter(cls: T) -> TypeAdapter[T]
|
||||
```
|
||||
|
||||
|
||||
TypeAdapters are heavy objects, and in an application context we'd typically
|
||||
create them once in a global scope and reuse them as often as possible.
|
||||
However, this isn't feasible for user-generated functions. Instead, we use a
|
||||
cache to minimize the cost of creating them as much as possible.
|
||||
|
||||
|
||||
### `issubclass_safe` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L123" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
issubclass_safe(cls: type, base: type) -> bool
|
||||
```
|
||||
|
||||
|
||||
Check if cls is a subclass of base, even if cls is a type variable.
|
||||
|
||||
|
||||
### `is_class_member_of_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L133" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
is_class_member_of_type(cls: Any, base: type) -> bool
|
||||
```
|
||||
|
||||
|
||||
Check if cls is a member of base, even if cls is a type variable.
|
||||
|
||||
Base can be a type, a UnionType, or an Annotated type. Generic types are not
|
||||
considered members (e.g. T is not a member of list\[T]).
|
||||
|
||||
|
||||
### `find_kwarg_by_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L155" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
find_kwarg_by_type(fn: Callable, kwarg_type: type) -> str | None
|
||||
```
|
||||
|
||||
|
||||
Find the name of the kwarg that is of type kwarg_type.
|
||||
|
||||
Includes union types that contain the kwarg_type, as well as Annotated types.
|
||||
|
||||
|
||||
### `create_function_without_params` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L181" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_function_without_params(fn: Callable[..., Any], exclude_params: list[str]) -> Callable[..., Any]
|
||||
```
|
||||
|
||||
|
||||
Create a new function with the same code but without the specified parameters in annotations.
|
||||
|
||||
This is used to exclude parameters from type adapter processing when they can't be serialized.
|
||||
The excluded parameters are removed from the function's __annotations__ dictionary.
|
||||
|
||||
|
||||
### `replace_type` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L454" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
replace_type(type_, type_map: dict[type, type])
|
||||
```
|
||||
|
||||
|
||||
Given a (possibly generic, nested, or otherwise complex) type, replaces all
|
||||
instances of keys in type_map with their corresponding values.
|
||||
|
||||
This is useful for transforming types when creating tools.
|
||||
|
||||
**Args:**
|
||||
- `type_`: The type to transform.
|
||||
- `type_map`: A mapping of types to replace (keys are replaced by values).
|
||||
|
||||
Examples:
|
||||
```python
|
||||
>>> replace_type(list[int | bool], {int: str})
|
||||
list[str | bool]
|
||||
|
||||
>>> replace_type(list[list[int]], {int: str})
|
||||
list[list[str]]
|
||||
```
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `FastMCPBaseModel` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L38" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Base model for FastMCP models.
|
||||
|
||||
|
||||
### `Image` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L238" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Helper class for returning images from tools.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `to_image_content` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
to_image_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.ImageContent
|
||||
```
|
||||
|
||||
Convert to MCP ImageContent.
|
||||
|
||||
|
||||
#### `to_data_uri` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L304" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
to_data_uri(self, mime_type: str | None = None) -> str
|
||||
```
|
||||
|
||||
Get image as a data URI.
|
||||
|
||||
|
||||
### `Audio` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L310" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Helper class for returning audio from tools.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `to_audio_content` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L347" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
to_audio_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.AudioContent
|
||||
```
|
||||
|
||||
### `File` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L368" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Helper class for returning file data from tools.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `to_resource_content` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L407" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
to_resource_content(self, mime_type: str | None = None, annotations: Annotations | None = None) -> mcp.types.EmbeddedResource
|
||||
```
|
||||
|
||||
### `ContextSamplingFallbackProtocol` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/types.py#L490" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
@@ -0,0 +1,140 @@
|
||||
---
|
||||
title: ui
|
||||
sidebarTitle: ui
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.ui`
|
||||
|
||||
|
||||
|
||||
Shared UI utilities for FastMCP HTML pages.
|
||||
|
||||
This module provides reusable HTML/CSS components for OAuth callbacks,
|
||||
consent pages, and other user-facing interfaces.
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `create_page` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L453" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_page(content: str, title: str = 'FastMCP', additional_styles: str = '', csp_policy: str = "default-src 'none'; style-src 'unsafe-inline'; img-src https: data:; base-uri 'none'") -> str
|
||||
```
|
||||
|
||||
|
||||
Create a complete HTML page with FastMCP styling.
|
||||
|
||||
**Args:**
|
||||
- `content`: HTML content to place inside the page
|
||||
- `title`: Page title
|
||||
- `additional_styles`: Extra CSS to include
|
||||
- `csp_policy`: Content Security Policy header value.
|
||||
If empty string "", the CSP meta tag is omitted entirely.
|
||||
|
||||
**Returns:**
|
||||
- Complete HTML page as string
|
||||
|
||||
|
||||
### `create_logo` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L501" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_logo(icon_url: str | None = None, alt_text: str = 'FastMCP') -> str
|
||||
```
|
||||
|
||||
|
||||
Create logo HTML.
|
||||
|
||||
**Args:**
|
||||
- `icon_url`: Optional custom icon URL. If not provided, uses the FastMCP logo.
|
||||
- `alt_text`: Alt text for the logo image.
|
||||
|
||||
**Returns:**
|
||||
- HTML for logo image tag.
|
||||
|
||||
|
||||
### `create_status_message` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L516" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_status_message(message: str, is_success: bool = True) -> str
|
||||
```
|
||||
|
||||
|
||||
Create a status message with icon.
|
||||
|
||||
**Args:**
|
||||
- `message`: Status message text
|
||||
- `is_success`: True for success (✓), False for error (✕)
|
||||
|
||||
**Returns:**
|
||||
- HTML for status message
|
||||
|
||||
|
||||
### `create_info_box` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L539" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_info_box(content: str, is_error: bool = False, centered: bool = False, monospace: bool = False) -> str
|
||||
```
|
||||
|
||||
|
||||
Create an info box.
|
||||
|
||||
**Args:**
|
||||
- `content`: HTML content for the info box
|
||||
- `is_error`: True for error styling, False for normal
|
||||
- `centered`: True to center the text, False for left-aligned
|
||||
- `monospace`: True to use gray monospace font styling instead of blue
|
||||
|
||||
**Returns:**
|
||||
- HTML for info box
|
||||
|
||||
|
||||
### `create_detail_box` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L568" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_detail_box(rows: list[tuple[str, str]]) -> str
|
||||
```
|
||||
|
||||
|
||||
Create a detail box with key-value pairs.
|
||||
|
||||
**Args:**
|
||||
- `rows`: List of (label, value) tuples
|
||||
|
||||
**Returns:**
|
||||
- HTML for detail box
|
||||
|
||||
|
||||
### `create_button_group` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L591" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_button_group(buttons: list[tuple[str, str, str]]) -> str
|
||||
```
|
||||
|
||||
|
||||
Create a group of buttons.
|
||||
|
||||
**Args:**
|
||||
- `buttons`: List of (text, value, css_class) tuples
|
||||
|
||||
**Returns:**
|
||||
- HTML for button group
|
||||
|
||||
|
||||
### `create_secure_html_response` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/ui.py#L609" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
create_secure_html_response(html: str, status_code: int = 200) -> HTMLResponse
|
||||
```
|
||||
|
||||
|
||||
Create an HTMLResponse with security headers.
|
||||
|
||||
Adds X-Frame-Options: DENY to prevent clickjacking attacks per MCP security best practices.
|
||||
|
||||
**Args:**
|
||||
- `html`: HTML content to return
|
||||
- `status_code`: HTTP status code
|
||||
|
||||
**Returns:**
|
||||
- HTMLResponse with security headers
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: version_check
|
||||
sidebarTitle: version_check
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.version_check`
|
||||
|
||||
|
||||
Version checking utilities for FastMCP.
|
||||
|
||||
## Functions
|
||||
|
||||
### `get_latest_version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/version_check.py#L98" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
get_latest_version(include_prereleases: bool = False) -> str | None
|
||||
```
|
||||
|
||||
|
||||
Get the latest version of FastMCP from PyPI, using cache when available.
|
||||
|
||||
**Args:**
|
||||
- `include_prereleases`: If True, include pre-release versions.
|
||||
|
||||
**Returns:**
|
||||
- The latest version string, or None if unavailable.
|
||||
|
||||
|
||||
### `check_for_newer_version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/version_check.py#L124" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
check_for_newer_version() -> str | None
|
||||
```
|
||||
|
||||
|
||||
Check if a newer version of FastMCP is available.
|
||||
|
||||
**Returns:**
|
||||
- The latest version string if newer than current, None otherwise.
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
---
|
||||
title: versions
|
||||
sidebarTitle: versions
|
||||
---
|
||||
|
||||
# `fastmcp.utilities.versions`
|
||||
|
||||
|
||||
Version comparison utilities for component versioning.
|
||||
|
||||
This module provides utilities for comparing component versions. Versions are
|
||||
strings that are first attempted to be parsed as PEP 440 versions (using the
|
||||
`packaging` library), falling back to lexicographic string comparison.
|
||||
|
||||
Examples:
|
||||
- "1", "2", "10" → parsed as PEP 440, compared semantically (1 < 2 < 10)
|
||||
- "1.0", "2.0" → parsed as PEP 440
|
||||
- "v1.0" → 'v' prefix stripped, parsed as "1.0"
|
||||
- "2025-01-15" → not valid PEP 440, compared as strings
|
||||
- None → sorts lowest (unversioned components)
|
||||
|
||||
|
||||
## Functions
|
||||
|
||||
### `parse_version_key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L197" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
parse_version_key(version: str | None) -> VersionKey
|
||||
```
|
||||
|
||||
|
||||
Parse a version string into a sortable key.
|
||||
|
||||
**Args:**
|
||||
- `version`: The version string, or None for unversioned.
|
||||
|
||||
**Returns:**
|
||||
- A VersionKey suitable for sorting.
|
||||
|
||||
|
||||
### `version_sort_key` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L209" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
version_sort_key(component: FastMCPComponent) -> tuple[VersionKey, str]
|
||||
```
|
||||
|
||||
|
||||
Get a sort key for a component based on its version.
|
||||
|
||||
Use with sorted() or max() to order components by version.
|
||||
|
||||
The key is a `(VersionKey, raw)` tuple. The `VersionKey` orders by PEP 440
|
||||
semantics (or lexicographically for non-PEP 440 strings); the raw version
|
||||
string is a deterministic tie-breaker so that two components whose versions
|
||||
are PEP 440-equivalent but spelled differently (e.g. `"1"` and `"1.0"`) are
|
||||
ordered reproducibly instead of by registration order. The raw tie-breaker
|
||||
only affects equivalent-version ties and never the primary version order,
|
||||
so range/equality matching (which uses `VersionKey` directly) is unchanged.
|
||||
|
||||
**Args:**
|
||||
- `component`: The component to get a sort key for.
|
||||
|
||||
**Returns:**
|
||||
- A deterministic, sortable `(VersionKey, raw)` tuple.
|
||||
|
||||
|
||||
### `compare_versions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L237" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
compare_versions(a: str | None, b: str | None) -> int
|
||||
```
|
||||
|
||||
|
||||
Compare two version strings.
|
||||
|
||||
**Args:**
|
||||
- `a`: First version string (or None).
|
||||
- `b`: Second version string (or None).
|
||||
|
||||
**Returns:**
|
||||
- -1 if a < b, 0 if a == b, 1 if a > b.
|
||||
|
||||
|
||||
### `is_version_greater` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L259" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
is_version_greater(a: str | None, b: str | None) -> bool
|
||||
```
|
||||
|
||||
|
||||
Check if version a is greater than version b.
|
||||
|
||||
**Args:**
|
||||
- `a`: First version string (or None).
|
||||
- `b`: Second version string (or None).
|
||||
|
||||
**Returns:**
|
||||
- True if a > b, False otherwise.
|
||||
|
||||
|
||||
### `max_version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L272" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
max_version(a: str | None, b: str | None) -> str | None
|
||||
```
|
||||
|
||||
|
||||
Return the greater of two versions.
|
||||
|
||||
**Args:**
|
||||
- `a`: First version string (or None).
|
||||
- `b`: Second version string (or None).
|
||||
|
||||
**Returns:**
|
||||
- The greater version, or None if both are None.
|
||||
|
||||
|
||||
### `min_version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
min_version(a: str | None, b: str | None) -> str | None
|
||||
```
|
||||
|
||||
|
||||
Return the lesser of two versions.
|
||||
|
||||
**Args:**
|
||||
- `a`: First version string (or None).
|
||||
- `b`: Second version string (or None).
|
||||
|
||||
**Returns:**
|
||||
- The lesser version, or None if both are None.
|
||||
|
||||
|
||||
### `dedupe_with_versions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L306" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
dedupe_with_versions(components: Sequence[C], key_fn: Callable[[C], str]) -> list[C]
|
||||
```
|
||||
|
||||
|
||||
Deduplicate components by key, keeping highest version.
|
||||
|
||||
Groups components by key, selects the highest version from each group,
|
||||
and injects available versions into meta if any component is versioned.
|
||||
|
||||
**Args:**
|
||||
- `components`: Sequence of components to deduplicate.
|
||||
- `key_fn`: Function to extract the grouping key from a component.
|
||||
|
||||
**Returns:**
|
||||
- Deduplicated list with versions injected into meta.
|
||||
|
||||
|
||||
## Classes
|
||||
|
||||
### `VersionSpec` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L31" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
Specification for filtering components by version.
|
||||
|
||||
Used by transforms and providers to filter components to a specific
|
||||
version or version range. Unversioned components (version=None) always
|
||||
match any spec.
|
||||
|
||||
**Args:**
|
||||
- `gte`: If set, only versions >= this value match.
|
||||
- `lt`: If set, only versions < this value match.
|
||||
- `eq`: If set, only this exact version matches (gte/lt ignored).
|
||||
Matching is PEP 440-normalized and `v`-prefix insensitive, so
|
||||
`eq="v1.0"` matches a component versioned `"1.0"`, and `eq="1.0"`
|
||||
matches `"1"` (PEP 440 treats `1` and `1.0` as the same version).
|
||||
If a server registers two PEP 440-equivalent spellings of the
|
||||
same component (e.g. both `"1"` and `"1.0"`), they are the same
|
||||
version under this spec; selection among them is deterministic
|
||||
(see `version_sort_key`), not registration-order dependent.
|
||||
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `matches` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L55" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
matches(self, version: str | None) -> bool
|
||||
```
|
||||
|
||||
Check if a version matches this spec.
|
||||
|
||||
**Args:**
|
||||
- `version`: The version to check, or None for unversioned.
|
||||
- `match_none`: Whether unversioned (None) components match. Defaults to True
|
||||
for backward compatibility with retrieval operations. Set to False
|
||||
when filtering (e.g., enable/disable) to exclude unversioned components
|
||||
from version-specific rules.
|
||||
|
||||
**Returns:**
|
||||
- True if the version matches the spec.
|
||||
|
||||
|
||||
#### `intersect` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L88" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
```python
|
||||
intersect(self, other: VersionSpec | None) -> VersionSpec
|
||||
```
|
||||
|
||||
Return a spec that satisfies both this spec and other.
|
||||
|
||||
Used by transforms to combine caller constraints with filter constraints.
|
||||
For example, if a VersionFilter has lt="3.0" and caller requests eq="1.0",
|
||||
the intersection validates "1.0" is in range and returns the exact spec.
|
||||
|
||||
**Args:**
|
||||
- `other`: Another spec to intersect with, or None.
|
||||
|
||||
**Returns:**
|
||||
- A VersionSpec that matches only versions satisfying both specs.
|
||||
|
||||
|
||||
### `VersionKey` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/utilities/versions.py#L124" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
||||
|
||||
|
||||
A comparable version key that handles None, PEP 440 versions, and strings.
|
||||
|
||||
Comparison order:
|
||||
1. None (unversioned) sorts lowest
|
||||
2. PEP 440 versions sort by semantic version order
|
||||
3. Invalid versions (strings) sort lexicographically
|
||||
4. When comparing PEP 440 vs string, PEP 440 comes first
|
||||
|
||||
Reference in New Issue
Block a user