Skip to content

Context.request_id stringifies integer request IDs and None, corrupting related_request_id correlation #3876

Open

Description

@shivamm-gupta

Release Line

2.x (main branch)

Problem Description

In JSON-RPC 2.0 and the MCP specification, RequestId is defined as str | int.

In src/mcp/server/mcpserver/context.py:299-301, Context.request_id is defined as:

@property
def request_id(self) -> str:
    """Get the unique ID for this request."""
    return str(self.request_context.request_id)

And in ctx.elicit(), ctx.elicit_url(), and ctx.log() (lines 226, 261, 285):

related_request_id=self.request_id

This causes two bugs:

  1. Integer request ID corruption: When an incoming JSON-RPC request uses an integer ID (e.g., 42), ctx.request_id coerces it to "42". Downstream notifications and elicitation messages carry related_request_id: "42" instead of 42, breaking correlation on clients that distinguish numeric and string IDs.
  2. None coerced to string "None": When a handler runs in a context without a request ID (e.g., notification handlers or server-initiated tasks where request_context.request_id is None), str(None) evaluates to the string "None". As a result, the server sends related_request_id: "None" over the wire rather than None or omitting the field.

Minimal Reproduction Code

from mcp.server.context import ServerRequestContext
from mcp.server.mcpserver.context import Context

# 1. Integer Request ID
req_ctx_int = ServerRequestContext(
    session=None,
    lifespan_context={},
    method="tools/call",
    request_id=42,
    protocol_version="2026-07-28",
)
ctx_int = Context(request_context=req_ctx_int)
print(f"Integer ID result: {ctx_int.request_id!r} (type: {type(ctx_int.request_id).__name__})")
assert ctx_int.request_id == 42, f"Expected 42 (int), got {ctx_int.request_id!r}"

# 2. None Request ID (e.g. notifications)
req_ctx_none = ServerRequestContext(
    session=None,
    lifespan_context={},
    method="notifications/message",
    request_id=None,
    protocol_version="2026-07-28",
)
ctx_none = Context(request_context=req_ctx_none)
print(f"None ID result: {ctx_none.request_id!r} (type: {type(ctx_none.request_id).__name__})")
assert ctx_none.request_id is None, f"Expected None, got {ctx_none.request_id!r}"

Actual Output

Integer ID result: '42' (type: str)
AssertionError: Expected 42 (int), got '42'

None ID result: 'None' (type: str)
AssertionError: Expected None, got 'None'

Expected Output

Context.request_id should return RequestId | None preserving the original type (int, str, or None).

Proposed Fix

Update Context.request_id in src/mcp/server/mcpserver/context.py:

@property
def request_id(self) -> RequestId | None:
    """Get the unique ID for this request."""
    if self._request_context is None:
        return None
    return self._request_context.request_id

and ensure related_request_id in elicit(), elicit_url(), and log() passes the optional RequestId.

I would be happy to submit a PR with test coverage if assigned.


Assisted by AI; reviewed and verified with reproduction script.

Activity

  1. added
    bugSomething isn't working
    v1Affects the v1.x maintenance line
    v2Affects the v2 line (2.x on main)
    on Nov 19, 2026
  2. Shanmukh-l33t commented on Nov 19, 2026

    @Shanmukh-l33t

    Root cause confirmed, and the coercion happens in exactly one place: Context.request_id wraps ServerRequestContext.request_id in str(...), so every related_request_id= site (elicit, elicit_url, log, plus the resolve.py resolver path) inherited it. ServerRequestContext.request_id is already RequestId | None, so the wrapper added nothing except the corruption.

    Behaviour change, exactly: Context.request_id now returns RequestId | None unchanged.

    • inbound 42 (int): was "42", now 42
    • inbound "abc" (str): unchanged, "abc"
    • no inbound id (notification handler, server initiated task): was "None", now None

    One existing assertion encoded the bug: tests/server/mcpserver/test_server.py::TestContextInjection::test_context_logging pinned related_request_id="2" for a client that sends integer ids, so it now expects 2. No production caller needed changing, because the three call sites already pass the property straight through.

    RED before, at upstream main 77001c9:

    assert '42' == 42        # Context().request_id
    assert 'None' is None    # Context().request_id
    

    GREEN after, same two tests in tests/server/mcpserver/test_elicitation.py: one asserts the elicitation the tool sends carries related_request_id as the integer 42, the other asserts request_id is None for a context with no id. Full suite under branch coverage: 6234 passed, 100.00% coverage, no missing statements or partial branches. The single failure, test_permission_error, also fails on unmodified main when the suite runs as root. ruff check, ruff format in check mode, and pyright are clean.

    Branch, no PR: main...Shanmukh-l33t:python-sdk:fix/3876-request-id-preserve

    The patch is ready to open as a PR if a maintainer assigns this issue to me.

    AI assistance: this analysis and patch were produced with an AI agent, and every test result above was run locally.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingv1Affects the v1.x maintenance linev2Affects the v2 line (2.x on main)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions