Skip to content

fix(agent): reopen an mcp.json server whose connection retired - #7114

Merged
M4n5ter merged 4 commits into
rust-previewfrom
fix/mcp-reopen-retired-connection
Nov 21, 2026
Merged

M4n5ter merged 4 commits into
rust-previewfrom
fix/mcp-reopen-retired-connection

Conversation

@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor

Summary

Part of #7112 (direction 1 only).

A call that ends with an unknown result retires its MCP connection. The cached file layer kept handing that connection to every later turn and conversation, so each failed before its model request until the Host restarted or mcp.json changed.

A cached mcp.json layer is now reused only while all of its connections, and those of the file layers below it, are available. Otherwise the next preparation reopens the layer under the same revision: a new protocol session with new binding generations. The call is never replayed.

  • The startup gate keeps concurrent preparations to one reopen; the second one finds the new layer.
  • The replaced layer stays valid for Runs that already hold it (current_activation accepts it) and is closed by prune() once nothing references its catalog, or when Projects closes.
  • A client composition built over a replaced layer is rebuilt.
  • If reopening fails (the server does not start, or an earlier cleanup failure is retained), the cached layer stays published, as today.

Not covered

  • The same turn. After fix(agent): hand a tool call with an unknown result back to the model #7043 hands the unknown result back, the next model request in that turn still fails. Nothing prepares MCP within a turn, and a reopened connection has a new generation, which the authorization check refuses for admitted work by design. Continuing the turn needs a change to that contract.
  • Installation-configuration servers. Their tools and binding generations are part of the Owner's tool basis for the whole activation, so reopening one means reactivating. The product configures MCP through mcp.json, which this covers.
  • The remote CleanupUnconfirmed hold and the misleading failure text (directions 3 and 4 of bug(agent): one MCP call with an unknown result retires the connection and fails every later request #7112).
  • Reopening a layer also restarts its healthy servers. A Run that had selected their tools fails on its next request with a changed binding, the same as after editing mcp.json today.

@M4n5ter this is in your area and it touches current_activation; say so if you want the reopen done differently or would rather take it yourself.

AI use

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Claude Code. A Claude Opus 5.5 subagent reproduced the problem and wrote the change and test; Claude Fable 5.2 set the scope and reviewed the diff.

Checklist

  • Tests cover the change and fail without it
  • Format, typecheck and the affected suites pass locally

mcp_server_that_exits_mid_call_is_reopened_for_the_next_turn: a stdio server from the global mcp.json exits during a call; the next turn in that conversation and a new conversation each reach the model and complete, and the server process has been started exactly twice. Tested on the global file layer only; the project layer, the client recomposition and the failed-reopen fallback are covered by reading. maka-agent-native lib: 197 tests, passing except two that are intermittent on plain rust-preview (see #7111).

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

English

Thanks for the clear breakdown in #7112 and the real-process MCP crash/reopen test. There are a few concrete issues to address in this implementation:

  1. keep_cached silently swallows reopen errors and causes double-spawns per message (plugins/agent/native/src/mcp/projects.rs)
    When reopening fails (e.g., broken command / unreachable server) or when cleanup_failures is already non-empty, keep_cached discards the real error and returns Ok(dead_catalog). On a real agent.send path:

    • owner/send.rs calls prepare() -> sees !layers_available() -> calls start(), fails to reopen, swallows the error, and queues the message with the dead catalog.
    • driver_assembly.rs then calls capture() -> sees !layers_available() again -> runs start() and spawns/fails the broken server a second time, swallows the error again, and starts the Run.
    • The Run then fails at authorize_model_request with unavailable_selected_binding -> the opaque Recovery is unavailable for adapter supplied no safe interrupted-attempt recovery evidence message, hiding the actual startup or cleanup failure.
    • It also bypasses the existing cleanup_failures hard gate whenever a retired cache entry exists.
      Because nothing removes the old entry from snapshots.revisions until a new layer succeeds, returning Err(error) directly on reopen failure preserves the existing cache without silently swallowing the real error.
  2. Concurrent reopens of global ~/.maka/mcp.json across different workspaces are not serialized (plugins/agent/native/src/mcp/projects.rs)
    startup_gate is keyed by proposal.revision. Two workspaces with different project mcp.json files (or one with a project file and one without) have distinct proposal.revisions while sharing the same global_revision. When a global server retires and both prepare concurrently, each acquires a different gate and runs open_layer(&proposal.global, ...) in parallel, launching duplicate global MCP processes and pushing the losing live process into snapshots.replaced. Acquiring startup_gate(&global_revision) around opening the global layer (in consistent global-then-project lock order to prevent deadlocks) avoids duplicate spawns.

  3. Design trade-off: file-layer reopening interrupts sibling healthy servers in the same mcp.json (plugins/agent/native/src/mcp/projects.rs, plugins/agent/native/src/owner/access/model.rs)
    Suppose mcp.json defines Server A (healthy) and Server B (crashes in Session 2), while Session 1 is mid-turn using Server A. Reopening the whole mcp.json layer gives Server A a new binding generation. Although current_activation now accepts Session 1's old activation via snapshots.replaced, current_activation still returns the newly published catalog (Server A gen 2), so Session 1's next model step fails authorize_model_request's internal_bindings generation check. Worth clarifying whether whole-layer blast radius is acceptable here or if reopening should be scoped to the retired server.

简体中文

感谢在 #7112 里把链路梳理得很清楚,也补了起真实 MCP 进程的端到端测试。当前实现有几个明确可达的问题需要先处理:

  1. keep_cached 静默吞掉重开失败,且单条消息会连续拉起两次坏进程(plugins/agent/native/src/mcp/projects.rs)
    当重开失败(命令异常/远端不可达)或 cleanup_failures 已非空时,keep_cached 会把真实错误吞掉并返回 Ok(死 catalog)。走实际发送路径时:

    • owner/send.rs 调 prepare() 看到 !layers_available() -> 调 start() 重开失败,吞错后仍用死 catalog 把消息入队;
    • 紧接着 driver_assembly.rs 调 capture() 再次看到 !layers_available() -> 又进 start() 第二次拉起并失败,再次吞错启动 Run;
    • 随后 Run 在 authorize_model_request 撞 unavailable_selected_binding,落到晦涩的 Recovery is unavailable for adapter supplied no safe interrupted-attempt recovery evidence,把真正的启动或清理报错全掩盖了。
    • 同时,只要存在已失效的缓存层,原本 cleanup_failures 的硬拦截也会被绕过。
      由于新层成功前本来就不会从 snapshots.revisions 删除旧条目,重开失败时直接返回 Err(error) 即可保留旧缓存状态,同时把真实原因暴露出来,不要静默吞错。
  2. 跨 workspace 共享全局 ~/.maka/mcp.json 时 startup_gate 挡不住并发重开(plugins/agent/native/src/mcp/projects.rs)
    startup_gate 目前按 proposal.revision 加锁。两个不同 workspace(项目 mcp.json 不同,或一个有一个没有)拿的是不同的 proposal.revision,但共用同一个 global_revision。当全局 MCP 服务退役、两边并发准备时,会各自拿到不同锁并并行执行 open_layer(&proposal.global, ...),拉起两份重复的全局进程,其中一份活进程直接被顶进 snapshots.replaced。应该对全局层按 global_revision 单独加 gate(固定先 global 后 project 顺序加锁避免死锁)。

  3. 设计取舍:整层重开会波及同一 mcp.json 中正在运行的健康服务(plugins/agent/native/src/mcp/projects.rs、plugins/agent/native/src/owner/access/model.rs)
    如果 mcp.json 同时配了服务 A(健康)和服务 B(在会话 2 崩溃),而会话 1 正在跑使用服务 A 的多步 turn:会话 2 重开整个 mcp.json 层会给服务 A 也分配新的 binding generation。虽然 current_activation 通过 snapshots.replaced 放行了旧 activation 的身份校验,但它最终返回的仍是新发布层(服务 A 已是新 generation),导致会话 1 下一步在 authorize_model_request 校验 internal_bindings 时失败中断。这里需要明确是接受整层重开的波及面,还是把重开粒度收窄到失效的单个 server。

@UncertaintyDeterminesYou4ndMe
UncertaintyDeterminesYou4ndMe force-pushed the fix/mcp-reopen-retired-connection branch from a2674e8 to 8ce9a7c Compare November 21, 2026 08:43
@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Rebased onto b499e51; the fix for item 1 is a separate commit, 8ce9a7c.

1. keep_cached. You are right, including the double spawn: send.rs and then driver_assembly.rs each tried to reopen, and the Run ended with the opaque recovery text. keep_cached is removed. The cleanup-failure gate and both open failures return their error as they did before this PR; a cached layer is reused only while layers_available() holds. When the server cannot restart, the send is now rejected with the server's own startup error and the message is not queued, so nothing spawns it a second time. New test mcp_server_that_cannot_restart_rejects_each_message_with_its_startup_error: after the crash, two messages are each rejected with MCP server fixture: MCP initialization failed, and the process count goes 1 → 2 → 3, one start per message. It failed before the fix with "send was accepted".

2. Concurrent reopen of the global layer. I think this is already serialized, before and after this PR. start() takes startup_gate(proposal.revision) and then, whenever the global revision differs, startup_gate(global_revision) (global_gate / _global_opening), re-checks the global cache inside it, opens, and writes the snapshot before releasing. A workspace without a project file has proposal.revision == global_revision (propose()), so it takes that same gate. The order is always project then global, so there is no cycle. This PR only adds layers_available() to the re-check inside the gate. If I am missing a path that opens the global layer outside that gate, point me at it. I did not add a concurrency test: making two workspaces enter the global open at once deterministically needs hooks in the code.

3. Blast radius. Your example is worse than what I wrote in the description: it breaks a Run that is mid-turn on a healthy server, not only a later request. I agree the reopen should be scoped to the retired server. That means per-server binding generations inside a layer in place of one open per layer, which goes further into the connection ownership than this PR does. Would you rather take that part, or should I attempt it here? If you prefer, I can also cut this PR down to the error reporting from item 1 and leave reopening to that design.

maka-agent-native lib: 200 tests passing.

(Claude Code, Claude Fable 5.2, with a Claude Opus 5.5 subagent on the implementation.)

@M4n5ter

M4n5ter commented Nov 21, 2026

Copy link
Copy Markdown
Member
English

Thanks for the clean follow-up!

  • Item 1 (keep_cached): Looks great — removing keep_cached fixes both the opaque error and the double spawn, and the new regression test covers it cleanly.
  • Item 2 (Global layer gate): You're right — start() already takes startup_gate(&global_revision) in project -> global order (and shares the same gate when proposal.revision == global_revision). Good pushback; sorry for missing lines 678–683 in the earlier pass.
  • Item 3 (Blast radius / per-server reopen): Go for it right here in this PR! Don't worry about the change footprint — feel free to rework the layer/server connection ownership cleanly and elegantly so only the retired server is reopened without disturbing healthy sibling servers or in-flight Runs. We have no backward-compatibility burden here, so no need for compatibility branches or shims.
简体中文

回复和修复都很清楚:

  • 第 1 点(keep_cached):改得很干净,报错透传和二次 spawn 都解决了,新补的单测也覆盖到位。
  • 第 2 点(全局层并发重开):你说得对,start() 里确实已经按 project -> global 顺序拿了 startup_gate(&global_revision)(无项目文件时共用同一把 gate),上一轮漏看了 678–683 行,感谢指出。
  • 第 3 点(按 server 粒度重开):别怕改动面,直接在这个 PR 里干就行!改动大点没关系,能把层内连接所有权和 per-server binding generation 拆干净优雅、做到只重开断连的那个 server 而不影响同层健康 server 和在途 Run 就行。目前没有历史兼容性包袱,直接按最干净的设计重构即可,不用留兼容层。

@UncertaintyDeterminesYou4ndMe
UncertaintyDeterminesYou4ndMe force-pushed the fix/mcp-reopen-retired-connection branch from 8ce9a7c to e1bb2fe Compare November 21, 2026 10:02
@UncertaintyDeterminesYou4ndMe

Copy link
Copy Markdown
Contributor Author

Item 3 is done in e1bb2fe, rebased onto c7b7bf2.

What changed. A reopened layer now starts only the servers whose connection is not available. Every other server of that layer keeps its connection and its authority generation, so the internal_bindings check in authorize_model_request still passes for a Run that uses them.

  • Servers holds one entry per server (name, generation, connection, bindings). Servers::reopen(previous, ..) keeps the available entries of previous and connects the rest. A failed connect closes only the connections that this attempt started.
  • A replaced layer keeps only the connections the new layer did not take over. They close when nothing references the old catalog, as before. I did not close them at reopen time, because on_tool_list_changed also makes a connection unavailable while calls on it can still be in flight.
  • start() holds the cached layer's catalog while it reopens, so prune cannot close a connection that is being handed over.
  • When the global layer is reopened, the project layer above it is rebuilt on the new parent with all of its own connections kept.

Limit. A Run whose selected tools include the retired server still stops at its next model step, as it did before this PR. Only the next message gets the new connection.

Test. The fixture mcp.json now has a second server. The reopen test asserts that it starts once and still answers after the first server was replaced. It does not run a second Session mid-turn; the kept generation follows from the kept connection.

The two red checks on the previous head were desktop_composer_references_a_conversation_without_waking_it on Windows, which this PR does not touch.

— Claude Fable 5.2, working with the PR author

A call that ends with an unknown result retires its MCP connection, and the
cached layer kept handing that connection to every later turn and Session,
so each one failed before its model request until the Host restarted.

A cached file layer is now used only while all of its connections, and
those of the file layers below it, are available. Otherwise the next
preparation reopens the layer under the same revision, as a new protocol
session with new binding generations; the call itself is never replayed.
The startup gate keeps concurrent preparations to one reopen. The replaced
layer stays valid for Runs that already hold it and closes once nothing
references it, or when the Projects close. A client composition over a
replaced layer is rebuilt. If reopening fails, the cached layer stays in
use as before.

Servers from the installation configuration are unchanged: their tools
and bindings belong to the activation's tool basis and change only by
reactivation.

Refs #7112

Generated-by: Claude Code (Claude Opus 5.5)
…start

A failed reopen no longer falls back to the retired layer. The send is
rejected with the server's startup error, as for a first open, so one
message starts the broken server once and the cleanup-failure gate holds
again.

Generated-by: Claude Code (Claude Opus 5.5)
The other servers of the same mcp.json layer keep their connection and
authority generation, so Runs that use them continue.
@M4n5ter
M4n5ter force-pushed the fix/mcp-reopen-retired-connection branch from e1bb2fe to fbafd44 Compare November 21, 2026 10:21
@M4n5ter

M4n5ter commented Nov 21, 2026

Copy link
Copy Markdown
Member
English

The per-server reopen design (Server, Servers::except, Snapshot::replaced_by, and client.rs recomposition) is super clean — ownership, rollback, and prune cascading all line up.

Rebased onto rust-preview and added one small follow-up before merging:

  • Moved layers_available to Projects::layers_available(&self, catalog) checking each layer's snapshot.servers via Servers::available() (and verifying the layer hasn't been superseded in snapshots.revisions). This covers MCP servers that initially expose zero tools (so they still reopen after notifications/tools/list_changed or transport retirement) and checks per server rather than per tool binding.
  • Added mcp_zero_tool_server_reopens_after_retiring in mcp_connection.rs covering that case while verifying sibling servers stay on their original process.

Verified locally (cargo fmt --all -- --check, cargo clippy -p maka-agent-native --all-targets -- -D warnings, mcp_connection 3/3 x 3 runs, mcp 7/7), merging now.

简体中文

按 server 粒度重开的这套设计(Server、Servers::except、Snapshot::replaced_by 以及 client.rs 重组合)非常干净,所有权拆分、失败回滚和 prune 级联回收都对得上。

已 rebase 到最新 rust-preview,并在合并前顺手补了一个小边界:

  • 将 layers_available 移到 Projects::layers_available(&self, catalog),改为按 layer 链检查 snapshot.servers 的 Servers::available()(并校验该层未被同 revision 的新快照替换),既覆盖启动时返回 0 个 tool 的动态 MCP server(在 notifications/tools/list_changed 或断连后也能正常重开),也从按 tool 遍历改为按 server 检查。
  • 在 mcp_connection.rs 中补充了 mcp_zero_tool_server_reopens_after_retiring 回归测试,同时验证同文件其它健康 server 保持原进程。

本地已验证通过(cargo fmt --all -- --check、cargo clippy -p maka-agent-native --all-targets -- -D warnings、mcp_connection 3/3 连跑 3 遍、mcp 7/7 全过),直接合入。

@M4n5ter
M4n5ter merged commit a0895bc into rust-preview Nov 21, 2026
@M4n5ter
M4n5ter deleted the fix/mcp-reopen-retired-connection branch November 21, 2026 10:21
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