Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
e4d4f24
feat(sdk): add host-facing authenticateMcpServer for OAuth MCP servers
AdityaxDeore Nov 9, 2026
f69b84c
fix(sdk): address CodeRabbit review on authenticateMcpServer (#2493)
AdityaxDeore Nov 9, 2026
377c897
fix(sdk): address CodeRabbit round-2 review on authenticateMcpServer …
AdityaxDeore Nov 9, 2026
672c580
fix(sdk): address CodeRabbit round-3 review on authenticateMcpServer …
AdityaxDeore Nov 9, 2026
24f1088
test(sdk): cover the fence-after-settle and failed-reconnect outcomes…
AdityaxDeore Nov 9, 2026
11cba9d
fix(sdk): address CodeRabbit round-4 review on authenticateMcpServer …
AdityaxDeore Nov 9, 2026
129fb79
test(sdk): keep mocked init transparent to init.cache patches (#2493)
AdityaxDeore Nov 15, 2026
4b5cb57
fix(skills): evict the cancelled skill-read result before a retry (#2…
AdityaxDeore Nov 17, 2026
70e652e
fix(sdk): replace tools by exact server ownership in every auth outco…
AdityaxDeore Nov 17, 2026
ca6b111
fix(sdk): run pre-turn MCP work in the session's SDK context (#2493)
AdityaxDeore Nov 17, 2026
a77b7d8
fix(sdk): make the host's process-initialization wait abortable (#2493)
AdityaxDeore Nov 17, 2026
72593d0
fix(sdk): capture the host flow's credential identity before initiali…
AdityaxDeore Nov 17, 2026
ec45081
fix(sdk): keep surviving shared discovery inside its originating cred…
AdityaxDeore Nov 17, 2026
00c3ab9
fix(sdk): track live owners through the connection-cancellation lifec…
AdityaxDeore Nov 17, 2026
20ffdd1
test(mcp): update XAA scope-entry counts for the P1 initial-reads sco…
AdityaxDeore Nov 17, 2026
0a212e5
fix(sdk): satisfy typecheck for the abortable-init race and discovery…
AdityaxDeore Nov 17, 2026
69c64de
chore(mcp): keep the acquire-id_token comment with its call (#2493)
AdityaxDeore Nov 17, 2026
b9008d8
fix(mcp): register the stalled stdio closer once the wrapper supplies…
AdityaxDeore Nov 17, 2026
bb8c622
Merge upstream main into feat/2294-sdk-mcp-oauth-authenticate
AdityaxDeore Nov 18, 2026
c8bfee5
Bind host reconnect discovery to the actual server connection
AdityaxDeore Nov 18, 2026
8ec9d40
Replace a stale remote authenticate tool with the OAuth recovery tool
AdityaxDeore Nov 18, 2026
80c20e8
Honor the session environment during host-triggered MCP setup
AdityaxDeore Nov 18, 2026
f0c3509
Describe host completion and next-turn status consistently
AdityaxDeore Nov 18, 2026
d4ff835
Keep a live reconnect waiter when the creator cancels before transpor…
AdityaxDeore Nov 18, 2026
96e6e56
Release the correct connection after host cancellation / failed tool …
AdityaxDeore Nov 18, 2026
6ecdee4
Keep surviving discovery requests in the originating credential names…
AdityaxDeore Nov 18, 2026
d6b5464
Add regression tests for the jatmn review round (PR #2493)
AdityaxDeore Nov 18, 2026
4b44121
Fix CodeRabbit review round on PR #2493
AdityaxDeore Nov 18, 2026
58c3dd4
Add regression tests for the CodeRabbit review round (PR #2493)
AdityaxDeore Nov 18, 2026
0379acb
fix(mcp): record settled connects and adopt them synchronously (CodeR…
AdityaxDeore Nov 18, 2026
55cb215
test(mcp): regression for settled-connect adoption vs release
AdityaxDeore Nov 18, 2026
1c7c9d1
fix(sdk): snapshot session env, guard registration, fix win32 env del…
AdityaxDeore Nov 18, 2026
851516f
test(sdk): regression tests for CodeRabbit #2493 reviews 5952738851 a…
AdityaxDeore Nov 18, 2026
de0cdd0
fix(sdk): address CodeRabbit review 5955577457 (join assertions, win3…
AdityaxDeore Nov 18, 2026
bbc2521
test(sdk): regression tests for CodeRabbit #2493 reviews 5956557301 a…
AdityaxDeore Nov 18, 2026
b992165
fix(sdk): address CodeRabbit review 5956557301 and Copilot 5955514041…
AdityaxDeore Nov 18, 2026
8b4e5c4
test(sdk): regression tests for CodeRabbit #2493 review 5957362782 (r…
AdityaxDeore Nov 18, 2026
d9c8f10
fix(sdk): address CodeRabbit review 5957362782 (session-owned transpo…
AdityaxDeore Nov 18, 2026
447c95a
fix(sdk): address CodeRabbit review 5961865068 (ownership-aware MCP c…
AdityaxDeore Nov 18, 2026
10660a9
test(sdk): regression tests for CodeRabbit #2493 review 5961865068 (i…
AdityaxDeore Nov 18, 2026
5094d4b
fix(sdk): address jatmn, CodeRabbit and CodeQL follow-ups on MCP auth
AdityaxDeore Nov 18, 2026
cfc54fc
test(sdk): regression tests for MCP auth review follow-ups
AdityaxDeore Nov 18, 2026
9b7903c
fix(sdk): address CodeRabbit #2493 review 5966435933
AdityaxDeore Nov 19, 2026
e54aca1
Merge upstream/main into feat/2294-sdk-mcp-oauth-authenticate
AdityaxDeore Nov 19, 2026
7c69566
test(sdk): strengthen abort-discovery and setup-join tests per CodeRa…
AdityaxDeore Nov 19, 2026
0e94650
fix(sdk): honor host abort before installing MCP clients or submittin…
AdityaxDeore Nov 19, 2026
3ee8b13
fix(sdk): address CodeRabbit #2493 review leftovers (reconnect owner …
AdityaxDeore Nov 19, 2026
20eef78
fix(sdk): scope MCP task index by SDK client so one generation's fail…
AdityaxDeore Nov 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/entrypoints/sdk.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,23 @@ export interface SDKSession {
close(): void
/** Respond to a pending permission prompt. */
respondToPermission(toolUseId: string, decision: PermissionResult): void
/**
* Start the OAuth flow for one of the session's MCP servers and await it.
* The authorization URL is delivered to `options.onAuthorizationUrl` as
* soon as it is known; the returned promise resolves once the flow settles
* and the server has been reconnected, with the server's new status.
* Only `http`/`sse` servers support this. Closing the session aborts an
* in-flight flow.
*/
authenticateMcpServer(
name: string,
options?: {
/** Called with the authorization URL as soon as it is known. */
onAuthorizationUrl?: (url: string) => void
/** Abort this sign-in without closing the session. */
signal?: AbortSignal
},
): Promise<McpServerStatus>
}

// ============================================================================
Expand Down
235 changes: 235 additions & 0 deletions src/entrypoints/sdk/mcpNeedsAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import { join } from 'node:path'

import { snapshotEnv } from '../../test/envSnapshot.js'
import type { McpAuthOutput } from '../../tools/McpAuthTool/McpAuthTool.js'
import type { MCPServerConnection } from '../../services/mcp/types.js'
import type { Tool } from '../../Tool.js'
import type { SDKSession } from './v2.js'
import {
getClaudeConfigHomeDirOverrideForTesting,
setClaudeConfigHomeDirForTesting,
Expand Down Expand Up @@ -99,6 +101,7 @@ mock.module('../../services/mcp/client.js', () => ({
}))

const { connectSdkMcpServers } = await import('./permissions.js')
const { unstable_v2_createSession } = await import('./v2.js')

let server: ReturnType<typeof Bun.serve> | null = null
let configHome = ''
Expand All @@ -122,6 +125,8 @@ let heldExchange: {
let heldMetadata: { arrived: boolean; answer: () => void; answered: Promise<void> } | null = null
/** Every session a test opens; teardown closes them, whatever the test did. */
const sessions: AbortController[] = []
/** SDK sessions a proposal-2 test opens; teardown closes them. */
const sdkSessions: SDKSession[] = []

/**
* A server that asks to be signed into, and answers the discovery the MCP
Expand Down Expand Up @@ -405,6 +410,7 @@ beforeEach(async () => {

afterEach(async () => {
for (const session of sessions.splice(0)) session.abort()
for (const sdkSession of sdkSessions.splice(0)) sdkSession.close()
heldExchange?.answer()
heldExchange = null
heldMetadata?.answer()
Expand Down Expand Up @@ -1227,3 +1233,232 @@ test.each(['success', 'sibling-error', 'close', 'discard', 'sibling-error-close'
expect(status).toBe(outcome.endsWith('close') || outcome.endsWith('discard') ? undefined : 200)
} finally { root.abort(); await Promise.all(flows) }
}, 30_000)

// ============================================================================
// Proposal 2 (#2294): a host-facing way to start the OAuth flow, know when
// authorization finished, and reconnect afterwards.
// ============================================================================

/** An SDK session holding the gated server, before any turn. */
function openGatedSession(url: string): SDKSession {
const session = unstable_v2_createSession({
cwd: process.cwd(),
mcpServers: { gated: { type: 'http', url } },
})
sdkSessions.push(session)
return session
}

/**
* REPRO: the session reports needs-auth in system:init and offers the host
* no way to act — no method to start the flow, await it, or reconnect.
* Fails until authenticateMcpServer exists on SDKSession.
*/
test('THE SESSION OFFERS A HOST-FACING authenticateMcpServer METHOD', async () => {
const url = serveNeedingAuth()
const session = openGatedSession(url)

expect(typeof (session as unknown as { authenticateMcpServer?: unknown }).authenticateMcpServer).toBe('function')
}, 30_000)

/** An SDK session holding arbitrary servers, before any turn. */
function openSessionWith(mcpServers: Record<string, unknown>): SDKSession {
const session = unstable_v2_createSession({ cwd: process.cwd(), mcpServers })
sdkSessions.push(session)
return session
}

/** An engine that records what the session swaps into it, and does nothing else. */
function recordingEngine() {
const calls: { setMcpClients: MCPServerConnection[][]; updateTools: Tool[][] } = {
setMcpClients: [],
updateTools: [],
}
const engine = {
// Everything the session touches on an engine, doing nothing.
injectAgents: () => {},
setMcpClients: (clients: MCPServerConnection[]) => {
calls.setMcpClients.push([...clients])
},
updateTools: (tools: Tool[]) => {
calls.updateTools.push([...tools])
},
getMcpClients: () => calls.setMcpClients.at(-1) ?? [],
getMessages: () => [],
interrupt: () => {},
submitMessage: async function* (): AsyncGenerator<never> {},
}
return { engine, calls }
}

/** Swap a session's engine for a recording one, as v2.sessionEnvTurn does. */
function recordEngine(session: SDKSession) {
const recorded = recordingEngine()
;(session as unknown as { setEngine: (engine: unknown) => void }).setEngine(recorded.engine)
return recorded.calls
}

/**
* The whole point: a host with a "Sign in" button gets the URL, the user
* finishes in the browser, and the same session — no new session, no new
* turn — ends up with the server's real tools.
*/
test('authenticateMcpServer DELIVERS THE URL, AWAITS THE FLOW, AND RECONNECTS IN PLACE', async () => {
const url = serveNeedingAuth()
const session = openGatedSession(url)

const seenUrls: string[] = []
const done = session.authenticateMcpServer('gated', {
onAuthorizationUrl: seen => seenUrls.push(seen),
})
await waitFor(() => seenUrls.length > 0)
expect(seenUrls[0]).toStartWith(new URL('/authorize', url).toString())

// The browser's last step: the provider redirects back with a code.
expect((await fetch(callbackFor(seenUrls[0]!))).status).toBe(200)

const status = await done
expect(status.name).toBe('gated')
expect(status.status).toBe('connected')
expect(status.serverInfo).toEqual({ name: 'gated', version: '1' })
expect(status.tools?.map(tool => tool.name)).toEqual(['hello'])
expect(reconnects).toBe(1)
expect(storedAccessTokens()).toEqual([`token-for-${clientOf({ authUrl: seenUrls[0] } as McpAuthOutput)}`])
}, 30_000)

/**
* The swap itself: the reconnected client replaces the needs-auth one, and
* the tool pool drops the authenticate pseudo-tool for the real tools.
* Observed through a recording engine — no provider is needed to see it.
*/
test('authenticateMcpServer SWAPS THE CLIENT AND THE REAL TOOLS INTO THE SESSION', async () => {
const url = serveNeedingAuth()
const session = openGatedSession(url)
const calls = recordEngine(session)

const seenUrls: string[] = []
const done = session.authenticateMcpServer('gated', {
onAuthorizationUrl: seen => seenUrls.push(seen),
})
await waitFor(() => seenUrls.length > 0)
expect((await fetch(callbackFor(seenUrls[0]!))).status).toBe(200)
const status = await done
expect(status.status).toBe('connected')

// At connect time the pool held the authenticate pseudo-tool, not hello.
expect(calls.updateTools.length).toBeGreaterThanOrEqual(2)
const atConnect = calls.updateTools[0]!.map(tool => tool.name)
expect(atConnect).toContain('mcp__gated__authenticate')
expect(atConnect).not.toContain('mcp__gated__hello')
// After the reconnect the pool holds the real tool, not the pseudo-tool.
const afterReconnect = calls.updateTools.at(-1)!.map(tool => tool.name)
expect(afterReconnect).toContain('mcp__gated__hello')
expect(afterReconnect).not.toContain('mcp__gated__authenticate')
// And the client list the next turn's system:init is built from holds the
// connected client, not the needs-auth one.
const clients = calls.setMcpClients.at(-1)!
expect(clients.map(client => [client.name, client.type])).toEqual([['gated', 'connected']])
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}, 30_000)

/** A name the session never configured is a host error, not a connection outcome. */
test('authenticateMcpServer REJECTS AN UNKNOWN SERVER', async () => {
const url = serveNeedingAuth()
const session = openGatedSession(url)

await expect(session.authenticateMcpServer('nope')).rejects.toThrow('Server not found: nope')
expect(reconnects).toBe(0)
}, 30_000)

/** In-process SDK tools have no OAuth flow to start. */
test('authenticateMcpServer REJECTS A SERVER WITHOUT AN OAUTH TRANSPORT', async () => {
const session = openSessionWith({ local: { type: 'sdk', name: 'local', tools: [] } })

await expect(session.authenticateMcpServer('local')).rejects.toThrow(
'Server type "sdk" does not support OAuth authentication',
)
expect(reconnects).toBe(0)
}, 30_000)

/**
* Asking again replaces the first attempt rather than racing it — same rule
* as the authenticate tool and cli/print.ts mcp_authenticate, for the same
* reason: each attempt registers its own client, and the first one left
* running would exchange its code with the second's client.
*/
test('ASKING AGAIN SUPERSEDES THE EARLIER ATTEMPT, AND THE NEW ONE COMPLETES', async () => {
const url = serveNeedingAuth()
const session = openGatedSession(url)

const firstUrls: string[] = []
const secondUrls: string[] = []
const first = session.authenticateMcpServer('gated', {
onAuthorizationUrl: seen => firstUrls.push(seen),
})
// A handler now, not after the second call: the supersede rejects this
// while the test is still waiting for the second URL, and a rejection
// with no handler yet is an unhandled error. (A plain .catch, as the
// file does for background flows — expect().rejects attached this early
// hangs the runner.)
const firstRejected = first.catch(() => 'caught')
await waitFor(() => firstUrls.length > 0)
const second = session.authenticateMcpServer('gated', {
onAuthorizationUrl: seen => secondUrls.push(seen),
})
await waitFor(() => secondUrls.length > 0)
expect(secondUrls[0]).not.toBe(firstUrls[0])

// The first link no longer leads anywhere, and its promise rejects.
await expect(firstRejected).resolves.toBe('caught')
await expect(fetch(callbackFor(firstUrls[0]!))).rejects.toThrow()
expect(storedAccessTokens()).toEqual([])

// The second does, with the client it was issued to.
expect((await fetch(callbackFor(secondUrls[0]!))).status).toBe(200)
const status = await second
expect(status.status).toBe('connected')
expect(storedAccessTokens()).toEqual([`token-for-${clientOf({ authUrl: secondUrls[0] } as McpAuthOutput)}`])
expect(refusedExchanges).toBe(0)
}, 30_000)

/**
* Closing the session stops the flow, as the authenticate tool's does: the
* callback listener goes away, nothing is stored, nothing reconnects.
*/
test('CLOSING THE SESSION ABORTS AN IN-FLIGHT FLOW', async () => {
const url = serveNeedingAuth()
const session = openGatedSession(url)

const seenUrls: string[] = []
const done = session.authenticateMcpServer('gated', {
onAuthorizationUrl: seen => seenUrls.push(seen),
})
await waitFor(() => seenUrls.length > 0)

session.close()

await expect(done).rejects.toThrow()
// The user finishing in the browser after close reaches nothing.
await expect(fetch(callbackFor(seenUrls[0]!))).rejects.toThrow()
expect(storedAccessTokens()).toEqual([])
expect(reconnects).toBe(0)
}, 30_000)

/**
* A flow that fails — here the stand-in refuses the code exchange — rejects
* instead of resolving with a status, and leaves nothing half-connected.
*/
test('A FAILED EXCHANGE REJECTS, AND NOTHING RECONNECTS', async () => {
const url = serveNeedingAuth(true)
const session = openGatedSession(url)

const seenUrls: string[] = []
const done = session.authenticateMcpServer('gated', {
onAuthorizationUrl: seen => seenUrls.push(seen),
})
await waitFor(() => seenUrls.length > 0)
expect((await fetch(callbackFor(seenUrls[0]!))).status).toBe(200)

await expect(done).rejects.toThrow()
expect(storedAccessTokens()).toEqual([])
expect(reconnects).toBe(0)
}, 30_000)
Loading