Skip to content

fix(mcp): avoid memory spikes from oversized client TLS files - #110016

Closed
wahaha1223 wants to merge 16 commits into
openclaw:mainfrom
wahaha1223:fix/mcp-bound-client-tls-files
Closed

wahaha1223 wants to merge 16 commits into
openclaw:mainfrom
wahaha1223:fix/mcp-bound-client-tls-files

Conversation

@wahaha1223

@wahaha1223 wahaha1223 commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes memory spikes when an MCP client certificate or key points to a very large file, and makes MCP Doctor report the same configuration error as the connection path.

User Impact

Each certificate/key file is limited to 64 KiB. Regular files, symbolic links, and hard links remain supported; no configuration migration is needed.

Why This Change Was Made

Runtime and Doctor share a bounded asynchronous file reader. Each runtime fetch client coalesces pending TLS-material reads and reuses successful material; failed reads remain retryable. Credentials remain scoped to the configured server origin, with cancellation and request authority checked before dispatch.

The cleanup repair also closes unclaimed native model-catalog clients on plugin retirement while preserving active peers. For returned or late-returned startup clients, terminal cleanup retains ownership until exit is observed or an explicit retry succeeds.

Original contribution by @wahaha1223.

Evidence

Earlier TLS regression proof used real localhost mutual TLS: ordinary and linked PEM files authenticated, oversized files and FIFOs were rejected before HTTP dispatch, and the registered CLI Doctor agreed. This proof predates the final cleanup composition.

  • On Node 24.21, the Gateway test postimage now committed in 3a82a986fc8e passed all 89 cases in 61.44 seconds. The unchanged shared-client fixtures passed all 137 cases in 48.93 seconds before signing their d964818c2e5c parent. Relevant test typechecks, scoped lint, and the line-growth check passed. Independent reviews of the fixture repairs found no actionable P0–P2 findings.
  • The fixtures now isolate HOME and await actual startup close events instead of assuming fake-clock advancement finishes real I/O. The preceding CLI-title fixture correction passed 73 cases in 46.188 seconds with an inherited CLI title.
  • Execution SHA fb0f8320676c passed its Linux build in 209.607 seconds and the unchanged three-case native-discovery comparison in 49.708 seconds. Completed cases and suite teardown retained zero client entries; both controls retained two. The canonical runner verified the completed compiler generation before retaining it.

Signed candidate 3a82a986fc8e differs from the live execution SHA only in the CLI preaction test and the three fixture files above. Runtime, documentation, and dependency bytes are identical; the live comparison was not rerun on this descendant.

Both recorded managed launchers exited via SIGKILL, and the final scoped process check was empty. Individual native-child exits were not captured; this is not exhaustive descendant-exit proof. Cleanup failures before a transport returns a client remain outside this repair.

Native build, full repository checks, and all 616 scheduled Vitest shards passed on 3a82a986fc8e in 2h43m51.854s. The full run passed the repaired Gateway and shared-client files, the registered Doctor TLS-limit regression, and the HTTP-fetch and request-authority cases. Pending: required CI and reviews on the exact published head. Earlier incomplete runs are not counted as full passes.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Jul 17, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jul 17, 2026
@clawsweeper

clawsweeper Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 25, 2026, 12:55 PM ET / 16:55 UTC (Revision 11).

ClawSweeper review

What this changes

The branch bounds MCP client certificate and key reads, adds matching Doctor diagnostics and documentation, and repairs Codex app-server client cleanup and related runtime fixtures.

Merge readiness

⛔ Blocked before merge - 5 items remain

Current main still reads MCP client TLS files without a size bound, so this PR remains useful. The earlier Doctor diagnostic finding is resolved. The new 64 KiB ceiling can reject an existing valid mTLS configuration, and the current head is reported as conflicting with main.

