Previously in FastMCP, the powerful Context object – the gateway to MCP features like logging, progress reporting, resource access, and client LLM sampling – was only easily accessible in MCP tool functions. While tools are central to MCP, this limited where you could add dynamic, session-aware logic.
Starting with FastMCP 2.2.5, the Context object is now available across all FastMCP components! You can now seamlessly inject and use context within:
- Tools (
@tool()) - Resources (
@resource("resource://user")) - Resource templates (e.g.,
@resource("resource://users/{user_id}")) - Prompt functions (
@prompt())
In all cases, the pattern is the same: add a keyword argument to your decorated function and give it a type hint of Context. FastMCP will detect the annotation and inject the correct context automatically.
from fastmcp import FastMCP, Context
mcp = FastMCP(name="ContextDemo")
@mcp.tool()async def add(a: int, b: int, ctx: Context) -> int: # ctx will be automatically injected by FastMCP await ctx.debug(f"Adding {a} and {b}") return a + bIn addition to logging, Context allows you to take advantage of powerful features like client LLM sampling.
For more details, see the FastMCP Context documentation.
