Repository navigation
fix(mcp): keep metadata and cleanup from eagerly loading runtimes - #133028
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 3:04 AM ET / 07:04 UTC. ClawSweeper reviewWhat this changesThe PR makes MCP runtime construction and OAuth profile resolution demand-loaded, reroutes metadata and teardown callers through the manager API, and adds lifecycle and import-boundary coverage. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness✅ Ready for maintainer review No introduced correctness or security defect was found. Current main still has the import-time factory binding this PR removes, so the change remains necessary; the active MEMBER-authored PR also carries the protected Priority: P2 Review scores
Verification
How this fits togetherMCP configuration feeds the session runtime manager, which creates transport clients only when a session needs discovery or tool execution. Gateway and CLI metadata/cleanup paths can inspect or retire sessions without activating those transport dependencies. flowchart LR
A[MCP configuration] --> B[Session runtime manager]
C[Gateway and CLI metadata] --> B
B --> D{Runtime needed?}
D -->|Yes| E[Lazy transport and auth loading]
E --> F[MCP discovery and tool calls]
D -->|No| G[Metadata and cleanup]
G --> H[Retired session state]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +604, Tests +462, Other +2. Total +1068 across 29 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep a single manager-owned lazy runtime boundary, with pending creation retaining ownership until its result cannot be published after teardown. Do we have a high-confidence way to reproduce the issue? Yes in source: current main's manager throws when its factory has not been bound, while the added tests directly exercise manager-first construction and teardown races. Is this the best way to solve the issue? Yes: moving construction behind the manager’s single lazy factory preserves the existing auth and transport owners while allowing metadata and cleanup callers to remain runtime-free. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 4f92b28df82a. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
af0f09e to
ae83dd2
Compare
|
Merged and verified: e620c4f556a45, via the native workflow. The completion receipt binds the actual squash to reviewed head 8ab596daab8e. Exact-head CI 33297440085 passed, attempt 1. Native cleanup completed without a GitHub-rule bypass. The MCP repair remains net -46 production/build LOC, preserving canonical credential refresh, requester/generation isolation, and App lease ownership. Fresh auth/lifecycle proof, functional App conformance, native build/live CLI, and configured P0-only autoreview passed. The PR Evidence section retains exact commands, source identities, earlier failed attempts, historical package proof and its limits. Final combined-main verification passed 159 tests across seven files at With that exact caller repair, the fresh composed build, compiled MCP metadata/profile-policy/App-preview smoke, and isolated public Context7 CLI flow all passed. The compiled smoke kept coding/messaging tools, excluded minimal/denied tools, and preserved the same filtering into SDK custom tools. It used local built dist with isolated state, not a new Docker/npm installation. No timeout increase, weakened assertion, obsolete compatibility export, credential fallback, or operator-state change was used. |
Keep profile credential resolution behind the existing bearer-demand boundary. Use the lifecycle manager without import-time factory binding, and fence late creation and disposal to their exact pending owners. Preserve refresh, requester scopes, and App leases; migrate internal, UI, and packaged harness callers to the canonical manager API. Keep the deferred core modules on stable build paths for live updates. Add real-owner auth, import, and child/lease regression coverage, and repair OAuth test readiness and database cleanup without larger timeouts.
Let the SDK own transport callbacks and response correlation in the real profile-refresh fixture. Cover initialization and ping responses while keeping optional SSE probes separate from RPC POST ordering. Fix the hosted lint-suppression gate without expanding its allowlist, changing process deadlines, or adding a production test seam.
f47a23e to
8ab596d
Compare
|
Merged via squash.
|
…enclaw#133028) * fix(mcp): defer auth loading and own lazy runtime creation Keep profile credential resolution behind the existing bearer-demand boundary. Use the lifecycle manager without import-time factory binding, and fence late creation and disposal to their exact pending owners. Preserve refresh, requester scopes, and App leases; migrate internal, UI, and packaged harness callers to the canonical manager API. Keep the deferred core modules on stable build paths for live updates. Add real-owner auth, import, and child/lease regression coverage, and repair OAuth test readiness and database cleanup without larger timeouts. * test(mcp): exercise profile refresh through the SDK client Let the SDK own transport callbacks and response correlation in the real profile-refresh fixture. Cover initialization and ping responses while keeping optional SSE probes separate from RPC POST ordering. Fix the hosted lint-suppression gate without expanding its allowlist, changing process deadlines, or adding a production test seam.
Related: #132932 — independently owned tool-metadata extraction; this PR does not duplicate it.
What Problem This Solves
Resolves a problem where MCP metadata and cleanup operations initialized runtime dependencies they did not need, while creating a session through the lifecycle manager depended on another module having bound its factory first. Genuinely lazy creation also needs teardown to own pending work so a late result cannot resurrect a disposed runtime or clear its successor.
This repairs MCP-owned import paths. It does not claim every CLI path is loader-free, equate module loading with plugin activation, or attribute historical MCP deadline failures to import timing.
Why This Change Was Made
Profile resolution loads at the existing asynchronous bearer-demand boundary and still uses canonical profile stores, external overlays, OAuth refresh, and raw access tokens on every use. Lifecycle consumers use the manager API; the manager loads its real factory on demand instead of depending on an import-time setter. Exact pending-promise ownership fences publication and cleanup, preserves requester serialization and aliases, and retains required retirement across creation and reuse.
App view deletion still releases its lease before deferred retirement. Internal, UI-conformance, and packaged-test callers use the canonical manager API. Factory/auth modules use the existing stable build-entry mechanism for deferred imports during live dist replacement. No compatibility reexports or alternate stores were added.
Connected test repairs keep the real boundaries intact: OAuth CLI login is driven from its emitted authorization URL and joined before cleanup; auth fixtures close acquired database owners in the right order and use the SDK Client for initialization/ping response correlation. The temporary quota fixture repair is no longer in this diff: current main already supplies its provider-tagged history and improved selection/response handling, so the duplicate ten-line commit was dropped during conflict resolution.
User Impact
MCP metadata inspection and empty cleanup no longer require the transport factory or profile-auth implementation first. Discovery, tool execution, refresh, requester isolation, and App lease retirement continue through their existing owners. Gateway action/approval bodies, configuration, dependencies, schema, persistence semantics, and permission policy are unchanged by this PR.
Production/build LOC: +172/-218, net -46. Tests/test support: +1198/-84, net +1114. Twenty-nine files; test-only support is counted separately from production.
Evidence
Current candidate:
8ab596daab8eedffb5b05c6f0a50f2eee7893d08, treef69808937d4223349ed4627e334558d8d0d3391d, rebased onto6425f8f16a27d1f941cc3c99d964c330e8e2e53a.https://mcp.context7.com/mcp, returning two server tools and no diagnostics. Build commit8ab596daab8eedffb5b05c6f0a50f2eee7893d08was checked explicitly. Every command retained its 30-second guard; no credentials or startup bypasses were supplied, and temporary state was removed.pnpm buildandgit diff --checkpassed, with no ineffective-dynamic-import diagnostic. Fresh complete-candidate Codex autoreview is scoped-clean at the configured P0-only threshold, confidence 0.97. A broader-priority review is not claimed.pnpm test:docker:agent-bundle-mcp-toolspassed on Blacksmith Testboxtbx_01m187vbsdxxrgthrmcn4b0r36, Actions run 33287999441, wrapper exit 0. It tested earlier implementation snapshotaf0f09ea7635cf34dcde3d876123581652769d00, treec8e0ca01f55826feed8f6f9d77d2528b49b7c5aa; remote synthetic headcb18521b677c437a6a47ad8c1f1e78d4582f72d8had that exact whole tree and clean status before/after. Profile/tool gating and MCP App preview passed. The lease was stopped and independently confirmed completed. The MCP production patch remains identical; this is not a claim that the entire later base tree was packaged in that earlier run.rust-v0.151.0. This supports the unchanged projection contract, not a broader Codex-upgrade verdict.Exact-head CI passed: CI run 33297440085, attempt 1, completed successfully on
8ab596daab8eedffb5b05c6f0a50f2eee7893d08. The native watcher and typed run metadata both verified this result. The latest ClawSweeper review at this exact head found no repair findings; its CI-completion rank-up move is satisfied.Merged: e620c4f556a45 through the native prepare/merge workflow; completion receipt. The exact reviewed head was merged, the retained receipt is complete, and the native PR worktree was cleaned up. One earlier admission stopped before intent/dispatch when the final PR/main snapshot changed; its task-owned lock was recovered only after process cleanup and the no-dispatch state were verified. No credential reset, policy change, or GitHub-rule bypass was used.
Post-merge composition
The independent metadata extraction landed immediately before this PR. Its four overlapping edits were metadata import/test/build-entry migrations, and the initial combined MCP cohort passed all 143 cases. A fresh main build then caught a separate stale Code Mode import of
getPluginToolSideEffectOwnerKeyfrom the old runtime module; three existing recovery tests reproduced the same defect.Eden (@edenfunf) independently landed the canonical one-line caller repair in PR 133155, commit be5e79ca4713. Raw-parent comparison verified that its patch is byte-for-byte identical to the local repair validated here, so no duplicate PR was published and no obsolete export was restored.
Final canonical-main verification at
bed5daf176f6d7552b27b7c87d33e7d201dd82f6, containing both landed repairs, passed 159 tests across seven files: 143 MCP runtime/harness/auth/lifecycle cases, 15 Code Mode recovery cases, and one full-attempt recovery boundary. The checkout is clean at that synced main snapshot.Additional composed build/runtime proof passed on public base
41dccabf17967bcc64d6caf7a40334e6f5dca363plus the exact now-landed caller patch (local verification treec2d821bfb52ec6b28f63a97763f034b58b58a7a2): fresh build; the compiled MCP client with isolated HOME/config/state; and the real public Context7 CLI flow. The compiled client verified shared tool metadata, coding/messaging tool counts of 3, minimal/denied counts of 0, matching SDK custom-tool filtering, and an MCP App preview. This extra smoke used freshly built local dist, not Docker or a new npm-install transaction; it is not represented as a full build of every later main commit.CI failures repaired
Initial CI run 33288382089 rejected the auth fixture's new inline lint suppression. The fixture now lets the SDK Client own transport callbacks instead of expanding the suppression allowlist. All four exact ratchet cases and thirteen auth/lifecycle cases pass.
Next CI run 33290675386 exposed a quota-test data gap after main's current-provider filter landed. The unchanged five-case suite reproduced it on the actual executed merge
5d6990c332684e071ed0d0b916ae267cc9792675: Work's main session was active, but the mock supplied only a global roster row and empty history. Provider-tagged history fixed that exact merge and the PR branch without changing assertions, filtering or deadlines. Newer current main independently includes that input and improved scenario handling, so the duplicate test commit was dropped; the whole current-main file passes on this candidate.Earlier failed local attempts remain in the record: an incomplete installed OpenAI SDK required a lockfile-preserving pnpm reinstall, and some cold-source/native-CLI attempts exhausted unchanged guards. Later focused and public CLI runs passed without increasing bounds. No exact latency benefit or explanation of historical deadlines is claimed.
Proof limits: OAuth credentials are synthetic with real local protocol/store owners, not live vendor OAuth. App expiry is clock-controlled. Functional Docker proof is tarball-backed runtime execution, not a complete npm install/upgrade transaction. No production visual UI change is introduced by this PR, and no operator state or another active worktree was changed.
Focused current-head commands
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/mcp-app-conformance.e2e.test.ts -t 'drives the authenticated Control UI and ticketed standalone bridges'Native CLI commands ran from a neutral temporary workspace with isolated HOME/config/state and a fixed per-command process guard. The prior complete changed gate used all 29 original candidate paths explicitly; later auth-fixture and quota repairs also passed their scoped
node scripts/check-changed.mjs -- <path>checks.Follow-up recorded separately: align provider-normalization architecture documentation with current manifest/runtime ownership; no provider-wide loader rewrite is included here.
AI-assisted implementation and validation.