Skip to main content
Middleware adds behavior that applies across multiple operations—authentication, logging, rate limiting, or request transformation—without modifying individual tools or resources.
MCP middleware is a FastMCP-specific concept and is not part of the official MCP protocol specification.

Overview

MCP middleware forms a pipeline around your server’s operations. When a request arrives, it flows through each middleware in order—each can inspect, modify, or reject the request before passing it along. After the operation completes, the response flows back through the same middleware in reverse order.
This bidirectional flow means middleware can:
  • Pre-process: Validate authentication, log incoming requests, check rate limits
  • Post-process: Transform responses, record timing metrics, handle errors consistently
The key decision point is call_next(context). Calling it continues the chain; not calling it stops processing entirely.

Execution Order

Middleware executes in the order added to the server. The first middleware runs first on the way in and last on the way out:
This ordering matters. Place error handling early so it catches exceptions from all subsequent middleware. Place logging late so it records the actual execution after other middleware has processed the request.

Server Composition

When using mounted servers, middleware behavior follows a clear hierarchy:
  • Parent middleware runs for all requests, including those routed to mounted servers
  • Mounted server middleware only runs for requests handled by that specific server
Requests to child_tool flow through the parent’s AuthMiddleware first, then through the child’s LoggingMiddleware. Middleware-stored state does not automatically cross mount boundaries. If AuthMiddleware on the parent calls ctx.set_state("user_id", ...), a tool on the child server calling ctx.get_state("user_id") will get None — each FastMCP instance owns its own session state store. To share state across the mount, either pass the same session_state_store to both servers or use serializable=False for request-scoped values. See State and Mounted Servers for details.

Hooks

Rather than processing every message identically, FastMCP provides specialized hooks at different levels of specificity. Multiple hooks fire for a single request, going from general to specific: When a client calls a tool, the middleware chain processes on_message first, then on_request, then on_call_tool. This hierarchy lets you target exactly the right scope—use on_message for logging everything, on_request for authentication, and on_call_tool for tool-specific behavior.

Hook Signature

Every hook follows the same pattern:
Parameters:
  • contextMiddlewareContext containing request information
  • call_next — Async function to continue the middleware chain
Returns: The appropriate result type for the hook (varies by operation).

MiddlewareContext

The context parameter provides access to request details:

Message Hooks

on_message

Called for every MCP message—both requests and notifications.
Use for: Logging, metrics, or any cross-cutting concern that applies to all traffic.

on_request

Called for MCP requests that expect a response.
Use for: Authentication, authorization, request validation.

on_notification

Called for fire-and-forget MCP notifications.
Use for: Event logging, async side effects.

Operation Hooks

on_call_tool

Called when a tool is executed. The context.message contains name (tool name) and arguments (dict).
Returns: Tool execution result or raises ToolError.

on_read_resource

Called when a resource is read. The context.message contains uri (resource URI).
Returns: Resource content.

on_get_prompt

Called when a prompt is retrieved. The context.message contains name (prompt name) and arguments (dict).
Returns: Prompt messages.

on_list_tools

Called when listing available tools. Returns a list of FastMCP Tool objects before MCP conversion.
Returns: list[Tool] — Can be filtered before returning to client.

on_list_resources

Called when listing available resources. Returns FastMCP Resource objects.
Returns: list[Resource]

on_list_resource_templates

Called when listing resource templates.
Returns: list[ResourceTemplate]

on_list_prompts

Called when listing available prompts.
Returns: list[Prompt]

on_initialize

Called when a client connects and initializes the session. This hook cannot modify the initialization response.
Returns: None — The initialization response is handled internally by the MCP protocol.
Raising McpError after call_next() will only log the error, not send it to the client. The response has already been sent. Always reject before call_next().

Raw Handler

For complete control over all messages, override __call__ instead of individual hooks:
This bypasses the hook dispatch system entirely. Use when you need uniform handling regardless of message type.

Session Availability

The MCP session may not be available during certain phases like initialization. Check before accessing session-specific attributes:
For HTTP-specific data (headers, client IP) when using HTTP transports, see HTTP Requests.

Built-in Middleware

FastMCP includes production-ready middleware for common server concerns.

Logging

LoggingMiddleware provides human-readable request and response logging. StructuredLoggingMiddleware outputs JSON-formatted logs for aggregation tools like Datadog or Splunk.

Timing

TimingMiddleware logs execution duration for all requests. DetailedTimingMiddleware provides per-operation timing with separate tracking for tools, resources, and prompts.

Caching

Caches tool calls, resource reads, and list operations with TTL-based expiration.
Each operation type can be configured independently using settings classes:
Each settings class accepts:
  • enabled — Enable/disable caching for this operation
  • ttl — Time-to-live in seconds
  • included_* / excluded_* — Whitelist or blacklist specific items
For persistence or distributed deployments, configure a different storage backend:
See Storage Backends for complete options.
Cache keys are based on the operation name and arguments only — they do not include user or session identity. If your tools return user-specific data derived from auth context (e.g., headers or session state) rather than from the request arguments, you should either disable caching for those tools or ensure user identity is part of the tool arguments.

Rate Limiting

RateLimitingMiddleware uses a token bucket algorithm allowing controlled bursts. SlidingWindowRateLimitingMiddleware provides precise time-window rate limiting without burst allowance.
For sliding window rate limiting:

Error Handling

ErrorHandlingMiddleware provides centralized error logging and transformation. RetryMiddleware automatically retries with exponential backoff for transient failures.
For automatic retries:

Ping

Keeps long-lived connections alive by sending periodic pings.
The ping task starts on the first message and stops automatically when the session ends. Most useful for stateful HTTP connections; has no effect on stateless connections.

Response Limiting

Large tool responses can overwhelm LLM context windows or cause memory issues. You can add response-limiting middleware to enforce size constraints on tool outputs.
When a response exceeds the limit, the middleware extracts all text content, joins it together, truncates to fit within the limit, and returns a single TextContent block. For non-text responses, the serialized JSON is used as the text source.
If a tool defines an output_schema, truncated responses will no longer conform to that schema — the client will receive a plain TextContent block instead of the expected structured output. Keep this in mind when setting size limits for tools with structured responses.

Combining Middleware

Order matters. Place middleware that should run first (on the way in) earliest:

Custom Middleware

When the built-in middleware doesn’t fit your needs—custom authentication schemes, domain-specific logging, or request transformation—subclass Middleware and override the hooks you need.
Override only the hooks relevant to your use case. Unoverridden hooks pass through automatically.

Denying Requests

Raise the appropriate error type to stop processing and return an error to the client.
Do not return error values or skip call_next() to indicate errors—raise exceptions for proper error propagation.

Modifying Requests

Change the message before passing it down the chain.

Modifying Responses

Transform results after the handler executes.
For more complex tool transformations, consider Transforms instead.

Filtering Lists

List operations return FastMCP objects that you can filter before they reach the client. When filtering list results, also block execution in the corresponding operation hook to maintain consistency:

Accessing Component Metadata

During execution hooks, component metadata (like tags) isn’t directly available. Look up the component through the server:
The same pattern works for resources and prompts:

Storing State

Middleware can store state that tools access later through the FastMCP context.
Tools retrieve the state:
See Context State Management for details.

Constructor Parameters

Initialize middleware with configuration:

Error Handling in Custom Middleware

Wrap call_next() to handle errors from downstream middleware and handlers.
Catching and not re-raising suppresses the error entirely. Usually you want to log and re-raise.

Audit and Event Records

A common need is to emit one structured record per tool call — for audit logs, policy decisions, or offline analysis — without wrapping individual tools or storing raw payloads. on_call_tool is the right place: it sees the call start, the resolved ToolResult (so it can detect empty or error results), the duration, and can deny the call before it runs. Use OpenTelemetry when the goal is to export spans to an observability backend. Reach for a record like this when you want a self-contained, redacted audit trail — or to drive runtime decisions from the result.
Each record carries the fields downstream tools tend to need — tool name, call id, input schema hash, redacted arguments, result class (completed / empty / error / failed), and duration — while raw inputs and outputs stay out by default. To make this a policy layer, deny inside the same hook before calling call_next:

Complete Example

Authentication middleware checking API keys for specific tools: