← Back to Pull requests

fix(agent-mcp): use the configured server name for sdk tool names #21322

Open
ggbdpq opened this pull request with 2557 lines diff across 26 files
View on GitHub
ggbdpq ggbdpq commented on Oct 04, 2026 10:36 UTC
Author

Summary

Fixes #21321.

When an Agent runtime mounts user-installed MCP servers, buildAgentMcpServers keyed the SDK server entry by the raw mcpId (a 36-char UUID) and set its name to the same UUID. For type: "sdk" servers the Claude Agent SDK discards the entry's name field and uses the record key as the server identity and tool-name prefix, so the mcp__<UUID>__ prefix (43 chars) ate most of the SDK's 64-char tool-name budget and long tool names got truncated to unreadable <8 chars>_<12-hex> hashes (15 of Firecrawl's 26 tools in the reporter's setup).

The fix uses the configured short server name as the record key and entry name, with a conservative collision fallback to the mcpId (unknown name, or a name already taken by another mounted server or one of the built-in cherry server keys). createMcpBridgeServer stays bound to the id, so the upstream connection path is untouched. Consumers audited: the claude-code runtime is the fix point; the DSH bridge reads value.name, so its tool names become readable too; the Pi runtime deliberately uses id ?? name for stable namespacing and is unaffected.

Verification

| Check | Result |
| --- | --- |
| New tests: short name registered as the SDK key with the bridge still bound by id; name collision falls back to mcpId; built-in cherry keys cannot be shadowed | 2 cases red before fix, all green after |
| buildMcpServers.test.ts full file | 31/31 passed |
| Extended: claudeCode + dsh + pi + toolApproval runtime suites | 49 files / 1117 tests passed |
| pnpm typecheck (all groups) | 0 errors |
| oxlint + oxfmt --check on changed files | clean |

AI Use

Implemented with GLM-5.3-Flash (ZCode). Root cause localization, consumer-chain audit (claude-code / DSH / Pi), patch and tests by AI; verified locally as listed above.

Checklist

  • I have read the Contributing Guide

  • Commit signed off (DCO)

  • Tests added for the changed behavior

  • pnpm typecheck passes locally
  • Diff: 2557 lines (+2434 / -123) across 26 files Reviewer: ggbdpq Review duration: 14308m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.96) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.96 · 2557 lines diff across 26 files
    0.96
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    82%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Sensitive Paths sensitive_paths
    0.096
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    44 items
    ggbdpq ggbdpq commented on Oct 08, 2026 12:32 UTC
    Author

    This comment was translated automatically.

    Conflict resolution landed: rebased to latest main, head dc39005176.

    Upstream #17610 (MCP SDK v2) conflicted with this PR in the same two files, handled as follows:

    Semantic Decision (both orthogonal, both preserved)

  • Upstream changed structure: AgentMcpServer.instance → connect(transport), snapshot missing throws error, bridge factory lazified. This PR changed record key semantics (register with config name). Both don't conflict: buildMcpServers in mcpCatalog.ts still uses record key as SDK config key (source of mcp__<key>__<tool> tool name prefix), the fix in this PR remains necessary under the new sleeve structure.

  • Consumer verification: newly added Pi runtime (piMcpExtension.ts uses server.id ?? server.name, doesn't read record key) and DSH (buildDshCherryToolBridge tool naming uses server.name field) are both unaffected by the key name change.
  • Upstream New Test Adaptation (disclosure)

  • #17610 added settingsBuilder snapshot test asserting record key as mcp-1 (old key name behavior); per this PR's semantics the key should now be the snapshot server's config name Old server, updated that assertion (bridge still binds to id, toHaveBeenCalledWith('mcp-1', ...) assertion kept as-is).

  • This PR's test block adapted to new interface: asserts { type: 'sdk', name, instance: { connect } }; after bridge factory lazification, uses passthrough capture serveStdio to drive factory, proving bridge still binds to server id not record key.
  • Verification: 167/167 tests green in both affected test files; tsc --noEmit zero errors across four projects; oxlint/eslint/oxfmt all clean on changed files.

    ---
    <details>
    <summary>Original Content</summary>

    冲突解决落地:已 rebase 到最新 main,head dc39005176。

    上游 #17610(MCP SDK v2)与本单在同两个文件相撞,处理如下:

    语义裁决(双方正交,均保留)

  • 上游改的是结构:AgentMcpServer.instance → connect(transport)、快照缺失抛错、bridge 工厂惰性化。本单改的是 record key 语义(用配置名注册)。两者不冲突:mcpCatalog.ts 的 buildMcpServers 仍以 record key 作为 SDK config key(mcp__<key>__<tool> 工具名前缀来源),本单修复在 sleeve 新结构下依然必要。

  • 消费方核查:新增的 Pi runtime(piMcpExtension.ts 用 server.id ?? server.name,不读 record key)与 DSH(buildDshCherryToolBridge 工具命名用 server.name 字段)均不受键名变更影响。
  • 上游新测试适配(披露)

  • #17610 新增的 settingsBuilder 快照测试断言 record key 为 mcp-1(旧键名行为);按本单语义该键现应为快照 server 的配置名 Old server,已更新该断言(bridge 仍绑定 id 的 toHaveBeenCalledWith('mcp-1', ...) 断言原样保留)。

  • 本单测试块适配新接口:断言 { type: 'sdk', name, instance: { connect } };bridge 工厂惰性化后改用透传 capture serveStdio 驱动工厂,证明 bridge 仍绑定 server id 而非 record key。
  • 验证:两个受影响测试文件 167/167 绿;tsc --noEmit 四项目零错误;oxlint/eslint/oxfmt 改动文件全净。
    </details>

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 00:20 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +92,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId
    +      takenServerNames.add(serverName)
    +      servers[serverName] = {

    Must fix: A mounted server named __proto__ passes schema and service validation, but assigning it to this ordinary {} changes its prototype instead of adding an enumerable entry. Claude and DSH use Object.entries, and Pi uses Object.values, so all three silently omit this server and its tools. The previous UUID key preserved it. Use a null-prototype record or safe own-property insertion, and add a regression test for this accepted name.

    inv_44d81942c8936c54#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 00:20 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +92,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId

    Must fix: The fallback mcpId is not guaranteed to be free. Mount A before B, give A a configured name equal to B’s UUID, and name B skills. A occupies B’s UUID key; B then falls back to that same key because skills is reserved, silently overwriting A and removing its tools from every runtime. Both names are accepted, and the baseline retained both servers. Reserve mounted-server IDs before allocating configured names, or otherwise guarantee fallback uniqueness, and test that both entries survive.

    inv_0d0c589c6c622eb9#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 00:20 UTC
    Reviewer

    Two narrow but confirmed regressions silently drop mounted MCP servers: the accepted name __proto__ creates no enumerable entry, and an unchecked UUID fallback can overwrite another server. Both affect the shared map consumed by Claude, DSH, and Pi. Please fix both allocation cases and add regression coverage.

    Frozen-head CI records 13 successful and 5 skipped Check Runs. Legacy status has zero contexts; frozen-pair merge CI is unavailable. Review used static analysis; no local project tests ran, and CI logs were unavailable. Maintainer confirmation of the configured-name tool-identity behavior also remains outstanding under the review’s product-decision gate.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=093e9d6ddbcd1785 -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 02:14 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +92,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId
    +      takenServerNames.add(serverName)
    +      servers[serverName] = {

    Fixed in 8c5b0619b2: the record is now built with a null prototype, so a server configured as __proto__ registers as its own enumerable key instead of mutating the prototype. The regression test (keeps a server named __proto__ as an own enumerable key..., src/main/ai/runtime/agentMcpServers.test.ts) fails on the parent commit - Object.keys loses the entry - and passes here.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 02:14 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +92,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId

    Fixed in 8c5b0619b2: every mounted server's id is reserved before configured names are allocated, so the id fallback can no longer collide - the exact A/B scenario from this thread now keeps both entries. Regression test (keeps every mounted server when a fallback id collides with another server key) is red on the parent commit (A is silently overwritten) and green here.

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 02:51 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +98,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId

    Must fix: Changing this namespace invalidates existing agent-level denials such as mcp__<server UUID>__run: a server named github now exposes mcp__github__run, while resolveDisallowedTools() preserves the saved rule and Cherry's isDisabled() guard checks exact names. This configuration is accepted and persisted through the agent DataApi. An explicitly disabled tool can consequently execute in Full Access without the intended denial. Preserve or translate saved denials using stable server identity, and add regression coverage for an existing UUID-based rule across this change.

    inv_65c7909519ba8aba#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 02:51 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +98,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId
    +      takenServerNames.add(serverName)
    +      servers[serverName] = {
             id: legacyServer.id,
    -        name: mcpId,
    +        name: serverName,

    Must fix: Two valid mounted servers can now generate the same DSH tool identity: server docs exposing search__all and server docs__search exposing all both become mcp__docs__search__all. These names pass validation, and the bridge preserves this provider-safe identifier. DshCherryToolBridge then throws on the duplicate, closes connections and fails the entire turn before prompt admission. The former distinct UUID namespaces kept these tools separate. Guarantee uniqueness of final tool identities, for example with stable identity suffixes on collisions, while retaining readable prefixes and consistent policy mappings.

    inv_4a52b28e1d0c44c6#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 02:51 UTC
    Reviewer

    Two regressions require changes: saved agent-level MCP denials can stop matching after the namespace change, and valid server/tool pairs can collide and prevent DSH turns from starting. The earlier prototype and fallback-ID defects are fixed. Maintainer confirmation of the public tool-identity contract remains unrecorded.

    Frozen-head CI: 13 successful and 17 skipped Check Runs; legacy status has zero contexts. Frozen-pair merge CI is unavailable. Review used static source inspection and independent verification; no project tests ran locally, SDK execution was not reproduced, and CI logs were unavailable.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=ea8c882fb0577316 -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 04:22 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +98,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId

    Fixed in 4cadf1abf4. Mounted-server keys now come from a shared allocator (resolveAgentMcpServerKeys in agentMcpServers.ts) that mirrors the record build's allocation exactly, and every consumer rewrites legacy id-keyed rules before exact-name matching: the SDK disallowedTools hard-block list (settingsBuilder), the live policy snapshot's isDisabled (agentTools), and the dsh pushed policy on both connect and reconcile. Pi already matched mcp__<serverId>__<tool> directly and needs no change. Regression test: a legacy mcp__<uuid>__run rule now disables mcp__github__run (agentTools.test.ts, red on the parent commit), and the key map is pinned to the record allocation in agentMcpServers.test.ts.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 04:22 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -90,9 +98,15 @@ export function buildAgentMcpServers(
             throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
           }
           if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    -      servers[mcpId] = {
    +      // The SDK derives tool names (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from
    +      // the record key, so a 36-char UUID key leaves ~21 chars for the tool name and truncates the
    +      // rest into unreadable hashes (issue #21321). Register under the configured short name; fall
    +      // back to the id when the name is unknown or taken (`mcp_server.name` is not unique).
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId
    +      takenServerNames.add(serverName)
    +      servers[serverName] = {
             id: legacyServer.id,
    -        name: mcpId,
    +        name: serverName,

    Fixed in 4cadf1abf4. buildDshCherryToolBridge no longer throws on a flattened collision: the first pair keeps the readable wire name (mcp__docs__search__all) and a later one gets a deterministic 12-hex sha256 suffix of the raw server/tool pair, still within the 63-char provider-safe cap, so both tools stay registered and routable to their own server. Regression tests cover the exact docs/docs__search case, two same-named servers, and lossy-normalized tools within one server (DshCherryToolBridge.test.ts; the first two are red on the parent commit).

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 04:47 UTC
    Code Review
    src/main/ai/runtime/dsh/DshRuntimeConnection.ts:1
    @@ -398,6 +409,9 @@ export class DshRuntimeConnection implements AgentRuntimeConnection {
             ),
             { agentsDataRoot, toolResultRoot }
           )
    +      // Legacy id-keyed denials must reach the bridge plugin in the current name-keyed form — the
    +      // plugin matches exact runtime tool names (`mcp__<record key>__<tool>`).
    +      this.disabledTools = new Set(translateLegacyMcpToolRules([...this.disabledTools], this.serverNameById))

    Must fix: Translate denials through the bridge’s final allocated tool identities. For a UUID-mounted server named Old server exposing run, the saved mcp__<UUID>__run denial becomes mcp__Old server__run, but the executable tool is mcp__oldServer__run_4f7413c24ae4. The plugin’s exact match misses the denial and Full Access permits execution; the baseline UUID name matched. Reconciliation at line 603 repeats the mismatch. Share a stable-server/raw-tool-to-runtime-name mapping with startup and reconciliation, including normalization and collision suffixes.

    inv_740771ad070431b8#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 04:47 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -125,6 +120,23 @@ export async function buildDshCherryToolBridge(
       }
     }
     
    +/**
    + * Collision identity for two (server, tool) pairs that flatten to the same wire name: the readable
    + * prefix stays, and a fixed-width sha256 head of the raw pair keeps the extra name deterministic
    + * (the same pair always resolves to the same identity) within the 63-char provider-safe cap.
    + */
    +function disambiguatedDshToolName(serverName: string, toolName: string, taken: ReadonlySet<string>): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  const hash = createHash('sha256').update(`${serverName}\0${toolName}`).digest('hex')
    +  let name = `${base}_${hash.slice(0, 12)}`
    +  let counter = 1
    +  while (taken.has(name)) {
    +    name = `${base}_${(hash + String(counter)).slice(0, 12)}`

    Must fix: The counter never changes the candidate: SHA-256 already supplies 64 hex characters, so (hash + String(counter)).slice(0, 12) always returns the same prefix. Mounting docs with tools search__all and search__all_353988fff1e9, followed by docs__search with tool all, occupies both the plain name and its hash fallback. This loops forever synchronously in Electron main, freezing startup and main-process responsiveness. Make the counter affect the retained suffix and ensure allocation terminates.

    inv_247e01908a8ceb9f#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 04:47 UTC
    Code Review
    src/main/ai/tools/adapters/claudeCode/agentTools.ts:1
    @@ -197,8 +200,14 @@ export async function createClaudeAgentToolPolicySnapshot(
         policy = buildClaudeToolPolicy(nextAgent)
         // Same derivation as the build-time SDK `disallowedTools`, recomputed on every live update so a
         // mid-session disable is honored by `canUseTool` on the warm connection (registry exposure +
    -    // user opt-out + dependency cascade).
    -    disallowed = new Set(resolveDisallowedTools(nextAgent, options.conditionContext))
    +    // user opt-out + dependency cascade). Legacy id-keyed rules are rewritten first so a denial
    +    // saved under the pre-#21322 namespace still blocks its name-keyed tool.
    +    disallowed = new Set(
    +      resolveDisallowedTools(
    +        { disabledTools: translateLegacyMcpToolRules(nextAgent.disabledTools, options.serverNameById) },

    Must fix: Refresh the captured server mapping when reusing the policy snapshot for a new connection. Prewarm under server name old, rename it to new, connect without a denial, then add mcp__<UUID>__run during an active turn: ensureToolPolicySnapshot() retains the old options, and warm-signature mismatch disposal does not clear that snapshot. The live guard blocks mcp__old__run instead of executable mcp__new__run. Startup SDK restrictions cannot cover the later-added rule, so Full Access can execute it while rebuilding is deferred. Update mapping state while preserving the shared snapshot used by live hooks.

    inv_c8ce0a9103d90bf5#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 04:47 UTC
    Reviewer

    Changes requested at 4cadf1abf479633569c012f216c25456cb40f157: DSH denial translation can allow explicitly disabled tools, DSH collision retries can freeze Electron main, and a stale Claude policy mapping can miss a denial added during an active turn after prewarm and rename.

    Frozen-head CI: 8 successful, 8 in progress, 14 skipped Check Runs. Legacy status has zero contexts; frozen-pair merge CI is unavailable due to mismatched parents. Review used source analysis and reported isolated naming experiments; no project tests or application reproduction ran, and CI logs were unavailable. Maintainer approval of the public naming change is not established in the supplied context.

    Cherry Review · Blocked

    3 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=4cea8a2c1901cdbe -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 11:06 UTC
    Code Review
    src/main/ai/runtime/dsh/DshRuntimeConnection.ts:1
    @@ -398,6 +409,9 @@ export class DshRuntimeConnection implements AgentRuntimeConnection {
             ),
             { agentsDataRoot, toolResultRoot }
           )
    +      // Legacy id-keyed denials must reach the bridge plugin in the current name-keyed form — the
    +      // plugin matches exact runtime tool names (`mcp__<record key>__<tool>`).
    +      this.disabledTools = new Set(translateLegacyMcpToolRules([...this.disabledTools], this.serverNameById))

    Fixed in 8d9be7de8f: the bridge now exposes its mcp__<server name>__<raw tool> -> runtime-name mapping (ruleNames), and DshRuntimeConnection translates denial rules through it on both startup and reconcile. A legacy mcp__<UUID>__run rule now lands on the identity the bridge actually registered (mcp__oldServer__run_4f7413c24ae4 in your example); rules with no registered identity pass through unchanged.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 11:06 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -125,6 +120,23 @@ export async function buildDshCherryToolBridge(
       }
     }
     
    +/**
    + * Collision identity for two (server, tool) pairs that flatten to the same wire name: the readable
    + * prefix stays, and a fixed-width sha256 head of the raw pair keeps the extra name deterministic
    + * (the same pair always resolves to the same identity) within the 63-char provider-safe cap.
    + */
    +function disambiguatedDshToolName(serverName: string, toolName: string, taken: ReadonlySet<string>): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  const hash = createHash('sha256').update(`${serverName}\0${toolName}`).digest('hex')
    +  let name = `${base}_${hash.slice(0, 12)}`
    +  let counter = 1
    +  while (taken.has(name)) {
    +    name = `${base}_${(hash + String(counter)).slice(0, 12)}`

    Fixed in 8d9be7de8f: the counter now reaches the retained suffix by rehashing server\0tool\0<counter> (the old (hash + counter).slice(0, 12) always read the same 12 head chars of the 64-hex digest), and allocation is bounded - after 1000 candidates it throws instead of freezing the main process. Your taken-fallback scenario is a regression test now; on the pre-fix code the suite hangs indefinitely (the sync loop starves the worker's event loop, so even the test timeout cannot fire).

    ggbdpq ggbdpq commented on code on Oct 10, 2026 11:06 UTC
    Code Review
    src/main/ai/tools/adapters/claudeCode/agentTools.ts:1
    @@ -197,8 +200,14 @@ export async function createClaudeAgentToolPolicySnapshot(
         policy = buildClaudeToolPolicy(nextAgent)
         // Same derivation as the build-time SDK `disallowedTools`, recomputed on every live update so a
         // mid-session disable is honored by `canUseTool` on the warm connection (registry exposure +
    -    // user opt-out + dependency cascade).
    -    disallowed = new Set(resolveDisallowedTools(nextAgent, options.conditionContext))
    +    // user opt-out + dependency cascade). Legacy id-keyed rules are rewritten first so a denial
    +    // saved under the pre-#21322 namespace still blocks its name-keyed tool.
    +    disallowed = new Set(
    +      resolveDisallowedTools(
    +        { disabledTools: translateLegacyMcpToolRules(nextAgent.disabledTools, options.serverNameById) },

    Fixed in 8d9be7de8f: ClaudeAgentToolPolicySnapshot.update() now accepts a fresh serverNameById, and ensureToolPolicySnapshot passes the caller's current mapping on the warm-hit path - the rebuild after a mid-session rename translates id-keyed rules under the new key, so a later-added mcp__<UUID>__run blocks the executable mcp__new__run instead of the stale mcp__old__run. The shared snapshot instance is preserved (live hooks still resolve it by session id).

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 11:22 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -69,40 +76,40 @@ export async function buildDshCherryToolBridge(
       const clients: Client[] = []
       const tools: BridgeToolDescriptor[] = []
       const bindings = new Map<string, DshToolBinding>()
    +  const usedNames = new Set<string>()
    +  const ruleNames = new Map<string, string>()
     
       for (const [serverId, server] of Object.entries(servers)) {
         let client: Client | undefined
         try {
           client = await connectClient(server, `cherry-dsh-${serverId}`)
           const result = await client.listTools()
    -      const serverNames = new Set<string>()
    -      const serverTools = result.tools.map((tool) => ({
    -        descriptor: toBridgeDescriptor(server.name, tool),
    -        rawName: tool.name
    -      }))
    -      for (const { descriptor } of serverTools) {
    -        if (bindings.has(descriptor.name) || serverNames.has(descriptor.name)) {
    -          throw new DshCherryToolIdentityError(`Duplicate dsh Cherry tool name: ${descriptor.name}`)
    -        }
    -        serverNames.add(descriptor.name)
    -      }
           clients.push(client)
    -      for (const { descriptor, rawName } of serverTools) {
    -        tools.push(descriptor)
    -        bindings.set(descriptor.name, { client, rawName })
    +      for (const raw of result.tools) {
    +        // Two valid (server, tool) pairs can flatten to one wire name (`docs` + `search__all` vs
    +        // `docs__search` + `all`), and the first server to claim a name wins it. A stable hash
    +        // suffix keeps every tool callable — throwing here would fail the whole turn on a
    +        // configuration the name allocator accepts.
    +        let name = buildDshCherryToolName(server.name, raw.name)
    +        if (usedNames.has(name)) name = disambiguatedDshToolName(server.name, raw.name, usedNames)
    +        usedNames.add(name)
    +        ruleNames.set(`mcp__${server.name}__${raw.name}`, name)

    Must fix: Mount distinct UUID-backed servers named docs and docs__search, exposing search__all and all. Both write the rule key mcp__docs__search__all, although their executable names are distinct. The second mapping overwrites the first, so a saved UUID-based denial for the first tool translates to the second executable instead. Startup and reconciliation propagate this incorrect denial to exact-match enforcement, leaving the intended tool executable under Full Access. Preserve stable server-ID/raw-tool identity through translation and map it directly to the allocated runtime name.

    inv_e4c4d7ef9ac60821#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 11:22 UTC
    Code Review
    src/shared/ai/tools/mcpToolName.ts:1
    @@ -145,6 +145,44 @@ export type McpFunctionCallToolNameParts = {
       toolPart: string
     }
     
    +/**
    + * Saved agent-level denials written while MCP tools were keyed by server id (`mcp__<uuid>__tool`)
    + * no longer match runtime names derived from the configured server name. Rewrite each legacy rule
    + * whose server segment is a known id into the current server key; name-form rules (and rules naming
    + * unknown servers) pass through unchanged. Ids contain no underscores, so splitting on the first
    + * `__` is exact for legacy rules and never mis-splits a `__`-bearing server name.
    + */
    +export function translateLegacyMcpToolRules(
    +  rules: readonly string[] | null | undefined,
    +  serverNameById: ReadonlyMap<string, string> = new Map()
    +): string[] {
    +  return (rules ?? []).map((rule) => {
    +    if (!rule.startsWith('mcp__')) return rule
    +    const rest = rule.slice('mcp__'.length)
    +    const delimiterIndex = rest.indexOf('__')
    +    if (delimiterIndex <= 0) return rule
    +    const mapped = serverNameById.get(rest.slice(0, delimiterIndex))

    Must fix: Existing DSH runtime denials can use normalized and hashed names. For UUID aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa and tool this_is_a_long_tool_name_for_search, the baseline name was mcp__aaaaaaaaAaaa4aaa8aaaAaaaaaaaaaaa__thisIsALong_90a915510650. The agent PATCH API accepts and persists this denial, and baseline exact matching enforced it. Mounting the server as docs now changes its executable name, but this raw-ID lookup and the bridge map both leave the old denial unchanged. The formerly disabled tool can therefore execute under Full Access. Reconstruct previous DSH runtime aliases from server IDs and raw catalogs and map them to current allocated identities.

    inv_c8026c7dd363caa1#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 11:22 UTC
    Reviewer

    Two blocking DSH permission regressions: ambiguous server/tool names can redirect an existing denial to the wrong tool, and previously saved hashed runtime denials stop matching after configured-name mounting. Both can permit explicitly disabled tools under Full Access.

    Captured head CI: 1 successful check, 20 skipped, 8 running, 7 queued; legacy status has zero contexts. Frozen-pair merge CI is unavailable. Review used source tracing and isolated reviewer experiments; no project tests or application reproduction ran.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=2341754f0b96df7b -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 13:14 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -69,40 +76,40 @@ export async function buildDshCherryToolBridge(
       const clients: Client[] = []
       const tools: BridgeToolDescriptor[] = []
       const bindings = new Map<string, DshToolBinding>()
    +  const usedNames = new Set<string>()
    +  const ruleNames = new Map<string, string>()
     
       for (const [serverId, server] of Object.entries(servers)) {
         let client: Client | undefined
         try {
           client = await connectClient(server, `cherry-dsh-${serverId}`)
           const result = await client.listTools()
    -      const serverNames = new Set<string>()
    -      const serverTools = result.tools.map((tool) => ({
    -        descriptor: toBridgeDescriptor(server.name, tool),
    -        rawName: tool.name
    -      }))
    -      for (const { descriptor } of serverTools) {
    -        if (bindings.has(descriptor.name) || serverNames.has(descriptor.name)) {
    -          throw new DshCherryToolIdentityError(`Duplicate dsh Cherry tool name: ${descriptor.name}`)
    -        }
    -        serverNames.add(descriptor.name)
    -      }
           clients.push(client)
    -      for (const { descriptor, rawName } of serverTools) {
    -        tools.push(descriptor)
    -        bindings.set(descriptor.name, { client, rawName })
    +      for (const raw of result.tools) {
    +        // Two valid (server, tool) pairs can flatten to one wire name (`docs` + `search__all` vs
    +        // `docs__search` + `all`), and the first server to claim a name wins it. A stable hash
    +        // suffix keeps every tool callable — throwing here would fail the whole turn on a
    +        // configuration the name allocator accepts.
    +        let name = buildDshCherryToolName(server.name, raw.name)
    +        if (usedNames.has(name)) name = disambiguatedDshToolName(server.name, raw.name, usedNames)
    +        usedNames.add(name)
    +        ruleNames.set(`mcp__${server.name}__${raw.name}`, name)

    Fixed in 07a6a14427. The bridge rule map no longer keys denials by the ambiguous flattened string alone: it now also registers an exact <serverKey>\u0000<rawTool> pair identity, and translateMcpToolRulesToRuntimeNames preserves the split point of an id-keyed rule so a uuid-keyed denial resolves onto its own pair's allocated name even when a second pair flattens to the same rule string. For already-flattened name-form denials (which genuinely cannot say which pair they meant) the lookup now maps the string to every candidate — over-blocking instead of letting an explicitly disabled tool execute. Verified: new bridge test keeps both colliding identities resolvable (pair-exact + merged fail-closed), new translator test pins the id-keyed denial to its own pair, full dsh + claudeCode-adjacent suites 441 passed, tsc clean, oxlint/oxfmt clean on the touched files.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 13:14 UTC
    Code Review
    src/shared/ai/tools/mcpToolName.ts:1
    @@ -145,6 +145,44 @@ export type McpFunctionCallToolNameParts = {
       toolPart: string
     }
     
    +/**
    + * Saved agent-level denials written while MCP tools were keyed by server id (`mcp__<uuid>__tool`)
    + * no longer match runtime names derived from the configured server name. Rewrite each legacy rule
    + * whose server segment is a known id into the current server key; name-form rules (and rules naming
    + * unknown servers) pass through unchanged. Ids contain no underscores, so splitting on the first
    + * `__` is exact for legacy rules and never mis-splits a `__`-bearing server name.
    + */
    +export function translateLegacyMcpToolRules(
    +  rules: readonly string[] | null | undefined,
    +  serverNameById: ReadonlyMap<string, string> = new Map()
    +): string[] {
    +  return (rules ?? []).map((rule) => {
    +    if (!rule.startsWith('mcp__')) return rule
    +    const rest = rule.slice('mcp__'.length)
    +    const delimiterIndex = rest.indexOf('__')
    +    if (delimiterIndex <= 0) return rule
    +    const mapped = serverNameById.get(rest.slice(0, delimiterIndex))

    Fixed in 07a6a14427. The bridge now reconstructs the pre-name DSH runtime aliases from every known mounted-server id (the same buildDshCherryToolName(id, rawTool) construction the runtime used before configured-name registration, covering both the wire-safe mcp__<id>__<tool> form and the hashed lossy mcp__<camelized>__<camelized>_<sha256-12> form in your example) and maps each onto the currently allocated name, so a persisted hashed denial follows its server after it starts registering under the configured name. Verified: new bridge test asserts the hashed alias key resolves to the current identity for a uuid-mounted long tool name, full dsh + claudeCode-adjacent suites 441 passed, tsc clean, oxlint/oxfmt clean on the touched files.

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 13:29 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -125,6 +140,62 @@ export async function buildDshCherryToolBridge(
       }
     }
     
    +/**
    + * Collision identity for two (server, tool) pairs that flatten to the same wire name: the readable
    + * prefix stays, and a fixed-width sha256 head of the raw pair keeps the extra name deterministic
    + * (the same pair always resolves to the same identity) within the 63-char provider-safe cap.
    + */
    +function disambiguatedDshToolName(serverName: string, toolName: string, taken: ReadonlySet<string>): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  let name = `${base}_${createHash('sha256').update(`${serverName}\0${toolName}`).digest('hex').slice(0, 12)}`
    +  // The counter must reach the retained suffix: re-hashing with it produces a fresh candidate,
    +  // and the bound turns a pathological config into a thrown error instead of a frozen main
    +  // process (a synchronous loop here blocks Electron startup).
    +  for (let counter = 1; counter <= DSH_TOOL_NAME_DISAMBIGUATION_LIMIT; counter++) {
    +    if (!taken.has(name)) return name
    +    name = `${base}_${createHash('sha256').update(`${serverName}\0${toolName}\0${counter}`).digest('hex').slice(0, 12)}`
    +  }
    +  throw new Error(
    +    `No free dsh tool name for ${serverName}/${toolName} after ${DSH_TOOL_NAME_DISAMBIGUATION_LIMIT} candidates`
    +  )
    +}
    +
    +/**
    + * Index the registered identities for denial-rule translation. A flattened name-form string that
    + * two pairs share maps to every candidate (over-blocking beats letting an explicitly disabled
    + * tool execute); the `\0`-joined pair identity (never a valid `mcp__` string) stays exact for
    + * id-keyed rules; and each known mounted-server id rebuilds the name tools carried before
    + * configured-name registration so old denials follow their server.
    + */
    +function buildDshCherryRuleNameLookup(
    +  identities: ReadonlyArray<{ serverKey: string; rawTool: string; runtimeName: string }>,
    +  serverNameById: ReadonlyMap<string, string> = new Map()
    +): ReadonlyMap<string, readonly string[]> {
    +  const ruleNames = new Map<string, readonly string[]>()
    +  const addRule = (rule: string, runtimeName: string) => {
    +    const existing = ruleNames.get(rule)
    +    if (existing) {
    +      if (!existing.includes(runtimeName)) ruleNames.set(rule, [...existing, runtimeName])
    +    } else {
    +      ruleNames.set(rule, [runtimeName])
    +    }
    +  }
    +  const rawToolsByKey = new Map<string, Array<{ rawTool: string; runtimeName: string }>>()
    +  for (const { serverKey, rawTool, runtimeName } of identities) {
    +    addRule(`mcp__${serverKey}__${rawTool}`, runtimeName)

    Must fix: Preserve allocated runtime identities in this lookup as well as raw aliases. Mount UUID-backed A (Old server / run) before B (oldServer / run_4f7413c24ae4): A receives mcp__oldServer__run_4f7413c24ae4, while B receives a collision suffix. A's runtime string is indexed only as B's raw alias, so saving it in disabledTools replaces A's denial with B's allocated name. Startup and reconciliation propagate this replacement, and the exact-match DSH policy allows A under Full Access. Merge each allocated runtime identity into the fail-closed candidate map and add a regression test for this collision.

    inv_812e93ec164f5f6b#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 13:29 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -54,6 +54,68 @@ export interface AgentNotificationContext {
       allowAnyOwnedChannel: boolean
     }
     
    +/**
    + * Resolve the agent's mounted servers once: parse each `agent.mcps` entry (id or name), skip the
    + * browser builtin, and allocate the runtime record key. The SDK derives tool names
    + * (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from the record key, so a 36-char UUID
    + * key leaves ~21 chars for the tool name and truncates the rest into unreadable hashes
    + * (issue #21321) — register under the configured short name; fall back to the id when the name is
    + * unknown or taken (`mcp_server.name` is not unique). Single source shared by the record builder
    + * and legacy denial-rule translation, so a saved rule always translates to the exact key the
    + * server registers under.
    + */
    +function resolveMountedAgentMcpServers(
    +  agent: Pick<AgentEntity, 'mcps'>,
    +  mcpServerSnapshots?: McpServerSnapshotMap
    +): Array<{ mcpId: string; legacyServer: McpServerEntity; key: string }> {
    +  // Built-in entries are added first; a user server must never take their keys.
    +  const takenServerNames = new Set<string>(Object.values(CHERRY_MCP_SERVER))
    +  // Mounted ids are reserved before any name allocation so the id fallback below can never
    +  // collide with another mounted server's configured name (and vice versa): each server keeps
    +  // its own key even when names and ids cross-import each other (`mcp_server.name` is not unique).
    +  for (const mcpId of agent.mcps ?? []) takenServerNames.add(mcpId)
    +
    +  const resolved: Array<{ mcpId: string; legacyServer: McpServerEntity; key: string }> = []
    +  for (const mcpId of agent.mcps ?? []) {
    +    try {
    +      const serverSnapshot = mcpServerSnapshots?.get(mcpId)
    +      const legacyServer = mcpServerSnapshots ? serverSnapshot : mcpServerService.findByIdOrName(mcpId)
    +      if (
    +        legacyServer &&
    +        isInMemoryBuiltinMcpServer(legacyServer) &&
    +        legacyServer.name === BuiltinMcpServerNames.browser
    +      )
    +        continue
    +      if (mcpServerSnapshots && !serverSnapshot) {
    +        throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
    +      }
    +      if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId

    Must fix: Update the metadata catalog alongside this key allocation. Mount UUID-backed A and B, both named docs and exposing run: A registers under docs, B under its UUID, but claudeCode/mcpCatalog.ts:87–88 lets B overwrite metadata for mcp__docs__run. streamAdapter.ts:1789,1808–1811 consequently assigns B's server ID and description to A's calls and results, including persisted provenance. Execution still routes to A. Build authoritative metadata entries from the same allocated runtime keys and prevent compatibility aliases from overwriting them.

    inv_4bbaa63043d6c8a2#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 13:29 UTC
    Reviewer

    Two confirmed regressions require changes: DSH collision translation can remove an explicit tool denial, and Claude name collisions can assign another server’s identity to calls and persisted results. Head CI snapshot: 12 successful, 14 skipped, 5 in progress, no failures; legacy status had zero contexts. Frozen-pair merge CI was unavailable. Verification used source tracing and isolated naming experiments; no local project tests or application reproduction ran.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=20c5a423f33165eb -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 15:20 UTC
    Code Review
    src/main/ai/runtime/agentMcpServers.ts:1
    @@ -54,6 +54,68 @@ export interface AgentNotificationContext {
       allowAnyOwnedChannel: boolean
     }
     
    +/**
    + * Resolve the agent's mounted servers once: parse each `agent.mcps` entry (id or name), skip the
    + * browser builtin, and allocate the runtime record key. The SDK derives tool names
    + * (`mcp__<key>__<tool>`, 64-char cap) and routes tool calls from the record key, so a 36-char UUID
    + * key leaves ~21 chars for the tool name and truncates the rest into unreadable hashes
    + * (issue #21321) — register under the configured short name; fall back to the id when the name is
    + * unknown or taken (`mcp_server.name` is not unique). Single source shared by the record builder
    + * and legacy denial-rule translation, so a saved rule always translates to the exact key the
    + * server registers under.
    + */
    +function resolveMountedAgentMcpServers(
    +  agent: Pick<AgentEntity, 'mcps'>,
    +  mcpServerSnapshots?: McpServerSnapshotMap
    +): Array<{ mcpId: string; legacyServer: McpServerEntity; key: string }> {
    +  // Built-in entries are added first; a user server must never take their keys.
    +  const takenServerNames = new Set<string>(Object.values(CHERRY_MCP_SERVER))
    +  // Mounted ids are reserved before any name allocation so the id fallback below can never
    +  // collide with another mounted server's configured name (and vice versa): each server keeps
    +  // its own key even when names and ids cross-import each other (`mcp_server.name` is not unique).
    +  for (const mcpId of agent.mcps ?? []) takenServerNames.add(mcpId)
    +
    +  const resolved: Array<{ mcpId: string; legacyServer: McpServerEntity; key: string }> = []
    +  for (const mcpId of agent.mcps ?? []) {
    +    try {
    +      const serverSnapshot = mcpServerSnapshots?.get(mcpId)
    +      const legacyServer = mcpServerSnapshots ? serverSnapshot : mcpServerService.findByIdOrName(mcpId)
    +      if (
    +        legacyServer &&
    +        isInMemoryBuiltinMcpServer(legacyServer) &&
    +        legacyServer.name === BuiltinMcpServerNames.browser
    +      )
    +        continue
    +      if (mcpServerSnapshots && !serverSnapshot) {
    +        throw new Error(`MCP server not found in request snapshot: ${mcpId}`)
    +      }
    +      if (!legacyServer) throw new Error(`MCP server not found: ${mcpId}`)
    +      const serverName = legacyServer.name && !takenServerNames.has(legacyServer.name) ? legacyServer.name : mcpId

    Fixed in 454a6499c9: buildMcpToolMetadata now claims metadata first under the same allocated record keys the runtime registers (resolveMountedAgentMcpServers), so mcp__docs__run resolves to the server that actually registered that key, and compatibility aliases (uuid/name forms, catalog id) never overwrite a runtime-key entry. Regression test (mcpCatalog.test.ts) mounts two UUID-backed servers both named docs exposing run: red on the parent commit (B's metadata won mcp__docs__run), green here; uuid-form lookups for both servers are unchanged.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 15:20 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -125,6 +140,62 @@ export async function buildDshCherryToolBridge(
       }
     }
     
    +/**
    + * Collision identity for two (server, tool) pairs that flatten to the same wire name: the readable
    + * prefix stays, and a fixed-width sha256 head of the raw pair keeps the extra name deterministic
    + * (the same pair always resolves to the same identity) within the 63-char provider-safe cap.
    + */
    +function disambiguatedDshToolName(serverName: string, toolName: string, taken: ReadonlySet<string>): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  let name = `${base}_${createHash('sha256').update(`${serverName}\0${toolName}`).digest('hex').slice(0, 12)}`
    +  // The counter must reach the retained suffix: re-hashing with it produces a fresh candidate,
    +  // and the bound turns a pathological config into a thrown error instead of a frozen main
    +  // process (a synchronous loop here blocks Electron startup).
    +  for (let counter = 1; counter <= DSH_TOOL_NAME_DISAMBIGUATION_LIMIT; counter++) {
    +    if (!taken.has(name)) return name
    +    name = `${base}_${createHash('sha256').update(`${serverName}\0${toolName}\0${counter}`).digest('hex').slice(0, 12)}`
    +  }
    +  throw new Error(
    +    `No free dsh tool name for ${serverName}/${toolName} after ${DSH_TOOL_NAME_DISAMBIGUATION_LIMIT} candidates`
    +  )
    +}
    +
    +/**
    + * Index the registered identities for denial-rule translation. A flattened name-form string that
    + * two pairs share maps to every candidate (over-blocking beats letting an explicitly disabled
    + * tool execute); the `\0`-joined pair identity (never a valid `mcp__` string) stays exact for
    + * id-keyed rules; and each known mounted-server id rebuilds the name tools carried before
    + * configured-name registration so old denials follow their server.
    + */
    +function buildDshCherryRuleNameLookup(
    +  identities: ReadonlyArray<{ serverKey: string; rawTool: string; runtimeName: string }>,
    +  serverNameById: ReadonlyMap<string, string> = new Map()
    +): ReadonlyMap<string, readonly string[]> {
    +  const ruleNames = new Map<string, readonly string[]>()
    +  const addRule = (rule: string, runtimeName: string) => {
    +    const existing = ruleNames.get(rule)
    +    if (existing) {
    +      if (!existing.includes(runtimeName)) ruleNames.set(rule, [...existing, runtimeName])
    +    } else {
    +      ruleNames.set(rule, [runtimeName])
    +    }
    +  }
    +  const rawToolsByKey = new Map<string, Array<{ rawTool: string; runtimeName: string }>>()
    +  for (const { serverKey, rawTool, runtimeName } of identities) {
    +    addRule(`mcp__${serverKey}__${rawTool}`, runtimeName)

    Fixed in 454a6499c9: each registered runtime identity now claims its own name in the fail-closed candidate map, so a denial saved under A's runtime string (mcp__oldServer__run_4f7413c24ae4) translates to both candidates ([aRuntime, bRuntime]) instead of being rewritten onto B's disambiguated name alone — the exact-match policy keeps blocking A, with B's candidate merged fail-closed like every other ambiguous form. Regression test (DshCherryToolBridge.test.ts) mounts Old server/run before oldServer/run_4f7413c24ae4: red on the parent commit (translated to B's name only), green here.

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 15:46 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -69,40 +86,40 @@ export async function buildDshCherryToolBridge(
       const clients: Client[] = []
       const tools: BridgeToolDescriptor[] = []
       const bindings = new Map<string, DshToolBinding>()
    +  const usedNames = new Set<string>()
    +  const identities: Array<{ serverKey: string; rawTool: string; runtimeName: string }> = []
     
       for (const [serverId, server] of Object.entries(servers)) {
         let client: Client | undefined
         try {
           client = await connectClient(server, `cherry-dsh-${serverId}`)
           const result = await client.listTools()
    -      const serverNames = new Set<string>()
    -      const serverTools = result.tools.map((tool) => ({
    -        descriptor: toBridgeDescriptor(server.name, tool),
    -        rawName: tool.name
    -      }))
    -      for (const { descriptor } of serverTools) {
    -        if (bindings.has(descriptor.name) || serverNames.has(descriptor.name)) {
    -          throw new DshCherryToolIdentityError(`Duplicate dsh Cherry tool name: ${descriptor.name}`)
    -        }
    -        serverNames.add(descriptor.name)
    -      }
           clients.push(client)
    -      for (const { descriptor, rawName } of serverTools) {
    -        tools.push(descriptor)
    -        bindings.set(descriptor.name, { client, rawName })
    +      for (const raw of result.tools) {
    +        // Two valid (server, tool) pairs can flatten to one wire name (`docs` + `search__all` vs
    +        // `docs__search` + `all`), and the first server to claim a name wins it. A stable hash
    +        // suffix keeps every tool callable — throwing here would fail the whole turn on a
    +        // configuration the name allocator accepts.
    +        let name = buildDshCherryToolName(server.name, raw.name)
    +        if (usedNames.has(name)) name = disambiguatedDshToolName(server.name, raw.name, usedNames)

    Must fix: Preserve saved denials across collision reallocations. Mount docs/search__all before docs__search/all, then persist the second tool's allocated name, mcp__docs__search__all_353988fff1e9, in disabledTools through PATCH /agents/:agentId. After removing the first server and reconnecting, the remaining tool becomes mcp__docs__search__all. The rebuilt lookup omits its previous suffixed identity, so translation leaves the obsolete denial unchanged and the exact-match policy allows the tool under bypassPermissions. Resolve denials through stable server/tool identities, retain compatibility for saved collision names, and add a reconnect regression test.

    inv_89f0638bcccfdfc6#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 15:46 UTC
    Code Review
    src/main/ai/runtime/claudeCode/mcpCatalog.ts:1
    @@ -138,20 +147,36 @@ export async function buildMcpToolMetadata(
       const mcpIds = agent.mcps
       if (!mcpIds?.length) return undefined
     
    -  const metadataByName: Record<string, McpToolDisplayMetadata> = {}
       const mcpService = application.get('McpCatalogService')
    -
    -  for (const mcpId of mcpIds) {
    +  // Same allocation the record builder uses: the key a server registers under is the only
    +  // authority for which metadata a runtime tool name (`mcp__<key>__<tool>`) resolves to.
    +  const mounted = resolveMountedAgentMcpServers(agent).flatMap(({ mcpId, legacyServer, key }) => {
         try {
    -      const server = mcpServerService.findByIdOrName(mcpId)
    -      if (!server) continue
    -
    -      const tools = mcpService.listTools(server.id)
    -      for (const tool of tools) {
    -        addMcpToolMetadataAliases(metadataByName, server, tool)
    -      }
    +      return [{ server: legacyServer, key, tools: mcpService.listTools(legacyServer.id) }]
         } catch (error) {
           logger.warn('Failed to build MCP tool display metadata', { mcpId, error })
    +      return []
    +    }
    +  })
    +
    +  const metadataByName: Record<string, McpToolDisplayMetadata> = {}
    +  // Authoritative pass: the allocated runtime key claims its tool names before any alias.
    +  for (const { server, key, tools } of mounted) {
    +    for (const tool of tools) {
    +      const metadata: McpToolDisplayMetadata = {
    +        type: 'mcp',
    +        serverId: server.id,
    +        serverName: server.name,
    +        name: tool.name,
    +        description: tool.description
    +      }
    +      addMcpToolMetadataAlias(metadataByName, `mcp__${key}__${tool.name}`, metadata)
    +      addMcpToolMetadataAlias(metadataByName, `mcp__${key}__${toCamelCase(tool.name)}`, metadata)

    Must fix: Register every exact runtime tool name before adding camelized aliases. When a docs server lists search_docs before searchDocs, this line assigns the first tool's metadata to mcp__docs__searchDocs; first-wins insertion then rejects the second tool's exact entry. streamAdapter.ts uses that entry for the display name and description, so calls and persisted results for searchDocs receive search_docs metadata. Execution remains correctly routed, but the recorded metadata is incorrect. Move camelized aliases into a later pass and test this alias/exact-name collision.

    inv_7af8200c111553d7#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 15:46 UTC
    Reviewer

    Two confirmed regressions require changes: a saved DSH denial can stop blocking after a colliding server is removed, and Claude metadata aliases can capture another tool's exact identity.

    Frozen-head CI snapshot: 15 successful checks, 3 renderer shards in progress, 2 skipped. Legacy status has zero contexts; merge CI is unavailable for the frozen parent pair. Verification used source tracing and isolated verifier experiments; no project tests or live SDK/application sessions were run.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=5f593bd95e553737 -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 15:55 UTC
    Code Review
    src/main/ai/runtime/claudeCode/mcpCatalog.ts:1
    @@ -138,20 +147,36 @@ export async function buildMcpToolMetadata(
       const mcpIds = agent.mcps
       if (!mcpIds?.length) return undefined
     
    -  const metadataByName: Record<string, McpToolDisplayMetadata> = {}
       const mcpService = application.get('McpCatalogService')
    -
    -  for (const mcpId of mcpIds) {
    +  // Same allocation the record builder uses: the key a server registers under is the only
    +  // authority for which metadata a runtime tool name (`mcp__<key>__<tool>`) resolves to.
    +  const mounted = resolveMountedAgentMcpServers(agent).flatMap(({ mcpId, legacyServer, key }) => {
         try {
    -      const server = mcpServerService.findByIdOrName(mcpId)
    -      if (!server) continue
    -
    -      const tools = mcpService.listTools(server.id)
    -      for (const tool of tools) {
    -        addMcpToolMetadataAliases(metadataByName, server, tool)
    -      }
    +      return [{ server: legacyServer, key, tools: mcpService.listTools(legacyServer.id) }]
         } catch (error) {
           logger.warn('Failed to build MCP tool display metadata', { mcpId, error })
    +      return []
    +    }
    +  })
    +
    +  const metadataByName: Record<string, McpToolDisplayMetadata> = {}
    +  // Authoritative pass: the allocated runtime key claims its tool names before any alias.
    +  for (const { server, key, tools } of mounted) {
    +    for (const tool of tools) {
    +      const metadata: McpToolDisplayMetadata = {
    +        type: 'mcp',
    +        serverId: server.id,
    +        serverName: server.name,
    +        name: tool.name,
    +        description: tool.description
    +      }
    +      addMcpToolMetadataAlias(metadataByName, `mcp__${key}__${tool.name}`, metadata)
    +      addMcpToolMetadataAlias(metadataByName, `mcp__${key}__${toCamelCase(tool.name)}`, metadata)

    Fixed in fda31efb79: exact mcp__<key>__<tool> entries are now claimed for every tool before any camelized alias runs — camelized key-form aliases moved into the compatibility pass (first-claim-wins, never overwriting an exact entry). Regression test mounts one docs server listing search_docs before searchDocs: red on the parent commit (mcp__docs__searchDocs displayed search_docs metadata), green here.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 15:55 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -69,40 +86,40 @@ export async function buildDshCherryToolBridge(
       const clients: Client[] = []
       const tools: BridgeToolDescriptor[] = []
       const bindings = new Map<string, DshToolBinding>()
    +  const usedNames = new Set<string>()
    +  const identities: Array<{ serverKey: string; rawTool: string; runtimeName: string }> = []
     
       for (const [serverId, server] of Object.entries(servers)) {
         let client: Client | undefined
         try {
           client = await connectClient(server, `cherry-dsh-${serverId}`)
           const result = await client.listTools()
    -      const serverNames = new Set<string>()
    -      const serverTools = result.tools.map((tool) => ({
    -        descriptor: toBridgeDescriptor(server.name, tool),
    -        rawName: tool.name
    -      }))
    -      for (const { descriptor } of serverTools) {
    -        if (bindings.has(descriptor.name) || serverNames.has(descriptor.name)) {
    -          throw new DshCherryToolIdentityError(`Duplicate dsh Cherry tool name: ${descriptor.name}`)
    -        }
    -        serverNames.add(descriptor.name)
    -      }
           clients.push(client)
    -      for (const { descriptor, rawName } of serverTools) {
    -        tools.push(descriptor)
    -        bindings.set(descriptor.name, { client, rawName })
    +      for (const raw of result.tools) {
    +        // Two valid (server, tool) pairs can flatten to one wire name (`docs` + `search__all` vs
    +        // `docs__search` + `all`), and the first server to claim a name wins it. A stable hash
    +        // suffix keeps every tool callable — throwing here would fail the whole turn on a
    +        // configuration the name allocator accepts.
    +        let name = buildDshCherryToolName(server.name, raw.name)
    +        if (usedNames.has(name)) name = disambiguatedDshToolName(server.name, raw.name, usedNames)

    Fixed in fda31efb79: each identity now also indexes its reconstructible historical collision name — pairCollisionName(serverKey, rawTool) is the same deterministic first candidate disambiguatedDshToolName allocates, so a denial saved under mcp__docs__search__all_353988fff1e9 follows the pair onto the plain mcp__docs__search__all after the colliding neighbor is unmounted. Regression test builds the bridge with both pairs, rebuilds it with only the survivor, and asserts the saved denial translates to the survivor's current name: red on the parent commit, green here.

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 16:14 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -125,6 +144,80 @@ export async function buildDshCherryToolBridge(
       }
     }
     
    +/**
    + * Collision identity for two (server, tool) pairs that flatten to the same wire name: the readable
    + * prefix stays, and a fixed-width sha256 head of the raw pair keeps the extra name deterministic
    + * (the same pair always resolves to the same identity) within the 63-char provider-safe cap.
    + */
    +function pairCollisionName(serverName: string, toolName: string): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  return `${base}_${createHash('sha256').update(`${serverName}\0${toolName}`).digest('hex').slice(0, 12)}`
    +}
    +
    +function disambiguatedDshToolName(serverName: string, toolName: string, taken: ReadonlySet<string>): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  let name = pairCollisionName(serverName, toolName)
    +  // The counter must reach the retained suffix: re-hashing with it produces a fresh candidate,
    +  // and the bound turns a pathological config into a thrown error instead of a frozen main
    +  // process (a synchronous loop here blocks Electron startup).
    +  for (let counter = 1; counter <= DSH_TOOL_NAME_DISAMBIGUATION_LIMIT; counter++) {
    +    if (!taken.has(name)) return name
    +    name = `${base}_${createHash('sha256').update(`${serverName}\0${toolName}\0${counter}`).digest('hex').slice(0, 12)}`
    +  }
    +  throw new Error(
    +    `No free dsh tool name for ${serverName}/${toolName} after ${DSH_TOOL_NAME_DISAMBIGUATION_LIMIT} candidates`
    +  )
    +}
    +
    +/**
    + * Index the registered identities for denial-rule translation. A flattened name-form string that
    + * two pairs share maps to every candidate (over-blocking beats letting an explicitly disabled
    + * tool execute); the `\0`-joined pair identity (never a valid `mcp__` string) stays exact for
    + * id-keyed rules; and each known mounted-server id rebuilds the name tools carried before
    + * configured-name registration so old denials follow their server.
    + */
    +function buildDshCherryRuleNameLookup(
    +  identities: ReadonlyArray<{ serverKey: string; rawTool: string; runtimeName: string }>,
    +  serverNameById: ReadonlyMap<string, string> = new Map()
    +): ReadonlyMap<string, readonly string[]> {
    +  const ruleNames = new Map<string, readonly string[]>()
    +  const addRule = (rule: string, runtimeName: string) => {
    +    const existing = ruleNames.get(rule)
    +    if (existing) {
    +      if (!existing.includes(runtimeName)) ruleNames.set(rule, [...existing, runtimeName])
    +    } else {
    +      ruleNames.set(rule, [runtimeName])
    +    }
    +  }
    +  const rawToolsByKey = new Map<string, Array<{ rawTool: string; runtimeName: string }>>()
    +  for (const { serverKey, rawTool, runtimeName } of identities) {
    +    addRule(`mcp__${serverKey}__${rawTool}`, runtimeName)
    +    addRule(`${serverKey}\u0000${rawTool}`, runtimeName)
    +    // The registered runtime name itself is a saved denial string: a user disabling a tool at
    +    // runtime writes exactly this string. Another pair's name-form rule can flatten onto it
    +    // (B `oldServer`/`run_4f7413c24ae4` vs A `Old server`/`run`), so the runtime identity must
    +    // claim its own name too — otherwise translation rewrites A's denial onto B's allocation
    +    // and the exact-match policy lets the explicitly disabled tool execute.
    +    addRule(runtimeName, runtimeName)
    +    // A denial can also be saved under this pair's collision-allocated name from an earlier
    +    // topology whose colliding neighbor has since been unmounted: the survivor re-registers
    +    // under the plain name and the saved string matches nothing. The disambiguator is a
    +    // deterministic hash of the pair, so the historical name is reconstructible and follows
    +    // the pair to its current identity.
    +    const historical = pairCollisionName(serverKey, rawTool)

    Must fix: Preserve counter-allocated denial identities across reconnects too. Mount docs exposing search__all and search__all_353988fff1e9, then docs__search exposing all: the latter receives mcp__docs__search__all_4e11dd82a154. Save that name in disabledTools, remove docs, and reconnect. The survivor gets the plain name, but this lookup reconstructs only the first pair-hash alias (_353988fff1e9), leaving the saved denial unmatched. DSH checks disabled tools by exact name, so the explicitly disabled tool can execute under bypassPermissions. No cryptographic collision is needed. Persist stable server-ID/raw-tool identity or retain compatibility for all allocated denial identities, and add a counter-allocation reconnect regression test.

    inv_72af0d1a27f73cb8#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on code on Oct 10, 2026 16:14 UTC
    Code Review
    src/main/ai/runtime/claudeCode/mcpCatalog.ts:1
    @@ -138,20 +151,34 @@ export async function buildMcpToolMetadata(
       const mcpIds = agent.mcps
       if (!mcpIds?.length) return undefined
     
    -  const metadataByName: Record<string, McpToolDisplayMetadata> = {}
       const mcpService = application.get('McpCatalogService')
    -
    -  for (const mcpId of mcpIds) {
    +  // Same allocation the record builder uses: the key a server registers under is the only
    +  // authority for which metadata a runtime tool name (`mcp__<key>__<tool>`) resolves to.
    +  const mounted = resolveMountedAgentMcpServers(agent).flatMap(({ mcpId, legacyServer, key }) => {

    Must fix: Refresh metadata using the running connection’s captured server allocation. Mount UUID-backed A then B, both named docs and exposing run; remove A from the agent during an active turn, then refresh B’s changed tool cache. This function reallocates docs to B, and ClaudeCodeSessionStateService replaces the adapter’s metadata in place. The active SDK connection remains bound to A until the deferred rebuild, so mcp__docs__run executes against A but receives B’s server ID and description in call/result metadata. Keep the allocation fixed until connection replacement and cover this mount-change/cache-refresh sequence.

    inv_5ae37a72707f1d84#f1

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 16:14 UTC
    Reviewer

    Two confirmed regressions require changes: counter-allocated DSH denials can stop blocking after reconnect, and live Claude metadata refresh can attribute calls/results to the wrong MCP server while connection rebuilding is deferred.

    Frozen head: fda31efb792f2811a2881387d94f464253abd0d6. CI snapshot: 5 successful, 12 in-progress, 14 skipped Check Runs; no legacy status contexts. Frozen-pair synthetic-merge CI was unavailable because its parents differed. Review used source/baseline inspection and an isolated allocation experiment; no project tests or end-to-end SDK execution ran.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=397b9afdf34be896 -->

    ggbdpq ggbdpq commented on code on Oct 10, 2026 17:07 UTC
    Code Review
    src/main/ai/runtime/claudeCode/mcpCatalog.ts:1
    @@ -138,20 +151,34 @@ export async function buildMcpToolMetadata(
       const mcpIds = agent.mcps
       if (!mcpIds?.length) return undefined
     
    -  const metadataByName: Record<string, McpToolDisplayMetadata> = {}
       const mcpService = application.get('McpCatalogService')
    -
    -  for (const mcpId of mcpIds) {
    +  // Same allocation the record builder uses: the key a server registers under is the only
    +  // authority for which metadata a runtime tool name (`mcp__<key>__<tool>`) resolves to.
    +  const mounted = resolveMountedAgentMcpServers(agent).flatMap(({ mcpId, legacyServer, key }) => {

    Fixed in 9ae2fa6946: the build-time server allocation is captured once (resolveAgentMcpServerKeys) and shared by legacy denial translation, metadata (initial build, warm reconciliation, and the live catalog refresh — the state service now stores it and passes it to every refresh), and the catalog sync registration. Metadata is attributed under the running connection's frozen allocation until a rebuild replaces the connection, so removing A mid-turn no longer hands docs to B. Regression test builds metadata for a frozen {id-a: docs, id-b: id-b} allocation while the agent only mounts B: red on the parent commit (mcp__docs__run re-attributed to B), green here.

    ggbdpq ggbdpq commented on code on Oct 10, 2026 17:07 UTC
    Code Review
    src/main/ai/runtime/dsh/DshCherryToolBridge.ts:1
    @@ -125,6 +144,80 @@ export async function buildDshCherryToolBridge(
       }
     }
     
    +/**
    + * Collision identity for two (server, tool) pairs that flatten to the same wire name: the readable
    + * prefix stays, and a fixed-width sha256 head of the raw pair keeps the extra name deterministic
    + * (the same pair always resolves to the same identity) within the 63-char provider-safe cap.
    + */
    +function pairCollisionName(serverName: string, toolName: string): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  return `${base}_${createHash('sha256').update(`${serverName}\0${toolName}`).digest('hex').slice(0, 12)}`
    +}
    +
    +function disambiguatedDshToolName(serverName: string, toolName: string, taken: ReadonlySet<string>): string {
    +  const base = buildDshCherryToolName(serverName, toolName).slice(0, 50)
    +  let name = pairCollisionName(serverName, toolName)
    +  // The counter must reach the retained suffix: re-hashing with it produces a fresh candidate,
    +  // and the bound turns a pathological config into a thrown error instead of a frozen main
    +  // process (a synchronous loop here blocks Electron startup).
    +  for (let counter = 1; counter <= DSH_TOOL_NAME_DISAMBIGUATION_LIMIT; counter++) {
    +    if (!taken.has(name)) return name
    +    name = `${base}_${createHash('sha256').update(`${serverName}\0${toolName}\0${counter}`).digest('hex').slice(0, 12)}`
    +  }
    +  throw new Error(
    +    `No free dsh tool name for ${serverName}/${toolName} after ${DSH_TOOL_NAME_DISAMBIGUATION_LIMIT} candidates`
    +  )
    +}
    +
    +/**
    + * Index the registered identities for denial-rule translation. A flattened name-form string that
    + * two pairs share maps to every candidate (over-blocking beats letting an explicitly disabled
    + * tool execute); the `\0`-joined pair identity (never a valid `mcp__` string) stays exact for
    + * id-keyed rules; and each known mounted-server id rebuilds the name tools carried before
    + * configured-name registration so old denials follow their server.
    + */
    +function buildDshCherryRuleNameLookup(
    +  identities: ReadonlyArray<{ serverKey: string; rawTool: string; runtimeName: string }>,
    +  serverNameById: ReadonlyMap<string, string> = new Map()
    +): ReadonlyMap<string, readonly string[]> {
    +  const ruleNames = new Map<string, readonly string[]>()
    +  const addRule = (rule: string, runtimeName: string) => {
    +    const existing = ruleNames.get(rule)
    +    if (existing) {
    +      if (!existing.includes(runtimeName)) ruleNames.set(rule, [...existing, runtimeName])
    +    } else {
    +      ruleNames.set(rule, [runtimeName])
    +    }
    +  }
    +  const rawToolsByKey = new Map<string, Array<{ rawTool: string; runtimeName: string }>>()
    +  for (const { serverKey, rawTool, runtimeName } of identities) {
    +    addRule(`mcp__${serverKey}__${rawTool}`, runtimeName)
    +    addRule(`${serverKey}\u0000${rawTool}`, runtimeName)
    +    // The registered runtime name itself is a saved denial string: a user disabling a tool at
    +    // runtime writes exactly this string. Another pair's name-form rule can flatten onto it
    +    // (B `oldServer`/`run_4f7413c24ae4` vs A `Old server`/`run`), so the runtime identity must
    +    // claim its own name too — otherwise translation rewrites A's denial onto B's allocation
    +    // and the exact-match policy lets the explicitly disabled tool execute.
    +    addRule(runtimeName, runtimeName)
    +    // A denial can also be saved under this pair's collision-allocated name from an earlier
    +    // topology whose colliding neighbor has since been unmounted: the survivor re-registers
    +    // under the plain name and the saved string matches nothing. The disambiguator is a
    +    // deterministic hash of the pair, so the historical name is reconstructible and follows
    +    // the pair to its current identity.
    +    const historical = pairCollisionName(serverKey, rawTool)

    Fixed in 9ae2fa6946: when a rule has no exact entry, translation now falls back to the stripped plain name (<name>_<12-hex disambiguator> → <name>), resolving saved denials under any counter depth — the stripped name maps through the fail-closed candidate map like every other ambiguous form. Regression test mounts docs/[search__all, search__all_353988fff1e9] + docs__search/all (counter-allocated third name), saves it, rebuilds with only the survivor, and asserts the denial translates to the survivor's plain name: red on the parent commit, green here.

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 17:24 UTC
    Reviewer

    One blocking technical defect: persisted DSH counter-allocated tool denials can lose their target after reconnect, allowing an explicitly disabled tool to execute under bypassPermissions. Exact-name capture and truncated-prefix recovery failures share the same missing historical-alias handling.

    Frozen-head CI snapshot: 10 successful, 6 in progress, 14 skipped Check Runs; no recorded failures. Legacy status has zero contexts. Matching synthetic-merge CI is unavailable. Verification used source inspection and isolated function evaluations; no project tests or live SDK/MCP sessions ran.

    Cherry Review · Blocked

    1 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=2729a16490b2aed9 -->

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 22:45 UTC
    Reviewer

    One confirmed blocking regression: DSH denial translation can discard a saved tool’s historical alias after a catalog change and reconnect, allowing the explicitly disabled tool under bypassPermissions.

    Frozen head: 875584f6dc195534869ca89b08bb5f7c9e15368c. CI snapshot: 15 successful Check Runs, 8 skipped, and 2 in progress (renderer 1/5 and macOS). Legacy status has zero contexts; matching merge CI is unavailable. Verification used source inspection and isolated function evaluations, not project tests or full runtime execution. A separate Claude truncation candidate remains unconfirmed and is excluded from findings.

    Cherry Review · Blocked

    1 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=cf476445bae439d6 -->

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 10, 2026 23:12 UTC
    Reviewer

    Changes requested: saved MCP denials can be rewritten away from the disabled tool, allowing execution under DSH bypassPermissions; distinct Claude server/tool pairs can also collapse into one metadata identity and lose correct attribution.

    Frozen head: cc12640788c040241075db3b282d03c5d85c4d10. CI snapshot: 14 successful, 8 skipped and 4 in-progress Check Runs; no recorded failures. Legacy status had zero contexts. Matching frozen-pair merge CI was unavailable.

    Review used source tracing, baseline comparison and targeted verification. No project tests ran; full application/SDK execution and CI logs were unavailable. No wrong-server SDK dispatch is alleged.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=201fa3f4fb64557d -->

    cherry-ai-bot[bot] cherry-ai-bot[bot] commented on Oct 11, 2026 01:48 UTC
    Reviewer

    Two technical regressions require changes: DSH denial translation can allow an explicitly disabled tool, and ambiguous Claude tool names lose server attribution. The dispatch behavior of the live Claude SDK is not established.

    Frozen-head CI: 13 successful, 14 skipped, two failed checks (basic-checks, repository-checks), one queued, and two running. Legacy status has zero contexts; matching merge CI and failure logs were unavailable. Review used source inspection and isolated function evaluations; no project tests or live SDK sessions ran.

    Cherry Review · Blocked

    2 blocking
    See inline comments for individual findings.

    <!-- cherry-review:run=ec3c402173f751bc -->

    ggbdpq ggbdpq commented on Oct 13, 2026 12:27 UTC
    Author

    All four round-13 findings are addressed in 3cb59abc61:

  • Displaced siblings — the migration now diffs the complete old/new allocations and rewrites every mounted server whose record key changed, so a sibling bumped onto its id by the renamed server's new claim keeps its denials.

  • Hashed denial identities — hashed entries are rewritten onto the new allocation's stripped base (raw key when wire-safe, camelized otherwise, truncated to 50 with the tail re-attached) instead of carrying the old fragment and hash past a longer prefix; the bridge lookup now also indexes the camelized base of every live pair so a migrated lossy denial resolves after a lossy-to-safe rename (Old server/get_time → docs/get_time).

  • Explicit disabledTools wins — stored server rules migrate only when the PATCH omits the field; submitted lists (including an explicit empty one) are persisted verbatim, while agent-mounted rules still follow the rename.

  • Non-blocking — agent disabledTools writes go through a transaction-aware AgentService.updateDisabledToolsTx and onAgentUpdated fires after commit.
  • Local validation: vitest suites for mcpToolName, McpServerService, DshCherryToolBridge and AgentService (416 tests) green, tsc --noEmit clean, oxlint clean, i18n checks passing.

    Reviewers
    Assignees
    ggbdpq ggbdpq
    Labels
    risk: low confidence: 82.2% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 96% (HIGH) · Higher = larger blast radius
    96%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.2% · Lower = rushed or shallow review
    82.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.1% · Safe to merge
    17.1%