Skip to content

fix(mcp): keep metadata and cleanup from eagerly loading runtimes - #133028

Merged
steipete merged 2 commits into
mainfrom
steipete/distracted-shamir-3c36eb
Aug 30, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/distracted-shamir-3c36eb

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

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, tree f69808937d4223349ed4627e334558d8d0d3391d, rebased onto 6425f8f16a27d1f941cc3c99d964c330e8e2e53a.

  • Current-main refresh: all 29 remaining file patches are byte-for-byte identical before and after the required conflict rebase. The sole upstream overlap was the now-redundant quota fixture. The fetched base passed main CI run 33296353305. Direct caller/callee review found no incompatible MCP owner drift; the plugin loader and runtime factory carry the same config/state capability objects through lazy materialization, and the embedded caller still awaits creation and captures App policy. This addresses ClawSweeper's current-main inspection/rank-up request.
  • Before/after import proof: cold-import regressions failed against original production for the intended profile-implementation and App-runtime import edges, then passed with the candidate restored. These are forbidden-import failures, not timeout-based evidence.
  • Current-head MCP/auth proof: 17 focused cases passed: four suppression-ratchet cases plus thirteen auth/import/manager cases. Real local store/provider owners and SDK HTTP requests cover external rotation/removal, persisted refresh, raw-token projection, request/generation isolation, and delayed creation/disposal. The refresh fixture performs normal SDK Client initialization and validated ping responses; the original 30-second child guards remain unchanged.
  • Current-head quota composition: the complete upstream five-case quota E2E file passed in its original order after dropping our duplicate fixture. Current main's provider input, normal sidebar selection, held-response handling, and stale-auth/account/plan assertions are retained unchanged. There is no quota-test or production UI diff in this PR.
  • Current-head App bridge conformance: the functional authenticated-Control-UI/ticketed-standalone case passed. It uses a real source-mounted component, Gateway, stdio, and official MCP App, not a full normal dashboard. The separate composed-operation/cancellation case was intentionally filtered out.
  • Current-head native CLI: after a fresh build, the isolated built CLI completed list → normal add with its default probe → verbose status → reload → probe → unset → empty list against https://mcp.context7.com/mcp, returning two server tools and no diagnostics. Build commit 8ab596daab8eedffb5b05c6f0a50f2eee7893d08 was checked explicitly. Every command retained its 30-second guard; no credentials or startup bypasses were supplied, and temporary state was removed.
  • Current-head build/review: fresh pnpm build and git diff --check passed, 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.
  • Sibling coverage: an earlier 338-case cohort across 20 files passed: 95 Gateway/App, 42 CLI, 170 agents-core, 19 agents-support, and 12 agents-core-isolated. Later fixture refinements and the rebase are covered by the current focused runs; the earlier cohort is not represented as a new all-current suite.
  • Lifecycle proof: a fresh manager-API-first process performed empty cleanup, real stdio creation, discovery/call, disposal/child exit, and recreation/teardown. V8 recorded zero factory calls before demand and one per creation. Real stdio-child/SQLite-lock tests cover run disposal and clock-controlled App-view retirement.
  • Package runtime: pnpm test:docker:agent-bundle-mcp-tools passed on Blacksmith Testbox tbx_01m187vbsdxxrgthrmcn4b0r36, Actions run 33287999441, wrapper exit 0. It tested earlier implementation snapshot af0f09ea7635cf34dcde3d876123581652769d00, tree c8e0ca01f55826feed8f6f9d77d2528b49b7c5aa; remote synthetic head cb18521b677c437a6a47ad8c1f1e78d4582f72d8 had 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.
  • Static checks: the original complete classified format/type/lint/architecture gate passed, including zero runtime import cycles. Both subsequent test-only repairs passed their scoped changed checks; current-head hosted CI is tracked below.
  • Dependency contract: the MCP SDK remains 1.30.0. For current main's separate Codex package update, direct sibling-source inspection checked MCP configuration and bearer resolution, plus explicit HTTP bearer construction, at 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 getPluginToolSideEffectOwnerKey from 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 41dccabf17967bcc64d6caf7a40334e6f5dca363 plus the exact now-landed caller patch (local verification tree c2d821bfb52ec6b28f63a97763f034b58b58a7a2): 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 test/scripts/lint-suppressions.test.ts src/agents/mcp-auth-profile.integration.test.ts src/agents/mcp-ui-resource.import-boundary.test.ts src/agents/agent-bundle-mcp-manager.lifecycle.test.ts
