mirror of
https://github.com/PrefectHQ/fastmcp.git
synced 2026-08-10 07:39:10 +02:00
* Switch to new OpenAPI parser as default Remove the legacy OpenAPI parser and make the experimental parser the default. The experimental parser (introduced in 2.11) offers better performance, improved compatibility, and a more maintainable architecture. - Delete legacy parser (server/openapi.py, utilities/openapi.py) - Move experimental parser to main locations - Remove enable_new_openapi_parser feature flag - Update documentation to remove experimental references * Add deprecation stubs for experimental OpenAPI imports * Add deprecated enable_new_openapi_parser setting and deprecation tests * SDK docs * REview comments * Fix docstrings * Update docstring * Review comments * Fix broken links
786 lines
30 KiB
Text
786 lines
30 KiB
Text
---
|
|
title: server
|
|
sidebarTitle: server
|
|
---
|
|
|
|
# `fastmcp.server.server`
|
|
|
|
|
|
FastMCP - A more ergonomic interface for MCP servers.
|
|
|
|
## Functions
|
|
|
|
### `default_lifespan` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
default_lifespan(server: FastMCP[LifespanResultT]) -> AsyncIterator[Any]
|
|
```
|
|
|
|
|
|
Default lifespan context manager that does nothing.
|
|
|
|
**Args:**
|
|
- `server`: The server instance this lifespan is managing
|
|
|
|
**Returns:**
|
|
- An empty dictionary as the lifespan result.
|
|
|
|
|
|
### `add_resource_prefix` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2454" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_resource_prefix(uri: str, prefix: str) -> str
|
|
```
|
|
|
|
|
|
Add a prefix to a resource URI using path formatting (resource://prefix/path).
|
|
|
|
**Args:**
|
|
- `uri`: The original resource URI
|
|
- `prefix`: The prefix to add
|
|
|
|
**Returns:**
|
|
- The resource URI with the prefix added
|
|
|
|
**Examples:**
|
|
|
|
```python
|
|
add_resource_prefix("resource://path/to/resource", "prefix")
|
|
"resource://prefix/path/to/resource"
|
|
```
|
|
With absolute path:
|
|
```python
|
|
add_resource_prefix("resource:///absolute/path", "prefix")
|
|
"resource://prefix//absolute/path"
|
|
```
|
|
|
|
**Raises:**
|
|
- `ValueError`: If the URI doesn't match the expected protocol\://path format
|
|
|
|
|
|
### `remove_resource_prefix` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2492" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
remove_resource_prefix(uri: str, prefix: str) -> str
|
|
```
|
|
|
|
|
|
Remove a prefix from a resource URI.
|
|
|
|
**Args:**
|
|
- `uri`: The resource URI with a prefix
|
|
- `prefix`: The prefix to remove
|
|
|
|
**Returns:**
|
|
- The resource URI with the prefix removed
|
|
|
|
**Examples:**
|
|
|
|
```python
|
|
remove_resource_prefix("resource://prefix/path/to/resource", "prefix")
|
|
"resource://path/to/resource"
|
|
```
|
|
With absolute path:
|
|
```python
|
|
remove_resource_prefix("resource://prefix//absolute/path", "prefix")
|
|
"resource:///absolute/path"
|
|
```
|
|
|
|
**Raises:**
|
|
- `ValueError`: If the URI doesn't match the expected protocol\://path format
|
|
|
|
|
|
### `has_resource_prefix` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2536" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
has_resource_prefix(uri: str, prefix: str) -> bool
|
|
```
|
|
|
|
|
|
Check if a resource URI has a specific prefix.
|
|
|
|
**Args:**
|
|
- `uri`: The resource URI to check
|
|
- `prefix`: The prefix to look for
|
|
|
|
**Returns:**
|
|
- True if the URI has the specified prefix, False otherwise
|
|
|
|
**Examples:**
|
|
|
|
```python
|
|
has_resource_prefix("resource://prefix/path/to/resource", "prefix")
|
|
True
|
|
```
|
|
With other path:
|
|
```python
|
|
has_resource_prefix("resource://other/path/to/resource", "prefix")
|
|
False
|
|
```
|
|
|
|
**Raises:**
|
|
- `ValueError`: If the URI doesn't match the expected protocol\://path format
|
|
|
|
|
|
## Classes
|
|
|
|
### `FastMCP` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L140" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
**Methods:**
|
|
|
|
#### `settings` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L316" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
settings(self) -> Settings
|
|
```
|
|
|
|
#### `name` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L327" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
name(self) -> str
|
|
```
|
|
|
|
#### `instructions` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L331" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
instructions(self) -> str | None
|
|
```
|
|
|
|
#### `instructions` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L335" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
instructions(self, value: str | None) -> None
|
|
```
|
|
|
|
#### `version` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L339" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
version(self) -> str | None
|
|
```
|
|
|
|
#### `website_url` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L343" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
website_url(self) -> str | None
|
|
```
|
|
|
|
#### `icons` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L347" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
icons(self) -> list[mcp.types.Icon]
|
|
```
|
|
|
|
#### `run_async` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L374" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
run_async(self, transport: Transport | None = None, show_banner: bool = True, **transport_kwargs: Any) -> None
|
|
```
|
|
|
|
Run the FastMCP server asynchronously.
|
|
|
|
**Args:**
|
|
- `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http")
|
|
|
|
|
|
#### `run` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L404" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
run(self, transport: Transport | None = None, show_banner: bool = True, **transport_kwargs: Any) -> None
|
|
```
|
|
|
|
Run the FastMCP server. Note this is a synchronous function.
|
|
|
|
**Args:**
|
|
- `transport`: Transport protocol to use ("stdio", "sse", or "streamable-http")
|
|
|
|
|
|
#### `add_middleware` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L448" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_middleware(self, middleware: Middleware) -> None
|
|
```
|
|
|
|
#### `get_tools` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L451" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_tools(self) -> dict[str, Tool]
|
|
```
|
|
|
|
Get all tools (unfiltered), including mounted servers, indexed by key.
|
|
|
|
|
|
#### `get_tool` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L471" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_tool(self, key: str) -> Tool
|
|
```
|
|
|
|
#### `get_resources` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L477" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_resources(self) -> dict[str, Resource]
|
|
```
|
|
|
|
Get all resources (unfiltered), including mounted servers, indexed by key.
|
|
|
|
|
|
#### `get_resource` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L508" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_resource(self, key: str) -> Resource
|
|
```
|
|
|
|
#### `get_resource_templates` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L514" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_resource_templates(self) -> dict[str, ResourceTemplate]
|
|
```
|
|
|
|
Get all resource templates (unfiltered), including mounted servers, indexed by key.
|
|
|
|
|
|
#### `get_resource_template` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L545" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_resource_template(self, key: str) -> ResourceTemplate
|
|
```
|
|
|
|
Get a registered resource template by key.
|
|
|
|
|
|
#### `get_prompts` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L552" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_prompts(self) -> dict[str, Prompt]
|
|
```
|
|
|
|
Get all prompts (unfiltered), including mounted servers, indexed by key.
|
|
|
|
|
|
#### `get_prompt` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L572" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
get_prompt(self, key: str) -> Prompt
|
|
```
|
|
|
|
#### `custom_route` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L578" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
custom_route(self, path: str, methods: list[str], name: str | None = None, include_in_schema: bool = True) -> Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]]
|
|
```
|
|
|
|
Decorator to register a custom HTTP route on the FastMCP server.
|
|
|
|
Allows adding arbitrary HTTP endpoints outside the standard MCP protocol,
|
|
which can be useful for OAuth callbacks, health checks, or admin APIs.
|
|
The handler function must be an async function that accepts a Starlette
|
|
Request and returns a Response.
|
|
|
|
**Args:**
|
|
- `path`: URL path for the route (e.g., "/auth/callback")
|
|
- `methods`: List of HTTP methods to support (e.g., ["GET", "POST"])
|
|
- `name`: Optional name for the route (to reference this route with
|
|
Starlette's reverse URL lookup feature)
|
|
- `include_in_schema`: Whether to include in OpenAPI schema, defaults to True
|
|
|
|
|
|
#### `add_tool` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1264" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_tool(self, tool: Tool) -> Tool
|
|
```
|
|
|
|
Add a tool to the server.
|
|
|
|
The tool function can optionally request a Context object by adding a parameter
|
|
with the Context type annotation. See the @tool decorator for examples.
|
|
|
|
**Args:**
|
|
- `tool`: The Tool instance to register
|
|
|
|
**Returns:**
|
|
- The tool instance that was added to the server.
|
|
|
|
|
|
#### `remove_tool` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1289" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
remove_tool(self, name: str) -> None
|
|
```
|
|
|
|
Remove a tool from the server.
|
|
|
|
**Args:**
|
|
- `name`: The name of the tool to remove
|
|
|
|
**Raises:**
|
|
- `NotFoundError`: If the tool is not found
|
|
|
|
|
|
#### `add_tool_transformation` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1309" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_tool_transformation(self, tool_name: str, transformation: ToolTransformConfig) -> None
|
|
```
|
|
|
|
Add a tool transformation.
|
|
|
|
|
|
#### `remove_tool_transformation` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1315" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
remove_tool_transformation(self, tool_name: str) -> None
|
|
```
|
|
|
|
Remove a tool transformation.
|
|
|
|
|
|
#### `tool` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1320" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
tool(self, name_or_fn: AnyFunction) -> FunctionTool
|
|
```
|
|
|
|
#### `tool` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1337" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
tool(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionTool]
|
|
```
|
|
|
|
#### `tool` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1353" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
tool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool
|
|
```
|
|
|
|
Decorator to register a tool.
|
|
|
|
Tools can optionally request a Context object by adding a parameter with the
|
|
Context type annotation. The context provides access to MCP capabilities like
|
|
logging, progress reporting, and resource access.
|
|
|
|
This decorator supports multiple calling patterns:
|
|
- @server.tool (without parentheses)
|
|
- @server.tool (with empty parentheses)
|
|
- @server.tool("custom_name") (with name as first argument)
|
|
- @server.tool(name="custom_name") (with name as keyword argument)
|
|
- server.tool(function, name="custom_name") (direct function call)
|
|
|
|
**Args:**
|
|
- `name_or_fn`: Either a function (when used as @tool), a string name, or None
|
|
- `name`: Optional name for the tool (keyword-only, alternative to name_or_fn)
|
|
- `description`: Optional description of what the tool does
|
|
- `tags`: Optional set of tags for categorizing the tool
|
|
- `output_schema`: Optional JSON schema for the tool's output
|
|
- `annotations`: Optional annotations about the tool's behavior
|
|
- `exclude_args`: Optional list of argument names to exclude from the tool schema.
|
|
Note\: `exclude_args` will be deprecated in FastMCP 2.14 in favor of dependency
|
|
injection with `Depends()` for better lifecycle management.
|
|
- `meta`: Optional meta information about the tool
|
|
- `enabled`: Optional boolean to enable or disable the tool
|
|
|
|
**Examples:**
|
|
|
|
Register a tool with a custom name:
|
|
```python
|
|
@server.tool
|
|
def my_tool(x: int) -> str:
|
|
return str(x)
|
|
|
|
# Register a tool with a custom name
|
|
@server.tool
|
|
def my_tool(x: int) -> str:
|
|
return str(x)
|
|
|
|
@server.tool("custom_name")
|
|
def my_tool(x: int) -> str:
|
|
return str(x)
|
|
|
|
@server.tool(name="custom_name")
|
|
def my_tool(x: int) -> str:
|
|
return str(x)
|
|
|
|
# Direct function call
|
|
server.tool(my_function, name="custom_name")
|
|
```
|
|
|
|
|
|
#### `add_resource` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1490" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_resource(self, resource: Resource) -> Resource
|
|
```
|
|
|
|
Add a resource to the server.
|
|
|
|
**Args:**
|
|
- `resource`: A Resource instance to add
|
|
|
|
**Returns:**
|
|
- The resource instance that was added to the server.
|
|
|
|
|
|
#### `add_template` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1512" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_template(self, template: ResourceTemplate) -> ResourceTemplate
|
|
```
|
|
|
|
Add a resource template to the server.
|
|
|
|
**Args:**
|
|
- `template`: A ResourceTemplate instance to add
|
|
|
|
**Returns:**
|
|
- The template instance that was added to the server.
|
|
|
|
|
|
#### `resource` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1534" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
resource(self, uri: str) -> Callable[[AnyFunction], Resource | ResourceTemplate]
|
|
```
|
|
|
|
Decorator to register a function as a resource.
|
|
|
|
The function will be called when the resource is read to generate its content.
|
|
The function can return:
|
|
- str for text content
|
|
- bytes for binary content
|
|
- other types will be converted to JSON
|
|
|
|
Resources can optionally request a Context object by adding a parameter with the
|
|
Context type annotation. The context provides access to MCP capabilities like
|
|
logging, progress reporting, and session information.
|
|
|
|
If the URI contains parameters (e.g. "resource://{param}") or the function
|
|
has parameters, it will be registered as a template resource.
|
|
|
|
**Args:**
|
|
- `uri`: URI for the resource (e.g. "resource\://my-resource" or "resource\://{param}")
|
|
- `name`: Optional name for the resource
|
|
- `description`: Optional description of the resource
|
|
- `mime_type`: Optional MIME type for the resource
|
|
- `tags`: Optional set of tags for categorizing the resource
|
|
- `enabled`: Optional boolean to enable or disable the resource
|
|
- `annotations`: Optional annotations about the resource's behavior
|
|
- `meta`: Optional meta information about the resource
|
|
|
|
**Examples:**
|
|
|
|
Register a resource with a custom name:
|
|
```python
|
|
@server.resource("resource://my-resource")
|
|
def get_data() -> str:
|
|
return "Hello, world!"
|
|
|
|
@server.resource("resource://my-resource")
|
|
async get_data() -> str:
|
|
data = await fetch_data()
|
|
return f"Hello, world! {data}"
|
|
|
|
@server.resource("resource://{city}/weather")
|
|
def get_weather(city: str) -> str:
|
|
return f"Weather for {city}"
|
|
|
|
@server.resource("resource://{city}/weather")
|
|
async def get_weather_with_context(city: str, ctx: Context) -> str:
|
|
await ctx.info(f"Fetching weather for {city}")
|
|
return f"Weather for {city}"
|
|
|
|
@server.resource("resource://{city}/weather")
|
|
async def get_weather(city: str) -> str:
|
|
data = await fetch_weather(city)
|
|
return f"Weather for {city}: {data}"
|
|
```
|
|
|
|
|
|
#### `add_prompt` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1674" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
add_prompt(self, prompt: Prompt) -> Prompt
|
|
```
|
|
|
|
Add a prompt to the server.
|
|
|
|
**Args:**
|
|
- `prompt`: A Prompt instance to add
|
|
|
|
**Returns:**
|
|
- The prompt instance that was added to the server.
|
|
|
|
|
|
#### `prompt` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1697" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
prompt(self, name_or_fn: AnyFunction) -> FunctionPrompt
|
|
```
|
|
|
|
#### `prompt` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1711" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
prompt(self, name_or_fn: str | None = None) -> Callable[[AnyFunction], FunctionPrompt]
|
|
```
|
|
|
|
#### `prompt` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1724" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
prompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt
|
|
```
|
|
|
|
Decorator to register a prompt.
|
|
|
|
Prompts can optionally request a Context object by adding a parameter with the
|
|
Context type annotation. The context provides access to MCP capabilities like
|
|
logging, progress reporting, and session information.
|
|
|
|
This decorator supports multiple calling patterns:
|
|
- @server.prompt (without parentheses)
|
|
- @server.prompt() (with empty parentheses)
|
|
- @server.prompt("custom_name") (with name as first argument)
|
|
- @server.prompt(name="custom_name") (with name as keyword argument)
|
|
- server.prompt(function, name="custom_name") (direct function call)
|
|
|
|
Args:
|
|
name_or_fn: Either a function (when used as @prompt), a string name, or None
|
|
name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
|
|
description: Optional description of what the prompt does
|
|
tags: Optional set of tags for categorizing the prompt
|
|
enabled: Optional boolean to enable or disable the prompt
|
|
meta: Optional meta information about the prompt
|
|
|
|
Examples:
|
|
|
|
```python
|
|
@server.prompt
|
|
def analyze_table(table_name: str) -> list[Message]:
|
|
schema = read_table_schema(table_name)
|
|
return [
|
|
{
|
|
"role": "user",
|
|
"content": f"Analyze this schema:
|
|
{schema}"
|
|
}
|
|
]
|
|
|
|
@server.prompt()
|
|
async def analyze_with_context(table_name: str, ctx: Context) -> list[Message]:
|
|
await ctx.info(f"Analyzing table {table_name}")
|
|
schema = read_table_schema(table_name)
|
|
return [
|
|
{
|
|
"role": "user",
|
|
"content": f"Analyze this schema:
|
|
{schema}"
|
|
}
|
|
]
|
|
|
|
@server.prompt("custom_name")
|
|
async def analyze_file(path: str) -> list[Message]:
|
|
content = await read_file(path)
|
|
return [
|
|
{
|
|
"role": "user",
|
|
"content": {
|
|
"type": "resource",
|
|
"resource": {
|
|
"uri": f"file://{path}",
|
|
"text": content
|
|
}
|
|
}
|
|
}
|
|
]
|
|
|
|
@server.prompt(name="custom_name")
|
|
def another_prompt(data: str) -> list[Message]:
|
|
return [{"role": "user", "content": data}]
|
|
|
|
# Direct function call
|
|
server.prompt(my_function, name="custom_name")
|
|
```
|
|
|
|
|
|
#### `run_stdio_async` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1868" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
run_stdio_async(self, show_banner: bool = True, log_level: str | None = None) -> None
|
|
```
|
|
|
|
Run the server using stdio transport.
|
|
|
|
**Args:**
|
|
- `show_banner`: Whether to display the server banner
|
|
- `log_level`: Log level for the server
|
|
|
|
|
|
#### `run_http_async` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1898" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
run_http_async(self, show_banner: bool = True, transport: Literal['http', 'streamable-http', 'sse'] = 'http', host: str | None = None, port: int | None = None, log_level: str | None = None, path: str | None = None, uvicorn_config: dict[str, Any] | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None) -> None
|
|
```
|
|
|
|
Run the server using HTTP transport.
|
|
|
|
**Args:**
|
|
- `transport`: Transport protocol to use - either "streamable-http" (default) or "sse"
|
|
- `host`: Host address to bind to (defaults to settings.host)
|
|
- `port`: Port to bind to (defaults to settings.port)
|
|
- `log_level`: Log level for the server (defaults to settings.log_level)
|
|
- `path`: Path for the endpoint (defaults to settings.streamable_http_path or settings.sse_path)
|
|
- `uvicorn_config`: Additional configuration for the Uvicorn server
|
|
- `middleware`: A list of middleware to apply to the app
|
|
- `json_response`: Whether to use JSON response format (defaults to settings.json_response)
|
|
- `stateless_http`: Whether to use stateless HTTP (defaults to settings.stateless_http)
|
|
|
|
|
|
#### `http_app` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L1977" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
http_app(self, path: str | None = None, middleware: list[ASGIMiddleware] | None = None, json_response: bool | None = None, stateless_http: bool | None = None, transport: Literal['http', 'streamable-http', 'sse'] = 'http') -> StarletteWithLifespan
|
|
```
|
|
|
|
Create a Starlette app using the specified HTTP transport.
|
|
|
|
**Args:**
|
|
- `path`: The path for the HTTP endpoint
|
|
- `middleware`: A list of middleware to apply to the app
|
|
- `transport`: Transport protocol to use - either "streamable-http" (default) or "sse"
|
|
|
|
**Returns:**
|
|
- A Starlette application configured with the specified transport
|
|
|
|
|
|
#### `mount` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2026" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
mount(self, server: FastMCP[LifespanResultT], prefix: str | None = None, as_proxy: bool | None = None) -> None
|
|
```
|
|
|
|
Mount another FastMCP server on this server with an optional prefix.
|
|
|
|
Unlike importing (with import_server), mounting establishes a dynamic connection
|
|
between servers. When a client interacts with a mounted server's objects through
|
|
the parent server, requests are forwarded to the mounted server in real-time.
|
|
This means changes to the mounted server are immediately reflected when accessed
|
|
through the parent.
|
|
|
|
When a server is mounted with a prefix:
|
|
- Tools from the mounted server are accessible with prefixed names.
|
|
Example: If server has a tool named "get_weather", it will be available as "prefix_get_weather".
|
|
- Resources are accessible with prefixed URIs.
|
|
Example: If server has a resource with URI "weather://forecast", it will be available as
|
|
"weather://prefix/forecast".
|
|
- Templates are accessible with prefixed URI templates.
|
|
Example: If server has a template with URI "weather://location/{id}", it will be available
|
|
as "weather://prefix/location/{id}".
|
|
- Prompts are accessible with prefixed names.
|
|
Example: If server has a prompt named "weather_prompt", it will be available as
|
|
"prefix_weather_prompt".
|
|
|
|
When a server is mounted without a prefix (prefix=None), its tools, resources, templates,
|
|
and prompts are accessible with their original names. Multiple servers can be mounted
|
|
without prefixes, and they will be tried in order until a match is found.
|
|
|
|
There are two modes for mounting servers:
|
|
1. Direct mounting (default when server has no custom lifespan): The parent server
|
|
directly accesses the mounted server's objects in-memory for better performance.
|
|
In this mode, no client lifecycle events occur on the mounted server, including
|
|
lifespan execution.
|
|
|
|
2. Proxy mounting (default when server has a custom lifespan): The parent server
|
|
treats the mounted server as a separate entity and communicates with it via a
|
|
Client transport. This preserves all client-facing behaviors, including lifespan
|
|
execution, but with slightly higher overhead.
|
|
|
|
**Args:**
|
|
- `server`: The FastMCP server to mount.
|
|
- `prefix`: Optional prefix to use for the mounted server's objects. If None,
|
|
the server's objects are accessible with their original names.
|
|
- `as_proxy`: Whether to treat the mounted server as a proxy. If None (default),
|
|
automatically determined based on whether the server has a custom lifespan
|
|
(True if it has a custom lifespan, False otherwise).
|
|
- `tool_separator`: Deprecated. Separator character for tool names.
|
|
- `resource_separator`: Deprecated. Separator character for resource URIs.
|
|
- `prompt_separator`: Deprecated. Separator character for prompt names.
|
|
|
|
|
|
#### `import_server` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2144" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
import_server(self, server: FastMCP[LifespanResultT], prefix: str | None = None, tool_separator: str | None = None, resource_separator: str | None = None, prompt_separator: str | None = None) -> None
|
|
```
|
|
|
|
Import the MCP objects from another FastMCP server into this one,
|
|
optionally with a given prefix.
|
|
|
|
Note that when a server is *imported*, its objects are immediately
|
|
registered to the importing server. This is a one-time operation and
|
|
future changes to the imported server will not be reflected in the
|
|
importing server. Server-level configurations and lifespans are not imported.
|
|
|
|
When a server is imported with a prefix:
|
|
- The tools are imported with prefixed names
|
|
Example: If server has a tool named "get_weather", it will be
|
|
available as "prefix_get_weather"
|
|
- The resources are imported with prefixed URIs using the new format
|
|
Example: If server has a resource with URI "weather://forecast", it will
|
|
be available as "weather://prefix/forecast"
|
|
- The templates are imported with prefixed URI templates using the new format
|
|
Example: If server has a template with URI "weather://location/{id}", it will
|
|
be available as "weather://prefix/location/{id}"
|
|
- The prompts are imported with prefixed names
|
|
Example: If server has a prompt named "weather_prompt", it will be available as
|
|
"prefix_weather_prompt"
|
|
|
|
When a server is imported without a prefix (prefix=None), its tools, resources,
|
|
templates, and prompts are imported with their original names.
|
|
|
|
**Args:**
|
|
- `server`: The FastMCP server to import
|
|
- `prefix`: Optional prefix to use for the imported server's objects. If None,
|
|
objects are imported with their original names.
|
|
- `tool_separator`: Deprecated. Separator for tool names.
|
|
- `resource_separator`: Deprecated and ignored. Prefix is now
|
|
applied using the protocol\://prefix/path format
|
|
- `prompt_separator`: Deprecated. Separator for prompt names.
|
|
|
|
|
|
#### `from_openapi` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2278" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
from_openapi(cls, openapi_spec: dict[str, Any], client: httpx.AsyncClient, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI
|
|
```
|
|
|
|
Create a FastMCP server from an OpenAPI specification.
|
|
|
|
|
|
#### `from_fastapi` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2306" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
from_fastapi(cls, app: Any, name: str | None = None, route_maps: list[RouteMap] | None = None, route_map_fn: OpenAPIRouteMapFn | None = None, mcp_component_fn: OpenAPIComponentFn | None = None, mcp_names: dict[str, str] | None = None, httpx_client_kwargs: dict[str, Any] | None = None, tags: set[str] | None = None, **settings: Any) -> FastMCPOpenAPI
|
|
```
|
|
|
|
Create a FastMCP server from a FastAPI application.
|
|
|
|
|
|
#### `as_proxy` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2347" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
as_proxy(cls, backend: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy
|
|
```
|
|
|
|
Create a FastMCP proxy server for the given backend.
|
|
|
|
The `backend` argument can be either an existing `fastmcp.client.Client`
|
|
instance or any value accepted as the `transport` argument of
|
|
`fastmcp.client.Client`. This mirrors the convenience of the
|
|
`fastmcp.client.Client` constructor.
|
|
|
|
|
|
#### `generate_name` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2439" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|
|
|
|
```python
|
|
generate_name(cls, name: str | None = None) -> str
|
|
```
|
|
|
|
### `MountedServer` <sup><a href="https://github.com/jlowin/fastmcp/blob/main/src/fastmcp/server/server.py#L2449" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
|