Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

feat: per-MCP-server request headers via x-tfg-mcp-headers (#567)

pranjaltrvd185dc04565d6
diff --git a/.changeset/tfg-per-server-mcp-headers.md b/.changeset/tfg-per-server-mcp-headers.md
new file mode 100644
index 000000000..bf3718b88
--- /dev/null
+++ b/.changeset/tfg-per-server-mcp-headers.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+Per-MCP-server request headers via `x-tfg-mcp-headers`, merged into the invoke headers for the named server. Lets a caller that authenticates as one identity give each MCP server the identity it should actually see.
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index 2c0ae33fb..dfafa7719 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -83,6 +83,7 @@ import { PACKAGE_VERSION } from './packageVersion';
import { ActiveTurnRegistry } from './runtime/activeTurns';
import { EventSubscriptionRegistry } from './runtime/event-subscription';
import { printStandaloneStartupBanner } from './startupBanner';
+import { parsePerServerMcpHeaders, X_TFG_MCP_HEADERS } from './truefoundry/perServerMcpHeaders';
import { TrueFoundryMcpServerStore } from './truefoundry/TrueFoundryMcpServerStore';
import { TrueFoundryModelProviderStore } from './truefoundry/TrueFoundryModelProviderStore';
import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundryServiceFoundryServerClient';
@@ -161,10 +162,17 @@ function buildResolveMcpServerStore<TTransaction>(options: {
logger: options.logger,
tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
});
- return c =>
- c
- ? new TrueFoundryMcpServerStore<TTransaction>({ client, accessToken: requireRequestCredentialToken(c) })
- : withAuthPersistence;
+ return c => {
+ if (!c) {
+ return withAuthPersistence;
+ }
+ const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);
+ return new TrueFoundryMcpServerStore<TTransaction>({
+ client,
+ accessToken: requireRequestCredentialToken(c),
+ perServerHeaders: rawPerServerHeaders ? parsePerServerMcpHeaders(rawPerServerHeaders) : {},
+ });
+ };
}
/** SQLite stores; Redis unused (executor peering disabled). */
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
index f1cdfa44d..b4ad236f0 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
@@ -20,6 +20,7 @@ import {
toTrueFoundryMcpManifest,
type SfyMcpServerSummary,
} from './mapSfyMcpServers';
+import type { PerServerMcpHeaders } from './perServerMcpHeaders';
import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from './trueFoundryManaged';
import type { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
@@ -27,6 +28,13 @@ function managed(): never {
throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });
}
+function withoutAuthorization(headers: Record<string, string> | undefined): Record<string, string> {
+ if (headers === undefined) {
+ return {};
+ }
+ return Object.fromEntries(Object.entries(headers).filter(([name]) => name.toLowerCase() !== 'authorization'));
+}
+
/**
* Read-only MCP registry backed by ServiceFoundry + the tenant AI Gateway.
* Writes and local OAuth client columns are not supported — configure servers in TrueFoundry.
@@ -35,15 +43,29 @@ function managed(): never {
export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServerWithAuthStore<TTransaction> {
readonly #client: TrueFoundryServiceFoundryServerClient;
readonly #accessToken: string;
+ readonly #perServerHeaders: PerServerMcpHeaders;
- constructor(input: { client: TrueFoundryServiceFoundryServerClient; accessToken: string }) {
+ constructor(input: {
+ client: TrueFoundryServiceFoundryServerClient;
+ accessToken: string;
+ perServerHeaders?: PerServerMcpHeaders;
+ }) {
this.#client = input.client;
this.#accessToken = input.accessToken;
+ this.#perServerHeaders = input.perServerHeaders ?? {};
}
+ /**
+ * The gateway Bearer is what the gateway authorises `USE_MCP_SERVER` on; the overrides are cargo
+ * it forwards upstream. Writing the Bearer last is not enough on its own to protect it, because
+ * object keys are case-sensitive and header names are not: an override under another casing would
+ * survive as a separate key and reach the wire alongside it. So it is dropped, not overwritten.
+ */
resolveInvokeHeaders(record: McpServerRecord): Record<string, string> {
- void record;
- return { Authorization: `Bearer ${this.#accessToken}` };
+ return {
+ ...withoutAuthorization(this.#perServerHeaders[record.name]),
+ Authorization: `Bearer ${this.#accessToken}`,
+ };
}
async listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]> {
diff --git a/packages/trueforge/src/truefoundry/perServerMcpHeaders.ts b/packages/trueforge/src/truefoundry/perServerMcpHeaders.ts
new file mode 100644
index 000000000..549fd75a7
--- /dev/null
+++ b/packages/trueforge/src/truefoundry/perServerMcpHeaders.ts
@@ -0,0 +1,37 @@
+import { HTTPException } from 'hono/http-exception';
+import { z } from 'zod';
+
+/**
+ * Per-MCP-server request headers, keyed by server name.
+ *
+ * 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.
+ */
+export const X_TFG_MCP_HEADERS = 'x-tfg-mcp-headers';
+
+const PerServerMcpHeadersSchema = z.record(z.string().min(1), z.record(z.string().min(1), z.string()));
+
+export type PerServerMcpHeaders = z.infer<typeof PerServerMcpHeadersSchema>;
+
+/**
+ * Rejects a malformed value rather than dropping it: the alternative to failing is running a user's
+ * tool calls under the caller's own identity, which is the thing these headers exist to prevent.
+ * An absent header is the caller's to interpret.
+ */
+export function parsePerServerMcpHeaders(raw: string): PerServerMcpHeaders {
+ let decoded: unknown;
+ try {
+ decoded = JSON.parse(raw);
+ } catch (error) {
+ throw new HTTPException(400, { message: `${X_TFG_MCP_HEADERS} must be a JSON object`, cause: error });
+ }
+
+ const parsed = PerServerMcpHeadersSchema.safeParse(decoded);
+ if (!parsed.success) {
+ throw new HTTPException(400, {
+ message: `${X_TFG_MCP_HEADERS} must map each MCP server name to a header map`,
+ });
+ }
+ return parsed.data;
+}
diff --git a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
new file mode 100644
index 000000000..275806f29
--- /dev/null
+++ b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts
@@ -0,0 +1,85 @@
+import { HTTPException } from 'hono/http-exception';
+import type { McpServerRecord } from '../../../src/db/mcpServerStore';
+import { parsePerServerMcpHeaders } from '../../../src/truefoundry/perServerMcpHeaders';
+import { TrueFoundryMcpServerStore } from '../../../src/truefoundry/TrueFoundryMcpServerStore';
+
+const record = (name: string): McpServerRecord => ({ name }) as McpServerRecord;
+
+const storeWith = (perServerHeaders: Record<string, Record<string, string>>): TrueFoundryMcpServerStore =>
+ new TrueFoundryMcpServerStore({
+ client: {} as never,
+ accessToken: 'caller-token',
+ perServerHeaders,
+ });
+
+describe('parsePerServerMcpHeaders', () => {
+ it('parses a header map per server name', () => {
+ const raw = JSON.stringify({ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' } });
+
+ expect(parsePerServerMcpHeaders(raw)).toEqual({
+ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },
+ });
+ });
+
+ it.each([
+ ['not json', 'not-json'],
+ ['an array', '[]'],
+ ['a scalar', '"nope"'],
+ ['a server mapped to a string', JSON.stringify({ 'tfy-platform-mcp': 'Bearer user' })],
+ ['a header mapped to a number', JSON.stringify({ 'tfy-platform-mcp': { 'x-h': 1 } })],
+ ])('rejects %s rather than silently dropping the identity it carries', (_case, raw) => {
+ expect(() => parsePerServerMcpHeaders(raw)).toThrow(HTTPException);
+ });
+
+ it('keeps the parse failure as the cause, so a bad header can be debugged', () => {
+ expect(() => parsePerServerMcpHeaders('not-json')).toThrow(
+ expect.objectContaining({ cause: expect.any(SyntaxError) }),
+ );
+ });
+});
+
+describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {
+ it('sends only the gateway Bearer when a server has no override', () => {
+ expect(storeWith({}).resolveInvokeHeaders(record('tfy-docs-mcp'))).toEqual({
+ Authorization: 'Bearer caller-token',
+ });
+ });
+
+ it("merges that server's override on top of the Bearer", () => {
+ const headers = storeWith({
+ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },
+ }).resolveInvokeHeaders(record('tfy-platform-mcp'));
+
+ expect(headers).toEqual({
+ Authorization: 'Bearer caller-token',
+ 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}',
+ });
+ });
+
+ it('gives one server nothing of another, so an identity cannot reach the wrong upstream', () => {
+ const headers = storeWith({
+ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },
+ }).resolveInvokeHeaders(record('tfy-pylon-mcp'));
+
+ 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',
+ name => {
+ const headers = storeWith({
+ 'tfy-platform-mcp': { [name]: 'Bearer smuggled' },
+ }).resolveInvokeHeaders(record('tfy-platform-mcp'));
+
+ expect(Object.values(headers)).toEqual(['Bearer caller-token']);
+ },
+ );
+
+ it('keeps the rest of an override that also carried an authorization key', () => {
+ const headers = storeWith({
+ 'tfy-platform-mcp': { authorization: 'Bearer smuggled', 'x-tfy-mcp-headers': '{"a":"b"}' },
+ }).resolveInvokeHeaders(record('tfy-platform-mcp'));
+
+ expect(headers).toEqual({ Authorization: 'Bearer caller-token', 'x-tfy-mcp-headers': '{"a":"b"}' });
+ });
+});