Repository navigation
Migrate MCP SDK 1.16 → 2.x with a single dispatch point - #495
Conversation
|
Summary: Sound consolidation of stdio, HTTP and daemon onto one SDK path in MCPServerBase, but a few unexplained or untested behavior changes should be settled before merge. Scope of review: I read the full source diff, the isolation test and the conftest change. I only skimmed the other tests through commit messages and file lists. I did not run the suite. My local checkout is not the PR head, so I compared against origin/main for the one claim I checked there. The whole PR touches one coupled code path, so I reviewed it as a single group instead of launching parallel agents. Logical groups
Strengths
Issues Major
Minor
Reusability
|
|
Summary: This is a sound consolidation of stdio, HTTP and the daemon onto one SDK path (MCPServerBase.serve_connection). The two Major findings from the earlier PR comment are already fixed at head e36992b, and the one remaining defect is a small shutdown race plus a few minor items. Grouping
Group 2 is the dependency of the other groups, so I read it first. Stale comment: The earlier review comment (author HananKavitzAmat, 2026-11-09) is partly garbled. Three of its claims no longer hold at head:
Issues Critical: none.
Minor
Reusability
Decision: REQUEST CHANGES. Fix the pump_out cancellation race and add a contract test for argument validation. The remaining items can be follow-ups. |
|
The shutdown race is fixed in b1ccab3. It now cancels only pump_in and lets pump_out drain once the write stream closes. A regression test sends one request, then EOF, and On the minors:
|
|
Summary: The PR moves stdio, HTTP and the daemon onto one MCPServerBase.serve_connection path and deletes the daemon's hand-rolled JSON-RPC dispatcher. At head 886e166 the earlier review findings (shutdown race, validation source, malformed-frame reply, aclosing) are fixed. A few small issues remain, so I'd merge after the minor fixes. I read the PR diffs for base.py, common.py, stdio.py, http_server.py, daemon/server.py, client_proxy.py and stdio_lines.py. I did not run the suite, and I only skimmed the test and lockfile changes. Grouping. The core path is coupled, so I reviewed it myself instead of launching parallel agents.
Groups 3 and 4 depend on group 2, so I read group 2 first. Strengths
Issues
Reusability
|
…; add serve_connection()/build_streamable_http_app() to MCPServerBase - _register_common_tool_handlers() now builds self.server via the SDK 2.x constructor-callback API (on_call_tool/on_list_tools) instead of the removed @server.call_tool()/@server.list_tools() decorators. Tool failures are reported via CallToolResult.is_error (not raise), per the daemon's existing error contract. - Add MCPServerBase.serve_connection(read_frame, write_frame): drives one dual-era SDK session over a generic duplex-frame transport. A frame that fails JSON-RPC shape validation is connection-fatal. - Add MCPServerBase.build_streamable_http_app(**kwargs): wraps StreamableHTTPSessionManager(app=self.server, **kwargs). - Update tests/test_mcp_tool_consistency.py's direct-handler-invocation tests (previously reaching into the decorator-era server.request_handlers[CallToolRequest] dict) to use the SDK 2.x _request_handlers["tools/call"].handler accessor via a new _invoke_call_tool() test helper, since the old public dict no longer exists under the constructor-callback API. - Add tests/unit/test_base_serve_connection.py covering legacy initialize, modern per-request _meta envelope, and connection-fatal malformed frames against a fake duplex-frame transport. daemon/server.py, mcp_server/stdio.py, and mcp_server/http_server.py are intentionally untouched -- they still drive self.server through the old SDK entrypoints until Task 4 rewires them onto serve_connection()/ build_streamable_http_app().
… into chunkhound.utils.stdio_lines
… single SDK dispatch point - daemon/server.py: _handle_client's message loop now calls self.serve_connection() (Task 2) over the existing IPC read/write frame helpers, instead of the hand-rolled _dispatch_mcp loop. _dispatch_mcp/ _handle_initialize/_handle_tools_list/_handle_tools_call are left in place (now dead code reachable only from direct unit-test calls) for Task 5 to delete once Task 6 migrates their test callers. - daemon/server.py: _register_tools() now calls self._register_common_tool_handlers() instead of being a no-op. This was required but not previously flagged: serve_connection() asserts self.server is not None, and the daemon's self.server was only ever built via _register_tools(); leaving it a no-op would crash every client connection. Updated the stale docstring/comment in base.py that described the daemon as the one subclass with a no-op _register_tools(). - mcp_server/stdio.py: run()'s _MCP_AVAILABLE branch now builds frames from chunkhound.utils.stdio_lines (Task 3) and delegates to serve_connection(), instead of calling mcp.server.stdio.stdio_server() directly. Removed the now-unused NotificationOptions/ InitializationOptions/mcp.server.stdio imports. The SDK-unavailable fallback branch is unchanged. - mcp_server/http_server.py: removed the StreamableHTTPSessionManager import and conditional; __init__ now builds self._session_manager via self.build_streamable_http_app(stateless=False). Added a type: ignore[union-attr] on the _lifespan() session_manager.run() call with a comment, since the ternary assignment widens mypy's inferred type to `Any | None` (no behavior change; _MCP_AVAILABLE is still checked before run() can ever be reached with a None manager). - tests/unit/test_mcp_wrapper_sdk_isolation.py: new, per plan brief — AST-only check that chunkhound/daemon/server.py, client_proxy.py, mcp_server/stdio.py, mcp_server/http_server.py import no `mcp` symbol, and that mcp_server/base.py still does (single dispatch point). - tests/mcp/conftest.py + tests/mcp/test_daemon_dual_era.py: new daemon_harness fixture spins up a real ChunkHoundDaemon bound to a real IPC socket (chunkhound.daemon.ipc), stubbing out only initialize()/_initialization_complete (DB/embeddings are not exercised by these tests). Covers: legacy initialize handshake + tools/list, modern 2026-07-28 _meta-envelope tools/list (resultType/ttlMs/ cacheScope), and two concurrent requests on one connection correlated by id. Verification in this sandbox (chunkhound_native's bundled DuckDB binary cannot be built here — network-blocked, pre-existing/unfixable): - test_mcp_wrapper_sdk_isolation.py's AST logic verified correct via a standalone `uv run python` script bypassing pytest (its own collection is blocked only by tests/unit/conftest.py's unrelated autouse `_disable_auto_compaction` fixture, which imports chunkhound.providers for every test in that directory regardless of content — confirmed identical against an untouched baseline file in the same directory). - test_daemon_dual_era.py's collection failure confirmed to be the same chunkhound_native ImportError chain (chunkhound.daemon.server -> mcp_server.base -> core.analytics -> chunkhound_native), not a defect in the new test/fixture code. - ruff check: the 4 touched files + 3 new test files are clean. - mypy: touched files went from 16 baseline errors (compared via a `git worktree add` at HEAD) to 14; lost 2 pre-existing stdio.py errors (dead code removed), no new errors beyond the one union-attr call site deliberately suppressed above. - tests/test_smoke.py: 11/14 pass; the 3 failures are the same environment-wide chunkhound_native ImportError across dozens of unrelated modules (autodoc, code_mapper, etc.), not specific to this change.
…ia MCPServerBase.serve_connection()
…SDK 2.x APIs - Tool.inputSchema -> Tool.input_schema, streamablehttp_client -> streamable_http_client (httpx_client_factory -> http_client, 2-tuple yield instead of 3-tuple), CallToolResult.isError -> is_error: real SDK 2.x renames the old test call sites never caught (chunkhound_native was unbuildable in the dev sandbox throughout implementation, so these tests never actually ran until now). - test_stdio_tool_call_uses_error_content_when_success_precedes_error and test_daemon_tool_call_propagates_mixed_content_error_flag: updated to match the plan's intentional new contract (CallToolResult.content keeps the full mixed-content list in original order; it no longer collapses to a single raised error like the old SDK 1.x call_tool() decorator did). Also fixed the daemon test's stale patch target (chunkhound.mcp_server.common.handle_tool_call, which stopped being observable once the old per-method local import was deleted in Task 5) to chunkhound.mcp_server.base.handle_tool_call, matching the single dispatch point. - daemon_stdio_call test helper: ClientProxy._write_stdin_line() was folded directly into _forward_stdin_to_socket() during the Task 3 stdio_lines extraction and no longer exists as a callable method; replicated its two-line parse-and-forward logic inline. Also added the initialize handshake + notifications/initialized notification the real SDK session now requires before accepting tools/call (the old hand-rolled daemon dispatcher had no such lifecycle gate).
sys.stdout.buffer is a read-only property on the real TextIOWrapper -- monkeypatch.setattr(sys.stdout, "buffer", ...) always raised AttributeError: readonly attribute, confirmed independent of pytest's capture mode. This Task-3 test never actually ran until the chunkhound_native rebuild unblocked real pytest execution in this sandbox. Fix: replace the whole sys.stdout object with a SimpleNamespace exposing the fake .buffer, matching the pattern already used elsewhere in this file for sys.stdin.
…on test on_list_tools waits up to 5s for initialization; the harness gave up after 2.5s and cancelled the session, so the SDK answered 'Connection closed'. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ecord verification Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…ate SDK stream import
- serve_connection: forward invalid JSON-RPC frames to the session and keep
serving, as the SDK's stdio_server does
- daemon/stdio readers: skip non-object JSON (e.g. batch arrays), log IPC read errors
- use public anyio memory streams instead of mcp.shared._context_streams
- stdio: write stdout off the event loop
- restore http_server.py rationale comments; fix pyproject comments; drop history docstrings
… from comments - base.py: Tool(input_schema=...) (snake_case field; serialized alias unchanged) - http_server.py, tests: remove references to internal planning documents
tmp_path nests directories by test name (pytest-of-<user>/pytest-N/<test_name><idx>/), and this suite's long test names (e.g. test_daemon_serves_two_concurrent_requests_on_one_connection) push project_dir-derived socket paths past Linux's 108-byte sun_path limit, failing bind() with "AF_UNIX path too long" deterministically — not an environment fluke. Build the socket in its own short tempfile.mkdtemp() dir instead of nesting it under tmp_path, and clean it up in the fixture teardown. Verified: all 4 previously-failing tests in test_daemon_dual_era.py now pass, full tests/mcp/ suite (15/15) passes, smoke tests pass, ruff/mypy clean on the changed file.
MCP SDK 2.x no longer validates tools/call arguments, so invalid input reached the tool code and surfaced as raw TypeErrors. Validate against the registered schema in on_call_tool and return an isError result instead.
The constructor wrote CHUNKHOUND_MCP_MODE=1 into os.environ as a side effect. While it is set, RichOutputFormatter.error() prints nothing, so any test that built a server in-process silenced [ERROR] output for every later test in the same pytest process. In CI this made four Code Mapper tests fail deterministically on all platforms (empty stdout). Every real entry point (stdio/http main, the mcp command, CLI startup) already sets the variable before constructing a server, so the write was redundant there. It also undid the scrub in daemon discovery that keeps MCP mode out of the daemon child process. Tests that run an entry point (mcp_command, async_main) set the variable on purpose; add an opt-in isolated_mcp_mode fixture that restores it, and use it in the two tests that leaked. monkeypatch.delenv records no undo when the variable is unset, so it cannot do this; correct the comment in test_mcp_read_only.py that claimed otherwise. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
ipc.create_server expects tcp:<host>:<port> on win32, but the harness passed a Unix socket path, so the four test_daemon_dual_era tests errored at setup with IndexError in _parse_tcp_address. Reserve a free loopback port on Windows; keep the short AF_UNIX path elsewhere. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… lock - Coerce tool arguments with parse_mcp_arguments before validating, so numeric strings (page_size: "10") keep working; coercion errors and schema violations return "Input validation error". Also coerce last_n_commits. - Validate against the schema advertised by tools/list (_build_filtered_tool_dicts) so validation cannot diverge from listing; unadvertised tools fall through to handle_tool_call's own errors. - serve_connection: cancel the task group on exit so a blocked read_frame() cannot hang the session; keep "id": null in error responses (exclude_unset); document the malformed-frame gap; type on_list_tools params. - Regenerate requirements-lock.txt (drops stale fastmcp pin that required mcp<2; adds mcp-types, httpx2) and update requirements.txt. - http_server: assert instead of type: ignore. - Isolation test: cover mcp_types and discover wrapper files by glob. - Drop unused is_ci import; ruff-format test_stdio_lines.py.
The previous hang fix cancelled the whole task group, which also cancelled pump_out and could drop the last in-flight response (e.g. EOF right after a request while a slow write_frame/drain is pending). Cancel only pump_in via its own scope and let pump_out finish once the write stream is closed. Adds a regression test.
…ction - utils/stdio_lines: add iter_json_frames(), the single owner of the "skip undecodable / non-object lines" policy; ClientProxy and the stdio server both use it instead of re-implementing decode/skip. - stdio server and iter_json_frames close the stdin line generator via contextlib.aclosing so the Unix read pipe is released deterministically. - base: build the jsonschema validator without validate()'s per-call check_schema() (schemas are ours). - tests: add tests/utils/mcp_session (call_tool/list_tools through the public serve_connection seam) and use it instead of reaching into the SDK's private _request_handlers; add a test for iter_json_frames.
…ry an id serve_connection silently dropped frames failing JSON-RPC shape validation, leaving callers with a readable id waiting forever. Reply with -32600 and serialize writes between pump_in and pump_out.
886e166 to
08248c0
Compare
|
Summary: Moving stdio, HTTP and the daemon onto one serve_connection path is a good consolidation. One shutdown-ordering bug and some stale documentation remain, so I'd merge after a small fix. Grouping
Groups 3 and 4 depend on group 2. The code path is tightly coupled, so I reviewed it as one unit instead of splitting it across parallel agents. Strengths
Issues Critical: none. Major
Minor
Reusability
|
…fy serve_connection docs
Summary
Bumps the mcp dependency to >=2.3,<3 and moves all MCP transports (stdio, HTTP, daemon) onto one SDK-facing code path. The path is
MCPServerBase.serve_connection() / build_streamable_http_app() in chunkhound/mcp_server/base.py.
Changes
Notes for reviewers
google.genai import). Lazy-importing the LLM providers in llm_manager.py is an untried follow-up.
Testing
Automated
Smoke tests, the MCP unit tests and the tests/mcp suite all pass (39 tests). Ruff and mypy are clean on
mcp_server/base.py.
Manual checks (on Pi.dev and Claude Code)
comes back as a clear validation error.
file.
The daemon shut itself down after both disconnected.