Priority: P2
Reviewed head: 3a82a986fc8e82322584b6dbee2bff80385e3dbb
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has meaningful runtime proof and resolves the earlier Doctor gap, while the mTLS upgrade contract and conflicted integration remain unsettled.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR body records after-fix localhost mutual-TLS behavior for normal and linked PEMs and rejection of oversized files before HTTP dispatch, plus a native app-server client comparison for cleanup. Production bytes are unchanged between that native execution commit and the reviewed head. No stored-data contract changes; individual native-child exits were not captured.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body records after-fix localhost mutual-TLS behavior for normal and linked PEMs and rejection of oversized files before HTTP dispatch, plus a native app-server client comparison for cleanup. Production bytes are unchanged between that native execution commit and the reviewed head. No stored-data contract changes; individual native-child exits were not captured.
Evidence reviewed 9 items Current main still needs the MCP fix: Current main uses unbounded synchronous reads for clientCert and clientKey; Doctor checks only whether their paths name files.
Introduced size limit: The PR reads each configured TLS file through a regular-file reader capped at 65,536 bytes; this changes acceptance of existing larger files.
Earlier finding resolved: Doctor now calls the same bounded reader as runtime, and its registered CLI test expects an error for oversized certificate and key files. The transport docs state the limit.
Findings 1 actionable finding [P1] Settle compatibility for existing mTLS files above the new ceiling
Security None None.

How this fits together

OpenClaw’s MCP HTTP client reads configured certificate and key files before dispatching requests to remote tool servers; the MCP Doctor checks those settings for operators. The Codex plugin separately uses app-server clients to discover models and serve agent runs, then closes them during plugin retirement.

flowchart LR
  A[Configured MCP server] --> B[Certificate and key reader]
  B --> C{Within file limit?}
  C -->|Yes| D[Guarded HTTP request]
  C -->|No| E[Doctor error or failed connection]
  F[Codex model discovery] --> G[App-server client owner]
  G --> H[Plugin retirement cleanup]
Loading

Decision needed

Question Recommendation
Should existing MCP mTLS configurations with certificate or key files above 64 KiB intentionally stop connecting after upgrade? Accept the 64 KiB ceiling: Approve the documented failure and Doctor diagnostic as an intentional upgrade change after checking representative existing PEM chains.

Why: The cap prevents unbounded reads but changes a previously accepted public configuration contract; source and tests cannot establish the intended compatibility tradeoff.

Before merge

  • Settle compatibility for existing mTLS files above the new ceiling (P1) - The new 64 KiB cap rejects configured PEM files that current main reads successfully, so an existing MCP connection can stop working after upgrade. Doctor and documentation now expose the limit, resolving the earlier diagnostic finding, but the accepted upgrade contract or a compatibility-safe bound still needs a maintainer decision.
  • Resolve merge risk (P1) - An existing mTLS certificate or key file above 64 KiB will fail before its first MCP request after upgrade. Doctor now identifies the problem, but the PR has no accepted compatibility policy or upgrade proof for existing valid PEM chains.
  • Resolve merge risk (P1) - The current head is reported as conflicting with main, and no pinned merged tree was available to verify the integrated result.
  • Complete next step (P2) - Resolve the main-branch conflicts and obtain a maintainer decision on the 64 KiB limit’s effect on existing mTLS configurations, with upgrade evidence.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

  • [P1] Settle compatibility for existing mTLS files above the new ceiling — src/agents/mcp-client-tls.ts:4
Agent review details

Security

None.

PR surface

Source +325, Tests +1085, Docs +24. Total +1434 across 44 files.

View PR surface stats
Area Files Added Removed Net
Source 17 634 309 +325
Tests 23 1262 177 +1085
Docs 4 27 3 +24
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 44 1923 489 +1434

Review metrics

Metric Value Why it matters
Production and test line delta production +634/-309, tests +1262/-177 The stated Codex lifecycle repair accounts for substantial production growth beyond the focused TLS reader.
New TLS file limit 64 KiB per certificate or key This new acceptance limit is the compatibility decision for existing mTLS configurations.

