Jeremiah Lowin commited on
Commit
719c995
·
1 Parent(s): aef8e8e

Add dependency docs

Browse files
docs/docs.json CHANGED
@@ -65,6 +65,7 @@
65
  "patterns/proxy",
66
  "patterns/composition",
67
  "patterns/decorating-methods",
 
68
  "patterns/openapi",
69
  "patterns/fastapi",
70
  "patterns/contrib",
 
65
  "patterns/proxy",
66
  "patterns/composition",
67
  "patterns/decorating-methods",
68
+ "patterns/http-requests",
69
  "patterns/openapi",
70
  "patterns/fastapi",
71
  "patterns/contrib",
docs/patterns/http-requests.mdx ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: HTTP Requests
3
+ sidebarTitle: HTTP Requests
4
+ description: Accessing and using HTTP requests in FastMCP servers
5
+ icon: network-wired
6
+ ---
7
+ import { VersionBadge } from '/snippets/version-badge.mdx'
8
+
9
+ <VersionBadge version="2.2.11" />
10
+
11
+ ## Overview
12
+
13
+ When running FastMCP as a web server, your MCP tools, resources, and prompts might need to access the underlying HTTP request information, such as headers, client IP, or query parameters.
14
+
15
+ FastMCP provides a clean way to access HTTP request information through a dependency function.
16
+
17
+ ## Accessing HTTP Requests
18
+
19
+ The recommended way to access the current HTTP request is through the `get_http_request()` dependency function:
20
+
21
+ ```python {2, 3, 11}
22
+ from fastmcp import FastMCP
23
+ from fastmcp.server.dependencies import get_http_request
24
+ from starlette.requests import Request
25
+
26
+ mcp = FastMCP(name="HTTPRequestDemo")
27
+
28
+ @mcp.tool()
29
+ async def user_agent_info() -> dict:
30
+ """Return information about the user agent."""
31
+ # Get the HTTP request
32
+ request: Request = get_http_request()
33
+
34
+ # Access request data
35
+ user_agent = request.headers.get("user-agent", "Unknown")
36
+ client_ip = request.client.host if request.client else "Unknown"
37
+
38
+ return {
39
+ "user_agent": user_agent,
40
+ "client_ip": client_ip,
41
+ "path": request.url.path,
42
+ }
43
+ ```
44
+
45
+ This approach works anywhere within a request's execution flow, not just within your MCP function. It's useful when:
46
+
47
+ 1. You need access to HTTP information in helper functions
48
+ 2. You're calling nested functions that need HTTP request data
49
+ 3. You're working with middleware or other request processing code
50
+
51
+ ## Important Notes
52
+
53
+ - HTTP requests are only available when FastMCP is running as part of a web application
54
+ - Accessing the HTTP request outside of a web request context will raise a `RuntimeError`
55
+ - The `get_http_request()` function returns a standard [Starlette Request](https://www.starlette.io/requests/) object
56
+
57
+ ## Common Use Cases
58
+
59
+ ### Accessing Request Headers
60
+
61
+ ```python
62
+ from fastmcp.server.dependencies import get_http_request
63
+
64
+ @mcp.tool()
65
+ async def get_auth_info() -> dict:
66
+ """Get authentication information from request headers."""
67
+ request = get_http_request()
68
+
69
+ # Get authorization header
70
+ auth_header = request.headers.get("authorization", "")
71
+
72
+ # Check for Bearer token
73
+ is_bearer = auth_header.startswith("Bearer ")
74
+
75
+ return {
76
+ "has_auth": bool(auth_header),
77
+ "auth_type": "Bearer" if is_bearer else "Other" if auth_header else "None"
78
+ }
79
+ ```
docs/servers/context.mdx CHANGED
@@ -21,6 +21,8 @@ The `Context` object provides a clean interface to access MCP features within yo
21
 
22
  ## Accessing the Context
23
 
 
 
24
  To use the context object within any of your functions, simply add a parameter to your function signature and type-hint it as `Context`. FastMCP will automatically inject the context instance when your function is called.
25
 
26
  **Key Points:**
@@ -32,7 +34,7 @@ To use the context object within any of your functions, simply add a parameter t
32
  - The type hint can be a union (`Context | None`) or use `Annotated[]` and it will still work properly.
33
  - Context is only available during a request; attempting to use context methods outside a request will raise errors. If you need to debug or call your context methods outside of a request, you can type your variable as `Context | None=None` to avoid missing argument errors.
34
 
35
- ### Tools
36
 
37
  ```python
38
  from fastmcp import FastMCP, Context
@@ -46,7 +48,7 @@ async def process_file(file_uri: str, ctx: Context) -> str:
46
  return "Processed file"
47
  ```
48
 
49
- ### Resources and Templates
50
 
51
  <VersionBadge version="2.2.5" />
52
 
@@ -64,7 +66,7 @@ async def get_user_profile(user_id: str, ctx: Context) -> dict:
64
  return {"id": user_id}
65
  ```
66
 
67
- ### Prompts
68
 
69
  <VersionBadge version="2.2.5" />
70
 
@@ -77,6 +79,38 @@ async def data_analysis_request(dataset: str, ctx: Context) -> str:
77
  ```
78
 
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  ## Context Capabilities
81
 
82
  ### Logging
@@ -263,7 +297,7 @@ async def request_info(ctx: Context) -> dict:
263
 
264
  For advanced use cases, you can access the underlying MCP session, FastMCP server, and HTTP requests.
265
 
266
- #### Accessing FastMCP and Sessions
267
 
268
  ```python
269
  @mcp.tool()
@@ -279,10 +313,16 @@ async def advanced_tool(ctx: Context) -> str:
279
  return f"Server: {server_name}"
280
  ```
281
 
282
- #### Accessing HTTP Requests
283
 
284
  <VersionBadge version="2.2.7" />
285
 
 
 
 
 
 
 
286
  For web applications, you can access the underlying HTTP request:
287
 
288
  ```python
@@ -307,9 +347,7 @@ async def handle_web_request(ctx: Context) -> dict:
307
  - **`ctx.fastmcp -> FastMCP`**: Access the server instance the context belongs to
308
  - **`ctx.session`**: Access the raw `mcp.server.session.ServerSession` object
309
  - **`ctx.request_context`**: Access the raw `mcp.shared.context.RequestContext` object
310
- - **`ctx.get_http_request() -> Request`**: Access the active Starlette request object (when running with a web server)
311
 
312
  <Warning>
313
  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.
314
  </Warning>
315
-
 
21
 
22
  ## Accessing the Context
23
 
24
+ ### Via Dependency Injection
25
+
26
  To use the context object within any of your functions, simply add a parameter to your function signature and type-hint it as `Context`. FastMCP will automatically inject the context instance when your function is called.
27
 
28
  **Key Points:**
 
34
  - The type hint can be a union (`Context | None`) or use `Annotated[]` and it will still work properly.
35
  - Context is only available during a request; attempting to use context methods outside a request will raise errors. If you need to debug or call your context methods outside of a request, you can type your variable as `Context | None=None` to avoid missing argument errors.
36
 
37
+ #### Tools
38
 
39
  ```python
40
  from fastmcp import FastMCP, Context
 
48
  return "Processed file"
49
  ```
50
 
51
+ #### Resources and Templates
52
 
53
  <VersionBadge version="2.2.5" />
54
 
 
66
  return {"id": user_id}
67
  ```
68
 
69
+ #### Prompts
70
 
71
  <VersionBadge version="2.2.5" />
72
 
 
79
  ```
80
 
81
 
82
+ ### Via Dependency Function
83
+
84
+ <VersionBadge version="2.2.11" />
85
+
86
+ While the simplest way to access context is through function parameter injection as shown above, there are cases where you need to access the context in code that may not be easy to modify to accept a context parameter, or that is nested deeper within your function calls.
87
+
88
+ FastMCP provides dependency functions that allow you to retrieve the active context from anywhere within a server request's execution flow:
89
+
90
+ ```python {2,9}
91
+ from fastmcp import FastMCP, Context
92
+ from fastmcp.server.dependencies import get_context
93
+
94
+ mcp = FastMCP(name="DependencyDemo")
95
+
96
+ # Utility function that needs context but doesn't receive it as a parameter
97
+ async def process_data(data: list[float]) -> dict:
98
+ # Get the active context - only works when called within a request
99
+ ctx = get_context()
100
+ await ctx.info(f"Processing {len(data)} data points")
101
+
102
+ @mcp.tool()
103
+ async def analyze_dataset(dataset_name: str) -> dict:
104
+ # Call utility function that uses context internally
105
+ data = load_data(dataset_name)
106
+ await process_data(data)
107
+ ```
108
+
109
+ **Important Notes:**
110
+
111
+ - The `get_context` function should only be used within the context of a server request. Calling it outside of a request will raise a `RuntimeError`.
112
+ - The `get_context` function is server-only and should not be used in client code.
113
+
114
  ## Context Capabilities
115
 
116
  ### Logging
 
297
 
298
  For advanced use cases, you can access the underlying MCP session, FastMCP server, and HTTP requests.
299
 
300
+ #### FastMCP Server and Sessions
301
 
302
  ```python
303
  @mcp.tool()
 
313
  return f"Server: {server_name}"
314
  ```
315
 
316
+ #### HTTP Requests
317
 
318
  <VersionBadge version="2.2.7" />
319
 
320
+ <Warning>
321
+ The `ctx.get_http_request()` method is deprecated and will be removed in a future version.
322
+ Please use the `get_http_request()` dependency function instead.
323
+ See the [HTTP Requests pattern](/patterns/http-requests) for more details.
324
+ </Warning>
325
+
326
  For web applications, you can access the underlying HTTP request:
327
 
328
  ```python
 
347
  - **`ctx.fastmcp -> FastMCP`**: Access the server instance the context belongs to
348
  - **`ctx.session`**: Access the raw `mcp.server.session.ServerSession` object
349
  - **`ctx.request_context`**: Access the raw `mcp.shared.context.RequestContext` object
 
350
 
351
  <Warning>
352
  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.
353
  </Warning>