Skip to content

Migrate MCP SDK 1.16 → 2.x with a single dispatch point - #495

Merged
HananKavitzAmat merged 28 commits into
chunkhound:mainfrom
tamarsh68:merge-issue-mcp
Nov 11, 2026
Merged

HananKavitzAmat merged 28 commits into
chunkhound:mainfrom
tamarsh68:merge-issue-mcp

Conversation

@tamarsh68

Copy link
Copy Markdown
Contributor

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

  • Dependency: mcp moves to 2.x (pyproject.toml, uv.lock, requirements-lock.txt at 2.3.0).
  • Handlers: tool handlers use the SDK 2.x constructor callbacks (on_call_tool, on_list_tools). Tool is built with the input_schema kwarg.
  • Single dispatch point:
    • stdio, HTTP and daemon wrappers no longer import mcp and delegate to MCPServerBase.
    • The daemon's hand-rolled JSON-RPC dispatcher is removed.
    • ClientProxy's stdin handling is extracted to chunkhound.utils.stdio_lines.
    • A test in tests/unit/test_mcp_wrapper_sdk_isolation.py enforces the rule among the wrappers.
  • Behaviour fixes:
    • Tool arguments are validated against the tool's input schema.
    • Malformed frames are skipped instead of closing the session.
    • The private SDK stream import is dropped.
  • Tests:
    • Migrated to the 2.x APIs.
    • The daemon test harness now avoids AF_UNIX path-too-long errors.
    • Startup initialization timeouts in subprocess tests are raised to 15s.
  • Merges and cleanup:
    • Merged upstream main (twice).
    • Removed internal plan references from comments.
    • Cleaned ruff and mypy findings in mcp_server/base.py.

Notes for reviewers

  • The 15s init timeouts defeat the 5s VS Code startup guard in those tests. 6s still flaked under -n auto because 2.x startup is slower (e.g.
    google.genai import). Lazy-importing the LLM providers in llm_manager.py is an untried follow-up.
  • chunkhound/mcp_server/common.py still imports mcp.types for type helpers. The isolation test only covers the transport wrappers.
  • Known gaps:
    • A malformed daemon frame that carries an id gets no reply.
    • Some unit tests touch the SDK's private _request_handlers.
  • tests/cli/test_index_daemon_conflict.py::test_index_with_healthy_daemon_shows_running_message is a known flaky test, and it is also flaky upstream.

Testing

  1. 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.

  2. Manual checks (on Pi.dev and Claude Code)

  • Direct stdio (--no-daemon): a client can connect, list tools and call them. A search call with a missing argument
    comes back as a clear validation error.
  • Stdio through the daemon (default mode): same behaviour as direct mode, including a real search hit on an indexed
    file.
  • Two clients on one daemon: the second client attached to the daemon the first had started. Both got correct answers.
    The daemon shut itself down after both disconnected.
  • HTTP: the initialize request succeeds and returns a session id.
  • Both protocol versions (stateful and stateless) against one daemon: two subagents connected to the same daemon, one per protocol version. All steps passed for both.

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

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

  1. Dependency bump: pyproject.toml, uv.lock, requirements-lock.txt.
  2. Core SDK 2.x migration: base.py (callbacks, serve_connection, build_streamable_http_app, argument validation).
  3. Transport rewiring: daemon/server.py, stdio.py, http_server.py. The daemon's hand-rolled JSON-RPC dispatcher is deleted.
  4. Stdin extraction: utils/stdio_lines.py and client_proxy.py.
  5. Tests and harness.

Strengths

  • The deleted daemon dispatcher is real DRY progress. The code had two protocol implementations before; now it has
    one, and the stdin handling that was Windoshared place.
  • The stdio_lines extraction is a faithful move of the old Windows polling and Unix pipe code, and ClientProxy and
    stdio now share it.
  • The code drops the SDK-private stream import and builds plain anyio streams. A test also guards against private
    mcp.*._x imports.

Issues

