π The fast, Pythonic way to build MCP servers and clients.
Handle request_context availability during MCP initialization (#2400)
Jeremiah Lowinbc076cba1299
diff --git a/docs/servers/context.mdx b/docs/servers/context.mdxindex 1fb88ffad..4abd6dc90 100644--- a/docs/servers/context.mdx+++ b/docs/servers/context.mdx@@ -313,6 +313,48 @@ async def request_info(ctx: Context) -> dict:- **`ctx.client_id -> str | None`**: Get the ID of the client making the request, if provided during initialization- **`ctx.session_id -> str | None`**: Get the MCP session ID for session-based data sharing (HTTP transports only)+#### Request Context Availability++<VersionBadge version="2.13.1" />++The `ctx.request_context` property provides access to the underlying MCP request context, but returns `None` when the MCP session has not been established yet. This typically occurs:++- During middleware execution in the `on_request` hook before the MCP handshake completes+- During the initialization phase of client connections++The MCP request context is distinct from the HTTP request. For HTTP transports, HTTP request data may be available even when the MCP session is not yet established.++To safely access the request context in situations where it may not be available:++```python+from fastmcp import FastMCP, Context+from fastmcp.server.dependencies import get_http_request++mcp = FastMCP(name="Session Aware Demo")++async def session_info(ctx: Context) -> dict:+ """Return session information when available."""++ # Check if MCP session is available+ if ctx.request_context:+ # MCP session available - can access MCP-specific attributes+ return {+ "session_id": ctx.session_id,+ "request_id": ctx.request_id,+ "has_meta": ctx.request_context.meta is not None+ }+ else:+ # MCP session not available - use HTTP helpers for request data (if using HTTP transport)+ request = get_http_request()+ return {+ "message": "MCP session not available",+ "user_agent": request.headers.get("user-agent", "Unknown")+ }+```++For HTTP request access that works regardless of MCP session availability (when using HTTP transports), use the [HTTP request helpers](#http-requests) like `get_http_request()` and `get_http_headers()`.+#### Client Metadata<VersionBadge version="2.13.1" />diff --git a/docs/servers/middleware.mdx b/docs/servers/middleware.mdxindex b3a79bdc1..341d91046 100644--- a/docs/servers/middleware.mdx+++ b/docs/servers/middleware.mdx@@ -103,11 +103,45 @@ This hierarchy allows you to target your middleware logic with the right level o- `on_list_resource_templates`: Called when listing resource templates- `on_list_prompts`: Called when listing available prompts<VersionBadge version="2.13.0" />-- `on_initialize`: Called when a client connects and initializes the session (returns `None`)+- `on_initialize`: Called when a client connects and initializes the session (returns `None`)<Note>The `on_initialize` hook receives the client's initialization request but **returns `None`** rather than a result. The initialization response is handled internally by the MCP protocol and cannot be modified by middleware. This hook is useful for client detection, logging connections, or initializing session state, but not for modifying the initialization handshake itself.</Note>+### MCP Session Availability in Middleware++<VersionBadge version="2.13.1" />++The MCP session and request context are not available during certain phases like initialization. When middleware runs during these phases, `context.fastmcp_context.request_context` returns `None` rather than the full MCP request context.++This typically occurs when:+- The `on_request` hook fires during client initialization+- The MCP handshake hasn't completed yet++To handle this in middleware, check if the MCP request context is available before accessing MCP-specific attributes. Note that the MCP request context is distinct from the HTTP request - for HTTP transports, you can use HTTP helpers to access request data even when the MCP session is not available:++```python+from fastmcp.server.middleware import Middleware, MiddlewareContext++class SessionAwareMiddleware(Middleware):+ async def on_request(self, context: MiddlewareContext, call_next):+ ctx = context.fastmcp_context++ if ctx.request_context:+ # MCP session available - can access session-specific attributes+ session_id = ctx.session_id+ request_id = ctx.request_id+ else:+ # MCP session not available yet - use HTTP helpers for request data (if using HTTP transport)+ from fastmcp.server.dependencies import get_http_headers+ headers = get_http_headers()+ # Access HTTP data for auth, logging, etc.++ return await call_next(context)+```++For HTTP request data (headers, client IP, etc.) when using HTTP transports, use `get_http_request()` or `get_http_headers()` from `fastmcp.server.dependencies`, which work regardless of MCP session availability. See [HTTP Requests](/servers/context#http-requests) for details.+## Component Access in MiddlewareUnderstanding how to access component information (tools, resources, prompts) in middleware is crucial for building powerful middleware functionality. The access patterns differ significantly between listing operations and execution operations.diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.pyindex 94d983db3..d2124b7f1 100644--- a/src/fastmcp/server/context.py+++ b/src/fastmcp/server/context.py@@ -181,15 +181,33 @@ class Context:_current_context.reset(token)@property- def request_context(self) -> RequestContext[ServerSession, Any, Request]:+ def request_context(self) -> RequestContext[ServerSession, Any, Request] | None:"""Access to the underlying request context.- If called outside of a request context, this will raise a ValueError.+ Returns None when the MCP session has not been established yet.+ Returns the full RequestContext once the MCP session is available.++ For HTTP request access in middleware, use `get_http_request()` from fastmcp.server.dependencies,+ which works whether or not the MCP session is available.++ Example in middleware:+ ```python+ async def on_request(self, context, call_next):+ ctx = context.fastmcp_context+ if ctx.request_context:+ # MCP session available - can access session_id, request_id, etc.+ session_id = ctx.session_id+ else:+ # MCP session not available yet - use HTTP helpers+ from fastmcp.server.dependencies import get_http_request+ request = get_http_request()+ return await call_next(context)+ ```"""try:return request_ctx.get()- except LookupError as e:- raise ValueError("Context is not available outside of a request") from e+ except LookupError:+ return Noneasync def report_progress(self, progress: float, total: float | None = None, message: str | None = None@@ -203,7 +221,7 @@ class Context:progress_token = (self.request_context.meta.progressToken- if self.request_context.meta+ if self.request_context and self.request_context.metaelse None)@@ -292,13 +310,21 @@ class Context:"""Get the client ID if available."""return (getattr(self.request_context.meta, "client_id", None)- if self.request_context.meta+ if self.request_context and self.request_context.metaelse None)@propertydef request_id(self) -> str:- """Get the unique ID for this request."""+ """Get the unique ID for this request.++ Raises RuntimeError if MCP request context is not available.+ """+ if self.request_context is None:+ raise RuntimeError(+ "request_id is not available because the MCP session has not been established yet. "+ "Check `context.request_context` for None before accessing this attribute."+ )return str(self.request_context.request_id)@property@@ -313,6 +339,9 @@ class Context:The session ID for StreamableHTTP transports, or a generated IDfor other transports.+ Raises:+ RuntimeError if MCP request context is not available.+Example:```python@server.tool@@ -323,6 +352,11 @@ class Context:```"""request_ctx = self.request_context+ if request_ctx is None:+ raise RuntimeError(+ "session_id is not available because the MCP session has not been established yet. "+ "Check `context.request_context` for None before accessing this attribute."+ )session = request_ctx.session# Try to get the session ID from the session attributes@@ -347,7 +381,15 @@ class Context:@propertydef session(self) -> ServerSession:- """Access to the underlying session for advanced usage."""+ """Access to the underlying session for advanced usage.++ Raises RuntimeError if MCP request context is not available.+ """+ if self.request_context is None:+ raise RuntimeError(+ "session is not available because the MCP session has not been established yet. "+ "Check `context.request_context` for None before accessing this attribute."+ )return self.request_context.session# Convenience methods for common log levels