π The fast, Pythonic way to build MCP servers and clients.
Add context calls
Jeremiah Lowin384468830c2e
diff --git a/src/fastmcp/server.py b/src/fastmcp/server.pyindex d70bb90ee..3f3e736c5 100644--- a/src/fastmcp/server.py+++ b/src/fastmcp/server.py@@ -119,12 +119,22 @@ class FastMCP:for info in tools]+ def get_context(self) -> Optional["Context"]:+ try:+ request_context = self._mcp_server.request_context+ return Context(request_context=request_context, fastmcp=self)+ except LookupError:+ return None+async def call_tool(self, name: str, arguments: dict) -> Sequence[Union[TextContent, ImageContent]]:"""Call a tool by name with arguments."""try:- result = await self._tool_manager.call_tool(name, arguments)+ context = self.get_context()+ result = await self._tool_manager.call_tool(+ name, arguments, context=context+ )return _convert_to_content(result)except Exception as e:logger.error(f"Error calling tool {name}: {e}")@@ -385,9 +395,24 @@ class Context(BaseModel):"""_request_context: RequestContext- fastmcp: FastMCP+ _fastmcp: FastMCP++ def __init__(+ self, *, request_context: RequestContext, fastmcp: FastMCP, **kwargs: Any+ ):+ super().__init__(**kwargs)+ self._request_context = request_context+ self._fastmcp = fastmcp- model_config: dict = dict(arbitrary_types_allowed=True)+ @property+ def fastmcp(self) -> FastMCP:+ """Access to the FastMCP server."""+ return self._fastmcp++ @property+ def request_context(self) -> RequestContext:+ """Access to the underlying request context."""+ return self._request_contextasync def report_progress(self, progress: float, total: Optional[float] = None@@ -400,15 +425,15 @@ class Context(BaseModel):"""progress_token = (- self._request_context.meta.progressToken- if self._request_context.meta+ self.request_context.meta.progressToken+ if self.request_context.metaelse None)if not progress_token:return- await self._request_context.session.send_progress_notification(+ await self.request_context.session.send_progress_notification(progress_token=progress_token, progress=progress, total=total)@@ -421,7 +446,7 @@ class Context(BaseModel):Returns:The resource content as either text or bytes"""- return await self.fastmcp.read_resource(uri)+ return await self._fastmcp.read_resource(uri)def log(self,@@ -429,7 +454,6 @@ class Context(BaseModel):message: str,*,logger_name: Optional[str] = None,- **extra: Any,) -> None:"""Send a log message to the client.@@ -439,26 +463,24 @@ class Context(BaseModel):logger_name: Optional logger name**extra: Additional structured data to include"""- self._request_context.session.send_log_message(- level=level, data=message, logger=logger_name, extra=extra+ self.request_context.session.send_log_message(+ level=level, data=message, logger=logger_name)@propertydef client_id(self) -> Optional[str]:"""Get the client ID if available."""- return (- self._request_context.meta.clientId if self._request_context.meta else None- )+ return self.request_context.meta.clientId if self.request_context.meta else None@propertydef request_id(self) -> str:"""Get the unique ID for this request."""- return self._request_context.request_id+ return self.request_context.request_id@propertydef session(self):"""Access to the underlying session for advanced usage."""- return self._request_context.session+ return self.request_context.session# Convenience methods for common log levelsdef debug(self, message: str, **extra: Any) -> None:diff --git a/src/fastmcp/tools.py b/src/fastmcp/tools.pyindex 351d3eb27..7c87c3b91 100644--- a/src/fastmcp/tools.py+++ b/src/fastmcp/tools.py@@ -1,12 +1,16 @@"""Tool management for FastMCP."""import inspect-from typing import Any, Callable, Dict, Optional+from typing import Any, Callable, Dict, Optional, TYPE_CHECKINGfrom pydantic import BaseModel, Field, TypeAdapter, validate_callfrom .exceptions import ToolErrorfrom .utilities.logging import get_logger+import fastmcp++if TYPE_CHECKING:+ from fastmcp.server import Contextlogger = get_logger(__name__)@@ -19,6 +23,9 @@ class Tool(BaseModel):description: str = Field(description="Description of what the tool does")parameters: dict = Field(description="JSON schema for tool parameters")is_async: bool = Field(description="Whether the tool is async")+ context_kwarg: Optional[str] = Field(+ None, description="Name of the kwarg that should receive context"+ )@classmethoddef from_function(@@ -26,6 +33,7 @@ class Tool(BaseModel):func: Callable,name: Optional[str] = None,description: Optional[str] = None,+ context_kwarg: Optional[str] = None,) -> "Tool":"""Create a Tool from a function."""func_name = name or func.__name__@@ -39,6 +47,14 @@ class Tool(BaseModel):# Get schema from TypeAdapter - will fail if function isn't properly typedparameters = TypeAdapter(func).json_schema()+ # Find context parameter if it exists+ if context_kwarg is None:+ sig = inspect.signature(func)+ for param_name, param in sig.parameters.items():+ if param.annotation is fastmcp.Context:+ context_kwarg = param_name+ break+# ensure the arguments are properly castfunc = validate_call(func)@@ -48,11 +64,16 @@ class Tool(BaseModel):description=func_doc,parameters=parameters,is_async=is_async,+ context_kwarg=context_kwarg,)- async def run(self, arguments: dict) -> Any:+ async def run(self, arguments: dict, context: Optional["Context"] = None) -> Any:"""Run the tool with arguments."""try:+ # Inject context if needed+ if self.context_kwarg and context:+ arguments[self.context_kwarg] = context+# Call function with proper async handlingif self.is_async:return await self.func(**arguments)@@ -92,10 +113,12 @@ class ToolManager:self._tools[tool.name] = toolreturn tool- async def call_tool(self, name: str, arguments: dict) -> Any:+ async def call_tool(+ self, name: str, arguments: dict, context: Optional["Context"] = None+ ) -> Any:"""Call a tool by name with arguments."""tool = self.get_tool(name)if not tool:raise ToolError(f"Unknown tool: {name}")- return await tool.run(arguments)+ return await tool.run(arguments, context=context)diff --git a/tests/test_server.py b/tests/test_server.pyindex 2fa16b722..29d892c39 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -1,7 +1,7 @@from mcp.shared.memory import (create_connected_server_and_client_session as client_session,)-from fastmcp import FastMCP+from fastmcp import FastMCP, Contextfrom fastmcp.resources import FileResource, FunctionResourcefrom fastmcp.utilities.types import Imagefrom mcp.types import TextContent, ImageContent@@ -9,7 +9,10 @@ import pytestfrom pydantic import BaseModelfrom pathlib import Pathimport base64-from typing import Union+from typing import Union, TYPE_CHECKING++if TYPE_CHECKING:+ from fastmcp import Contextclass TestServer:@@ -368,3 +371,95 @@ class TestServerResourceTemplates:assert isinstance(resource, FunctionResource)result = await resource.read()assert result == "Data for test"+++class TestContextInjection:+ """Test context injection in tools."""++ async def test_context_detection(self):+ """Test that context parameters are properly detected."""+ mcp = FastMCP()++ def tool_with_context(x: int, ctx: Context) -> str:+ return f"Request {ctx.request_id}: {x}"++ tool = mcp._tool_manager.add_tool(tool_with_context)+ assert tool.context_kwarg == "ctx"++ async def test_context_injection(self):+ """Test that context is properly injected into tool calls."""+ mcp = FastMCP()++ def tool_with_context(x: int, ctx: Context) -> str:+ assert ctx.request_id is not None+ return f"Request {ctx.request_id}: {x}"++ mcp.add_tool(tool_with_context)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("tool_with_context", {"x": 42})+ assert len(result.content) == 1+ assert "Request" in result.content[0].text+ assert "42" in result.content[0].text++ async def test_async_context(self):+ """Test that context works in async functions."""+ mcp = FastMCP()++ async def async_tool(x: int, ctx: Context) -> str:+ assert ctx.request_id is not None+ return f"Async request {ctx.request_id}: {x}"++ mcp.add_tool(async_tool)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("async_tool", {"x": 42})+ assert len(result.content) == 1+ assert "Async request" in result.content[0].text+ assert "42" in result.content[0].text++ async def test_context_logging(self):+ """Test that context logging methods work."""+ mcp = FastMCP()++ def logging_tool(msg: str, ctx: Context) -> str:+ ctx.debug("Debug message")+ ctx.info("Info message")+ ctx.warning("Warning message")+ ctx.error("Error message")+ return f"Logged messages for {msg}"++ mcp.add_tool(logging_tool)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("logging_tool", {"msg": "test"})+ assert len(result.content) == 1+ assert "Logged messages for test" in result.content[0].text++ async def test_optional_context(self):+ """Test that context is optional."""+ mcp = FastMCP()++ def no_context(x: int) -> int:+ return x * 2++ mcp.add_tool(no_context)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("no_context", {"x": 21})+ assert len(result.content) == 1+ assert result.content[0].text == "42"++ async def test_context_resource_access(self):+ """Test that context can access resources."""+ mcp = FastMCP()++ @mcp.resource("test://data")+ def test_resource() -> str:+ return "resource data"++ @mcp.tool()+ async def tool_with_resource(ctx: Context) -> str:+ data = await ctx.read_resource("test://data")+ return f"Read resource: {data}"++ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("tool_with_resource", {})+ assert len(result.content) == 1+ assert "Read resource: resource data" in result.content[0].text