node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner ui/src/e2e/chat-quota-pill-93041.e2e.test.ts
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'
pnpm build
git diff --check 6425f8f16a27d1f941cc3c99d964c330e8e2e53a HEAD

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.

@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 02:36
@steipete
steipete requested a review from a team as a code owner August 30, 2026 02:36
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 3:04 AM ET / 07:04 UTC.

ClawSweeper review

What this changes

The 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 provenance

Possible 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 maintainer label and stays open for normal maintainer review.

Priority: P2
Reviewed head: 8ab596daab8eedffb5b05c6f0a50f2eee7893d08

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent, net-negative owner-boundary refactor with targeted concurrency and import-boundary coverage; no blocking defect was identified.
Proof confidence 🦞 diamond lobster (5/6) Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate; its supplied exact-head CI and focused runtime, CLI, packaged, and lifecycle evidence are consistent with the reviewed manager and caller boundaries.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate; its supplied exact-head CI and focused runtime, CLI, packaged, and lifecycle evidence are consistent with the reviewed manager and caller boundaries.
Evidence reviewed 7 items Demand-loaded runtime owner: The manager now keeps the transport runtime behind one lazy loader and supplies it only to creation, while the manager API exposes metadata and cleanup operations without requiring that runtime import.
Late-creation disposal fence: Replacement creation claims the in-flight slot before awaits and verifies that claim before publishing; disposal removes publication before awaiting the captured producer.
Lifecycle coverage: The added tests exercise pending-factory session/global disposal, identity replacement, retained retirement, and requester-chain ordering without adding a production-only test seam.
Findings None None.
Security None None.

How this fits together

MCP 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +604, Tests +462, Other +2. Total +1068 across 29 files.

View PR surface stats
Area Files Added Removed Net
Source 17 822 218 +604
Tests 11 545 83 +462
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 3 1 +2
Total 29 1370 302 +1068

Review metrics

Metric Value Why it matters
Production and test delta production -46 net; tests/test support +1,114 net The refactor reduces production code while adding focused lifecycle, import-boundary, auth, and packaged-runtime coverage.

Technical review

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

Labels

Label justifications:

  • P2: This is a targeted MCP lifecycle and import-boundary reliability repair without evidence of an active release-blocking failure.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate; its supplied exact-head CI and focused runtime, CLI, packaged, and lifecycle evidence are consistent with the reviewed manager and caller boundaries.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • tzy-17: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-08-30T02:43:15.322Z sha af0f09ea7635cf34dcde3d876123581652769d00 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T02:52:19.525Z sha af0f09ea7635cf34dcde3d876123581652769d00 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T03:43:36.456Z sha ae83dd2 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T04:52:28.198Z sha f47a23e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T05:22:49.296Z sha f47a23e :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T06:51:34.968Z sha 8ab596d :: needs maintainer review before merge. :: none

@steipete steipete self-assigned this Aug 30, 2026
@steipete
steipete force-pushed the steipete/distracted-shamir-3c36eb branch from af0f09e to ae83dd2 Compare August 30, 2026 03:37
@steipete

steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor Author

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 bed5daf176f6d7552b27b7c87d33e7d201dd82f6, and the checkout is clean. A post-merge build also caught a separate stale Code Mode metadata import. Eden (@edenfunf) landed the canonical repair in PR 133155; its raw-parent patch is byte-identical to the repair validated here, so no duplicate PR was published.

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.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 30, 2026
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.
@steipete
steipete force-pushed the steipete/distracted-shamir-3c36eb branch from f47a23e to 8ab596d Compare August 30, 2026 06:40
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 30, 2026
@steipete
steipete merged commit e620c4f into main Aug 30, 2026
264 checks passed
@steipete
steipete deleted the steipete/distracted-shamir-3c36eb branch August 30, 2026 07:06
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui cli CLI command changes gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant