From 4d49c73e026309d20d45e154cebd80cdbadfad6a Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:12:13 -0600 Subject: [PATCH] fix(core): refresh MCP OAuth tokens before they expire (#63028) --- packages/core/src/credential.ts | 4 +- packages/core/src/mcp/client.ts | 12 +- packages/core/src/mcp/connection.ts | 4 +- packages/core/src/mcp/index.ts | 7 +- packages/core/src/mcp/oauth.ts | 442 +++++------ packages/core/src/mcp/pool.ts | 6 +- packages/core/test/mcp-oauth.test.ts | 1088 ++++++++++++++------------ 7 files changed, 832 insertions(+), 731 deletions(-) diff --git a/packages/core/src/credential.ts b/packages/core/src/credential.ts index ffddc4c6965..d83cc805779 100644 --- a/packages/core/src/credential.ts +++ b/packages/core/src/credential.ts @@ -30,8 +30,8 @@ export type Value = Credential.Value export const Event = Credential.Event /** Whether an access token is due for a refresh. `expires` 0 means the issuer gave no lifetime. */ -export const expiring = (value: OAuth, now: number) => - value.expires !== 0 && value.expires <= now + Duration.toMillis(Duration.minutes(5)) +export const expiring = (value: OAuth, now: number, margin: Duration.Input = Duration.minutes(5)) => + value.expires !== 0 && value.expires <= now + Duration.toMillis(margin) export class Info extends Schema.Class("Credential.Info")({ id: ID, diff --git a/packages/core/src/mcp/client.ts b/packages/core/src/mcp/client.ts index a296770114c..aa2ca866f58 100644 --- a/packages/core/src/mcp/client.ts +++ b/packages/core/src/mcp/client.ts @@ -2,7 +2,9 @@ export * as McpClient from "./client.js" import { pathToFileURL } from "node:url" import { + type AuthProvider, Client, + InsufficientScopeError, OAuthError, OAuthErrorCode, ProtocolError, @@ -20,7 +22,6 @@ import { type ElicitResult, type GetPromptResult, type Implementation, - type OAuthClientProvider, type Prompt, type ReadResourceResult, type Resource, @@ -192,8 +193,8 @@ export interface ConnectOptions { readonly config: typeof ConfigMCP.Server.Type | Attached /** Resolves a relative stdio `cwd` and is the default one, and is the root `roots/list` answers with. */ readonly directory: string - /** Remote only. A provider with no stored token and a no-op redirect ends in UnauthorizedError → needs_auth. */ - readonly authProvider?: OAuthClientProvider + /** Remote only. A 401 the provider cannot recover from ends in UnauthorizedError → needs_auth. */ + readonly authProvider?: AuthProvider readonly elicitation?: ElicitationHandler readonly clientInfo?: Implementation /** False declares no roots and leaves `roots/list` unanswered, for a connection no one directory owns. */ @@ -341,7 +342,7 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { return yield* initialize(transport) } const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js")) - const fetch = yield* McpOAuth.loggedFetch({ server, directory: options.directory }, options.authProvider) + const fetch = yield* McpOAuth.loggedFetch({ server, directory: options.directory }) // Servers that bundle their own Code Mode (Cloudflare and others) expose raw tools when asked // with ?codemode=false, which is what our Code Mode wants. The configured URL stays the OAuth identity. const url = new URL(config.url) @@ -567,7 +568,8 @@ export const connect = Effect.fnUntraced(function* (options: ConnectOptions) { } const error = Cause.squash(exit.cause) - if (error instanceof UnauthorizedError) return yield* new NeedsAuthError({ server, message: error.message }) + if (error instanceof UnauthorizedError || error instanceof InsufficientScopeError) + return yield* new NeedsAuthError({ server, message: error.message }) if (error instanceof UnsupportedProtocolVersionError) return yield* new ConnectError({ server, diff --git a/packages/core/src/mcp/connection.ts b/packages/core/src/mcp/connection.ts index b23b8c989bd..61e3becce20 100644 --- a/packages/core/src/mcp/connection.ts +++ b/packages/core/src/mcp/connection.ts @@ -1,6 +1,6 @@ export * as McpConnection from "./connection.js" -import type { OAuthClientProvider } from "@modelcontextprotocol/client" +import type { AuthProvider } from "@modelcontextprotocol/client" import type { Mcp } from "@opencode/schema/mcp" import { Cause, Effect, Exit, Scope } from "effect" import { FetchHttpClient } from "effect/http" @@ -52,7 +52,7 @@ export interface Input { readonly shared?: boolean readonly clientInfo?: { readonly name: string; readonly version: string } /** Read on every attempt, so a credential change applies to the next one. */ - readonly authProvider: Effect.Effect + readonly authProvider: Effect.Effect readonly elicitation: McpClient.ElicitationHandler /** A stdio server is spawned on this execution plane. */ readonly environment: Environment.Interface diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index ded23718d7e..ab5e294ba70 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -296,12 +296,13 @@ export const layer = (options?: Options) => : Effect.succeed(undefined) const connectProvider = Effect.fnUntraced(function* ( + name: ServerName, entry: ServerEntry, credential: Credential.Info | undefined, ) { if (entry.config.type !== "remote" || !entry.integrationID) return undefined const { McpOAuth } = yield* Effect.promise(() => import("./oauth.js")) - return yield* McpOAuth.connectProvider({ config: entry.config, credential }).pipe( + return yield* McpOAuth.connectProvider({ server: name, config: entry.config, credential }).pipe( Effect.provideService(Credential.Service, credentials), Effect.provideService(FetchHttpClient.Fetch, fetch), ) @@ -397,7 +398,7 @@ export const layer = (options?: Options) => const credential = yield* selectCredential(entry) return { key: McpPool.key({ ...input, credential: credential?.id }), - authProvider: connectProvider(entry, credential), + authProvider: connectProvider(name, entry, credential), } } // Resolved exactly as the spawn resolves it, `~` included, so the key matches where the server runs. @@ -420,7 +421,7 @@ export const layer = (options?: Options) => directory: location.directory, clientInfo: options?.clientInfo, authProvider: Effect.suspend(() => - selectCredential(entry).pipe(Effect.flatMap((credential) => connectProvider(entry, credential))), + selectCredential(entry).pipe(Effect.flatMap((credential) => connectProvider(name, entry, credential))), ), elicitation, environment, diff --git a/packages/core/src/mcp/oauth.ts b/packages/core/src/mcp/oauth.ts index 815fbfbcb9d..fe0972303f9 100644 --- a/packages/core/src/mcp/oauth.ts +++ b/packages/core/src/mcp/oauth.ts @@ -4,23 +4,24 @@ import { auth, LATEST_PROTOCOL_VERSION, checkResourceAllowed, + discoverAuthorizationServerMetadata, discoverOAuthServerInfo, extractWWWAuthenticateParams, + OAuthError, + OAuthErrorCode, parseErrorResponse, + refreshAuthorization, resourceUrlFromServerUrl, UnauthorizedError, + type AuthProvider, type FetchLike, type OAuthClientProvider, type OAuthDiscoveryState, type StoredOAuthClientInformation, type StoredOAuthTokens, } from "@modelcontextprotocol/client" -import { - OAuthMetadataSchema, - OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema, -} from "@modelcontextprotocol/core" -import { Cause, Data, Deferred, Effect, Option, Schema } from "effect" +import { OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema } from "@modelcontextprotocol/core" +import { Cause, Clock, Data, Deferred, Duration, Effect, Option, Schema } from "effect" import { FetchHttpClient } from "effect/http" import type { ServerResponse } from "node:http" import type { AddressInfo } from "node:net" @@ -33,71 +34,29 @@ import { ErrorSummary } from "../util/error-summary.js" /** Client ID Metadata Document: servers that support CIMD accept this URL as the client_id without registration. */ export const CLIENT_METADATA_URL = "https://opencode.ai/oauth/opencode/client.json" -// Refresh tokens rotate, so concurrent refreshes of the same token share one request or the second gets invalid_grant. -const refreshes = new Map>() +// The authorization server refused the refresh token or the client: only a new login helps. +class RefreshRejected extends Data.TaggedError("McpOAuth.RefreshRejected")<{ readonly message: string }> {} -/** Sends one refresh request whose body carries `token`, in place of the in-process share. */ -type Refresh = (send: FetchLike, url: string | URL, init: RequestInit, token: string) => ReturnType +// Discovery named another authorization server than the one that issued the credential. Its tokens are not sent +// there; the credential stays for its own server, and a new login is needed meanwhile. +class IssuerChanged extends Data.TaggedError("McpOAuth.IssuerChanged")<{ readonly message: string }> {} -// Providers backed by a stored credential refresh under its cross-process lock; see connectProvider. -const lockedRefreshes = new WeakMap() +// Like other MCP clients: refreshing this close to expiry leaves short-lived tokens alone until they are due. +const REFRESH_AHEAD = Duration.seconds(30) -const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown)) +const rejections = new Set([ + OAuthErrorCode.InvalidGrant, + OAuthErrorCode.InvalidClient, + OAuthErrorCode.UnauthorizedClient, +]) -class RefreshRejected extends Data.TaggedError("McpOAuth.RefreshRejected")<{ - readonly status: number - readonly headers: Headers - readonly body: string -}> {} - -// The SDK takes a refresh failure it cannot classify (network error, timeout, 5xx) as a lost login and -// starts a new authorization, which a connection reports as needs_auth until the user signs in again. -// temporarily_unavailable is an OAuth error the SDK surfaces as is, so the attempt fails and the -// credential stays for the next one. -const unavailable = (reason: string) => - Response.json( - { error: "temporarily_unavailable", error_description: `Could not refresh the OAuth token: ${reason}` }, - { status: 503 }, - ) - -const refreshKey = (url: string | URL, init: RequestInit | undefined) => { - if (!(init?.body instanceof URLSearchParams) || init.body.get("grant_type") !== "refresh_token") return undefined - return [String(url), init.body.get("client_id") ?? "", init.body.get("refresh_token") ?? ""].join("\u0000") -} - -// Bun's and Node's fetch types both apply here and the SDK's FetchLike wants Bun's Response, so the -// overload is picked by annotation and clone() is pinned to the type it was called on. A tool call -// can stay silent for minutes, so Bun's idle deadline is off; the MCP execution timeout still applies. -const share = (pending: ReturnType) => pending.then((response) => response.clone() as typeof response) - -// Requests use `FetchHttpClient.Fetch`, which an embedder can replace, rather than the global fetch. -const sender = Effect.fnUntraced(function* (refresh?: Refresh) { - const fetch = yield* FetchHttpClient.Fetch - const base: FetchLike = (url, init) => fetch(url, { ...init, timeout: false } as BunFetchRequestInit) - const send: FetchLike = (url, init) => { - const key = refreshKey(url, init) - if (key === undefined) return base(url, init) - if (refresh && init?.body instanceof URLSearchParams) - return refresh(base, url, init, init.body.get("refresh_token") ?? "") - const current = refreshes.get(key) - if (current) return share(current) - const pending = base(url, init).finally(() => { - if (refreshes.get(key) === pending) refreshes.delete(key) - }) - refreshes.set(key, pending) - return share(pending) - } - return send -}) - -/** Pass the connection's provider so a stored credential's refresh runs under the credential lock. */ -export const loggedFetch = ( - fields: { readonly server: string; readonly directory?: string }, - provider?: OAuthClientProvider, -) => +export const loggedFetch = (fields: { readonly server: string; readonly directory?: string }) => Effect.gen(function* () { const run = Effect.runPromiseWith(yield* Effect.context()) - const send = yield* sender(provider && lockedRefreshes.get(provider)) + const fetch = yield* FetchHttpClient.Fetch + // Bun's idle deadline is off because a tool call can stay silent for minutes; the MCP execution timeout still + // applies. Requests use `FetchHttpClient.Fetch`, which an embedder can replace, rather than the global fetch. + const send: FetchLike = (url, init) => fetch(url, { ...init, timeout: false } as BunFetchRequestInit) const request: FetchLike = (url, init) => { const grant = init?.body instanceof URLSearchParams ? init.body.get("grant_type") : undefined const operation = grant === "refresh_token" ? "refresh" : grant === "authorization_code" ? "exchange" : undefined @@ -176,54 +135,31 @@ interface Store { interface Options { readonly config: typeof ConfigMCP.Remote.Type readonly store: Store - readonly fetch: FetchLike - /** Absent on connect: the provider then refuses to register a client or redirect, ending in needs_auth. */ - readonly redirect?: { + readonly redirect: { readonly url: string readonly state: string readonly open: (url: URL) => void | Promise } readonly clientMetadataUrl?: string - readonly discovery?: OAuthDiscoveryState - readonly invalidate?: OAuthClientProvider["invalidateCredentials"] + readonly discovery: OAuthDiscoveryState } const provider = (options: Options): OAuthClientProvider => { const oauth = options.config.oauth || undefined const client = oauth?.client_id ? { client_id: oauth.client_id, client_secret: oauth.client_secret } : undefined const redirect = options.redirect - // A missing redirectUrl selects the client-credentials grant in the SDK, so connect still names one. - const redirectUrl = redirect?.url ?? oauth?.redirect_uri ?? "http://127.0.0.1/callback" - const refuse = (what: string) => new UnauthorizedError(`MCP server "${options.config.url}" requires ${what}`) - const identity = new URL(options.config.url) - identity.hash = "" - let discovery: OAuthDiscoveryState | undefined = options.discovery + let discovery = options.discovery return { - redirectUrl, - discoveryState: async () => { - discovery ??= await configuredDiscovery({ config: options.config, fetchFn: options.fetch }) - return discovery - }, + redirectUrl: redirect.url, + discoveryState: async () => discovery, saveDiscoveryState: (state) => { discovery = state }, - // The SDK sends no RFC 8707 resource when the server publishes no resource metadata; some - // authorization servers require one, so fall back to the configured URL. - validateResourceURL: async (_serverUrl, resource) => { - if (!resource) return identity - if (!checkResourceAllowed({ requestedResource: identity, configuredResource: resource })) - throw new Error(`Protected resource ${resource} does not cover ${identity}`) - const canonical = new URL(resource) - // The transport dials the configured URL with extra query parameters and some servers echo - // that back as the resource. Query is transport detail, not identity: the token stays bound - // to the configured URL so a later refresh names the same resource the login did. - if (canonical.origin === identity.origin && canonical.pathname === identity.pathname) return identity - return canonical - }, + validateResourceURL: async (_serverUrl, resource) => selectResource(options.config, resource), ...(options.clientMetadataUrl ? { clientMetadataUrl: options.clientMetadataUrl } : {}), - ...(redirect ? { state: () => redirect.state } : {}), + state: () => redirect.state, clientMetadata: { - redirect_uris: [redirectUrl], + redirect_uris: [redirect.url], client_name: "opencode", client_uri: "https://opencode.ai", logo_uri: "https://opencode.ai/web-app-manifest-512x512.png", @@ -232,24 +168,17 @@ const provider = (options: Options): OAuthClientProvider => { token_endpoint_auth_method: client?.client_secret ? "client_secret_post" : "none", ...(oauth?.scope ? { scope: oauth.scope } : {}), }, - clientInformation: async () => { - if (client) return client - const stored = await options.store.clientInformation() - if (!stored && !redirect) throw refuse("a login before it can register a client") - return stored - }, + clientInformation: async () => client ?? (await options.store.clientInformation()), saveClientInformation: (info) => options.store.saveClientInformation(info), tokens: () => options.store.tokens(), saveTokens: (tokens) => options.store.saveTokens(tokens), redirectToAuthorization: (url) => { - if (!redirect) throw refuse("user authorization") if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error( `MCP server "${options.config.url}" returned a ${url.protocol} authorization URL; only http and https are supported`, ) return redirect.open(url) }, - ...(options.invalidate ? { invalidateCredentials: options.invalidate } : {}), saveCodeVerifier: (verifier) => options.store.saveCodeVerifier(verifier), codeVerifier: async () => { const verifier = await options.store.codeVerifier() @@ -259,6 +188,22 @@ const provider = (options: Options): OAuthClientProvider => { } } +// The SDK sends no RFC 8707 resource when the server publishes no resource metadata; some +// authorization servers require one, so fall back to the configured URL. +const selectResource = (config: typeof ConfigMCP.Remote.Type, resource: string | undefined) => { + const identity = new URL(config.url) + identity.hash = "" + if (!resource) return identity + if (!checkResourceAllowed({ requestedResource: identity, configuredResource: resource })) + throw new Error(`Protected resource ${resource} does not cover ${identity}`) + const canonical = new URL(resource) + // The transport dials the configured URL with extra query parameters and some servers echo + // that back as the resource. Query is transport detail, not identity: the token stays bound + // to the configured URL so a later refresh names the same resource the login did. + if (canonical.origin === identity.origin && canonical.pathname === identity.pathname) return identity + return canonical +} + const memoryStore = (): Store => { let tokens: StoredOAuthTokens | undefined let client: StoredOAuthClientInformation | undefined @@ -282,160 +227,191 @@ const memoryStore = (): Store => { export const clientFromCredential = (credential: Credential.OAuth) => credential.metadata?.client as StoredOAuthClientInformation | undefined +// Where the login found its authorization server and which resource it named, so a refresh need not discover them. +const Discovery = Schema.Struct({ authorizationServer: Schema.String, resource: Schema.String }) +const decodeDiscovery = Schema.decodeUnknownOption(Discovery) +const discoveryFromCredential = (credential: Credential.OAuth) => + Option.getOrUndefined(decodeDiscovery(credential.metadata?.discovery)) + const toCredential = (input: { readonly methodID: Integration.MethodID readonly serverUrl: string readonly tokens: StoredOAuthTokens readonly client: StoredOAuthClientInformation | undefined + readonly discovery: typeof Discovery.Type | undefined }) => Credential.OAuth.make({ type: "oauth", methodID: input.methodID, access: input.tokens.access_token, refresh: input.tokens.refresh_token ?? "", - // 0 is non-expiring; toTokens then omits expires_in so the SDK does not force a refresh. + // 0 means the server gave no lifetime, so the token is only refreshed after a 401. expires: input.tokens.expires_in ? Date.now() + input.tokens.expires_in * 1000 : 0, metadata: { serverUrl: input.serverUrl, tokenType: input.tokens.token_type, ...(input.tokens.scope ? { scope: input.tokens.scope } : {}), ...(input.tokens.issuer ? { issuer: input.tokens.issuer } : {}), + ...(input.discovery ? { discovery: input.discovery } : {}), ...(input.client ? { client: input.client } : {}), }, }) -const toTokens = (credential: Credential.OAuth): StoredOAuthTokens => { - const metadata = credential.metadata ?? {} - return { - access_token: credential.access, - token_type: typeof metadata.tokenType === "string" ? metadata.tokenType : "Bearer", - ...(credential.refresh ? { refresh_token: credential.refresh } : {}), - ...(credential.expires ? { expires_in: Math.max(0, Math.floor((credential.expires - Date.now()) / 1000)) } : {}), - ...(typeof metadata.scope === "string" ? { scope: metadata.scope } : {}), - ...(typeof metadata.issuer === "string" ? { issuer: metadata.issuer } : {}), - } -} - /** - * A provider for one credential the caller already selected, or none. It never looks up the active credential - * itself: it reads and refreshes only the selected row, and a provider made without one stays anonymous. + * Bearer tokens for one credential the caller already selected, or none. It never looks up the active credential + * itself: it reads and refreshes only the selected row, and one made without a credential stays anonymous. A + * connection never starts a login, so a token the server refuses and cannot be refreshed ends in needs_auth. */ export const connectProvider = Effect.fnUntraced(function* (input: { + readonly server: string readonly config: typeof ConfigMCP.Remote.Type readonly credential: Credential.Info | undefined -}) { - const credentials = yield* Credential.Service - const run = Effect.runPromiseWith(yield* Effect.context()) - const fetch = yield* sender() +}): Effect.fn.Return { const found = input.credential - if (!found || found.value.type !== "oauth") return provider({ config: input.config, store: memoryStore(), fetch }) + // Without onUnauthorized the transport answers a 401 with UnauthorizedError. + if (found?.value.type !== "oauth") return { token: async () => undefined } const id = found.id - const methodID = found.value.methodID - const read = async () => { - const stored = await run(credentials.get(id)) - return stored?.value.type === "oauth" ? stored.value : undefined - } - // Refresh tokens rotate and the row is shared across connections: only drop it while it still holds ours. - let presented = found.value.refresh - // Every process and Location sharing the database refreshes this row one at a time. A caller holding a - // refresh token the row no longer has gets the stored tokens instead of spending it: servers that rotate - // refresh tokens revoke the grant on reuse. - const refresh: Refresh = (send, url, init, token) => - run( - credentials - .refresh(id, { - stale: (current) => current.refresh === token, - refresh: (current) => - Effect.gen(function* () { - // The body is read here so the refresh time limit also covers a server that stalls after its headers. - const { response, body } = yield* Effect.tryPromise({ - try: async (signal) => { - const response = await send(url, { ...init, signal }) - return { response, body: await response.text() } - }, - catch: (error) => error, - }) - const parsed = OAuthTokensSchema.safeParse( - response.ok ? Option.getOrUndefined(decodeJson(body)) : undefined, - ) - if (!parsed.success) - return yield* new RefreshRejected({ status: response.status, headers: response.headers, body }) - // The SDK ignores an issuer in the token response; keep the one this credential was stamped with. - const issuer = current.metadata?.issuer - return toCredential({ - methodID, - serverUrl: input.config.url, - tokens: { - refresh_token: token, - ...parsed.data, - issuer: typeof issuer === "string" ? issuer : undefined, - }, - client: clientFromCredential(current), - }) - }), - }) - .pipe( - Effect.map((value) => - value - ? Response.json(toTokens(value)) - : // The credential was signed out meanwhile; the SDK drops it and reports needs_auth. - Response.json({ error: "invalid_grant" }, { status: 400 }), + const credentials = yield* Credential.Service + const fetchFn = yield* loggedFetch({ server: input.server }) + const run = Effect.runPromiseWith(yield* Effect.context()) + const read = credentials.get(id).pipe(Effect.map((row) => (row?.value.type === "oauth" ? row.value : undefined))) + const refresh = (stale: (current: Credential.OAuth, now: number) => boolean, resourceMetadataUrl?: URL) => + credentials.refresh(id, { + stale, + refresh: (current) => + exchange({ config: input.config, fetchFn, current, resourceMetadataUrl }).pipe( + Effect.tapError((error) => + error instanceof RefreshRejected + ? Effect.logWarning("mcp oauth credential invalidated", { credentialID: id, reason: error.message }).pipe( + Effect.andThen(credentials.remove(id)), + ) + : Effect.void, ), - Effect.catch((error) => { - if (!(error instanceof RefreshRejected)) - return Effect.succeed(unavailable(error instanceof Error ? error.message : String(error))) - if (error.status === 429 || error.status >= 500) return Effect.succeed(unavailable(`HTTP ${error.status}`)) - return Effect.succeed(new Response(error.body, { status: error.status, headers: error.headers })) - }), ), - ) - const result = provider({ - config: input.config, - fetch, - invalidate: async (scope) => { - if (scope === "verifier" || scope === "discovery") return - const oauth = await read() - if (!oauth || oauth.refresh !== presented) return - await run(Effect.logWarning("mcp oauth credential invalidated", { credentialID: id, scope })) - await run(credentials.remove(id)) - }, - store: { - tokens: async () => { - const oauth = await read() - if (!oauth) return undefined - presented = oauth.refresh - return toTokens(oauth) - }, - saveTokens: async (tokens) => { - const previous = await read() - // Another connection rotated past the token this one presented; its tokens win. - if (previous && previous.refresh !== presented && previous.refresh !== (tokens.refresh_token ?? "")) return - const value = toCredential({ - methodID, - serverUrl: input.config.url, - tokens, - client: previous ? clientFromCredential(previous) : undefined, - }) - presented = value.refresh - await run(credentials.update(id, { value })) - }, - clientInformation: async () => { - const oauth = await read() - return oauth ? clientFromCredential(oauth) : undefined - }, - saveClientInformation: async (client) => { - const oauth = await read() - if (!oauth) return - await run(credentials.update(id, { value: { ...oauth, metadata: { ...oauth.metadata, client } } })) - }, - codeVerifier: async () => undefined, - saveCodeVerifier: async () => {}, - }, - }) - lockedRefreshes.set(result, refresh) - return result + }) + const due = (current: Credential.OAuth, now: number) => Credential.expiring(current, now, REFRESH_AHEAD) + const refused = () => new UnauthorizedError(`MCP server "${input.config.url}" requires user authorization`) + // The token last sent. A 401 refreshes only while the row still holds it: another connection or process may + // have refreshed it already. + let presented: string | undefined + return { + token: () => + run( + Effect.gen(function* () { + const current = yield* read + // Refreshing ahead needs the discovery the login saved. If it fails, the current token goes out and a + // 401 decides. + const ahead = + current?.refresh && discoveryFromCredential(current) && due(current, yield* Clock.currentTimeMillis) + const value = ahead ? yield* refresh(due).pipe(Effect.orElseSucceed(() => current)) : current + presented = value?.access + return presented + }), + ), + onUnauthorized: (context) => + run( + Effect.gen(function* () { + const rejected = presented + if (!(yield* read)?.refresh) return yield* Effect.fail(refused()) + const value = yield* refresh( + (current) => current.access === rejected, + extractWWWAuthenticateParams(context.response).resourceMetadataUrl, + ).pipe( + Effect.catch((error) => + error instanceof RefreshRejected || error instanceof IssuerChanged + ? Effect.fail(refused()) + : // Not a lost login: keep the credential and fail this attempt so the next one tries again. An OAuth + // error names only its code: its description can quote the server's whole response. + Effect.fail( + new OAuthError( + OAuthErrorCode.TemporarilyUnavailable, + `Could not refresh the OAuth token: ${ + error instanceof OAuthError + ? error.code + : error instanceof Error + ? error.message + : String(error) + }`, + ), + ), + ), + ) + if (!value) return yield* Effect.fail(refused()) + }), + ), + } }) +// Refreshes with the discovery the login saved, or discovers as the login did and saves the result. +const exchange = (input: { + readonly config: typeof ConfigMCP.Remote.Type + readonly fetchFn: FetchLike + readonly current: Credential.OAuth + readonly resourceMetadataUrl: URL | undefined +}) => + Effect.tryPromise({ + try: async (signal) => { + const fetchFn: FetchLike = async (url, init) => { + const response = await input.fetchFn(url, { ...init, signal }) + // A failing token endpoint says nothing about the login; report its status, not its body. + if (init?.method === "POST" && (response.status === 429 || response.status >= 500)) + throw new Error(`HTTP ${response.status}`) + return response + } + const oauth = input.config.oauth || undefined + const client = oauth?.client_id + ? { client_id: oauth.client_id, client_secret: oauth.client_secret } + : clientFromCredential(input.current) + if (!client) throw new RefreshRejected({ message: "no OAuth client information" }) + const saved = discoveryFromCredential(input.current) + const configured = await configuredDiscovery({ config: input.config, fetchFn }) + const server = + configured ?? + (saved + ? { + authorizationServerUrl: saved.authorizationServer, + authorizationServerMetadata: await discoverAuthorizationServerMetadata(saved.authorizationServer, { + fetchFn, + }), + resourceMetadata: undefined, + } + : await discoverOAuthServerInfo(input.config.url, { + resourceMetadataUrl: input.resourceMetadataUrl, + fetchFn, + })) + const found = server.authorizationServerMetadata?.issuer ?? server.authorizationServerUrl + const issuer = input.current.metadata?.issuer + if (typeof issuer === "string" && found.replace(/\/$/, "") !== issuer.replace(/\/$/, "")) + throw new IssuerChanged({ message: `issued by ${issuer}, but discovery names ${found}` }) + const resource = saved?.resource ?? selectResource(input.config, server.resourceMetadata?.resource).toString() + const tokens = await refreshAuthorization(server.authorizationServerUrl, { + metadata: server.authorizationServerMetadata, + clientInformation: client, + refreshToken: input.current.refresh, + resource, + fetchFn, + }) + return toCredential({ + methodID: input.current.methodID, + serverUrl: input.config.url, + tokens: { + refresh_token: input.current.refresh, + ...tokens, + issuer: found, + }, + client: clientFromCredential(input.current), + // A configured metadata URL is read on every refresh, so changing it applies at once. + discovery: configured ? undefined : { authorizationServer: server.authorizationServerUrl, resource }, + }) + }, + catch: (error) => + error instanceof RefreshRejected || error instanceof IssuerChanged + ? error + : error instanceof OAuthError && rejections.has(error.code) + ? new RefreshRejected({ message: error.message }) + : error, + }) + export const authorize = (input: { readonly name: string readonly config: typeof ConfigMCP.Remote.Type @@ -557,7 +533,6 @@ export const authorize = (input: { const oauthProvider = provider({ config: input.config, store, - fetch: fetchFn, clientMetadataUrl: cimd ? CLIENT_METADATA_URL : undefined, discovery: { ...discovery, resourceMetadataUrl: resourceMetadataUrl?.toString() }, redirect: { @@ -579,7 +554,18 @@ export const authorize = (input: { hasRefreshToken: Boolean(tokens.refresh_token), expiresIn: tokens.expires_in, }) - return toCredential({ methodID: input.methodID, serverUrl: input.config.url, tokens, client }) + return toCredential({ + methodID: input.methodID, + serverUrl: input.config.url, + tokens, + client, + discovery: oauth?.auth_server_metadata_url + ? undefined + : { + authorizationServer: discovery.authorizationServerUrl, + resource: selectResource(input.config, discovery.resourceMetadata?.resource).toString(), + }, + }) }) yield* Effect.tryPromise({ diff --git a/packages/core/src/mcp/pool.ts b/packages/core/src/mcp/pool.ts index 5a4841d6ca1..9c81d7c7069 100644 --- a/packages/core/src/mcp/pool.ts +++ b/packages/core/src/mcp/pool.ts @@ -1,6 +1,6 @@ export * as McpPool from "./pool.js" -import type { OAuthClientProvider } from "@modelcontextprotocol/client" +import type { AuthProvider } from "@modelcontextprotocol/client" import type { Mcp } from "@opencode/schema/mcp" import { CrossSpawnSpawner } from "@opencode/util/cross-spawn-spawner" import { makeGlobalNode } from "@opencode/util/effect/app-node" @@ -24,7 +24,7 @@ export interface Input extends McpConnection.Input { export interface Selection { readonly key: string - readonly authProvider: Effect.Effect + readonly authProvider: Effect.Effect } export interface Interface { @@ -88,7 +88,7 @@ function fingerprint(secret: string | Record | undefined) { // A Location holding a shared connection. The pool reaches Locations only through the holders // registered right now, never through the one that opened the connection. interface Holder { - readonly authProvider: Effect.Effect + readonly authProvider: Effect.Effect readonly elicitation: McpClient.ElicitationHandler["create"] readonly closed: (reason: string) => void readonly changed: (kind: McpConnection.Kind) => void diff --git a/packages/core/test/mcp-oauth.test.ts b/packages/core/test/mcp-oauth.test.ts index 6ed86ddddad..e9b17193abd 100644 --- a/packages/core/test/mcp-oauth.test.ts +++ b/packages/core/test/mcp-oauth.test.ts @@ -1,5 +1,5 @@ import { afterAll, describe, expect, test } from "bun:test" -import { auth, OAuthError, refreshAuthorization, type FetchLike } from "@modelcontextprotocol/client" +import { OAuthError, UnauthorizedError, type AuthProvider } from "@modelcontextprotocol/client" import path from "path" import { ConfigMCP } from "@opencode/schema/config/mcp" import { Credential } from "@opencode/core/credential" @@ -58,13 +58,6 @@ const memoryCredentials = (initial: Credential.Info[]) => { return { rows, service } } -const connectProvider = (config: typeof ConfigMCP.Remote.Type, store: ReturnType) => - Effect.runPromise( - McpOAuth.connectProvider({ config, credential: Array.from(store.rows.values()).at(-1) }).pipe( - Effect.provideService(Credential.Service, store.service), - ), - ) - // Serves authorization server metadata with the given capabilities and records DCR + token requests. const authorizationServer = (metadata: Record) => { const registrations: unknown[] = [] @@ -166,6 +159,7 @@ describe("MCP OAuth", () => { expect(tokenRequests[0]?.get("code")).toBe("accepted") expect(tokenRequests[0]?.get("code_verifier")).not.toBeNull() expect(tokenRequests[0]?.get("resource")).toBe(server.url.href) + expect(credential.metadata?.discovery).toEqual({ authorizationServer: server.url.href, resource: server.url.href }) }) test("keeps waiting for the redirect after callback requests without OAuth parameters", async () => { @@ -275,172 +269,6 @@ describe("MCP OAuth", () => { expect(result.exit._tag).toBe("Failure") }) - test("refreshes tokens loaded from a persisted credential", async () => { - const tokenRequests: URLSearchParams[] = [] - const server = Bun.serve({ - port: 0, - async fetch(request) { - const url = new URL(request.url) - if (request.method !== "POST" || url.pathname !== "/token") return new Response(null, { status: 404 }) - tokenRequests.push(new URLSearchParams(await request.text())) - return Response.json({ access_token: "next", token_type: "Bearer" }) - }, - }) - const store = memoryCredentials([credential({ access: "expired", refresh: "refresh", url: server.url.href })]) - const oauthProvider = await connectProvider(remote(server.url.href), store) - - const result = await auth(oauthProvider, { serverUrl: server.url.href }).finally(() => server.stop(true)) - - expect(result).toBe("AUTHORIZED") - expect(tokenRequests).toHaveLength(1) - expect(tokenRequests[0]?.get("grant_type")).toBe("refresh_token") - expect(tokenRequests[0]?.get("refresh_token")).toBe("refresh") - // The refreshed tokens land on the same credential row, stamped with the issuer they were minted by. - const stored = store.rows.get(Credential.ID.make("cred_test"))?.value - expect(stored?.type === "oauth" && stored.access).toBe("next") - expect(stored?.type === "oauth" && stored.metadata?.issuer).toBe(server.url.href) - }) - - test("refreshes the credential it was made with, not the one signed in since", async () => { - const server = Bun.serve({ - port: 0, - async fetch(request) { - const url = new URL(request.url) - if (request.method !== "POST" || url.pathname !== "/token") return new Response(null, { status: 404 }) - const refresh = new URLSearchParams(await request.text()).get("refresh_token") - return Response.json({ access_token: `next-for-${refresh}`, token_type: "Bearer" }) - }, - }) - const selected = credential({ access: "expired", refresh: "refresh", url: server.url.href }) - const newer = new Credential.Info({ - ...credential({ - access: "other", - refresh: "other-refresh", - url: server.url.href, - expires: Date.now() + 3_600_000, - }), - id: Credential.ID.make("cred_newer"), - }) - const store = memoryCredentials([selected, newer]) - const oauthProvider = await Effect.runPromise( - McpOAuth.connectProvider({ config: remote(server.url.href), credential: selected }).pipe( - Effect.provideService(Credential.Service, store.service), - ), - ) - - const result = await auth(oauthProvider, { serverUrl: server.url.href }).finally(() => server.stop(true)) - - expect(result).toBe("AUTHORIZED") - expect((await oauthProvider.tokens())?.access_token).toBe("next-for-refresh") - const stored = store.rows.get(selected.id)?.value - expect(stored?.type === "oauth" && stored.access).toBe("next-for-refresh") - const untouched = store.rows.get(newer.id)?.value - expect(untouched?.type === "oauth" && untouched.access).toBe("other") - }) - - test("stays anonymous when made without a credential, even after one is signed in", async () => { - const store = memoryCredentials([]) - const oauthProvider = await Effect.runPromise( - McpOAuth.connectProvider({ config: remote(authServer.url.href), credential: undefined }).pipe( - Effect.provideService(Credential.Service, store.service), - ), - ) - store.rows.set( - Credential.ID.make("cred_test"), - credential({ access: "late", refresh: "late", url: authServer.url.href }), - ) - expect(await oauthProvider.tokens()).toBeUndefined() - }) - - test("reports needs_auth for an unauthorized server without registering a client", async () => { - let registrations = 0 - const server = Bun.serve({ - port: 0, - fetch(request) { - const url = new URL(request.url) - if (request.method === "POST" && url.pathname === "/register") registrations++ - if (url.pathname === "/mcp") return new Response(null, { status: 401 }) - return new Response(null, { status: 404 }) - }, - }) - const config = new ConfigMCP.Remote({ type: "remote", url: `${server.url.origin}/mcp` }) - const oauthProvider = await connectProvider(config, memoryCredentials([])) - - const exit = await Effect.runPromise( - Effect.scoped( - McpClient.connect({ server: "test", config, directory: import.meta.dir, authProvider: oauthProvider }), - ).pipe(Effect.provide(hostEnvironmentLayer), Effect.exit), - ).finally(() => server.stop(true)) - - const error = Exit.isFailure(exit) && Cause.squash(exit.cause) - expect(error).toBeInstanceOf(McpClient.NeedsAuthError) - expect(error instanceof McpClient.NeedsAuthError && error.message).toBe( - `MCP server "${config.url}" requires a login before it can register a client`, - ) - expect(registrations).toBe(0) - }) - - test("drops an invalidated credential only while it still holds the presented token", async () => { - const url = authServer.url.href - const rotated = memoryCredentials([credential({ access: "a", refresh: "r1", url })]) - const rotatedProvider = await connectProvider(remote(url), rotated) - await rotatedProvider.tokens() - // Another connection refreshed first; the row now holds a token this provider never presented. - await Effect.runPromise( - rotated.service.update(Credential.ID.make("cred_test"), { - value: credential({ access: "b", refresh: "r2", url }).value, - }), - ) - await rotatedProvider.invalidateCredentials?.("tokens") - expect(rotated.rows.size).toBe(1) - - const stale = memoryCredentials([credential({ access: "a", refresh: "r1", url })]) - const staleProvider = await connectProvider(remote(url), stale) - await staleProvider.tokens() - await staleProvider.invalidateCredentials?.("tokens") - expect(stale.rows.size).toBe(0) - }) - - test("shares concurrent refreshes for the same token", async () => { - let requests = 0 - const pending = Promise.withResolvers() - const server = Bun.serve({ - port: 0, - async fetch(request) { - const body = new URLSearchParams(await request.text()) - if (body.get("grant_type") !== "refresh_token") return new Response(null, { status: 404 }) - requests++ - await pending.promise - return Response.json({ access_token: "access", token_type: "Bearer", refresh_token: "next" }) - }, - }) - const fetchFn = await Effect.runPromise(McpOAuth.loggedFetch({ server: "test" })) - const options = { - metadata: { - issuer: server.url.origin, - authorization_endpoint: `${server.url.origin}/authorize`, - token_endpoint: `${server.url.origin}/token`, - response_types_supported: ["code"], - }, - clientInformation: { client_id: "client" }, - refreshToken: "refresh", - fetchFn, - } - - const first = refreshAuthorization(new URL(server.url.origin), options) - const second = refreshAuthorization(new URL(server.url.origin), options) - // Both refreshes must reach the token endpoint before the shared response is released. - await new Promise((resolve) => setTimeout(resolve, 50)) - - expect(requests).toBe(1) - pending.resolve() - const results = await Promise.all([first, second]).finally(() => server.stop(true)) - expect(results).toEqual([ - { access_token: "access", token_type: "Bearer", refresh_token: "next" }, - { access_token: "access", token_type: "Bearer", refresh_token: "next" }, - ]) - }) - test("generates a loopback redirect URL when none is configured", async () => { expect(await authorize()).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/) }) @@ -465,77 +293,6 @@ describe("MCP OAuth", () => { ) }) - test("sends the configured URL as the resource when the server publishes no metadata", async () => { - const { server, tokenRequests } = authorizationServer({}) - const url = `${server.url.origin}/mcp` - const oauthProvider = await connectProvider( - remote(url), - memoryCredentials([credential({ access: "expired", refresh: "refresh", url })]), - ) - - await auth(oauthProvider, { serverUrl: url }).finally(() => server.stop(true)) - - expect(tokenRequests[0]?.get("resource")).toBe(url) - }) - - test("discovers resource metadata without the query the transport dialed", async () => { - const probes: string[] = [] - const server = Bun.serve({ - port: 0, - fetch(request) { - probes.push(new URL(request.url).pathname + new URL(request.url).search) - return new Response(null, { status: 404 }) - }, - }) - const url = `${server.url.origin}/mcp` - const oauthProvider = await connectProvider(remote(url), memoryCredentials([])) - - await auth(oauthProvider, { serverUrl: `${url}?codemode=false` }) - .catch(() => undefined) - .finally(() => server.stop(true)) - - expect(probes).toContain("/.well-known/oauth-protected-resource/mcp") - expect(probes.some((probe) => probe.includes("codemode"))).toBe(false) - }) - - test("keeps the configured URL as the resource when metadata echoes the dialed query", async () => { - const tokenRequests: URLSearchParams[] = [] - const server = Bun.serve({ - port: 0, - async fetch(request) { - const url = new URL(request.url) - if (url.pathname === "/.well-known/oauth-authorization-server") - return Response.json({ - issuer: url.origin, - authorization_endpoint: `${url.origin}/authorize`, - token_endpoint: `${url.origin}/token`, - response_types_supported: ["code"], - }) - if (url.pathname === "/.well-known/oauth-protected-resource/mcp") - return Response.json({ resource: `${url.origin}/mcp${url.search}`, authorization_servers: [url.origin] }) - if (request.method === "POST" && url.pathname === "/token") { - tokenRequests.push(new URLSearchParams(await request.text())) - return Response.json({ access_token: "next", token_type: "Bearer" }) - } - return new Response(null, { status: 404 }) - }, - }) - const url = `${server.url.origin}/mcp` - const oauthProvider = await connectProvider( - remote(url), - memoryCredentials([credential({ access: "expired", refresh: "refresh", url })]), - ) - - // The transport dials with ?codemode=false and follows the 401 challenge to metadata that echoes it. - await auth(oauthProvider, { - serverUrl: `${url}?codemode=false`, - resourceMetadataUrl: new URL(`${server.url.origin}/.well-known/oauth-protected-resource/mcp?codemode=false`), - }).finally(() => server.stop(true)) - - expect(tokenRequests[0]?.get("grant_type")).toBe("refresh_token") - expect(tokenRequests[0]?.get("resource")).toBe(url) - }) - test("finds resource metadata through the 401 header when the well-known path is not served", async () => { const server = Bun.serve({ port: 0, @@ -577,23 +334,8 @@ describe("MCP OAuth", () => { expect(authorization.origin).toBe(issuer.url.origin) expect(authorization.pathname).toBe("/authorize") expect(authorization.searchParams.get("resource")).toBe(url) - - const { server, tokenRequests } = authorizationServer({}) - const store = memoryCredentials([credential({ access: "expired", refresh: "refresh", url })]) - const oauthProvider = await connectProvider( - new ConfigMCP.Remote({ - type: "remote", - url, - oauth: { ...oauth, auth_server_metadata_url: `${server.url.origin}/.well-known/oauth-authorization-server` }, - }), - store, - ) - await auth(oauthProvider, { serverUrl: url }).finally(() => { - resource.stop(true) - issuer.stop(true) - server.stop(true) - }) - expect(tokenRequests[0]?.get("grant_type")).toBe("refresh_token") + resource.stop(true) + issuer.stop(true) }) test("requests offline_access without forcing a consent prompt", async () => { @@ -692,73 +434,46 @@ describe("MCP OAuth", () => { // Each instance has its own database connection, in-process lock table and file lock client over one // database file, the way the TUI, desktop app and background service share credentials. -describe("MCP OAuth refresh across processes", () => { - const id = Credential.ID.make("cred_shared") - - // A token endpoint that rotates refresh tokens and rejects reuse. The test releases each response. - const rotatingServer = () => { - const state = { current: "r1", generation: 1 } - const sent: string[] = [] - const received = Promise.withResolvers() - const release = Promise.withResolvers() - const server = Bun.serve({ - port: 0, - async fetch(request) { - const url = new URL(request.url) - if (request.method !== "POST" || url.pathname !== "/token") return new Response(null, { status: 404 }) - const token = new URLSearchParams(await request.text()).get("refresh_token") ?? "" - sent.push(token) - received.resolve() - await release.promise - if (token !== state.current) return Response.json({ error: "invalid_grant" }, { status: 400 }) - state.generation++ - state.current = `r${state.generation}` - return Response.json({ - access_token: `a${state.generation}`, - token_type: "Bearer", - refresh_token: state.current, - expires_in: 3600, - }) - }, - }) - return { server, sent, received: received.promise, release: () => release.resolve() } - } +describe("MCP OAuth connections", () => { + const id = Credential.ID.make("cred_test") + // Each instance has its own database connection, in-process lock table and file lock client over one file, + // like two OpenCode processes sharing a database. const instance = (file: string) => ManagedRuntime.make( AppNodeBuilder.build(Credential.node, [Database.node.replace(Database.configured({ path: file }))]), ) - const connection = (runtime: ReturnType, url: string) => - runtime.runPromise( - Effect.gen(function* () { - const credentials = yield* Credential.Service - const provider = yield* McpOAuth.connectProvider({ - config: remote(url), - credential: yield* credentials.get(id), - }) - return { provider, fetchFn: yield* McpOAuth.loggedFetch({ server: "test" }, provider) } - }), - ) - - const stored = async (runtime: ReturnType) => { - const value = (await runtime.runPromise(Credential.Service.use((credentials) => credentials.get(id))))?.value - return value?.type === "oauth" ? { access: value.access, refresh: value.refresh } : undefined - } - - const setup = async (url: string) => { + const setup = async ( + url: string, + input: { expires?: number; metadata?: Record; config?: typeof ConfigMCP.Remote.Type } = {}, + ) => { const tmp = await tmpdir() const file = path.join(tmp.path, "opencode.db") const first = instance(file) const second = instance(file) + const row = credential({ access: "a1", refresh: "r1", url, expires: input.expires ?? Date.now() + 3_600_000 }) await first.runPromise( Credential.Service.use((credentials) => - credentials.create({ ...credential({ access: "a1", refresh: "r1", url }), id }), + credentials.create({ + ...row, + value: { ...row.value, metadata: { ...row.value.metadata, ...input.metadata } }, + }), ), ) + const config = input.config ?? remote(url) + const provider = (runtime: ReturnType) => + runtime.runPromise( + Credential.Service.use((credentials) => + credentials + .get(id) + .pipe(Effect.flatMap((credential) => McpOAuth.connectProvider({ server: "test", config, credential }))), + ), + ) return { first, second, + provider, async [Symbol.asyncDispose]() { await Promise.all([first.dispose(), second.dispose()]) await tmp[Symbol.asyncDispose]() @@ -766,103 +481,225 @@ describe("MCP OAuth refresh across processes", () => { } } - const refresh = (server: ReturnType, fetchFn: FetchLike, refreshToken: string) => - refreshAuthorization(new URL(server.url.origin), { - metadata: { - issuer: server.url.origin, - authorization_endpoint: `${server.url.origin}/authorize`, - token_endpoint: `${server.url.origin}/token`, - response_types_supported: ["code"], + const stored = async (runtime: ReturnType) => { + const value = (await runtime.runPromise(Credential.Service.use((credentials) => credentials.get(id))))?.value + return value?.type === "oauth" ? { access: value.access, refresh: value.refresh } : undefined + } + + const unauthorized = (provider: AuthProvider, url: string, response = new Response(null, { status: 401 })) => + provider.onUnauthorized?.({ response, serverUrl: new URL(url), fetchFn: fetch }) + + const connect = (provider: AuthProvider, url: string, config = remote(url)) => + Effect.runPromise( + Effect.scoped( + McpClient.connect({ server: "test", config, directory: import.meta.dir, authProvider: provider }), + ).pipe(Effect.provide(hostEnvironmentLayer), Effect.exit), + ) + + const failure = (exit: Awaited>) => Exit.isFailure(exit) && Cause.squash(exit.cause) + + // A server whose MCP endpoint accepts only the refreshed token and whose token endpoint the test switches. + const guardedServer = () => { + const state = { + token: "ok" as "ok" | "unavailable" | "invalid_grant", + tokenEndpoint: undefined as string | undefined, + sent: [] as Array, + refused: 0, + } + const server = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/.well-known/oauth-authorization-server") + return Response.json({ + issuer: url.origin, + authorization_endpoint: `${url.origin}/authorize`, + token_endpoint: state.tokenEndpoint ?? `${url.origin}/token`, + response_types_supported: ["code"], + }) + if (request.method === "POST" && url.pathname === "/token") { + state.sent.push(new URLSearchParams(await request.text()).get("refresh_token")) + if (state.token === "unavailable") return new Response("upstream unavailable", { status: 503 }) + if (state.token === "invalid_grant") return Response.json({ error: "invalid_grant" }, { status: 400 }) + return Response.json({ access_token: "a2", token_type: "Bearer", refresh_token: "r2", expires_in: 3600 }) + } + if (request.method === "POST" && url.pathname === "/mcp") { + if (request.headers.get("authorization") !== "Bearer a2") { + state.refused++ + return new Response(null, { status: 401 }) + } + const body = (await request.json()) as { id: number; method: string; params?: { protocolVersion?: string } } + if (body.method !== "initialize") return new Response(null, { status: 202 }) + return Response.json({ + jsonrpc: "2.0", + id: body.id, + result: { + protocolVersion: body.params?.protocolVersion, + capabilities: {}, + serverInfo: { name: "test", version: "1" }, + }, + }) + } + return new Response(null, { status: 404 }) }, - clientInformation: { client_id: "client" }, - refreshToken, - fetchFn, }) + return { server, state, url: `${server.url.origin}/mcp` } + } - test("sends one refresh when two instances refresh the same credential at once", async () => { - const endpoint = rotatingServer() - await using processes = await setup(endpoint.server.url.href) - const [first, second] = await Promise.all([ - connection(processes.first, endpoint.server.url.href), - connection(processes.second, endpoint.server.url.href), - ]) + test("refreshes a refused token and retries with the new one", async () => { + const guarded = guardedServer() + await using processes = await setup(guarded.url) - const pending = refresh(endpoint.server, first.fetchFn, "r1") - // The first instance holds the credential lock until its rotated tokens are saved. - await endpoint.received - const waiting = refresh(endpoint.server, second.fetchFn, "r1") - endpoint.release() - const results = await Promise.all([pending, waiting]).finally(() => endpoint.server.stop(true)) + const exit = await connect(await processes.provider(processes.first), guarded.url).finally(() => + guarded.server.stop(true), + ) - expect(endpoint.sent).toEqual(["r1"]) - expect(results.map((tokens) => [tokens.access_token, tokens.refresh_token])).toEqual([ - ["a2", "r2"], - ["a2", "r2"], - ]) - expect((await first.provider.tokens())?.access_token).toBe("a2") - expect((await second.provider.tokens())?.access_token).toBe("a2") - expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) - }) - - test("uses the stored tokens instead of sending a refresh token another instance already spent", async () => { - const endpoint = rotatingServer() - endpoint.release() - await using processes = await setup(endpoint.server.url.href) - const stale = await connection(processes.first, endpoint.server.url.href) - const other = await connection(processes.second, endpoint.server.url.href) - await refresh(endpoint.server, other.fetchFn, "r1") - - const tokens = await refresh(endpoint.server, stale.fetchFn, "r1").finally(() => endpoint.server.stop(true)) - - expect(endpoint.sent).toEqual(["r1"]) - expect([tokens.access_token, tokens.refresh_token]).toEqual(["a2", "r2"]) - expect(await stored(processes.first)).toEqual({ access: "a2", refresh: "r2" }) - }) - - test("keeps tokens another instance rotated when a slower refresh saves", async () => { - const endpoint = rotatingServer() - endpoint.release() - await using processes = await setup(endpoint.server.url.href) - const slow = await connection(processes.first, endpoint.server.url.href) - expect((await slow.provider.tokens())?.refresh_token).toBe("r1") - const other = await connection(processes.second, endpoint.server.url.href) - await refresh(endpoint.server, other.fetchFn, "r1").finally(() => endpoint.server.stop(true)) - - await slow.provider.saveTokens({ access_token: "late", token_type: "Bearer", refresh_token: "late" }) - - expect(await stored(processes.first)).toEqual({ access: "a2", refresh: "r2" }) - }) - - test("saves rotated tokens through the SDK's refresh under the lock", async () => { - const endpoint = rotatingServer() - endpoint.release() - await using processes = await setup(endpoint.server.url.href) - const current = await connection(processes.first, endpoint.server.url.href) - - const result = await auth(current.provider, { - serverUrl: endpoint.server.url.href, - fetchFn: current.fetchFn, - }).finally(() => endpoint.server.stop(true)) - - expect(result).toBe("AUTHORIZED") - expect(endpoint.sent).toEqual(["r1"]) + expect(Exit.isSuccess(exit)).toBe(true) + expect(guarded.state.sent).toEqual(["r1"]) const value = (await processes.second.runPromise(Credential.Service.use((credentials) => credentials.get(id)))) ?.value expect(value?.type === "oauth" && [value.access, value.refresh, value.metadata?.issuer]).toEqual([ "a2", "r2", - endpoint.server.url.href, + guarded.server.url.origin, ]) }) - describe("when the refresh fails", () => { - // A server whose MCP endpoint accepts only the refreshed token and whose token endpoint the test switches. - const guardedServer = () => { - const state = { - token: "ok" as "ok" | "unavailable" | "invalid_grant", - tokenEndpoint: undefined as string | undefined, - sent: [] as Array, + describe("ahead of expiry", () => { + // An authorization server whose token endpoint the test switches, and the discovery a login saves for it. + const issuerServer = () => { + const state = { token: "ok" as "ok" | "unavailable", sent: [] as string[] } + const server = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/.well-known/oauth-authorization-server/as") + return Response.json({ + issuer: `${url.origin}/as`, + authorization_endpoint: `${url.origin}/as/authorize`, + token_endpoint: `${url.origin}/as/token`, + response_types_supported: ["code"], + }) + if (request.method !== "POST" || url.pathname !== "/as/token") return new Response(null, { status: 404 }) + state.sent.push(`${new URLSearchParams(await request.text()).get("resource")}`) + if (state.token === "unavailable") return new Response(null, { status: 503 }) + return Response.json({ access_token: "a2", token_type: "Bearer", refresh_token: "r2", expires_in: 3600 }) + }, + }) + const origin = server.url.origin + const discovery = { authorizationServer: `${origin}/as`, resource: `${origin}/mcp` } + return { server, state, url: `${origin}/mcp`, discovery } + } + + test("refreshes a token that expires within 30 seconds with the saved discovery before sending it", async () => { + const as = issuerServer() + await using processes = await setup(as.url, { + expires: Date.now() + 10_000, + metadata: { discovery: as.discovery }, + }) + + const token = await (await processes.provider(processes.first)).token().finally(() => as.server.stop(true)) + + expect(token).toBe("a2") + // The saved discovery names the authorization server and resource; the MCP server is never probed. + expect(as.state.sent).toEqual([as.url]) + expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) + }) + + test("sends the current token when the refresh fails", async () => { + const as = issuerServer() + as.state.token = "unavailable" + await using processes = await setup(as.url, { + expires: Date.now() + 10_000, + metadata: { discovery: as.discovery }, + }) + + const token = await (await processes.provider(processes.first)).token().finally(() => as.server.stop(true)) + + expect(token).toBe("a1") + expect(await stored(processes.second)).toEqual({ access: "a1", refresh: "r1" }) + }) + + test("leaves tokens with time left, without a lifetime, or saved without discovery to the 401", async () => { + const as = issuerServer() + const cases = [ + { expires: Date.now() + 60_000, metadata: { discovery: as.discovery } }, + { expires: 0, metadata: { discovery: as.discovery } }, + { expires: Date.now() + 10_000 }, + ] + for (const input of cases) { + await using processes = await setup(as.url, input) + expect(await (await processes.provider(processes.first)).token()).toBe("a1") } + as.server.stop(true) + expect(as.state.sent).toEqual([]) + }) + }) + + test("refreshes the credential it was made with, not the one signed in since", async () => { + const guarded = guardedServer() + await using processes = await setup(guarded.url) + const provider = await processes.provider(processes.first) + const newer = await processes.first.runPromise( + Credential.Service.use((credentials) => + credentials.create({ + integrationID, + value: credential({ access: "other", refresh: "other-refresh", url: guarded.url }).value, + }), + ), + ) + + await provider.token() + await unauthorized(provider, guarded.url)?.finally(() => guarded.server.stop(true)) + + expect(guarded.state.sent).toEqual(["r1"]) + expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) + const untouched = ( + await processes.second.runPromise(Credential.Service.use((credentials) => credentials.get(newer.id))) + )?.value + expect(untouched?.type === "oauth" && untouched.access).toBe("other") + }) + + test("reports needs_auth for an unauthorized server without a credential or any OAuth request", async () => { + const requests: string[] = [] + const server = Bun.serve({ + port: 0, + fetch(request) { + const url = new URL(request.url) + requests.push(url.pathname) + if (url.pathname === "/mcp") return new Response(null, { status: 401 }) + return new Response(null, { status: 404 }) + }, + }) + const url = `${server.url.origin}/mcp` + const provider = await Effect.runPromise( + McpOAuth.connectProvider({ server: "test", config: remote(url), credential: undefined }).pipe( + Effect.provideService(Credential.Service, memoryCredentials([]).service), + ), + ) + + const exit = await connect(provider, url).finally(() => server.stop(true)) + + expect(failure(exit)).toBeInstanceOf(McpClient.NeedsAuthError) + expect(requests.every((path) => path === "/mcp")).toBe(true) + }) + + describe("resource", () => { + test("sends the configured URL when the server publishes no metadata", async () => { + const { server, tokenRequests } = authorizationServer({}) + const url = `${server.url.origin}/mcp` + await using processes = await setup(url) + const provider = await processes.provider(processes.first) + + await provider.token() + await unauthorized(provider, url)?.finally(() => server.stop(true)) + + expect(tokenRequests[0]?.get("grant_type")).toBe("refresh_token") + expect(tokenRequests[0]?.get("resource")).toBe(url) + }) + + test("keeps the configured URL when metadata echoes the dialed query", async () => { + const tokenRequests: URLSearchParams[] = [] const server = Bun.serve({ port: 0, async fetch(request) { @@ -871,70 +708,246 @@ describe("MCP OAuth refresh across processes", () => { return Response.json({ issuer: url.origin, authorization_endpoint: `${url.origin}/authorize`, - token_endpoint: state.tokenEndpoint ?? `${url.origin}/token`, + token_endpoint: `${url.origin}/token`, response_types_supported: ["code"], }) + if (url.pathname === "/.well-known/oauth-protected-resource/mcp") + return Response.json({ resource: `${url.origin}/mcp${url.search}`, authorization_servers: [url.origin] }) if (request.method === "POST" && url.pathname === "/token") { - state.sent.push(new URLSearchParams(await request.text()).get("refresh_token")) - if (state.token === "unavailable") return new Response("upstream unavailable", { status: 503 }) - if (state.token === "invalid_grant") return Response.json({ error: "invalid_grant" }, { status: 400 }) - return Response.json({ access_token: "a2", token_type: "Bearer", refresh_token: "r2", expires_in: 3600 }) - } - if (request.method === "POST" && url.pathname === "/mcp") { - if (request.headers.get("authorization") !== "Bearer a2") return new Response(null, { status: 401 }) - const body = (await request.json()) as { - id: number - method: string - params?: { protocolVersion?: string } - } - if (body.method !== "initialize") return new Response(null, { status: 202 }) - return Response.json({ - jsonrpc: "2.0", - id: body.id, - result: { - protocolVersion: body.params?.protocolVersion, - capabilities: {}, - serverInfo: { name: "test", version: "1" }, - }, - }) + tokenRequests.push(new URLSearchParams(await request.text())) + return Response.json({ access_token: "next", token_type: "Bearer" }) } return new Response(null, { status: 404 }) }, }) - return { server, state, url: `${server.url.origin}/mcp` } + const url = `${server.url.origin}/mcp` + await using processes = await setup(url) + const provider = await processes.provider(processes.first) + + // The transport dials with ?codemode=false and the 401 points at metadata that echoes it. + await provider.token() + await unauthorized( + provider, + `${url}?codemode=false`, + new Response(null, { + status: 401, + headers: { + "WWW-Authenticate": `Bearer resource_metadata="${server.url.origin}/.well-known/oauth-protected-resource/mcp?codemode=false"`, + }, + }), + )?.finally(() => server.stop(true)) + + expect(tokenRequests[0]?.get("resource")).toBe(url) + }) + + test("discovers the resource for a login saved without one", async () => { + const tokenRequests: URLSearchParams[] = [] + const server = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/.well-known/oauth-authorization-server") + return Response.json({ + issuer: url.origin, + authorization_endpoint: `${url.origin}/authorize`, + token_endpoint: `${url.origin}/token`, + response_types_supported: ["code"], + }) + if (url.pathname === "/.well-known/oauth-protected-resource/mcp") + return Response.json({ resource: `${url.origin}/`, authorization_servers: [url.origin] }) + if (request.method === "POST" && url.pathname === "/token") { + tokenRequests.push(new URLSearchParams(await request.text())) + return Response.json({ access_token: "a2", token_type: "Bearer" }) + } + return new Response(null, { status: 404 }) + }, + }) + const url = `${server.url.origin}/mcp` + await using processes = await setup(url) + const provider = await processes.provider(processes.first) + + await provider.token() + await unauthorized(provider, url)?.finally(() => server.stop(true)) + + expect(tokenRequests[0]?.get("resource")).toBe(`${server.url.origin}/`) + }) + + test("follows the 401 to the resource for a login saved without discovery, and saves it", async () => { + const tokenRequests: URLSearchParams[] = [] + const server = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/custom/metadata") + return Response.json({ resource: `${url.origin}/`, authorization_servers: [`${url.origin}/as`] }) + if (url.pathname === "/.well-known/oauth-authorization-server/as") + return Response.json({ + issuer: `${url.origin}/as`, + authorization_endpoint: `${url.origin}/as/authorize`, + token_endpoint: `${url.origin}/as/token`, + response_types_supported: ["code"], + }) + if (request.method === "POST" && url.pathname === "/as/token") { + tokenRequests.push(new URLSearchParams(await request.text())) + return Response.json({ access_token: "a2", token_type: "Bearer", refresh_token: "r2", expires_in: 3600 }) + } + return new Response(null, { status: 404 }) + }, + }) + const url = `${server.url.origin}/mcp` + await using processes = await setup(url, { expires: Date.now() - 1_000 }) + const provider = await processes.provider(processes.first) + + await provider.token() + await unauthorized( + provider, + url, + new Response(null, { + status: 401, + headers: { "WWW-Authenticate": `Bearer resource_metadata="${server.url.origin}/custom/metadata"` }, + }), + )?.finally(() => server.stop(true)) + + expect(tokenRequests.map((body) => body.get("resource"))).toEqual([`${server.url.origin}/`]) + const value = (await processes.second.runPromise(Credential.Service.use((credentials) => credentials.get(id)))) + ?.value + expect(value?.type === "oauth" && value.metadata?.discovery).toEqual({ + authorizationServer: `${server.url.origin}/as`, + resource: `${server.url.origin}/`, + }) + }) + + test("refreshes through configured authorization server metadata", async () => { + const { server, tokenRequests } = authorizationServer({}) + const resource = Bun.serve({ port: 0, fetch: () => new Response(null, { status: 404 }) }) + const url = `${resource.url.origin}/mcp` + await using processes = await setup(url, { + config: new ConfigMCP.Remote({ + type: "remote", + url, + oauth: { + client_id: "client", + auth_server_metadata_url: `${server.url.origin}/.well-known/oauth-authorization-server`, + }, + }), + }) + const provider = await processes.provider(processes.first) + + await provider.token() + await unauthorized(provider, url)?.finally(() => { + resource.stop(true) + server.stop(true) + }) + + expect(tokenRequests[0]?.get("grant_type")).toBe("refresh_token") + expect(tokenRequests[0]?.get("resource")).toBe(url) + }) + }) + + describe("across processes", () => { + // A token endpoint that rotates refresh tokens and rejects reuse. The test releases each response. + const rotatingServer = () => { + const state = { current: "r1", generation: 1 } + const sent: string[] = [] + const received = Promise.withResolvers() + const release = Promise.withResolvers() + const server = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (request.method !== "POST" || url.pathname !== "/token") return new Response(null, { status: 404 }) + const token = new URLSearchParams(await request.text()).get("refresh_token") ?? "" + sent.push(token) + received.resolve() + await release.promise + if (token !== state.current) return Response.json({ error: "invalid_grant" }, { status: 400 }) + state.generation++ + state.current = `r${state.generation}` + return Response.json({ + access_token: `a${state.generation}`, + token_type: "Bearer", + refresh_token: state.current, + expires_in: 3600, + }) + }, + }) + return { server, sent, received: received.promise, release: () => release.resolve() } } - const connect = async (runtime: ReturnType, url: string) => { - const current = await connection(runtime, url) - return Effect.runPromise( - Effect.scoped( - McpClient.connect({ - server: "test", - config: remote(url), - directory: import.meta.dir, - authProvider: current.provider, - }), - ).pipe(Effect.provide(hostEnvironmentLayer), Effect.exit), - ) - } + test("sends one refresh when two instances refresh the same credential at once", async () => { + const endpoint = rotatingServer() + const url = endpoint.server.url.href + await using processes = await setup(url) + const [first, second] = await Promise.all([ + processes.provider(processes.first), + processes.provider(processes.second), + ]) + await Promise.all([first.token(), second.token()]) - const failure = (exit: Awaited>) => Exit.isFailure(exit) && Cause.squash(exit.cause) + const pending = unauthorized(first, url) + // The first instance holds the credential lock until its rotated tokens are saved. + await endpoint.received + const waiting = unauthorized(second, url) + endpoint.release() + await Promise.all([pending, waiting]).finally(() => endpoint.server.stop(true)) + expect(endpoint.sent).toEqual(["r1"]) + expect([await first.token(), await second.token()]).toEqual(["a2", "a2"]) + expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) + }) + + test("uses the stored tokens instead of spending a refresh token another instance already spent", async () => { + const endpoint = rotatingServer() + endpoint.release() + const url = endpoint.server.url.href + await using processes = await setup(url) + const stale = await processes.provider(processes.first) + const other = await processes.provider(processes.second) + await Promise.all([stale.token(), other.token()]) + await unauthorized(other, url) + + await unauthorized(stale, url)?.finally(() => endpoint.server.stop(true)) + + expect(endpoint.sent).toEqual(["r1"]) + expect(await stale.token()).toBe("a2") + }) + + test("needs auth without a request when the credential was signed out", async () => { + const endpoint = rotatingServer() + endpoint.release() + const url = endpoint.server.url.href + await using processes = await setup(url) + const provider = await processes.provider(processes.first) + await provider.token() + await processes.second.runPromise(Credential.Service.use((credentials) => credentials.remove(id))) + + const error = await Promise.resolve(unauthorized(provider, url)) + .catch((error: unknown) => error) + .finally(() => endpoint.server.stop(true)) + + expect(error).toBeInstanceOf(UnauthorizedError) + expect(endpoint.sent).toEqual([]) + }) + }) + + describe("when the refresh fails", () => { test("fails without signing out when the token endpoint answers 503", async () => { const guarded = guardedServer() await using processes = await setup(guarded.url) guarded.state.token = "unavailable" - const failed = failure(await connect(processes.first, guarded.url)) + const failed = failure(await connect(await processes.provider(processes.first), guarded.url)) expect(failed).toBeInstanceOf(McpClient.ConnectError) - expect(failed instanceof McpClient.ConnectError && [failed.message, failed.answered]).toEqual([ + expect(failed instanceof McpClient.ConnectError && failed.answered).toBe(false) + expect(failed instanceof McpClient.ConnectError && failed.message).toBe( "Could not refresh the OAuth token: HTTP 503 (temporarily_unavailable)", - false, - ]) + ) expect(await stored(processes.second)).toEqual({ access: "a1", refresh: "r1" }) guarded.state.token = "ok" - const exit = await connect(processes.first, guarded.url).finally(() => guarded.server.stop(true)) + const exit = await connect(await processes.provider(processes.first), guarded.url).finally(() => + guarded.server.stop(true), + ) expect(Exit.isSuccess(exit)).toBe(true) expect(guarded.state.sent).toEqual(["r1", "r1"]) expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) @@ -947,13 +960,15 @@ describe("MCP OAuth refresh across processes", () => { guarded.state.tokenEndpoint = `${closed.url.origin}/token` await using processes = await setup(guarded.url) - const failed = failure(await connect(processes.first, guarded.url)) + const failed = failure(await connect(await processes.provider(processes.first), guarded.url)) expect(failed).toBeInstanceOf(McpClient.ConnectError) expect(failed instanceof McpClient.ConnectError && failed.answered).toBe(false) expect(await stored(processes.second)).toEqual({ access: "a1", refresh: "r1" }) guarded.state.tokenEndpoint = undefined - const exit = await connect(processes.first, guarded.url).finally(() => guarded.server.stop(true)) + const exit = await connect(await processes.provider(processes.first), guarded.url).finally(() => + guarded.server.stop(true), + ) expect(Exit.isSuccess(exit)).toBe(true) }) @@ -962,7 +977,7 @@ describe("MCP OAuth refresh across processes", () => { guarded.state.token = "invalid_grant" await using processes = await setup(guarded.url) - const failed = failure(await connect(processes.first, guarded.url)) + const failed = failure(await connect(await processes.provider(processes.first), guarded.url)) guarded.server.stop(true) expect(failed).toBeInstanceOf(McpClient.NeedsAuthError) expect(await stored(processes.second)).toBeUndefined() @@ -970,25 +985,31 @@ describe("MCP OAuth refresh across processes", () => { test("keeps the credential when the refresh times out", async () => { const received = Promise.withResolvers() + let aborted = false const hung = Bun.serve({ port: 0, - fetch: () => { + fetch: (request) => { + request.signal.addEventListener("abort", () => { + aborted = true + }) received.resolve() return new Promise(() => {}) }, }) - await using processes = await setup(hung.url.href) + const url = hung.url.href + await using processes = await setup(url) const error = await processes.first .runPromise( Effect.gen(function* () { const credentials = yield* Credential.Service const provider = yield* McpOAuth.connectProvider({ - config: remote(hung.url.href), + server: "test", + config: remote(url), credential: yield* credentials.get(id), }) - const fetchFn = yield* McpOAuth.loggedFetch({ server: "test" }, provider) - const pending = refresh(hung, fetchFn, "r1").catch((error: unknown) => error) + yield* Effect.promise(() => provider.token()) + const pending = Promise.resolve(unauthorized(provider, url)).catch((error: unknown) => error) yield* Effect.promise(() => received.promise) yield* TestClock.adjust("30 seconds") return yield* Effect.promise(() => pending) @@ -998,55 +1019,146 @@ describe("MCP OAuth refresh across processes", () => { expect(error instanceof OAuthError && error.code).toBe("temporarily_unavailable") expect(await stored(processes.second)).toEqual({ access: "a1", refresh: "r1" }) + expect(aborted).toBe(true) + }) + + test("sends nothing to an authorization server other than the one that issued the credential", async () => { + const received: string[] = [] + const attacker = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/resource") + return Response.json({ resource: `${url.origin}/`, authorization_servers: [url.origin] }) + if (url.pathname === "/.well-known/oauth-authorization-server") + return Response.json({ + issuer: url.origin, + authorization_endpoint: `${url.origin}/authorize`, + token_endpoint: `${url.origin}/token`, + response_types_supported: ["code"], + }) + if (request.method === "POST") received.push(await request.text()) + return Response.json({ access_token: "stolen", token_type: "Bearer" }) + }, + }) + const url = `${attacker.url.origin}/mcp` + // Saved before discovery was stored: only the issuer the login found is known. + await using processes = await setup(url, { metadata: { issuer: "https://auth.legit.example" } }) + const provider = await processes.provider(processes.first) + + await provider.token() + const error = await Promise.resolve( + unauthorized( + provider, + url, + new Response(null, { + status: 401, + headers: { "WWW-Authenticate": `Bearer resource_metadata="${attacker.url.origin}/resource"` }, + }), + ), + ) + .catch((error: unknown) => error) + .finally(() => attacker.stop(true)) + + expect(error).toBeInstanceOf(UnauthorizedError) + expect(received).toEqual([]) + const value = (await processes.second.runPromise(Credential.Service.use((credentials) => credentials.get(id)))) + ?.value + expect(value?.type === "oauth" && [value.access, value.refresh, value.metadata?.issuer]).toEqual([ + "a1", + "r1", + "https://auth.legit.example", + ]) + }) + + test("names only the error code of a token endpoint that answers without an OAuth error", async () => { + const guarded = guardedServer() + await using processes = await setup(guarded.url) + const provider = await processes.provider(processes.first) + const server = Bun.serve({ + port: 0, + fetch: () => new Response("secret echo of the request", { status: 400 }), + }) + guarded.state.tokenEndpoint = `${server.url.origin}/token` + + await provider.token() + const error = await Promise.resolve(unauthorized(provider, guarded.url)) + .catch((error: unknown) => error) + .finally(() => { + server.stop(true) + guarded.server.stop(true) + }) + + expect(error instanceof OAuthError && error.message).toBe("Could not refresh the OAuth token: server_error") + expect(await stored(processes.second)).toEqual({ access: "a1", refresh: "r1" }) + }) + + test("signs out a credential without client information", async () => { + const { server, tokenRequests } = authorizationServer({}) + const url = `${server.url.origin}/mcp` + await using processes = await setup(url, { config: new ConfigMCP.Remote({ type: "remote", url }) }) + const provider = await processes.provider(processes.first) + + await provider.token() + const error = await Promise.resolve(unauthorized(provider, url)) + .catch((error: unknown) => error) + .finally(() => server.stop(true)) + + expect(error).toBeInstanceOf(UnauthorizedError) + expect(tokenRequests).toEqual([]) + expect(await stored(processes.second)).toBeUndefined() + }) + + test("tries the next metadata URL when one answers 502", async () => { + const tokenRequests: string[] = [] + const server = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/.well-known/oauth-authorization-server") return new Response(null, { status: 502 }) + if (url.pathname === "/.well-known/openid-configuration") + return Response.json({ + issuer: url.origin, + authorization_endpoint: `${url.origin}/authorize`, + token_endpoint: `${url.origin}/token`, + response_types_supported: ["code"], + subject_types_supported: ["public"], + id_token_signing_alg_values_supported: ["RS256"], + jwks_uri: `${url.origin}/jwks`, + }) + if (request.method === "POST" && url.pathname === "/token") { + tokenRequests.push(url.pathname) + return Response.json({ access_token: "a2", token_type: "Bearer", refresh_token: "r2" }) + } + return new Response(null, { status: 404 }) + }, + }) + const url = `${server.url.origin}/mcp` + await using processes = await setup(url) + const provider = await processes.provider(processes.first) + + await provider.token() + await unauthorized(provider, url)?.finally(() => server.stop(true)) + + expect(tokenRequests).toEqual(["/token"]) + expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) }) }) - test("hands a rejected refresh back to the SDK and keeps the credential", async () => { + test("reports needs_auth when the server asks for more scope", async () => { const server = Bun.serve({ port: 0, - fetch: () => Response.json({ error: "invalid_grant", error_description: "revoked" }, { status: 400 }), + fetch: () => + new Response(null, { + status: 403, + headers: { "WWW-Authenticate": 'Bearer error="insufficient_scope", scope="admin"' }, + }), }) - await using processes = await setup(server.url.href) - const current = await connection(processes.first, server.url.href) + const url = `${server.url.origin}/mcp` + await using processes = await setup(url) - const error = await refresh(server, current.fetchFn, "r1") - .catch((error: unknown) => error) - .finally(() => server.stop(true)) + const exit = await connect(await processes.provider(processes.first), url).finally(() => server.stop(true)) - expect(error).toBeInstanceOf(OAuthError) - expect(error instanceof OAuthError && [error.code, error.message]).toEqual(["invalid_grant", "revoked"]) - expect(await stored(processes.second)).toEqual({ access: "a1", refresh: "r1" }) - }) - - test("answers invalid_grant without a request when the credential was signed out", async () => { - const endpoint = rotatingServer() - endpoint.release() - await using processes = await setup(endpoint.server.url.href) - const current = await connection(processes.first, endpoint.server.url.href) - await processes.second.runPromise(Credential.Service.use((credentials) => credentials.remove(id))) - - const error = await refresh(endpoint.server, current.fetchFn, "r1") - .catch((error: unknown) => error) - .finally(() => endpoint.server.stop(true)) - - expect(error instanceof OAuthError && error.code).toBe("invalid_grant") - expect(endpoint.sent).toEqual([]) - }) - - test("releases the lock when the token endpoint is unreachable", async () => { - const endpoint = rotatingServer() - endpoint.release() - const unreachable = Bun.serve({ port: 0, fetch: () => new Response(null, { status: 404 }) }) - unreachable.stop(true) - await using processes = await setup(endpoint.server.url.href) - const current = await connection(processes.first, endpoint.server.url.href) - - const error = await refresh(unreachable, current.fetchFn, "r1").catch((error: unknown) => error) - expect(error instanceof OAuthError && error.code).toBe("temporarily_unavailable") - expect(await stored(processes.first)).toEqual({ access: "a1", refresh: "r1" }) - - const tokens = await refresh(endpoint.server, current.fetchFn, "r1").finally(() => endpoint.server.stop(true)) - expect([tokens.access_token, tokens.refresh_token]).toEqual(["a2", "r2"]) - expect(await stored(processes.second)).toEqual({ access: "a2", refresh: "r2" }) + expect(failure(exit)).toBeInstanceOf(McpClient.NeedsAuthError) }) })