You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
10
10
11
11
## What Is Context?
12
12
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:
14
14
15
15
-**Logging**: Send debug, info, warning, and error messages back to the client
16
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
21
22
22
## Accessing the Context
23
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.
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.
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.
108
108
109
109
```python
110
110
@mcp.tool()
@@ -137,7 +137,7 @@ Progress reporting requires the client to have sent a `progressToken` in the ini
137
137
138
138
### Resource Access
139
139
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.
141
141
142
142
```python
143
143
@mcp.tool()
@@ -177,7 +177,7 @@ The returned content is typically accessed via `content_list[0].content` and can
177
177
178
178
<VersionBadgeversion="2.0.0" />
179
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.
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.
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
280
</Warning>
281
281
282
-
## Using Context in Other Components
282
+
## Using Context in Different Components
283
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.
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
+
asyncdefget_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
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.
Use `async def` when your prompt function performs I/O operations like network requests, database queries, file I/O, or external service calls.
173
173
174
-
### The MCP Session
174
+
### Accessing MCP Context
175
175
176
-
Prompts can access the MCP features via the `Context` object, just like tools.
176
+
<VersionBadgeversion="2.2.5" />
177
177
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`:
-**`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
96
-**`tags`**: A set of strings for categorization, potentially used by clients for filtering.
97
97
98
+
### Accessing MCP Context
99
+
100
+
<VersionBadgeversion="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`:
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
127
+
98
128
99
129
### Asynchronous Resources
100
130
@@ -205,6 +235,8 @@ Note that this parameter is only available when using `add_resource()` directly
205
235
206
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.
207
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
+
208
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.
209
241
210
242
Here is a complete example that shows how to define two resource templates:
@@ -379,28 +411,6 @@ In this stacked decorator pattern:
379
411
380
412
Templates provide a powerful way to expose parameterized data access points following REST-like principles.
381
413
382
-
### Custom Template Keys
383
-
384
-
<VersionBadgeversion="2.2.0" />
385
-
386
-
Similar to resources, you can provide custom keys when directly adding templates:
Copy file name to clipboardExpand all lines: docs/servers/tools.mdx
+35-34Lines changed: 35 additions & 34 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -263,7 +263,8 @@ FastMCP automatically catches exceptions raised within your tool function:
263
263
264
264
Using informative exceptions helps the LLM understand failures and react appropriately.
265
265
266
-
### Accessing MCP Context
266
+
## MCP Context
267
+
267
268
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`.
269
270
@@ -304,39 +305,6 @@ The Context object provides access to:
304
305
305
306
For full documentation on the Context object and all its capabilities, see the [Context documentation](/servers/context).
306
307
307
-
## Server Behavior
308
-
309
-
### Duplicate Tools
310
-
311
-
<VersionBadgeversion="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
-
defmy_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
308
## Parameter Types
341
309
342
310
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
631
|`description`| Any | Human-readable description (appears in schema) |
664
632
665
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
+
<VersionBadgeversion="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
+
defmy_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