Major

  • Removed os.environ["CHUNKHOUND_MCP_MODE"] = "1" from MCPServerBase.init (base.py, around line 161 on main). PR description never mentions it. Removal , because daemon/discovery.py:1089-1096deliberately scrubs this variable. But it also changes behavior for HTTP and for in-process stdio construction. rich_output.py:179 and run.py:42 guards de that every entry point (main.py:238,mcp.py:68, http_server.py:264) still sets it before anything can print to stdout. Add a note or a test. serve_connection can hang in pump_in (basef server.run() returns or raises whileread_frame() is blocked (a stalled stdin or IPC read), the finally closes the memory streams. It never cancels pump_in, so the task group waits for the noup scope after run() returns.
  • Tool-argument validation has no test and no stated schema source (base.py, around lines 394-411). It validates against TOOL_REGISTRY[...].parameters. The _build_filtered_tool_dicts(), which candiffer (for example read-only filtering). Validate against what is advertised. Also add a contract test for the error shape. The PR only verified this man

Minor

  • base.py, around line 636: the serve_connection docstring says malformed frames are forwarded and the session keepsserving. The second commit message said thPR description says "skipped". The daemon'sknown gap, where a malformed frame with an id gets no reply, is a real JSON-RPC conformance hole, and it is not tracked anywhere.
  • tests/unit/test_mcp_wrapper_sdk_isolation.py: the isolation test only checks mcp and mcp.*. base.py also imports mcp_types.jsonrpc, and the wrappers could g caught. common.py also still importsmcp.types, so "single dispatch point" is only partly true. That AST test, and the tests that reach in_handlers, go against the AGENTS.mdTESTING_PHILOSOPHY. They test internal plumbing, not a user-visible contract. The _request_handlers accessor is private SDK API, so it is fragile across m
  • stdio.py: it imports json, anyio and stdio_lines inside run() and defines the frame helpers inline. This is fine, but those helpers could sit with stdio_lin
  • http_server.py: the new # type: ignore[union-attr] hides a real None path. Prefer an assert or a typed accessor.
  • ClientProxy and the daemon each hand-roll ipping. serve_connection already toleratesbad frames, so one place should own that policy.
  • The 15s init timeouts in the tests defeat they exist to test. The author already noteslazy-importing LLM providers as a follow-up. Open an issue and link it.
  • mcp-types is now pinned as a direct depende the uv.lock and requirements-lock.txtentries agree.

Reusability

  • Move the frame read and write helpers fromrame/_write_frame and ClientProxy into asmall shared "frame transport" utility. Each currently re-implements JSON decode, skip and write.
  • Extend the isolation test to cover mcp_typt from a glob instead of a hard-coded list.This also lets it handle common.py.
  • Keep schema validation as a single functiol dicts, so listing and validation can neverdiverge.
    Decision: REQUEST CHANGES. Please address the CHUNKHOUND_MCP_MODE removal, the pump_in hang and the validation schema source. Add contract tests for validation ang. The rest can be tracked as follow-ups.

@HananKavitzAmat

HananKavitzAmat commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

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

  1. Dependencies: pyproject.toml, uv.lock, requirements*.txt.
  2. Core SDK 2.x migration: base.py and common.py.
  3. Transport rewiring: daemon/server.py, stdio.py, http_server.py.
  4. Stdin extraction: utils/stdio_lines.py and client_proxy.py.
  5. Tests and harness.

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:

  • pump_in hang: serve_connection now calls ts finally (base.py around line 344).
  • Validation schema source: _validate_advertised_tool_arguments validates against _build_filtered_tool_dicts(), thesame source as tools/list.
  • Docstring and PR description: The serve_connection docstring now says malformed frames are forwarded and the sesskeeps serving. It also states the known gawith an id gets no reply.
    rengths
  • The hand-rolled daemon JSON-RPC dispatcher is deleted: _dispatch_mcp, _handle_initialize, _handle_tools_list and _handle_tools_call are gone. That leaves ostead of two, and the daemon's old fixedprotocolVersion no longer drifts from the SDK.
  • Windows stdin polling lives in utils/stdioth no mcp imports, shared by ClientProxy andstdio.
  • The CHUNKHOUND_MCP_MODE removal from MCPSe discovery.py:1089-1096 scrubs that variableon purpose so the daemon can log, and init was silently re-setting it inside the daemon process. The stdio, HTTP
    and CLI entry points still set it themselv.py:264, main.py:238, mcp.py:68).

Issues

Critical: none.
Major

  • base.py:337-344: the finally cancels the whole task group, which includes pump_out. If run() returns, for example on stdin EOF, right after sending its last relled mid-write_frame. For stdio the threadwrite is probably not interrupted, but the daemon's await writer.drain() can be. Cancel only pump_in, and let pump_out finish once write_stream is closeThis is the one logic fix I'd require, alongwith a test that sends one request, then EOF, and checks the response still arrives.

Minor

  • base.py:~1380: validation is not covered bat asserts a missing required argumentreturns isError=True with an Input validation error: message. jsonschema.validate also re-checks the schema on every call, so a precompiled validator is cheape
  • base.py:337-344 and stdio.py:143-176: the iter_stdin_lines() async generator is never aclose()d after serve_connection. On Unix the connect_readd on garbage collection. Wrap it incontextlib.aclosing. Malformed or undecodable frames get no JSO484 and client_proxy silently continue. Thisis acknowledged as a known gap, but open a tracking issue instead of leaving it only in a docstring. stdio.py:143-176: it imports json and anyie frame helpers inline.
  • tests/unit/test_mcp_wrapper_sdk_isolation.py and the tests that touch _request_handlers test internal plumbing andprivate SDK accessor. They go against TEST
  • The isolation test does not cover mcp_types, and common.py still imports mcp.types, so "single dispatch point" is only partly true.
  • The 15s init timeouts in the tests defeat the 5s VS Code startup guard they exist to test. Open an issue for lazy-importing the LLM providers and link
  • The removal of CHUNKHOUND_MCP_MODE is not mentioned in the PR description. Add one line about it.

Reusability

  • Move stdio.py's read_frame and write_frame and _write_frame into a small sharedframe-transport helper. Each re-implements decode, skip-non-dict and write.
  • Make the isolation test glob chunkhound/**s.*, with an explicit allowlist (base.py,common.py).
  • ClientProxy._forward_stdin_to_socket and s lines and skip bad ones. One place shouldown that policy.

Decision: REQUEST CHANGES. Fix the pump_out cancellation race and add a contract test for argument validation. The remaining items can be follow-ups.

@tamarsh68

Copy link
Copy Markdown
Contributor Author

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
checks the response still arrives.

On the minors:

  • Argument validation test: test_tools_call_rejects_arguments_violating_input_schema covers a missing required argument and an invalid enum value. Both return isError=True. Validation now runs against the schema advertised by tools/list, after coercion.
  • Precompiled validator: done in 783f27d. There is no per-call check_schema().
  • Unclosed iter_stdin_lines(): done in 783f27d. It is closed with contextlib.aclosing, and iter_json_frames() now owns the skip policy.
  • Malformed frame with an id: fixed in 5b29a16. serve_connection now replies with JSON-RPC -32600 Invalid Request carrying that id, and the session keeps serving. A write lock serializes that reply against pump_out. A new test sends {"id": 7, "method": 123} and asserts the error reply.
  • Isolation test scope: it now covers mcp_types as well as mcp. common.py is an explicit exemption for type helpers only.
  • Tests reaching into _request_handlers: the tests now go through serve_connection, via a tests/utils/mcp_session helper.
  • 15s init timeouts: keeping these on purpose. The MCP 2.x SDK is a heavier package, so initialization takes longer than the old 5s bound allows. They are still bounded, so a real hang is still caught.

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

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.

  1. Dependency bump (pyproject.toml, lockfiles).
  2. SDK 2.x core (base.py, common.py).
  3. Transport wrappers (daemon/server.py, stdio.py, http_server.py).
  4. Shared stdin helper (utils/stdio_lines.py, client_proxy.py).
  5. Tests and harness.

Groups 3 and 4 depend on group 2, so I read group 2 first.

Strengths

  • There is now one protocol implementation instead of two. The daemon's dispatcher and its fixed protocolVersion are gone.
  • stdio_lines is a clean, mcp-free home for the Windows polling code. ClientProxy and stdio share it, and iter_json_frames owns the skip-bad-line policy.
  • Validation runs against _build_filtered_tool_dicts(), the same source as tools/list. The validator is precompiled, and pump_out now drains after run() ends.

Issues
itical: none.
jor: none.
nor

  • base.py pump_in (around the read_stream_writer.send(message) call): serve_connection closes read_stream_writer and then cancels pump_in. If pump_in is mid-seClosedResourceError/BrokenResourceError. That surfaces as an ExceptionGroup and can mask run()'s own result. Cancel in_scope first and close the writer after, or catch those errors in pump_in.
  • base.py pump_in, invalid-frame path: it awaits send_frame for the -32600 reply before forwarding exc. A slow client's drain() therefore stalls inbound the docstring should say so.
  • base.py, serve_connection docstring: it still lists "Known gap: a malformed request that carries an id gets no reply". Commit 5b29a16 fixed that, per thove the stale paragraph. The PR body's "Known gaps" has the same stale line.
  • common.py, last_n_commits coercion: this a PR body doesn't mention it. A non-numericstring raises ValueError, which on_call_tool does catch and report as a validation error. Please say so in the
    description.
  • stdio.py, run(): the imports (json, anyio.to_thread) and the frame helpers are inline. Move read_frame/write_frame
    next to iter_json_frames in stdio_lines.
  • http_server.py: the assert self._session_manager is not None is fine. The _MCP_AVAILABLE conditional could be
    simpler if build_streamable_http_app raise.
  • Tests: the 15s init timeouts defeat the 5s VS Code startup guard they check. Please open an issue for lazy-importing
    the LLM providers and link it in the PR bo
  • The PR description doesn't mention that CHUNKHOUND_MCP_MODE is no longer set in init. Add a line saying the
    entry points set it instead (main.py, mcp.aemon intentionally doesn't.
  • common.py still imports mcp.types. This is acknowledged, but the "single dispatch point" wording overstates it.
  • I did not verify that jsonschema and mcp-tndencies in the final pyproject.toml. Thelocal checkout isn't at head. Please confirm both are listed.

Reusability

  • Three places now decode frames and skip ba daemon _read_frame, and ClientProxy's IPCreads. A small shared helper could own that policy.
  • The frame write path is duplicated betweenemon _write_frame. These differ only intransport, so this is acceptable.
    Decision: REQUEST CHANGES (light). Fix the pump_in close/cancel ordering and the stale docstring and PR-body text. The remaining items can go to follow-up issues.

tamarsh68 and others added 26 commits November 11, 2026 13:10
…; 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().
… 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.
…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]>
…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.
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

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

  1. Dependencies: pyproject.toml, uv.lock, requirements*.txt.
  2. SDK 2.x core: mcp_server/base.py and common.py.
  3. Transport wrappers: daemon/server.py, stdio.py, http_server.py.
  4. Shared stdin helper: utils/stdio_lines.py and client_proxy.py.
  5. Tests and harness.

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

  • The daemon's hand-rolled JSON-RPC dispatcher is gone, so there is one protocol implementation instead of two.
  • Argument validation uses _build_filtered_tool_dicts(), the same source tools/list advertises (base.py:1422). The validator skips the per-call check_schema().
  • pump_in is cancelled on its own scope so pump_out can drain queued responses. A malformed frame that carries an id now gets a -32600 reply (base.py:1604-1640).

Issues

Critical: none.

Major

  • base.py:1660-1668: in the finally block, read_stream_writer.aclose() runs before in_scope.cancel().
    • read_stream_writer is a zero-buffer streng reads it, so pump_in can be blocked inread_stream_writer.send(...).
    • Closing the writer under it raises CloserceError inside pump_in. Those escape as anExceptionGroup and can mask run()'s own result.
    • Fix: call in_scope.cancel() first and clternatively, catch those two errors inpump_in.
    • Add a test where a frame is in flight wh

Minor

  • The docstring "Known gap" paragraph (base.py:1556-1558) is stale, because -32600 now fixes that gap. The same line
    is still in the PR body's "Known gaps". Re
  • The docstring also says the SDK drops an invalid frame and sends no reply. That is no longer accurate, because
    serve_connection now replies itself. The as before send(exc), so a slow client'sdrain() stalls inbound reads. Mention that in the docstring.
  • The PR body doesn't mention that CHUNKHOUNn MCPServerBase.init. Say that the entrypoints set it instead (main.py, mcp.py, http_server.py) and that the daemon deliberately doesn't
    (daemon/discovery.py).
  • The PR body doesn't mention the last_n_commits coercion in common.py.
  • "Single dispatch point" overstates it, becmcp.types. Reword it, or note that common.pyis an explicit allowlist exemption.
  • The 15s init timeouts defeat the 5s VS Coding. Open an issue for lazy-importing the LLM providers and link it in the PR.
  • stdio.py defines frame helpers and imports run(). Move read_frame and write_frame nextto iter_json_frames in stdio_lines.
  • The # type: ignore[union-attr] and _MCP_AVver.py could be simpler. Use an assert or atyped accessor.
  • Some tests still touch _request_handlers, NTS.md TESTING_PHILOSOPHY says to testcontracts, not plumbing. Finish moving them onto the tests/utils/mcp_session helper.

Reusability

  • Frame decode-and-skip logic now lives in t, the daemon's _read_frame, and ClientProxy's IPC reads. Have one helper own the skip policy.
  • Make the isolation test glob chunkhound/**base.py, common.py) instead of a hard-codedwrapper list.
  • pyproject.toml at head lists mcp>=2.3.0,<3nschema>=4.0.0. That confirms the dependencyquestion from the earlier review.
    Decision: REQUEST CHANGES (light). Fix the close-before-cancel ordering in serve_connection and add a test for it. Fix the stale docstring and PR-body text. The rew-up issues.

@HananKavitzAmat
HananKavitzAmat added this pull request to the merge queue Nov 11, 2026
Merged via the queue into chunkhound:main with commit 3b30593 Nov 11, 2026
25 checks passed
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.

2 participants