Skip to content
Open
Show file tree
Hide file tree
Changes from 33 commits
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
7 changes: 7 additions & 0 deletions src/Tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,13 @@ export type Tool<
isOpenWorld?(input: z.infer<Input>): boolean
requiresUserInteraction?(): boolean
isMcp?: boolean
/**
* True only for the local OAuth recovery tool created by
* createMcpAuthTool. A remote server can expose its own tool named
* `authenticate` with the same qualified name and owner metadata, so
* name alone cannot tell them apart — this marker can.
*/
isMcpAuthTool?: boolean
isLsp?: boolean
/**
* When true, this tool is deferred (sent with defer_loading: true) and requires
Expand Down
34 changes: 34 additions & 0 deletions src/entrypoints/sdk.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,40 @@ 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, so the host can open it while the flow runs. The
* returned promise resolves once the flow settles and the server has been
* reconnected, with the server's new status: `status` plus `serverInfo`
* when connected, `error` when the reconnect failed, and the
* model-visible `tools` (with annotations) when connected. A flow that
* completes without a redirect (a cached IdP token signs in silently)
* never calls `onAuthorizationUrl` and still resolves with whatever
* status the reconnect then reports. A reconnect that still does not
* connect resolves with that status instead of rejecting — read `status`
* and `error`. A flow that itself fails, is cancelled, or is superseded
* by a newer call for the same server rejects — including cancellation
* via `interrupt()`, which aborts the SDK root signal the flow listens
* to, closing the session, or the call's own `signal`. The next turn's
* `system:init` carries the same server with only its name and status.
* Only `http`/`sse` servers support this. The flow runs in the
* environment captured when the call starts — the session's `env`
* overrides included, whether the call starts inside a turn or before
* the first one. A call made by `canUseTool` during an
* environment-carrying turn uses that turn's environment, lent rather
* than re-acquired, so the sign-in does not wait on the mutex the turn
* holds.
*/
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
4,640 changes: 4,628 additions & 12 deletions src/entrypoints/sdk/mcpNeedsAuth.test.ts

Large diffs are not rendered by default.

