Skip to content

fix: make Context logging methods spec-compliant by accepting Any data type#2195

Open
Jimil-Joshi wants to merge 1 commit intomodelcontextprotocol:mainfrom
Jimil-Joshi:fix/context-logging-spec-compliance
Open

fix: make Context logging methods spec-compliant by accepting Any data type#2195
Jimil-Joshi wants to merge 1 commit intomodelcontextprotocol:mainfrom
Jimil-Joshi:fix/context-logging-spec-compliance

Conversation

@Jimil-Joshi
Copy link

Summary

Fixes #397

Per the MCP specification, the data field in LoggingMessageNotificationParams allows any JSON serializable type:

The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.

However, the Context.log() and convenience methods (debug, info, warning, error) were typed as message: str, which prevented users from logging structured data like dicts, lists, numbers, etc.

Changes

  • Context.log(): Changed message: str parameter to data: Any to match the MCP spec and the underlying ServerSession.send_log_message(data: Any)
  • Convenience methods (debug, info, warning, error): Updated to accept data: Any instead of message: str
  • Removed extra parameter: Structured data can now be passed directly as data (e.g., ctx.info({"event": "processing", "count": 5})) making the extra workaround unnecessary
  • Updated docstrings: Document that any JSON serializable type is accepted
  • Added test: Verifies logging of dict, list, number, boolean, and None types

Example

`python
@server.tool()
async def my_tool(x: int, ctx: Context) -> str:
# String messages still work (backward compatible)
await ctx.info(f"Processing {x}")

# Now also supports structured data per MCP spec
await ctx.info({"event": "processing", "input": x})
await ctx.debug(["step1", "step2", "step3"])
await ctx.warning(42)
return "done"

`

Test Results

All 87 tests in tests/server/mcpserver/test_server.py pass, including the new structured data logging test.

…a type

Per the MCP specification, the data field in LoggingMessageNotificationParams
allows any JSON serializable type, not just strings. The Context.log() and
convenience methods (debug, info, warning, error) were typed as message: str,
which prevented users from logging structured data like dicts, lists, numbers, etc.

Changes:
- Change message: str to data: Any in Context.log() and all convenience methods
- Remove the extra parameter (structured data can now be passed directly as data)
- Update docstrings to document that any JSON serializable type is accepted
- Update class docstring with examples of structured data logging
- Add test for logging structured data (dict, list, number, boolean, None)

Fixes modelcontextprotocol#397
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Context logging function types are not spec compliant

1 participant