Jeremiah Lowin commited on
Commit
df7a6d4
·
1 Parent(s): 31e3fd3

Update docs for context

Browse files
docs/servers/context.mdx CHANGED
@@ -1,16 +1,16 @@
1
  ---
2
  title: MCP Context
3
  sidebarTitle: Context
4
- description: Access MCP capabilities like logging, progress, and resources within your tools.
5
  icon: rectangle-code
6
  ---
7
  import { VersionBadge } from '/snippets/version-badge.mdx'
8
 
9
- When defining FastMCP [tools](/servers/tools), your functions might need to interact with the underlying MCP session or access server capabilities. FastMCP provides the `Context` object for this purpose.
10
 
11
  ## What Is Context?
12
 
13
- The `Context` object provides a clean interface to access MCP features within your tool functions, including:
14
 
15
  - **Logging**: Send debug, info, warning, and error messages back to the client
16
  - **Progress Reporting**: Update the client on the progress of long-running operations
@@ -21,7 +21,7 @@ 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 your tool function, simply add a parameter to your function signature and type-hint it as `Context`. FastMCP will automatically inject the context instance when your tool is called.
25
 
26
  ```python
27
  from fastmcp import FastMCP, Context
@@ -65,15 +65,15 @@ async def process_file(file_uri: str, ctx: Context) -> str:
65
 
66
  - The parameter name (e.g., `ctx`, `context`) doesn't matter, only the type hint `Context` is important.
67
  - The context parameter can be placed anywhere in your function's signature.
68
- - The context is optional - tools that don't need it can omit the parameter.
69
- - Context is only available within tool functions during a request; attempting to use context methods outside a request will raise errors.
70
- - Context methods are async, so your tool function usually needs to be async as well.
71
 
72
  ## Context Capabilities
73
 
74
  ### Logging
75
 
76
- Send log messages back to the MCP client. This is useful for debugging and providing visibility into tool execution during a request.
77
 
78
  ```python
79
  @mcp.tool()
@@ -97,14 +97,14 @@ async def analyze_data(data: list[float], ctx: Context) -> dict:
97
  **Available Logging Methods:**
98
 
99
  - **`ctx.debug(message: str)`**: Low-level details useful for debugging
100
- - **`ctx.info(message: str)`**: General information about tool execution
101
  - **`ctx.warning(message: str)`**: Potential issues that didn't prevent execution
102
  - **`ctx.error(message: str)`**: Errors that occurred during execution
103
  - **`ctx.log(level: Literal["debug", "info", "warning", "error"], message: str, logger_name: str | None = None)`**: Generic log method supporting custom logger names
104
 
105
  ### Progress Reporting
106
 
107
- For long-running tools, notify the client about the progress of the operation. This allows clients to display progress indicators and provide a better user experience.
108
 
109
  ```python
110
  @mcp.tool()
@@ -137,7 +137,7 @@ Progress reporting requires the client to have sent a `progressToken` in the ini
137
 
138
  ### Resource Access
139
 
140
- Read data from resources registered with your FastMCP server. This allows tools to access files, configuration, or dynamically generated content.
141
 
142
  ```python
143
  @mcp.tool()
@@ -177,7 +177,7 @@ The returned content is typically accessed via `content_list[0].content` and can
177
 
178
  <VersionBadge version="2.0.0" />
179
 
180
- Request the client's LLM to generate text based on provided messages. This is useful when your tool needs to leverage the LLM's capabilities to process data or generate responses.
181
 
182
  ```python
183
  @mcp.tool()
@@ -279,6 +279,60 @@ async def advanced_tool(ctx: Context) -> str:
279
  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.
280
  </Warning>
281
 
282
- ## Using Context in Other Components
283
 
284
- Currently, Context is primarily designed for use within tool functions. Support for Context in other components like resources and prompts is planned for future releases.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: MCP Context
3
  sidebarTitle: Context
4
+ description: Access MCP capabilities like logging, progress, and resources within your MCP objects.
5
  icon: rectangle-code
6
  ---
7
  import { VersionBadge } from '/snippets/version-badge.mdx'
8
 
9
+ When defining FastMCP [tools](/servers/tools), [resources](/servers/resources), resource templates, or [prompts](/servers/prompts), your functions might need to interact with the underlying MCP session or access server capabilities. FastMCP provides the `Context` object for this purpose.
10
 
11
  ## What Is Context?
12
 
13
+ The `Context` object provides a clean interface to access MCP features within your functions, including:
14
 
15
  - **Logging**: Send debug, info, warning, and error messages back to the client
16
  - **Progress Reporting**: Update the client on the progress of long-running operations
 
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
  ```python
27
  from fastmcp import FastMCP, Context
 
65
 
66
  - The parameter name (e.g., `ctx`, `context`) doesn't matter, only the type hint `Context` is important.
67
  - The context parameter can be placed anywhere in your function's signature.
68
+ - The context is optional - functions that don't need it can omit the parameter.
69
+ - Context is only available during a request; attempting to use context methods outside a request will raise errors.
70
+ - Context methods are async, so your function usually needs to be async as well.
71
 
72
  ## Context Capabilities
73
 
74
  ### Logging
75
 
76
+ Send log messages back to the MCP client. This is useful for debugging and providing visibility into function execution during a request.
77
 
78
  ```python
79
  @mcp.tool()
 
97
  **Available Logging Methods:**
98
 
99
  - **`ctx.debug(message: str)`**: Low-level details useful for debugging
100
+ - **`ctx.info(message: str)`**: General information about execution
101
  - **`ctx.warning(message: str)`**: Potential issues that didn't prevent execution
102
  - **`ctx.error(message: str)`**: Errors that occurred during execution
103
  - **`ctx.log(level: Literal["debug", "info", "warning", "error"], message: str, logger_name: str | None = None)`**: Generic log method supporting custom logger names
104
 
105
  ### Progress Reporting
106
 
107
+ For long-running operations, notify the client about the progress. This allows clients to display progress indicators and provide a better user experience.
108
 
109
  ```python
110
  @mcp.tool()
 
137
 
138
  ### Resource Access
139
 
140
+ Read data from resources registered with your FastMCP server. This allows functions to access files, configuration, or dynamically generated content.
141
 
142
  ```python
143
  @mcp.tool()
 
177
 
178
  <VersionBadge version="2.0.0" />
179
 
180
+ Request the client's LLM to generate text based on provided messages. This is useful when your function needs to leverage the LLM's capabilities to process data or generate responses.
181
 
182
  ```python
183
  @mcp.tool()
 
279
  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.
280
  </Warning>
281
 
282
+ ## Using Context in Different Components
283
 
284
+ All FastMCP components (tools, resources, templates, and prompts) can use the Context object following the same pattern - simply add a parameter with the `Context` type annotation.
285
+
286
+ ### Context in Resources and Templates
287
+
288
+ Resources and resource templates can access context to customize their behavior:
289
+
290
+ ```python
291
+ @mcp.resource("resource://user-data")
292
+ async def get_user_data(ctx: Context) -> dict:
293
+ """Fetch personalized user data based on the request context."""
294
+ user_id = ctx.client_id or "anonymous"
295
+ await ctx.info(f"Fetching data for user {user_id}")
296
+
297
+ # Example of using context for dynamic resource generation
298
+ return {
299
+ "user_id": user_id,
300
+ "last_access": datetime.now().isoformat(),
301
+ "request_id": ctx.request_id
302
+ }
303
+
304
+ @mcp.resource("resource://users/{user_id}/profile")
305
+ async def get_user_profile(user_id: str, ctx: Context) -> dict:
306
+ """Fetch user profile from database with context-aware logging."""
307
+ await ctx.info(f"Fetching profile for user {user_id}")
308
+
309
+ # Example of using context in a template resource
310
+ # In a real implementation, you might query a database
311
+ return {
312
+ "id": user_id,
313
+ "name": f"User {user_id}",
314
+ "request_id": ctx.request_id
315
+ }
316
+ ```
317
+
318
+ ### Context in Prompts
319
+
320
+ Prompts can use context to generate more dynamic templates:
321
+
322
+ ```python
323
+ @mcp.prompt()
324
+ async def data_analysis_request(dataset: str, ctx: Context) -> str:
325
+ """Generate a request to analyze data with contextual information."""
326
+ await ctx.info(f"Generating data analysis prompt for {dataset}")
327
+
328
+ # Could use context to read configuration or personalize the prompt
329
+ return f"""Please analyze the following dataset: {dataset}
330
+
331
+ Request initiated at: {datetime.now().isoformat()}
332
+ Request ID: {ctx.request_id}
333
+ """
334
+ ```
335
+
336
+ <VersionBadge version="2.3.0" />
337
+
338
+ All FastMCP objects now support context injection using the same consistent pattern, making it easy to add session-aware capabilities to all aspects of your MCP server.
docs/servers/prompts.mdx CHANGED
@@ -171,33 +171,24 @@ async def data_based_prompt(data_id: str) -> str:
171
 
172
  Use `async def` when your prompt function performs I/O operations like network requests, database queries, file I/O, or external service calls.
173
 
174
- ### The MCP Session
175
 
176
- Prompts can access the MCP features via the `Context` object, just like tools.
177
 
178
- ```python
179
- from fastmcp import Context
 
 
 
 
180
 
181
  @mcp.prompt()
182
  async def generate_report_request(report_type: str, ctx: Context) -> str:
183
- """Generates a request for a report based on available data."""
184
- # Log the request
185
- await ctx.info(f"Generating prompt for report type: {report_type}")
186
-
187
- # Could potentially use ctx.read_resource to fetch data
188
- # Or ctx.sample to get additional input from the LLM
189
-
190
- return f"Please create a {report_type} report based on the available data."
191
  ```
192
 
193
- Using the `ctx` parameter (based on its `Context` type hint), you can access:
194
-
195
- - **Logging:** `ctx.debug()`, `ctx.info()`, etc.
196
- - **Resource Access:** `ctx.read_resource(uri)`
197
- - **LLM Sampling:** `ctx.sample(...)`
198
- - **Request Info:** `ctx.request_id`, `ctx.client_id`
199
-
200
- Refer to the [Context documentation](/servers/context) for more details on these capabilities.
201
 
202
  ## Server Behavior
203
 
 
171
 
172
  Use `async def` when your prompt function performs I/O operations like network requests, database queries, file I/O, or external service calls.
173
 
174
+ ### Accessing MCP Context
175
 
176
+ <VersionBadge version="2.2.5" />
177
 
178
+ Prompts can access additional MCP information and features through the `Context` object. To access it, add a parameter to your prompt function with a type annotation of `Context`:
179
+
180
+ ```python {6}
181
+ from fastmcp import FastMCP, Context
182
+
183
+ mcp = FastMCP(name="PromptServer")
184
 
185
  @mcp.prompt()
186
  async def generate_report_request(report_type: str, ctx: Context) -> str:
187
+ """Generates a request for a report."""
188
+ return f"Please create a {report_type} report. Request ID: {ctx.request_id}"
 
 
 
 
 
 
189
  ```
190
 
191
+ For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
 
 
 
 
 
 
 
192
 
193
  ## Server Behavior
194
 
docs/servers/resources.mdx CHANGED
@@ -95,6 +95,36 @@ def get_application_status() -> dict:
95
  - **`mime_type`**: Specifies the content type (FastMCP often infers a default like `text/plain` or `application/json`, but explicit is better for non-text types).
96
  - **`tags`**: A set of strings for categorization, potentially used by clients for filtering.
97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  ### Asynchronous Resources
100
 