Merge-risk options

Maintainer options:

  1. Settle and prove the bound (recommended)
    Select a limit against representative existing PEM chains, verify fresh and upgrade behavior, and resolve the main-branch conflicts.
  2. Accept the operator change
    Explicitly accept that larger configured files will stop connecting and retain Doctor’s actionable diagnostic.
  3. Pause this branch
    Defer merging if the compatibility cost or conflicting integration work outweighs the bounded-read fix.

Technical review

Best possible solution:

Keep bounded TLS reads and shared Doctor validation, but settle the acceptable PEM-chain limit against existing configurations and verify the upgrade path before landing the integrated branch.

Do we have a high-confidence way to reproduce the issue?

Yes for the source-level defect: current main synchronously reads configured MCP TLS files without a bound. This read-only review did not run an oversized-file reproduction.

Is this the best way to solve the issue?

Unclear until maintainers settle the 64 KiB upgrade contract. Sharing a bounded reader with Doctor is a narrow repair for the memory spike; the exact ceiling remains a product choice.

Full review comments:

  • [P1] Settle compatibility for existing mTLS files above the new ceiling — src/agents/mcp-client-tls.ts:4
    The new 64 KiB cap rejects configured PEM files that current main reads successfully, so an existing MCP connection can stop working after upgrade. Doctor and documentation now expose the limit, resolving the earlier diagnostic finding, but the accepted upgrade contract or a compatibility-safe bound still needs a maintainer decision.
    Confidence: 0.92

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4c4fc7b79f42.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR addresses a bounded MCP memory-allocation defect with limited configuration-specific impact.
  • merge-risk: 🚨 compatibility: The introduced 64 KiB limit can reject existing certificate or key files that current main accepts.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): The PR body records after-fix localhost mutual-TLS behavior for normal and linked PEMs and rejection of oversized files before HTTP dispatch, plus a native app-server client comparison for cleanup. Production bytes are unchanged between that native execution commit and the reviewed head. No stored-data contract changes; individual native-child exits were not captured.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body records after-fix localhost mutual-TLS behavior for normal and linked PEMs and rejection of oversized files before HTTP dispatch, plus a native app-server client comparison for cleanup. Production bytes are unchanged between that native execution commit and the reviewed head. No stored-data contract changes; individual native-child exits were not captured.

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)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • NIO: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Obtain the maintainer’s explicit size-limit decision and verify a representative existing configuration after upgrade.
  • Resolve the reported merge conflicts and review the integrated result.

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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-31T17:21:16.846Z sha 66e1a0f :: found issues before merge. :: [P1] Define a compatibility-safe MCP TLS file limit
  • reviewed 2026-08-05T12:26:37.309Z sha 66e1a0f :: found issues before merge. :: [P1] Define a compatibility-safe MCP TLS file limit
  • reviewed 2026-08-05T13:20:28.348Z sha 66e1a0f :: found issues before merge. :: [P1] Define a compatibility-safe MCP TLS file limit
  • reviewed 2026-08-14T10:16:43.144Z sha 66e1a0f :: found issues before merge. :: [P1] Define a compatibility-safe MCP TLS file limit
  • reviewed August 16, 2026, 1:05 PM ET / 17:05 UTC sha unknown :: found issues before merge. :: [P1] Define a compatibility-safe MCP TLS file limit
  • reviewed 2026-08-18T12:37:45.200Z sha 66e1a0f :: found issues before merge. :: [P1] Define and preflight the MCP TLS-file size contract
  • reviewed 2026-08-24T02:09:12.369Z sha 66e1a0f :: needs changes before merge. :: [P1] Preflight the new MCP TLS-file ceiling
  • reviewed 2026-08-30T02:56:10.162Z sha 66e1a0f :: needs changes before merge. :: [P1] Preflight the new MCP TLS-file ceiling

@wahaha1223
wahaha1223 force-pushed the fix/mcp-bound-client-tls-files branch from 6b6ee3c to 66e1a0f Compare July 17, 2026 14:23
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Jul 31, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 18, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Sep 13, 2026
@steipete steipete self-assigned this Sep 23, 2026
steipete and others added 2 commits September 23, 2026 01:52
Share asynchronous bounded TLS file loading between HTTP requests and MCP
Doctor. Preserve configured links and PEM bytes, bound each file to 64 KiB,
and keep origin scoping, cancellation, and final request authority intact.
Clean up request deadlines when dispatcher preparation fails.

Co-authored-by: wahaha1223 <[email protected]>
Preserve the reviewed bounded TLS-file correction and contributor ancestry
while including the canonical popup listener and test-fixture repairs.
Keep main's shared MCP CLI option and list helpers.
Include the mainline maintenance-owner line-cap repair from openclaw#156809.
The reviewed nine-file TLS delta and all reviewed owner modules are unchanged.
Include the readonly-reuse wrapper archive and release validation repairs.
Preserve the reviewed bounded TLS-file correction and contributor ancestry.
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Sep 24, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Sep 24, 2026
steipete and others added 3 commits September 24, 2026 03:01
Adopt the native compiler tooling while preserving the bounded asynchronous MCP TLS-file reader and its existing validation.

Co-authored-by: wahaha1223 <[email protected]>
Integrate main through 92635da. The reviewed TLS delta and its owners are unchanged; the canonical projection helper removes the registry line-limit failure without changing the lint budget.

Co-authored-by: wahaha1223 <[email protected]>
Integrate plugin cache retirement from ec78e8e, the lightweight idle fixture from 14f4d2d, and the reviewed pressure-listener repair ea9b2cc (openclaw#157584). These repairs let validation finish within the existing heap and worker budgets.
steipete and others added 7 commits September 24, 2026 17:38
Complete the paired idle-worker fixture migration from openclaw#157341 and isolate independent PR fixtures from outer maintainer controls as reviewed in openclaw#157755. Keep production behavior, worker budgets, and assertions unchanged.
Integrate the canonical cleanup correction from openclaw#157323
(0440fa7).

Retain registry resources through terminal cleanup and invoke harness disposal
through the existing cleanup admission. In-process retirement continues to
preserve shared clients owned by live peers.

Co-authored-by: Ayaan Zaidi <[email protected]>
Adopt canonical main repair 537ac5f. Clear inherited inline Git configuration only in fixture-owned child commands, retaining the real Git maintenance assertions. Exact landed postimage and its review and test evidence are unchanged.
Register catalog cleanup with the plugin lifecycle and join its admitted request producers before closing unclaimed clients. Explicit harness shutdown starts catalog disposal and shared startup cancellation together so parked work cannot launch a replacement while shutdown waits.

Retain cleanup receipts for returned and late-returned startup clients until physical exit or a successful retry. Preserve peer leases and report cleanup failures before reopening startup admission. Adopt the canonical startup-joining repair from 890ab59.
Adopt canonical main repair 481045d. Seed the fixture title before observing the setter so an already-correct inherited title cannot fail the startup-policy test. Keep the exact canonical postimage and all existing assertions; production code is unchanged.
Keep the Gateway HOME test inside a temporary account home so plugin metadata cannot read an operator database. Wait for stdin to close before checking that startup still awaits physical exit, and keep fixture cleanup reachable on test cancellation.

Group the startup fixtures in their own support file while preserving test order, deadlines, and assertions.
Preserve the default and named-profile environments and assertions while consolidating their repeated setup. Keep the test isolated in its temporary account home and below its original line count.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes extensions: codex size: XL and removed size: S labels Sep 25, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Sep 26, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Sep 26, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

@openclaw-barnacle openclaw-barnacle Bot closed this Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes docs Improvements or additions to documentation extensions: codex gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants