Skip to content

Subagents need an MCP capability broker: parent allowlists, zero-start by default, bounded pooling, and deterministic teardown #38353

Open

Description

@NgoQuocViet2001

What variant of Codex are you using?

Codex Desktop / app-server multi-agent workflows. The design should also apply to CLI and IDE subagents.

Observed on:

  • Codex App 26.803.10989.0
  • Windows 11 x64, build 26200
  • multi_agent = true
  • max_concurrent_threads_per_session = 128

What feature would you like to see?

Treat MCP access as a leased capability assigned by the parent/orchestrator, rather than automatically turning every inherited MCP configuration into a live runtime for every subagent.

A general-purpose child should start with no live MCP processes. The parent should be able to give that child an explicit MCP allowlist, and an allowed server should start only when the child actually calls one of its tools. MCP runtimes should be bounded, attributable to an owner/lease, and deterministically released.

This is both a reliability feature and a least-privilege feature: most coding/research/QA children do not need every credentialed MCP available to the parent.

Why this is a distinct gap

There are several related reports, but they cover individual symptoms or only part of the lifecycle:

Those are valuable pieces. The missing abstraction is a single policy/ownership layer covering:

  1. which MCPs a child is allowed to use;
  2. whether any process must start at child creation;
  3. how first-run/catalog discovery avoids an N-child fan-out;
  4. how live instances are bounded and reused where safe;
  5. who owns each process and when its lease ends;
  6. what happens when resource limits are reached.

In particular, #38217 is a good foundation, but cached-tool lazy startup alone does not cover first run/cache miss, explicit per-child capability selection, bounded process ownership, or completed-child teardown.

Concrete production incident

In one Codex Desktop task, the UI showed 128 active subagents and remained in progress for more than an hour. Steering/new messages stopped being accepted.

At the time of inspection, one globally configured Node stdio server (@sjawhar/whatsapp-mcp) had multiplied into:

  • 11 Node server processes;
  • 11 launcher processes;
  • about 1.465 GB working set for the Node servers alone;
  • several old instances with roughly 3,600 CPU seconds each.

This MCP was not relevant to the children doing repository research.

Killing only that exact 22-process MCP tree reduced the pressure immediately. Two instances respawned while the configuration was still enabled. After removing only that MCP configuration and terminating those two exact processes, the count stayed at zero in the follow-up check. No unrelated MCP configuration was changed.

The high concurrency setting made the incident severe, but this is exactly why fan-out needs backpressure: an accepted subagent limit should not silently permit subagents × configured MCP process trees to exhaust the machine or make the parent UI unsteerable.

Proposed model

1. Parent-controlled capability manifest

The parent supplies an allowlist when spawning a child. The default lightweight child inherits no live MCP servers.

Illustrative configuration/API (names are only examples):

[agents.default.mcp]
inherit = "none"
startup = "on_tool_call"
max_live_servers = 2
idle_timeout_sec = 60

[agents.docs_researcher.mcp]
allow = ["openai-docs"]

An equivalent spawn-time override could be:

spawn_agent(..., mcp_allow = ["github"], mcp_inherit = false)

Keep inherit = "all" as an explicit compatibility option.

2. Separate tool catalogs from live connections

A child may need tool schemas for planning, but that should not require one live server per child.

  • Reuse a centrally cached catalog keyed by effective server configuration.
  • On a cache miss, perform at most one coordinated discovery startup for that configuration, cache the result, then stop the discovery process if it is not leased.
  • Concurrent children wait on the same discovery future instead of each starting a copy.
  • A selected/required MCP should be eager only when explicitly required for that specific child, not merely because it is required in the parent's global configuration.

3. Bounded MCP broker/pool

The app-server should broker runtimes by a stable key such as workspace + effective config hash + auth/permission scope.

  • Share only servers that are declared safe to share.
  • For stateful/non-shareable servers, use a bounded per-server pool.
  • Queue requests or return a clear resource-limit error instead of spawning without a ceiling.
  • Apply a global process/memory budget independent of the maximum subagent count.

4. Lease-based ownership and deterministic teardown

Every live MCP runtime should expose an owner/lease:

server_config_hash
runtime_id
owning_task_or_pool
agent_ids
started_at
last_used_at
lease_count
shutdown_reason

Release the lease on child completion, cancellation, failure, interruption, thread close, and app-server shutdown. When the last lease is released, terminate immediately or after a short idle TTL. Process-tree teardown must work even if client objects or resumable agent identities still exist.

5. Resource backpressure and diagnostics

Before spawning a child or MCP runtime, estimate/check the resulting budget.

If the limit would be exceeded:

  • keep the MCP dormant;
  • queue the child/tool call;
  • or show a clear warning with the server and owning agents.

The Desktop diagnostics panel should show live MCP instance count, owning task/agent, age, CPU/memory, and a safe “unload idle MCPs” action.

Suggested implementation path

  1. Extend the lazy-start work from Start required cached MCP servers lazily for subagents #38217 so the tool catalog is not coupled to a per-child live connection, including cache-miss coalescing.
  2. Add a per-agent MCP capability manifest to the spawn/session configuration.
  3. Put process creation behind an app-server broker with per-config single-flight and configurable pool limits.
  4. Reuse the explicit shutdown/process-handle machinery from Terminate stdio MCP servers on shutdown to avoid process leaks #19753 for lease release.
  5. Add a watchdog/circuit breaker so MCP fan-out can never make the parent unable to accept cancellation or steering.

Acceptance tests

A PID-recording stdio fixture could make this deterministic:

  1. No-use fan-out: spawn 64 children that never call MCP tools. After catalog discovery, live MCP process count must remain at the parent baseline, not grow with N.
  2. Cold-cache single-flight: with no cached catalog, spawn 64 children concurrently. At most one discovery runtime per effective server config may start, and it must exit after discovery if unleased.
  3. Explicit allowlist: only one designated child is allowed to use server A. Other children must neither see its callable tools nor receive its credentials.
  4. First tool call: the designated child calls one MCP tool. Exactly one runtime (or the configured bounded count) starts.
  5. Completion/cancel/error: after that child completes, is cancelled, or crashes, the runtime returns to baseline within the teardown/idle timeout.
  6. Resume: a later follow-up lazily reacquires a healthy runtime; historical thread viewing alone starts none.
  7. Backpressure: setting a high subagent limit cannot exceed the separate MCP runtime budget, and parent cancellation/steering remains responsive.
  8. Windows process tree: wrapper and descendant processes are gone after lease release, not only the direct launcher.

Additional information

Official documentation currently explains that subagents inherit parent session settings such as mcp_servers unless overridden, and that concurrency is separately controlled by agents.max_concurrent_threads_per_session:

Configuration inheritance is useful, but it should mean “available under policy,” not “eagerly instantiate the entire capability surface for every child.”

This proposal would turn the recent lazy-start and shutdown fixes into a coherent invariant:

Creating a subagent must not create a live MCP process unless that child was explicitly granted the capability and actually needs a connection; every created runtime must have a bounded owner and a deterministic release path.

Activity

  1. added
    enhancement
    app
    mcp
    app-server
    subagent
    windows-os
    on Aug 13, 2026
  2. NgoQuocViet2001 commented on Aug 13, 2026

    @NgoQuocViet2001
    Author

    Thanks for reviewing main and #31922 at the code level. Speaking as the issue reporter, not for the maintainers, I strongly support the durable spawn-time allowlist as an independently reviewable first stage.

    My answers to the three questions are:

    1. Land the allowlist before broker/lease ownership rather than wait for the entire architecture. It creates an enforceable capability boundary and immediately prevents cold-cache startup for servers a child was never granted. Pooling, single-flight discovery, budgets, and teardown can remain follow-up stages. This first stage would not fix retention of an allowed server, so this issue should remain open as the architectural umbrella.

    2. Keep an empty MCP allowlist semantically separate from tool_free. tool_free removes the entire tool/skill/plugin surface. mcp_allow = [] should mean “no MCP” while still permitting appropriate built-in tools such as shell and apply-patch. The implementations may share low-level filtering, but overloading tool_free would make the policy too coarse.

    3. Use inherit-all as the initial compatibility default, with an explicit deny-all option. The API needs to preserve the tri-state distinction:

      • omitted: compatibility inheritance;
      • empty: deny every MCP;
      • populated: allow exactly those server IDs.

    One important nuance: after spawn-time resolution, even omitted/inherit-all should be normalized to the exact effective server IDs granted at spawn and persisted with the child. Otherwise, adding a global/plugin MCP later could silently broaden an old child’s authority on cold resume. Only an explicit parent action should expand the persisted grant.

    A few acceptance details would make this an authorization boundary rather than only a startup optimization:

    • resolve config/plugin/extension contributions first, then filter before catalog lookup, authentication/environment propagation, or connection creation;
    • filter every MCP surface—tools, resources, prompts, deferred/tool-search candidates—not only live connections;
    • use stable server IDs; unknown requested names should fail closed with a clear spawn error, never fall back to inherit-all;
    • enforce the persisted grant on follow-up, residency reload, and cold resume;
    • cover both warm and cold catalog states and assert zero PID creation for disallowed stdio servers;
    • verify that an empty MCP allowlist preserves permitted non-MCP built-in tools.

    There is now a second independent Windows incident behind this request. After removing the previously identified WhatsApp MCP, a later session again reached 91% memory with dozens of Python (2) groups. The remaining Python MCPs were identified from their live process trees as workspace-mcp and mcp-atlassian; each runtime used an uvx -> uv -> wrapper -> python -> python chain. The Desktop log simultaneously showed app-server saturation at six in-flight requests, repeated thread/read hydration expiry, and even critical turn/steer requests expiring after 30 seconds. Disabling only those two MCPs and reducing subagent concurrency from 128 to 6 left multi-agent enabled, removed the exact ten-process current baseline, and produced zero respawns in the follow-up check.

    Per docs/contributing.md, I will not open an unsolicited upstream PR. I am preparing a focused, tested branch implementing only this first-stage allowlist so the design can be evaluated concretely.

    @openai/codex-core-agent-team: could a maintainer confirm whether this stage boundary is aligned and, if so, explicitly invite the contribution? The proposed PR will stay under the repository’s size guidance and include integration coverage for omitted/empty/populated policy, unknown-name failure, zero disallowed PID startup, and persisted resume behavior.

  3. NgoQuocViet2001 commented on Aug 13, 2026

    @NgoQuocViet2001
    Author

    @openai/codex-core-agent-team I implemented the proposed first-stage mitigation as a tested draft review artifact: NgoQuocViet2001#1

    The patch adds a V1/V2 spawn_agent.mcp_allow contract with three explicit states (snapshot current effective set / deny all / exact validated subset), applies it after all MCP contributions are merged but before connections start, and persists the exact grant across cold resume. A PID-level Windows test verifies that mcp_allow: [] does not launch another stdio MCP process.

    I did not open an upstream PR because the contribution policy says external PRs are invitation-only. If this direction fits the team's architecture, an invitation would let me retarget the same rebased and tested commit to openai/codex without rework.

  4. NgoQuocViet2001 commented on Aug 14, 2026

    @NgoQuocViet2001
    Author

    Follow-up correction after a deeper state/runtime inspection: the Desktop "Active subagents" counter is not a trustworthy concurrency measurement.

    In a separate affected task on the same Desktop build, the UI showed 273 Active + 13 Done. A read-only inspection found exactly 286 persisted descendants, and all 286 thread_spawn_edges rows were still open. At the same time, the parent reported only 1 executing child, and the Windows process tree contained 9 node_repl.exe children rather than hundreds of agent runtimes.

    Detailed evidence and the proposed lifecycle/reconciliation invariant are here: #38364 (comment #38364 (comment)).

    Therefore, the original incident's “128 active” UI value should be read as 128 entries classified Active by the panel, not as proof that 128 model threads were simultaneously executing. I do not want the capability-broker request to rely on an incorrect concurrency claim.

    The MCP resource incident itself remains independently verified:

    So there are two related but distinct defects:

    1. Lifecycle/UI reconciliation: historical/open edges are mislabeled as currently Active (Subagents panel permanently shows completed agents as Active and Working #38364 / Windows Codex Desktop: opening/resuming historical subagent threads spawns duplicate MCP and node_repl process stacks #37453).
    2. Capability/resource amplification: each genuinely resident or resumed child may instantiate inherited MCP stacks; spawn-time allowlists and bounded ownership remain useful even when the true live agent count is small (this issue).

    This distinction also suggests a useful diagnostic contract: expose separate counts for executing, resident, and historical/open-edge, plus MCP runtimes owned by each execution lease.

  5. aldi949 commented on Sep 23, 2026

    @aldi949

    @NgoQuocViet2001 hey — I've been looking into this problem from the user side and found several reports where subagents either inherit way too much MCP state or don't get the tools they need at all.

    Your capability-broker proposal is one of the clearest descriptions I've found.

    Is this painful enough in your actual workflow that you'd use a separate tool today to inspect/control exactly what MCP tools, context and processes each agent receives? Or do you see this mainly as something Codex itself should fix?

  6. CBEPX commented on Oct 15, 2026

    @CBEPX

    macOS 0.162.1: bounded residency retains used MCPs. Explicit teardown passes

    I tested the installed Codex CLI 0.162.1 on macOS 27.0.1, arm64, with 48 GiB RAM.
    These results separate completed-agent residency from a failure to terminate processes.

    The test used a separate Codex state directory and the installed codex app-server.
    A local deterministic Responses endpoint supplied tool calls and final responses, without paid inference or production credentials.
    I tested both a minimal stdio MCP with a child process and a real Serena/Pyright chain.
    Serena used a one-file Python project and an existing Pyright installation. I disabled its dashboard for this test.

    Relevant versions and settings:

    • Codex CLI: 0.162.1. Source tag rust-v0.162.1, commit 092d3acd6bec3e3a14bdc7e7a2810ab628ab759d.
    • I did not independently prove that the installed binary was built from that exact commit.
    • Serena: 2.0.1.dev0, installed VCS commit d9e4c796fae0207ba6848d1df4b331122a5567b5.
    • features.multi_agent = true, features.multi_agent_v2 = true. Default V2 concurrency settings.
    • One configured stdio MCP. Code mode disabled in this isolated test.

    Reproduction sequence and results

    1. Start a root thread and invoke the MCP once.
    2. Spawn five children sequentially with fork_turns: "none". Each child invokes the MCP and completes before the next starts.
    3. Send a follow-up task to the evicted first child. Invoke its MCP again.
    4. Interrupt a completed child. Separately test a model error after an MCP call, and interruption of an active child.
    5. Start an independent sentinel thread and invoke its MCP.
    6. Archive the first root, verify the sentinel still works, then archive the sentinel.
    7. Start another root and invoke its MCP. Close app-server stdin and wait for exit.
    Checkpoint Live MCP servers / child processes
    Root used MCP 1 / 1
    Five children completed in sequence 2, 3, 4, 4, 4 / same counts
    Evicted child resumed and used MCP 4 / 4
    Completed child interrupted 4 / 4
    Failed or actively interrupted child 4 / 4
    Independent sentinel started 5 / 5
    First root archived 1 / 1. Sentinel tool still works
    Sentinel archived 0 / 0
    New root, followed by app-server exit 1 / 1 → 0 / 0

    Both full runs passed, including 12 distinct successful MCP calls in each run.
    The minimal MCP recorded 11 starts and 11 SIGTERM exits. No owned server or child survived final shutdown.
    The real Serena run also left no server or Pyright process.
    Independent Serena stdin-EOF tests passed five cycles, with shutdown taking 0.199–0.265 seconds.

    A warm-catalog control used five children that did not invoke Serena.
    It retained only the root's one Serena/Pyright pair, then zero after archive.
    This does not test cold-cache startup.

    Interpretation

    The observed ceiling matches V2 residency.
    Completed, errored, and interrupted children remain resident until another admission needs capacity.
    Eviction calls shutdown_and_wait().
    The default configuration permits three resident children plus the root per tree.

    On the working machine, a separate snapshot found 33 Serena processes with about 19.06 GiB aggregate footprint.
    Thirty Pyright Node processes accounted for another 20.59 GiB.
    The two inspected Python-server logs each reported about 10,860 workspace source files.
    These are footprint measurements, not resident RAM, and they do not establish a heap leak.

    This supports a narrower follow-up: release idle MCP runtimes while preserving resumable agent history, or expose explicit runtime unloading.
    Process-count limits alone do not bound the memory cost of retained language servers across multiple root trees.
    The tested archive, eviction, and app-server exit paths worked in 0.162.1.
    I am not reporting an unbounded leak or claiming that those shutdown paths are broken.

  7. CBEPX commented on Oct 16, 2026

    @CBEPX

    Agent work: stage finished

    Client: codex · Session: codex-lifecycle-upstream-evidence-20261016-0437 · Claim: 5257b8c0-8661-4f91-9559-b6a28462a328

    Mode: write · Started: 2026-10-16T04:36:35+03:00 · Updated: 2026-10-16T04:48:05+03:00

    Stage: Recovery: Stopped owner claim; coordination note is finished and issue marker absent; recover with verified absent-marker fix

    Scope in this repository: read-only or external scope

  8. CBEPX commented on Oct 16, 2026

    @CBEPX

    Tested opt-in runtime unload prototype

    The fork patch adds features.multi_agent_v2.completed_agent_unload_delay_secs on the pinned rust-v0.162.1 source.
    It reuses native eviction and preserves the existing concurrency limit.
    An absent setting preserves the previous behavior. Zero requests unload at the first safe opportunity.
    The timer excludes root sessions and checks active work, mailbox triggers, descendants, and reloadable history.
    It retries once after five seconds when a guard blocks unload.

    The patch also protects delivery and interrupt operations during teardown.
    Regression tests first reproduced the failures, including an interrupt race that could delete reload metadata.
    An independent Claude Opus review approved the final correction.

    ARM64 CI passed 2,768 core tests and 44 feature tests.
    The upstream formatter command passed.
    The source files in the clean fork commit match the tested CI snapshot a4e2564.

    Five local macOS E2E runs passed with the hash-checked binary: setting absent, delays 0 and 2, and real Serena/Pyright with dashboard on/off.
    The tests cover history, final-result delivery, followup before and during teardown, interruption, active calls, sleep/mail, nested children, a separate session, archive, and EOF.
    With unload enabled, each completed child left only the root MCP/LSP pair. Archive and EOF left zero owned processes.
    A fresh process check found none of the 140 owned MCP/LSP process IDs from these runs.

    This is an isolated prototype, not an upstream release or evidence of a Pyright heap leak.
    Codex does not restore transient MCP state after reload. Stateful servers need separate qualification before opt-in.

  9. NgoQuocViet2001 commented on Oct 21, 2026

    @NgoQuocViet2001
    Author

    Thanks @CBEPX for the detailed testing of MCP runtime retention and unloading, and @aldi949 for asking about the impact on my workflow.

    After running into this issue, I added a rule in config.toml telling Codex to spawn no more than six subagents at a time. I haven't experienced the same lag since then. I haven't tried raising the limit again because the current cap still suits the way I work.

    Another factor is that I sometimes ask subagents to use a less capable model for investigation or coding, and weaker results can make the main agent spend a lot of extra tokens reviewing and correcting their work. So, for my workflow, more subagents do not necessarily mean better efficiency, and the current setup has been working well for me.

    I'll look into how much recent Codex versions have addressed this issue. If things have improved, I may try increasing the limit to around 24 concurrent subagents. Thanks everyone for continuing to investigate and contribute here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    appapp-serverenhancementmcpperformancesubagentwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions