Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877---title: serversidebarTitle: server---
# `fastmcp.server.server`
FastMCP - A more ergonomic interface for MCP servers.
## Functions
### `default_lifespan` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L271" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythondefault_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.
### `create_proxy` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2473" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncreate_proxy(target: Client[ClientTransportT] | ClientTransport | FastMCP[Any] | SDKServer | AnyUrl | Path | MCPConfig | dict[str, Any] | str, **settings: Any) -> FastMCPProxy```
Create a FastMCP proxy server for the given target.
This is the recommended way to create a proxy server. For lower-level control,use `FastMCPProxy` or `ProxyProvider` directly from `fastmcp.server.providers.proxy`.
**Args:**- `target`: The backend to proxy to. Can be\:- A Client instance (connected or disconnected)- A ClientTransport- A FastMCP server instance- A URL string or AnyUrl- A Path to a server script- An MCPConfig or dict- `mode`: Protocol-era negotiation for auto-created proxy clients (anon-Client target). By default (``None``) the backend MIRRORS thefront connection's negotiated era per request, so the whole chainspeaks one era end-to-end\: a modern front reaches a modern backend(a guard tool's `InputRequiredResult` (SEP-2322) round-trips) and ahandshake front reaches a handshake backend (server-initiatedsampling / elicitation / roots push-forwarding works). Pass anexplicit mode (e.g. ``"auto"`` or a version string) to pin thebackend era regardless of the front; this overrides mirroring and isappropriate when the backend only speaks one era. Ignored when`target` is already a `Client` (which carries its own mode).- `**settings`: Additional settings passed to FastMCPProxy (name, etc.)
**Returns:**- A FastMCPProxy server that proxies to the target.
## Classes
### `StateValue` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L306" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
Wrapper for stored context state values.
### `FastMCP` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L312" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
**Methods:**
#### `name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L546" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonname(self) -> str```
#### `instructions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L550" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoninstructions(self) -> str | None```
#### `instructions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L554" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoninstructions(self, value: str | None) -> None```
#### `version` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L558" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonversion(self) -> str | None```
#### `website_url` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L562" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonwebsite_url(self) -> str | None```
#### `icons` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L566" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonicons(self) -> list[mcp_types.Icon]```
#### `local_provider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L573" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlocal_provider(self) -> LocalProvider```
The server's local provider, which stores directly-registered components.
Use this to remove components:
mcp.local_provider.remove_tool("my_tool") mcp.local_provider.remove_resource("data://info") mcp.local_provider.remove_prompt("my_prompt")
#### `add_middleware` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L637" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_middleware(self, middleware: Middleware) -> None```
#### `required_extensions` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L662" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrequired_extensions(self) -> Sequence[ServerExtension]```
Bundled extensions and auto-registerable registrations for composition.
#### `add_provider` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L666" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_provider(self, provider: Provider) -> None```
Add a provider for dynamic tools, resources, and prompts.
Providers are queried in registration order. The first provider to returna non-None result wins. Static components (registered via decorators)always take precedence over providers.
**Args:**- `provider`: A Provider instance that will provide components dynamically.- `namespace`: Optional namespace prefix. When set\:- Tools become "namespace_toolname"- Resources become "protocol\://namespace/path"- Prompts become "namespace_promptname"
#### `get_tasks` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L780" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_tasks(self) -> Sequence[FastMCPComponent]```
Get task-eligible components with server-level transforms applied.
Overrides AggregateProvider.get_tasks() to apply server-level transformsafter aggregation. AggregateProvider handles provider-level namespacing.
#### `add_transform` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L805" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_transform(self, transform: Transform) -> None```
Add a server-level transform.
Server-level transforms are applied after all providers are aggregated.They transform tools, resources, and prompts from ALL providers.
**Args:**- `transform`: The transform to add.
#### `list_tools` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L825" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_tools(self) -> Sequence[Tool]```
List all enabled tools from providers.
Overrides Provider.list_tools() to add enabled filtering, auth filtering,and middleware execution. Returns all versions (no deduplication).Protocol handlers deduplicate for MCP wire format.
#### `get_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L900" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_tool(self, name: str, version: VersionSpec | None = None) -> Tool | None```
Get a tool by name, filtering disabled tools.
Overrides Provider.get_tool() to filter disabled tools after alltransforms (including session-level) have been applied. This ensuressession transforms can override provider-level disables.
When the highest version is disabled and no explicit version wasrequested, falls back to the next-highest enabled version.
A tool from `ToolInjectionMiddleware` takes precedence over a providertool with the same name. It is matched by name alone, so a requestedversion is ignored, and it is subject to its own `auth` check but notto transforms or visibility.
**Args:**- `name`: The tool name.- `version`: Version filter (None returns highest version).
**Returns:**- The tool if found, enabled, and authorized, None otherwise.
#### `list_resources` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L964" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_resources(self) -> Sequence[Resource]```
List all enabled resources from providers.
Overrides Provider.list_resources() to add visibility filtering, auth filtering,and middleware execution. Returns all versions (no deduplication).Protocol handlers deduplicate for MCP wire format.
#### `get_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1049" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_resource(self, uri: str, version: VersionSpec | None = None) -> Resource | None```
Get a resource by URI, filtering disabled resources.
Overrides Provider.get_resource() to add visibility filtering after alltransforms (including session-level) have been applied.
When the highest version is disabled and no explicit version wasrequested, falls back to the next-highest enabled version.
**Args:**- `uri`: The resource URI.- `version`: Version filter (None returns highest version).
**Returns:**- The resource if found and enabled, None otherwise.
#### `list_resource_templates` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1099" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_resource_templates(self) -> Sequence[ResourceTemplate]```
List all enabled resource templates from providers.
Overrides Provider.list_resource_templates() to add visibility filtering,auth filtering, and middleware execution. Returns all versions (no deduplication).Protocol handlers deduplicate for MCP wire format.
#### `get_resource_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1181" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_resource_template(self, uri: str, version: VersionSpec | None = None) -> ResourceTemplate | None```
Get a resource template by URI, filtering disabled templates.
Overrides Provider.get_resource_template() to add visibility filtering afterall transforms (including session-level) have been applied.
When the highest version is disabled and no explicit version wasrequested, falls back to the next-highest enabled version.
**Args:**- `uri`: The template URI.- `version`: Version filter (None returns highest version).
**Returns:**- The template if found and enabled, None otherwise.
#### `list_prompts` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1235" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonlist_prompts(self) -> Sequence[Prompt]```
List all enabled prompts from providers.
Overrides Provider.list_prompts() to add visibility filtering, auth filtering,and middleware execution. Returns all versions (no deduplication).Protocol handlers deduplicate for MCP wire format.
#### `get_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1307" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonget_prompt(self, name: str, version: VersionSpec | None = None) -> Prompt | None```
Get a prompt by name, filtering disabled prompts.
Overrides Provider.get_prompt() to add visibility filtering after alltransforms (including session-level) have been applied.
When the highest version is disabled and no explicit version wasrequested, falls back to the next-highest enabled version.
**Args:**- `name`: The prompt name.- `version`: Version filter (None returns highest version).
**Returns:**- The prompt if found and enabled, None otherwise.
#### `call_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1357" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncall_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult```
Call a tool by name.
This is the public API for executing tools. By default, middleware is applied.
**Args:**- `name`: The tool name- `arguments`: Tool arguments (optional)- `version`: Specific version to call. If None, calls highest version.- `run_middleware`: If True (default), apply the middleware chain.Set to False when called from middleware to avoid re-applying.
**Returns:**- ToolResult.
A guard tool that requests client input (SEP-2322 multi-round-trip)returns an ``InputRequiredToolResult`` (a ``ToolResult`` subclass); itflows back through the middleware chain as an ordinary result and thewire handler unwraps it into an ``InputRequiredResult`` on the response.
**Raises:**- `NotFoundError`: If tool not found or disabled- `ToolError`: If tool execution fails- `ValidationError`: If arguments fail validation
#### `read_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1529" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonread_resource(self, uri: str) -> ResourceResult```
Read a resource by URI.
This is the public API for reading resources. By default, middleware is applied.Checks concrete resources first, then templates.
**Args:**- `uri`: The resource URI- `version`: Specific version to read. If None, reads highest version.- `run_middleware`: If True (default), apply the middleware chain.Set to False when called from middleware to avoid re-applying.
**Returns:**- ResourceResult.
**Raises:**- `NotFoundError`: If resource not found or disabled- `ResourceError`: If resource read fails
#### `render_prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1687" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonrender_prompt(self, name: str, arguments: dict[str, Any] | None = None) -> PromptResult```
Render a prompt by name.
This is the public API for rendering prompts. By default, middleware is applied.Use get_prompt() to retrieve the prompt definition without rendering.
**Args:**- `name`: The prompt name- `arguments`: Prompt arguments (optional)- `version`: Specific version to render. If None, renders highest version.- `run_middleware`: If True (default), apply the middleware chain.Set to False when called from middleware to avoid re-applying.
**Returns:**- PromptResult.
**Raises:**- `NotFoundError`: If prompt not found or disabled- `PromptError`: If prompt rendering fails
#### `add_tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1767" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_tool(self, tool: Tool | Callable[..., Any]) -> Tool```
Add a tool to the server.
The tool function can optionally request a Context object by adding a parameterwith the Context type annotation. See the @tool decorator for examples.
**Args:**- `tool`: The Tool instance or @tool-decorated function to register
**Returns:**- The tool instance that was added to the server.
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1782" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontool(self, name_or_fn: F) -> F```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1803" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontool(self, name_or_fn: str | None = None) -> Callable[[F], F]```
#### `tool` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1823" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythontool(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool]```
Decorator to register a tool.
Tools can optionally request a Context object by adding a parameter with theContext type annotation. The context provides access to MCP capabilities likelogging, 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- `meta`: Optional meta information about the tool
**Examples:**
Register a tool with a custom name:```python@server.tooldef my_tool(x: int) -> str: return str(x)
# Register a tool with a custom name@server.tooldef 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 callserver.tool(my_function, name="custom_name")```
#### `add_resource` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1920" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_resource(self, resource: Resource | Callable[..., Any]) -> Resource | ResourceTemplate```
Add a resource to the server.
**Args:**- `resource`: A Resource instance or @resource-decorated function to add
**Returns:**- The resource instance that was added to the server.
#### `add_template` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1933" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_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/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L1944" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonresource(self, uri: str) -> Callable[[F], F]```
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 theContext type annotation. The context provides access to MCP capabilities likelogging, progress reporting, and session information.
If the URI contains parameters (e.g. "resource://{param}") or the functionhas 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- `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/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2063" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_prompt(self, prompt: Prompt | Callable[..., Any]) -> Prompt```
Add a prompt to the server.
**Args:**- `prompt`: A Prompt instance or @prompt-decorated function to add
**Returns:**- The prompt instance that was added to the server.
#### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2075" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonprompt(self, name_or_fn: F) -> F```
#### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2090" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonprompt(self, name_or_fn: str | None = None) -> Callable[[F], F]```
#### `prompt` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2104" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonprompt(self, name_or_fn: str | AnyFunction | None = None) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[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 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") ```
#### `add_completion_handler` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2202" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonadd_completion_handler(self, handler: CompletionHandler) -> None```
Register the server's argument-completion handler.
A server has a single completion handler that answers every`completion/complete` request, switching on the reference (a prompt orresource template) and the argument being completed. Registering it alsoregisters the low-level `completion/complete` handler, which is whatmakes the SDK declare the completions capability — so the capability isadvertised exactly when the server can answer. Calling this againreplaces the handler.
**Args:**- `handler`: A callable taking the reference, the`CompletionArgument`, and the optional `CompletionContext`, andreturning candidate values (a `Completion`, a list of strings,or None). May be sync or async.
#### `completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2223" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncompletion(self, handler: CompletionHandler) -> CompletionHandler```
#### `completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2226" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncompletion(self) -> Callable[[CompletionHandler], CompletionHandler]```
#### `completion` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2230" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythoncompletion(self, handler: CompletionHandler | None = None) -> CompletionHandler | Callable[[CompletionHandler], CompletionHandler]```
Decorator to register the server's argument-completion handler.
The handler answers `completion/complete` requests for prompt argumentsand resource-template parameters. It receives the reference beingcompleted, the argument (its name and the partial value typed so far),and the context of arguments already supplied, and returns candidatevalues. Return a list of strings, a `Completion` (to include paginationhints), or None when the reference/argument is not one it handles — anunhandled reference yields an empty completion, not an error.
Registering a handler declares the completions capability; a server withnone does not advertise it. This works identically on the handshake andmodern protocol eras.
Supports both `@mcp.completion` and `@mcp.completion()`.
Example:
```python from fastmcp import FastMCP from mcp_types import Completion, PromptReference
mcp = FastMCP("Completion Server")
@mcp.prompt def poem(theme: str) -> str: return f"Write a poem about {theme}"
@mcp.completion def complete(ref, argument, context): if isinstance(ref, PromptReference) and ref.name == "poem": if argument.name == "theme": options = ["nature", "love", "adventure"] return [o for o in options if o.startswith(argument.value)] return None ```
#### `mount` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2280" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonmount(self, server: FastMCP[LifespanResultT], namespace: str | None = None, tool_names: dict[str, str] | None = None) -> None```
Mount another FastMCP server on this server with an optional namespace.
Mounting establishes a dynamic connection between servers. When a clientinteracts with a mounted server's objects through the parent server, requestsare forwarded to the mounted server in real-time. This means changes to themounted server are immediately reflected when accessed through the parent.
When a server is mounted with a namespace:- Tools from the mounted server are accessible with namespaced names. Example: If server has a tool named "get_weather", it will be available as "namespace_get_weather".- Resources are accessible with namespaced URIs. Example: If server has a resource with URI "weather://forecast", it will be available as "weather://namespace/forecast".- Templates are accessible with namespaced URI templates. Example: If server has a template with URI "weather://location/{id}", it will be available as "weather://namespace/location/{id}".- Prompts are accessible with namespaced names. Example: If server has a prompt named "weather_prompt", it will be available as "namespace_weather_prompt".
When a server is mounted without a namespace (namespace=None), its tools, resources, templates,and prompts are accessible with their original names. Multiple servers can be mountedwithout namespaces, and they will be tried in order until a match is found.
The mounted server's lifespan is executed when the parent server starts, and itsmiddleware chain is invoked for all operations (tool calls, resource reads, prompts).
**Args:**- `server`: The FastMCP server to mount.- `namespace`: Optional namespace to use for the mounted server's objects. If None,the server's objects are accessible with their original names.- `tool_names`: Optional mapping of original tool names to custom names. Use thisto override namespaced names. Keys are the original tool names from themounted server.
#### `from_openapi` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2351" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonfrom_openapi(cls, openapi_spec: dict[str, Any], client: httpx2.AsyncClient | None = None, name: str = 'OpenAPI Server', 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, validate_output: bool = True, **settings: Any) -> Self```
Create a FastMCP server from an OpenAPI specification.
**Args:**- `openapi_spec`: OpenAPI schema as a dictionary- `client`: Optional httpx2 AsyncClient for making HTTP requests.If not provided, a default client is created using the firstserver URL from the OpenAPI spec with a 30-second timeout.Legacy httpx clients are temporarily accepted with a deprecationwarning.- `name`: Name for the MCP server- `route_maps`: Optional list of RouteMap objects defining route mappings- `route_map_fn`: Optional callable for advanced route type mapping- `mcp_component_fn`: Optional callable for component customization- `mcp_names`: Optional dictionary mapping operationId to component names- `tags`: Optional set of tags to add to all components- `validate_output`: If True (default), tools use the output schemaextracted from the OpenAPI spec for response validation. IfFalse, a permissive schema is used instead, allowing anyresponse structure while still returning structured JSON.- `**settings`: Additional settings passed to FastMCP
**Returns:**- A FastMCP server with an OpenAPIProvider attached.
#### `from_fastapi` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2404" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythonfrom_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) -> Self```
Create a FastMCP server from a FastAPI application.
**Args:**- `app`: FastAPI application instance- `name`: Name for the MCP server (defaults to app.title)- `route_maps`: Optional list of RouteMap objects defining route mappings- `route_map_fn`: Optional callable for advanced route type mapping- `mcp_component_fn`: Optional callable for component customization- `mcp_names`: Optional dictionary mapping operationId to component names- `httpx_client_kwargs`: Optional kwargs passed to httpx2.AsyncClient.Use this to configure timeout and other client settings.- `tags`: Optional set of tags to add to all components- `**settings`: Additional settings passed to FastMCP
**Returns:**- A FastMCP server with an OpenAPIProvider attached.
#### `generate_name` <sup><a href="https://github.com/PrefectHQ/fastmcp/blob/main/fastmcp_slim/fastmcp/server/server.py#L2459" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>
```pythongenerate_name(cls, name: str | None = None) -> str```