fix: Make context logging functions spec-compliant (#397) #1906
+0
−2,849
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fix Issue #397: Context Logging Type Compliance
Problem
According to the MCP specification, the
datafield in logging notifications can be any JSON-serializable type. However, the FastMCPContextlogging methods (info(),debug(),warning(),error()) were incorrectly typed to only acceptstrfor the message parameter.The issue was that while the underlying
ServerSession.send_log_message()correctly acceptsdata: Any, the FastMCP convenience methods exposedmessage: str, preventing users from logging structured data like dictionaries, lists, numbers, etc.Solution
This fix makes the FastMCP context logging functions spec-compliant by:
Changed
Context.log()method signature:async def log(..., message: str, ..., extra: dict[str, Any] | None = None)async def log(..., data: Any, ...)extraparameter sincedatanow accepts any JSON-serializable type directlyUpdated convenience methods (
debug(),info(),warning(),error()):message: strtodata: Anyextraparameter for cleaner APIAdded comprehensive tests:
test_context_logging_with_structured_data()to verify logging works with:await ctx.info({"status": "success", "message": msg})await ctx.debug([1, 2, 3])await ctx.warning(42)await ctx.error(True)Example Usage
Testing
Breaking Changes
The
extraparameter has been removed from all logging methods. Users who were using this pattern:Should now use:
This is actually more intuitive and aligns with the MCP specification.
Files Changed
src/mcp/server/fastmcp/server.py: Updated Context.log() method and convenience methodstests/server/fastmcp/test_server.py: Added test for structured data logging