The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: TrueFoundry MCP Connect auth via ServiceFoundry (#566)
Srajan Asthana4c1260eab715
diff --git a/.changeset/tf-mcp-connect-auth.md b/.changeset/tf-mcp-connect-auth.mdnew file mode 100644index 000000000..e78d31954--- /dev/null+++ b/.changeset/tf-mcp-connect-auth.md@@ -0,0 +1,7 @@+---+"@truefoundry/trueforge": patch+"@truefoundry/trueforge-ui": patch+"@truefoundry/trueforge-sdk": patch+---++Wire TrueFoundry MCP authorize, status, and delete through ServiceFoundry; stub list auth_status; gate oauth2 invoke mid-turn with authRequired; paginate MCP server lists. UI treats SFY consent `code`/`error` on the FE landing like local DCR success/failure.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex 3df5d5a89..9852ea08a 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -1644,10 +1644,14 @@"$ref": "#/components/schemas/AvailableMCPServer"},"type": "array"+ },+ "pagination": {+ "$ref": "#/components/schemas/TokenPagination"}},"required": [- "data"+ "data",+ "pagination"],"type": "object"},@@ -1702,10 +1706,14 @@"$ref": "#/components/schemas/ConfiguredMCPServer"},"type": "array"+ },+ "pagination": {+ "$ref": "#/components/schemas/TokenPagination"}},"required": [- "data"+ "data",+ "pagination"],"type": "object"},@@ -5786,7 +5794,32 @@},"/api/v1/mcp-servers": {"get": {- "description": "MCP servers as a slim name/url list for the composer. No auth or auth_status.",+ "description": "Paginated MCP servers as a slim name/url list for the composer.",+ "parameters": [+ {+ "description": "Page size. Defaults to 100, max 200.",+ "in": "query",+ "name": "limit",+ "required": false,+ "schema": {+ "default": 100,+ "description": "Page size. Defaults to 100, max 200.",+ "maximum": 200,+ "minimum": 1,+ "type": "integer"+ }+ },+ {+ "description": "Opaque token from a previous response `next_page_token`.",+ "in": "query",+ "name": "page_token",+ "required": false,+ "schema": {+ "description": "Opaque token from a previous response `next_page_token`.",+ "type": "string"+ }+ }+ ],"responses": {"200": {"content": {@@ -5796,7 +5829,17 @@}}},- "description": "All MCP servers (chat projection)."+ "description": "Paginated MCP servers (chat projection)."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid query parameters or page token."},"401": {"content": {@@ -5813,6 +5856,11 @@"tags": ["MCP Servers"],+ "x-fern-pagination": {+ "cursor": "$request.page_token",+ "next_cursor": "$response.pagination.next_page_token",+ "results": "$response.data"+ },"x-fern-sdk-group-name": ["mcpServers"],@@ -5969,7 +6017,7 @@"x-fern-sdk-method-name": "delete_authorization"},"get": {- "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.",+ "description": "Returns current auth status. When OAuth is required, includes an authorization URL. Optional return_to is the post-consent landing path.","parameters": [{"description": "MCP server name.",@@ -5983,12 +6031,12 @@}},{- "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",+ "description": "Same-origin path to land in the browser after consent.","in": "query","name": "return_to","required": false,"schema": {- "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",+ "description": "Same-origin path to land in the browser after consent.","type": "string"}}@@ -7865,7 +7913,32 @@},"/api/v1/settings/mcp-servers": {"get": {- "description": "All MCP servers with nested auth_status (settings / admin projection). Header auth values are redacted.",+ "description": "Paginated MCP servers with auth_status. Header secrets are redacted.",+ "parameters": [+ {+ "description": "Page size. Defaults to 100, max 200.",+ "in": "query",+ "name": "limit",+ "required": false,+ "schema": {+ "default": 100,+ "description": "Page size. Defaults to 100, max 200.",+ "maximum": 200,+ "minimum": 1,+ "type": "integer"+ }+ },+ {+ "description": "Opaque token from a previous response `next_page_token`.",+ "in": "query",+ "name": "page_token",+ "required": false,+ "schema": {+ "description": "Opaque token from a previous response `next_page_token`.",+ "type": "string"+ }+ }+ ],"responses": {"200": {"content": {@@ -7875,7 +7948,17 @@}}},- "description": "All MCP servers"+ "description": "Paginated MCP servers"+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid query parameters or page token."},"401": {"content": {@@ -7902,6 +7985,11 @@"tags": ["MCP Servers"],+ "x-fern-pagination": {+ "cursor": "$request.page_token",+ "next_cursor": "$response.pagination.next_page_token",+ "results": "$response.data"+ },"x-fern-sdk-group-name": ["settings","mcpServers"@@ -8049,7 +8137,7 @@},"/api/v1/settings/mcp-servers/{name}": {"get": {- "description": "A single MCP server by name, with nested auth_status (settings / admin projection). Header auth values are redacted.",+ "description": "A single MCP server by name, with nested live auth_status (settings / admin projection). Header auth values are redacted.","parameters": [{"description": "MCP server name.",diff --git a/AGENTS.md b/AGENTS.mdindex 65cab9f2b..e43455ca3 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -11,7 +11,6 @@- Runtime types backed by Zod schemas MUST be derived with named `z.infer<typeof Schema>` aliases; code MUST NOT duplicate those schemas as hand-written interfaces or indirect utility-type chains.- Modules MUST use static `import` and `import type`; they MUST NOT use `require()`, `require.resolve()`, or lint suppressions to bypass import checks.- A change that makes code unused MUST remove that dead code in the same change; it MUST NOT leave stale exports, files, documentation, duplicates, or “just in case” shims.-- Comments MUST explain intent, trade-offs, or constraints and remain concise; they MUST NOT restate the code or include issue-tracker IDs.- Every nested `AGENTS.md` MUST have a sibling `CLAUDE.md` containing only `@AGENTS.md`, so Cursor and Claude Code load the same scoped rules.- OpenAPI specs under `.github/fern/openapi/openapi.json` and `docs/openapi.json` are autogenerated in CI and MUST NOT be edited manually (both copies MUST stay identical)- Code under `packages/trueforge-sdk` is autogenerated in CI and MUST NOT be edited manually@@ -20,3 +19,11 @@- Zod unions MUST use `z.discriminatedUnion` whenever every member carries a shared literal discriminator field; `z.union` is only permitted when no such common discriminator exists.- HTTP/OpenAPI wire shapes (path params, query params, request/response JSON fields) and database identifiers (table/column names, persisted jsonb document keys) MUST use `snake_case`.- Server code MUST NOT read environment variables via `process.env` directly; all env reads MUST go through `packages/trueforge/src/config.ts`, unless there is a documented special requirement (for example bootstrap before config is loaded).++## Code comments++- Comments MUST explain intent, trade-offs, or constraints and remain brief; they MUST NOT restate the code, include issue-tracker IDs, or use `{@link …}` / deep cross-links.+- Do NOT add file-level banners that enumerate implementations, backends, or call graphs; put a one-line note on the symbol that needs it, or omit.+- Comments MUST NOT leak internal wiring into public or shared surfaces.+- OpenAPI / route `description` and `.describe(…)` strings MUST stay under 50 words and describe the caller-visible contract only — not backend routing or storage.+- TODOs stay to one short line when needed.diff --git a/docs/openapi.json b/docs/openapi.jsonindex 3df5d5a89..9852ea08a 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -1644,10 +1644,14 @@"$ref": "#/components/schemas/AvailableMCPServer"},"type": "array"+ },+ "pagination": {+ "$ref": "#/components/schemas/TokenPagination"}},"required": [- "data"+ "data",+ "pagination"],"type": "object"},@@ -1702,10 +1706,14 @@"$ref": "#/components/schemas/ConfiguredMCPServer"},"type": "array"+ },+ "pagination": {+ "$ref": "#/components/schemas/TokenPagination"}},"required": [- "data"+ "data",+ "pagination"],"type": "object"},@@ -5786,7 +5794,32 @@},"/api/v1/mcp-servers": {"get": {- "description": "MCP servers as a slim name/url list for the composer. No auth or auth_status.",+ "description": "Paginated MCP servers as a slim name/url list for the composer.",+ "parameters": [+ {+ "description": "Page size. Defaults to 100, max 200.",+ "in": "query",+ "name": "limit",+ "required": false,+ "schema": {+ "default": 100,+ "description": "Page size. Defaults to 100, max 200.",+ "maximum": 200,+ "minimum": 1,+ "type": "integer"+ }+ },+ {+ "description": "Opaque token from a previous response `next_page_token`.",+ "in": "query",+ "name": "page_token",+ "required": false,+ "schema": {+ "description": "Opaque token from a previous response `next_page_token`.",+ "type": "string"+ }+ }+ ],"responses": {"200": {"content": {@@ -5796,7 +5829,17 @@}}},- "description": "All MCP servers (chat projection)."+ "description": "Paginated MCP servers (chat projection)."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid query parameters or page token."},"401": {"content": {@@ -5813,6 +5856,11 @@"tags": ["MCP Servers"],+ "x-fern-pagination": {+ "cursor": "$request.page_token",+ "next_cursor": "$response.pagination.next_page_token",+ "results": "$response.data"+ },"x-fern-sdk-group-name": ["mcpServers"],@@ -5969,7 +6017,7 @@"x-fern-sdk-method-name": "delete_authorization"},"get": {- "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.",+ "description": "Returns current auth status. When OAuth is required, includes an authorization URL. Optional return_to is the post-consent landing path.","parameters": [{"description": "MCP server name.",@@ -5983,12 +6031,12 @@}},{- "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",+ "description": "Same-origin path to land in the browser after consent.","in": "query","name": "return_to","required": false,"schema": {- "description": "Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.",+ "description": "Same-origin path to land in the browser after consent.","type": "string"}}@@ -7865,7 +7913,32 @@},"/api/v1/settings/mcp-servers": {"get": {- "description": "All MCP servers with nested auth_status (settings / admin projection). Header auth values are redacted.",+ "description": "Paginated MCP servers with auth_status. Header secrets are redacted.",+ "parameters": [+ {+ "description": "Page size. Defaults to 100, max 200.",+ "in": "query",+ "name": "limit",+ "required": false,+ "schema": {+ "default": 100,+ "description": "Page size. Defaults to 100, max 200.",+ "maximum": 200,+ "minimum": 1,+ "type": "integer"+ }+ },+ {+ "description": "Opaque token from a previous response `next_page_token`.",+ "in": "query",+ "name": "page_token",+ "required": false,+ "schema": {+ "description": "Opaque token from a previous response `next_page_token`.",+ "type": "string"+ }+ }+ ],"responses": {"200": {"content": {@@ -7875,7 +7948,17 @@}}},- "description": "All MCP servers"+ "description": "Paginated MCP servers"+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid query parameters or page token."},"401": {"content": {@@ -7902,6 +7985,11 @@"tags": ["MCP Servers"],+ "x-fern-pagination": {+ "cursor": "$request.page_token",+ "next_cursor": "$response.pagination.next_page_token",+ "results": "$response.data"+ },"x-fern-sdk-group-name": ["settings","mcpServers"@@ -8049,7 +8137,7 @@},"/api/v1/settings/mcp-servers/{name}": {"get": {- "description": "A single MCP server by name, with nested auth_status (settings / admin projection). Header auth values are redacted.",+ "description": "A single MCP server by name, with nested live auth_status (settings / admin projection). Header auth values are redacted.","parameters": [{"description": "MCP server name.",diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.mdindex 556d2dc31..d15745c03 100644--- a/packages/trueforge-sdk/reference.md+++ b/packages/trueforge-sdk/reference.md@@ -441,7 +441,7 @@ await client.server.getCapabilities();</details>## MCP Servers-<details><summary><code>client.mcpServers.<a href="/src/api/resources/mcpServers/client/Client.ts">list</a>() -> TrueForge.ListAvailableMcpServersResponse</code></summary>+<details><summary><code>client.mcpServers.<a href="/src/api/resources/mcpServers/client/Client.ts">list</a>({ ...params }) -> core.Page<TrueForge.AvailableMcpServer, TrueForge.ListAvailableMcpServersResponse></code></summary><dl><dd>@@ -453,7 +453,7 @@ await client.server.getCapabilities();<dl><dd>-MCP servers as a slim name/url list for the composer. No auth or auth_status.+Paginated MCP servers as a slim name/url list for the composer.</dd></dl></dd>@@ -484,6 +484,14 @@ await client.mcpServers.list();<dl><dd>+**request:** `TrueForge.ListMcpServersRequest`++</dd>+</dl>++<dl>+<dd>+**requestOptions:** `McpServersClient.RequestOptions`</dd>@@ -508,7 +516,7 @@ await client.mcpServers.list();<dl><dd>-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.+Returns current auth status. When OAuth is required, includes an authorization URL. Optional return_to is the post-consent landing path.</dd></dl></dd>@@ -2826,7 +2834,7 @@ await client.internal.agents.getCodeSnippets("agent_id");</details>## Settings McpServers-<details><summary><code>client.settings.mcpServers.<a href="/src/api/resources/settings/resources/mcpServers/client/Client.ts">list</a>() -> TrueForge.ListMcpServersResponse</code></summary>+<details><summary><code>client.settings.mcpServers.<a href="/src/api/resources/settings/resources/mcpServers/client/Client.ts">list</a>({ ...params }) -> core.Page<TrueForge.ConfiguredMcpServer, TrueForge.ListMcpServersResponse></code></summary><dl><dd>@@ -2838,7 +2846,7 @@ await client.internal.agents.getCodeSnippets("agent_id");<dl><dd>-All MCP servers with nested auth_status (settings / admin projection). Header auth values are redacted.+Paginated MCP servers with auth_status. Header secrets are redacted.</dd></dl></dd>@@ -2869,6 +2877,14 @@ await client.settings.mcpServers.list();<dl><dd>+**request:** `TrueForge.settings.ListMcpServersRequest`++</dd>+</dl>++<dl>+<dd>+**requestOptions:** `McpServersClient.RequestOptions`</dd>@@ -3033,7 +3049,7 @@ await client.settings.mcpServers.createOrUpdate({<dl><dd>-A single MCP server by name, with nested auth_status (settings / admin projection). Header auth values are redacted.+A single MCP server by name, with nested live auth_status (settings / admin projection). Header auth values are redacted.</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.tsindex 6c76af5a7..e72285989 100644--- a/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/Client.ts@@ -23,10 +23,12 @@ export class McpServersClient {}/**- * MCP servers as a slim name/url list for the composer. No auth or auth_status.+ * Paginated MCP servers as a slim name/url list for the composer.*+ * @param {TrueForge.ListMcpServersRequest} request* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.*+ * @throws {@link TrueForge.BadRequestError}* @throws {@link TrueForge.UnauthorizedError}* @throws {@link errors.TrueForgeError}* @throws {@link errors.TrueForgeTimeoutError}@@ -34,76 +36,107 @@ export class McpServersClient {* @example* await client.mcpServers.list()*/- public list(- requestOptions?: McpServersClient.RequestOptions,- ): core.HttpResponsePromise<TrueForge.ListAvailableMcpServersResponse> {- return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));- }-- private async __list(+ public async list(+ request: TrueForge.ListMcpServersRequest = {},requestOptions?: McpServersClient.RequestOptions,- ): Promise<core.WithRawResponse<TrueForge.ListAvailableMcpServersResponse>> {- const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();- const _headers: core.Fetcher.Args["headers"] = mergeHeaders(- _authRequest.headers,- this._options?.headers,- requestOptions?.headers,- );- const _response = await (this._options.fetcher ?? core.fetcher)({- url: core.url.join(- (await core.Supplier.get(this._options.baseUrl)) ??- (await core.Supplier.get(this._options.environment)),- "api/v1/mcp-servers",- ),- method: "GET",- headers: _headers,- queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),- timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,- maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,- abortSignal: requestOptions?.abortSignal,- fetchFn: this._options?.fetch,- logging: this._options.logging,- });- if (_response.ok) {- return {- data: serializers.ListAvailableMcpServersResponse.parseOrThrow(_response.body, {- unrecognizedObjectKeys: "passthrough",- allowUnrecognizedUnionMembers: true,- allowUnrecognizedEnumValues: true,- skipValidation: true,- breadcrumbsPrefix: ["response"],- }),- rawResponse: _response.rawResponse,- };- }-- if (_response.error.reason === "status-code") {- switch (_response.error.statusCode) {- case 401:- throw new TrueForge.UnauthorizedError(- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ ): Promise<core.Page<TrueForge.AvailableMcpServer, TrueForge.ListAvailableMcpServersResponse>> {+ const list = core.HttpResponsePromise.interceptFunction(+ async (+ request: TrueForge.ListMcpServersRequest,+ ): Promise<core.WithRawResponse<TrueForge.ListAvailableMcpServersResponse>> => {+ const { limit = 100, pageToken } = request;+ const _queryParams: Record<string, unknown> = {+ limit,+ page_token: pageToken,+ };+ const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(+ _authRequest.headers,+ this._options?.headers,+ requestOptions?.headers,+ );+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/mcp-servers",+ ),+ method: "GET",+ headers: _headers,+ queryString: core.url+ .queryBuilder()+ .addMany(_queryParams)+ .mergeAdditional(requestOptions?.queryParams)+ .build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.ListAvailableMcpServersResponse.parseOrThrow(_response.body, {unrecognizedObjectKeys: "passthrough",allowUnrecognizedUnionMembers: true,allowUnrecognizedEnumValues: true,skipValidation: true,breadcrumbsPrefix: ["response"],}),- _response.rawResponse,- );- default:- throw new errors.TrueForgeError({- statusCode: _response.error.statusCode,- body: _response.error.body,rawResponse: _response.rawResponse,- });- }- }-- return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/mcp-servers");+ };+ }+ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 400:+ throw new TrueForge.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 401:+ throw new TrueForge.UnauthorizedError(+ 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,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/mcp-servers");+ },+ );+ const dataWithRawResponse = await list(request).withRawResponse();+ return new core.Page<TrueForge.AvailableMcpServer, TrueForge.ListAvailableMcpServersResponse>({+ response: dataWithRawResponse.data,+ rawResponse: dataWithRawResponse.rawResponse,+ hasNextPage: (response) =>+ response?.pagination.nextPageToken != null &&+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),+ getItems: (response) => response?.data ?? [],+ loadPage: (response) => {+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));+ },+ });}/**- * 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.+ * Returns current auth status. When OAuth is required, includes an authorization URL. Optional return_to is the post-consent landing path.** @param {string} name - MCP server name.* @param {TrueForge.AuthorizeMcpServersRequest} requestdiff --git a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.tsindex 1393c70f6..a401bd427 100644--- a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts@@ -5,6 +5,6 @@* {}*/export interface AuthorizeMcpServersRequest {- /** Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended. */+ /** Same-origin path to land in the browser after consent. */returnTo?: string;}diff --git a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/ListMcpServersRequest.ts b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/ListMcpServersRequest.tsnew file mode 100644index 000000000..1ae7afca8--- /dev/null+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/ListMcpServersRequest.ts@@ -0,0 +1,12 @@+// This file was auto-generated by Fern from our API Definition.++/**+ * @example+ * {}+ */+export interface ListMcpServersRequest {+ /** Page size. Defaults to 100, max 200. */+ limit?: number;+ /** Opaque token from a previous response `next_page_token`. */+ pageToken?: string;+}diff --git a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/index.tsindex 9f3c48ef4..3716ca15b 100644--- a/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/index.ts+++ b/packages/trueforge-sdk/src/api/resources/mcpServers/client/requests/index.ts@@ -1 +1,2 @@export type { AuthorizeMcpServersRequest } from "./AuthorizeMcpServersRequest.js";+export type { ListMcpServersRequest } from "./ListMcpServersRequest.js";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.tsindex 8de9d7c10..4c38f5d30 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@@ -24,10 +24,12 @@ export class McpServersClient {}/**- * All MCP servers with nested auth_status (settings / admin projection). Header auth values are redacted.+ * Paginated MCP servers with auth_status. Header secrets are redacted.*+ * @param {TrueForge.settings.ListMcpServersRequest} request* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.*+ * @throws {@link TrueForge.BadRequestError}* @throws {@link TrueForge.UnauthorizedError}* @throws {@link TrueForge.ForbiddenError}* @throws {@link errors.TrueForgeError}@@ -36,83 +38,119 @@ export class McpServersClient {* @example* await client.settings.mcpServers.list()*/- public list(- requestOptions?: McpServersClient.RequestOptions,- ): core.HttpResponsePromise<TrueForge.ListMcpServersResponse> {- return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));- }-- private async __list(+ public async list(+ request: TrueForge.settings.ListMcpServersRequest = {},requestOptions?: McpServersClient.RequestOptions,- ): Promise<core.WithRawResponse<TrueForge.ListMcpServersResponse>> {- const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();- const _headers: core.Fetcher.Args["headers"] = mergeHeaders(- _authRequest.headers,- this._options?.headers,- requestOptions?.headers,- );- const _response = await (this._options.fetcher ?? core.fetcher)({- url: core.url.join(- (await core.Supplier.get(this._options.baseUrl)) ??- (await core.Supplier.get(this._options.environment)),- "api/v1/settings/mcp-servers",- ),- method: "GET",- headers: _headers,- queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),- timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,- maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,- abortSignal: requestOptions?.abortSignal,- fetchFn: this._options?.fetch,- logging: this._options.logging,- });- if (_response.ok) {- return {- data: serializers.ListMcpServersResponse.parseOrThrow(_response.body, {- unrecognizedObjectKeys: "passthrough",- allowUnrecognizedUnionMembers: true,- allowUnrecognizedEnumValues: true,- skipValidation: true,- breadcrumbsPrefix: ["response"],- }),- rawResponse: _response.rawResponse,- };- }-- if (_response.error.reason === "status-code") {- switch (_response.error.statusCode) {- case 401:- throw new TrueForge.UnauthorizedError(- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {- unrecognizedObjectKeys: "passthrough",- allowUnrecognizedUnionMembers: true,- allowUnrecognizedEnumValues: true,- skipValidation: true,- breadcrumbsPrefix: ["response"],- }),- _response.rawResponse,- );- case 403:- throw new TrueForge.ForbiddenError(- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ ): Promise<core.Page<TrueForge.ConfiguredMcpServer, TrueForge.ListMcpServersResponse>> {+ const list = core.HttpResponsePromise.interceptFunction(+ async (+ request: TrueForge.settings.ListMcpServersRequest,+ ): Promise<core.WithRawResponse<TrueForge.ListMcpServersResponse>> => {+ const { limit = 100, pageToken } = request;+ const _queryParams: Record<string, unknown> = {+ limit,+ page_token: pageToken,+ };+ const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest();+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(+ _authRequest.headers,+ this._options?.headers,+ requestOptions?.headers,+ );+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/settings/mcp-servers",+ ),+ method: "GET",+ headers: _headers,+ queryString: core.url+ .queryBuilder()+ .addMany(_queryParams)+ .mergeAdditional(requestOptions?.queryParams)+ .build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.ListMcpServersResponse.parseOrThrow(_response.body, {unrecognizedObjectKeys: "passthrough",allowUnrecognizedUnionMembers: true,allowUnrecognizedEnumValues: true,skipValidation: true,breadcrumbsPrefix: ["response"],}),- _response.rawResponse,- );- default:- throw new errors.TrueForgeError({- statusCode: _response.error.statusCode,- body: _response.error.body,rawResponse: _response.rawResponse,- });- }- }-- return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/settings/mcp-servers");+ };+ }+ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 400:+ throw new TrueForge.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 401:+ throw new TrueForge.UnauthorizedError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 403:+ throw new TrueForge.ForbiddenError(+ 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,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }+ return handleNonStatusCodeError(+ _response.error,+ _response.rawResponse,+ "GET",+ "/api/v1/settings/mcp-servers",+ );+ },+ );+ const dataWithRawResponse = await list(request).withRawResponse();+ return new core.Page<TrueForge.ConfiguredMcpServer, TrueForge.ListMcpServersResponse>({+ response: dataWithRawResponse.data,+ rawResponse: dataWithRawResponse.rawResponse,+ hasNextPage: (response) =>+ response?.pagination.nextPageToken != null &&+ !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""),+ getItems: (response) => response?.data ?? [],+ loadPage: (response) => {+ return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken));+ },+ });}/**@@ -378,7 +416,7 @@ export class McpServersClient {}/**- * A single MCP server by name, with nested auth_status (settings / admin projection). Header auth values are redacted.+ * A single MCP server by name, with nested live auth_status (settings / admin projection). Header auth values are redacted.** @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/requests/ListMcpServersRequest.ts b/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/requests/ListMcpServersRequest.tsnew file mode 100644index 000000000..1ae7afca8--- /dev/null+++ b/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/requests/ListMcpServersRequest.ts@@ -0,0 +1,12 @@+// This file was auto-generated by Fern from our API Definition.++/**+ * @example+ * {}+ */+export interface ListMcpServersRequest {+ /** Page size. Defaults to 100, max 200. */+ limit?: number;+ /** Opaque token from a previous response `next_page_token`. */+ pageToken?: string;+}diff --git a/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/requests/index.tsindex fc296fdb3..f613d1329 100644--- a/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/requests/index.ts+++ b/packages/trueforge-sdk/src/api/resources/settings/resources/mcpServers/client/requests/index.ts@@ -1,2 +1,3 @@export type { CreateMcpServerRequest } from "./CreateMcpServerRequest.js";+export type { ListMcpServersRequest } from "./ListMcpServersRequest.js";export type { UpdateMcpServerRequest } from "./UpdateMcpServerRequest.js";diff --git a/packages/trueforge-sdk/src/api/types/ListAvailableMcpServersResponse.ts b/packages/trueforge-sdk/src/api/types/ListAvailableMcpServersResponse.tsindex 6801fb973..d2d9c7525 100644--- a/packages/trueforge-sdk/src/api/types/ListAvailableMcpServersResponse.ts+++ b/packages/trueforge-sdk/src/api/types/ListAvailableMcpServersResponse.ts@@ -4,4 +4,5 @@ import type * as TrueForge from "../index.js";export interface ListAvailableMcpServersResponse {data: TrueForge.AvailableMcpServer[];+ pagination: TrueForge.TokenPagination;}diff --git a/packages/trueforge-sdk/src/api/types/ListMcpServersResponse.ts b/packages/trueforge-sdk/src/api/types/ListMcpServersResponse.tsindex e0165c61d..a97f0018c 100644--- a/packages/trueforge-sdk/src/api/types/ListMcpServersResponse.ts+++ b/packages/trueforge-sdk/src/api/types/ListMcpServersResponse.ts@@ -4,4 +4,5 @@ import type * as TrueForge from "../index.js";export interface ListMcpServersResponse {data: TrueForge.ConfiguredMcpServer[];+ pagination: TrueForge.TokenPagination;}diff --git a/packages/trueforge-sdk/src/serialization/types/ListAvailableMcpServersResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListAvailableMcpServersResponse.tsindex 84dbffc66..47abdf4d4 100644--- a/packages/trueforge-sdk/src/serialization/types/ListAvailableMcpServersResponse.ts+++ b/packages/trueforge-sdk/src/serialization/types/ListAvailableMcpServersResponse.ts@@ -4,16 +4,19 @@ import type * as TrueForge from "../../api/index.js";import * as core from "../../core/index.js";import type * as serializers from "../index.js";import { AvailableMcpServer } from "./AvailableMcpServer.js";+import { TokenPagination } from "./TokenPagination.js";export const ListAvailableMcpServersResponse: core.serialization.ObjectSchema<serializers.ListAvailableMcpServersResponse.Raw,TrueForge.ListAvailableMcpServersResponse> = core.serialization.object({data: core.serialization.list(AvailableMcpServer),+ pagination: TokenPagination,});export declare namespace ListAvailableMcpServersResponse {export interface Raw {data: AvailableMcpServer.Raw[];+ pagination: TokenPagination.Raw;}}diff --git a/packages/trueforge-sdk/src/serialization/types/ListMcpServersResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListMcpServersResponse.tsindex cb4af53ea..edff253b4 100644--- a/packages/trueforge-sdk/src/serialization/types/ListMcpServersResponse.ts+++ b/packages/trueforge-sdk/src/serialization/types/ListMcpServersResponse.ts@@ -4,16 +4,19 @@ import type * as TrueForge from "../../api/index.js";import * as core from "../../core/index.js";import type * as serializers from "../index.js";import { ConfiguredMcpServer } from "./ConfiguredMcpServer.js";+import { TokenPagination } from "./TokenPagination.js";export const ListMcpServersResponse: core.serialization.ObjectSchema<serializers.ListMcpServersResponse.Raw,TrueForge.ListMcpServersResponse> = core.serialization.object({data: core.serialization.list(ConfiguredMcpServer),+ pagination: TokenPagination,});export declare namespace ListMcpServersResponse {export interface Raw {data: ConfiguredMcpServer.Raw[];+ pagination: TokenPagination.Raw;}}diff --git a/packages/trueforge-sdk/tests/wire/mcpServers.test.ts b/packages/trueforge-sdk/tests/wire/mcpServers.test.tsindex 76183071d..7481d6b7e 100644--- a/packages/trueforge-sdk/tests/wire/mcpServers.test.ts+++ b/packages/trueforge-sdk/tests/wire/mcpServers.test.ts@@ -11,18 +11,18 @@ describe("McpServersClient", () => {const rawResponseBody = {data: [{ auth: { type: "dcr" }, auth_status: { status: "authenticated" }, name: "name", url: "url" }],+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },};server- .mockEndpoint()+ .mockEndpoint({ once: false }).get("/api/v1/mcp-servers").respondWith().statusCode(200).jsonBody(rawResponseBody).build();- const response = await client.mcpServers.list();- expect(response).toEqual({+ const expected = {data: [{auth: {@@ -35,7 +35,18 @@ describe("McpServersClient", () => {url: "url",},],- });+ pagination: {+ limit: 1,+ nextPageToken: "next_page_token",+ previousPageToken: "previous_page_token",+ },+ };+ const page = await client.mcpServers.list();++ expect(expected.data).toEqual(page.data);+ expect(page.hasNextPage()).toBe(true);+ const nextPage = await page.getNextPage();+ expect(expected.data).toEqual(nextPage.data);});test("list (2)", async () => {@@ -44,6 +55,25 @@ describe("McpServersClient", () => {const rawResponseBody = { error: { message: "message" } };+ server+ .mockEndpoint()+ .get("/api/v1/mcp-servers")+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.mcpServers.list();+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("list (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };+server.mockEndpoint().get("/api/v1/mcp-servers")diff --git a/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts b/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.tsindex 9e92895a3..0a673c9b5 100644--- a/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts+++ b/packages/trueforge-sdk/tests/wire/settings/mcpServers.test.ts@@ -17,18 +17,18 @@ describe("McpServersClient", () => {name: "name",},],+ pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" },};server- .mockEndpoint()+ .mockEndpoint({ once: false }).get("/api/v1/settings/mcp-servers").respondWith().statusCode(200).jsonBody(rawResponseBody).build();- const response = await client.settings.mcpServers.list();- expect(response).toEqual({+ const expected = {data: [{authStatus: {@@ -43,7 +43,18 @@ describe("McpServersClient", () => {name: "name",},],- });+ pagination: {+ limit: 1,+ nextPageToken: "next_page_token",+ previousPageToken: "previous_page_token",+ },+ };+ const page = await client.settings.mcpServers.list();++ expect(expected.data).toEqual(page.data);+ expect(page.hasNextPage()).toBe(true);+ const nextPage = await page.getNextPage();+ expect(expected.data).toEqual(nextPage.data);});test("list (2)", async () => {@@ -52,6 +63,25 @@ describe("McpServersClient", () => {const rawResponseBody = { error: { message: "message" } };+ server+ .mockEndpoint()+ .get("/api/v1/settings/mcp-servers")+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.settings.mcpServers.list();+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("list (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };+server.mockEndpoint().get("/api/v1/settings/mcp-servers")@@ -65,7 +95,7 @@ describe("McpServersClient", () => {}).rejects.toThrow(TrueForgeTypes.UnauthorizedError);});- test("list (3)", async () => {+ test("list (4)", async () => {const server = mockServerPool.createServer();const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl });diff --git a/packages/trueforge-ui/src/containers/McpOauthContainer/PostMcpOauthScreen.tsx b/packages/trueforge-ui/src/containers/McpOauthContainer/PostMcpOauthScreen.tsxindex da513d140..0edd532e1 100644--- a/packages/trueforge-ui/src/containers/McpOauthContainer/PostMcpOauthScreen.tsx+++ b/packages/trueforge-ui/src/containers/McpOauthContainer/PostMcpOauthScreen.tsx@@ -8,13 +8,31 @@ import { Icon } from '../../icons/Icon.js';const BROADCAST_RETRY_DELAY_MS = 1000;const WINDOW_CLOSE_DELAY_MS = 5000;+/**+ * Prefer `isSuccess` when present; otherwise treat a `code` without `error` as success.+ */+function resolvePopupSuccess(searchParams: URLSearchParams): boolean {+ if (searchParams.get('error')) {+ return false;+ }+ const flag = searchParams.get('isSuccess')?.toLowerCase();+ if (flag === 'true') {+ return true;+ }+ if (flag === 'false') {+ return false;+ }+ const code = searchParams.get('code');+ return code != null && code.length > 0;+}+const PostMcpOauthScreen = () => {const [result, setResult] = useState<McpAuthPopupMessage | null>();useEffect(() => {const searchParams = new URLSearchParams(window.location.search);const popupUid = searchParams.get('pUid');- const isSuccess = searchParams.get('isSuccess')?.toLowerCase() === 'true';+ const isSuccess = resolvePopupSuccess(searchParams);setResult(popupUid ? { popupUid, isSuccess } : null);const broadcastResult = () => {diff --git a/packages/trueforge-ui/test/containers/McpOauthContainer/PostMcpOauthScreen.test.tsx b/packages/trueforge-ui/test/containers/McpOauthContainer/PostMcpOauthScreen.test.tsxindex 40721b396..94acdd782 100644--- a/packages/trueforge-ui/test/containers/McpOauthContainer/PostMcpOauthScreen.test.tsx+++ b/packages/trueforge-ui/test/containers/McpOauthContainer/PostMcpOauthScreen.test.tsx@@ -61,6 +61,30 @@ describe('PostMcpOauthScreen', () => {expect(channels[1]?.close).toHaveBeenCalledOnce();});+ it('treats TrueFoundry code (without error) as success', () => {+ window.history.replaceState({}, '', '/?screenType=mcp-auth&pUid=popup-tfy&code=inbound-auth-code');++ render(<PostMcpOauthScreen />);++ expect(screen.getByRole('heading', { name: 'Authorization successful' })).toBeInTheDocument();+ expect(channels[0]?.postMessage).toHaveBeenCalledWith({+ popupUid: 'popup-tfy',+ isSuccess: true,+ });+ });++ it('treats TrueFoundry error as failure even when code is also present', () => {+ window.history.replaceState({}, '', '/?screenType=mcp-auth&pUid=popup-deny&code=x&error=access_denied');++ render(<PostMcpOauthScreen />);++ expect(screen.getByRole('heading', { name: 'Authorization failed' })).toBeInTheDocument();+ expect(channels[0]?.postMessage).toHaveBeenCalledWith({+ popupUid: 'popup-deny',+ isSuccess: false,+ });+ });+it('renders and broadcasts a failed authorization result', () => {window.history.replaceState({}, '', '/oauth/callback?pUid=popup-456&isSuccess=false');diff --git a/packages/trueforge/src/apis/mcpServers.ts b/packages/trueforge/src/apis/mcpServers.tsindex 805a51b92..ca5ea1395 100644--- a/packages/trueforge/src/apis/mcpServers.ts+++ b/packages/trueforge/src/apis/mcpServers.ts@@ -1,6 +1,8 @@import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';+import { InvalidPageTokenError } from '@truefoundry/trueforge-core/agent-session';import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/trueforge-core/core';import type { Context } from 'hono';+import { HTTPException } from 'hono/http-exception';import type { Logger } from 'winston';import type { ResolveRequestContext } from '../auth/identity';import { safeReturnTo } from '../auth/safeReturnTo';@@ -115,25 +117,35 @@ async function toConfiguredMcpServer<TTransaction>(params: {};}-/** Admin/settings MCP CRUD (mounted at /api/v1/settings/mcp-servers). */+/** Admin/settings MCP CRUD. */export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {const listHandler: RouteHandler<typeof listMcpServersRoute> = async c => {const requestContext = deps.resolveRequestContext(c);const userRef = requestContext.subject.id;- const records = await deps.resolveMcpServerStore(c).listServers({- tenant_id: requestContext.tenant_id,- names: undefined,- });- const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({- records,- userRef,- });- const data: ConfiguredMcpServer[] = records.map(record => ({- name: record.name,- manifest: redactMcpServerManifest(record.manifest),- auth_status: statuses.get(record.name) ?? { status: 'auth_required' },- }));- return c.json({ data }, 200);+ const { limit, page_token: pageToken } = c.req.valid('query');+ try {+ const { data: records, pagination } = await deps.resolveMcpServerStore(c).listServers({+ tenant_id: requestContext.tenant_id,+ names: undefined,+ limit,+ page_token: pageToken,+ });+ const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({+ records,+ userRef,+ });+ const data: ConfiguredMcpServer[] = records.map(record => ({+ name: record.name,+ manifest: redactMcpServerManifest(record.manifest),+ auth_status: statuses.get(record.name) ?? { status: 'auth_required' },+ }));+ return c.json({ data, pagination }, 200);+ } catch (error) {+ if (error instanceof InvalidPageTokenError) {+ return c.json({ error: { message: error.message } }, 400);+ }+ throw error;+ }};const getHandler: RouteHandler<typeof getMcpServerRoute> = async c => {@@ -148,7 +160,13 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRoureturn c.json({ error: { message: `MCP server not found: ${name}` } }, 404);}return c.json(- { data: await toConfiguredMcpServer({ store: deps.resolveMcpServerStore(c), record, userRef }) },+ {+ data: await toConfiguredMcpServer({+ store: deps.resolveMcpServerStore(c),+ record,+ userRef,+ }),+ },200,);};@@ -287,7 +305,13 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou});return c.json(- { data: await toConfiguredMcpServer({ store: deps.resolveMcpServerStore(c), record, userRef }) },+ {+ data: await toConfiguredMcpServer({+ store: deps.resolveMcpServerStore(c),+ record,+ userRef,+ }),+ },200,);} catch (error) {@@ -313,7 +337,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRoureturn router;}-/** List, tools, and authorize (mounted at /api/v1/mcp-servers). */+/** Chat list, tools, and authorize. */export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {const authorizeHandler: RouteHandler<typeof authorizeMcpServerRoute> = async c => {const { name } = c.req.valid('param');@@ -334,6 +358,9 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<});return c.json(authStatus, 200);} catch (error) {+ if (error instanceof HTTPException) {+ throw error;+ }if (error instanceof McpServerNotFoundError) {return c.json({ error: { message: error.message } }, 404);}@@ -364,8 +391,6 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<tenant_id: requestContext.tenant_id,name,store: deps.resolveMcpServerStore(c),- tokenStore: deps.tokenStore,- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,userRef,});if (connection === undefined) {@@ -419,7 +444,11 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<});return c.json({- data: await toConfiguredMcpServer({ store: deps.resolveMcpServerStore(c), record, userRef }),+ data: await toConfiguredMcpServer({+ store: deps.resolveMcpServerStore(c),+ record,+ userRef,+ }),},200,);@@ -435,24 +464,34 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<router.openapi(listAvailableMcpServersRoute, async c => {const requestContext = deps.resolveRequestContext(c);const userRef = requestContext.subject.id;- const records = await deps.resolveMcpServerStore(c).listServers({- tenant_id: requestContext.tenant_id,- names: undefined,- });- const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({- records,- userRef,- });- const data: AvailableMcpServer[] = records.map(record => {- const authType = record.manifest.auth?.type;- return {- name: record.name,- url: record.manifest.url,- ...(authType !== undefined ? { auth: { type: authType } } : {}),- auth_status: statuses.get(record.name) ?? { status: 'auth_required' },- };- });- return c.json({ data }, 200);+ const { limit, page_token: pageToken } = c.req.valid('query');+ try {+ const { data: records, pagination } = await deps.resolveMcpServerStore(c).listServers({+ tenant_id: requestContext.tenant_id,+ names: undefined,+ limit,+ page_token: pageToken,+ });+ const statuses = await deps.resolveMcpServerStore(c).resolveAuthStatuses({+ records,+ userRef,+ });+ const data: AvailableMcpServer[] = records.map(record => {+ const authType = record.manifest.auth?.type;+ return {+ name: record.name,+ url: record.manifest.url,+ ...(authType !== undefined ? { auth: { type: authType } } : {}),+ auth_status: statuses.get(record.name) ?? { status: 'auth_required' },+ };+ });+ return c.json({ data, pagination }, 200);+ } catch (error) {+ if (error instanceof InvalidPageTokenError) {+ return c.json({ error: { message: error.message } }, 400);+ }+ throw error;+ }});router.openapi(listMcpServerToolsRoute, listToolsHandler);router.openapi(authorizeMcpServerRoute, authorizeHandler);diff --git a/packages/trueforge/src/apis/turns.ts b/packages/trueforge/src/apis/turns.tsindex f7f3afb9f..68cb78f5e 100644--- a/packages/trueforge/src/apis/turns.ts+++ b/packages/trueforge/src/apis/turns.ts@@ -36,7 +36,6 @@ import type { IMcpServerWithAuthStore } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { ISkillStore } from '../db/skillStore';-import type { IOAuthTokenStore } from '../mcp/auth/types';import {createAndExecuteTurnRoute,downloadSandboxFileRoute,@@ -106,7 +105,6 @@ export interface TurnsRouterDeps {activeTurns: ActiveTurnRegistry;resolveModelProviderStore: (c: Context) => IModelProviderStore;resolveMcpServerStore: (c: Context) => IMcpServerWithAuthStore;- tokenStore: IOAuthTokenStore;skillStore: ISkillStore;agentStore: IAgentStore;/** Resumable live turn-event transport: create-turn writes, subscribe polls. */@@ -123,7 +121,7 @@ export interface TurnsRouterDeps {*/export type BeginTurnExecutionDeps = Pick<TurnsRouterDeps,- 'activeTurns' | 'eventSubscriptions' | 'tokenStore' | 'skillStore' | 'agentStore' | 'sandboxProviderStore' | 'logger'+ 'activeTurns' | 'eventSubscriptions' | 'skillStore' | 'agentStore' | 'sandboxProviderStore' | 'logger'> & {modelProviderStore: IModelProviderStore;mcpServerStore: IMcpServerWithAuthStore;@@ -135,7 +133,6 @@ export type BeginTurnExecutionDeps = Pick<*/function createTurnResolver(deps: {mcpServerStore: IMcpServerWithAuthStore;- tokenStore: IOAuthTokenStore;skillStore: ISkillStore;sandboxProviderStore: ISandboxProviderStore;agentStore: IAgentStore;@@ -148,7 +145,6 @@ function createTurnResolver(deps: {}): TurnResourceResolver {const {mcpServerStore,- tokenStore,skillStore,sandboxProviderStore,agentStore,@@ -181,8 +177,6 @@ function createTurnResolver(deps: {tenant_id,name,store: mcpServerStore,- tokenStore,- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,userRef,});if (connection === undefined) {@@ -378,7 +372,6 @@ export async function beginTurnExecution(params: {const tenant_id = session.tenant_id;const resolver = createTurnResolver({mcpServerStore: deps.mcpServerStore,- tokenStore: deps.tokenStore,skillStore: deps.skillStore,sandboxProviderStore: deps.sandboxProviderStore,agentStore: deps.agentStore,diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.tsindex b123a7630..79c4d28ad 100644--- a/packages/trueforge/src/app.ts+++ b/packages/trueforge/src/app.ts@@ -253,8 +253,8 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {authMiddleware,),);- // Public MCP OAuth callback must be registered before the gated `/mcp-servers` mount so- // `withAuth` cannot intercept IdP redirects to `/api/v1/mcp-servers/oauth/*`.+ // Public MCP OAuth callbacks (local DCR + TrueFoundry/SFY) must be registered before the gated+ // `/mcp-servers` mount so `withAuth` cannot intercept IdP redirects to `/api/v1/mcp-servers/oauth/*`.app.route('/api/v1/mcp-servers/oauth',createMcpOAuthRouter({@@ -314,7 +314,6 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {eventSubscriptions: deps.eventSubscriptions,modelProviderStore: deps.resolveModelProviderStore(),mcpServerStore: deps.resolveMcpServerStore(),- tokenStore: deps.tokenStore,skillStore: deps.skillStore,agentStore: deps.agentStore,sandboxProviderStore: deps.sandboxProviderStore,@@ -396,7 +395,6 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {activeTurns: deps.activeTurns,resolveModelProviderStore: deps.resolveModelProviderStore,resolveMcpServerStore: deps.resolveMcpServerStore,- tokenStore: deps.tokenStore,skillStore: deps.skillStore,agentStore: deps.agentStore,eventSubscriptions: deps.eventSubscriptions,diff --git a/packages/trueforge/src/db/McpServerWithAuthStore.ts b/packages/trueforge/src/db/McpServerWithAuthStore.tsindex 47272af99..b9f8060bf 100644--- a/packages/trueforge/src/db/McpServerWithAuthStore.ts+++ b/packages/trueforge/src/db/McpServerWithAuthStore.ts@@ -1,8 +1,5 @@-/**- * Wraps a DB-backed {@link IMcpServerStore} with local DCR authorize / status / revoke- * and configured invoke headers so API handlers can call auth methods on the store- * without depending on a token store.- */+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import type { RemoteMcpHeaders } from '@truefoundry/trueforge-core/core';import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';import type { IOAuthTokenStore, OAuthClientRecord } from '../mcp/auth/types';import { resolveConfiguredMcpRequestHeaders, resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer';@@ -35,7 +32,10 @@ export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerWthis.#clientName = input.clientName;}- listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]> {+ listServers(+ input: ListMcpServersInput,+ transaction?: TTransaction,+ ): Promise<{ data: McpServerRecord[]; pagination: TokenPagination }> {return this.#store.listServers(input, transaction);}@@ -55,7 +55,30 @@ export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerWreturn this.#store.upsertServer(input, transaction);}- resolveInvokeHeaders(record: McpServerRecord): Record<string, string> {+ resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders {+ const { record, userRef } = input;+ if (record.manifest.auth?.type === 'dcr') {+ return async () => {+ const result = await resolveMcpAuth({+ tokenStore: this.#tokenStore,+ mcpServerStore: this.#store,+ serverId: record.id,+ userRef,+ mcpServerUrl: record.manifest.url,+ mcpServerName: record.name,+ clientName: this.#clientName,+ });+ if (isMcpAuthRequired(result)) {+ // Wire `id` must match RemoteMCP.id (AgentSpec name), not the DB row ULID.+ return {+ authRequired: {+ servers: [{ id: record.name, name: record.name, auth_url: result.authUrl.href }],+ },+ };+ }+ return { headers: result.headers };+ };+ }return resolveConfiguredMcpRequestHeaders(record.manifest);}@@ -89,7 +112,6 @@ export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerW}async authorize(input: AuthorizeMcpServerInput): Promise<McpAuthStatus> {- void input.redirectURL;const record = await this.#store.getServer({ tenant_id: input.tenant_id, name: input.name });if (record === undefined) {throw new McpServerNotFoundError(input.name);diff --git a/packages/trueforge/src/db/mcpServerStore.ts b/packages/trueforge/src/db/mcpServerStore.tsindex 225a8b69e..936a1c51b 100644--- a/packages/trueforge/src/db/mcpServerStore.ts+++ b/packages/trueforge/src/db/mcpServerStore.ts@@ -1,17 +1,5 @@-/**- * Configured MCP servers: identity columns plus a Zod-validated `McpServerManifest` jsonb document.- *- * - {@link IMcpServerStore}: CRUD + DCR client columns (`IOAuthClientStore`).- * Implemented by PostgresMcpServerStore, SqliteMcpServerStore, and- * TrueFoundryMcpServerStore (read-only ServiceFoundry listing).- * - {@link IMcpServerWithAuthStore}: persistence + authorize / status / revoke +- * {@link IMcpServerWithAuthStore.resolveInvokeHeaders};- * {@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 `?:`.- */+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import type { RemoteMcpHeaders } from '@truefoundry/trueforge-core/core';import type {OAuthClientRecord as ContractOAuthClientRecord,OAuthPendingAuthorization as ContractOAuthPendingAuthorization,@@ -39,8 +27,10 @@ export interface GetMcpServerInput {export interface ListMcpServersInput {tenant_id: string;- /** `undefined` lists all; empty returns `[]` without querying; otherwise `WHERE name IN (...)`. */+ /** `undefined` lists all; empty yields no rows without querying. */names: readonly string[] | undefined;+ limit: number;+ page_token: string | undefined;}export interface CreateMcpServerInput {@@ -85,10 +75,8 @@ export interface AuthorizeMcpServerInput {tenant_id: string;name: string;userRef: string;- /** Relative same-origin path for local DCR pending-auth return. */+ /** Same-origin relative path to land after consent. */returnTo?: string;- /** Absolute redirect URL when a remote auth backend needs a full callback URL. */- redirectURL?: string;}export interface DeleteMcpAuthorizationInput {@@ -99,7 +87,10 @@ export interface DeleteMcpAuthorizationInput {/** Row persistence + DCR client columns — no authorize/status/revoke. */export interface IMcpServerStore<TTransaction = never> extends IOAuthClientStore<TTransaction> {- listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]>;+ listServers(+ input: ListMcpServersInput,+ transaction?: TTransaction,+ ): Promise<{ data: McpServerRecord[]; pagination: TokenPagination }>;getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined>;/*** Load one server while holding a row lock for the lifetime of `transaction`.@@ -116,11 +107,7 @@ export interface IMcpServerStore<TTransaction = never> extends IOAuthClientStoreupsertServer(input: UpsertMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord>;}-/**- * Settings/MCP API store: persistence plus Connect UX auth and invoke headers.- * McpServerWithAuthStore implements via a token store; remote-backed stores may call- * an upstream status/authorize API instead.- */+/** Persistence plus authorize / status / revoke and invoke headers. */export interface IMcpServerWithAuthStore<TTransaction = never> extends IMcpServerStore<TTransaction> {/** Wire `auth_status` for Connect UX, keyed by server name. */resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>>;@@ -131,12 +118,8 @@ export interface IMcpServerWithAuthStore<TTransaction = never> extends IMcpServe/** Revoke this subject's authorization for the named server. */deleteAuthorization(input: DeleteMcpAuthorizationInput): Promise<void>;- /**- * Static HTTP headers for MCP invoke (tools/list, turns).- * Local DCR is handled separately in {@link getMcpConnection}; this covers- * TrueFoundry gateway Bearer, configured header auth, and no-auth (`{}`).- */- resolveInvokeHeaders(record: McpServerRecord): Record<string, string>;+ /** Headers for MCP invoke; may be static or an async resolver that can return `authRequired`. */+ resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders;}/**diff --git a/packages/trueforge/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts b/packages/trueforge/src/db/postgres/mcp-server-store/PostgresMcpServerStore.tsindex 148531257..43680f141 100644--- a/packages/trueforge/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts+++ b/packages/trueforge/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts@@ -1,3 +1,8 @@+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import {+ decodeOffsetPageToken,+ paginateOffsetRows,+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';import type { Kysely, Selectable, Transaction } from 'kysely';import type { OAuthClientRecord } from '../../../mcp/auth/types';import { newId } from '../../../utils/id';@@ -34,17 +39,26 @@ export class PostgresMcpServerStore implements IMcpServerStore<Transaction<Databthis.#db = db;}- async listServers(input: ListMcpServersInput, transaction?: Transaction<Database>): Promise<McpServerRecord[]> {+ async listServers(+ input: ListMcpServersInput,+ transaction?: Transaction<Database>,+ ): Promise<{ data: McpServerRecord[]; pagination: TokenPagination }> {+ const offset = decodeOffsetPageToken(input.page_token);if (input.names?.length === 0) {- return [];+ return paginateOffsetRows([], input.limit, offset);}const db = transaction ?? this.#db;let query = db.selectFrom('mcp_server').selectAll().where('tenant_id', '=', input.tenant_id);if (input.names !== undefined) {query = query.where('name', 'in', [...input.names]);}- const rows = await query.orderBy('name').execute();- return rows.map(toRecord);+ const rows = await query+ .orderBy('name')+ .limit(input.limit + 1)+ .offset(offset)+ .execute();+ const { data, pagination } = paginateOffsetRows(rows, input.limit, offset);+ return { data: data.map(toRecord), pagination };}async getServer(input: GetMcpServerInput, transaction?: Transaction<Database>): Promise<McpServerRecord | undefined> {diff --git a/packages/trueforge/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts b/packages/trueforge/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.tsindex a4e13824c..1829e7e86 100644--- a/packages/trueforge/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts+++ b/packages/trueforge/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts@@ -1,3 +1,8 @@+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import {+ decodeOffsetPageToken,+ paginateOffsetRows,+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';import type { ExpressionBuilder, Kysely, Transaction } from 'kysely';import type { OAuthClientRecord } from '../../../mcp/auth/types';import type { McpServerManifest } from '../../../schemas/mcpServer';@@ -38,16 +43,25 @@ export class SqliteMcpServerStore implements IMcpServerStore<Transaction<Databasthis.#db = db;}- async listServers(input: ListMcpServersInput, transaction?: Transaction<Database>): Promise<McpServerRecord[]> {+ async listServers(+ input: ListMcpServersInput,+ transaction?: Transaction<Database>,+ ): Promise<{ data: McpServerRecord[]; pagination: TokenPagination }> {+ const offset = decodeOffsetPageToken(input.page_token);if (input.names?.length === 0) {- return [];+ return paginateOffsetRows([], input.limit, offset);}const db = transaction ?? this.#db;let query = db.selectFrom('mcp_server').select(recordColumns).where('tenant_id', '=', input.tenant_id);if (input.names !== undefined) {query = query.where('name', 'in', [...input.names]);}- return await query.orderBy('name').execute();+ const rows = await query+ .orderBy('name')+ .limit(input.limit + 1)+ .offset(offset)+ .execute();+ return paginateOffsetRows(rows, input.limit, offset);}async getServer(input: GetMcpServerInput, transaction?: Transaction<Database>): Promise<McpServerRecord | undefined> {diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.tsindex dfafa7719..59c05d10b 100644--- a/packages/trueforge/src/main.ts+++ b/packages/trueforge/src/main.ts@@ -166,10 +166,12 @@ function buildResolveMcpServerStore<TTransaction>(options: {if (!c) {return withAuthPersistence;}+ const requestContext = resolveRequestContext(c);const rawPerServerHeaders = c.req.header(X_TFG_MCP_HEADERS);return new TrueFoundryMcpServerStore<TTransaction>({client,accessToken: requireRequestCredentialToken(c),+ subject: requestContext.subject,perServerHeaders: rawPerServerHeaders ? parsePerServerMcpHeaders(rawPerServerHeaders) : {},});};diff --git a/packages/trueforge/src/routes/mcpServerRoutes.ts b/packages/trueforge/src/routes/mcpServerRoutes.tsindex 8c1488957..bcc486a9a 100644--- a/packages/trueforge/src/routes/mcpServerRoutes.ts+++ b/packages/trueforge/src/routes/mcpServerRoutes.ts@@ -1,9 +1,5 @@-/**- * DB-backed MCP server route definitions.- * Admin routes mount at /api/v1/settings/mcp-servers; the chat list,- * tools, and authorize routes mount at /api/v1/mcp-servers.- */import { createRoute, z } from '@hono/zod-openapi';+import { MCP_SERVERS_PAGE_LIMIT, MCP_SERVERS_PAGE_LIMIT_MAX } from '../schemas/common';import { RequestErrorResponseSchema } from '../schemas/errors';import {CreateMcpServerRequestSchema,@@ -14,21 +10,44 @@ import {UpdateMcpServerRequestSchema,} from '../schemas/mcpServer';import { trueFoundryManagedResponse } from '../truefoundry/trueFoundryManaged';+import { TOKEN_PAGINATION } from './fernExtensions';import { OpenApiTag } from './openapiTags';-/** Chat/composer read view — mounted at /api/v1/mcp-servers (not under settings). */+export const ListMcpServersQuerySchema = z+ .object({+ limit: z.coerce+ .number()+ .int()+ .min(1)+ .max(MCP_SERVERS_PAGE_LIMIT_MAX)+ .optional()+ .default(MCP_SERVERS_PAGE_LIMIT)+ .describe(`Page size. Defaults to ${String(MCP_SERVERS_PAGE_LIMIT)}, max ${String(MCP_SERVERS_PAGE_LIMIT_MAX)}.`),+ page_token: z.string().optional().describe('Opaque token from a previous response `next_page_token`.'),+ })+ .openapi('ListMCPServersQuery');++/** Chat/composer MCP list (not under settings). */export const listAvailableMcpServersRoute = createRoute({method: 'get',path: '/',tags: [OpenApiTag.MCP_SERVERS],summary: 'List MCP servers for chat',- description: 'MCP servers as a slim name/url list for the composer. No auth or auth_status.',+ description: 'Paginated MCP servers as a slim name/url list for the composer.','x-fern-sdk-group-name': ['mcpServers'],'x-fern-sdk-method-name': 'list',+ 'x-fern-pagination': TOKEN_PAGINATION,+ request: {+ query: ListMcpServersQuerySchema,+ },responses: {200: {content: { 'application/json': { schema: ListAvailableMcpServersResponseSchema } },- description: 'All MCP servers (chat projection).',+ description: 'Paginated MCP servers (chat projection).',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid query parameters or page token.',},401: {content: { 'application/json': { schema: RequestErrorResponseSchema } },@@ -42,14 +61,21 @@ export const listMcpServersRoute = createRoute({path: '/',tags: [OpenApiTag.MCP_SERVERS],summary: 'List MCP servers',- description:- 'All MCP servers with nested auth_status (settings / admin projection). Header auth values are redacted.',+ description: 'Paginated MCP servers with auth_status. Header secrets are redacted.','x-fern-sdk-group-name': ['settings', 'mcpServers'],'x-fern-sdk-method-name': 'list',+ 'x-fern-pagination': TOKEN_PAGINATION,+ request: {+ query: ListMcpServersQuerySchema,+ },responses: {200: {content: { 'application/json': { schema: ListMcpServersResponseSchema } },- description: 'All MCP servers',+ description: 'Paginated MCP servers',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid query parameters or page token.',},401: {content: { 'application/json': { schema: RequestErrorResponseSchema } },@@ -72,7 +98,7 @@ export const getMcpServerRoute = createRoute({tags: [OpenApiTag.MCP_SERVERS],summary: 'Get a single MCP server by name',description:- 'A single MCP server by name, with nested auth_status (settings / admin projection). Header auth values are redacted.',+ 'A single MCP server by name, with nested live auth_status (settings / admin projection). Header auth values are redacted.','x-fern-sdk-group-name': ['settings', 'mcpServers'],'x-fern-sdk-method-name': 'get',request: {@@ -204,12 +230,7 @@ export const listMcpServerToolsRoute = createRoute({});const McpAuthorizeQuerySchema = z.object({- return_to: z- .string()- .optional()- .describe(- 'Optional path to return to after OAuth. Must be a same-origin relative path; the OAuth callback redirects here with `isSuccess`/`reason` appended.',- ),+ return_to: z.string().optional().describe('Same-origin path to land in the browser after consent.'),});export const authorizeMcpServerRoute = createRoute({@@ -220,9 +241,7 @@ export const authorizeMcpServerRoute = createRoute({'x-fern-sdk-group-name': ['mcpServers'],'x-fern-sdk-method-name': 'authorize',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.',+ 'Returns current auth status. When OAuth is required, includes an authorization URL. Optional return_to is the post-consent landing path.',request: {params: McpServerNameParamsSchema,query: McpAuthorizeQuerySchema,diff --git a/packages/trueforge/src/runtime/sessionResources.ts b/packages/trueforge/src/runtime/sessionResources.tsindex ac4a8174f..2db4f8ace 100644--- a/packages/trueforge/src/runtime/sessionResources.ts+++ b/packages/trueforge/src/runtime/sessionResources.ts@@ -1,6 +1,3 @@-/**- * Store-backed model/MCP/skill/sandbox resolution for session admit and turns.- */import type { AgentSpec } from '@truefoundry/trueforge-core/agent-session';import {Sandbox,@@ -17,12 +14,10 @@ import { HTTPException } from 'hono/http-exception';import { join } from 'node:path';import type { Logger } from 'winston';import configuration from '../config';-import type { IMcpServerStore, IMcpServerWithAuthStore, McpServerRecord } from '../db/mcpServerStore';+import type { IMcpServerStore, IMcpServerWithAuthStore } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { ISkillStore } from '../db/skillStore';-import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';-import type { IOAuthTokenStore } from '../mcp/auth/types';import { LocalSandboxProvider } from '../sandbox/local/provider/LocalSandboxProvider';import { getCachedLocalSandboxSupport, isLocalSandboxFallbackEnabled } from '../sandbox/localRuntime';import { toDaytonaSandboxProvider } from '../sandbox/providerUtils';@@ -100,79 +95,29 @@ export async function getModelDetails({};}-function dcrHeadersResolver(params: {- record: McpServerRecord;- tokenStore: IOAuthTokenStore;- mcpServerStore: IMcpServerStore;- clientName: string;- userRef: string;-}): RemoteMcpHeaders {- const { record, tokenStore, mcpServerStore, clientName, userRef } = params;- return async () => {- const result = await resolveMcpAuth({- tokenStore,- mcpServerStore,- serverId: record.id,- userRef,- mcpServerUrl: record.manifest.url,- mcpServerName: record.name,- clientName,- });- if (isMcpAuthRequired(result)) {- // Wire `id` must match RemoteMCP.id (AgentSpec name), not the DB row ULID —- // init events, tool-call metadata, and snapshots all key by name.- return {- authRequired: {- servers: [{ id: record.name, name: record.name, auth_url: result.authUrl.href }],- },- };- }- return { headers: result.headers };- };-}-/**- * Load MCP url + headers for a configured server.- * - Local `remote` + `dcr`: resolveMcpAuth via the harness token store.- * - Otherwise: {@link IMcpServerWithAuthStore.resolveInvokeHeaders}- * (TrueFoundry gateway Bearer, configured header auth, or `{}`).- * Returns undefined when the server is not registered — callers choose the response.+ * Load MCP url + headers for a configured server. Returns undefined when unregistered.+ *+ * TODO: OAuth header resolvers re-run on every RemoteMCP listTools/callTool; cache or gate later.*/export async function getMcpConnection({tenant_id,name,store,- tokenStore,- clientName,userRef,}: {tenant_id: string;name: string;store: IMcpServerWithAuthStore;- tokenStore: IOAuthTokenStore;- clientName: string;userRef: string;}): Promise<McpConnection | undefined> {const record = await store.getServer({ tenant_id, name });if (record === undefined) {return undefined;}- // TrueFoundry wire `dcr` is Connect UX only — invoke uses store Bearer, not local DCR.- if (record.manifest.type !== 'truefoundry' && record.manifest.auth?.type === 'dcr') {- return {- url: record.manifest.url,- headers: dcrHeadersResolver({- record,- tokenStore,- mcpServerStore: store,- clientName,- userRef,- }),- };- }return {url: record.manifest.url,- headers: store.resolveInvokeHeaders(record),+ headers: store.resolveInvokeHeaders({ record, userRef }),};}@@ -332,7 +277,14 @@ export async function validateAgentSpec({if (requestedMcpServers.length > 0) {const names = requestedMcpServers.map(server => server.name);const configuredNames = new Set(- (await mcpServerStore.listServers({ tenant_id, names })).map(record => record.name),+ (+ await mcpServerStore.listServers({+ tenant_id,+ names,+ limit: Math.max(names.length, 1),+ page_token: undefined,+ })+ ).data.map(record => record.name),);const unknown = requestedMcpServers.find(server => !configuredNames.has(server.name));if (unknown !== undefined) {diff --git a/packages/trueforge/src/schemas/common.ts b/packages/trueforge/src/schemas/common.tsindex d96e14a65..1772d9737 100644--- a/packages/trueforge/src/schemas/common.ts+++ b/packages/trueforge/src/schemas/common.ts@@ -22,6 +22,10 @@ export type ResourceName = z.infer<typeof NameSchema>;export const PAGE_LIMIT = 25;/** Session/turn event list page size (default = max). */export const EVENTS_PAGE_LIMIT = 100;+/** MCP server list default page size. */+export const MCP_SERVERS_PAGE_LIMIT = 100;+/** MCP server list max page size. */+export const MCP_SERVERS_PAGE_LIMIT_MAX = 200;/** Adds a validation issue if two entries share a name. */export function uniqueNames(entries: { name: string }[], ctx: z.RefinementCtx): void {diff --git a/packages/trueforge/src/schemas/mcpServer.ts b/packages/trueforge/src/schemas/mcpServer.tsindex 37feb0e14..edca4ccc1 100644--- a/packages/trueforge/src/schemas/mcpServer.ts+++ b/packages/trueforge/src/schemas/mcpServer.ts@@ -7,6 +7,7 @@* Turn execution resolves DCR tokens via resolveMcpAuth.*/import { z } from '@hono/zod-openapi';+import { TokenPaginationSchema } from '@truefoundry/trueforge-core/agent-session';import type { OAuthToken } from '../mcp/auth/types';import { NameSchema } from './common';@@ -104,7 +105,10 @@ export const UpdateMcpServerRequestSchema = zexport const GetMcpServerResponseSchema = z.object({ data: ConfiguredMcpServerSchema }).openapi('GetMCPServerResponse');export const ListMcpServersResponseSchema = z- .object({ data: z.array(ConfiguredMcpServerSchema) })+ .object({+ data: z.array(ConfiguredMcpServerSchema),+ pagination: TokenPaginationSchema,+ }).openapi('ListMCPServersResponse');/** Public auth mechanism for chat/composer (no secrets). */@@ -128,7 +132,10 @@ export const AvailableMcpServerSchema = z.openapi('AvailableMCPServer');export const ListAvailableMcpServersResponseSchema = z- .object({ data: z.array(AvailableMcpServerSchema) })+ .object({+ data: z.array(AvailableMcpServerSchema),+ pagination: TokenPaginationSchema,+ }).openapi('ListAvailableMCPServersResponse');export type McpServerType = z.infer<typeof McpServerTypeSchema>;@@ -160,7 +167,7 @@ export function resolveMcpAuthStatus({manifest: McpServerManifest;token?: OAuthToken;}): McpAuthStatus {- // TODO: Replace stub with live ServiceFoundry auth status when Connect /authorize is wired.+ // TrueFoundry list responses treat this as authenticated until live per-item status is requested.if (manifest.type === 'truefoundry') {return { status: 'authenticated' };}diff --git a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.tsindex b4ad236f0..b1404d089 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryMcpServerStore.ts@@ -1,4 +1,13 @@+import type { TokenPagination } from '@truefoundry/trueforge-core/agent-session';+import {+ decodeOffsetPageToken,+ paginateOffsetRows,+} from '@truefoundry/trueforge-core/agent-session/store/OffsetPageToken';+import { McpConnectionError, type RemoteMcpHeaders } from '@truefoundry/trueforge-core/core';import { HTTPException } from 'hono/http-exception';+import type { RequestSubject } from '../auth/identity';+import { safeReturnTo } from '../auth/safeReturnTo';+import { getPublicBaseUrl } from '../config';import {McpServerNotFoundError,type AuthorizeMcpServerInput,@@ -24,6 +33,16 @@ import type { PerServerMcpHeaders } from './perServerMcpHeaders';import { TRUEFOUNDRY_MANAGED_MESSAGE, TRUEFOUNDRY_MANAGED_STATUS } from './trueFoundryManaged';import type { TrueFoundryServiceFoundryServerClient } from './TrueFoundryServiceFoundryServerClient';+export type TrueFoundryMcpApiClient = Pick<+ TrueFoundryServiceFoundryServerClient,+ | 'getMcpServerByName'+ | 'listMcpServers'+ | 'listGatewayInstallations'+ | 'getMcpAuthorize'+ | 'getMcpAuthStatus'+ | 'deleteMcpAuth'+>;+function managed(): never {throw new HTTPException(TRUEFOUNDRY_MANAGED_STATUS, { message: TRUEFOUNDRY_MANAGED_MESSAGE });}@@ -35,50 +54,91 @@ function withoutAuthorization(headers: Record<string, string> | undefined): Recoreturn 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.- * Connect UX auth methods are stubbed for v1 (live SFY authorize is a follow-up).- */+/** Absolute FE landing for the upstream authorize `redirectURL` from `PUBLIC_BASE_URL` + safe `return_to`. */+export function resolveAuthorizeRedirectURL(input: { returnTo?: string }): string {+ try {+ return new URL(safeReturnTo(input.returnTo), `${getPublicBaseUrl()}/`).href;+ } catch (error) {+ throw new McpConnectionError('PUBLIC_BASE_URL is required for TrueFoundry MCP OAuth but was empty', 500, {+ cause: error,+ });+ }+}++/** Read-only MCP registry for TrueFoundry mode (writes managed elsewhere). */export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServerWithAuthStore<TTransaction> {- readonly #client: TrueFoundryServiceFoundryServerClient;+ readonly #client: TrueFoundryMcpApiClient;readonly #accessToken: string;+ readonly #subject: RequestSubject;readonly #perServerHeaders: PerServerMcpHeaders;+ #gatewayUrl: string | undefined;constructor(input: {- client: TrueFoundryServiceFoundryServerClient;+ client: TrueFoundryMcpApiClient;accessToken: string;+ subject: RequestSubject;perServerHeaders?: PerServerMcpHeaders;}) {this.#client = input.client;this.#accessToken = input.accessToken;+ this.#subject = input.subject;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> {- return {+ /** Caller Bearer plus optional per-server overrides; oauth servers re-check auth before invoke. */+ resolveInvokeHeaders(input: { record: McpServerRecord; userRef: string }): RemoteMcpHeaders {+ const { record, userRef } = input;+ const staticHeaders = {...withoutAuthorization(this.#perServerHeaders[record.name]),Authorization: `Bearer ${this.#accessToken}`,};+ if (record.manifest.auth?.type === 'dcr') {+ return async () => {+ const status = await this.authorize({+ tenant_id: record.tenant_id,+ name: record.name,+ userRef,+ });+ if (status.status === 'auth_required') {+ const authUrl = status.authorization_url;+ if (authUrl === undefined || authUrl.length === 0) {+ throw new HTTPException(422, {+ message: `MCP server "${record.name}" requires authentication but returned no authorization URL`,+ });+ }+ return {+ authRequired: {+ servers: [{ id: record.name, name: record.name, auth_url: authUrl }],+ },+ };+ }+ return { headers: staticHeaders };+ };+ }+ return staticHeaders;}- async listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]> {+ async listServers(+ input: ListMcpServersInput,+ transaction?: TTransaction,+ ): Promise<{ data: McpServerRecord[]; pagination: TokenPagination }> {void transaction;+ const offset = decodeOffsetPageToken(input.page_token);if (input.names?.length === 0) {- return [];- }- const records = await this.#records(input.tenant_id);- if (input.names === undefined) {- return records;+ return paginateOffsetRows([], input.limit, offset);}- const wanted = new Set(input.names);- return records.filter(record => wanted.has(record.name));++ const rows = await this.#client.listMcpServers({+ accessToken: this.#accessToken,+ limit: input.limit + 1,+ offset,+ ...(input.names !== undefined ? { names: input.names } : {}),+ });+ const gatewayUrl = await this.#resolveGatewayUrl();+ const records = mapSfyMcpServers({ rows }).map(server =>+ toRecord({ tenant_id: input.tenant_id, server, gatewayUrl }),+ );+ return paginateOffsetRows(records, input.limit, offset);}async getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined> {@@ -88,7 +148,7 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServreturn undefined;}const server = parseSfyMcpServerSummary(row);- const gatewayUrl = resolveDefaultGatewayUrl(await this.#client.listGatewayInstallations(this.#accessToken));+ const gatewayUrl = await this.#resolveGatewayUrl();return toRecord({ tenant_id: input.tenant_id, server, gatewayUrl });}@@ -128,24 +188,48 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServreturn managed();}- resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>> {+ async resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>> {+ void input.userRef;const out = new Map<string, McpAuthStatus>();++ if (input.records.length > 1) {+ for (const record of input.records) {+ out.set(record.name, resolveMcpAuthStatus({ manifest: record.manifest }));+ }+ return out;+ }+for (const record of input.records) {+ if (record.manifest.auth?.type === 'dcr') {+ out.set(+ record.name,+ await this.#client.getMcpAuthStatus({+ accessToken: this.#accessToken,+ mcpServerId: record.id,+ subjectId: this.#subject.id,+ subjectType: this.#subject.type,+ }),+ );+ continue;+ }out.set(record.name, resolveMcpAuthStatus({ manifest: record.manifest }));}- return Promise.resolve(out);+ return 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 });+ return this.#client.getMcpAuthorize({+ accessToken: this.#accessToken,+ mcpServerId: record.id,+ redirectURL: resolveAuthorizeRedirectURL({+ ...(input.returnTo !== undefined ? { returnTo: input.returnTo } : {}),+ }),+ });}async deleteAuthorization(input: DeleteMcpAuthorizationInput): Promise<void> {@@ -154,16 +238,20 @@ export class TrueFoundryMcpServerStore<TTransaction = never> implements IMcpServif (record === undefined) {throw new McpServerNotFoundError(input.name);}- // No local token store for TrueFoundry-managed MCP (v1).+ await this.#client.deleteMcpAuth({+ accessToken: this.#accessToken,+ mcpServerId: record.id,+ subjectId: this.#subject.id,+ subjectType: this.#subject.type,+ authSource: 'oauth',+ });}- 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 }));+ async #resolveGatewayUrl(): Promise<string> {+ if (this.#gatewayUrl === undefined) {+ this.#gatewayUrl = resolveDefaultGatewayUrl(await this.#client.listGatewayInstallations(this.#accessToken));+ }+ return this.#gatewayUrl;}}diff --git a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.tsindex 047aabed6..cacc40992 100644--- a/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts+++ b/packages/trueforge/src/truefoundry/TrueFoundryServiceFoundryServerClient.ts@@ -4,14 +4,15 @@ import { fetch as undiciFetch, type Dispatcher } from 'undici';import type { Logger } from 'winston';import { z } from 'zod';+import type { McpAuthStatus } from '../schemas/mcpServer';import { createInternalTlsDispatcher, normalizeInternalTlsUrl, type InternalTlsOptions } from './internalTls';+import { parseSfyMcpAuthStatus, parseSfyMcpAuthorizeResult, type SfyMcpAuthSource } from './mapSfyMcpServers';const INTEGRATIONS_PATH = 'v1/provider-integrations';const INSTALLATIONS_PATH = 'v1/llm-gateway/installations';const MCP_SERVERS_PATH = 'v1/mcp';const SESSION_PATH = 'v1/session';const INTEGRATIONS_PAGE_SIZE = 1000;-const MCP_SERVERS_PAGE_SIZE = 100;/*** Fields required to build RequestContext from ServiceFoundry `GET /v1/session`.@@ -90,14 +91,15 @@ export class TrueFoundryServiceFoundryServerClient {const items: unknown[] = [];let offset = 0;for (;;) {- const payload = await this.#getJson(- this.#url(INTEGRATIONS_PATH, {+ const payload = await this.#requestJson({+ url: this.#url(INTEGRATIONS_PATH, {type: 'model',offset: String(offset),limit: String(INTEGRATIONS_PAGE_SIZE),}),accessToken,- );+ method: 'GET',+ });const response = this.#parseListResponse(payload);const page = listPage(response);const total = listPaginationTotal(response);@@ -111,50 +113,51 @@ export class TrueFoundryServiceFoundryServerClient {}listGatewayInstallations(accessToken: string): Promise<unknown> {- return this.#getJson(this.#url(INSTALLATIONS_PATH), accessToken);+ return this.#requestJson({+ url: this.#url(INSTALLATIONS_PATH),+ accessToken,+ method: 'GET',+ });}- /**- * 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;+ /** One page of MCP servers; optional `names` filters with `name IN (…)`. */+ async listMcpServers(input: {+ accessToken: string;+ limit: number;+ offset: number;+ names?: readonly string[];+ }): Promise<unknown[]> {+ const query: Record<string, string> = {+ offset: String(input.offset),+ limit: String(input.limit),+ ...(input.names !== undefined+ ? {+ filter: JSON.stringify({+ op: 'and',+ values: [{ field: 'name', op: 'IN', values: [...input.names] }],+ }),+ }+ : {}),+ };+ const payload = await this.#requestJson({+ url: this.#url(MCP_SERVERS_PATH, query),+ accessToken: input.accessToken,+ method: 'GET',+ });+ return listPage(this.#parseListResponse(payload));}- /**- * 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}.- */+ /** Resolve one MCP server by name (`name EQUAL`, limit 1). */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 payload = await this.#requestJson({+ url: this.#url(MCP_SERVERS_PATH, { filter, limit: '1', offset: '0' }),+ accessToken: input.accessToken,+ method: 'GET',+ });const rows = listPage(this.#parseListResponse(payload));if (rows.length > 1) {this.#logger?.warn('TrueFoundry ServiceFoundry MCP name filter returned multiple rows', {@@ -165,6 +168,88 @@ export class TrueFoundryServiceFoundryServerClient {return rows[0];}+ /** Per-subject authorize; includes a consent URL when auth is required. */+ async getMcpAuthorize(input: {+ accessToken: string;+ mcpServerId: string;+ redirectURL?: string;+ gatewayBaseURL?: string;+ }): Promise<McpAuthStatus> {+ const search: Record<string, string> = {};+ if (input.redirectURL !== undefined) {+ search['redirectURL'] = input.redirectURL;+ }+ if (input.gatewayBaseURL !== undefined) {+ search['gatewayBaseURL'] = input.gatewayBaseURL;+ }+ const payload = await this.#requestJson({+ url: this.#url(`${MCP_SERVERS_PATH}/${encodeURIComponent(input.mcpServerId)}/authorize`, search),+ accessToken: input.accessToken,+ method: 'GET',+ });+ try {+ return parseSfyMcpAuthorizeResult(payload);+ } catch (error) {+ this.#logger?.error('TrueFoundry ServiceFoundry MCP authorize returned an unexpected response', {+ mcpServerId: input.mcpServerId,+ ...extractErrorLogFields(error),+ });+ throw new HTTPException(424, {+ message: 'TrueFoundry ServiceFoundry MCP authorize returned an unexpected response',+ cause: error,+ });+ }+ }++ /** Per-subject auth status without seeding a consent URL. */+ async getMcpAuthStatus(input: {+ accessToken: string;+ mcpServerId: string;+ subjectId: string;+ subjectType: string;+ }): Promise<McpAuthStatus> {+ const payload = await this.#requestJson({+ url: this.#url(`${MCP_SERVERS_PATH}/${encodeURIComponent(input.mcpServerId)}/auth/status`, {+ subjectId: input.subjectId,+ subjectType: input.subjectType,+ }),+ accessToken: input.accessToken,+ method: 'GET',+ });+ try {+ return parseSfyMcpAuthStatus(payload);+ } catch (error) {+ this.#logger?.error('TrueFoundry ServiceFoundry MCP auth status returned an unexpected response', {+ mcpServerId: input.mcpServerId,+ ...extractErrorLogFields(error),+ });+ throw new HTTPException(424, {+ message: 'TrueFoundry ServiceFoundry MCP auth status returned an unexpected response',+ cause: error,+ });+ }+ }++ /** Revoke the subject's OAuth token or auth-override. */+ async deleteMcpAuth(input: {+ accessToken: string;+ mcpServerId: string;+ subjectId: string;+ subjectType: string;+ authSource: SfyMcpAuthSource;+ }): Promise<void> {+ await this.#requestJson({+ url: this.#url(`${MCP_SERVERS_PATH}/${encodeURIComponent(input.mcpServerId)}/auth`),+ accessToken: input.accessToken,+ method: 'DELETE',+ body: {+ subjectId: input.subjectId,+ subjectType: input.subjectType,+ authSource: input.authSource,+ },+ });+ }+/*** `GET v1/session` for RequestContext mapping.* `user: null` (invalid/missing auth on a 200) → 401; all other failures → 500.@@ -172,7 +257,11 @@ export class TrueFoundryServiceFoundryServerClient {async getSession(accessToken: string): Promise<GetSessionResponse> {let payload: unknown;try {- payload = await this.#getJson(this.#url(SESSION_PATH), accessToken);+ payload = await this.#requestJson({+ url: this.#url(SESSION_PATH),+ accessToken,+ method: 'GET',+ });} catch (error) {if (error instanceof HTTPException && (error.status === 401 || error.status === 403)) {throw error;@@ -211,7 +300,7 @@ export class TrueFoundryServiceFoundryServerClient {#url(path: string, search?: Record<string, string>): URL {const url = new URL(`${this.#baseUrl}/${path}`);- if (search) {+ if (search !== undefined) {for (const [key, value] of Object.entries(search)) {url.searchParams.set(key, value);}@@ -219,21 +308,34 @@ export class TrueFoundryServiceFoundryServerClient {return url;}- async #getJson(url: URL, accessToken: string): Promise<unknown> {+ async #requestJson(input: {+ url: URL;+ accessToken: string;+ method: 'GET' | 'DELETE' | 'POST' | 'PUT';+ body?: unknown;+ }): Promise<unknown> {const startedAt = Date.now();+ const headers: Record<string, string> = {+ accept: 'application/json',+ authorization: `Bearer ${input.accessToken}`,+ };+ let body: string | undefined;+ if (input.body !== undefined) {+ headers['content-type'] = 'application/json';+ body = JSON.stringify(input.body);+ }let response: Awaited<ReturnType<typeof undiciFetch>>;try {- response = await undiciFetch(url, {- method: 'GET',- headers: {- accept: 'application/json',- authorization: `Bearer ${accessToken}`,- },+ response = await undiciFetch(input.url, {+ method: input.method,+ headers,+ ...(body !== undefined ? { body } : {}),...(this.#dispatcher ? { dispatcher: this.#dispatcher } : {}),});} catch (error) {this.#logger?.warn('TrueFoundry ServiceFoundry server request failed', {- url: url.href,+ url: input.url.href,+ method: input.method,durationMs: Date.now() - startedAt,...extractErrorLogFields(error),});@@ -243,7 +345,8 @@ export class TrueFoundryServiceFoundryServerClient {});}this.#logger?.info('TrueFoundry ServiceFoundry server request completed', {- url: url.href,+ url: input.url.href,+ method: input.method,status: response.status,durationMs: Date.now() - startedAt,});@@ -258,6 +361,24 @@ export class TrueFoundryServiceFoundryServerClient {message: `TrueFoundry ServiceFoundry server request failed: ${detail ?? `HTTP ${String(response.status)}`}`,});}- return response.json();+ if (response.status === 204) {+ return undefined;+ }+ const text = await response.text();+ if (text.length === 0) {+ return undefined;+ }+ try {+ return JSON.parse(text) as unknown;+ } catch (error) {+ this.#logger?.error('TrueFoundry ServiceFoundry server returned non-JSON', {+ url: input.url.href,+ ...extractErrorLogFields(error),+ });+ throw new HTTPException(424, {+ message: 'TrueFoundry ServiceFoundry server returned non-JSON',+ cause: error,+ });+ }}}diff --git a/packages/trueforge/src/truefoundry/mapSfyMcpServers.ts b/packages/trueforge/src/truefoundry/mapSfyMcpServers.tsindex 4cf844474..0464390fc 100644--- a/packages/trueforge/src/truefoundry/mapSfyMcpServers.ts+++ b/packages/trueforge/src/truefoundry/mapSfyMcpServers.ts@@ -1,12 +1,12 @@-/**- * ServiceFoundry MCP list rows → lean summaries (Zod, fail loudly — same pattern as mapEnabledModels).- */import { z } from 'zod';-import type { McpServerManifest } from '../schemas/mcpServer';+import type { McpAuthStatus, McpServerManifest } from '../schemas/mcpServer';-/** Placeholder in SFY `proxyUrl` replaced with the tenant gateway base URL. */+/** Placeholder in upstream `proxyUrl` replaced with the tenant gateway base URL. */export const MCP_PROXY_BASE_URL_TEMPLATE = '{{mcpProxyBaseURL}}';+/** Upstream per-subject auth record kinds for DELETE auth. */+export type SfyMcpAuthSource = 'oauth' | 'auth-override';+const IsoInstantSchema = z.union([z.string().min(1), z.date()]).transform((value, ctx) => {if (value instanceof Date) {if (!Number.isFinite(value.getTime())) {@@ -41,10 +41,29 @@ const SfyMcpServerRowSchema = z.object({.optional(),});+const SfyMcpAuthStatusAuthenticatedSchema = z.object({ status: z.literal('authenticated') });+const SfyMcpAuthStatusNotRequiredSchema = z.object({ status: z.literal('authentication_not_required') });+const SfyMcpAuthStatusRequiredSchema = z.object({ status: z.literal('authentication_required') });+const SfyMcpAuthorizeRequiredSchema = SfyMcpAuthStatusRequiredSchema.extend({+ authorization_endpoint: z.url(),+});++const SfyMcpAuthStatusSchema = z.discriminatedUnion('status', [+ SfyMcpAuthStatusAuthenticatedSchema,+ SfyMcpAuthStatusRequiredSchema,+ SfyMcpAuthStatusNotRequiredSchema,+]);++const SfyMcpAuthorizeResultSchema = z.discriminatedUnion('status', [+ SfyMcpAuthStatusAuthenticatedSchema,+ SfyMcpAuthorizeRequiredSchema,+ SfyMcpAuthStatusNotRequiredSchema,+]);+export interface SfyMcpServerSummary {id: string;name: string;- /** May contain `{{mcpProxyBaseURL}}`; callers must run {@link resolveMcpProxyUrl}. */+ /** May contain `{{mcpProxyBaseURL}}`; resolve with `resolveMcpProxyUrl`. */proxyUrl: string;description: string;authType: string | undefined;@@ -52,14 +71,14 @@ export interface SfyMcpServerSummary {updatedAt: string;}-/** Parse one SFY MCP list row. Throws ZodError on contract drift. */+/** Parse one upstream MCP list row. Throws ZodError on contract drift. */export function parseSfyMcpServerSummary(row: unknown): SfyMcpServerSummary {const parsed = SfyMcpServerRowSchema.parse(row);return {id: parsed.id,name: parsed.name,proxyUrl: parsed.proxyUrl,- // SFY description is optional; TrueForge manifests require a non-empty string.+ // Description is optional upstream; TrueForge manifests require a non-empty string.description: parsed.manifest?.description ?? parsed.name,authType: parsed.manifest?.auth_data?.type,createdAt: parsed.createdAt,@@ -67,12 +86,12 @@ export function parseSfyMcpServerSummary(row: unknown): SfyMcpServerSummary {};}-/** Map SFY MCP list rows; each row must satisfy the schema. */+/** Map upstream 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. */+/** Substitute `{{mcpProxyBaseURL}}` in an upstream 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)) {@@ -81,10 +100,7 @@ export function resolveMcpProxyUrl(input: { proxyUrl: string; gatewayBaseURL: streturn 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 comes from the MCP store's `resolveInvokeHeaders` — not wire `header` auth.- */+/** Map an upstream MCP row to a TrueFoundry wire manifest (`oauth2` → `dcr`). */export function toTrueFoundryMcpManifest(input: {server: SfyMcpServerSummary;gatewayUrl: string;@@ -97,3 +113,30 @@ export function toTrueFoundryMcpManifest(input: {...(input.server.authType === 'oauth2' ? { auth: { type: 'dcr' as const } } : {}),};}++function toHarnessAuthStatus(+ payload: z.infer<typeof SfyMcpAuthStatusSchema> | z.infer<typeof SfyMcpAuthorizeResultSchema>,+): McpAuthStatus {+ switch (payload.status) {+ case 'authenticated':+ return { status: 'authenticated' };+ case 'authentication_not_required':+ return { status: 'not_required' };+ case 'authentication_required': {+ if ('authorization_endpoint' in payload) {+ return { status: 'auth_required', authorization_url: payload.authorization_endpoint };+ }+ return { status: 'auth_required' };+ }+ }+}++/** Parse an upstream MCP auth/status payload. */+export function parseSfyMcpAuthStatus(payload: unknown): McpAuthStatus {+ return toHarnessAuthStatus(SfyMcpAuthStatusSchema.parse(payload));+}++/** Parse an upstream MCP authorize payload (consent URL when auth is required). */+export function parseSfyMcpAuthorizeResult(payload: unknown): McpAuthStatus {+ return toHarnessAuthStatus(SfyMcpAuthorizeResultSchema.parse(payload));+}diff --git a/packages/trueforge/tests/db/mcpServerStoreContractSuite.ts b/packages/trueforge/tests/db/mcpServerStoreContractSuite.tsindex 7d0d28f9f..9435903eb 100644--- a/packages/trueforge/tests/db/mcpServerStoreContractSuite.ts+++ b/packages/trueforge/tests/db/mcpServerStoreContractSuite.ts@@ -95,8 +95,14 @@ export function runMcpServerStoreContractSuite(getStore: () => IMcpServerStore):expect(updated.created_at).toBe(created.created_at);expect(Date.parse(updated.updated_at)).toBeGreaterThanOrEqual(Date.parse(created.updated_at));- const servers = await store.listServers({ tenant_id: TENANT, names: undefined });- expect(servers).toEqual([updated]);+ const servers = await store.listServers({+ tenant_id: TENANT,+ names: undefined,+ limit: 25,+ page_token: undefined,+ });+ expect(servers.data).toEqual([updated]);+ expect(servers.pagination).toEqual({ limit: 25 });});it('listServers returns only the tenant, ordered by name', async () => {@@ -109,9 +115,14 @@ export function runMcpServerStoreContractSuite(getStore: () => IMcpServerStore):});await store.upsertServer({ tenant_id: 'other-tenant', name: 'linear', manifest: manifest() });- const servers = await store.listServers({ tenant_id: TENANT, names: undefined });- expect(servers.map(server => server.name)).toEqual(['deepwiki', 'linear']);- expect(servers.every(server => server.tenant_id === TENANT)).toBe(true);+ const servers = await store.listServers({+ tenant_id: TENANT,+ names: undefined,+ limit: 25,+ page_token: undefined,+ });+ expect(servers.data.map(server => server.name)).toEqual(['deepwiki', 'linear']);+ expect(servers.data.every(server => server.tenant_id === TENANT)).toBe(true);});it('listServers filters by names and returns empty for an empty name list', async () => {@@ -131,12 +142,54 @@ export function runMcpServerStoreContractSuite(getStore: () => IMcpServerStore):const filtered = await store.listServers({tenant_id: TENANT,names: ['notion', 'missing', 'deepwiki'],+ limit: 25,+ page_token: undefined,});- expect(filtered.map(server => server.name)).toEqual(['deepwiki', 'notion']);+ expect(filtered.data.map(server => server.name)).toEqual(['deepwiki', 'notion']);- await expect(store.listServers({ tenant_id: TENANT, names: [] })).resolves.toEqual([]);+ await expect(+ store.listServers({ tenant_id: TENANT, names: [], limit: 25, page_token: undefined }),+ ).resolves.toEqual({ data: [], pagination: { limit: 25 } });});+ it('listServers paginates with limit and page_token', async () => {+ const store = getStore();+ await store.upsertServer({+ tenant_id: TENANT,+ name: 'alpha',+ manifest: manifest({ name: 'alpha', url: 'https://mcp.alpha.example/mcp' }),+ });+ await store.upsertServer({+ tenant_id: TENANT,+ name: 'bravo',+ manifest: manifest({ name: 'bravo', url: 'https://mcp.bravo.example/mcp' }),+ });+ await store.upsertServer({+ tenant_id: TENANT,+ name: 'charlie',+ manifest: manifest({ name: 'charlie', url: 'https://mcp.charlie.example/mcp' }),+ });++ const first = await store.listServers({+ tenant_id: TENANT,+ names: undefined,+ limit: 2,+ page_token: undefined,+ });+ expect(first.data.map(server => server.name)).toEqual(['alpha', 'bravo']);+ expect(first.pagination.limit).toBe(2);+ expect(first.pagination.next_page_token).toBeDefined();++ const second = await store.listServers({+ tenant_id: TENANT,+ names: undefined,+ limit: 2,+ page_token: first.pagination.next_page_token,+ });+ expect(second.data.map(server => server.name)).toEqual(['charlie']);+ expect(second.pagination.next_page_token).toBeUndefined();+ expect(second.pagination.previous_page_token).toBeDefined();+ });it('upsert leaves oauth columns null and does not clear a saved OAuth client', async () => {const store = getStore();const created = await store.upsertServer({diff --git a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.tsindex 66ea90872..fc6971e65 100644--- a/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts+++ b/packages/trueforge/tests/unit/apis/deletedSessionCrud.test.ts@@ -64,7 +64,6 @@ describe('public CRUD after session deletion', () => {activeTurns,resolveModelProviderStore: () => modelProviderStore,resolveMcpServerStore: () => mcpServerStore,- tokenStore,skillStore,agentStore,eventSubscriptions: new EventSubscriptionRegistry(undefined),diff --git a/packages/trueforge/tests/unit/apis/mcpServers.test.ts b/packages/trueforge/tests/unit/apis/mcpServers.test.tsindex 85589316b..ceba2d00f 100644--- a/packages/trueforge/tests/unit/apis/mcpServers.test.ts+++ b/packages/trueforge/tests/unit/apis/mcpServers.test.ts@@ -179,9 +179,65 @@ describe('mcp-servers routers', () => {expect(list.status).toBe(200);expect(await list.json()).toEqual({data: [configured(putBody, 'not_required')],+ pagination: { limit: 100 },});});+ it('GET / settings and chat list honor limit and page_token', async () => {+ await mcpServerStore.upsertServer({+ tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id,+ name: 'page-alpha',+ manifest: {+ type: 'remote',+ name: 'page-alpha',+ url: 'https://mcp.alpha.example/mcp',+ description: 'Page alpha.',+ },+ });+ await mcpServerStore.upsertServer({+ tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id,+ name: 'page-bravo',+ manifest: {+ type: 'remote',+ name: 'page-bravo',+ url: 'https://mcp.bravo.example/mcp',+ description: 'Page bravo.',+ },+ });++ const first = await settingsRouter.request('/?limit=1');+ expect(first.status).toBe(200);+ const firstBody = (await first.json()) as {+ data: { name: string }[];+ pagination: { limit: number; next_page_token?: string };+ };+ expect(firstBody.data).toHaveLength(1);+ expect(firstBody.pagination.limit).toBe(1);+ expect(firstBody.pagination.next_page_token).toBeDefined();++ const second = await settingsRouter.request(+ `/?limit=1&page_token=${encodeURIComponent(firstBody.pagination.next_page_token ?? '')}`,+ );+ expect(second.status).toBe(200);+ const secondBody = (await second.json()) as {+ data: { name: string }[];+ pagination: { limit: number; previous_page_token?: string };+ };+ expect(secondBody.data).toHaveLength(1);+ expect(secondBody.data[0]?.name).not.toBe(firstBody.data[0]?.name);+ expect(secondBody.pagination.previous_page_token).toBeDefined();++ const chatFirst = await mcpServersRouter.request('/?limit=1');+ expect(chatFirst.status).toBe(200);+ const chatBody = (await chatFirst.json()) as {+ data: unknown[];+ pagination: { limit: number; next_page_token?: string };+ };+ expect(chatBody.data).toHaveLength(1);+ expect(chatBody.pagination.limit).toBe(1);+ expect(chatBody.pagination.next_page_token).toBeDefined();+ });+it('POST creates a server and returns 409 on name clash', async () => {const createBody = {type: 'remote' as const,diff --git a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.tsindex 635742a92..1f039fa72 100644--- a/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts+++ b/packages/trueforge/tests/unit/apis/sandboxFileDownload.test.ts@@ -46,7 +46,6 @@ async function buildApp() {tokenStore,clientName: 'test-client',}),- tokenStore,skillStore: new SqliteSkillStore(db),agentStore: new SqliteAgentStore(db),eventSubscriptions: new EventSubscriptionRegistry(undefined),diff --git a/packages/trueforge/tests/unit/apis/schedules.test.ts b/packages/trueforge/tests/unit/apis/schedules.test.tsindex 3d44e81ff..b712ab23c 100644--- a/packages/trueforge/tests/unit/apis/schedules.test.ts+++ b/packages/trueforge/tests/unit/apis/schedules.test.ts@@ -74,7 +74,6 @@ async function setup() {eventSubscriptions: {} as never,modelProviderStore: {} as never,mcpServerStore: {} as never,- tokenStore: {} as never,skillStore: {} as never,agentStore,sandboxProviderStore: {} as never,diff --git a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.tsindex 5f7c6bd6b..aa6aeff59 100644--- a/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts+++ b/packages/trueforge/tests/unit/apis/turnHarnessErrorStatus.test.ts@@ -66,7 +66,6 @@ async function postTurnRejectingWith(error: AgentHarnessError): Promise<ResponsetokenStore,clientName: 'test-client',}),- tokenStore,skillStore: new SqliteSkillStore(db),agentStore: new SqliteAgentStore(db),eventSubscriptions: new EventSubscriptionRegistry(undefined),diff --git a/packages/trueforge/tests/unit/apis/turns.test.ts b/packages/trueforge/tests/unit/apis/turns.test.tsindex fc2bfd620..9e1bddc28 100644--- a/packages/trueforge/tests/unit/apis/turns.test.ts+++ b/packages/trueforge/tests/unit/apis/turns.test.ts@@ -65,7 +65,6 @@ describe('turns', () => {activeTurns: new ActiveTurnRegistry(),resolveModelProviderStore: () => new SqliteModelProviderStore(db),resolveMcpServerStore: () => mcpServerStoreWithAuth(db, tokenStore),- tokenStore,skillStore: new SqliteSkillStore(db),agentStore: new SqliteAgentStore(db),eventSubscriptions: new EventSubscriptionRegistry(undefined),@@ -187,7 +186,6 @@ describe('turns', () => {resolveModelProviderStore: () => modelProviderStore,agentStore: new SqliteAgentStore(db),resolveMcpServerStore: () => mcpServerStoreWithAuth(db, tokenStore),- tokenStore,skillStore: new SqliteSkillStore(db),eventSubscriptions,sandboxProviderStore: new SqliteSandboxProviderStore(db),@@ -289,7 +287,6 @@ describe('turns', () => {activeTurns: new ActiveTurnRegistry(),resolveModelProviderStore: () => modelProviderStore,resolveMcpServerStore: () => mcpServerStoreWithAuth(db, tokenStore),- tokenStore,skillStore: new SqliteSkillStore(db),agentStore: new SqliteAgentStore(db),eventSubscriptions: new EventSubscriptionRegistry(undefined),diff --git a/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts b/packages/trueforge/tests/unit/runtime/getMcpConnection.test.tsindex f9065ad8f..12307fa0f 100644--- a/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts+++ b/packages/trueforge/tests/unit/runtime/getMcpConnection.test.ts@@ -84,8 +84,6 @@ describe('getMcpConnection', () => {tenant_id: 'default',name: 'oauth-mcp',store: mcpServerStore,- tokenStore,- clientName: 'test-client',userRef: STANDALONE_REQUEST_CONTEXT.subject.id,});expect(connection).toBeDefined();@@ -144,8 +142,6 @@ describe('getMcpConnection', () => {tenant_id: 'default',name: 'tokened-mcp',store: mcpServerStore,- tokenStore,- clientName: 'test-client',userRef: STANDALONE_REQUEST_CONTEXT.subject.id,});expect(connection).toBeDefined();@@ -173,8 +169,6 @@ describe('getMcpConnection', () => {tenant_id: 'default',name: 'open-mcp',store: mcpServerStore,- tokenStore,- clientName: 'test-client',userRef: STANDALONE_REQUEST_CONTEXT.subject.id,});expect(connection).toBeDefined();@@ -203,8 +197,6 @@ describe('getMcpConnection', () => {tenant_id: 'default',name: 'header-mcp',store: mcpServerStore,- tokenStore,- clientName: 'test-client',userRef: STANDALONE_REQUEST_CONTEXT.subject.id,});expect(connection).toBeDefined();@@ -216,30 +208,44 @@ describe('getMcpConnection', () => {expect(connection.headers).toEqual({ Authorization: 'Bearer static-token' });});- it('skips local DCR for truefoundry servers even when wire auth is dcr', async () => {- await mcpServerStore.upsertServer({- tenant_id: 'default',- name: 'tfy-mcp',- manifest: {- type: 'truefoundry',+ describe('truefoundry dcr mid-turn', () => {+ it('uses store resolveInvokeHeaders (async authRequired path)', async () => {+ const record = {+ id: 'mcp-id-1',+ tenant_id: 'default',name: 'tfy-mcp',- url: 'https://gateway.example/mcp-server/tfy-mcp',- description: 'TrueFoundry-managed MCP.',- auth: { type: 'dcr' },- },- });+ manifest: {+ type: 'truefoundry' as const,+ name: 'tfy-mcp',+ url: 'https://gateway.example/mcp-server/tfy-mcp',+ description: 'TrueFoundry-managed MCP.',+ auth: { type: 'dcr' as const },+ },+ created_at: '2026-01-15T12:00:00.000Z',+ updated_at: '2026-01-16T12:00:00.000Z',+ };+ const store = Object.create(mcpServerStore) as IMcpServerWithAuthStore;+ store.getServer = async () => record;+ store.resolveInvokeHeaders = () => async () => ({+ authRequired: {+ servers: [{ id: 'tfy-mcp', name: 'tfy-mcp', auth_url: 'https://consent.example/authorize' }],+ },+ });- const connection = await getMcpConnection({- tenant_id: 'default',- name: 'tfy-mcp',- store: mcpServerStore,- tokenStore,- clientName: 'test-client',- userRef: STANDALONE_REQUEST_CONTEXT.subject.id,- });- expect(connection).toEqual({- url: 'https://gateway.example/mcp-server/tfy-mcp',- headers: {},+ const connection = await getMcpConnection({+ tenant_id: 'default',+ name: 'tfy-mcp',+ store,+ userRef: 'user-1',+ });+ if (connection === undefined || typeof connection.headers !== 'function') {+ throw new Error('expected async headers resolver');+ }+ await expect(connection.headers()).resolves.toEqual({+ authRequired: {+ servers: [{ id: 'tfy-mcp', name: 'tfy-mcp', auth_url: 'https://consent.example/authorize' }],+ },+ });});});@@ -249,8 +255,6 @@ describe('getMcpConnection', () => {tenant_id: 'default',name: 'missing-mcp',store: mcpServerStore,- tokenStore,- clientName: 'test-client',userRef: STANDALONE_REQUEST_CONTEXT.subject.id,}),).resolves.toBeUndefined();diff --git a/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.tsnew file mode 100644index 000000000..1cd74887a--- /dev/null+++ b/packages/trueforge/tests/unit/truefoundry/TrueFoundryMcpServerStore.test.ts@@ -0,0 +1,246 @@+import { getPublicBaseUrl } from '../../../src/config';+import { McpServerNotFoundError } from '../../../src/db/mcpServerStore';+import { MCP_PROXY_BASE_URL_TEMPLATE } from '../../../src/truefoundry/mapSfyMcpServers';+import type { TrueFoundryMcpApiClient } from '../../../src/truefoundry/TrueFoundryMcpServerStore';+import {+ resolveAuthorizeRedirectURL,+ TrueFoundryMcpServerStore,+} from '../../../src/truefoundry/TrueFoundryMcpServerStore';++const TENANT = 'default';+const ACCESS_TOKEN = 'caller-access-token';++const SFY_ROW = {+ id: 'mcp-id-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',+ manifest: { description: 'GitHub MCP', auth_data: { type: 'oauth2' } },+};++const GATEWAY_INSTALLATIONS = [{ isDefault: true, manifest: { url: 'https://gateway.example' } }];++type MockClient = {+ [K in keyof TrueFoundryMcpApiClient]: jest.MockedFunction<TrueFoundryMcpApiClient[K]>;+};++function createMockClient(): MockClient {+ return {+ getMcpServerByName: jest.fn(),+ listMcpServers: jest.fn(),+ listGatewayInstallations: jest.fn(),+ getMcpAuthorize: jest.fn(),+ getMcpAuthStatus: jest.fn(),+ deleteMcpAuth: jest.fn(),+ };+}++function createStore(input?: {+ accessToken?: string;+ client?: MockClient;+ subject?: { id: string; type: string; display_name: string };+}) {+ const client = input?.client ?? createMockClient();+ client.getMcpServerByName.mockResolvedValue(SFY_ROW);+ client.listGatewayInstallations.mockResolvedValue(GATEWAY_INSTALLATIONS);+ client.listMcpServers.mockResolvedValue([SFY_ROW]);+ client.getMcpAuthorize.mockResolvedValue({ status: 'authenticated' });+ client.getMcpAuthStatus.mockResolvedValue({ status: 'authenticated' });+ client.deleteMcpAuth.mockResolvedValue(undefined);+ const store = new TrueFoundryMcpServerStore({+ client,+ accessToken: input?.accessToken ?? ACCESS_TOKEN,+ subject: input?.subject ?? { id: 'user-1', type: 'user', display_name: 'user-1' },+ });+ return { store, client };+}++function dcrRecord(overrides: { name?: string } = {}) {+ const name = overrides.name ?? 'github';+ return {+ id: 'mcp-id-1',+ tenant_id: TENANT,+ name,+ manifest: {+ type: 'truefoundry' as const,+ name,+ url: 'https://gateway.example/mcp-server/github',+ description: 'GitHub MCP',+ auth: { type: 'dcr' as const },+ },+ created_at: '2026-01-15T12:00:00.000Z',+ updated_at: '2026-01-16T12:00:00.000Z',+ };+}++describe('resolveAuthorizeRedirectURL', () => {+ it('builds an absolute FE landing from return_to', () => {+ const returnTo = '/?screenType=mcp-auth&pUid=popup-1';+ expect(resolveAuthorizeRedirectURL({ returnTo })).toBe(new URL(returnTo, `${getPublicBaseUrl()}/`).href);+ });+});++describe('TrueFoundryMcpServerStore', () => {+ describe('listServers', () => {+ it('forwards one SFY page with limit+1 and paginates', async () => {+ const { store, client } = createStore();+ const second = { ...SFY_ROW, id: 'mcp-id-2', name: 'linear' };+ client.listMcpServers.mockResolvedValue([SFY_ROW, second]);++ const page = await store.listServers({+ tenant_id: TENANT,+ names: undefined,+ limit: 1,+ page_token: undefined,+ });++ expect(client.listMcpServers).toHaveBeenCalledWith({+ accessToken: ACCESS_TOKEN,+ limit: 2,+ offset: 0,+ });+ expect(page.data.map(server => server.name)).toEqual(['github']);+ expect(page.pagination.next_page_token).toBeDefined();+ expect(client.listGatewayInstallations).toHaveBeenCalledTimes(1);+ });++ it('filters names with one SFY list call (name IN)', async () => {+ const { store, client } = createStore();+ client.listMcpServers.mockResolvedValue([SFY_ROW]);++ const page = await store.listServers({+ tenant_id: TENANT,+ names: ['github', 'missing'],+ limit: 10,+ page_token: undefined,+ });++ expect(client.listMcpServers).toHaveBeenCalledWith({+ accessToken: ACCESS_TOKEN,+ limit: 11,+ offset: 0,+ names: ['github', 'missing'],+ });+ expect(client.getMcpServerByName).not.toHaveBeenCalled();+ expect(page.data.map(server => server.name)).toEqual(['github']);+ });+ });++ describe('authorize', () => {+ it('derives upstream redirectURL from return_to', async () => {+ const { store, client } = createStore();+ const returnTo = '/?screenType=mcp-auth&pUid=popup-1';+ await store.authorize({ tenant_id: TENANT, name: 'github', userRef: 'user-1', returnTo });+ expect(client.getMcpAuthorize).toHaveBeenCalledWith({+ accessToken: ACCESS_TOKEN,+ mcpServerId: 'mcp-id-1',+ redirectURL: resolveAuthorizeRedirectURL({ returnTo }),+ });+ });++ it('throws McpServerNotFoundError when the server is missing', async () => {+ const client = createMockClient();+ client.getMcpServerByName.mockResolvedValue(undefined);+ const store = new TrueFoundryMcpServerStore({+ client,+ accessToken: ACCESS_TOKEN,+ subject: { id: 'user-1', type: 'user', display_name: 'user-1' },+ });+ await expect(store.authorize({ tenant_id: TENANT, name: 'missing', userRef: 'user-1' })).rejects.toBeInstanceOf(+ McpServerNotFoundError,+ );+ });+ });++ describe('deleteAuthorization', () => {+ it('forwards constructor subject to SFY delete', async () => {+ const { store, client } = createStore({+ subject: {+ id: 'va-1:ext:[email protected]',+ type: 'virtualaccount',+ display_name: 'va-1:ext:[email protected]',+ },+ });+ await store.deleteAuthorization({ tenant_id: TENANT, name: 'github', userRef: 'ignored' });+ expect(client.deleteMcpAuth).toHaveBeenCalledWith({+ accessToken: ACCESS_TOKEN,+ mcpServerId: 'mcp-id-1',+ subjectId: 'va-1:ext:[email protected]',+ subjectType: 'virtualaccount',+ authSource: 'oauth',+ });+ });+ });++ describe('resolveAuthStatuses', () => {+ it('skips live status for multi-record lists', async () => {+ const { store, client } = createStore();+ const statuses = await store.resolveAuthStatuses({+ records: [dcrRecord(), dcrRecord({ name: 'slack' })],+ userRef: 'user-1',+ });+ expect(client.getMcpAuthStatus).not.toHaveBeenCalled();+ expect(statuses.get('github')).toEqual({ status: 'authenticated' });+ expect(statuses.get('slack')).toEqual({ status: 'authenticated' });+ });++ it('calls live status for a single record', async () => {+ const { store, client } = createStore();+ client.getMcpAuthStatus.mockResolvedValue({+ status: 'auth_required',+ authorization_url: 'https://consent.example/authorize',+ });+ const statuses = await store.resolveAuthStatuses({+ records: [dcrRecord()],+ userRef: 'user-1',+ });+ expect(client.getMcpAuthStatus).toHaveBeenCalledWith({+ accessToken: ACCESS_TOKEN,+ mcpServerId: 'mcp-id-1',+ subjectId: 'user-1',+ subjectType: 'user',+ });+ expect(statuses.get('github')).toEqual({+ status: 'auth_required',+ authorization_url: 'https://consent.example/authorize',+ });+ });+ });++ describe('resolveInvokeHeaders mid-turn', () => {+ async function invoke(store: TrueFoundryMcpServerStore) {+ const headers = store.resolveInvokeHeaders({ record: dcrRecord(), userRef: 'user-1' });+ if (typeof headers !== 'function') {+ throw new Error('expected async headers resolver for truefoundry+dcr');+ }+ return headers();+ }++ it('returns authRequired when authorize reports auth_required', async () => {+ const { store, client } = createStore();+ client.getMcpAuthorize.mockResolvedValue({+ status: 'auth_required',+ authorization_url: 'https://consent.example/authorize',+ });+ await expect(invoke(store)).resolves.toEqual({+ authRequired: {+ servers: [{ id: 'github', name: 'github', auth_url: 'https://consent.example/authorize' }],+ },+ });+ });++ it('returns gateway Bearer when authorize reports authenticated', async () => {+ const { store } = createStore();+ await expect(invoke(store)).resolves.toEqual({+ headers: { Authorization: `Bearer ${ACCESS_TOKEN}` },+ });+ });++ it('throws 422 when auth_required lacks authorization_url', async () => {+ const { store, client } = createStore();+ client.getMcpAuthorize.mockResolvedValue({ status: 'auth_required' });+ await expect(invoke(store)).rejects.toMatchObject({ status: 422 });+ });+ });+});diff --git a/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.ts b/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.tsindex efde13d77..8f4051fd0 100644--- a/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.ts+++ b/packages/trueforge/tests/unit/truefoundry/mapSfyMcpServers.test.ts@@ -2,6 +2,8 @@ import { ZodError } from 'zod';import {MCP_PROXY_BASE_URL_TEMPLATE,mapSfyMcpServers,+ parseSfyMcpAuthStatus,+ parseSfyMcpAuthorizeResult,parseSfyMcpServerSummary,resolveMcpProxyUrl,toTrueFoundryMcpManifest,@@ -147,3 +149,60 @@ describe('toTrueFoundryMcpManifest', () => {).toBeUndefined();});});++describe('parseSfyMcpAuthStatus', () => {+ it('maps authenticated', () => {+ expect(parseSfyMcpAuthStatus({ status: 'authenticated' })).toEqual({ status: 'authenticated' });+ });++ it('maps authentication_not_required', () => {+ expect(parseSfyMcpAuthStatus({ status: 'authentication_not_required', reason: 'none' })).toEqual({+ status: 'not_required',+ });+ });++ it('maps authentication_required without a consent URL', () => {+ expect(parseSfyMcpAuthStatus({ status: 'authentication_required' })).toEqual({+ status: 'auth_required',+ });+ });++ it('strips authorization_endpoint on status (consent URL is authorize-only)', () => {+ expect(+ parseSfyMcpAuthStatus({+ status: 'authentication_required',+ authorization_endpoint: 'https://gateway.example/authorize',+ }),+ ).toEqual({+ status: 'auth_required',+ });+ });++ it('rejects unknown status', () => {+ expect(() => parseSfyMcpAuthStatus({ status: 'nope' })).toThrow(ZodError);+ });+});++describe('parseSfyMcpAuthorizeResult', () => {+ it('requires authorization_endpoint when authentication_required', () => {+ expect(() => parseSfyMcpAuthorizeResult({ status: 'authentication_required' })).toThrow(ZodError);+ });++ it('maps authentication_required with consent URL', () => {+ expect(+ parseSfyMcpAuthorizeResult({+ status: 'authentication_required',+ authorization_endpoint: 'https://gateway.example/authorize?client_id=1',+ }),+ ).toEqual({+ status: 'auth_required',+ authorization_url: 'https://gateway.example/authorize?client_id=1',+ });+ });++ it('maps authenticated', () => {+ expect(parseSfyMcpAuthorizeResult({ status: 'authenticated', method: 'oauth' })).toEqual({+ status: 'authenticated',+ });+ });+});diff --git a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.tsindex 275806f29..64a9392b9 100644--- a/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts+++ b/packages/trueforge/tests/unit/truefoundry/perServerMcpHeaders.test.ts@@ -3,15 +3,32 @@ 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 record = (name: string): McpServerRecord => ({+ id: name,+ tenant_id: 'default',+ name,+ manifest: {+ type: 'truefoundry',+ name,+ url: `https://gateway.example/mcp-server/${name}`,+ description: name,+ },+ created_at: '2026-01-15T12:00:00.000Z',+ updated_at: '2026-01-16T12:00:00.000Z',+});const storeWith = (perServerHeaders: Record<string, Record<string, string>>): TrueFoundryMcpServerStore =>new TrueFoundryMcpServerStore({client: {} as never,accessToken: 'caller-token',+ subject: { id: 'user-1', type: 'user', display_name: 'user-1' },perServerHeaders,});+function invokeHeaders(store: TrueFoundryMcpServerStore, name: string) {+ return store.resolveInvokeHeaders({ record: record(name), userRef: 'user-1' });+}+describe('parsePerServerMcpHeaders', () => {it('parses a header map per server name', () => {const raw = JSON.stringify({ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' } });@@ -40,15 +57,18 @@ describe('parsePerServerMcpHeaders', () => {describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {it('sends only the gateway Bearer when a server has no override', () => {- expect(storeWith({}).resolveInvokeHeaders(record('tfy-docs-mcp'))).toEqual({+ expect(invokeHeaders(storeWith({}), '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'));+ const headers = invokeHeaders(+ storeWith({+ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },+ }),+ 'tfy-platform-mcp',+ );expect(headers).toEqual({Authorization: 'Bearer caller-token',@@ -57,9 +77,12 @@ describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {});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'));+ const headers = invokeHeaders(+ storeWith({+ 'tfy-platform-mcp': { 'x-tfy-mcp-headers': '{"Authorization":"Bearer user"}' },+ }),+ 'tfy-pylon-mcp',+ );expect(headers).toEqual({ Authorization: 'Bearer caller-token' });});@@ -67,18 +90,24 @@ describe('TrueFoundryMcpServerStore.resolveInvokeHeaders', () => {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'));+ const headers = invokeHeaders(+ storeWith({+ 'tfy-platform-mcp': { [name]: 'Bearer smuggled' },+ }),+ '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'));+ const headers = invokeHeaders(+ storeWith({+ 'tfy-platform-mcp': { authorization: 'Bearer smuggled', 'x-tfy-mcp-headers': '{"a":"b"}' },+ }),+ 'tfy-platform-mcp',+ );expect(headers).toEqual({ Authorization: 'Bearer caller-token', 'x-tfy-mcp-headers': '{"a":"b"}' });});