Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
6d85393
feat: x-tfg-mcp-headers to pass MCP credentials and skip consent, wit…
rutvij-menavlikar Nov 10, 2026
c09705e
Merge remote-tracking branch 'origin/main' into rutvij/age-2723_1
cursoragent Nov 12, 2026
b6007af
feat: use gateway 401 authorization_urls for MCP auth_required; drop …
cursoragent Nov 12, 2026
cf1d6c5
refactor: trim MCP auth changes and shorten comments (AGE-2723)
cursoragent Nov 12, 2026
a15ecff
chore: merge changesets into one (AGE-2723)
cursoragent Nov 12, 2026
e57439b
fix: accept only http(s) consent URLs from MCP 401 bodies (AGE-2723)
cursoragent Nov 12, 2026
014c4bc
feat: accept nested x-tfg-mcp-headers entries for virtual MCPs (AGE-2…
cursoragent Nov 12, 2026
0550d0e
chore: keep x-tfg-mcp-headers error message and shorten changeset (AG…
cursoragent Nov 12, 2026
8ca71f6
Merge branch 'main' into rutvij/age-2723_1
rutvij-menavlikar Nov 12, 2026
76eb522
feat: forward nested x-tfg-mcp-headers entries in open-source mode to…
cursoragent Nov 12, 2026
d16ae4a
Merge remote-tracking branch 'origin/rutvij/age-2723_1' into rutvij/a…
cursoragent Nov 12, 2026
d5efb54
chore: keep original doc wording for moved MCP header helpers (AGE-2723)
cursoragent Nov 12, 2026
0027e08
feat: send nested x-tfg-mcp-headers entries as plain headers in open-…
cursoragent Nov 12, 2026
11b1046
fix: reject managed MCP transport headers in x-tfg-mcp-headers (AGE-2…
cursoragent Nov 12, 2026
550abe6
Merge branch 'main' into rutvij/age-2723_1
rutvij-menavlikar Nov 12, 2026
59979c3
fix: keep onUnauthorized fallback when stamping session header (AGE-2…
rutvij-menavlikar Nov 13, 2026
64fd20f
fix: cap 401 SSE bodies and drop the rejected MCP session on consent …
cursoragent Nov 13, 2026
5f8755e
refactor: move per-server MCP headers out of src/mcp and keep TrueFou…
cursoragent Nov 16, 2026
408c61d
refactor: move TrueFoundry gateway 401 parsing into truefoundry/ (AGE…
cursoragent Nov 16, 2026
3aa59d9
Revert "refactor: move TrueFoundry gateway 401 parsing into truefound…
cursoragent Nov 16, 2026
f7199c7
Revert "refactor: move per-server MCP headers out of src/mcp and keep…
cursoragent Nov 16, 2026
a7c46dd
refactor: move per-server MCP headers to src/runtime and split TrueFo…
cursoragent Nov 16, 2026
39ed31a
refactor: accept virtual MCP header entries only in TrueFoundry mode …
cursoragent Nov 16, 2026
3206498
refactor: drop the onUnauthorized fallback; a 401 either carries cons…
cursoragent Nov 16, 2026
9aae945
chore: list managed MCP headers in the x-tfg-mcp-headers error (AGE-2…
cursoragent Nov 17, 2026
82ce524
refactor: on a 401, offer the server's own consent flow instead of pa…
cursoragent Nov 17, 2026
f18ecbb
refactor: keep open-source 401s a hard failure for caller headers too…
cursoragent Nov 17, 2026
6b8873c
fix: keep the upstream 401 when the consent lookup fails (AGE-2723)
cursoragent Nov 17, 2026
53605f0
refactor: restore up-front MCP authorize; consent on 401 only for cal…
cursoragent Nov 17, 2026
6d2e944
refactor: keep main's TrueFoundry authorize path verbatim; caller-cre…
cursoragent Nov 17, 2026
7578551
refactor: caller-credential 401s fail like any other 401; drop the co…
cursoragent Nov 17, 2026
e1acaff
feat: final 401 handling for x-tfg-mcp-headers per agreed spec (AGE-2…
cursoragent Nov 17, 2026
e36c89c
fix: start DCR consent on a 401 without deleting the stored token (AG…
cursoragent Nov 17, 2026
43d9a6d
Revert "fix: start DCR consent on a 401 without deleting the stored t…
cursoragent Nov 17, 2026
581baea
fix: keep the 401 consent hook when stamping the session header (AGE-…
rutvij-menavlikar Nov 17, 2026
75a6713
fix: start DCR consent on a 401 without deleting the stored token (AG…
cursoragent Nov 17, 2026
e4449a4
Merge branch 'main' into rutvij/age-2723_1
rutvij-menavlikar Nov 17, 2026
413960a
Minor fixes pointed by cursor review
chiragjn Nov 18, 2026
f52d1b5
refactor: rename per-server override headers and tidy 401 consent han…
cursoragent Nov 18, 2026
20679e0
Merge branch 'main' into rutvij/age-2723_1
rutvij-menavlikar Nov 18, 2026
9695d62
test: drop redundant x-tfg-mcp-headers tests (AGE-2723)
cursoragent Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/x-tfg-mcp-headers-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@truefoundry/trueforge-core': patch
'@truefoundry/trueforge': patch
---

`x-tfg-mcp-headers` passes per-MCP-server headers. Open-source mode merges a server's entry over its registered headers, and an entry `Authorization` skips DCR. TrueFoundry mode sends the entry (flat, or a nested virtual MCP map) as `x-tfy-mcp-headers` and no longer calls authorize before connecting. On a 401: open-source fails when the entry carried `Authorization`, otherwise a DCR server restarts consent; TrueFoundry fails whenever the server had an entry, otherwise asks authorize for a consent URL and fails with 422 when authorize returns none or reports no consent is needed.
44 changes: 41 additions & 3 deletions packages/trueforge-core/src/core/mcp/RemoteMCP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { paginateWithCursorGuard } from './pagination';
import {
connectRemoteMcp,
DEFAULT_MAX_MCP_RESPONSE_BYTES,
isAuthError,
isSessionExpiredError,
type RemoteMcpConnection,
type RemoteMcpFetch,
Expand All @@ -40,8 +41,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<string, string> } | { authRequired: MCPAuthRequired };
/**
* What a headers resolver returns: the headers to send, or a signal that auth is required.
* On a 401, `authRequiredOnUnauthorized` may offer consent; without it, or if it returns undefined, the 401 fails.
*/
export type ResolveHeadersResult =
| { headers: Record<string, string>; authRequiredOnUnauthorized?: () => Promise<MCPAuthRequired | undefined> }
Comment thread
rutvij-menavlikar marked this conversation as resolved.
Resolved
| { authRequired: MCPAuthRequired };
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/** Static headers, or a resolver (invoked at connect) returning headers or signalling auth-required. */
export type RemoteMcpHeaders = Record<string, string> | (() => Promise<ResolveHeadersResult>);
Expand Down Expand Up @@ -184,7 +190,39 @@ export class RemoteMCP implements ToolSource {
if ('authRequired' in headersResult) {
return { authRequired: headersResult.authRequired };
}
return this.connectAndRun(headersResult.headers, operation, true);
let used: RemoteMcpConnection | undefined;
const tracked = (connection: RemoteMcpConnection): Promise<T> => {
used = connection;
return operation(connection);
};
try {
return await this.connectAndRun(headersResult.headers, tracked, true);
} catch (error) {
let authRequired: MCPAuthRequired | undefined = undefined;
try {
if (isAuthError(error)) {
authRequired = await headersResult.authRequiredOnUnauthorized?.();
}
} catch (recoveryError) {
// Rethrow the recovery error unchanged so its status survives, with the 401 it replaced as
// `cause` — error logging already walks that chain.
if (recoveryError instanceof Error && recoveryError.cause === undefined) {
recoveryError.cause = error;
}
throw recoveryError;
}
if (authRequired === undefined) {
throw error;
}
// Reset only the rejected connection; a failed connect still leaves the old session and tools.
if (used !== undefined) {
await this.resetConnection(used);
} else if (!this.isConnected) {
this.sessionId = undefined;
this.cachedTools = undefined;
}
return { authRequired };
}
}

private async connectAndRun<T>(
Expand Down
5 changes: 4 additions & 1 deletion packages/trueforge-core/src/core/mcp/remoteMcpClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,13 @@ function mcpConnectOutcome(error: unknown): McpConnectOutcome {
return 'other';
}

function isAuthError(error: unknown): boolean {
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;
}
Expand Down
51 changes: 51 additions & 0 deletions packages/trueforge-core/tests/core/mcp/remoteMcpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,57 @@ describe('RemoteMCP + ToolSet', () => {
expect(state.callToolCalls).toBe(0);
});

it('returns authRequired when the resolver offers consent for a 401', async () => {
installFakeConnection({ connectError: new McpConnectionError('upstream 401', 401) });
const authRequired: MCPAuthRequired = {
servers: [{ id: 'inline-id-123', name: 'my-inline', auth_url: 'https://auth.example/consent' }],
};
const server = makeServer({
headers: () => Promise.resolve({ headers: {}, authRequiredOnUnauthorized: () => Promise.resolve(authRequired) }),
});

await expect(server.listTools()).resolves.toEqual({ authRequired });
});

it('drops the rejected connection when a call gets a 401 with consent, so the next call reconnects', async () => {
const state = installFakeConnection({ sessionId: 'sess-1' });
const authRequired: MCPAuthRequired = {
servers: [{ id: 'inline-id-123', name: 'my-inline', auth_url: 'https://auth.example/consent' }],
};
const server = makeServer({
headers: () => Promise.resolve({ headers: {}, authRequiredOnUnauthorized: () => Promise.resolve(authRequired) }),
});

await server.listTools();
state.queueCallToolError(Object.assign(new Error('HTTP 401'), { code: 401 }));
await expect(server.callTool({ name: 'read_thing', arguments: {} })).resolves.toEqual({ authRequired });
await server.callTool({ name: 'read_thing', arguments: {} });

expect(state.connectCalls).toBe(2);
});

it('throws the 401 when the resolver offers no consent', async () => {
installFakeConnection({ connectError: new McpConnectionError('upstream 401', 401) });
const server = makeServer({
headers: () => Promise.resolve({ headers: {}, authRequiredOnUnauthorized: () => Promise.resolve(undefined) }),
});

await expect(server.listTools()).rejects.toMatchObject({ statusCode: 401 });
});

it('propagates the resolver error when the consent lookup fails', async () => {
installFakeConnection({ connectError: new McpConnectionError('upstream 401', 401) });
const server = makeServer({
headers: () =>
Promise.resolve({ headers: {}, authRequiredOnUnauthorized: () => Promise.reject(new Error('lookup failed')) }),
});

await expect(server.listTools()).rejects.toMatchObject({
message: 'lookup failed',
cause: expect.objectContaining({ statusCode: 401 }),
});
});

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 });
Expand Down
6 changes: 4 additions & 2 deletions packages/trueforge/src/apis/turns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ import {
type EventSubscriptionPollOptions,
type EventSubscriptionRegistry,
} from '../runtime/event-subscription';
import { X_TFG_MCP_HEADERS } from '../runtime/perServerMcpHeaders';
import { validateSandboxFilePath } from '../runtime/sandboxFilePath';
import {
buildTurnSandbox,
Expand All @@ -123,7 +124,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';
Expand Down Expand Up @@ -832,7 +832,9 @@ function withTurnSessionHeader(connection: McpConnection, sessionId: string): Mc
...connection,
headers: async (): Promise<ResolveHeadersResult> => {
const resolved = await headers();
return 'authRequired' in resolved ? resolved : { headers: { ...resolved.headers, ...sessionHeader } };
return 'authRequired' in resolved
? resolved
: { ...resolved, headers: { ...resolved.headers, ...sessionHeader } };
},
};
}
Expand Down
36 changes: 32 additions & 4 deletions packages/trueforge/src/db/McpServerWithAuthStore.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { RemoteMcpHeaders } from '@truefoundry/trueforge-core/core';
import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';
import type { RemoteMcpHeaders, ResolveHeadersResult } from '@truefoundry/trueforge-core/core';
import { beginMcpAuthorization, isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';
import type { IOAuthTokenStore, OAuthClientRecord } from '../mcp/auth/types';
import { withServerOverrideHeaders, type PerServerMcpHeaders } from '../runtime/perServerMcpHeaders';
import { resolveConfiguredMcpRequestHeaders, resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer';
import {
McpServerNotFoundError,
Expand All @@ -22,15 +23,18 @@ export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerW
readonly #store: IMcpServerStore<TTransaction>;
readonly #tokenStore: IOAuthTokenStore<TTransaction>;
readonly #clientName: string;
readonly #perServerHeaders: PerServerMcpHeaders;

constructor(input: {
store: IMcpServerStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
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<McpServerRecord[]> {
Expand Down Expand Up @@ -62,9 +66,18 @@ export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerW
userRef: string;
turnMetadata?: TurnMetadata;
}): RemoteMcpHeaders {
const { record } = input;
return withServerOverrideHeaders({
serverOverrideHeaders: this.#perServerHeaders[record.name],
storeHeaders: this.#resolveStoreHeaders(input),
configuredHeaders: resolveConfiguredMcpRequestHeaders(record.manifest),
});
}

#resolveStoreHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders {
const { record, userRef } = input;
if (record.manifest.auth?.type === 'dcr') {
return async () => {
return async (): Promise<ResolveHeadersResult> => {
const result = await resolveMcpAuth({
tokenStore: this.#tokenStore,
mcpServerStore: this.#store,
Expand All @@ -82,7 +95,22 @@ export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerW
},
};
}
return { headers: result.headers };
return {
headers: result.headers,
// On a 401, start DCR consent; the stored token stays until the callback replaces it.
authRequiredOnUnauthorized: async () => {
const authorizationUrl = await beginMcpAuthorization({
tokenStore: this.#tokenStore,
mcpServerStore: this.#store,
serverId: record.id,
userRef,
mcpServerUrl: record.manifest.url,
mcpServerName: record.name,
clientName: this.#clientName,
});
return { servers: [{ id: record.name, name: record.name, auth_url: authorizationUrl.href }] };
},
};
};
}
return resolveConfiguredMcpRequestHeaders(record.manifest);
Expand Down
10 changes: 8 additions & 2 deletions packages/trueforge/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
Expand All @@ -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({
Expand Down
40 changes: 37 additions & 3 deletions packages/trueforge/src/mcp/auth/mcpDcr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ export async function createMcpOAuthClient(params: {

/**
* Returns the stored OAuth client for `serverId`, or discovers + DCR-registers and persists one.
* Used from `resolveMcpAuth` only — callers that already hold the client should pass it through.
* Callers that already hold the client should pass it to `buildMcpAuthorizationUrl` directly.
*/
export async function ensureMcpClientRegistered(params: {
mcpServerStore: IOAuthClientStore;
Expand Down Expand Up @@ -237,6 +237,39 @@ export async function buildMcpAuthorizationUrl(params: {
return { authorizationUrl: started.authorizationUrl, state };
}

/**
* Ensures a DCR client exists for the server, then builds the authorize URL and stores the pending
* PKCE row. Shared by the pre-connect consent path and the 401 recovery path.
*/
export async function beginMcpAuthorization(params: {
tokenStore: IOAuthTokenStore;
mcpServerStore: IOAuthClientStore;
serverId: string;
userRef: string;
mcpServerUrl: string;
mcpServerName: string;
clientName: string;
returnTo?: string;
}): Promise<URL> {
const client = await ensureMcpClientRegistered({
mcpServerStore: params.mcpServerStore,
serverId: params.serverId,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
clientName: params.clientName,
});
const { authorizationUrl } = await buildMcpAuthorizationUrl({
tokenStore: params.tokenStore,
client,
serverId: params.serverId,
userRef: params.userRef,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
...(params.returnTo !== undefined ? { returnTo: params.returnTo } : {}),
});
return authorizationUrl;
}

export async function resolveMcpAuth(params: {
tokenStore: IOAuthTokenStore;
mcpServerStore: IOAuthClientStore;
Expand Down Expand Up @@ -279,13 +312,14 @@ export async function resolveMcpAuth(params: {
if (token) {
await params.tokenStore.deleteToken(tokenKey);
}
const { authorizationUrl: authUrl } = await buildMcpAuthorizationUrl({
const authUrl = await beginMcpAuthorization({
tokenStore: params.tokenStore,
client,
mcpServerStore: params.mcpServerStore,
serverId: params.serverId,
userRef: params.userRef,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
clientName: params.clientName,
...(params.returnTo !== undefined ? { returnTo: params.returnTo } : {}),
});
return { authUrl };
Expand Down
Loading
Loading