Skip to content

perf: create McpContext on the first tool call - #3568

Merged
yulunz merged 1 commit into
mainfrom
perf/lazy-mcp-context
Nov 25, 2026
Merged

yulunz merged 1 commit into
mainfrom
perf/lazy-mcp-context

Conversation

@yulunz

@yulunz yulunz commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #3427

Lazy loading: server startup part d (parts a–c merged in #3563–#3566). Deferring McpContext until the first tool call removes the last static startup path from the server and daemon entrypoints to third_party/browser.js.

Idle memory footprint (before vs. after)

Measured on release builds (npm run profile:footprint, 3000 ms settle time after initialize + tools/list) on LTS Node.js releases:

  • Ubuntu x64 CI (test-memory-leaks.yml, Node 22 LTS, 3 launches):
Configuration Metric Before (main) After (this PR) Delta
default (--usage-statistics) Processes 1 1 0
default (--usage-statistics) Private 93.06 MiB 40.20 MiB -52.86 MiB (-56.8%)
no-usage-statistics (--no-usage-statistics) Processes 1 1 0
no-usage-statistics (--no-usage-statistics) Private ~91.6 MiB 34.68 MiB ~-56.9 MiB (-62.1%)
  • Local Linux x64 (Node v24.12.0 LTS, 5 launches, --ignore-budgets):
    • default: RSS 98.54 MiB, PSS 71.41 MiB, Private 48.07 MiB (down from 103.09 MiB private before lazy McpContext, -55.02 MiB / -53.4%).
    • no-usage-statistics: RSS 92.11 MiB, PSS 66.14 MiB, Private 43.95 MiB (down from 101.61 MiB private, -57.66 MiB / -56.7%).

Tightening the private-memory budgets in scripts/profile/footprint_mcp.ts follows in #3574.

What changed

  • src/index.ts:
    • Imports McpContext only as a type and stops constructing McpContext in McpServer's constructor.
    • A new #ensureContext(), called from #getContext(), rejects immediately when this.#closed is already true before importing ./McpContext.js, loads ./McpContext.js once with a cached dynamic import(), constructs McpContext, and synchronously calls context.setRoots(this.#combinedRoots()) in the same microtask before storing this.#context.
    • #updateRoots() records this.#lastClientRoots = result.roots and calls this.#context?.setRoots(this.#combinedRoots()) if the context exists.
    • #applyConfigLocked() commits nextConfig to this.#config and calls setRoots() / onConfigChanged(previousArgs) only when this.#context has already been created; while idle, a later McpContext.create() reads the committed this.#config and combined roots directly.
    • close() sets this.#closed = true and disposes this.#context if present; if close() occurs while import('./McpContext.js') is in flight, #ensureContext() disposes the newly created context and rejects with MCP server is closed.
    • If importing or creating McpContext rejects, this.#contextPromise is reset to undefined so later tool calls retry.
  • ESLint: eslint.config.js forbids value imports from third_party/browser.js in src/index.ts, src/bin/**/*.ts, and src/daemon/**/*.ts, and forbids value imports from ./McpContext.js in src/index.ts.

Modules now in both bundles

None new.

What still loads browser.js at startup

Nothing: a static walk of the built JS in out/Default/gen/src from both bin/chrome-devtools-mcp-main.js and daemon/daemon.js no longer reaches third_party/browser.js.

Test plan

  • Updated and added unit tests in tests/McpServer.test.ts:
    • creates the context on the first tool call with the navigation limit
    • applies roots updates and config reloads received while idle when the first tool call creates the context
    • creates a single context when two tool calls start concurrently
    • closes without creating or disposing a context when no tool ran
    • rejects tool calls after close without creating a context
    • disposes a context created while the server is closing and rejects the call
    • retries creating the context when a previous creation threw
  • npm run format and full npm run test.

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to check the following:

  1. src/index.ts, #ensureContext(): Reject before the import() when #closed is true, and keep the post-import check for a close() that occurs during the import. The current code loads the browser bundle and constructs McpContext (which calls overrideDevToolsGlobals) after close(), then gives the disposed context to the tool handler.

  2. eslint.config.js: Add a restriction on a value import of ./McpContext.js in src/index.ts, or add a test that walks the static import graph of the two entrypoints. The rule matches only a direct import of third_party/browser.js, so import {McpContext} from './McpContext.js' passes lint and loads the bundle at startup again.

  3. tests/McpServer.test.ts: Add a test that starts two tool calls before the first import() resolves and asserts calledOnceWithExactly on McpContext.create. No test calls the #contextPromise ??= branch with two concurrent callers, and that branch prevents a second context.

  4. tests/McpServer.test.ts, disposes a context created after the server is already closed: Replace sinon.assert.calledOnce(createContext) with calledOnceWithExactly, as the first test does. AGENTS.md requires exact-argument assertions.

@Lightning00Blade
Lightning00Blade force-pushed the perf/lazy-mcp-context branch 2 times, most recently from 3bccb16 to a55a7ce Compare November 23, 2026 13:49
Base automatically changed from refactor/lazy-tool-handler-response to main November 23, 2026 14:33
src/index.ts now imports McpContext only as a type and loads it via a
cached dynamic import on the first #getContext() call, cutting idle
server private memory by ~55%.

Roots updates, config reloads, and close() before any tool call run
without creating McpContext, #ensureContext() rejects immediately when
closed (and disposes and rejects if closed while import() is in flight),
and ESLint now forbids browser.js value imports in src/index.ts,
src/bin/**/*.ts, and src/daemon/**/*.ts as well as ./McpContext.js value
imports in src/index.ts.

Refs #3427
@yulunz
yulunz force-pushed the perf/lazy-mcp-context branch from 0ca4675 to 29533a8 Compare November 24, 2026 19:53
@yulunz

yulunz commented Nov 24, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review! Addressed all 4 items and rebased onto main:

  1. src/index.ts (#ensureContext()): Added a pre-import if (this.#closed) check that rejects immediately with MCP server is closed without loading ./McpContext.js, and updated the post-import if (this.#closed) check (for a close() while import() is in flight) to dispose context and throw new Error('MCP server is closed') instead of returning the disposed context.
  2. eslint.config.js: Added a Server entrypoint (src/index.ts) block restricting value imports from both third_party/browser.js and ./McpContext.js (allowTypeImports: true).
  3. tests/McpServer.test.ts: Added creates a single context when two tool calls start concurrently (starting two callTool invocations before import() resolves and asserting sinon.assert.calledOnceWithExactly(createContext, ...)) and rejects tool calls after close without creating a context (sinon.assert.notCalled(createContext)).
  4. tests/McpServer.test.ts: Updated disposes a context created while the server is closing and rejects the call to assert sinon.assert.calledOnceWithExactly(createContext, ...) and assert.rejects(callPromise, /MCP server is closed/).

@yulunz
yulunz requested a review from OrKoN November 24, 2026 20:06
@yulunz
yulunz added this pull request to the merge queue Nov 25, 2026
Merged via the queue into main with commit 8e9d442 Nov 25, 2026
17 checks passed
@yulunz
yulunz deleted the perf/lazy-mcp-context branch November 25, 2026 13:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants