python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

Duplicate `initialize` with changed parameters can overwrite `ServerSession.client_params`

Open cclabadmin opened this issue 6 months ago • 3 comments

Initial Checks

  • [x] I confirm that I'm using the latest version of MCP Python SDK
  • [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue

Description

After a normal MCP initialization flow, a Python SDK server accepts another initialize request on the same live connection/session and returns a normal initialize result.

I agree that the spec does not explicitly say every repeated initialize must be rejected. My concern is narrower: after the session has already moved into normal operation, a later same-session initialize with different parameters can update the server's stored client initialization parameters.

The MCP lifecycle documentation describes initialization as the first client/server interaction and says the operation phase uses the negotiated protocol version and capabilities. In that model, silently changing the stored client identity/capabilities/protocol version after operation has begun seems surprising unless the SDK intentionally supports same-session renegotiation.

  • src/mcp/server/session.py stores the client initialization request in ServerSession._client_params.
  • ServerSession.client_params exposes that value.
  • In both the stable release and the main snapshot I tested, the InitializeRequest handler assigns self._client_params = params.
  • ServerSession.check_client_capability() later reads self._client_params.capabilities, so a duplicate initialize with different capabilities can affect capability-gated server logic.

What I observed

Reproduced on stable v1.27.1 (77431ebe7dda9ed0c61451b22d3e7f8d981bc092):

  • stdio: a second initialize was accepted after notifications/initialized; a later ping still succeeded.
  • stateful Streamable HTTP: a second initialize was accepted after notifications/initialized; a later ping still succeeded.
  • stateless Streamable HTTP: a second initialize was accepted after notifications/initialized; a later ping still succeeded.

For stateful Streamable HTTP on v1.27.1, I added a local diagnostic tool that reads ctx.session.client_params before and after the duplicate initialize on the same session:

Duplicate initialize parameters Observed result
Same parameters No state change
Changed clientInfo and capabilities client_params.clientInfo and client_params.capabilities changed
Older protocolVersion (2024-11-05) client_params.protocolVersion and client_params.clientInfo changed

On the frozen main snapshot (161834d4aee2633c42d3976c8f8751b6c4d947d5), the same duplicate-initialize acceptance still reproduced. My diagnostic snapshot directly observed client_params.capabilities changing after a duplicate initialize with changed capabilities on both stdio and stateful Streamable HTTP.

Expected behavior

If same-session duplicate initialization is not intended, I would expect the server to reject the later initialize after normal operation has begun, for example with a JSON-RPC -32600 Invalid Request error.

If this tolerant behavior is intentional, I think it should be either:

  • a no-op once the session has already initialized, especially for changed parameters, or
  • documented as same-session renegotiation, including whether ServerSession.client_params, client capabilities, client identity, and protocol version are allowed to change.

Example Code

import json

try:
    # Current main branch naming.
    from mcp.server.mcpserver import Context, MCPServer
except ImportError:
    # Latest stable release naming.
    from mcp.server.fastmcp import Context, FastMCP as MCPServer


mcp = MCPServer("dup-init-repro")


def field(obj, *names):
    if obj is None:
        return None
    for name in names:
        if hasattr(obj, name):
            return getattr(obj, name)
    return None


def dump(value):
    if value is None:
        return None
    if hasattr(value, "model_dump"):
        return value.model_dump(mode="json", by_alias=True)
    return value


@mcp.tool()
async def session_snapshot(ctx: Context) -> str:
    params = ctx.session.client_params
    return json.dumps(
        {
            "protocolVersion": field(params, "protocolVersion", "protocol_version"),
            "clientInfo": dump(field(params, "clientInfo", "client_info")),
            "clientCapabilities": dump(field(params, "capabilities")),
        },
        separators=(",", ":"),
        default=str,
    )


if __name__ == "__main__":
    mcp.run(transport="streamable-http")

'''
Request sequence:

1. Start the server.
2. Send a normal `initialize`.
3. Send `notifications/initialized`.
4. Call the `session_snapshot` tool and record the returned JSON.
5. Send another `initialize` on the same live session, but change `clientInfo` and/or `capabilities`.
6. Call `session_snapshot` again on the same session.

On `v1.27.1`, the second snapshot reflects the changed `clientInfo` / `capabilities`. On the `main` snapshot I tested, the second snapshot still reflects changed `capabilities`.
'''

Python & MCP Python SDK

- Python: `3.12.3`
- MCP Python SDK: `mcp==1.27.1` (`v1.27.1`, `77431ebe7dda9ed0c61451b22d3e7f8d981bc092`)
- Also reproduced on `main` snapshot `161834d4aee2633c42d3976c8f8751b6c4d947d5` (`v1.25.0-159-g161834d4`, pinned 2026-05-11)

cclabadmin avatar May 15 '26 13:05 cclabadmin

confirmed on origin/main (616476f) and origin/v1.x (6213787). a second initialize after notifications/initialized is accepted by ServerSession._received_request and unconditionally overwrites _client_params — clientInfo, capabilities, and protocolVersion all change, and check_client_capability() flips with them. fix is a one-branch guard in src/mcp/server/session.py on the InitializeRequest case: when the session is already Initialized and not in stateless mode, respond with INVALID_REQUEST instead of overwriting the negotiated state.

workaround for server authors until fixed: don't trust ServerSession.client_params for authorization once the session is running; snapshot the negotiated capabilities at end of init and key off the snapshot.

repro (in-memory streams, no transport)

repro.py (runs against current main):

"""Reproduce issue #2605: duplicate initialize overwrites ServerSession._client_params."""

import anyio
import mcp.types as types
from mcp.server.session import ServerSession
from mcp.server.models import InitializationOptions
from mcp.shared.message import SessionMessage


async def drain_incoming(session: ServerSession):
    async for _ in session.incoming_messages:
        pass


async def main():
    init_opts = InitializationOptions(
        server_name="repro",
        server_version="0.0.0",
        capabilities=types.ServerCapabilities(),
    )

    c2s_send, c2s_recv = anyio.create_memory_object_stream[SessionMessage | Exception](32)
    s2c_send, s2c_recv = anyio.create_memory_object_stream[SessionMessage](32)

    next_id = 1

    def make_init(client_name, sampling, protocol_version=types.LATEST_PROTOCOL_VERSION):
        nonlocal next_id
        rid = next_id
        next_id += 1
        caps = types.ClientCapabilities()
        if sampling:
            caps = types.ClientCapabilities(sampling=types.SamplingCapability())
        req = types.InitializeRequest(
            method="initialize",
            params=types.InitializeRequestParams(
                protocol_version=protocol_version,
                capabilities=caps,
                client_info=types.Implementation(name=client_name, version="1"),
            ),
        )
        jr = types.JSONRPCRequest(
            jsonrpc="2.0",
            id=rid,
            **req.model_dump(by_alias=True, mode="json", exclude_none=True),
        )
        return rid, SessionMessage(jr)

    def make_initialized():
        return SessionMessage(types.JSONRPCNotification(jsonrpc="2.0", method="notifications/initialized"))

    async def drain_response(expected_id):
        with anyio.fail_after(5):
            while True:
                msg = await s2c_recv.receive()
                root = msg.message
                if hasattr(root, "id") and root.id == expected_id:
                    return root

    async with ServerSession(c2s_recv, s2c_send, init_opts) as session:
        async with anyio.create_task_group() as tg:
            tg.start_soon(drain_incoming, session)

            rid, msg = make_init("client-A", sampling=True)
            await c2s_send.send(msg)
            await drain_response(rid)
            await c2s_send.send(make_initialized())
            await anyio.sleep(0.1)

            cp = session.client_params
            print(f"AFTER FIRST: client={cp.client_info.name} sampling={cp.capabilities.sampling is not None} pv={cp.protocol_version}")
            print(f"  check(sampling)={session.check_client_capability(types.ClientCapabilities(sampling=types.SamplingCapability()))}")

            rid2, msg2 = make_init("client-B-evil", sampling=False, protocol_version="2024-11-05")
            await c2s_send.send(msg2)
            resp2 = await drain_response(rid2)
            print(f"second init response: {type(resp2).__name__}")

            cp = session.client_params
            print(f"AFTER SECOND: client={cp.client_info.name} sampling={cp.capabilities.sampling is not None} pv={cp.protocol_version}")
            print(f"  check(sampling)={session.check_client_capability(types.ClientCapabilities(sampling=types.SamplingCapability()))}")

            await c2s_send.aclose()


anyio.run(main)

run + output:

$ uv run python repro.py
AFTER FIRST: client=client-A sampling=True pv=2025-11-25
  check(sampling)=True
second init response: JSONRPCResponse
AFTER SECOND: client=client-B-evil sampling=False pv=2024-11-05
  check(sampling)=False

so client_params was silently rewritten and check_client_capability(sampling) flipped from True to False without the client ever losing the sampling capability via any spec-defined mechanism. v1.x reproduces identically with the .root / camelCase variants.

code path

src/mcp/server/session.py on main:

165 async def _received_request(self, responder: ...):
166     match responder.request:
167         case types.InitializeRequest(params=params):
168             requested_version = params.protocol_version
169             self._initialization_state = InitializationState.Initializing
170             self._client_params = params      # <-- no guard on prior state
171             with responder:
172                 await responder.respond(types.InitializeResult(...))
189             self._initialization_state = InitializationState.Initialized

check_client_capability() (session.py:122) reads self._client_params.capabilities, so any gate built on it follows the overwritten value. spec (lifecycle.mdx:40) states the initialization phase MUST be the first interaction and the operation phase MUST use the negotiated version and capabilities — silent mid-session renegotiation violates both.

suggested fix
// src/mcp/server/session.py
 case types.InitializeRequest(params=params):
+    # Spec: initialization MUST be the first interaction and the operation
+    # phase MUST use the negotiated values. Reject duplicate initialize so it
+    # cannot overwrite client_params. Stateless mode starts in Initialized but
+    # the per-request ServerSession still expects exactly one initialize.
+    if not self._stateless and self._initialization_state == InitializationState.Initialized:
+        with responder:
+            await responder.respond(
+                types.ErrorData(
+                    code=types.INVALID_REQUEST,
+                    message="Server is already initialized",
+                )
+            )
+        return
     requested_version = params.protocol_version
     self._initialization_state = InitializationState.Initializing
     self._client_params = params

stateless mode is exempted because each per-request ServerSession starts in Initialized and still expects exactly one initialize; without the exemption the first initialize in a stateless session would be rejected.

test to verify: drives an in-memory ServerSession through initialize + notifications/initialized + a second initialize with different clientInfo/capabilities/protocolVersion, then asserts the second response is JSONRPCError(INVALID_REQUEST) and session.client_params still reflects the first handshake. one pre-existing integration test (test_second_initialize_on_an_existing_session_is_accepted in tests/interaction/transports/test_hosting_session.py) was asserting the bug behaviour with a docstring noting the spec divergence — it's flipped to assert rejection.

full test suite passes (1743 passed, 98 skipped, 1 xfailed). same guard needed on v1.x.

ghost avatar Jun 01 '26 11:06 ghost

I’m going to work on a focused fix for this: reject a duplicate initialize after the session is initialized, and add a regression that the original client_params stay intact.

ychampion avatar Jul 08 '26 19:07 ychampion

Confirmed against current main: _on_request in src/mcp/server/runner.py commits self.connection.client_params, self.connection.protocol_version = self._negotiate_initialize(params) on every successful initialize call, with no check for whether the connection was already initialized. _handle_initialize doesn't guard either, so a second initialize with different clientInfo/capabilities silently overwrites the negotiated params for the life of the connection.

On the two open PRs:

  • #3078 modifies ServerSession._received_request in src/mcp/server/session.py (_client_params, _initialization_state). That internal state machine isn't where initialize is handled anymore — session.py's client_params is now a thin read-only proxy onto Connection.client_params (src/mcp/server/connection.py), and the actual handling lives in runner.py. The PR predates that move, so it doesn't apply to current main.
  • #2606 patches the right spot (_handle_initialize in runner.py), guarding on self.connection.client_params is not None and init != self.connection.client_params. That's correct for the common case and its test (test_runner_rejects_changed_duplicate_initialize) matches the architecture. One thing worth checking before merge: the guard runs inside _handle_initialize, which executes before the state commit at the end of _on_request (line ~239), so a rejected duplicate correctly leaves connection.client_params untouched — but it's worth an explicit test asserting the unchanged value post-rejection (matching the issue title), not just that an error is raised.

Proposed approach if this needs a fresh PR: same guard as #2606 (compare negotiated InitializeRequestParams against self.connection.client_params when already set, reject with INVALID_REQUEST on mismatch, no-op-accept on an identical repeat), plus a regression test in tests/server/test_runner.py that explicitly asserts connection.client_params is unchanged after the rejected duplicate.

AI disclosure: this comment and the accompanying analysis were produced with AI assistance (Claude Code), reviewed by me before posting.

jadhavgaurav avatar Aug 25 '26 07:08 jadhavgaurav