Skip to content

core: cached locations multiply MCP subprocesses #37844

Open

Description

@kitlangton

Summary

One V2 managed service can retain a full configured MCP subprocess set for every active or cached Location. A live 0.0.0-next-15839 snapshot showed approximately ten repeated MCP process groups under one healthy service, with about five configured MCP children per group. The direct children accounted for roughly 2.2 GiB RSS even though the MCP processes were idle at the sample boundary.

This is separate from process-global event fan-out, but the costs multiply in the same many-TUI workflow: each TUI commonly owns a different Location, so one service accumulates both more Location graphs and more MCP subprocess sets over time.

Reproduction

  1. Configure several local MCP servers at user scope.
  2. Start one managed V2 service.
  3. Open TUIs across approximately ten distinct Locations.
  4. Inspect the managed service process tree after Location acquisition.
  5. Leave Locations idle and verify whether their MCP subprocess groups are torn down after the configured Location cache TTL.

Expected Behavior

  • Project-specific MCP declarations remain Location-isolated.
  • Identical user-global MCP declarations do not require one eager subprocess per Location unless the server protocol or effective configuration requires isolation.
  • MCP servers that are not used by a Location can start lazily.
  • Evicting an idle Location deterministically stops every MCP subprocess owned by that Location.
  • Resource use has a documented scaling model for many concurrently open Locations.

Actual Behavior

The managed service had approximately ten start-time clusters containing the same configured MCP process shapes, for approximately 50 persistent MCP children. These clusters aligned with Location acquisition rather than tool invocation. The implementation currently makes MCP a Location node and depends on Location-scoped config, integrations, forms, credentials, and events.

The service remained semantically healthy, but it was under broader runtime pressure: its health request took 1.78 seconds, and the managed server plus connected OpenCode clients accounted for about 13 GiB RSS and 457% CPU in the same snapshot. No process was restarted or terminated during measurement.

Investigation Constraints

This should not be solved by making all MCP state process-global. Effective MCP configuration, credentials, integration ownership, forms, events, and tool registration can differ by Location. The ownership key needs to reflect those semantics.

Candidate directions to measure:

  • Start configured MCP servers only when tools, prompts, resources, or instructions are first requested.
  • Share a process only when the complete effective declaration and credential/placement semantics are identical.
  • Separate a shareable transport/process owner from Location-specific registration and event projection.
  • Verify the 60-minute Location idle TTL closes MCP scopes and child processes under real TUI usage.

Acceptance Criteria

  • A test opens multiple Locations with the same global MCP declaration and asserts the intended subprocess count.
  • A distinct project-scoped declaration remains isolated.
  • Concurrent first use shares one startup per ownership key.
  • Location eviction stops unshared children and releases shared ownership without interrupting remaining Locations.
  • A many-Location benchmark records child count, RSS, startup time, and teardown time.
  • Diagnostics report MCP ownership and lifecycle without command arguments, credentials, paths, prompts, or tool payloads.

Related

