fastmcp.server.server
FastMCP - A more ergonomic interface for MCP servers.
Functions
default_lifespan
server: The server instance this lifespan is managing
- An empty dictionary as the lifespan result.
create_proxy
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 (a non-Client target). By default (None) the backend MIRRORS the front connection’s negotiated era per request, so the whole chain speaks one era end-to-end: a modern front reaches a modern backend (a guard tool’sInputRequiredResult(SEP-2322) round-trips) and a handshake front reaches a handshake backend (server-initiated sampling / elicitation / roots push-forwarding works). Pass an explicit mode (e.g."auto"or a version string) to pin the backend era regardless of the front; this overrides mirroring and is appropriate when the backend only speaks one era. Ignored whentargetis already aClient(which carries its own mode).**settings: Additional settings passed to FastMCPProxy (name, etc.)
- A FastMCPProxy server that proxies to the target.
Classes
StateValue
Wrapper for stored context state values.
FastMCP
Methods:
name
instructions
instructions
version
website_url
icons
local_provider
add_middleware
add_extension
tools/call interceptor, and an optional lifespan — each
with access to FastMCP-level constructs (the component registry,
Context, auth scope). Its capability is advertised only while it is
registered.
The extension is bound to this server (so its handlers and interceptor
can reach it), its method bindings are wired onto the low-level server,
and it is recorded for capability advertisement, interception, and
lifespan entry. Registering two extensions with the same identifier is
an error, as is registering after the server’s lifespan has started —
the extension’s lifespan could no longer run, leaving it silently
half-active.
Extensions are served by the server they are registered on. A mounted
child’s extensions do not propagate to the root: the root serves the
wire, so only root-registered extensions advertise capabilities and
answer methods (matching the lifespan, which also defers to the root).
Register extensions on the server you run.
add_provider
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
add_transform
transform: The transform to add.
list_tools
get_tool
name: The tool name.version: Version filter (None returns highest version).
- The tool if found and enabled, None otherwise.
list_resources
get_resource
uri: The resource URI.version: Version filter (None returns highest version).
- The resource if found and enabled, None otherwise.
list_resource_templates
get_resource_template
uri: The template URI.version: Version filter (None returns highest version).
- The template if found and enabled, None otherwise.
list_prompts
get_prompt
name: The prompt name.version: Version filter (None returns highest version).
- The prompt if found and enabled, None otherwise.
call_tool
name: The tool namearguments: 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.
- ToolResult.
InputRequiredToolResult (a ToolResult subclass); it
flows back through the middleware chain as an ordinary result and the
wire handler unwraps it into an InputRequiredResult on the response.
Raises:
NotFoundError: If tool not found or disabledToolError: If tool execution failsValidationError: If arguments fail validation
read_resource
uri: The resource URIversion: 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.
- ResourceResult.
NotFoundError: If resource not found or disabledResourceError: If resource read fails
render_prompt
name: The prompt namearguments: 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.
- PromptResult.
NotFoundError: If prompt not found or disabledPromptError: If prompt rendering fails
add_tool
tool: The Tool instance or @tool-decorated function to register
- The tool instance that was added to the server.
tool
tool
tool
- @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)
name_or_fn: Either a function (when used as @tool), a string name, or Nonename: Optional name for the tool (keyword-only, alternative to name_or_fn)description: Optional description of what the tool doestags: Optional set of tags for categorizing the tooloutput_schema: Optional JSON schema for the tool’s outputannotations: Optional annotations about the tool’s behaviormeta: Optional meta information about the tool
add_resource
resource: A Resource instance or @resource-decorated function to add
- The resource instance that was added to the server.
add_template
template: A ResourceTemplate instance to add
- The template instance that was added to the server.
resource
- str for text content
- bytes for binary content
- other types will be converted to JSON
uri: URI for the resource (e.g. “resource://my-resource” or “resource://”)name: Optional name for the resourcedescription: Optional description of the resourcemime_type: Optional MIME type for the resourcetags: Optional set of tags for categorizing the resourceannotations: Optional annotations about the resource’s behaviormeta: Optional meta information about the resource
add_prompt
prompt: A Prompt instance or @prompt-decorated function to add
- The prompt instance that was added to the server.
prompt
prompt
prompt
- @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)
add_completion_handler
completion/complete request, switching on the reference (a prompt or
resource template) and the argument being completed. Registering it also
registers the low-level completion/complete handler, which is what
makes the SDK declare the completions capability — so the capability is
advertised exactly when the server can answer. Calling this again
replaces the handler.
Args:
handler: A callable taking the reference, theCompletionArgument, and the optionalCompletionContext, and returning candidate values (aCompletion, a list of strings, or None). May be sync or async.
completion
completion
completion
completion/complete requests for prompt arguments
and resource-template parameters. It receives the reference being
completed, the argument (its name and the partial value typed so far),
and the context of arguments already supplied, and returns candidate
values. Return a list of strings, a Completion (to include pagination
hints), or None when the reference/argument is not one it handles — an
unhandled reference yields an empty completion, not an error.
Registering a handler declares the completions capability; a server with
none does not advertise it. This works identically on the handshake and
modern protocol eras.
Supports both @mcp.completion and @mcp.completion().
Example:
mount
- 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/”, it will be available as “weather://namespace/location/”.
- Prompts are accessible with namespaced names. Example: If server has a prompt named “weather_prompt”, it will be available as “namespace_weather_prompt”.
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 this to override namespaced names. Keys are the original tool names from the mounted server.
from_openapi
openapi_spec: OpenAPI schema as a dictionaryclient: Optional httpx2 AsyncClient for making HTTP requests. If not provided, a default client is created using the first server URL from the OpenAPI spec with a 30-second timeout. Legacy httpx clients are temporarily accepted with a deprecation warning.name: Name for the MCP serverroute_maps: Optional list of RouteMap objects defining route mappingsroute_map_fn: Optional callable for advanced route type mappingmcp_component_fn: Optional callable for component customizationmcp_names: Optional dictionary mapping operationId to component namestags: Optional set of tags to add to all componentsvalidate_output: If True (default), tools use the output schema extracted from the OpenAPI spec for response validation. If False, a permissive schema is used instead, allowing any response structure while still returning structured JSON.**settings: Additional settings passed to FastMCP
- A FastMCP server with an OpenAPIProvider attached.
from_fastapi
app: FastAPI application instancename: Name for the MCP server (defaults to app.title)route_maps: Optional list of RouteMap objects defining route mappingsroute_map_fn: Optional callable for advanced route type mappingmcp_component_fn: Optional callable for component customizationmcp_names: Optional dictionary mapping operationId to component nameshttpx_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
- A FastMCP server with an OpenAPIProvider attached.

