Skip to content

Commit d4926d1

Browse files
committed
Improve README around the Context object
Enhanced Context and Tools sections with documentation of Context object injection, properties, and methods.
1 parent 959d4e3 commit d4926d1

File tree

1 file changed

+82
-1
lines changed

1 file changed

+82
-1
lines changed

README.md

Lines changed: 82 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,35 @@ def get_weather(city: str, unit: str = "celsius") -> str:
303303
_Full example: [examples/snippets/servers/basic_tool.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/basic_tool.py)_
304304
<!-- /snippet-source -->
305305

306+
Tools can optionally receive a Context object by including a parameter with the `Context` type annotation. This context is automatically injected by the FastMCP framework and provides access to MCP capabilities:
307+
308+
<!-- snippet-source examples/snippets/servers/tool_progress.py -->
309+
```python
310+
from mcp.server.fastmcp import Context, FastMCP
311+
312+
mcp = FastMCP(name="Progress Example")
313+
314+
315+
@mcp.tool()
316+
async def long_running_task(task_name: str, ctx: Context, steps: int = 5) -> str:
317+
"""Execute a task with progress updates."""
318+
await ctx.info(f"Starting: {task_name}")
319+
320+
for i in range(steps):
321+
progress = (i + 1) / steps
322+
await ctx.report_progress(
323+
progress=progress,
324+
total=1.0,
325+
message=f"Step {i + 1}/{steps}",
326+
)
327+
await ctx.debug(f"Completed step {i + 1}")
328+
329+
return f"Task '{task_name}' completed"
330+
```
331+
332+
_Full example: [examples/snippets/servers/tool_progress.py](https://github.com/modelcontextprotocol/python-sdk/blob/main/examples/snippets/servers/tool_progress.py)_
333+
<!-- /snippet-source -->
334+
306335
#### Structured Output
307336

308337
Tools will return structured results by default, if their return type
@@ -496,7 +525,59 @@ _Full example: [examples/snippets/servers/images.py](https://github.com/modelcon
496525

497526
### Context
498527

499-
The Context object gives your tools and resources access to MCP capabilities:
528+
The Context object is automatically injected into tool and resource functions that request it via type hints. It provides access to MCP capabilities like logging, progress reporting, resource reading, user interaction, and request metadata.
529+
530+
#### Getting Context in Functions
531+
532+
To use context in a tool or resource function, add a parameter with the `Context` type annotation:
533+
534+
```python
535+
from mcp.server.fastmcp import Context, FastMCP
536+
537+
mcp = FastMCP(name="Context Example")
538+
539+
540+
@mcp.tool()
541+
async def my_tool(x: int, ctx: Context) -> str:
542+
"""Tool that uses context capabilities."""
543+
# The context parameter can have any name as long as it's type-annotated
544+
return await process_with_context(x, ctx)
545+
```
546+
547+
#### Context Properties and Methods
548+
549+
The Context object provides the following capabilities:
550+
551+
**Request Information:**
552+
553+
- `ctx.request_id` - Unique ID for the current request
554+
- `ctx.client_id` - Client ID if available
555+
- `ctx.session` - Access to the underlying session for advanced usage
556+
557+
**Logging Methods:**
558+
559+
- `await ctx.debug(message)` - Send debug log message
560+
- `await ctx.info(message)` - Send info log message
561+
- `await ctx.warning(message)` - Send warning log message
562+
- `await ctx.error(message)` - Send error log message
563+
- `await ctx.log(level, message, logger_name=None)` - Send log with custom level
564+
565+
**Progress Reporting:**
566+
567+
- `await ctx.report_progress(progress, total=None, message=None)` - Report operation progress
568+
569+
**Resource Access:**
570+
571+
- `await ctx.read_resource(uri)` - Read a resource by URI
572+
573+
**User Interaction:**
574+
575+
- `await ctx.elicit(message, schema)` - Request additional information from user with validation
576+
577+
**Server Access:**
578+
579+
- `ctx.fastmcp` - Access to the FastMCP server instance
580+
- `ctx.request_context` - Access to the underlying request context for advanced usage
500581

501582
<!-- snippet-source examples/snippets/servers/tool_progress.py -->
502583
```python

0 commit comments

Comments
 (0)