Activity

  1. added
    bug
    on Jul 20, 2026
  2. self-assigned this
    on Jul 20, 2026
  3. added
    perf
    core
    on Jul 20, 2026
  4. mradwankhalil commented on Oct 14, 2026

    @mradwankhalil
    Contributor

    Additional 2.0.28 source/local-prototype context for the per-location retention problem: our desktop integration can retain about ten loaded chat folders, each with its own plugin/service graph; the local ledger records roughly 3.6 GB backend working set with the real plugin set. The aggregate is not proof of a leak inside any one MCP child.

    We prototyped an optional loaded-location ceiling, reclaiming the least recently active idle surplus locations and never reclaiming locations with a running execution. We also limited expired/surplus disposal to two locations at a time; an unbounded same-sweep teardown burst amplifies event-loop starvation. This is a policy mitigation rather than proof that client-presence-based release is wrong. Our 24-hour idle TTL is workstation-specific, not a proposed universal default.

    Before upstreaming that policy, it needs design agreement on retained locations, background shells/pending interactions, client presence, and the capacity guarantee when every location is active (the prototype is a soft ceiling, not a hard admission cap). Linking the local investigation here rather than opening a duplicate cached-location-memory issue. Relevant source: packages/core/src/location-activity.ts; the regression fixture exercises surplus eviction, active-execution protection, and bounded disposal.

  5. liucyoung commented on Oct 18, 2026

    @liucyoung

    Additional real-world data point confirming this is not isolated: on Windows, a single managed V2 service instance (OpenCode desktop, version 2.0.32) running ~14 concurrent sessions accumulated ~280 MCP-related OS processes / ~10.9 GB RSS before cleanup. Process tree tracing (Get-CimInstance Win32_Process) shows every spawn cluster's direct parent is the same single serve PID, consistent with the "one Location graph per cached location" model described in the issue body rather than any per-session process isolation.

    Timing data from ~/.local/share/opencode/log/opencode.log (mcp connected lines, grouped by run ID):

    run connections wall time interval
    A 753 ~8 h ~3.8 min between full resyncs
    B 704 ~7.5 h ~3.8 min
    C 332 ~3.5 h ~3.8 min

    All three (and every other active run) exhibit the same near-constant resync cadence of the entire configured MCP subprocess set, regardless of whether any tool call actually occurred in that window - i.e. it aligns with a Location cache TTL/rebuild timer rather than with tool invocation, matching the "clusters aligned with Location acquisition rather than tool invocation" observation already reported above.

    Mitigations in place locally while waiting for an upstream fix: (1) disabling unused MCP servers in opencode.json cuts the per-Location set from 6 to 3; (2) an idle-session cleanup script (DELETE /api/session/{id} after a configured inactivity threshold) so that stale Locations - and by extension their cached MCP process groups - get explicitly evicted instead of accumulating for hours; neither of these addresses the root cause described here, both are just papering over it until #46210/#37844 lands a proper lazy-start/LRU-reclaim behavior for identical global-scope MCP declarations across Locations.

    Workstation: Windows x86_64, OpenCode desktop v2.0.32 (opencode-cli.exe serve --service), no Docker involved, purely local stdio MCP servers (node/cmd/python/uvx wrappers). Happy to share more process-tree dumps or log excerpts if useful for the loaded-location-ceiling work mentioned in the last maintainer comment here.

  6. mlimarenko commented on Oct 28, 2026

    @mlimarenko
    Contributor

    Linking the recent controlled evidence from #51003 here so it remains attached to the shared per-location issue:

    #53046 remains open and is not part of released 2.2.0. It reduces discovery-only residency, not the initial discovery peak, package-launcher cost or caches already on disk; it does not pool servers genuinely used across locations. The fixture check did not measure real npx/uvx chains, RSS, cache sizes or wall-clock expiry. An initial grouped polling test was inconsistent and remains undiagnosed, as recorded in the linked comment.

    The separate reports of same-directory accumulation, reload survivors or children surviving a killed parent need their own lifecycle evidence; these per-location counts do not establish those causes.

  7. opencodejr commented on Oct 28, 2026

    @opencodejr
    Contributor

    Thanks for the detailed write-up. I tried this on @opencode/cli@2.2.0 (the snapshot 0.0.0-next-15839 isn't installable from npm).

    Setup: three user-scope local stdio MCP servers (a minimal idle server), one managed service (opencode service start), then opencode mcp list from five separate project directories.

    What I saw:

    • Each Location acquired got its own set of three MCP children under the service process, started at acquisition rather than on tool use (12 children across 4 Locations). This matches your snapshot.
    • With experimental.location_idle_timeout set to 30 seconds, the idle sweep evicted the Locations and stopped every MCP child, with none orphaned. Eviction teardown appears to work.

    Why I'm not treating it as a bug: this follows the current design. MCP is built as a Location node (makeLocationNode in packages/core/src/mcp/index.ts), and a local server's cwd defaults to the Location directory (packages/core/src/mcp/client.ts), so identical global declarations aren't yet identical processes across Locations. Lazy start, sharing by ownership key, a documented scaling model and lifecycle diagnostics would be design and performance improvements to the current behaviour, so this might be better tracked as a feature or enhancement.

    If you've seen MCP children survive past the Location idle TTL in real TUI use, the config and timings would be the most useful thing to add. That would be a real lifecycle bug.

  8. yethranayeh commented on Nov 7, 2026

    @yethranayeh

    Reproduced on 2.2.6

    Two locations stay loaded with no client attached and both are pinned by sessions from Oct 28 that the service still reports as running in /api/session/active, with time.busy set at service start.

    The agent checked and said:

    Each is waiting on an unanswered shell permission request, and the tool part is persisted as status: "running", executed: false.

    I don't know how I ended up wtih this kind of case where my clients for these directories were closed but they still require a permission request somehow.

    Apparently, this is the root cause from source for my case, per my agent's reply:

    location-activity.ts treats a location with an active session as occupied and skips eviction. In the current log, 14 locations have location services evicted, and these two never do, while other locations in the same service evict normally.

  9. m21-cerutti commented on Nov 14, 2026

    @m21-cerutti

    Adding the remaining gaps from #63964 (closed as a duplicate of this). The per-server pool option now covers part of this request, so I'm listing only what it doesn't.

    What pool: true doesn't cover yet

    • Scope is all-or-nothing. There is no way to say "one process for everything", "one per project" or "one per session". Pooling only happens when the full declaration matches, including a fixed cwd such as "~". With no cwd, each project folder still gets its own copy and nothing says so.
    • No lazy or idle behaviour for shared servers. A pooled connection still starts at location boot. It would be useful if it started on first use and stopped after an idle timeout, not only when the last directory closes. This pairs with [FEATURE]: Spawn MCP servers on demand (first tool use) instead of eagerly at session start #53028.
    • Diagnostics. opencode mcp list should show each server's scope, whether pool took effect (and why not), and how many locations share it.

    Two related problems

    Suggested next step

    • Keep pool as the opt-in, and add a documented scope value (global | project | session) behind it. The ownership key stays "identical effective declaration", as discussed above.
  10. DarkLicornor commented on Nov 17, 2026

    @DarkLicornor

    Adding reproduction data from Linux (opencode v2.1.3, CachyOS, kernel 6.x), measured on a live opencode serve --service process.

    Scale of the multiplication

    The service log recorded 592 location services booted events across 22 distinct working directories (/home/alexa alone: 179), against 525 location services evicted. At the time of measurement, 7 location instances were still holding live MCP sets.

    Process footprint at that point:

    • 7 location groups x 4 local stdio MCP servers (md, lsp, skills, playwright, codebase-memory minus one) = 28 server process groups
    • 54 opencode-owned processes total
    • 5.61 GB RSS across the tree
    • main server process alone: 1.8 GB RSS, 38% CPU steady on the single JS thread
    • 1167 inotify watches registered

    pool: true does not help on v2.1.3

    The config already sets "pool": true on md, skills, playwright and codebase-memory, each with a fixed "cwd". The duplication persisted anyway, because pool landed in 33d52e6011 (2026-11-04, PR #61185) and v2.1.3 predates it. The pool key is absent from the v2.1.3 binary's config schema entirely - a malformed/unknown value is silently ignored, so there is no warning that the mitigation is inert.

    Bisection isolating the cause

    An isolated server was started with plugins, MCP and instructions progressively enabled:

    Configuration CPU RSS
    No plugins, no MCP, no instructions 5% 137 MB
    + stasi plugin 8.2% -
    + opencode-use plugin 7.5% -
    + cmon plugin 7.1% -
    + full MCP config 5% -
    + real plugins dir via autodiscovery 4% -

    A client then completed a prompt against the isolated server at 0.7-4.5% CPU with 924 inotify watches. The cost is the per-location MCP process sets and the accumulated location instances - not plugins, not the client, and not the network (opencode.ai, api.openai.com and models.dev all had 66-129 ms TTFB during the same window).

    Secondary effect: watcher churn

    watcher subscribe fired 40,141 times against 81 stops. refresh() in packages/core/src/config/plugin/skill.ts:151 calls FiberMap.clear(watches) and then re-subscribes to every path, so each filesystem event recreates the entire watch set. Hot paths were ~/.agents/skills (618 subscriptions), ~/.config/opencode/plugins (618) and ~/.config/opencode/skills (104).

    Requested

    • Confirm whether pool: true is expected to work on v2.1.x, or whether it should be rejected with a warning rather than silently ignored so users on older builds can tell that the mitigation is inactive.
    • Consider capping or evicting MCP process sets for location nodes that are no longer active, and reuse watchers instead of clearing and re-subscribing the full path set on every event.

    🤖 AI-generated.

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

Metadata

Metadata

Assignees

Labels

2.0bugcoreperf

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions