Skip to content

Commit eefaade

Browse files
committed
Update docs for context
1 parent ef432ad commit eefaade

File tree

4 files changed

+146
-90
lines changed

4 files changed

+146
-90
lines changed

docs/servers/context.mdx

Lines changed: 68 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
---
22
title: MCP Context
33
sidebarTitle: Context
4-
description: Access MCP capabilities like logging, progress, and resources within your tools.
4+
description: Access MCP capabilities like logging, progress, and resources within your MCP objects.
55
icon: rectangle-code
66
---
77
import { VersionBadge } from '/snippets/version-badge.mdx'
88

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.
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.
1010

1111
## What Is Context?
1212

13-
The `Context` object provides a clean interface to access MCP features within your tool functions, including:
13+
The `Context` object provides a clean interface to access MCP features within your functions, including:
1414

1515
- **Logging**: Send debug, info, warning, and error messages back to the client
1616
- **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
2121

2222
## Accessing the Context
2323

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.
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.
2525

2626
```python
2727
from fastmcp import FastMCP, Context
@@ -65,15 +65,15 @@ async def process_file(file_uri: str, ctx: Context) -> str:
6565

6666
- The parameter name (e.g., `ctx`, `context`) doesn't matter, only the type hint `Context` is important.
6767
- 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.
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.
7171

7272
## Context Capabilities
7373

7474
### Logging
7575

76-
Send log messages back to the MCP client. This is useful for debugging and providing visibility into tool execution during a request.
76+
Send log messages back to the MCP client. This is useful for debugging and providing visibility into function execution during a request.
7777

7878
```python
7979
@mcp.tool()
@@ -97,14 +97,14 @@ async def analyze_data(data: list[float], ctx: Context) -> dict:
9797
**Available Logging Methods:**
9898

9999
- **`ctx.debug(message: str)`**: Low-level details useful for debugging
100-
- **`ctx.info(message: str)`**: General information about tool execution
100+
- **`ctx.info(message: str)`**: General information about execution
101101
- **`ctx.warning(message: str)`**: Potential issues that didn't prevent execution
102102
- **`ctx.error(message: str)`**: Errors that occurred during execution
103103
- **`ctx.log(level: Literal["debug", "info", "warning", "error"], message: str, logger_name: str | None = None)`**: Generic log method supporting custom logger names
104104

105105
### Progress Reporting
106106

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.
107+
For long-running operations, notify the client about the progress. This allows clients to display progress indicators and provide a better user experience.
108108

109109
```python
110110
@mcp.tool()
@@ -137,7 +137,7 @@ Progress reporting requires the client to have sent a `progressToken` in the ini
137137

138138
### Resource Access
139139

140-
Read data from resources registered with your FastMCP server. This allows tools to access files, configuration, or dynamically generated content.
140+
Read data from resources registered with your FastMCP server. This allows functions to access files, configuration, or dynamically generated content.
141141

142142
```python
143143
@mcp.tool()
@@ -177,7 +177,7 @@ The returned content is typically accessed via `content_list[0].content` and can
177177

178178
<VersionBadge version="2.0.0" />
179179

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.
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.
181181

182182
```python
183183
@mcp.tool()
@@ -279,6 +279,60 @@ async def advanced_tool(ctx: Context) -> str:
279279
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.
280280
</Warning>
281281

282-
## Using Context in Other Components
282+
## Using Context in Different Components
283283

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.
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

Lines changed: 11 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -171,33 +171,24 @@ async def data_based_prompt(data_id: str) -> str:
171171

172172
Use `async def` when your prompt function performs I/O operations like network requests, database queries, file I/O, or external service calls.
173173

174-
### The MCP Session
174+
### Accessing MCP Context
175175

176-
Prompts can access the MCP features via the `Context` object, just like tools.
176+
<VersionBadge version="2.2.5" />
177177

178-
```python
179-
from fastmcp import Context
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")
180184

181185
@mcp.prompt()
182186
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."
187+
"""Generates a request for a report."""
188+
return f"Please create a {report_type} report. Request ID: {ctx.request_id}"
191189
```
192190

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.
191+
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
201192

202193
## Server Behavior
203194

docs/servers/resources.mdx

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,36 @@ def get_application_status() -> dict:
9595
- **`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).
9696
- **`tags`**: A set of strings for categorization, potentially used by clients for filtering.
9797

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+
98128

99129
### Asynchronous Resources
100130

@@ -205,6 +235,8 @@ Note that this parameter is only available when using `add_resource()` directly
205235

206236
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.
207237

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+
208240
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.
209241

210242
Here is a complete example that shows how to define two resource templates:
@@ -379,28 +411,6 @@ In this stacked decorator pattern:
379411

380412
Templates provide a powerful way to expose parameterized data access points following REST-like principles.
381413

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-
404414
## Server Behavior
405415

406416
### Duplicate Resources

docs/servers/tools.mdx

Lines changed: 35 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,8 @@ FastMCP automatically catches exceptions raised within your tool function:
263263

264264
Using informative exceptions helps the LLM understand failures and react appropriately.
265265

266-
### Accessing MCP Context
266+
## MCP Context
267+
267268

268269
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`.
269270

@@ -304,39 +305,6 @@ The Context object provides access to:
304305

305306
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
306307

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-
340308
## Parameter Types
341309

342310
FastMCP supports a wide variety of parameter types to give you flexibility when designing your tools.
@@ -663,3 +631,36 @@ Common validation options include:
663631
| `description` | Any | Human-readable description (appears in schema) |
664632

665633
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.

0 commit comments

Comments
 (0)