@@ -205,6 +235,8 @@ Note that this parameter is only available when using `add_resource()` directly
205
 
206
  Resource Templates allow clients to request resources whose content depends on parameters embedded in the URI. Define a template using the **same `@mcp.resource` decorator**, but include `{parameter_name}` placeholders in the URI string and add corresponding arguments to your function signature.
207
 
 
 
208
  Resource templates generate a new resource for each unique set of parameters, which means that resources can be dynamically created on-demand. For example, if the resource template `"user://profile/{name}"` is registered, MCP clients could request `"user://profile/ford"` or `"user://profile/marvin"` to retrieve either of those two user profiles as resources, without having to register each resource individually.
209
 
210
  Here is a complete example that shows how to define two resource templates:
@@ -379,28 +411,6 @@ In this stacked decorator pattern:
379
 
380
  Templates provide a powerful way to expose parameterized data access points following REST-like principles.
381
 
382
- ### Custom Template Keys
383
-
384
- <VersionBadge version="2.2.0" />
385
-
386
- Similar to resources, you can provide custom keys when directly adding templates:
387
-
388
- ```python
389
- from fastmcp.resources import ResourceTemplate
390
-
391
- # Create a template with a function
392
- template = ResourceTemplate.from_function(
393
- my_function,
394
- uri_template="data://{id}/details",
395
- name="Data Details"
396
- )
397
-
398
- # Register with a custom key
399
- mcp._resource_manager.add_template(template, key="custom://{id}/view")
400
- ```
401
-
402
- This allows accessing the same template implementation through different URI patterns.
403
-
404
  ## Server Behavior
405
 
406
  ### Duplicate Resources
 
95
  - **`mime_type`**: Specifies the content type (FastMCP often infers a default like `text/plain` or `application/json`, but explicit is better for non-text types).
96
  - **`tags`**: A set of strings for categorization, potentially used by clients for filtering.
97
 
98
+ ### Accessing MCP Context
99
+
100
+ <VersionBadge version="2.2.5" />
101
+
102
+ Resources and resource templates can access additional MCP information and features through the `Context` object. To access it, add a parameter to your resource function with a type annotation of `Context`:
103
+
104
+ ```python {6, 14}
105
+ from fastmcp import FastMCP, Context
106
+
107
+ mcp = FastMCP(name="DataServer")
108
+
109
+ @mcp.resource("resource://system-status")
110
+ async def get_system_status(ctx: Context) -> dict:
111
+ """Provides system status information."""
112
+ return {
113
+ "status": "operational",
114
+ "request_id": ctx.request_id
115
+ }
116
+
117
+ @mcp.resource("resource://{name}/details")
118
+ async def get_details(name: str, ctx: Context) -> dict:
119
+ """Get details for a specific name."""
120
+ return {
121
+ "name": name,
122
+ "accessed_at": ctx.request_id
123
+ }
124
+ ```
125
+
126
+ For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
127
+
128
 
129
  ### Asynchronous Resources
130
 
 
235
 
236
  Resource Templates allow clients to request resources whose content depends on parameters embedded in the URI. Define a template using the **same `@mcp.resource` decorator**, but include `{parameter_name}` placeholders in the URI string and add corresponding arguments to your function signature.
237
 
238
+ Resource templates share most configuration options with regular resources (name, description, mime_type, tags), but add the ability to define URI parameters that map to function parameters.
239
+
240
  Resource templates generate a new resource for each unique set of parameters, which means that resources can be dynamically created on-demand. For example, if the resource template `"user://profile/{name}"` is registered, MCP clients could request `"user://profile/ford"` or `"user://profile/marvin"` to retrieve either of those two user profiles as resources, without having to register each resource individually.
241
 
242
  Here is a complete example that shows how to define two resource templates:
 
411
 
412
  Templates provide a powerful way to expose parameterized data access points following REST-like principles.
413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
  ## Server Behavior
415
 
416
  ### Duplicate Resources
