Skip to content

fix: reject changed duplicate initialize - #2606

Open
he-yufeng wants to merge 3 commits into
modelcontextprotocol:mainfrom
he-yufeng:fix/reject-changed-reinitialize
Open

he-yufeng wants to merge 3 commits into
modelcontextprotocol:mainfrom
he-yufeng:fix/reject-changed-reinitialize

Conversation

@he-yufeng

@he-yufeng he-yufeng commented May 15, 2026 •

Copy link
Copy Markdown

Summary

  • reject a second initialize when its negotiated parameters differ from the session's existing client_params
  • keep identical retries idempotent and exclude request _meta from the comparison
  • preserve the original negotiated state after rejection and keep the session usable
  • cover changed protocol version, capabilities and client info, identical retries, and a retry that changes only _meta

The branch now includes current main (77001c96f9507be0f4d009b83210a384a5e08bda) through a normal merge commit, followed by the review fix at 20715950dfc243ba996e123019cc0f312e71edcf.

To verify

Focused duplicate-initialize regressions:

uv run --frozen pytest -n0 \
  tests/server/test_runner.py::test_runner_rejects_changed_duplicate_initialize \
  tests/server/test_runner.py::test_runner_accepts_identical_duplicate_initialize \
  tests/server/test_runner.py::test_runner_duplicate_initialize_ignores_request_meta -q

Result: 3 passed. Before excluding _meta, the same selection was 1 failed, 2 passed: the _meta-only retry was rejected while the changed-parameters rejection and identical retry controls passed.

Adjacent suites:

uv run --frozen pytest -n0 tests/server/test_runner.py tests/server/test_session.py -q
uv run --frozen ruff check src/mcp/server/runner.py tests/server/test_runner.py
uv run --frozen ruff format --check src/mcp/server/runner.py tests/server/test_runner.py
uv run --frozen pyright src/mcp/server/runner.py tests/server/test_runner.py

Results: 135 passed; Ruff and pyright passed.

Full repository validation on Python 3.14.2:

./scripts/test

Result: 6235 passed, 9 skipped, 1 xfailed. Coverage is 100.00%, and strict-no-cover passed. git diff --check also passes.

AI assistance: Claude Code was used for implementation, test development and local validation. The final diff was reviewed line by line.

Closes #2605

@BossChaos

This comment was marked as abuse.

@he-yufeng

Copy link
Copy Markdown
Author

Rebased this PR onto the current runner/connection architecture instead of keeping the old ServerSession._received_request patch. The duplicate-initialize guard now lives in ServerRunner._handle_initialize(), so a second initialize with changed params returns INVALID_PARAMS and leaves the original connection.client_params intact.

Validation:

  • python -m py_compile src\mcp\server\runner.py tests\server\test_runner.py
  • uv run pytest tests/server/test_runner.py -q -k "initialize" --basetemp .tmp\pytest-2606-20260610 -p no:cacheprovider (16 passed)

@he-yufeng
he-yufeng force-pushed the fix/reject-changed-reinitialize branch from f77411a to f96c27e Compare June 10, 2026 13:38
@he-yufeng
he-yufeng force-pushed the fix/reject-changed-reinitialize branch from f96c27e to 74ae395 Compare June 22, 2026 10:19
@he-yufeng

Copy link
Copy Markdown
Author

Rebased onto current main and resolved the conflict in _handle_initialize: the duplicate-initialize rejection now layers on top of the new opts resolution (the create_initialization_options() fallback) instead of the old assert self.init_options is not None. test_runner_rejects_changed_duplicate_initialize still passes against the rebased base.

@he-yufeng

Copy link
Copy Markdown
Author

Bumping this. A second initialize with changed params can still shift session state after the handshake, so rejecting the changed duplicate keeps initialization once-only per the spec. Rebases cleanly on main if there is interest.

@he-yufeng

Copy link
Copy Markdown
Author

Still relevant: runner.py:231-239 overwrite the state on a repeated initialize instead of rejecting it. Would be nice to get a maintainer's take on this.

@he-yufeng

Copy link
Copy Markdown
Author

@Kludex @ErenAta16 Could you review 74ae3952?

A second initialize with changed parameters can currently overwrite session state after the handshake. Rejecting a changed duplicate keeps initialization once-only while allowing an identical retry if that is the intended compatibility behavior.

Could you check the protocol semantics for identical versus changed duplicates and confirm that no later request can rewrite the negotiated state? The current head has 27 successful checks.

@ErenAta16 ErenAta16 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed 74ae3952 by running it, on Windows with Python 3.12: once on the PR's own base (2397319), once with the diff applied to current main (77001c9, where git apply --check is clean), and once on main without it. For each checkout I opened a session with initialize, sent a second initialize, and compared the stored handshake state before and after.

second initialize                 main (no fix)                       with this PR
identical retry                   accepted, state unchanged           accepted, state unchanged
clientInfo.name changed           accepted, STATE OVERWRITTEN         rejected -32602, state unchanged
clientInfo.version changed        accepted, STATE OVERWRITTEN         rejected -32602, state unchanged
capabilities changed              accepted, STATE OVERWRITTEN         rejected -32602, state unchanged
protocolVersion changed           accepted, negotiated version reset  rejected -32602, state unchanged
only `_meta` added                accepted, state unchanged           rejected -32602, state unchanged

So the bug in #2605 is real on current main, including the negotiated protocol version, and the PR closes it. A rejected duplicate leaves the session usable: notifications/initialized and tools/list still work afterwards. The new test fails on the base source and passes with the change, tests/server/test_runner.py and tests/server/test_session.py pass (89 on the PR's base), and all 27 checks are green.

On "can a later request rewrite the negotiated state". client_params and protocol_version are assigned in one place, after the middleware chain succeeds in _on_request, so a vetoed or rejected initialize commits nothing. In loop mode initialize runs inline with the read loop parked, so two handshakes cannot interleave. The legacy stateless path builds its connection with no client params (Connection.from_envelope(..., None, None)), so the new check never fires there. I read these paths but did not write a concurrency test for them. On the protocol side, the lifecycle page has no explicit rule for a repeated initialize, and its own initialization error example uses -32602, so the error code is consistent.

One change I would make, not blocking. The check compares whole InitializeRequestParams objects, which include _meta. A retry whose handshake content is identical but whose _meta differs (a different progressToken, say) is rejected, although main accepts it and the description says an identical retry should be allowed. Comparing without meta fixes that:

if self.connection.client_params is not None and init.model_dump(exclude={"meta"}) != (
    self.connection.client_params.model_dump(exclude={"meta"})
):

I ran this on top of the PR on main: the four changed cases are still rejected, the _meta-only retry is accepted, and test_runner.py plus test_session.py give 133 passed. A test for the identical retry, and for the _meta-only case, would pin the behaviour the description promises; today only the changed-name case is tested.

Two smaller points.

  • The "To verify" commands in the description do not exercise this change. pytest tests/server/test_session.py -k "duplicate_initialize or server_session_initialize" collects nothing (all 13 tests deselected), and the ruff and pyright lines name session.py, while the diff touches runner.py and test_runner.py.
  • The branch is based on 2397319 and main has moved a lot in runner.py, connection.py and test_runner.py. The diff still applies cleanly, but a rebase would give a CI run on the current code. Two earlier pull requests for the same behaviour, #2945 and #3078, are closed; I do not know why, so it may be worth reading those threads before investing more here.

@he-yufeng

Copy link
Copy Markdown
Author

@ErenAta16 Thanks for checking the actual handshake behavior and for catching the _meta case. I have merged current main and pushed 20715950dfc243ba996e123019cc0f312e71edcf.

The comparison now excludes meta. The tests cover all three contracts:

  • changed protocol version, capabilities and client info are rejected with the original client_params preserved, and tools/list still works afterwards;
  • an identical retry is accepted and remains idempotent;
  • a retry that changes only _meta is accepted without changing the negotiated fields.

I also corrected the PR description so the commands target runner.py and test_runner.py. The focused selection is 3 passed, the two adjacent files are 135 passed, and the full ./scripts/test run is 6235 passed, 9 skipped, 1 xfailed with 100.00% coverage and strict-no-cover passing. Ruff and pyright pass.

AI assistance: Claude Code was used for the patch, tests and local validation. I reviewed the final diff before publishing it.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/mcp/server/runner.py">

<violation number="1" location="src/mcp/server/runner.py:432">
P1: Middleware can bypass this check by short-circuiting `initialize` or rewriting `ctx.params`; `_on_request` then commits the original request parameters unconditionally, allowing a changed duplicate to replace `client_params` and `client_capabilities`. Validate the original request before middleware or enforce the comparison at the commit point.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread src/mcp/server/runner.py
_, negotiated = self._negotiate_initialize(params)
init, negotiated = self._negotiate_initialize(params)
# `_meta` is request metadata, not negotiated session state.
if self.connection.client_params is not None and init.model_dump(exclude={"meta"}) != (

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Middleware can bypass this check by short-circuiting initialize or rewriting ctx.params; _on_request then commits the original request parameters unconditionally, allowing a changed duplicate to replace client_params and client_capabilities. Validate the original request before middleware or enforce the comparison at the commit point.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/mcp/server/runner.py, line 432:

<comment>Middleware can bypass this check by short-circuiting `initialize` or rewriting `ctx.params`; `_on_request` then commits the original request parameters unconditionally, allowing a changed duplicate to replace `client_params` and `client_capabilities`. Validate the original request before middleware or enforce the comparison at the commit point.</comment>

<file context>
@@ -427,7 +427,15 @@ def _negotiate_initialize(params: Mapping[str, Any] | None) -> tuple[InitializeR
-        _, negotiated = self._negotiate_initialize(params)
+        init, negotiated = self._negotiate_initialize(params)
+        # `_meta` is request metadata, not negotiated session state.
+        if self.connection.client_params is not None and init.model_dump(exclude={"meta"}) != (
+            self.connection.client_params.model_dump(exclude={"meta"})
+        ):
</file context>

This branch has not been deployed

No deployments
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.

Duplicate initialize with changed parameters can overwrite ServerSession.client_params

3 participants