Skip to content

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

feat: TFY integration MCP CRUD + catalog (#550)

Srajan Asthanaf17524548eb2
diff --git a/.changeset/truefoundry-managed-mcp.md b/.changeset/truefoundry-managed-mcp.md
new file mode 100644
index 000000000..d1bbd24a8
--- /dev/null
+++ b/.changeset/truefoundry-managed-mcp.md
@@ -0,0 +1,6 @@
+---
+"@truefoundry/trueforge": patch
+"@truefoundry/trueforge-sdk": patch
+---
+
+Add TrueFoundry-managed MCP list/get (SFY registry, gateway proxy URL, create/update 424).
diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json
index aa5809d9b..410fd969b 100644
--- a/.github/fern/openapi/openapi.json
+++ b/.github/fern/openapi/openapi.json
@@ -534,7 +534,7 @@
"$ref": "#/components/schemas/ResourceName"
},
"type": {
- "$ref": "#/components/schemas/MCPServerType"
+ "$ref": "#/components/schemas/CatalogMCPServerType"
},
"url": {
"description": "URL of the remote MCP server.",
@@ -550,6 +550,12 @@
],
"type": "object"
},
+ "CatalogMCPServerType": {
+ "enum": [
+ "remote"
+ ],
+ "type": "string"
+ },
"CatalogModel": {
"additionalProperties": false,
"properties": {
@@ -2154,7 +2160,7 @@
"$ref": "#/components/schemas/MCPServerType"
},
"url": {
- "description": "URL of the remote MCP server.",
+ "description": "MCP endpoint URL. For `truefoundry`, the resolved AI Gateway proxy URL.",
"format": "uri",
"type": "string"
}
@@ -2202,7 +2208,8 @@
},
"MCPServerType": {
"enum": [
- "remote"
+ "remote",
+ "truefoundry"
],
"type": "string"
},
@@ -5873,7 +5880,7 @@
},
"/api/v1/mcp-servers/{name}/authorize": {
"delete": {
- "description": "For auth.type dcr, deletes the stored OAuth token and returns the server with auth_status auth_required, keeping the dynamically registered OAuth client so the next authorize can reuse it. No-op for header or no-auth servers (returns the server unchanged).",
+ "description": "Disconnects OAuth for the MCP server when applicable and returns the updated server with auth_status. No-op when the server does not use stored OAuth tokens.",
"parameters": [
{
"description": "MCP server name.",
@@ -5896,7 +5903,7 @@
}
}
},
- "description": "The MCP server after disconnect (auth_required for dcr)."
+ "description": "The MCP server after disconnect."
},
"404": {
"content": {
@@ -5919,7 +5926,7 @@
"x-fern-sdk-method-name": "delete_authorization"
},
"get": {
- "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.",
+ "description": "Returns the current auth status for the MCP server. For OAuth (`auth.type` dcr), returns authenticated when a usable token exists; otherwise returns auth_required with an authorization URL. Optional return_to is where the OAuth callback redirects the browser; without it the callback returns JSON.",
"parameters": [
{
"description": "MCP server name.",
@@ -7910,6 +7917,16 @@
}
},
"description": "The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint)."
+ },
+ "424": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
}
},
"summary": "Create an MCP server",
@@ -7923,7 +7940,7 @@
"x-fern-sdk-method-name": "create"
},
"put": {
- "description": "Create or replace by `name`. Does not start DCR or change oauth client columns. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).",
+ "description": "Create or replace by `name`. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).",
"requestBody": {
"content": {
"application/json": {
@@ -7964,6 +7981,16 @@
}
},
"description": "The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint)."
+ },
+ "424": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
}
},
"summary": "Create or replace an MCP server",
diff --git a/docs/openapi.json b/docs/openapi.json
index aa5809d9b..410fd969b 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -534,7 +534,7 @@
"$ref": "#/components/schemas/ResourceName"
},
"type": {
- "$ref": "#/components/schemas/MCPServerType"
+ "$ref": "#/components/schemas/CatalogMCPServerType"
},
"url": {
"description": "URL of the remote MCP server.",
@@ -550,6 +550,12 @@
],
"type": "object"
},
+ "CatalogMCPServerType": {
+ "enum": [
+ "remote"
+ ],
+ "type": "string"
+ },
"CatalogModel": {
"additionalProperties": false,
"properties": {
@@ -2154,7 +2160,7 @@
"$ref": "#/components/schemas/MCPServerType"
},
"url": {
- "description": "URL of the remote MCP server.",
+ "description": "MCP endpoint URL. For `truefoundry`, the resolved AI Gateway proxy URL.",
"format": "uri",
"type": "string"
}
@@ -2202,7 +2208,8 @@
},
"MCPServerType": {
"enum": [
- "remote"
+ "remote",
+ "truefoundry"
],
"type": "string"
},
@@ -5873,7 +5880,7 @@
},
"/api/v1/mcp-servers/{name}/authorize": {
"delete": {
- "description": "For auth.type dcr, deletes the stored OAuth token and returns the server with auth_status auth_required, keeping the dynamically registered OAuth client so the next authorize can reuse it. No-op for header or no-auth servers (returns the server unchanged).",
+ "description": "Disconnects OAuth for the MCP server when applicable and returns the updated server with auth_status. No-op when the server does not use stored OAuth tokens.",
"parameters": [
{
"description": "MCP server name.",
@@ -5896,7 +5903,7 @@
}
}
},
- "description": "The MCP server after disconnect (auth_required for dcr)."
+ "description": "The MCP server after disconnect."
},
"404": {
"content": {
@@ -5919,7 +5926,7 @@
"x-fern-sdk-method-name": "delete_authorization"
},
"get": {
- "description": "For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.",
+ "description": "Returns the current auth status for the MCP server. For OAuth (`auth.type` dcr), returns authenticated when a usable token exists; otherwise returns auth_required with an authorization URL. Optional return_to is where the OAuth callback redirects the browser; without it the callback returns JSON.",
"parameters": [
{
"description": "MCP server name.",
@@ -7910,6 +7917,16 @@
}
},
"description": "The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint)."
+ },
+ "424": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
}
},
"summary": "Create an MCP server",
@@ -7923,7 +7940,7 @@
"x-fern-sdk-method-name": "create"
},
"put": {
- "description": "Create or replace by `name`. Does not start DCR or change oauth client columns. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).",
+ "description": "Create or replace by `name`. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).",
"requestBody": {
"content": {
"application/json": {
@@ -7964,6 +7981,16 @@
}
},
"description": "The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint)."
+ },
+ "424": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RequestErrorResponse"
+ }
+ }
+ },
+ "description": "Resource is managed by TrueFoundry (`TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL` is set)."
}
},
"summary": "Create or replace an MCP server",
diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md
index 01a8e751a..513a83723 100644
--- a/packages/trueforge-sdk/reference.md
+++ b/packages/trueforge-sdk/reference.md
@@ -508,7 +508,7 @@ await client.mcpServers.list();
<dl>
<dd>
-For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.
+Returns the current auth status for the MCP server. For OAuth (`auth.type` dcr), returns authenticated when a usable token exists; otherwise returns auth_required with an authorization URL. Optional return_to is where the OAuth callback redirects the browser; without it the callback returns JSON.
</dd>
</dl>
</dd>
@@ -579,7 +579,7 @@ await client.mcpServers.authorize("name");
<dl>
<dd>
-For auth.type dcr, deletes the stored OAuth token and returns the server with auth_status auth_required, keeping the dynamically registered OAuth client so the next authorize can reuse it. No-op for header or no-auth servers (returns the server unchanged).
+Disconnects OAuth for the MCP server when applicable and returns the updated server with auth_status. No-op when the server does not use stored OAuth tokens.
</dd>
</dl>
</dd>
@@ -2963,7 +2963,7 @@ await client.settings.mcpServers.create({
<dl>
<dd>
-Create or replace by `name`. Does not start DCR or change oauth client columns. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).
+Create or replace by `name`. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).
</dd>
</dl>
</dd>
diff --git a/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts b/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts
index 38dd6d2ff..6c76af5a7 100644
--- a/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts
@@ -103,7 +103,7 @@ export class McpServersClient {
}
/**
- * For servers without auth returns not_required, and for header credentials returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.
+ * Returns the current auth status for the MCP server. For OAuth (`auth.type` dcr), returns authenticated when a usable token exists; otherwise returns auth_required with an authorization URL. Optional return_to is where the OAuth callback redirects the browser; without it the callback returns JSON.
*
* @param {string} name - MCP server name.
* @param {TrueForge.AuthorizeMcpServersRequest} request
@@ -250,7 +250,7 @@ export class McpServersClient {
}
/**
- * For auth.type dcr, deletes the stored OAuth token and returns the server with auth_status auth_required, keeping the dynamically registered OAuth client so the next authorize can reuse it. No-op for header or no-auth servers (returns the server unchanged).
+ * Disconnects OAuth for the MCP server when applicable and returns the updated server with auth_status. No-op when the server does not use stored OAuth tokens.
*
* @param {string} name - MCP server name.
* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.
diff --git a/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts b/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts
index df89c39e0..8de9d7c10 100644
--- a/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts
+++ b/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts
@@ -124,6 +124,7 @@ export class McpServersClient {
* @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.ConflictError}
* @throws {@link TrueForge.UnprocessableEntityError}
+ * @throws {@link TrueForge.FailedDependencyError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
*
@@ -228,6 +229,17 @@ export class McpServersClient {
}),
_response.rawResponse,
);
+ case 424:
+ throw new TrueForge.FailedDependencyError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
default:
throw new errors.TrueForgeError({
statusCode: _response.error.statusCode,
@@ -241,13 +253,14 @@ export class McpServersClient {
}
/**
- * Create or replace by `name`. Does not start DCR or change oauth client columns. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).
+ * Create or replace by `name`. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).
*
* @param {TrueForge.settings.UpdateMcpServerRequest} request
* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.
*
* @throws {@link TrueForge.BadRequestError}
* @throws {@link TrueForge.UnprocessableEntityError}
+ * @throws {@link TrueForge.FailedDependencyError}
* @throws {@link errors.TrueForgeError}
* @throws {@link errors.TrueForgeTimeoutError}
*
@@ -341,6 +354,17 @@ export class McpServersClient {
}),
_response.rawResponse,
);
+ case 424:
+ throw new TrueForge.FailedDependencyError(
+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {
+ unrecognizedObjectKeys: "passthrough",
+ allowUnrecognizedUnionMembers: true,
+ allowUnrecognizedEnumValues: true,
+ skipValidation: true,
+ breadcrumbsPrefix: ["response"],
+ }),
+ _response.rawResponse,
+ );
default:
throw new errors.TrueForgeError({
statusCode: _response.error.statusCode,
diff --git a/packages/trueforge-sdk/src/api/types/CatalogMcpServer.ts b/packages/trueforge-sdk/src/api/types/CatalogMcpServer.ts
index c07b94b35..0fc7b5a65 100644
--- a/packages/trueforge-sdk/src/api/types/CatalogMcpServer.ts
+++ b/packages/trueforge-sdk/src/api/types/CatalogMcpServer.ts
@@ -9,7 +9,7 @@ export interface CatalogMcpServer {
/** URL of the MCP server logo asset. */
logo?: string;
name: TrueForge.ResourceName;
- type: TrueForge.McpServerType;
+ type: TrueForge.CatalogMcpServerType;
/** URL of the remote MCP server. */
url: string;
}
diff --git a/packages/trueforge-sdk/src/api/types/CatalogMcpServerType.ts b/packages/trueforge-sdk/src/api/types/CatalogMcpServerType.ts
new file mode 100644
index 000000000..38b5cfafe
--- /dev/null
+++ b/packages/trueforge-sdk/src/api/types/CatalogMcpServerType.ts
@@ -0,0 +1,3 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export type CatalogMcpServerType = "remote";
diff --git a/packages/trueforge-sdk/src/api/types/McpServerManifest.ts b/packages/trueforge-sdk/src/api/types/McpServerManifest.ts
index d03e2dd49..185a2d46c 100644
--- a/packages/trueforge-sdk/src/api/types/McpServerManifest.ts
+++ b/packages/trueforge-sdk/src/api/types/McpServerManifest.ts
@@ -8,6 +8,6 @@ export interface McpServerManifest {
description: string;
name: TrueForge.ResourceName;
type: TrueForge.McpServerType;
- /** URL of the remote MCP server. */
+ /** MCP endpoint URL. For `truefoundry`, the resolved AI Gateway proxy URL. */
url: string;
}
diff --git a/packages/trueforge-sdk/src/api/types/McpServerType.ts b/packages/trueforge-sdk/src/api/types/McpServerType.ts
index 01de5c507..b3535bb27 100644
--- a/packages/trueforge-sdk/src/api/types/McpServerType.ts
+++ b/packages/trueforge-sdk/src/api/types/McpServerType.ts
@@ -1,3 +1,7 @@
// This file was auto-generated by Fern from our API Definition.
-export type McpServerType = "remote";
+export const McpServerType = {
+ Remote: "remote",
+ Truefoundry: "truefoundry",
+} as const;
+export type McpServerType = (typeof McpServerType)[keyof typeof McpServerType];
diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts
index 6e7605e40..5449fdeb5 100644
--- a/packages/trueforge-sdk/src/api/types/index.ts
+++ b/packages/trueforge-sdk/src/api/types/index.ts
@@ -22,6 +22,7 @@ export * from "./CancelSessionResponse.js";
export * from "./CapabilitiesData.js";
export * from "./CatalogCustomModelProvider.js";
export * from "./CatalogMcpServer.js";
+export * from "./CatalogMcpServerType.js";
export * from "./CatalogModel.js";
export * from "./CatalogModelProvider.js";
export * from "./CatalogSandboxProvider.js";
diff --git a/packages/trueforge-sdk/src/serialization/types/CatalogMcpServer.ts b/packages/trueforge-sdk/src/serialization/types/CatalogMcpServer.ts
index 7a8634ae5..50832a5e1 100644
--- a/packages/trueforge-sdk/src/serialization/types/CatalogMcpServer.ts
+++ b/packages/trueforge-sdk/src/serialization/types/CatalogMcpServer.ts
@@ -3,8 +3,8 @@
import type * as TrueForge from "../../api/index.js";
import * as core from "../../core/index.js";
import type * as serializers from "../index.js";
+import { CatalogMcpServerType } from "./CatalogMcpServerType.js";
import { McpServerManifestAuth } from "./McpServerManifestAuth.js";
-import { McpServerType } from "./McpServerType.js";
import { ResourceName } from "./ResourceName.js";
export const CatalogMcpServer: core.serialization.ObjectSchema<
@@ -15,7 +15,7 @@ export const CatalogMcpServer: core.serialization.ObjectSchema<
description: core.serialization.string(),
logo: core.serialization.string().optional(),
name: ResourceName,
- type: McpServerType,
+ type: CatalogMcpServerType,
url: core.serialization.string(),
});
@@ -25,7 +25,7 @@ export declare namespace CatalogMcpServer {
description: string;
logo?: string | null;
name: ResourceName.Raw;
- type: McpServerType.Raw;
+ type: CatalogMcpServerType.Raw;
url: string;
}
}
diff --git a/packages/trueforge-sdk/src/serialization/types/CatalogMcpServerType.ts b/packages/trueforge-sdk/src/serialization/types/CatalogMcpServerType.ts
new file mode 100644
index 000000000..e46d4d46b
--- /dev/null
+++ b/packages/trueforge-sdk/src/serialization/types/CatalogMcpServerType.ts
@@ -0,0 +1,14 @@
+// This file was auto-generated by Fern from our API Definition.
+
+import type * as TrueForge from "../../api/index.js";
+import * as core from "../../core/index.js";
+import type * as serializers from "../index.js";
+
+export const CatalogMcpServerType: core.serialization.Schema<
+ serializers.CatalogMcpServerType.Raw,
+ TrueForge.CatalogMcpServerType
+> = core.serialization.stringLiteral("remote");
+
+export declare namespace CatalogMcpServerType {
+ export type Raw = "remote";
+}
diff --git a/packages/trueforge-sdk/src/serialization/types/McpServerType.ts b/packages/trueforge-sdk/src/serialization/types/McpServerType.ts
index 642a25ed3..3f8f43d8f 100644
--- a/packages/trueforge-sdk/src/serialization/types/McpServerType.ts
+++ b/packages/trueforge-sdk/src/serialization/types/McpServerType.ts
@@ -5,8 +5,8 @@ import * as core from "../../core/index.js";
import type * as serializers from "../index.js";
export const McpServerType: core.serialization.Schema<serializers.McpServerType.Raw, TrueForge.McpServerType> =
- core.serialization.stringLiteral("remote");
+ core.serialization.enum_(["remote", "truefoundry"]);
export declare namespace McpServerType {
- export type Raw = "remote";
+ export type Raw = "remote" | "truefoundry";
}
diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts
index 6e7605e40..5449fdeb5 100644
--- a/packages/trueforge-sdk/src/serialization/types/index.ts
+++ b/packages/trueforge-sdk/src/serialization/types/index.ts
@@ -22,6 +22,7 @@ export * from "./CancelSessionResponse.js";
export * from "./CapabilitiesData.js";
export * from "./CatalogCustomModelProvider.js";
export * from "./CatalogMcpServer.js";
+export * from "./CatalogMcpServerType.js";
export * from "./CatalogModel.js";
export * from "./CatalogModelProvider.js";
export * from "./CatalogSandboxProvider.js";
diff --git a/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts b/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts
index 6228b045b..9e92895a3 100644
--- a/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts
+++ b/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts
@@ -220,6 +220,33 @@ describe("McpServersClient", () => {
}).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);
});
+ test("create (5)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { description: "x", name: "xy", type: "remote", url: "url" } };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .post("/api/v1/settings/mcp-servers")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(424)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.settings.mcpServers.create({
+ manifest: {
+ description: "x",
+ name: "xy",
+ type: "remote",
+ url: "url",
+ },
+ });
+ }).rejects.toThrow(TrueForgeTypes.FailedDependencyError);
+ });
+
test("create_or_update (1)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
@@ -329,6 +356,33 @@ describe("McpServersClient", () => {
}).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);
});
+ test("create_or_update (4)", async () => {
+ const server = mockServerPool.createServer();
+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
+ const rawRequestBody = { manifest: { description: "x", name: "xy", type: "remote", url: "url" } };
+ const rawResponseBody = { error: { message: "message" } };
+
+ server
+ .mockEndpoint()
+ .put("/api/v1/settings/mcp-servers")
+ .jsonBody(rawRequestBody)
+ .respondWith()
+ .statusCode(424)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.settings.mcpServers.createOrUpdate({
+ manifest: {
+ description: "x",
+ name: "xy",
+ type: "remote",
+ url: "url",
+ },
+ });
+ }).rejects.toThrow(TrueForgeTypes.FailedDependencyError);
+ });
+
test("get (1)", async () => {
const server = mockServerPool.createServer();
const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });
diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.ts
index 5e3436195..5d227f936 100644
--- a/packages/trueforge/scripts/write-openapi.ts
+++ b/packages/trueforge/scripts/write-openapi.ts
@@ -64,11 +64,12 @@ const app = createServerApp({
resolveModelProviderStore: () => new SqliteModelProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
mcpCatalog: McpCatalog.load(),
- mcpServerStore: new McpServerWithAuthStore({
- store: new SqliteMcpServerStore(db),
- tokenStore,
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- }),
+ resolveMcpServerStore: () =>
+ new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ }),
tokenStore,
skillCatalog: SkillCatalog.load(),
skillStore: new SqliteSkillStore(db),
diff --git a/packages/trueforge/src/apis/agents.ts b/packages/trueforge/src/apis/agents.ts
index b5925ae13..0a3158a40 100644
--- a/packages/trueforge/src/apis/agents.ts
+++ b/packages/trueforge/src/apis/agents.ts
@@ -26,7 +26,7 @@ import { TENANT_ID } from './sessions';
export interface AgentsRouterDeps<TTransaction> {
agentStore: IAgentStore<TTransaction>;
resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
- mcpServerStore: IMcpServerStore<TTransaction>;
+ resolveMcpServerStore: (c: Context) => IMcpServerStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
@@ -44,17 +44,19 @@ function toWireAgent(record: AgentRecord): Agent {
async function validateManifest<TTransaction>({
spec,
deps,
- store,
+ modelProviderStore,
+ mcpServerStore,
}: {
spec: AgentSpec;
deps: AgentsRouterDeps<TTransaction>;
- store: IModelProviderStore<TTransaction>;
+ modelProviderStore: IModelProviderStore<TTransaction>;
+ mcpServerStore: IMcpServerStore<TTransaction>;
}): Promise<AgentSpec> {
await validateAgentSpec({
spec,
tenant_id: TENANT_ID,
- modelProviderStore: store,
- mcpServerStore: deps.mcpServerStore,
+ modelProviderStore,
+ mcpServerStore,
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
});
@@ -72,7 +74,8 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const manifest = await validateManifest({
spec: body.manifest,
deps,
- store: deps.resolveModelProviderStore(c),
+ modelProviderStore: deps.resolveModelProviderStore(c),
+ mcpServerStore: deps.resolveMcpServerStore(c),
});
try {
const record = await deps.agentStore.createAgent({
@@ -127,7 +130,8 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransac
const manifest = await validateManifest({
spec: body.manifest,
deps,
- store: deps.resolveModelProviderStore(c),
+ modelProviderStore: deps.resolveModelProviderStore(c),
+ mcpServerStore: deps.resolveMcpServerStore(c),
});
const record = await deps.agentStore.updateAgent({
tenant_id: TENANT_ID,
diff --git a/packages/trueforge/src/apis/mcpServers.ts b/packages/trueforge/src/apis/mcpServers.ts
index fd26008b1..32bb845bd 100644
--- a/packages/trueforge/src/apis/mcpServers.ts
+++ b/packages/trueforge/src/apis/mcpServers.ts
@@ -1,5 +1,6 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/trueforge-core/core';
+import type { Context } from 'hono';
import type { Logger } from 'winston';
import type { ResolveUserContext } from '../auth/identity';
import { safeReturnTo } from '../auth/safeReturnTo';
@@ -37,7 +38,7 @@ import { MissingStoredSecretError, resolveStoredSecretValue, toRedactedSecretVal
import { TENANT_ID } from './sessions';
export interface McpServersRouterDeps<TTransaction> {
- mcpServerStore: IMcpServerWithAuthStore<TTransaction>;
+ resolveMcpServerStore: (c: Context) => IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
@@ -119,11 +120,11 @@ async function toConfiguredMcpServer<TTransaction>(params: {
export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listMcpServersRoute> = async c => {
const userRef = deps.resolveUserContext(c).userRef;
- const records = await deps.mcpServerStore.listServers({
+ const records = await deps.resolveMcpServerStore(c).listServers({
tenant_id: TENANT_ID,
names: undefined,
});
- const statuses = await deps.mcpServerStore.resolveAuthStatuses({
+ const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({
records,
userRef,
});
@@ -138,14 +139,17 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
const getHandler: RouteHandler<typeof getMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
const userRef = deps.resolveUserContext(c).userRef;
- const record = await deps.mcpServerStore.getServer({
+ const record = await deps.resolveMcpServerStore(c).getServer({
tenant_id: TENANT_ID,
name,
});
if (!record) {
return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
}
- return c.json({ data: await toConfiguredMcpServer({ store: deps.mcpServerStore, record, userRef }) }, 200);
+ return c.json(
+ { data: await toConfiguredMcpServer({ store: deps.resolveMcpServerStore(c), record, userRef }) },
+ 200,
+ );
};
const createHandler: RouteHandler<typeof createMcpServerRoute> = async c => {
@@ -187,7 +191,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
try {
const record = await deps.withTransaction(async transaction => {
- const saved = await deps.mcpServerStore.createServer(
+ const saved = await deps.resolveMcpServerStore(c).createServer(
{
tenant_id: TENANT_ID,
name: manifest.name,
@@ -196,7 +200,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
transaction,
);
if (dcrClientToSave !== undefined) {
- await deps.mcpServerStore.saveClient({ id: saved.id, record: dcrClientToSave }, transaction);
+ await deps.resolveMcpServerStore(c).saveClient({ id: saved.id, record: dcrClientToSave }, transaction);
}
return saved;
});
@@ -204,7 +208,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
return c.json(
{
data: await toConfiguredMcpServer({
- store: deps.mcpServerStore,
+ store: deps.resolveMcpServerStore(c),
record,
userRef: deps.resolveUserContext(c).userRef,
}),
@@ -231,10 +235,9 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
// Bounded by `MCP_OAUTH_HTTP_TIMEOUT_MS` (15s);
// must stay under `POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS` (30s).
const record = await deps.withTransaction(async transaction => {
- const existing = await deps.mcpServerStore.getServerForUpdate(
- { tenant_id: TENANT_ID, name: incomingManifest.name },
- transaction,
- );
+ const existing = await deps
+ .resolveMcpServerStore(c)
+ .getServerForUpdate({ tenant_id: TENANT_ID, name: incomingManifest.name }, transaction);
const manifest = resolveMcpServerManifestForWrite({
incoming: incomingManifest,
existing: existing?.manifest,
@@ -245,7 +248,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
existing !== undefined && existing.manifest.url !== manifest.url && manifest.auth?.type === 'dcr';
if (manifest.auth?.type === 'dcr') {
const existingClient = existing
- ? await deps.mcpServerStore.getClient({ id: existing.id }, transaction)
+ ? await deps.resolveMcpServerStore(c).getClient({ id: existing.id }, transaction)
: undefined;
// Register when: brand-new server, client was cleared (e.g. invalid_client), or MCP URL changed
// (resource/AS may differ; reuse would keep stale oauth_server/client for the old AS).
@@ -260,7 +263,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
}
}
- const saved = await deps.mcpServerStore.upsertServer(
+ const saved = await deps.resolveMcpServerStore(c).upsertServer(
{
tenant_id: TENANT_ID,
name: manifest.name,
@@ -270,7 +273,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
);
if (dcrClientToSave !== undefined) {
// New DCR registration (create, missing client, or URL change): replace the shared client.
- await deps.mcpServerStore.saveClient({ id: saved.id, record: dcrClientToSave }, transaction);
+ await deps.resolveMcpServerStore(c).saveClient({ id: saved.id, record: dcrClientToSave }, transaction);
}
if (urlChanged) {
// URL is the OAuth resource/audience — drop every user's tokens and in-flight authorizes.
@@ -280,7 +283,10 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
return saved;
});
- return c.json({ data: await toConfiguredMcpServer({ store: deps.mcpServerStore, record, userRef }) }, 200);
+ return c.json(
+ { data: await toConfiguredMcpServer({ store: deps.resolveMcpServerStore(c), record, userRef }) },
+ 200,
+ );
} catch (error) {
if (error instanceof MissingStoredSecretError) {
return c.json({ error: { message: 'Header secret is required' } }, 400);
@@ -316,7 +322,7 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
}
try {
- const authStatus: McpAuthStatus = await deps.mcpServerStore.authorize({
+ const authStatus: McpAuthStatus = await deps.resolveMcpServerStore(c).authorize({
tenant_id: TENANT_ID,
name,
userRef,
@@ -352,7 +358,7 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const connection = await getMcpConnection({
tenant_id: TENANT_ID,
name,
- store: deps.mcpServerStore,
+ store: deps.resolveMcpServerStore(c),
tokenStore: deps.tokenStore,
clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
userRef,
@@ -393,21 +399,21 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const { name } = c.req.valid('param');
const userRef = deps.resolveUserContext(c).userRef;
try {
- const record = await deps.mcpServerStore.getServer({
+ const record = await deps.resolveMcpServerStore(c).getServer({
tenant_id: TENANT_ID,
name,
});
if (!record) {
return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
}
- await deps.mcpServerStore.deleteAuthorization({
+ await deps.resolveMcpServerStore(c).deleteAuthorization({
tenant_id: TENANT_ID,
name,
userRef,
});
return c.json(
{
- data: await toConfiguredMcpServer({ store: deps.mcpServerStore, record, userRef }),
+ data: await toConfiguredMcpServer({ store: deps.resolveMcpServerStore(c), record, userRef }),
},
200,
);
@@ -422,11 +428,11 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const router = new OpenAPIHono();
router.openapi(listAvailableMcpServersRoute, async c => {
const userRef = deps.resolveUserContext(c).userRef;
- const records = await deps.mcpServerStore.listServers({
+ const records = await deps.resolveMcpServerStore(c).listServers({
tenant_id: TENANT_ID,
names: undefined,
});
- const statuses = await deps.mcpServerStore.resolveAuthStatuses({
+ const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({
records,
userRef,
});
diff --git a/packages/trueforge/src/apis/sessions.ts b/packages/trueforge/src/apis/sessions.ts
index 05dec33b2..daefc34c1 100644
--- a/packages/trueforge/src/apis/sessions.ts
+++ b/packages/trueforge/src/apis/sessions.ts
@@ -76,7 +76,7 @@ export interface SessionsRouterDeps {
sessionStore: ISessionStore;
activeTurns: ActiveTurnRegistry;
resolveModelProviderStore: (c: Context) => IModelProviderStore;
- mcpServerStore: IMcpServerStore;
+ resolveMcpServerStore: (c: Context) => IMcpServerStore;
skillStore: ISkillStore;
agentStore: IAgentStore;
sandboxProviderStore: ISandboxProviderStore;
@@ -225,7 +225,7 @@ type InternalSessionsRouterDeps = Pick<
SessionsRouterDeps,
| 'sessions'
| 'resolveModelProviderStore'
- | 'mcpServerStore'
+ | 'resolveMcpServerStore'
| 'skillStore'
| 'agentStore'
| 'sandboxProviderStore'
@@ -262,7 +262,7 @@ function createGetOrCreateSessionByExternalIdHandler(
spec: body.agent.spec,
tenant_id: TENANT_ID,
modelProviderStore: deps.resolveModelProviderStore(c),
- mcpServerStore: deps.mcpServerStore,
+ mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
});
@@ -316,7 +316,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
spec: body.agent.spec,
tenant_id: TENANT_ID,
modelProviderStore: deps.resolveModelProviderStore(c),
- mcpServerStore: deps.mcpServerStore,
+ mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
});
@@ -375,7 +375,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {
spec: body.agent.spec,
tenant_id: TENANT_ID,
modelProviderStore: deps.resolveModelProviderStore(c),
- mcpServerStore: deps.mcpServerStore,
+ mcpServerStore: deps.resolveMcpServerStore(c),
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
});
diff --git a/packages/trueforge/src/apis/settings.ts b/packages/trueforge/src/apis/settings.ts
index c3ddb9e2c..79cd13434 100644
--- a/packages/trueforge/src/apis/settings.ts
+++ b/packages/trueforge/src/apis/settings.ts
@@ -20,7 +20,7 @@ import { createSkillsRouter } from './skills';
export interface SettingsRouterDeps<TTransaction> {
resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
- mcpServerStore: IMcpServerWithAuthStore<TTransaction>;
+ resolveMcpServerStore: (c: Context) => IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
@@ -41,7 +41,7 @@ export function createSettingsRouter<TTransaction>(deps: SettingsRouterDeps<TTra
router.route(
'/mcp-servers',
createSettingsMcpServersRouter({
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
tokenStore: deps.tokenStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.ts
index b0d6453ac..420069471 100644
--- a/packages/trueforge/src/apis/turns.ts
+++ b/packages/trueforge/src/apis/turns.ts
@@ -106,7 +106,7 @@ export interface TurnsRouterDeps {
sessionStore: ISessionStore;
activeTurns: ActiveTurnRegistry;
resolveModelProviderStore: (c: Context) => IModelProviderStore;
- mcpServerStore: IMcpServerStore;
+ resolveMcpServerStore: (c: Context) => IMcpServerStore;
tokenStore: IOAuthTokenStore;
skillStore: ISkillStore;
agentStore: IAgentStore;
@@ -119,19 +119,16 @@ export interface TurnsRouterDeps {
/**
* Deps needed to create a turn and drain events in-process (no HTTP). Unlike the HTTP path, this
- * carries an already-resolved `modelProviderStore` (the scheduler has no request context to resolve one).
+ * carries already-resolved `modelProviderStore` / `mcpServerStore` (the scheduler has no request
+ * context to resolve them).
*/
export type BeginTurnExecutionDeps = Pick<
TurnsRouterDeps,
- | 'activeTurns'
- | 'eventSubscriptions'
- | 'mcpServerStore'
- | 'tokenStore'
- | 'skillStore'
- | 'agentStore'
- | 'sandboxProviderStore'
- | 'logger'
-> & { modelProviderStore: IModelProviderStore };
+ 'activeTurns' | 'eventSubscriptions' | 'tokenStore' | 'skillStore' | 'agentStore' | 'sandboxProviderStore' | 'logger'
+> & {
+ modelProviderStore: IModelProviderStore;
+ mcpServerStore: IMcpServerStore;
+};
/**
* Builds the per-turn resolver. Agent / MCP / sandbox / LLM lookups are wired
@@ -674,7 +671,11 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {
input: body.input,
previous_turn_id: body.previous_turn_id,
userRef,
- deps: { ...deps, modelProviderStore: deps.resolveModelProviderStore(c) },
+ deps: {
+ ...deps,
+ modelProviderStore: deps.resolveModelProviderStore(c),
+ mcpServerStore: deps.resolveMcpServerStore(c),
+ },
};
try {
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index e305db4ee..930ae409b 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -170,8 +170,12 @@ export interface ServerDeps<TTransaction> {
* Called without a context (e.g. the scheduler) it returns the DB persistence store.
*/
resolveModelProviderStore: (c?: Context) => IModelProviderStore<TTransaction>;
+ /**
+ * Per-request store: DB singleton, or a token-bound TrueFoundry store in TrueFoundry mode.
+ * Called without a context (e.g. the scheduler / OAuth callback) it returns the DB persistence store.
+ */
+ resolveMcpServerStore: (c?: Context) => IMcpServerWithAuthStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
- mcpServerStore: IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
@@ -240,7 +244,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
'/api/v1/mcp-servers/oauth',
createMcpOAuthRouter({
tokenStore: deps.tokenStore,
- mcpServerStore: deps.mcpServerStore,
+ mcpServerStore: deps.resolveMcpServerStore(),
logger: deps.logger,
}),
);
@@ -248,7 +252,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
'/api/v1/mcp-servers',
withAuth(
createMcpServersRouter({
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
tokenStore: deps.tokenStore,
withTransaction: deps.withTransaction,
logger: deps.logger,
@@ -271,7 +275,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
createAgentsRouter({
agentStore: deps.agentStore,
resolveModelProviderStore: deps.resolveModelProviderStore,
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
withTransaction: deps.withTransaction,
@@ -289,7 +293,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
activeTurns: deps.activeTurns,
eventSubscriptions: deps.eventSubscriptions,
modelProviderStore: deps.resolveModelProviderStore(),
- mcpServerStore: deps.mcpServerStore,
+ mcpServerStore: deps.resolveMcpServerStore(),
tokenStore: deps.tokenStore,
skillStore: deps.skillStore,
agentStore: deps.agentStore,
@@ -306,7 +310,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
withAdminAuth(
createSettingsRouter({
resolveModelProviderStore: deps.resolveModelProviderStore,
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
tokenStore: deps.tokenStore,
skillStore: deps.skillStore,
sandboxProviderStore: deps.sandboxProviderStore,
@@ -322,7 +326,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
createInternalSessionsRouter({
sessions: deps.sessions,
resolveModelProviderStore: deps.resolveModelProviderStore,
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
skillStore: deps.skillStore,
agentStore: deps.agentStore,
sandboxProviderStore: deps.sandboxProviderStore,
@@ -347,7 +351,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sessionStore: deps.sessionStore,
activeTurns: deps.activeTurns,
resolveModelProviderStore: deps.resolveModelProviderStore,
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
skillStore: deps.skillStore,
agentStore: deps.agentStore,
sandboxProviderStore: deps.sandboxProviderStore,
@@ -366,7 +370,7 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
sessionStore: deps.sessionStore,
activeTurns: deps.activeTurns,
resolveModelProviderStore: deps.resolveModelProviderStore,
- mcpServerStore: deps.mcpServerStore,
+ resolveMcpServerStore: deps.resolveMcpServerStore,
tokenStore: deps.tokenStore,
skillStore: deps.skillStore,
agentStore: deps.agentStore,
diff --git a/packages/trueforge/src/db/mcpServerStore.ts b/packages/trueforge/src/db/mcpServerStore.ts
index 8bb6f5ea1..99277c12c 100644
--- a/packages/trueforge/src/db/mcpServerStore.ts
+++ b/packages/trueforge/src/db/mcpServerStore.ts
@@ -1,11 +1,12 @@
/**
- * Configured MCP servers: one row per server per tenant, identity as columns plus a
- * Zod-validated `McpServerManifest` jsonb document.
+ * Configured MCP servers: identity columns plus a Zod-validated `McpServerManifest` jsonb document.
*
- * - {@link IMcpServerStore}: DB CRUD + DCR client columns (`IOAuthClientStore`).
- * Implemented by PostgresMcpServerStore / SqliteMcpServerStore.
+ * - {@link IMcpServerStore}: CRUD + DCR client columns (`IOAuthClientStore`).
+ * Implemented by PostgresMcpServerStore, SqliteMcpServerStore, and
+ * TrueFoundryMcpServerStore (read-only ServiceFoundry listing).
* - {@link IMcpServerWithAuthStore}: persistence + authorize / status / revoke;
- * {@link McpServerWithAuthStore} (separate module) composes an {@link IMcpServerStore} + a token store.
+ * {@link McpServerWithAuthStore} composes an {@link IMcpServerStore} + a token store;
+ * TrueFoundryMcpServerStore implements this directly for remote Connect UX stubs.
*
* OAuth JSONB wire shapes (snake_case) and camelCase ↔ storage mappers live here
* alongside the store contract — absence is an explicit `| null`, not an optional `?:`.
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index 4ad4d3e72..b3874a51c 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -73,6 +73,7 @@ import { PACKAGE_VERSION } from './packageVersion';
import { ActiveTurnRegistry } from './runtime/activeTurns';
import { EventSubscriptionRegistry } from './runtime/event-subscription';
import { printStandaloneStartupBanner } from './startupBanner';
+import { TrueFoundryMcpServerStore } from './truefoundry/TrueFoundryMcpServerStore';
import { TrueFoundryModelProviderStore } from './truefoundry/TrueFoundryModelProviderStore';
import { TrueFoundryServiceFoundryServerClient } from './truefoundry/TrueFoundryServiceFoundryServerClient';
@@ -81,8 +82,8 @@ interface ServerPersistence<TTransaction> {
sessionStore: ISessionStore;
sessionMetricsStore: ISessionMetricsStore;
resolveModelProviderStore: (c?: Context) => IModelProviderStore<TTransaction>;
+ resolveMcpServerStore: (c?: Context) => IMcpServerWithAuthStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
- mcpServerStore: IMcpServerStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
@@ -116,6 +117,36 @@ function buildResolveModelProviderStore<TTransaction>(options: {
: options.persistenceStore;
}
+/**
+ * Per-request MCP store resolver. Local mode wraps DB persistence with
+ * {@link McpServerWithAuthStore}. TrueFoundry mode returns a token-bound
+ * {@link TrueFoundryMcpServerStore} (implements auth UX stubs); without request
+ * context (scheduler / OAuth callback) falls back to the local with-auth store.
+ */
+function buildResolveMcpServerStore<TTransaction>(options: {
+ persistenceStore: IMcpServerStore<TTransaction>;
+ tokenStore: IOAuthTokenStore<TTransaction>;
+ logger: Logger;
+}): (c?: Context) => IMcpServerWithAuthStore<TTransaction> {
+ const withAuthPersistence = new McpServerWithAuthStore<TTransaction>({
+ store: options.persistenceStore,
+ tokenStore: options.tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
+ if (!isTrueFoundryModeEnabled(configuration)) {
+ return () => withAuthPersistence;
+ }
+ const client = new TrueFoundryServiceFoundryServerClient({
+ serviceFoundryServerUrl: configuration.TRUEFOUNDRY_SERVICEFOUNDRY_SERVER_URL,
+ logger: options.logger,
+ tls: { enabled: configuration.TRUEFOUNDRY_MTLS_ENABLED, dir: configuration.TRUEFOUNDRY_MTLS_CERTS_DIR },
+ });
+ return c =>
+ c
+ ? new TrueFoundryMcpServerStore<TTransaction>({ client, accessToken: requireAccessToken(c) })
+ : withAuthPersistence;
+}
+
/** SQLite stores; Redis unused (executor peering disabled). */
async function createStandalonePersistence(options: {
sqlitePath: string;
@@ -155,6 +186,7 @@ async function createStandalonePersistence(options: {
logger.info(`Standalone mode: sqlite at ${sqlitePath}`);
logger.info('Standalone mode: executor peering disabled and Redis unused');
+ const tokenStore = new SqliteOAuthTokenStore(db);
return {
sessionStore: new SqliteSessionStore(db),
sessionMetricsStore: new SqliteSessionMetricsStore(db),
@@ -162,9 +194,13 @@ async function createStandalonePersistence(options: {
persistenceStore: new SqliteModelProviderStore(db),
logger,
}),
+ resolveMcpServerStore: buildResolveMcpServerStore({
+ persistenceStore: new SqliteMcpServerStore(db),
+ tokenStore,
+ logger,
+ }),
withTransaction: callback => db.transaction().execute(callback),
- mcpServerStore: new SqliteMcpServerStore(db),
- tokenStore: new SqliteOAuthTokenStore(db),
+ tokenStore,
skillStore: new SqliteSkillStore(db),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
agentStore: new SqliteAgentStore(db),
@@ -227,6 +263,7 @@ async function createDistributedPersistence(options: {
logger.info('Distributed mode: postgres');
logger.info(`Executor id: ${executorId}`);
+ const tokenStore = new PostgresOAuthTokenStore(db);
return {
sessionStore: new PostgresSessionStore(db),
sessionMetricsStore: new PostgresSessionMetricsStore(db),
@@ -234,9 +271,13 @@ async function createDistributedPersistence(options: {
persistenceStore: new PostgresModelProviderStore(db),
logger,
}),
+ resolveMcpServerStore: buildResolveMcpServerStore({
+ persistenceStore: new PostgresMcpServerStore(db),
+ tokenStore,
+ logger,
+ }),
withTransaction: callback => db.transaction().execute(callback),
- mcpServerStore: new PostgresMcpServerStore(db),
- tokenStore: new PostgresOAuthTokenStore(db),
+ tokenStore,
skillStore: new PostgresSkillStore(db),
sandboxProviderStore: new PostgresSandboxProviderStore(db),
agentStore: new PostgresAgentStore(db),
@@ -252,8 +293,8 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
sessionStore,
sessionMetricsStore,
resolveModelProviderStore,
+ resolveMcpServerStore,
withTransaction,
- mcpServerStore: persistenceMcpServerStore,
tokenStore,
skillStore,
sandboxProviderStore,
@@ -263,12 +304,6 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
redis,
} = persistence;
- const mcpServerStore: IMcpServerWithAuthStore<TTransaction> = new McpServerWithAuthStore({
- store: persistenceMcpServerStore,
- tokenStore,
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- });
-
const activeTurns = new ActiveTurnRegistry();
const requestReplyRouter = new RequestReplyRouter();
const eventSubscriptions = new EventSubscriptionRegistry<TurnStreamingEvent>(redis);
@@ -297,8 +332,8 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
skillCatalog: SkillCatalog.load(),
sandboxCatalog: SandboxCatalog.load(),
resolveModelProviderStore,
+ resolveMcpServerStore,
withTransaction,
- mcpServerStore,
tokenStore,
skillStore,
sandboxProviderStore,
diff --git a/packages/trueforge/src/routes/mcpServerRoutes.ts b/packages/trueforge/src/routes/mcpServerRoutes.ts
index 9bfda2f62..8c1488957 100644
--- a/packages/trueforge/src/routes/mcpServerRoutes.ts
+++ b/packages/trueforge/src/routes/mcpServerRoutes.ts
@@ -13,6 +13,7 @@ import {
McpAuthStatusSchema,
UpdateMcpServerRequestSchema,
} from '../schemas/mcpServer';
+import { trueFoundryManagedResponse } from '../truefoundry/trueFoundryManaged';
import { OpenApiTag } from './openapiTags';
/** Chat/composer read view — mounted at /api/v1/mcp-servers (not under settings). */
@@ -122,6 +123,7 @@ export const createMcpServerRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint).',
},
+ 424: trueFoundryManagedResponse,
},
});
@@ -131,8 +133,7 @@ export const putMcpServerRoute = createRoute({
tags: [OpenApiTag.MCP_SERVERS],
summary: 'Create or replace an MCP server',
description:
- 'Create or replace by `name`. Does not start DCR or change oauth client columns. ' +
- 'Header secrets: real value sets/rotates; redacted keeps existing (400 if none).',
+ 'Create or replace by `name`. Header secrets: real value sets/rotates; redacted keeps existing (400 if none).',
'x-fern-sdk-group-name': ['settings', 'mcpServers'],
'x-fern-sdk-method-name': 'create_or_update',
request: {
@@ -154,6 +155,7 @@ export const putMcpServerRoute = createRoute({
content: { 'application/json': { schema: RequestErrorResponseSchema } },
description: 'The server cannot satisfy `auth.type: dcr` (e.g. it advertises no registration_endpoint).',
},
+ 424: trueFoundryManagedResponse,
},
});
@@ -218,10 +220,9 @@ export const authorizeMcpServerRoute = createRoute({
'x-fern-sdk-group-name': ['mcpServers'],
'x-fern-sdk-method-name': 'authorize',
description:
- 'For servers without auth returns not_required, and for header credentials returns authenticated ' +
- '(no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token ' +
- 'exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. ' +
- 'Optional return_to is where the OAuth callback then redirects the browser; without it the callback returns JSON.',
+ 'Returns the current auth status for the MCP server. For OAuth (`auth.type` dcr), returns authenticated when a ' +
+ 'usable token exists; otherwise returns auth_required with an authorization URL. Optional return_to is where the ' +
+ 'OAuth callback redirects the browser; without it the callback returns JSON.',
request: {
params: McpServerNameParamsSchema,
query: McpAuthorizeQuerySchema,
@@ -262,16 +263,15 @@ export const deleteAuthorizationMcpServerRoute = createRoute({
'x-fern-sdk-group-name': ['mcpServers'],
'x-fern-sdk-method-name': 'delete_authorization',
description:
- 'For auth.type dcr, deletes the stored OAuth token and returns the server with auth_status ' +
- 'auth_required, keeping the dynamically registered OAuth client so the next authorize can reuse it. ' +
- 'No-op for header or no-auth servers (returns the server unchanged).',
+ 'Disconnects OAuth for the MCP server when applicable and returns the updated server with auth_status. ' +
+ 'No-op when the server does not use stored OAuth tokens.',
request: {
params: McpServerNameParamsSchema,
},
responses: {
200: {
content: { 'application/json': { schema: GetMcpServerResponseSchema } },
- description: 'The MCP server after disconnect (auth_required for dcr).',
+ description: 'The MCP server after disconnect.',
},
404: {
content: { 'application/json': { schema: RequestErrorResponseSchema } },
diff --git a/packages/trueforge/src/runtime/sessionResources.ts b/packages/trueforge/src/runtime/sessionResources.ts
index 5206df875..0255aa27f 100644
--- a/packages/trueforge/src/runtime/sessionResources.ts
+++ b/packages/trueforge/src/runtime/sessionResources.ts
@@ -134,7 +134,8 @@ function dcrHeadersResolver(params: {
/**
* Load MCP url + headers for a configured server.
- * DCR uses resolveMcpAuth; header / no-auth use resolveConfiguredMcpRequestHeaders.
+ * - `remote` + `dcr`: resolveMcpAuth via the harness token store.
+ * - header / no-auth: resolveConfiguredMcpRequestHeaders.
* Returns undefined when the server is not registered — callers choose the response.
*/
export async function getMcpConnection({
diff --git a/packages/trueforge/src/schemas/mcpCatalog.ts b/packages/trueforge/src/schemas/mcpCatalog.ts
index 215eb0481..574d202f5 100644
--- a/packages/trueforge/src/schemas/mcpCatalog.ts
+++ b/packages/trueforge/src/schemas/mcpCatalog.ts
@@ -6,10 +6,16 @@ import { z } from '@hono/zod-openapi';
import { NameSchema, uniqueNames } from './common';
import { McpServerDescriptionSchema, McpServerManifestAuthSchema, McpServerTypeSchema } from './mcpServer';
+/**
+ * Catalog presets are user-savable `remote` entries only.
+ * `truefoundry` is TrueFoundry-managed.
+ */
+export const CatalogMcpServerTypeSchema = McpServerTypeSchema.exclude(['truefoundry']).openapi('CatalogMCPServerType');
+
/** Catalog entry — discovery preset the settings UI copies into a PUT body. */
export const CatalogMcpServerSchema = z
.object({
- type: McpServerTypeSchema,
+ type: CatalogMcpServerTypeSchema,
name: NameSchema,
logo: z.url().optional().describe('URL of the MCP server logo asset.'),
url: z.url().describe('URL of the remote MCP server.'),
diff --git a/packages/trueforge/src/schemas/mcpServer.ts b/packages/trueforge/src/schemas/mcpServer.ts
index ae4d3739c..37feb0e14 100644
--- a/packages/trueforge/src/schemas/mcpServer.ts
+++ b/packages/trueforge/src/schemas/mcpServer.ts
@@ -10,8 +10,12 @@ import { z } from '@hono/zod-openapi';
import type { OAuthToken } from '../mcp/auth/types';
import { NameSchema } from './common';
-/** Transport/kind of MCP server. Extend when non-remote kinds ship. */
-export const McpServerTypeSchema = z.enum(['remote']).openapi('MCPServerType');
+/**
+ * Transport/kind of MCP server.
+ * `remote` — user-configured URL (standalone / local registry).
+ * `truefoundry` — TrueFoundry-managed: gateway proxy URL.
+ */
+export const McpServerTypeSchema = z.enum(['remote', 'truefoundry']).openapi('MCPServerType');
const McpServerHeaderAuthSchema = z
.object({
@@ -52,7 +56,7 @@ export const McpServerManifestObjectSchema = z
.object({
type: McpServerTypeSchema,
name: NameSchema,
- url: z.url().describe('URL of the remote MCP server.'),
+ url: z.url().describe('MCP endpoint URL. For `truefoundry`, the resolved AI Gateway proxy URL.'),
description: McpServerDescriptionSchema,
auth: McpServerManifestAuthSchema.optional(),
})
@@ -156,6 +160,10 @@ export function resolveMcpAuthStatus({
manifest: McpServerManifest;
token?: OAuthToken;
}): McpAuthStatus {
+ // TODO: Replace stub with live ServiceFoundry auth status when Connect /authorize is wired.
+ if (manifest.type === 'truefoundry') {
+ return { status: 'authenticated' };
+ }
if (manifest.auth?.type === 'dcr') {
return token ? { status: 'authenticated' } : { status: 'auth_required' };
}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
new file mode 100644
index 000000000..92593fa53
--- /dev/null
+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts
@@ -0,0 +1,152 @@
+import { HTTPException } from 'hono/http-exception';
+import {
+ McpServerNotFoundError,
+ type AuthorizeMcpServerInput,
+ type CreateMcpServerInput,
+ type DeleteMcpAuthorizationInput,
+ type GetMcpServerInput,
+ type IMcpServerWithAuthStore,
+ type ListMcpServersInput,
+ type McpServerRecord,
+ type ResolveMcpAuthStatusesInput,
+ type UpsertMcpServerInput,
+} from '../db/mcpServerStore';
+import type { OAuthClientRecord } from '../mcp/auth/types';
+import { resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer';
+import { resolveDefaultGatewayUrl } from './mapEnabledModels';
+import {
+ mapSfyMcpServers,
+ parseSfyMcpServerSummary,
+ toTrueFoundryMcpManifest,
+ type SfyMcpServerSummary,
+} from './mapSfyMcpServers';
+import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from './trueFoundryManaged';
+import type { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';
+
+function managed(): never {
+ throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });
+}
+
+/**
+ * Read-only MCP registry backed by ServiceFoundry + the tenant AI Gateway.
+ * Writes and local OAuth client columns are not supported — configure servers in TrueFoundry.
+ * Connect UX auth methods are stubbed for v1 (live SFY authorize is a follow-up).
+ */
+export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServerWithAuthStore<TTransaction> {
+ readonly #client: TrueFoundryServiceFoundryServerClient;
+ readonly #accessToken: string;
+
+ constructor(input: { client: TrueFoundryServiceFoundryServerClient; accessToken: string }) {
+ this.#client = input.client;
+ this.#accessToken = input.accessToken;
+ }
+
+ async listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]> {
+ void transaction;
+ if (input.names?.length === 0) {
+ return [];
+ }
+ const records = await this.#records(input.tenant_id);
+ if (input.names === undefined) {
+ return records;
+ }
+ const wanted = new Set(input.names);
+ return records.filter(record => wanted.has(record.name));
+ }
+
+ async getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined> {
+ void transaction;
+ const row = await this.#client.getMcpServerByName({ accessToken: this.#accessToken, name: input.name });
+ if (row === undefined) {
+ return undefined;
+ }
+ const server = parseSfyMcpServerSummary(row);
+ const gatewayUrl = resolveDefaultGatewayUrl(await this.#client.listGatewayInstallations(this.#accessToken));
+ return toRecord({ tenant_id: input.tenant_id, server, gatewayUrl });
+ }
+
+ getServerForUpdate(input: GetMcpServerInput, transaction: TTransaction): Promise<McpServerRecord | undefined> {
+ void input;
+ void transaction;
+ return managed();
+ }
+
+ createServer(input: CreateMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {
+ void input;
+ void transaction;
+ return managed();
+ }
+
+ upsertServer(input: UpsertMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {
+ void input;
+ void transaction;
+ return managed();
+ }
+
+ saveClient(params: { id: string; record: OAuthClientRecord }, transaction?: TTransaction): Promise<void> {
+ void params;
+ void transaction;
+ return managed();
+ }
+
+ getClient(params: { id: string }, transaction?: TTransaction): Promise<OAuthClientRecord | undefined> {
+ void params;
+ void transaction;
+ return managed();
+ }
+
+ deleteClient(params: { id: string }, transaction?: TTransaction): Promise<void> {
+ void params;
+ void transaction;
+ return managed();
+ }
+
+ resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>> {
+ const out = new Map<string, McpAuthStatus>();
+ for (const record of input.records) {
+ out.set(record.name, resolveMcpAuthStatus({ manifest: record.manifest }));
+ }
+ return Promise.resolve(out);
+ }
+
+ async authorize(input: AuthorizeMcpServerInput): Promise<McpAuthStatus> {
+ void input.redirectURL;
+ void input.returnTo;
+ void input.userRef;
+ const record = await this.getServer({ tenant_id: input.tenant_id, name: input.name });
+ if (record === undefined) {
+ throw new McpServerNotFoundError(input.name);
+ }
+ // TODO: Replace stub with live ServiceFoundry authorize / Connect when wired.
+ return resolveMcpAuthStatus({ manifest: record.manifest });
+ }
+
+ async deleteAuthorization(input: DeleteMcpAuthorizationInput): Promise<void> {
+ void input.userRef;
+ const record = await this.getServer({ tenant_id: input.tenant_id, name: input.name });
+ if (record === undefined) {
+ throw new McpServerNotFoundError(input.name);
+ }
+ // No local token store for TrueFoundry-managed MCP (v1).
+ }
+
+ async #records(tenant_id: string): Promise<McpServerRecord[]> {
+ const [rows, installations] = await Promise.all([
+ this.#client.listMcpServers(this.#accessToken),
+ this.#client.listGatewayInstallations(this.#accessToken),
+ ]);
+ const gatewayUrl = resolveDefaultGatewayUrl(installations);
+ return mapSfyMcpServers({ rows }).map(server => toRecord({ tenant_id, server, gatewayUrl }));
+ }
+}
+
+function toRecord(input: { tenant_id: string; server: SfyMcpServerSummary; gatewayUrl: string }): McpServerRecord {
+ return {
+ id: input.server.id,
+ tenant_id: input.tenant_id,
+ name: input.server.name,
+ manifest: toTrueFoundryMcpManifest({ server: input.server, gatewayUrl: input.gatewayUrl }),
+ created_at: input.server.createdAt,
+ updated_at: input.server.updatedAt,
+ };
+}
diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
index d31bacbbe..1f40ca014 100644
--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
@@ -8,7 +8,9 @@ import { createInternalTlsDispatcher, normalizeInternalTlsUrl, type InternalTlsO
const INTEGRATIONS_PATH = 'v1/provider-integrations';
const INSTALLATIONS_PATH = 'v1/llm-gateway/installations';
+const MCP_SERVERS_PATH = 'v1/mcp';
const INTEGRATIONS_PAGE_SIZE = 1000;
+const MCP_SERVERS_PAGE_SIZE = 100;
const ListResponseSchema = z.union([
z.array(z.unknown()),
@@ -18,6 +20,8 @@ const ListResponseSchema = z.union([
}),
]);
+type ListResponse = z.infer<typeof ListResponseSchema>;
+
const ServiceFoundryErrorSchema = z.object({
message: z.union([z.string(), z.array(z.string())]).optional(),
});
@@ -31,6 +35,14 @@ async function readServiceFoundryErrorMessage(
return Array.isArray(message) ? message.join(', ') : message;
}
+function listPage(response: ListResponse): unknown[] {
+ return Array.isArray(response) ? response : response.data;
+}
+
+function listPaginationTotal(response: ListResponse): number | undefined {
+ return Array.isArray(response) ? undefined : response.pagination?.total;
+}
+
export class TrueFoundryServiceFoundryServerClient {
readonly #baseUrl: string;
readonly #logger: Logger | undefined;
@@ -58,14 +70,11 @@ export class TrueFoundryServiceFoundryServerClient {
}),
accessToken,
);
- const parsed = ListResponseSchema.safeParse(payload);
- if (!parsed.success) {
- break;
- }
- const page = Array.isArray(parsed.data) ? parsed.data : parsed.data.data;
- const total = Array.isArray(parsed.data) ? undefined : parsed.data.pagination?.total;
+ const response = this.#parseListResponse(payload);
+ const page = listPage(response);
+ const total = listPaginationTotal(response);
items.push(...page);
- if (!total || items.length >= total || page.length === 0) {
+ if (total === undefined || items.length >= total || page.length === 0) {
break;
}
offset = items.length;
@@ -77,6 +86,71 @@ export class TrueFoundryServiceFoundryServerClient {
return this.#getJson(this.#url(INSTALLATIONS_PATH), accessToken);
}
+ /**
+ * Paginated `GET v1/mcp`. Returns raw SFY rows; callers parse with {@link mapSfyMcpServers}.
+ * Offset advances by raw page length (same as {@link listProviderIntegrations}).
+ */
+ async listMcpServers(accessToken: string): Promise<unknown[]> {
+ const items: unknown[] = [];
+ let offset = 0;
+ for (;;) {
+ const payload = await this.#getJson(
+ this.#url(MCP_SERVERS_PATH, {
+ offset: String(offset),
+ limit: String(MCP_SERVERS_PAGE_SIZE),
+ }),
+ accessToken,
+ );
+ const response = this.#parseListResponse(payload);
+ const page = listPage(response);
+ const total = listPaginationTotal(response);
+ items.push(...page);
+ if (total === undefined || items.length >= total || page.length === 0) {
+ break;
+ }
+ offset = items.length;
+ }
+ return items;
+ }
+
+ /**
+ * Resolve one MCP server by name via list filter `name EQUAL`.
+ * Returns the first raw row, or `undefined` when the tenant has no match.
+ * Callers parse with {@link parseSfyMcpServerSummary}.
+ */
+ async getMcpServerByName(input: { accessToken: string; name: string }): Promise<unknown> {
+ const filter = JSON.stringify({
+ op: 'and',
+ values: [{ field: 'name', op: 'EQUAL', value: input.name }],
+ });
+ const payload = await this.#getJson(
+ this.#url(MCP_SERVERS_PATH, { filter, limit: '1', offset: '0' }),
+ input.accessToken,
+ );
+ const rows = listPage(this.#parseListResponse(payload));
+ if (rows.length > 1) {
+ this.#logger?.warn('TrueFoundry ServiceFoundry MCP name filter returned multiple rows', {
+ name: input.name,
+ count: rows.length,
+ });
+ }
+ return rows[0];
+ }
+
+ #parseListResponse(payload: unknown): ListResponse {
+ const parsed = ListResponseSchema.safeParse(payload);
+ if (!parsed.success) {
+ this.#logger?.error('TrueFoundry ServiceFoundry server returned an unexpected list response', {
+ ...extractErrorLogFields(parsed.error),
+ });
+ throw new HTTPException(424, {
+ message: 'TrueFoundry ServiceFoundry server returned an unexpected list response',
+ cause: parsed.error,
+ });
+ }
+ return parsed.data;
+ }
+
#url(path: string, search?: Record<string, string>): URL {
const url = new URL(`${this.#baseUrl}/${path}`);
if (search) {
diff --git a/packages/trueforge/src/truefoundry/mapSfyMcpServers.ts b/packages/trueforge/src/truefoundry/mapSfyMcpServers.ts
new file mode 100644
index 000000000..97168f581
--- /dev/null
+++ b/packages/trueforge/src/truefoundry/mapSfyMcpServers.ts
@@ -0,0 +1,99 @@
+/**
+ * ServiceFoundry MCP list rows → lean summaries (Zod, fail loudly — same pattern as mapEnabledModels).
+ */
+import { z } from 'zod';
+import type { McpServerManifest } from '../schemas/mcpServer';
+
+/** Placeholder in SFY `proxyUrl` replaced with the tenant gateway base URL. */
+export const MCP_PROXY_BASE_URL_TEMPLATE = '{{mcpProxyBaseURL}}';
+
+const IsoInstantSchema = z.union([z.string().min(1), z.date()]).transform((value, ctx) => {
+ if (value instanceof Date) {
+ if (!Number.isFinite(value.getTime())) {
+ ctx.addIssue({ code: 'custom', message: 'Invalid Date' });
+ return z.NEVER;
+ }
+ return value.toISOString();
+ }
+ const ms = Date.parse(value);
+ if (!Number.isFinite(ms)) {
+ ctx.addIssue({ code: 'custom', message: 'Invalid ISO timestamp' });
+ return z.NEVER;
+ }
+ return new Date(ms).toISOString();
+});
+
+const SfyMcpServerRowSchema = z.object({
+ id: z.string().min(1),
+ name: z.string().min(1),
+ proxyUrl: z.string().min(1),
+ createdAt: IsoInstantSchema.optional(),
+ updatedAt: IsoInstantSchema.optional(),
+ manifest: z
+ .object({
+ description: z.string().min(1).optional(),
+ auth_data: z
+ .object({
+ type: z.string().min(1).optional(),
+ })
+ .optional(),
+ })
+ .optional(),
+});
+
+export interface SfyMcpServerSummary {
+ id: string;
+ name: string;
+ /** May contain `{{mcpProxyBaseURL}}`; callers must run {@link resolveMcpProxyUrl}. */
+ proxyUrl: string;
+ description: string;
+ authType: string | undefined;
+ createdAt: string;
+ updatedAt: string;
+}
+
+/** Parse one SFY MCP list row. Throws ZodError on contract drift. */
+export function parseSfyMcpServerSummary(row: unknown): SfyMcpServerSummary {
+ const parsed = SfyMcpServerRowSchema.parse(row);
+ const now = new Date().toISOString();
+ return {
+ id: parsed.id,
+ name: parsed.name,
+ proxyUrl: parsed.proxyUrl,
+ description: parsed.manifest?.description ?? parsed.name,
+ authType: parsed.manifest?.auth_data?.type,
+ createdAt: parsed.createdAt ?? now,
+ updatedAt: parsed.updatedAt ?? now,
+ };
+}
+
+/** Map SFY MCP list rows; each row must satisfy the schema. */
+export function mapSfyMcpServers(input: { rows: readonly unknown[] }): SfyMcpServerSummary[] {
+ return input.rows.map(parseSfyMcpServerSummary);
+}
+
+/** Substitute `{{mcpProxyBaseURL}}` in an SFY proxy URL template. */
+export function resolveMcpProxyUrl(input: { proxyUrl: string; gatewayBaseURL: string }): string {
+ const base = input.gatewayBaseURL.replace(/\/+$/, '');
+ if (!input.proxyUrl.includes(MCP_PROXY_BASE_URL_TEMPLATE)) {
+ return input.proxyUrl;
+ }
+ return input.proxyUrl.replaceAll(MCP_PROXY_BASE_URL_TEMPLATE, base);
+}
+
+/**
+ * Gateway proxy as `url`. SFY `oauth2` → wire `dcr` for Connect UX only (UI keys off auth type).
+ * Invoke Bearer is intentionally not embedded as `header` auth — that breaks the UI and is a follow-up PR.
+ */
+export function toTrueFoundryMcpManifest(input: {
+ server: SfyMcpServerSummary;
+ gatewayUrl: string;
+}): McpServerManifest {
+ return {
+ type: 'truefoundry',
+ name: input.server.name,
+ url: resolveMcpProxyUrl({ proxyUrl: input.server.proxyUrl, gatewayBaseURL: input.gatewayUrl }),
+ description: input.server.description,
+ ...(input.server.authType === 'oauth2' ? { auth: { type: 'dcr' as const } } : {}),
+ };
+}
diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.ts
index 2f81b5d4c..0305c84d7 100644
--- a/packages/trueforge/tests/unit/apis/agents.test.ts
+++ b/packages/trueforge/tests/unit/apis/agents.test.ts
@@ -80,7 +80,7 @@ describe('agents router', () => {
router = createAgentsRouter({
agentStore,
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore: new SqliteMcpServerStore(db),
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
skillStore: new SqliteSkillStore(db),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
diff --git a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
index fcd5b3009..d8f7a5d65 100644
--- a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
+++ b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts
@@ -41,7 +41,7 @@ describe('public CRUD after session deletion', () => {
sessionStore,
activeTurns,
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
skillStore,
agentStore,
sandboxProviderStore,
@@ -58,7 +58,7 @@ describe('public CRUD after session deletion', () => {
sessionStore,
activeTurns,
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
skillStore,
agentStore,
diff --git a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
index cad1a0d23..a38a29430 100644
--- a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
@@ -95,14 +95,14 @@ describe('MCP OAuth authorize + callback', () => {
withTransaction = callback => db.transaction().execute(callback);
logger = winston.createLogger({ silent: true });
settingsRouter = createSettingsMcpServersRouter({
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
resolveUserContext: () => LOCAL_USER_CONTEXT,
});
mcpServersRouter = createMcpServersRouter({
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
@@ -229,7 +229,7 @@ describe('MCP OAuth authorize + callback', () => {
it('authorize for one user does not authenticate another user on the same server', async () => {
const otherRouter = createMcpServersRouter({
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
diff --git a/packages/trueforge/tests/unit/apis/mcpServers.test.ts b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
index 25afde3e5..242b7fdfe 100644
--- a/packages/trueforge/tests/unit/apis/mcpServers.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
@@ -109,7 +109,7 @@ describe('mcp-servers routers', () => {
withTransaction = callback => db.transaction().execute(callback);
logger = winston.createLogger({ silent: true });
settingsRouter = createSettingsMcpServersRouter({
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
@@ -122,7 +122,7 @@ describe('mcp-servers routers', () => {
sandboxCatalog: SandboxCatalog.load(),
});
mcpServersRouter = createMcpServersRouter({
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
@@ -612,7 +612,7 @@ describe('mcp-servers routers', () => {
});
const otherRouter = createMcpServersRouter({
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
tokenStore,
withTransaction,
logger,
diff --git a/packages/trueforge/tests/unit/apis/modelProviders.test.ts b/packages/trueforge/tests/unit/apis/modelProviders.test.ts
index d235ada59..9ea68b4b2 100644
--- a/packages/trueforge/tests/unit/apis/modelProviders.test.ts
+++ b/packages/trueforge/tests/unit/apis/modelProviders.test.ts
@@ -98,11 +98,12 @@ async function createRouters(): Promise<{
return {
settingsRouter: createSettingsRouter({
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore: new McpServerWithAuthStore({
- store: new SqliteMcpServerStore(db),
- tokenStore,
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- }),
+ resolveMcpServerStore: () =>
+ new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ }),
tokenStore,
skillStore: new SqliteSkillStore(db),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
diff --git a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
index a46c0f545..a70d6107a 100644
--- a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
+++ b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts
@@ -39,7 +39,7 @@ async function buildApp() {
sessionStore,
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => new SqliteModelProviderStore(db),
- mcpServerStore: new SqliteMcpServerStore(db),
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
tokenStore: new SqliteOAuthTokenStore(db),
skillStore: new SqliteSkillStore(db),
agentStore: new SqliteAgentStore(db),
diff --git a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
index 52779be61..3f1767bc8 100644
--- a/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
+++ b/packages/trueforge/tests/unit/apis/sessionHttp.test.ts
@@ -80,7 +80,7 @@ describe('sessions HTTP agent binding', () => {
sessionStore,
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore,
+ resolveMcpServerStore: () => mcpServerStore,
skillStore,
agentStore,
sandboxProviderStore,
diff --git a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
index b92f3ceaf..2a7b6f76a 100644
--- a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
+++ b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts
@@ -56,7 +56,7 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<Response
sessionStore: new SqliteSessionStore(db),
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore: new SqliteMcpServerStore(db),
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
tokenStore: new SqliteOAuthTokenStore(db),
skillStore: new SqliteSkillStore(db),
agentStore: new SqliteAgentStore(db),
diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.ts
index 7cb470978..24cfe0f4e 100644
--- a/packages/trueforge/tests/unit/apis/turns.test.ts
+++ b/packages/trueforge/tests/unit/apis/turns.test.ts
@@ -53,7 +53,7 @@ describe('turns', () => {
sessionStore,
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => new SqliteModelProviderStore(db),
- mcpServerStore: new SqliteMcpServerStore(db),
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
tokenStore: new SqliteOAuthTokenStore(db),
skillStore: new SqliteSkillStore(db),
agentStore: new SqliteAgentStore(db),
@@ -173,7 +173,7 @@ describe('turns', () => {
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => modelProviderStore,
agentStore: new SqliteAgentStore(db),
- mcpServerStore: new SqliteMcpServerStore(db),
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
tokenStore: new SqliteOAuthTokenStore(db),
skillStore: new SqliteSkillStore(db),
eventSubscriptions,
@@ -272,7 +272,7 @@ describe('turns', () => {
sessionStore: new SqliteSessionStore(db),
activeTurns: new ActiveTurnRegistry(),
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore: new SqliteMcpServerStore(db),
+ resolveMcpServerStore: () => new SqliteMcpServerStore(db),
tokenStore: new SqliteOAuthTokenStore(db),
skillStore: new SqliteSkillStore(db),
agentStore: new SqliteAgentStore(db),
diff --git a/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.ts b/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.ts
new file mode 100644
index 000000000..1ad608a4d
--- /dev/null
+++ b/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.ts
@@ -0,0 +1,139 @@
+import { ZodError } from 'zod';
+import {
+ MCP_PROXY_BASE_URL_TEMPLATE,
+ mapSfyMcpServers,
+ parseSfyMcpServerSummary,
+ resolveMcpProxyUrl,
+ toTrueFoundryMcpManifest,
+ type SfyMcpServerSummary,
+} from '../../../src/truefoundry/mapSfyMcpServers';
+
+const BASE_ROW = {
+ id: 'mcp-1',
+ name: 'github',
+ proxyUrl: `${MCP_PROXY_BASE_URL_TEMPLATE}/mcp-server/github`,
+ createdAt: '2026-01-15T12:00:00.000Z',
+ updatedAt: '2026-01-16T12:00:00.000Z',
+};
+
+function summary(overrides: Partial<SfyMcpServerSummary> = {}): SfyMcpServerSummary {
+ return {
+ id: 'mcp-1',
+ name: 'github',
+ proxyUrl: `${MCP_PROXY_BASE_URL_TEMPLATE}/mcp-server/github`,
+ description: 'GitHub MCP',
+ authType: undefined,
+ createdAt: '2026-01-15T12:00:00.000Z',
+ updatedAt: '2026-01-16T12:00:00.000Z',
+ ...overrides,
+ };
+}
+
+describe('parseSfyMcpServerSummary', () => {
+ it('parses a full SFY row and reads oauth2 auth_data', () => {
+ expect(
+ parseSfyMcpServerSummary({
+ ...BASE_ROW,
+ manifest: {
+ description: 'GitHub tools',
+ auth_data: { type: 'oauth2' },
+ },
+ }),
+ ).toEqual({
+ id: 'mcp-1',
+ name: 'github',
+ proxyUrl: `${MCP_PROXY_BASE_URL_TEMPLATE}/mcp-server/github`,
+ description: 'GitHub tools',
+ authType: 'oauth2',
+ createdAt: '2026-01-15T12:00:00.000Z',
+ updatedAt: '2026-01-16T12:00:00.000Z',
+ });
+ });
+
+ it('falls back description to name and leaves authType undefined when manifest is omitted', () => {
+ const parsed = parseSfyMcpServerSummary(BASE_ROW);
+ expect(parsed.description).toBe('github');
+ expect(parsed.authType).toBeUndefined();
+ });
+
+ it('accepts Date timestamps and normalizes to ISO strings', () => {
+ const parsed = parseSfyMcpServerSummary({
+ ...BASE_ROW,
+ createdAt: new Date('2026-02-01T00:00:00.000Z'),
+ updatedAt: new Date('2026-02-02T00:00:00.000Z'),
+ });
+ expect(parsed.createdAt).toBe('2026-02-01T00:00:00.000Z');
+ expect(parsed.updatedAt).toBe('2026-02-02T00:00:00.000Z');
+ });
+
+ it('throws ZodError on contract drift', () => {
+ expect(() => parseSfyMcpServerSummary({ id: 'mcp-1', name: 'github' })).toThrow(ZodError);
+ });
+});
+
+describe('mapSfyMcpServers', () => {
+ it('maps every row through parseSfyMcpServerSummary', () => {
+ expect(mapSfyMcpServers({ rows: [BASE_ROW, { ...BASE_ROW, id: 'mcp-2', name: 'linear' }] })).toHaveLength(2);
+ });
+});
+
+describe('resolveMcpProxyUrl', () => {
+ it('substitutes the gateway base and strips trailing slashes from the base', () => {
+ expect(
+ resolveMcpProxyUrl({
+ proxyUrl: `${MCP_PROXY_BASE_URL_TEMPLATE}/mcp-server/github`,
+ gatewayBaseURL: 'https://gateway.example/',
+ }),
+ ).toBe('https://gateway.example/mcp-server/github');
+ });
+
+ it('replaces every template occurrence', () => {
+ expect(
+ resolveMcpProxyUrl({
+ proxyUrl: `${MCP_PROXY_BASE_URL_TEMPLATE}/a/${MCP_PROXY_BASE_URL_TEMPLATE}/b`,
+ gatewayBaseURL: 'https://gw.example',
+ }),
+ ).toBe('https://gw.example/a/https://gw.example/b');
+ });
+
+ it('returns the proxy URL unchanged when the template is absent', () => {
+ expect(
+ resolveMcpProxyUrl({
+ proxyUrl: 'https://already.resolved.example/mcp',
+ gatewayBaseURL: 'https://gateway.example',
+ }),
+ ).toBe('https://already.resolved.example/mcp');
+ });
+});
+
+describe('toTrueFoundryMcpManifest', () => {
+ it('maps oauth2 to wire dcr and resolves the gateway proxy URL', () => {
+ expect(
+ toTrueFoundryMcpManifest({
+ server: summary({ authType: 'oauth2' }),
+ gatewayUrl: 'https://gateway.example',
+ }),
+ ).toEqual({
+ type: 'truefoundry',
+ name: 'github',
+ url: 'https://gateway.example/mcp-server/github',
+ description: 'GitHub MCP',
+ auth: { type: 'dcr' },
+ });
+ });
+
+ it('omits auth when SFY auth type is not oauth2', () => {
+ expect(
+ toTrueFoundryMcpManifest({
+ server: summary({ authType: 'api_key' }),
+ gatewayUrl: 'https://gateway.example',
+ }).auth,
+ ).toBeUndefined();
+ expect(
+ toTrueFoundryMcpManifest({
+ server: summary({ authType: undefined }),
+ gatewayUrl: 'https://gateway.example',
+ }).auth,
+ ).toBeUndefined();
+ });
+});