docs/servers/tools.mdx CHANGED
@@ -263,7 +263,8 @@ FastMCP automatically catches exceptions raised within your tool function:
263
 
264
  Using informative exceptions helps the LLM understand failures and react appropriately.
265
 
266
- ### Accessing MCP Context
 
267
 
268
  Tools can access MCP features like logging, reading resources, or reporting progress through the `Context` object. To use it, add a parameter to your tool function with the type hint `Context`.
269
 
@@ -304,39 +305,6 @@ The Context object provides access to:
304
 
305
  For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
306
 
307
- ## Server Behavior
308
-
309
- ### Duplicate Tools
310
-
311
- <VersionBadge version="2.1.0" />
312
-
313
- You can control how the FastMCP server behaves if you try to register multiple tools with the same name. This is configured using the `on_duplicate_tools` argument when creating the `FastMCP` instance.
314
-
315
- ```python
316
- from fastmcp import FastMCP
317
-
318
- mcp = FastMCP(
319
- name="StrictServer",
320
- # Configure behavior for duplicate tool names
321
- on_duplicate_tools="error"
322
- )
323
-
324
- @mcp.tool()
325
- def my_tool(): return "Version 1"
326
-
327
- # This will now raise a ValueError because 'my_tool' already exists
328
- # and on_duplicate_tools is set to "error".
329
- # @mcp.tool()
330
- # def my_tool(): return "Version 2"
331
- ```
332
-
333
- The duplicate behavior options are:
334
-
335
- - `"warn"` (default): Logs a warning and the new tool replaces the old one.
336
- - `"error"`: Raises a `ValueError`, preventing the duplicate registration.
337
- - `"replace"`: Silently replaces the existing tool with the new one.
338
- - `"ignore"`: Keeps the original tool and ignores the new registration attempt.
339
-
340
  ## Parameter Types
341
 
342
  FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools.
@@ -663,3 +631,36 @@ Common validation options include:
663
  | `description` | Any | Human-readable description (appears in schema) |
664
 
665
  When a client sends invalid data, FastMCP will return a validation error explaining why the parameter failed validation.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
  Using informative exceptions helps the LLM understand failures and react appropriately.
265
 
266
+ ## MCP Context
267
+
268
 
269
  Tools can access MCP features like logging, reading resources, or reporting progress through the `Context` object. To use it, add a parameter to your tool function with the type hint `Context`.
270
 
 
305
 
306
  For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308
  ## Parameter Types
309
 
310
  FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools.
 
631
  | `description` | Any | Human-readable description (appears in schema) |
632
 
633
  When a client sends invalid data, FastMCP will return a validation error explaining why the parameter failed validation.
634
+
635
+ ## Server Behavior
636
+
637
+ ### Duplicate Tools
638
+
639
+ <VersionBadge version="2.1.0" />
640
+
641
+ You can control how the FastMCP server behaves if you try to register multiple tools with the same name. This is configured using the `on_duplicate_tools` argument when creating the `FastMCP` instance.
642
+
643
+ ```python
644
+ from fastmcp import FastMCP
645
+
646
+ mcp = FastMCP(
647
+ name="StrictServer",
648
+ # Configure behavior for duplicate tool names
649
+ on_duplicate_tools="error"
650
+ )
651
+
652
+ @mcp.tool()
653
+ def my_tool(): return "Version 1"
654
+
655
+ # This will now raise a ValueError because 'my_tool' already exists
656
+ # and on_duplicate_tools is set to "error".
657
+ # @mcp.tool()
658
+ # def my_tool(): return "Version 2"
659
+ ```
660
+
661
+ The duplicate behavior options are:
662
+
663
+ - `"warn"` (default): Logs a warning and the new tool replaces the old one.
664
+ - `"error"`: Raises a `ValueError`, preventing the duplicate registration.
665
+ - `"replace"`: Silently replaces the existing tool with the new one.
666
+ - `"ignore"`: Keeps the original tool and ignores the new registration attempt.