diff --git a/docs/servers/context.mdx b/docs/servers/context.mdx index e6554cb7d..fad0e48a0 100644 --- a/docs/servers/context.mdx +++ b/docs/servers/context.mdx @@ -253,7 +253,9 @@ async def request_info(ctx: Context) -> dict: ### Advanced Access -For advanced use cases, you can access the underlying MCP session and FastMCP server. +For advanced use cases, you can access the underlying MCP session, FastMCP server, and HTTP requests. + +#### Accessing FastMCP and Sessions ```python @mcp.tool() @@ -269,13 +271,17 @@ async def advanced_tool(ctx: Context) -> str: return f"Server: {server_name}" ``` +#### Accessing HTTP Requests + + + For web applications, you can access the underlying HTTP request: ```python @mcp.tool() async def handle_web_request(ctx: Context) -> dict: """Access HTTP request information from the Starlette request.""" - request = ctx.get_starlette_request() + request = ctx.get_http_request() # Access HTTP headers, query parameters, etc. user_agent = request.headers.get("user-agent", "Unknown") @@ -288,12 +294,12 @@ async def handle_web_request(ctx: Context) -> dict: } ``` -**Advanced Properties:** +#### Advanced Properties Reference - **`ctx.fastmcp -> FastMCP`**: Access the server instance the context belongs to - **`ctx.session`**: Access the raw `mcp.server.session.ServerSession` object - **`ctx.request_context`**: Access the raw `mcp.shared.context.RequestContext` object -- **`ctx.get_starlette_request() -> Request`**: Access the active Starlette request object (when running with a web server) +- **`ctx.get_http_request() -> Request`**: Access the active Starlette request object (when running with a web server) Direct use of `session` or `request_context` requires understanding the low-level MCP Python SDK and may be less stable than using the methods provided directly on the `Context` object. diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.py index 34dd3ea36..fc476d5d2 100644 --- a/src/fastmcp/server/context.py +++ b/src/fastmcp/server/context.py @@ -227,7 +227,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT]): return result.content - def get_starlette_request(self) -> Request: + def get_http_request(self) -> Request: """Get the active starlette request.""" request = get_current_starlette_request() if request is None: