Spaces:
Running
Running
File size: 15,663 Bytes
6e94ee5 df7a6d4 6e94ee5 c36510a 6e94ee5 1a68f2c 6e94ee5 df7a6d4 6e94ee5 815bac1 5375b3a 6e94ee5 2dc7995 6e94ee5 719c995 df7a6d4 6e94ee5 3cbdde4 719c995 3cbdde4 1a68f2c 6e94ee5 1a68f2c 6e94ee5 21b0f29 6e94ee5 3cbdde4 6e94ee5 719c995 6e94ee5 3cbdde4 6e94ee5 1a68f2c 3cbdde4 6e94ee5 719c995 6e94ee5 3cbdde4 6e94ee5 1a68f2c 26b329e 3cbdde4 6e94ee5 341332a 719c995 1a68f2c 719c995 1a68f2c 719c995 21b0f29 719c995 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 c36510a 1a68f2c 6e94ee5 1a68f2c 6e94ee5 1a68f2c 6e94ee5 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 1a68f2c 815bac1 5375b3a 6dcf299 5375b3a 815bac1 1a68f2c 6fe9090 1a68f2c 6e94ee5 21b0f29 6e94ee5 dcaa53c 6e94ee5 1a68f2c 341332a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 | ---
title: MCP Context
sidebarTitle: Context
description: Access MCP capabilities like logging, progress, and resources within your MCP objects.
icon: rectangle-code
---
import { VersionBadge } from '/snippets/version-badge.mdx'
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 advanced server capabilities. FastMCP provides the `Context` object for this purpose.
## What Is Context?
The `Context` object provides a clean interface to access MCP features within your functions, including:
- **Logging**: Send debug, info, warning, and error messages back to the client
- **Progress Reporting**: Update the client on the progress of long-running operations
- **Resource Access**: Read data from resources registered with the server
- **LLM Sampling**: Request the client's LLM to generate text based on provided messages
- **User Elicitation**: Request structured input from users during tool execution
- **State Management**: Store and share data across middleware and tool calls within a request
- **Request Information**: Access metadata about the current request
- **Server Access**: When needed, access the underlying FastMCP server instance
## Accessing the Context
### Via Dependency Injection
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.
**Key Points:**
- The parameter name (e.g., `ctx`, `context`) doesn't matter, only the type hint `Context` is important.
- The context parameter can be placed anywhere in your function's signature; it will not be exposed to MCP clients as a valid parameter.
- The context is optional - functions that don't need it can omit the parameter entirely.
- Context methods are async, so your function usually needs to be async as well.
- The type hint can be a union (`Context | None`) or use `Annotated[]` and it will still work properly.
- 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.
#### Tools
```python {1, 6}
from fastmcp import FastMCP, Context
mcp = FastMCP(name="Context Demo")
@mcp.tool
async def process_file(file_uri: str, ctx: Context) -> str:
"""Processes a file, using context for logging and resource access."""
# Context is available as the ctx parameter
return "Processed file"
```
#### Resources and Templates
<VersionBadge version="2.2.5" />
```python {1, 6, 12}
from fastmcp import FastMCP, Context
mcp = FastMCP(name="Context Demo")
@mcp.resource("resource://user-data")
async def get_user_data(ctx: Context) -> dict:
"""Fetch personalized user data based on the request context."""
# Context is available as the ctx parameter
return {"user_id": "example"}
@mcp.resource("resource://users/{user_id}/profile")
async def get_user_profile(user_id: str, ctx: Context) -> dict:
"""Fetch user profile with context-aware logging."""
# Context is available as the ctx parameter
return {"id": user_id}
```
#### Prompts
<VersionBadge version="2.2.5" />
```python {1, 6}
from fastmcp import FastMCP, Context
mcp = FastMCP(name="Context Demo")
@mcp.prompt
async def data_analysis_request(dataset: str, ctx: Context) -> str:
"""Generate a request to analyze data with contextual information."""
# Context is available as the ctx parameter
return f"Please analyze the following dataset: {dataset}"
```
### Via Runtime Dependency Function
<VersionBadge version="2.2.11" />
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.
FastMCP provides dependency functions that allow you to retrieve the active context from anywhere within a server request's execution flow:
```python {2,9}
from fastmcp import FastMCP
from fastmcp.server.dependencies import get_context
mcp = FastMCP(name="Dependency Demo")
# Utility function that needs context but doesn't receive it as a parameter
async def process_data(data: list[float]) -> dict:
# Get the active context - only works when called within a request
ctx = get_context()
await ctx.info(f"Processing {len(data)} data points")
@mcp.tool
async def analyze_dataset(dataset_name: str) -> dict:
# Call utility function that uses context internally
data = load_data(dataset_name)
await process_data(data)
```
**Important Notes:**
- 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`.
- The `get_context` function is server-only and should not be used in client code.
## Context Capabilities
FastMCP provides several advanced capabilities through the context object. Each capability has dedicated documentation with comprehensive examples and best practices:
### Logging
Send debug, info, warning, and error messages back to the MCP client for visibility into function execution.
```python
await ctx.debug("Starting analysis")
await ctx.info(f"Processing {len(data)} items")
await ctx.warning("Deprecated parameter used")
await ctx.error("Processing failed")
```
See [Server Logging](/servers/logging) for complete documentation and examples.
### Client Elicitation
<VersionBadge version="2.10.0" />
Request structured input from clients during tool execution, enabling interactive workflows and progressive disclosure. This is a new feature in the 6/18/2025 MCP spec.
```python
result = await ctx.elicit("Enter your name:", response_type=str)
if result.action == "accept":
name = result.data
```
See [User Elicitation](/servers/elicitation) for detailed examples and supported response types.
### LLM Sampling
<VersionBadge version="2.0.0" />
Request the client's LLM to generate text based on provided messages, useful for leveraging AI capabilities within your tools.
```python
response = await ctx.sample("Analyze this data", temperature=0.7)
```
See [LLM Sampling](/servers/sampling) for comprehensive usage and advanced techniques.
### Progress Reporting
Update clients on the progress of long-running operations, enabling progress indicators and better user experience.
```python
await ctx.report_progress(progress=50, total=100) # 50% complete
```
See [Progress Reporting](/servers/progress) for detailed patterns and examples.
### Resource Access
Read data from resources registered with your FastMCP server, allowing access to files, configuration, or dynamic content.
```python
content_list = await ctx.read_resource("resource://config")
content = content_list[0].content
```
**Method signature:**
- **`ctx.read_resource(uri: str | AnyUrl) -> list[ReadResourceContents]`**: Returns a list of resource content parts
### State Management
<VersionBadge version="2.11.0" />
Store and share data across middleware and tool calls within a request. Context objects maintain a state dictionary that's especially useful for passing information from [middleware](/servers/middleware) to your tools.
To store a value in the context state, use `ctx.set_state(key, value)`. To retrieve a value, use `ctx.get_state(key)`.
This simplified example shows how to use MCP middleware to store user info in the context state, and how to access that state in a tool:
```python {7-8, 16-17}
from fastmcp.server.middleware import Middleware, MiddlewareContext
class UserAuthMiddleware(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next):
# Middleware stores user info in context state
context.fastmcp_context.set_state("user_id", "user_123")
context.fastmcp_context.set_state("permissions", ["read", "write"])
return await call_next()
@mcp.tool
async def secure_operation(data: str, ctx: Context) -> str:
"""Tool can access state set by middleware."""
user_id = ctx.get_state("user_id") # "user_123"
permissions = ctx.get_state("permissions") # ["read", "write"]
if "write" not in permissions:
return "Access denied"
return f"Processing {data} for user {user_id}"
```
**Method signatures:**
- **`ctx.set_state(key: str, value: Any) -> None`**: Store a value in the context state
- **`ctx.get_state(key: str) -> Any`**: Retrieve a value from the context state (returns None if not found)
**State Inheritance:**
When a new context is created (nested contexts), it inherits a copy of its parent's state. This ensures that:
- State set on a child context never affects the parent context
- State set on a parent context after the child context is initialized is not propagated to the child context
This makes state management predictable and prevents unexpected side effects between nested operations.
### Change Notifications
<VersionBadge version="2.9.1" />
FastMCP automatically sends list change notifications when components (such as tools, resources, or prompts) are added, removed, enabled, or disabled. In rare cases where you need to manually trigger these notifications, you can use the context methods:
```python
@mcp.tool
async def custom_tool_management(ctx: Context) -> str:
"""Example of manual notification after custom tool changes."""
# After making custom changes to tools
await ctx.send_tool_list_changed()
await ctx.send_resource_list_changed()
await ctx.send_prompt_list_changed()
return "Notifications sent"
```
These methods are primarily used internally by FastMCP's automatic notification system and most users will not need to invoke them directly.
### FastMCP Server
To access the underlying FastMCP server instance, you can use the `ctx.fastmcp` property:
```python
@mcp.tool
async def my_tool(ctx: Context) -> None:
# Access the FastMCP server instance
server_name = ctx.fastmcp.name
...
```
### MCP Request
Access metadata about the current request and client.
```python
@mcp.tool
async def request_info(ctx: Context) -> dict:
"""Return information about the current request."""
return {
"request_id": ctx.request_id,
"client_id": ctx.client_id or "Unknown client"
}
```
**Available Properties:**
- **`ctx.request_id -> str`**: Get the unique ID for the current MCP request
- **`ctx.client_id -> str | None`**: Get the ID of the client making the request, if provided during initialization
- **`ctx.session_id -> str | None`**: Get the MCP session ID for session-based data sharing (HTTP transports only)
<Warning>
The MCP request is part of the low-level MCP SDK and intended for advanced use cases. Most users will not need to use it directly.
</Warning>
## Runtime Dependencies
### HTTP Requests
<VersionBadge version="2.2.11" />
The recommended way to access the current HTTP request is through the `get_http_request()` dependency function:
```python {2, 3, 11}
from fastmcp import FastMCP
from fastmcp.server.dependencies import get_http_request
from starlette.requests import Request
mcp = FastMCP(name="HTTP Request Demo")
@mcp.tool
async def user_agent_info() -> dict:
"""Return information about the user agent."""
# Get the HTTP request
request: Request = get_http_request()
# Access request data
user_agent = request.headers.get("user-agent", "Unknown")
client_ip = request.client.host if request.client else "Unknown"
return {
"user_agent": user_agent,
"client_ip": client_ip,
"path": request.url.path,
}
```
This approach works anywhere within a request's execution flow, not just within your MCP function. It's useful when:
1. You need access to HTTP information in helper functions
2. You're calling nested functions that need HTTP request data
3. You're working with middleware or other request processing code
### HTTP Headers
<VersionBadge version="2.2.11" />
If you only need request headers and want to avoid potential errors, you can use the `get_http_headers()` helper:
```python {2, 10}
from fastmcp import FastMCP
from fastmcp.server.dependencies import get_http_headers
mcp = FastMCP(name="Headers Demo")
@mcp.tool
async def safe_header_info() -> dict:
"""Safely get header information without raising errors."""
# Get headers (returns empty dict if no request context)
headers = get_http_headers()
# Get authorization header
auth_header = headers.get("authorization", "")
is_bearer = auth_header.startswith("Bearer ")
return {
"user_agent": headers.get("user-agent", "Unknown"),
"content_type": headers.get("content-type", "Unknown"),
"has_auth": bool(auth_header),
"auth_type": "Bearer" if is_bearer else "Other" if auth_header else "None",
"headers_count": len(headers)
}
```
By default, `get_http_headers()` excludes problematic headers like `host` and `content-length`. To include all headers, use `get_http_headers(include_all=True)`.
### Access Tokens
<VersionBadge version="2.11.0" />
When using authentication with your FastMCP server, you can access the authenticated user's access token information using the `get_access_token()` dependency function:
```python {2, 10}
from fastmcp import FastMCP
from fastmcp.server.dependencies import get_access_token, AccessToken
mcp = FastMCP(name="Auth Token Demo")
@mcp.tool
async def get_user_info() -> dict:
"""Get information about the authenticated user."""
# Get the access token (None if not authenticated)
token: AccessToken | None = get_access_token()
if token is None:
return {"authenticated": False}
return {
"authenticated": True,
"client_id": token.client_id,
"scopes": token.scopes,
"expires_at": token.expires_at,
"token_claims": token.claims, # JWT claims or custom token data
}
```
This is particularly useful when you need to:
1. **Access user identification** - Get the `client_id` or subject from token claims
2. **Check permissions** - Verify scopes or custom claims before performing operations
3. **Multi-tenant applications** - Extract tenant information from token claims
4. **Audit logging** - Track which user performed which actions
#### Working with Token Claims
The `claims` field contains all the data from the original token (JWT claims for JWT tokens, or custom data for other token types):
```python {2, 3, 9, 12, 15}
from fastmcp import FastMCP
from fastmcp.server.dependencies import get_access_token
mcp = FastMCP(name="Multi-tenant Demo")
@mcp.tool
async def get_tenant_data(resource_id: str) -> dict:
"""Get tenant-specific data using token claims."""
token: AccessToken | None = get_access_token()
# Extract tenant ID from token claims
tenant_id = token.claims.get("tenant_id") if token else None
# Extract user ID from standard JWT subject claim
user_id = token.claims.get("sub") if token else None
# Use tenant and user info to authorize and filter data
if not tenant_id:
raise ValueError("No tenant information in token")
return {
"resource_id": resource_id,
"tenant_id": tenant_id,
"user_id": user_id,
"data": f"Tenant-specific data for {tenant_id}",
}
```
|