Skip to content

agentHost: route MCP auth during session initialization - #334593

Merged
Paul (pwang347) merged 4 commits into
mainfrom
pwang/mcp-auth-initialization-race
Sep 8, 2026
Merged

Paul (pwang347) merged 4 commits into
mainfrom
pwang/mcp-auth-initialization-race

Conversation

@pwang347

@pwang347 Paul (pwang347) commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #329223

Root cause

The Copilot runtime intentionally keeps host-injected MCP bearer tokens session-scoped: the embedding host owns refresh, revocation, persistence, and per-server consent. Agent Host therefore has to deliver the workbench's persisted grant to every SDK session that challenges.

Two races could lose that delivery:

  1. A CopilotAgentSession can issue onMcpAuthRequest while initializeSession() is still running. The session was added to _chatEntriesBySdkId only after initialization completed, while handleAuthenticationToken() searched only that live map.
  2. Workbench silent MCP authentication coalesced by server identity across sessions. A session challenging after the shared operation's host-side fan-out had been snapshotted reused the promise but did not perform its own delivery.

Before/after evidence

Before — shipped Insiders, pre-fix

A real new Agent Host chat on the affected build immediately challenged again for an MCP whose VS Code authentication session and access grant already existed:

[Copilot:<new-session>] MCP server 'vscode-slack' requires authentication for https://mcp.slack.com
[AgentHost] MCP authentication succeeded for vscode-slack

The same startup trace contained repeated requires authentication → renderer token-delivery pairs for other previously authorized MCPs. This shows that persistence was intact in the workbench, but the token still had to be recovered again for each new SDK session—and could be lost in the initialization/coalescing races above.

After — this branch

Real signed-in Slack OAuth E2E

I loaded an isolated plugin containing only the github-slack MCP definition, authorized it once through the real Slack browser OAuth flow, and then started two brand-new Agent Host sessions. Isolating the definition prevents a second Slack client registration from changing the provider identity during the test.

Before the one-time authorization, VS Code correctly showed the server as requiring authentication. After authorization, both later sessions completed without an auth card, browser redirect, or other user interaction, and the server remained running:

Before one-time authorization After authorization and two new sessions
github-slack requires authentication github-slack remains running

The two later sessions are visible here as separate completed chats:

Two new sessions completed without another MCP authentication prompt

Each new SDK session still issued its expected session-scoped challenge. The workbench silently resolved that challenge from the persisted grant, and Slack reached connected (ready) in 326 ms and 350 ms respectively:

Session 1
08:30:55.171 MCP server 'github-slack' requires authentication
08:30:55.176 [AgentHost] MCP authentication succeeded for github-slack
08:30:55.497 MCP server 'github-slack' connected (ready)

Session 2
08:32:34.101 MCP server 'github-slack' requires authentication
08:32:34.123 [AgentHost] MCP authentication succeeded for github-slack
08:32:34.451 MCP server 'github-slack' connected (ready)

The separate workspace-local vscode-automation-mcp error visible in the server list is unrelated to this test; the isolated test target is github-slack.

Deterministic lifecycle regression coverage

The regression tests start real CopilotAgent chat creation/resume paths with the fake SDK blocked inside onMcpAuthRequest, then deliver the persisted token through the real Agent Host authentication service:

  • Two concurrently initializing new chats both receive { kind: 'token', accessToken: 'mcp-token' } and both become live from one host-side fan-out.
  • A later new chat performs its own persisted-token delivery instead of sharing an already-completed cross-session operation.
  • Provisional materialization, default cold resume, and peer-chat resume all receive the token before registration completes.
  • Insufficient scopes are rejected.
  • Shutdown while blocked on authentication, and shutdown during post-initialization metadata work, both cancel without registering or leaking the session.
  • Workbench coverage verifies two simultaneous sessions perform two target deliveries while the existing provider-level sequencer still serializes authentication-provider access.

Observed fixed-run result:

CopilotAgent — MCP authentication during session initialization
  7 passing

AgentHostChatContribution — mcp auth prompt
  5 passing

That final lifecycle matrix passed 30/30 repeated executions. No interactive Authenticate path is used in these successful cases.

Change

  • Track every Copilot session in a DisposableSet from SDK initialization until atomic ownership transfer to the live-session map.
  • Centralize all four initializeSession() paths in one initialize/register helper so future paths cannot bypass tracking.
  • Keep final client and working-directory validation synchronous with registration.
  • Dispose initialization-blocked sessions during shutdown and reject registration when shutdown already removed ownership.
  • Scope workbench silent-auth coalescing by URI comparison identity for the target session, so every session independently delivers its persisted grant while provider setup remains serialized by the existing authentication sequencer.
  • Add production-path coverage for concurrent immediate creation, later repeated delivery, provisional materialization, default cold resume, peer resume, scope mismatch, authentication-blocked shutdown, and shutdown during post-initialization metadata work.

No protocol, SDK/runtime token-storage, token refresh, scope, consent, or revocation semantics are changed.

Validation

  • npm run typecheck-client
  • Targeted ESLint on all changed files
  • npm run hygiene (full repository)
  • copilotAgent.test.ts: 363 passing, 1 pending
  • CopilotAgentSession MCP inventory: 27 passing
  • Agent service authentication suite: 12 passing
  • Agent Host MCP auth-prompt suite: 5 passing
  • Agent Host service graph: 6 passing
  • Final MCP lifecycle matrix: 30/30 repeated executions passed
  • Copilot Agent Host E2E replay, run twice after the final lifecycle changes: 177 passing, 21 pending on each run
  • Real signed-in Slack OAuth E2E: one interactive authorization followed by two independent sessions with silent persisted-token delivery and connected (ready) in 326 ms and 350 ms
  • Full Agent Host E2E replay: Copilot and Codex passed. Two conformance changeset failures and one Claude fixture mismatch were reproduced unchanged from a clean origin/main worktree.
  • GitHub CI: all jobs passed after rerunning the macOS Electron job, including the full Windows, Linux, and macOS Electron matrices.
  • Azure product build 471451: succeeded across every stage after retrying only the flaky macOS Electron job and its downstream-canceled Windows Electron job. Quality, Copilot, Linux, Windows, macOS, browser, remote, CLI, Electron, node_modules, and SDL checks are all green.
  • Final focused code review: no introduced issues or release blockers

The public AHP E2E harness cannot inject authenticate while createSession is still in flight, so the exact race is covered at the strongest deterministic layer: real CopilotAgent create/resume paths with the SDK auth callback blocked until Agent Host delivers the token.

Track initializing Copilot sessions so host-supplied MCP tokens reach pending SDK authentication callbacks before live-session registration. Dispose tracked sessions during shutdown to unblock initialization.

Co-authored-by: Copilot <[email protected]>
Copilot AI balanced review requested due to automatic review settings September 4, 2026 19:30

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Regression coverage must exercise a real create/resume path to prevent recurrence.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review tier: Balanced
Findings: 1 Medium severity

New issues introduced by this change (1)
Severity Finding
Medium severity src/​vs/​platform/​agentHost/​test/​node/​copilotAgent.test.ts — This regression test calls _withInitializingSession directly, so it would still pass if any (or…
What changed in this PR

Routes MCP authentication tokens to Copilot sessions during initialization and improves shutdown cleanup.

Changes:

  • Tracks initializing sessions for token routing.
  • Disposes or rejects sessions during shutdown.
  • Adds authentication and cleanup regression tests.
File Description
src/​vs/​platform/​agentHost/​test/​node/​copilotAgent.test.ts Adds regression tests, but does not exercise the production create/resume paths.
src/​vs/​platform/​agentHost/​node/​copilot/​copilotAgent.ts Adds initializing-session lifecycle management and token routing.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Centralize session initialization and registration so new call paths cannot bypass MCP auth routing. Exercise concurrent create, provisional materialization, default and peer resume, scope rejection, and shutdown through real CopilotAgent paths.

Co-authored-by: Copilot <[email protected]>
Paul Wang and others added 2 commits September 4, 2026 14:55
Keep initializing sessions owned and routable until atomic registration, and scope silent MCP authentication coalescing to each session so later challenges receive their own token delivery. Add create, materialize, resume, peer, concurrency, and shutdown regression coverage.

Co-authored-by: Copilot <[email protected]>
Use resource-aware session identity for silent auth coalescing and make the pre-registration lifecycle phase explicit.

Co-authored-by: Copilot <[email protected]>
@pwang347
Paul (pwang347) marked this pull request as ready for review September 8, 2026 17:44
@pwang347
Paul (pwang347) merged commit 405fbfc into main Sep 8, 2026
84 of 85 checks passed
@pwang347
Paul (pwang347) deleted the pwang/mcp-auth-initialization-race branch September 8, 2026 18:33
@vs-code-engineering vs-code-engineering Bot added this to the 1.138.0 milestone Sep 8, 2026
@vs-code-engineering vs-code-engineering Bot locked and limited conversation to collaborators Oct 24, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP authentication required for every new session

4 participants