diff --git a/.changeset/mcp-unauthorized-fallback.md b/.changeset/mcp-unauthorized-fallback.md new file mode 100644 index 0000000000..694a104653 --- /dev/null +++ b/.changeset/mcp-unauthorized-fallback.md @@ -0,0 +1,6 @@ +--- +'@truefoundry/trueforge-core': patch +'@truefoundry/trueforge': patch +--- + +`RemoteMCP` header resolvers can return `onUnauthorized`, used once on a 401. An MCP server rejecting an `x-tfg-mcp-headers` `Authorization` now falls back to its regular authorization flow. diff --git a/.changeset/x-tfg-mcp-headers-auth.md b/.changeset/x-tfg-mcp-headers-auth.md new file mode 100644 index 0000000000..4212562adc --- /dev/null +++ b/.changeset/x-tfg-mcp-headers-auth.md @@ -0,0 +1,5 @@ +--- +'@truefoundry/trueforge': patch +--- + +`x-tfg-mcp-headers` entries with `Authorization` skip that MCP server's consent flow: forwarded directly in open-source mode (along with other per-server headers), sent as `x-tfy-mcp-headers` in TrueFoundry mode. diff --git a/packages/trueforge-core/src/core/mcp/RemoteMCP.ts b/packages/trueforge-core/src/core/mcp/RemoteMCP.ts index f015f1e5cd..fdf86be96a 100644 --- a/packages/trueforge-core/src/core/mcp/RemoteMCP.ts +++ b/packages/trueforge-core/src/core/mcp/RemoteMCP.ts @@ -24,6 +24,7 @@ import { paginateWithCursorGuard } from './pagination'; import { connectRemoteMcp, DEFAULT_MAX_MCP_RESPONSE_BYTES, + isAuthError, isSessionExpiredError, type RemoteMcpConnection, type RemoteMcpTransportType, @@ -39,8 +40,13 @@ function redactUrlForTrace(url: string): string { } } -/** What a headers resolver returns: the headers to send, or a signal that auth is required. */ -export type ResolveHeadersResult = { headers: Record } | { authRequired: MCPAuthRequired }; +/** + * What a headers resolver returns: the headers to send, or a signal that auth is required. + * `onUnauthorized` is consulted once if the upstream rejects `headers` with a 401. + */ +export type ResolveHeadersResult = + | { headers: Record; onUnauthorized?: () => Promise } + | { authRequired: MCPAuthRequired }; /** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */ export type RemoteMcpHeaders = Record | (() => Promise); @@ -187,7 +193,34 @@ export class RemoteMCP implements ToolSource { if ('authRequired' in headersResult) { return { authRequired: headersResult.authRequired }; } - return this.connectAndRun(headersResult.headers, operation, true); + const { onUnauthorized } = headersResult; + if (onUnauthorized === undefined) { + return this.connectAndRun(headersResult.headers, operation, true); + } + let rejected: RemoteMcpConnection | undefined; + const tracked = (connection: RemoteMcpConnection): Promise => { + rejected = connection; + return operation(connection); + }; + try { + return await this.connectAndRun(headersResult.headers, tracked, true); + } catch (error) { + if (!isAuthError(error)) { + throw error; + } + this.logger.info(`Remote MCP ${this.name} rejected supplied credentials, falling back to its auth flow`); + // Reset only the rejected connection so a sibling's newer one survives; a failed connect keeps its stale session. + if (rejected !== undefined) { + await this.resetConnection(rejected); + } else if (!this.isConnected) { + this.sessionId = undefined; + } + const fallback = await onUnauthorized(); + if ('authRequired' in fallback) { + return { authRequired: fallback.authRequired }; + } + return this.connectAndRun(fallback.headers, operation, true); + } } private async connectAndRun( diff --git a/packages/trueforge-core/src/core/mcp/remoteMcpClient.ts b/packages/trueforge-core/src/core/mcp/remoteMcpClient.ts index 7393602a3b..7cc2f05f60 100644 --- a/packages/trueforge-core/src/core/mcp/remoteMcpClient.ts +++ b/packages/trueforge-core/src/core/mcp/remoteMcpClient.ts @@ -123,10 +123,14 @@ function mcpConnectOutcome(error: unknown): McpConnectOutcome { return 'other'; } -function isAuthError(error: unknown): boolean { +/** Upstream rejected the credentials, whether at connect or on a later request. */ +export function isAuthError(error: unknown): boolean { if (!(error instanceof Error)) { return false; } + if (error instanceof McpConnectionError) { + return error.statusCode === 401; + } if ('code' in error && error.code === 401) { return true; } diff --git a/packages/trueforge-core/tests/core/mcp/remoteMcpServer.test.ts b/packages/trueforge-core/tests/core/mcp/remoteMcpServer.test.ts index 267f85bd69..926fd0df8f 100644 --- a/packages/trueforge-core/tests/core/mcp/remoteMcpServer.test.ts +++ b/packages/trueforge-core/tests/core/mcp/remoteMcpServer.test.ts @@ -430,6 +430,39 @@ describe('RemoteMCP + ToolSet', () => { expect(state.callToolCalls).toBe(0); }); + it('falls back to onUnauthorized when supplied credentials are rejected at connect', async () => { + installFakeConnection({ connectError: new McpConnectionError('upstream 401', 401) }); + const authRequired: MCPAuthRequired = { + servers: [{ id: 'inline-id-123', name: 'my-inline', auth_url: 'https://auth.example' }], + }; + const onUnauthorized = jest.fn(() => Promise.resolve({ authRequired })); + const server = makeServer({ + headers: () => Promise.resolve({ headers: { Authorization: 'Bearer caller' }, onUnauthorized }), + }); + + await expect(server.listTools()).resolves.toEqual({ authRequired }); + expect(onUnauthorized).toHaveBeenCalledTimes(1); + }); + + it('reconnects with fallback headers when a call is rejected mid-session', async () => { + const state = installFakeConnection({ sessionId: 'sess-1' }); + const server = makeServer({ + headers: () => + Promise.resolve({ + headers: { Authorization: 'Bearer caller' }, + onUnauthorized: () => Promise.resolve({ headers: { Authorization: 'Bearer fallback' } }), + }), + }); + + await server.listTools(); + state.queueCallToolError(Object.assign(new Error('HTTP 401'), { code: 401 })); + const res = await server.callTool({ name: 'read_thing', arguments: {} }); + + expect(res).toMatchObject({ result: { content: [{ type: 'text', text: 'called read_thing' }] } }); + expect(state.connectCalls).toBe(2); + expect(mockConnect.mock.lastCall?.[0].headers).toEqual({ Authorization: 'Bearer fallback' }); + }); + it('emits init for a stateless (SSE) server on connect (matches gateway strict-compare behavior)', async () => { // Stateless connection reports a null session id. installFakeConnection({ sessionId: null }); diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.ts index bc0bed7dee..f4c1543d6d 100644 --- a/packages/trueforge/src/apis/turns.ts +++ b/packages/trueforge/src/apis/turns.ts @@ -74,6 +74,7 @@ import type { ISkillStore } from '../db/skillStore'; import type { TurnMetadata } from '../db/turnMetadata'; import type { IWebSearchProviderStore } from '../db/webSearchProviderStore'; import { currentLogContext, runWithLogContext, updateLogContext } from '../logger'; +import { X_TFG_MCP_HEADERS } from '../mcp/perServerMcpHeaders'; import type { TenantMemoryDeps } from '../memory/providers'; import { resolveSessionMemory } from '../memory/sessionMemory'; import { @@ -107,7 +108,6 @@ import { restoreTurnEventLog } from '../runtime/turnEventLogRestore'; import { MAX_SESSION_TITLE_LENGTH } from '../schemas/session'; import { assertGatewayMetadataRequestHeaders, X_TFY_METADATA } from '../truefoundry/gatewayMetadata'; import { X_TFG_MCP, X_TFG_MODELS, X_TFG_SKILLS, X_TFG_TOOLS } from '../truefoundry/inlineResources'; -import { X_TFG_MCP_HEADERS } from '../truefoundry/perServerMcpHeaders'; import { newId } from '../utils/id'; import { resolveWebSearchProvider } from '../websearch/providers'; import { canReadAgentBoundResource, canReadSession } from './agentAccess'; diff --git a/packages/trueforge/src/db/McpServerWithAuthStore.ts b/packages/trueforge/src/db/McpServerWithAuthStore.ts index 792fc9e2f9..cb93b5b5ae 100644 --- a/packages/trueforge/src/db/McpServerWithAuthStore.ts +++ b/packages/trueforge/src/db/McpServerWithAuthStore.ts @@ -1,6 +1,12 @@ -import type { RemoteMcpHeaders } from '@truefoundry/trueforge-core/core'; +import type { RemoteMcpHeaders, ResolveHeadersResult } from '@truefoundry/trueforge-core/core'; import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr'; import type { IOAuthTokenStore, OAuthClientRecord } from '../mcp/auth/types'; +import { + hasAuthorizationHeader, + overrideHeaders, + withoutAuthorization, + type PerServerMcpHeaders, +} from '../mcp/perServerMcpHeaders'; import { resolveConfiguredMcpRequestHeaders, resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer'; import { McpServerNotFoundError, @@ -18,19 +24,33 @@ import { } from './mcpServerStore'; import type { TurnMetadata } from './turnMetadata'; +async function resolveWithOverride(input: { + headers: RemoteMcpHeaders; + override: Record; +}): Promise { + const result = typeof input.headers === 'function' ? await input.headers() : { headers: input.headers }; + if ('authRequired' in result) { + return result; + } + return { headers: overrideHeaders({ base: result.headers, override: input.override }) }; +} + export class McpServerWithAuthStore implements IMcpServerWithAuthStore { readonly #store: IMcpServerStore; readonly #tokenStore: IOAuthTokenStore; readonly #clientName: string; + readonly #perServerHeaders: PerServerMcpHeaders; constructor(input: { store: IMcpServerStore; tokenStore: IOAuthTokenStore; clientName: string; + perServerHeaders?: PerServerMcpHeaders; }) { this.#store = input.store; this.#tokenStore = input.tokenStore; this.#clientName = input.clientName; + this.#perServerHeaders = input.perServerHeaders ?? {}; } listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise { @@ -57,11 +77,39 @@ export class McpServerWithAuthStore implements IMcpServerW return this.#store.deleteServer(input, transaction); } + /** Caller headers for the server go straight to it; one with Authorization skips its consent flow. */ resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string; turnMetadata?: TurnMetadata; }): RemoteMcpHeaders { + const registered = this.#resolveRegisteredHeaders(input); + const callerHeaders = this.#perServerHeaders[input.record.name]; + if (callerHeaders === undefined) { + return registered; + } + if (hasAuthorizationHeader(callerHeaders)) { + const headers = overrideHeaders({ + base: resolveConfiguredMcpRequestHeaders(input.record.manifest), + override: callerHeaders, + }); + const override = withoutAuthorization(callerHeaders); + return () => + Promise.resolve({ headers, onUnauthorized: () => resolveWithOverride({ headers: registered, override }) }); + } + if (typeof registered !== 'function') { + return overrideHeaders({ base: registered, override: callerHeaders }); + } + return async () => { + const result = await registered(); + if ('authRequired' in result) { + return result; + } + return { headers: overrideHeaders({ base: result.headers, override: callerHeaders }) }; + }; + } + + #resolveRegisteredHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders { const { record, userRef } = input; if (record.manifest.auth?.type === 'dcr') { return async () => { diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts index ea91204ce4..781474266c 100644 --- a/packages/trueforge/src/main.ts +++ b/packages/trueforge/src/main.ts @@ -319,8 +319,9 @@ async function createStandalonePersistence(options: { const tokenStore = new SqliteOAuthTokenStore(db); const agentStore = new SqliteAgentStore(db); const modelProviderStore = new SqliteModelProviderStore(db); + const mcpPersistenceStore = new SqliteMcpServerStore(db); const mcpServerStore = new McpServerWithAuthStore({ - store: new SqliteMcpServerStore(db), + store: mcpPersistenceStore, tokenStore, clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME, }); @@ -345,7 +346,12 @@ async function createStandalonePersistence(options: { mcpOAuthStore: mcpServerStore, redis: undefined, resolveAgentStore: () => agentStore, - resolveMcpServerStore: () => mcpServerStore, + resolveMcpServerStore: buildResolveMcpServerStore({ + persistenceStore: mcpPersistenceStore, + tokenStore, + client: undefined, + logger, + }), resolveModelProviderStore: () => modelProviderStore, resolveSkillStore: () => skillStore, resolveTurnSkillsStore: buildResolveTurnSkillsStore({ diff --git a/packages/trueforge/src/truefoundry/perServerMcpHeaders.ts b/packages/trueforge/src/mcp/perServerMcpHeaders.ts similarity index 57% rename from packages/trueforge/src/truefoundry/perServerMcpHeaders.ts rename to packages/trueforge/src/mcp/perServerMcpHeaders.ts index 549fd75a73..57b504c9cd 100644 --- a/packages/trueforge/src/truefoundry/perServerMcpHeaders.ts +++ b/packages/trueforge/src/mcp/perServerMcpHeaders.ts @@ -7,6 +7,7 @@ import { z } from 'zod'; * TrueForge authenticates the whole turn as one caller, so every MCP connection would otherwise * present that same identity. This carries the identity each individual server should see — * typically the end user behind the caller, for a server that resolves its own permissions. + * An entry carrying Authorization is used instead of that server's consent flow unless rejected. */ export const X_TFG_MCP_HEADERS = 'x-tfg-mcp-headers'; @@ -35,3 +36,26 @@ export function parsePerServerMcpHeaders(raw: string): PerServerMcpHeaders { } return parsed.data; } + +export function hasAuthorizationHeader(headers: Record | undefined): headers is Record { + return headers !== undefined && Object.keys(headers).some(name => name.toLowerCase() === 'authorization'); +} + +export function withoutAuthorization(headers: Record | undefined): Record { + if (headers === undefined) { + return {}; + } + return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'authorization')); +} + +/** Header names are case-insensitive, so an override must replace a base entry under any casing. */ +export function overrideHeaders(input: { + base: Record; + override: Record; +}): Record { + const overridden = new Set(Object.keys(input.override).map(name => name.toLowerCase())); + return { + ...Object.fromEntries(Object.entries(input.base).filter(([name]) => !overridden.has(name.toLowerCase()))), + ...input.override, + }; +} diff --git a/packages/trueforge/src/resolvers.ts b/packages/trueforge/src/resolvers.ts index 6bfdbfa8f1..27a2174f9c 100644 --- a/packages/trueforge/src/resolvers.ts +++ b/packages/trueforge/src/resolvers.ts @@ -22,6 +22,7 @@ import type { ISandboxProviderStore } from './db/sandboxProviderStore'; import type { ISkillStore } from './db/skillStore'; import type { IWebSearchProviderStore } from './db/webSearchProviderStore'; import type { IOAuthTokenStore } from './mcp/auth/types'; +import { parsePerServerMcpHeaders, X_TFG_MCP_HEADERS, type PerServerMcpHeaders } from './mcp/perServerMcpHeaders'; import type { MemoryProviderCache, TenantMemoryDeps } from './memory/providers'; import { headerValue } from './truefoundry/gatewayMetadata'; import { InlineMcpServerStore } from './truefoundry/InlineMcpServerStore'; @@ -42,11 +43,6 @@ import { } from './truefoundry/inlineResources'; import { InlineSkillStore } from './truefoundry/InlineSkillStore'; import { InlineCapabilitiesStore } from './truefoundry/inlineTools'; -import { - parsePerServerMcpHeaders, - X_TFG_MCP_HEADERS, - type PerServerMcpHeaders, -} from './truefoundry/perServerMcpHeaders'; import { TrueFoundryAgentStore } from './truefoundry/TrueFoundryAgentStore'; import { TrueFoundryMcpServerStore } from './truefoundry/TrueFoundryMcpServerStore'; import { TrueFoundryModelProviderStore } from './truefoundry/TrueFoundryModelProviderStore'; @@ -110,7 +106,8 @@ export function buildResolveModelProviderStore(options: { } /** - * Per-request MCP store over ServiceFoundry. `runAsAgent` selects a saved agent's token for turns. + * Per-request MCP store over ServiceFoundry, else the DB store with any `x-tfg-mcp-headers`. + * `runAsAgent` selects a saved agent's token for turns. */ export function buildResolveMcpServerStore(options: { persistenceStore: IMcpServerStore; @@ -138,6 +135,14 @@ export function buildResolveMcpServerStore(options: { } return store; } + if (input.perServerHeaders !== undefined) { + return new McpServerWithAuthStore({ + store: options.persistenceStore, + tokenStore: options.tokenStore, + clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME, + perServerHeaders: input.perServerHeaders, + }); + } return withAuthMcpPersistenceStore; }; } diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts index 671384a9fe..448b1a54ed 100644 --- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts +++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts @@ -1,4 +1,4 @@ -import { McpConnectionError, type RemoteMcpHeaders } from '@truefoundry/trueforge-core/core'; +import { McpConnectionError, type RemoteMcpHeaders, type ResolveHeadersResult } from '@truefoundry/trueforge-core/core'; import { HTTPException } from 'hono/http-exception'; import type { Logger } from 'winston'; import type { RequestContext, RequestSubject } from '../auth/identity'; @@ -20,6 +20,7 @@ import { } from '../db/mcpServerStore'; import type { TurnMetadata } from '../db/turnMetadata'; import type { OAuthClientRecord } from '../mcp/auth/types'; +import { hasAuthorizationHeader, withoutAuthorization, type PerServerMcpHeaders } from '../mcp/perServerMcpHeaders'; import { resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer'; import { accessTokenForRequest, @@ -37,7 +38,6 @@ import { toTrueFoundryMcpManifest, type SfyMcpServerSummary, } from './mapSfyMcpServers'; -import type { PerServerMcpHeaders } from './perServerMcpHeaders'; import type { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient'; export type TrueFoundryMcpApiClient = Pick< @@ -52,12 +52,8 @@ export type TrueFoundryMcpApiClient = Pick< | 'getTenantControlPlaneUrl' >; -function withoutAuthorization(headers: Record | undefined): Record { - if (headers === undefined) { - return {}; - } - return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'authorization')); -} +/** Per-server upstream headers the TrueFoundry gateway applies after its own caller auth. */ +const X_TFY_MCP_HEADERS = 'x-tfy-mcp-headers'; /** * Absolute FE landing for the upstream authorize `redirectURL`. @@ -109,14 +105,18 @@ export class TrueFoundryMcpServerStore implements IMcpServ this.#perServerHeaders = input.perServerHeaders ?? {}; } - /** Gateway Bearer (+ optional per-server overrides); SFY authorize first, else authRequired. */ + /** + * Gateway Bearer (+ optional per-server overrides); SFY authorize first, else authRequired. + * A caller entry with Authorization is sent as `x-tfy-mcp-headers`; authorize runs only on a 401. + */ resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string; turnMetadata?: TurnMetadata; }): RemoteMcpHeaders { const { record, userRef, turnMetadata } = input; - return async () => { + const callerHeaders = this.#perServerHeaders[record.name]; + const viaAuthorize = async (): Promise => { const status = await this.authorize({ tenant_id: record.tenant_id, name: record.name, @@ -137,12 +137,24 @@ export class TrueFoundryMcpServerStore implements IMcpServ } const authorization = await this.#resolveGatewayAuthorization(); const invokeHeaders = { - ...withoutAuthorization(this.#perServerHeaders[record.name]), + ...withoutAuthorization(callerHeaders), ...gatewayHeaders(authorization), ...gatewayMetadataHeadersForTurn(turnMetadata), }; return { headers: invokeHeaders }; }; + if (!hasAuthorizationHeader(callerHeaders)) { + return viaAuthorize; + } + // Each connection targets one server's gateway proxy, which takes a flat header map for it. + return async () => ({ + headers: { + ...gatewayHeaders(await this.#resolveGatewayAuthorization()), + ...gatewayMetadataHeadersForTurn(turnMetadata), + [X_TFY_MCP_HEADERS]: JSON.stringify(callerHeaders), + }, + onUnauthorized: viaAuthorize, + }); } async listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise { diff --git a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts b/packages/trueforge/tests/unit/mcp/perServerMcpHeaders.test.ts similarity index 58% rename from packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts rename to packages/trueforge/tests/unit/mcp/perServerMcpHeaders.test.ts index 1114ba0b4e..eee33e842a 100644 --- a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts +++ b/packages/trueforge/tests/unit/mcp/perServerMcpHeaders.test.ts @@ -1,12 +1,16 @@ import { HTTPException } from 'hono/http-exception'; import { createLogger } from 'winston'; +import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore'; import type { McpServerRecord } from '../../../src/db/mcpServerStore'; -import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken'; -import { parsePerServerMcpHeaders } from '../../../src/truefoundry/perServerMcpHeaders'; +import { createSqliteDb } from '../../../src/db/sqlite/client'; +import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore'; +import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore'; +import { parsePerServerMcpHeaders } from '../../../src/mcp/perServerMcpHeaders'; import { TrueFoundryMcpServerStore, type TrueFoundryMcpApiClient, } from '../../../src/truefoundry/TrueFoundryMcpServerStore'; +import { createTrueFoundryRequestContext } from '../../../src/truefoundry/accessToken'; function unusedClient(): TrueFoundryMcpApiClient { const unused = (): Promise => Promise.reject(new Error('unused')); @@ -127,28 +131,86 @@ describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => { expect(headers).toEqual({ Authorization: 'Bearer caller-token' }); }); - it.each(['Authorization', 'authorization', 'AUTHORIZATION', 'AuThOrIzAtIoN'])( - 'drops an override under %s, which object keys would otherwise keep beside the Bearer', + it.each(['Authorization', 'authorization', 'AUTHORIZATION'])( + 'sends an override under %s to the upstream via x-tfy-mcp-headers, never as the gateway Bearer', async name => { const headers = await invokeHeaders( - storeWith({ - 'tfy-platform-mcp': { [name]: 'Bearer smuggled' }, - }), + storeWith({ 'tfy-platform-mcp': { [name]: 'Bearer user' } }), 'tfy-platform-mcp', ); - expect(Object.values(headers)).toEqual(['Bearer caller-token']); + expect(headers).toEqual({ + Authorization: 'Bearer caller-token', + 'x-tfy-mcp-headers': JSON.stringify({ [name]: 'Bearer user' }), + }); }, ); - it('keeps the rest of an override that also carried an authorization key', async () => { - const headers = await invokeHeaders( - storeWith({ - 'tfy-platform-mcp': { authorization: 'Bearer smuggled', 'x-tfy-mcp-headers': '{"a":"b"}' }, + it('skips authorize for a caller Authorization, and runs it only when the upstream rejects it', async () => { + const getMcpAuthorize = jest.fn(async () => ({ + status: 'auth_required' as const, + authorization_url: 'https://auth.example/consent', + })); + const store = new TrueFoundryMcpServerStore({ + client: { ...unusedClient(), getMcpAuthorize }, + requestContext: createTrueFoundryRequestContext({ + tenant_id: 'default', + subject: { id: 'user-1', type: 'user', display_name: 'user-1' }, + roles: [], + user_credential: 'caller-token', }), - 'tfy-platform-mcp', - ); + agent: undefined, + logger: createLogger({ silent: true }), + perServerHeaders: { 'tfy-platform-mcp': { Authorization: 'Bearer user' } }, + }); + const resolve = store.resolveInvokeHeaders({ record: record('tfy-platform-mcp'), userRef: 'user-1' }); + if (typeof resolve !== 'function') { + throw new Error('expected a headers resolver'); + } + + const resolved = await resolve(); + expect(getMcpAuthorize).not.toHaveBeenCalled(); + if (!('onUnauthorized' in resolved) || resolved.onUnauthorized === undefined) { + throw new Error('expected a fallback to the consent flow'); + } + await expect(resolved.onUnauthorized()).resolves.toEqual({ + authRequired: { + servers: [{ id: 'tfy-platform-mcp', name: 'tfy-platform-mcp', auth_url: 'https://auth.example/consent' }], + }, + }); + }); +}); + +describe('McpServerWithAuthStore.resolveInvokeHeaders', () => { + const ossRecord: McpServerRecord = { + id: 'oauth-mcp', + tenant_id: 'default', + name: 'oauth-mcp', + manifest: { + type: 'remote', + name: 'oauth-mcp', + url: 'https://mcp.example/mcp', + description: '', + auth: { type: 'dcr' }, + }, + created_at: '2026-01-15T12:00:00.000Z', + updated_at: '2026-01-16T12:00:00.000Z', + }; + + it('forwards a caller Authorization directly instead of starting the DCR consent flow', async () => { + const db = createSqliteDb(':memory:'); + const store = new McpServerWithAuthStore({ + store: new SqliteMcpServerStore(db), + tokenStore: new SqliteOAuthTokenStore(db), + clientName: 'test-client', + perServerHeaders: { 'oauth-mcp': { Authorization: 'Bearer user', 'x-extra': '1' } }, + }); - expect(headers).toEqual({ Authorization: 'Bearer caller-token', 'x-tfy-mcp-headers': '{"a":"b"}' }); + const resolve = store.resolveInvokeHeaders({ record: ossRecord, userRef: 'user-1' }); + if (typeof resolve !== 'function') { + throw new Error('expected a headers resolver'); + } + await expect(resolve()).resolves.toMatchObject({ headers: { Authorization: 'Bearer user', 'x-extra': '1' } }); + await db.destroy(); }); });