129 changes: 108 additions & 21 deletions src/entrypoints/sdk/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { createMcpAuthTool } from '../../tools/McpAuthTool/McpAuthTool.js'
import { MCPTool } from '../../tools/MCPTool/MCPTool.js'
import type { MCPServerConnection, ScopedMcpServerConfig } from '../../services/mcp/types.js'
import { connectToServer, fetchToolsForClient, getServerCacheKey } from '../../services/mcp/client.js'
import { ClaudeAuthProvider } from '../../services/mcp/auth.js'
import { AuthenticationCancelledError, ClaudeAuthProvider } from '../../services/mcp/auth.js'
import { logError } from '../../utils/log.js'
import type { ActiveCredentialScope, CredentialScope } from '../../services/mcp/credentialScope.js'
import { clearKeychainCache } from '../../utils/secureStorage/macOsKeychainHelpers.js'
Expand Down Expand Up @@ -579,9 +579,53 @@ export function createExternalCanUseTool(
* namespace, so it is dropped on the way in and out, as a reconnect drops it
* before reading fresh credentials.
*/
function captureCredentialScope(runInOriginEnv?: ActiveCredentialScope): CredentialScope {
export function captureCredentialScope(
getOriginScope?: () => ActiveCredentialScope | undefined,
options?: {
signal?: AbortSignal
/**
* Environment to freeze alongside the process environment: a call
* made before the first turn has no turn to lend it the session's
* `env` overrides, so the caller passes them here and the frozen
* namespace is the session's established environment, not ambient.
* A call inside a turn already runs with those overrides applied,
* so overlaying them again changes nothing.
*/
env?: Record<string, string | undefined>
/**
* Queue ahead of regular waiters when the scope re-enters the
* environment mutex: a discovery that survives its caller must get
* the mutex before a session that queued earlier, or the remaining
* pages read that session's environment. Only the surviving
* discovery scope sets this.
*/
priority?: boolean
},
): CredentialScope {
// Captured inside the turn's tool call, where its variables are applied.
const turnEnv = new Map(Object.entries(process.env))
if (options?.env) {
for (const [key, value] of Object.entries(options.env)) {
if (value === undefined) {
// On Windows process.env is case-insensitive, so an override that
// deletes `openclaude_config_dir` must also remove an inherited
// `OPENCLAUDE_CONFIG_DIR` — otherwise the pre-turn scope keeps the
// ambient config home. Other platforms keep exact-key matching.
if (process.platform === 'win32') {
for (const existing of [...turnEnv.keys()]) {
if (existing.toUpperCase() === key.toUpperCase()) turnEnv.delete(existing)
}
}
turnEnv.delete(key)
} else turnEnv.set(key, value)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}
// The turn the call starts in lends its environment; freeze that scope
// now, instead of reading the live turn at resume time — by the time the
// user is back from the browser, another turn may hold the field, and the
// exchange would then run in that turn's namespace. A turn that already
// ended lends nothing, and the scope falls back to the mutex below.
const originScope = getOriginScope?.()
// Initial discovery/registration writes happen before any continuation.
clearKeychainCache()
const set = (key: string, value: string | undefined) => {
Expand All @@ -594,13 +638,23 @@ function captureCredentialScope(runInOriginEnv?: ActiveCredentialScope): Credent
return async work => {
// The query keeps this environment until the borrowed work settles.
// Do not queue behind the same query's still-open input stream.
const owned = runInOriginEnv?.(async () => {
const owned = originScope?.(async () => {
clearKeychainCache()
try { return await work() }
finally { clearKeychainCache() }
})
if (owned) return owned
await acquireEnvMutex()
const { acquired, reason } = await acquireEnvMutex(
options?.signal || options?.priority
? { signal: options.signal, priority: options.priority }
: undefined,
)
if (!acquired) {
if (reason === 'aborted' || options?.signal?.aborted) {
throw new AuthenticationCancelledError()
}
throw new Error('Failed to acquire environment mutex')
}
// What each changed variable was, to put back; recorded before it changes.
const displaced = new Map<string, string | undefined>()
try {
Expand Down Expand Up @@ -634,7 +688,7 @@ function captureCredentialScope(runInOriginEnv?: ActiveCredentialScope): Credent
*/
export async function connectSdkMcpServers(
mcpServers: Record<string, unknown> | undefined,
runInOriginEnv?: ActiveCredentialScope,
getOriginScope?: () => ActiveCredentialScope | undefined,
sessionSignal?: AbortSignal,
): Promise<{ clients: MCPServerConnection[]; tools: Tool[] }> {
if (!mcpServers || Object.keys(mcpServers).length === 0) {
Expand Down Expand Up @@ -729,27 +783,56 @@ export async function connectSdkMcpServers(
if (serverConfig.type === 'http' || serverConfig.type === 'sse') {
const key = getServerCacheKey(name, serverConfig)
const cached = connectToServer.cache.get(key)
if (cached && (await cached).type !== 'connected') {
clearKeychainCache()
if (
await new ClaudeAuthProvider(name, serverConfig).tokens() &&
connectToServer.cache.get(key) === cached
) {
connectToServer.cache.delete(key)
if (cached) {
// Register as a waiter before awaiting the shared pending
// connect: awaiting the cached promise directly would leave
// this caller uncounted, and a creator abort would close a
// transport this session still needs.
const joined = await connectToServer(
name,
serverConfig,
undefined,
sessionSignal,
)
if (joined.type !== 'connected') {
clearKeychainCache()
if (
await new ClaudeAuthProvider(name, serverConfig).tokens() &&
connectToServer.cache.get(key) === cached
) {
connectToServer.cache.delete(key)
}
}
}
}
// Connect to the server
// Note: SDK 'session' scope is not part of internal ConfigScope,
// but connectToServer accepts any object with scope field
const client = await connectToServer(name, scopedConfig as unknown as ScopedMcpServerConfig, {
totalServers: Object.keys(mcpServers).length,
stdioCount: 0,
sseCount: 0,
httpCount: 0,
sseIdeCount: 0,
wsIdeCount: 0,
})
const client = await connectToServer(
name,
scopedConfig as unknown as ScopedMcpServerConfig,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
totalServers: Object.keys(mcpServers).length,
stdioCount: 0,
sseCount: 0,
httpCount: 0,
sseIdeCount: 0,
wsIdeCount: 0,
},
// The session's signal is passed only when joining a connect
// another caller started: closing the session then releases the
// waiter it registered, so a later cancellation can close the
// transport instead of waiting out the connection timeout. A
// fresh connect is owned by the cache, not the session — passing
// the signal would attach the connect's abort listener to it,
// and closing the session would close a transport the next
// session reuses.
connectToServer.cache.get(
getServerCacheKey(name, scopedConfig as unknown as ScopedMcpServerConfig),
) !== undefined
? sessionSignal
: undefined,
)

// If connected, fetch tools
if (client.type === 'connected') {
Expand All @@ -774,7 +857,11 @@ export async function connectSdkMcpServers(
tools: [
createMcpAuthTool(name, scopedConfig as unknown as ScopedMcpServerConfig, {
realToolsInCurrentContext: false,
captureCredentialScope: () => captureCredentialScope(runInOriginEnv),
captureCredentialScope: signal =>
captureCredentialScope(
getOriginScope,
signal ? { signal } : undefined,
),
sessionSignal,
}),
],
Expand Down
2 changes: 1 addition & 1 deletion src/entrypoints/sdk/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ class QueryImpl implements Query {
// Connect MCP servers if provided
if (self.mcpServers && Object.keys(self.mcpServers).length > 0) {
try {
const { clients: mcpClients, tools: mcpTools } = await connectSdkMcpServers(self.mcpServers, runInQueryEnv, self.abortController.signal)
const { clients: mcpClients, tools: mcpTools } = await connectSdkMcpServers(self.mcpServers, () => runInQueryEnv, self.abortController.signal)
self.sdkMcpTools = mcpTools
if (mcpClients.length > 0) {
self.engine.setMcpClients(mcpClients)
Expand Down
96 changes: 70 additions & 26 deletions src/entrypoints/sdk/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,35 @@ export function assertValidSessionId(sessionId: string): void {
export interface MutexAcquireOptions {
/** Maximum time to wait for mutex in milliseconds. Default: no timeout (wait forever). */
timeoutMs?: number
/**
* Abort waiting for the mutex when this signal aborts. A cancelled waiter
* is removed from the queue, so it never acquires the mutex later and a
* later caller is not stuck behind it.
*/
signal?: AbortSignal
/**
* Queue ahead of regular waiters: when the holder releases, a priority
* waiter is picked before any regular waiter that queued earlier. Only
* for a scope that must re-enter its namespace before a competitor that
* queued first — a surviving discovery scope, not a turn or a fresh
* sign-in. At most one priority waiter exists per discovery, and it
* releases once its work settles, so regular waiters cannot starve
* behind it.
*/
priority?: boolean
}

export interface MutexAcquireResult {
/** Whether the mutex was acquired successfully. */
acquired: boolean
/** Reason for failure if not acquired. */
reason?: 'timeout'
reason?: 'timeout' | 'aborted'
}

function createEnvMutexState() {
const queue: Array<() => void> = []
/** Waiters that jump the regular queue when the holder releases. */
const priorityQueue: Array<() => void> = []
let locked = false

async function acquire(
Expand All @@ -76,54 +94,79 @@ function createEnvMutexState() {
return { acquired: true }
}

if (options?.timeoutMs === undefined) {
if (options?.signal?.aborted) {
return { acquired: false, reason: 'aborted' }
}

if (options?.timeoutMs === undefined && options?.signal === undefined) {
// No timeout - wait forever (original behavior for backward compatibility)
return new Promise(resolve => {
queue.push(() => resolve({ acquired: true }))
;(options?.priority ? priorityQueue : queue).push(() => resolve({ acquired: true }))
})
}

// With timeout - race between queue and timeout
// With timeout and/or abort signal - race between queue, timeout and abort
return new Promise(resolve => {
let resolved = false
let callback: () => void

const timeoutId = setTimeout(() => {
if (!resolved) {
resolved = true
// Remove ourselves from the queue to prevent orphaned callback
const index = queue.indexOf(callback)
if (index !== -1) {
queue.splice(index, 1)
const cleanup = () => {
if (timeoutId !== undefined) clearTimeout(timeoutId)
options?.signal?.removeEventListener('abort', onAbort)
}
const settle = (result: MutexAcquireResult) => {
if (resolved) return
resolved = true
cleanup()
// Remove ourselves from the queue so a later release does not wake
// a waiter that already left.
const index = queue.indexOf(callback)
if (index !== -1) {
queue.splice(index, 1)
} else {
const priorityIndex = priorityQueue.indexOf(callback)
if (priorityIndex !== -1) {
priorityQueue.splice(priorityIndex, 1)
}
resolve({ acquired: false, reason: 'timeout' })
}
}, options.timeoutMs)
resolve(result)
}

let timeoutId: ReturnType<typeof setTimeout> | undefined
if (options?.timeoutMs !== undefined) {
timeoutId = setTimeout(
() => settle({ acquired: false, reason: 'timeout' }),
options.timeoutMs,
)
}

const onAbort = () => settle({ acquired: false, reason: 'aborted' })
options?.signal?.addEventListener('abort', onAbort, { once: true })

callback = () => {
if (!resolved) {
resolved = true
clearTimeout(timeoutId)
cleanup()
resolve({ acquired: true })
}
}

queue.push(callback)
;(options?.priority ? priorityQueue : queue).push(callback)
})
}

function release(): void {
if (queue.length > 0) {
const next = queue.shift()
if (next) {
try {
next()
} catch {
// If callback throws, ensure mutex is unlocked so next caller can acquire
// The error is intentionally not propagated - callback errors should not
// block the mutex system. Callers should handle their own errors.
locked = false
}
// A priority waiter is picked before any regular waiter that queued
// earlier; within each queue the order stays FIFO.
const next = priorityQueue.length > 0 ? priorityQueue.shift() : queue.shift()
if (next) {
try {
next()
} catch {
// If callback throws, ensure mutex is unlocked so next caller can acquire
// The error is intentionally not propagated - callback errors should not
// block the mutex system. Callers should handle their own errors.
locked = false
}
} else {
locked = false
Expand All @@ -132,6 +175,7 @@ function createEnvMutexState() {

function reset(): void {
queue.length = 0
priorityQueue.length = 0
locked = false
}

Expand Down
Loading