Repository navigation
fix(gateway): claude-cli session tools fail after the turn that started the MCP loopback ends - #165432
Conversation
…rn's context The loopback listener starts lazily inside the first claude-cli turn and Node serves every later request in that listen-time async context, so requests inherited the starting turn's stores (transcript read fence, operator authority). Start the listener in a module-load snapshot and carry only the starter's Gateway resolver.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs changes before merge. Reviewed October 6, 2026, 9:31 PM ET / October 7, 2026, 01:31 UTC (Revision 6). ClawSweeper reviewWhat this changesThe PR isolates the shared CLI tool listener from its starting turn while preserving Gateway resources and restoring each calling run’s permissions and liveness checks. Merge readiness⛔ Needs changes before merge - 1 item remains Keep open: current main still has the request-scope and transcript-context leak, and the merged listener fix addresses a different lifetime. No blocking correctness defect was found in the pinned patch. Priority: P1 Review scores
Verification
How this fits togetherCLI-backed agents call OpenClaw tools through a shared local MCP HTTP listener. The listener resolves each run’s grant and dispatches tools into the Gateway, where permissions and current caller authority govern the action. flowchart TD
A[CLI agent turn] --> B[Host-owned run grant]
B --> C[Shared local MCP listener]
D[Gateway resource lifetime] --> C
C --> E[Restore calling run scope]
E --> F[Check permissions and live authority]
F --> G[Tool result or rejection]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +85, Tests +253, Docs +3. Total +341 across 11 files. View PR surface stats
Review metricsNone. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Use the shared detached-context and Gateway resource owners while keeping every tool call bound to its own live run authority. Do we have a high-confidence way to reproduce the issue? Yes: current-main startup retains the first request’s scope, and supplied production-file negative controls reproduce both the admin ceiling and stale transcript store. This read-only review did not execute target code. Is this the best way to solve the issue? Yes: the patch reuses existing lifecycle owners and restores per-run authority without adding configuration, protocol, or persisted-state changes. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 63938d89f149. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
chessing234
left a comment
There was a problem hiding this comment.
Reviewed commit bd874809fb55b650ea7efca17c7a90ac7e49bfae.
Inspected MCP listener context capture and startup/shutdown import ordering. No actionable correctness issue found.
Validation: static source review only; runtime tests were not run. This review makes no assertion that CI or platform tests pass.
Independent confirmation of this bug on 2026.9.5 (macOS arm64, Node 24.21.0, claude-cli runtime with a reusable live CLI session), plus one extra symptom path. Symptom in production. Six
Turns started by real inbound user messages kept working, because they carry their own receipt. Minimal repro of the leak (Node 24), matching your new test: import { AsyncLocalStorage } from "node:async_hooks";
import { createServer, request } from "node:http";
const fence = new AsyncLocalStorage(), rootWork = new AsyncLocalStorage();
let server;
await fence.run({ entryId: "stale" }, () => rootWork.run({}, () => rootWork.exit(() => new Promise(r => {
server = createServer((req, res) => res.end(JSON.stringify({ fence: fence.getStore() ?? null })));
server.listen(0, r);
}))));
request({ port: server.address().port }, res => res.on("data", d => { console.log(String(d)); server.close(); })).end();
// {"fence":{"entryId":"stale"}}One caveat on the module-load snapshot. It is only clean if Hardening suggestion (separate from this PR): make |
The listener no longer inherits its starter's scope, so each CLI grant now carries the Gateway request scope it was minted in. Bridge tool calls re-enter that scope, as in-process runtimes do, so a write-only restart-recovery run stays capped and a run whose client authority closed is still refused.
…its starting turn Node serves each loopback request in the listener's listen-time async context. Exiting stores one by one (caller identity, request scope, operator authority) still left the starting turn's transcript read fence and other turn-local stores on every later bridge call. Start the listener in a load-time AsyncLocalStorage snapshot, as runInMcpManagerContext does, keeping only the starter's Gateway resolver; each grant still re-enters its own run's request scope. The authority-chain regression test is adapted from Grynn's patch on openclaw#157144.
@clawsweeper re-review Updated head Evidence in the updated PR body: a fresh disposable Gateway built from the reviewed tree lets owner admin calls and cross-session history reads succeed; a write-only restart-recovery run that starts the listener receives |
|
🦞👀 Re-review progress:
|
Merge current main and reuse its detached async context owner instead of adding a second process-root snapshot. Keep each MCP grant bound to the originating request scope so later turns do not inherit the listener creator permission ceiling, liveness, or transcript fence. Preserve cold-entry and real HTTP authority regressions while removing duplicate coverage and host-only projection boilerplate.
Use the existing GatewayConnectionWork owner to retain spawn-broker and database-reader lifetimes while the shared MCP listener sheds creator turn context. Extend the HTTP regression to require the retained readers. Route the two MCP suites that use host-only SQLite through the existing database-worker fork lane; their CI thread-pool failures also affected direct dispatch.
|
Merged via squash.
|
What Problem This Solves
Fixes: CLI-backed agents lose admin or session tools after the turn that first starts the shared MCP bridge ends. The listener can retain that starter's permission ceiling, caller liveness, and transcript read fence.
Fixes #157126.
User Impact
Later CLI turns keep their own permissions and working session tools regardless of which turn started the listener. Write-only and revoked callers remain rejected. The listener also retains the Gateway's process broker and database-reader lifecycle. No new configuration, protocol, schema, or migration is required.
Why This Change Was Made
The earlier operator-authority fix in #165428 does not clear the other turn-local stores. Start the listener through the existing detached async-context owner, retain the Gateway resolver, and restore each grant's host-owned request scope for dispatch. Use the existing
GatewayConnectionWorkowner to retain the Gateway's spawn broker and read-only worker scope without retaining creator-turn authority.The previous revision incorrectly used a plain
AsyncWorkScope, dropping those host resources. The new HTTP regression requires the reader scope to survive while both the transcript fence and unrelated turn-local store disappear.The previous exact-head CI run also exposed a separate routing defect:
mcp-http.test.tsandmcp-http.session-controls.test.tsreached host-only SQLite from Vitest worker threads. The direct-dispatch cases failed too, before using the listener. Both files now use the existing parallel database-worker fork lane, like their MCP storage siblings; no new serial configuration or worker-count pin was added.Evidence
Verified head:
62dd7172822ec72dac19e57a71be362f34c7099a.Local static checks passed: scoped oxfmt, oxlint from a clean trusted-main worktree, and
git diff --check. Fresh independent Codex autoreview returnedscoped-cleanthrough P2 on the exact candidate tree before commit.Fresh untrusted AWS proof: lease
cbx_c81e884c7cc4, runrun_570d6c85fc3ce51a891d54556d684279; lease released after testing. The trusted-main bootstrap verified the pushed full SHA and no-role IMDS boundary. Public networking, no Tailscale, no credential hydration, isolated HOME.Result: core typecheck and 205 tests / 22 files passed, including all 19 MCP HTTP files and both previously failing files. Combined wall time 259.82 s; test orchestration 243.12 s. The native runner placed both database-dependent files in
gateway-database-workers, where all collector and direct-dispatch/HTTP session-control cases passed.Two production-only negative controls ran on the same lease, leaving regressions unchanged:
Previous-head control: 1 expected failure, exit 1, 31.55 s wall. The HTTP callback returned
[undefined, undefined, undefined]instead of[undefined, undefined, readerContext]: turn stores were clear, but the Gateway reader was lost.Main control: 2 expected failures, exit 1, 31.65 s wall. The callback retained the first-turn receipt and
first-turnmarker, and the owner-call assertion failed with:Exact-head CI: run 37556999602 passed, elapsed 449 s. The previous failed run 37554842902 exposed the missing host-main-thread test routing: its direct-dispatch stack reached
openSharedStateSqliteWorkerStoreand the!isMainThreadguard. That failure is separate from the resource-context regression, which the new negative control proves independently.Test cost: grouped single-worker shards took 19.13 s (unit), 156.77 s (Gateway), and 39.36 s (infrastructure), plus preparation/orchestration. Reported test-body time: async-scope 1.148 s; MCP HTTP 10.347 s; session-controls 31.287 s. These are grouped measurements, not independent per-file command wall times. The existing ten session-control cases exercise real SQLite writes and final-effect revocation across direct and HTTP boundaries; replacing that boundary with mocks would lose the contract being checked. No new process boots, polling, or sleep-based tests were added. Full build and live Claude inference were not run in this pass.
LOC versus main merge base: production +57/-61 (net -4); tests/support +344/-4; test routing +2/-0; docs +3/-0. The cold-import probe is Vitest-only support. Exact numstat:
ClawSweeper's earlier P1 remains addressed by per-grant permission ceilings and live caller checks. The latest reviewed findings were empty; the human cold-import concern remains covered by both entrypoint tests.
Original fix by @Oldrich333; incorporated request-scope work by @Leit-motif retains its original commits. Maintainer cleanup by Peter Steinberger reuses the existing context/resource owners, simplifies host-only projections, and removes duplicate coverage while preserving both cold-import tests and the installation-replacement fixture.