MCPcopy Index your code
hub / github.com/modelcontextprotocol/python-sdk / Context

Class Context

src/mcp/server/mcpserver/context.py:25–308  ·  view source on GitHub ↗

Context object providing access to MCP capabilities. This provides a cleaner interface to MCP's RequestContext functionality. It gets injected into tool and resource functions that request it via type hints. To use context in a tool function, add a parameter with the Context type annot

Source from the content-addressed store, hash-verified

23
24
25class Context(BaseModel, Generic[LifespanContextT, RequestT]):
26 """Context object providing access to MCP capabilities.
27
28 This provides a cleaner interface to MCP's RequestContext functionality.
29 It gets injected into tool and resource functions that request it via type hints.
30
31 To use context in a tool function, add a parameter with the Context type annotation:
32
33 ```python
34 @server.tool()
35 async def my_tool(x: int, ctx: Context) -> str:
36 # Log messages to the client
37 await ctx.info(f"Processing {x}")
38 await ctx.debug("Debug info")
39 await ctx.warning("Warning message")
40 await ctx.error("Error message")
41
42 # Report progress
43 await ctx.report_progress(50, 100)
44
45 # Access resources
46 data = await ctx.read_resource("resource://data")
47
48 # Get request info
49 request_id = ctx.request_id
50 client_id = ctx.client_id
51
52 return str(x)
53 ```
54
55 The context parameter name can be anything as long as it's annotated with Context.
56 The context is optional - tools that don't need it can omit the parameter.
57 """
58
59 _request_context: ServerRequestContext[LifespanContextT, RequestT] | None
60 _mcp_server: MCPServer | None
61 _input_params: InputResponseRequestParams | None
62
63 # TODO(maxisbey): Consider making request_context/mcp_server required, or refactor Context entirely.
64 def __init__(
65 self,
66 *,
67 request_context: ServerRequestContext[LifespanContextT, RequestT] | None = None,
68 mcp_server: MCPServer | None = None,
69 input_params: InputResponseRequestParams | None = None,
70 # TODO(Marcelo): We should drop this kwargs parameter.
71 **kwargs: Any,
72 ):
73 super().__init__(**kwargs)
74 self._request_context = request_context
75 self._mcp_server = mcp_server
76 self._input_params = input_params
77
78 @property
79 def mcp_server(self) -> MCPServer:
80 """Access to the MCPServer instance."""
81 if self._mcp_server is None: # pragma: no cover
82 raise ValueError("Context is not available outside of a request")

Calls

no outgoing calls