From bb7d41a53d30512e2ad3e2f00cf2323a7519b846 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Fri, 2 May 2025 17:36:09 -0400 Subject: [PATCH] =?UTF-8?q?get=5Fstarlette=5Frequest=20=E2=86=92=20get=5Fh?= =?UTF-8?q?ttp=5Frequest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/servers/context.mdx | 14 ++++++++++---- src/fastmcp/server/context.py | 2 +- 2 files changed, 11 insertions(+), 5 deletions(-) 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: