The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: wire the mcp dcr helper to apis (#36)
Sujai Kumar Guptac367d3e94665
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.jsonindex 459191996..122d0a3fe 100644--- a/fern/openapi/openapi.json+++ b/fern/openapi/openapi.json@@ -1607,23 +1607,17 @@],"type": "object"},- "McpAuthorizeResponse": {+ "McpOAuthCallbackSuccess": {"properties": {- "auth_url": {- "description": "Present only when status is authentication_required.",- "format": "uri",- "type": "string"- },- "status": {+ "success": {"enum": [- "authenticated",- "authentication_required"+ true],- "type": "string"+ "type": "boolean"}},"required": [- "status"+ "success"],"type": "object"},@@ -1667,7 +1661,7 @@"$ref": "#/components/schemas/McpServerAuthSettings"},"auth_status": {- "description": "Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, so an expired-but-refreshable token still reads as `authentication_required` here — call `/authorize` to actually resolve it. `not_required` for servers without `auth` configured.",+ "description": "Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, so an expired-but-refreshable token still reads as `authentication_required` here. `not_required` for servers without `auth` configured.","enum": ["authenticated","authentication_required",@@ -3671,132 +3665,6 @@"x-fern-sdk-method-name": "list"}},- "/api/v1/legacy/mcp-servers/oauth/callback": {- "get": {- "parameters": [- {- "description": "Opaque token; correlates this callback to its pending authorization.",- "in": "query",- "name": "state",- "required": true,- "schema": {- "description": "Opaque token; correlates this callback to its pending authorization.",- "minLength": 1,- "type": "string"- }- },- {- "description": "Authorization code, present when the user granted consent.",- "in": "query",- "name": "code",- "required": false,- "schema": {- "description": "Authorization code, present when the user granted consent.",- "minLength": 1,- "type": "string"- }- },- {- "description": "OAuth error code, present instead of `code` if the user denied consent or the IdP errored.",- "in": "query",- "name": "error",- "required": false,- "schema": {- "description": "OAuth error code, present instead of `code` if the user denied consent or the IdP errored.",- "type": "string"- }- },- {- "in": "query",- "name": "error_description",- "required": false,- "schema": {- "type": "string"- }- }- ],- "responses": {- "302": {- "description": "Redirects to the original `redirect_url` on success, or a failure page if `error` was present."- },- "400": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "Unknown or expired `state` (no matching pending authorization), or `code`/`error` both missing."- }- },- "summary": "OAuth callback for MCP authorization",- "tags": [- "Legacy MCP OAuth"- ],- "x-fern-ignore": true- }- },- "/api/v1/legacy/mcp-servers/{name}/authorize": {- "get": {- "description": "Registers a DCR client for this server if none exists yet, then returns an authorization URL to redirect the user to so they can complete the OAuth consent flow. Short-circuits to `{status: authenticated}` with no URL if the server is already connected.",- "parameters": [- {- "description": "MCP server name from mcp.yaml.",- "in": "path",- "name": "name",- "required": true,- "schema": {- "description": "MCP server name from mcp.yaml.",- "minLength": 1,- "type": "string"- }- },- {- "description": "Where to send the browser after OAuth completes.",- "in": "query",- "name": "redirect_url",- "required": true,- "schema": {- "description": "Where to send the browser after OAuth completes.",- "format": "uri",- "type": "string"- }- }- ],- "responses": {- "200": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/McpAuthorizeResponse"- }- }- },- "description": "Either already authenticated, or an authorization URL to redirect to."- },- "404": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/RequestErrorResponse"- }- }- },- "description": "MCP server not found."- }- },- "summary": "Start (or short-circuit) the auth flow for an MCP server",- "tags": [- "Legacy MCP Servers"- ],- "x-fern-sdk-group-name": [- "legacy",- "mcp_servers"- ],- "x-fern-sdk-method-name": "authorize"- }- },"/api/v1/legacy/mcp-servers/{name}/tools": {"get": {"description": "All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.",@@ -3943,6 +3811,89 @@"x-fern-sdk-method-name": "list"}},+ "/api/v1/mcp-servers/oauth/callback": {+ "get": {+ "parameters": [+ {+ "description": "Opaque token; correlates this callback to its pending authorization.",+ "in": "query",+ "name": "state",+ "required": true,+ "schema": {+ "description": "Opaque token; correlates this callback to its pending authorization.",+ "minLength": 1,+ "type": "string"+ }+ },+ {+ "description": "Authorization code, present when the user granted consent.",+ "in": "query",+ "name": "code",+ "required": false,+ "schema": {+ "description": "Authorization code, present when the user granted consent.",+ "minLength": 1,+ "type": "string"+ }+ },+ {+ "description": "OAuth error code, present instead of `code` if the user denied consent or the IdP errored.",+ "in": "query",+ "name": "error",+ "required": false,+ "schema": {+ "description": "OAuth error code, present instead of `code` if the user denied consent or the IdP errored.",+ "type": "string"+ }+ },+ {+ "in": "query",+ "name": "error_description",+ "required": false,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/McpOAuthCallbackSuccess"+ }+ }+ },+ "description": "Token exchanged successfully; no browser redirect."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "IdP `error`, unknown/expired `state`, token exchange failure, or `code`/`error` both missing."+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Unexpected failure during token exchange."+ }+ },+ "summary": "OAuth callback for MCP authorization",+ "tags": [+ "MCP OAuth"+ ],+ "x-fern-ignore": true+ }+ },"/api/v1/models": {"get": {"description": "Models across all configured model providers, addressed by fully qualified name `name/model_name`.",@@ -4968,7 +4919,7 @@},"/api/v1/settings/mcp-servers/{name}/authorize": {"get": {- "description": "Stub: returns authenticated when the server has no auth or header credentials on the row; auth_required with a placeholder authorization URL when auth.type is dcr. Real DCR lands in a follow-up.",+ "description": "For servers without auth or with header credentials, returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).","parameters": [{"description": "Configured MCP server name.",@@ -4982,12 +4933,12 @@}},{- "description": "Where to send the browser after OAuth completes.",+ "description": "Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet).","in": "query","name": "redirect_url",- "required": true,+ "required": false,"schema": {- "description": "Where to send the browser after OAuth completes.",+ "description": "Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet).","format": "uri","type": "string"}@@ -5004,6 +4955,16 @@},"description": "Either already authenticated, or an authorization URL to redirect to."},+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "DCR or authorize URL construction failed (e.g. server lacks registration_endpoint)."+ },"404": {"content": {"application/json": {@@ -5013,6 +4974,16 @@}},"description": "MCP server not found."+ },+ "500": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Server misconfiguration (e.g. PUBLIC_BASE_URL unset)."}},"summary": "Start (or short-circuit) the auth flow for a configured MCP server",diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsindex 6455664dc..a916baccf 100644--- a/packages/harness/src/core/index.ts+++ b/packages/harness/src/core/index.ts@@ -160,6 +160,7 @@ export {mcpClientInformation,mcpOAuthCallbackUrl,resolveMcpAuth,+ validateRedirectUris,} from './mcp/auth';export type {CompleteMcpAuthorizationResult,diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.tsindex 44e93e908..9e176dfcb 100644--- a/packages/harness/src/core/mcp/auth/index.ts+++ b/packages/harness/src/core/mcp/auth/index.ts@@ -20,3 +20,4 @@ export {mcpClientInformation,mcpOAuthCallbackUrl,} from './mcpOAuthHelpers';+export { validateRedirectUris } from './redirectUri';diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/harness/src/core/mcp/auth/mcpDcr.tsindex 94c345c5d..6ce31ab05 100644--- a/packages/harness/src/core/mcp/auth/mcpDcr.ts+++ b/packages/harness/src/core/mcp/auth/mcpDcr.ts@@ -5,7 +5,7 @@ import {registerClient,startAuthorization,} from '@modelcontextprotocol/sdk/client/auth.js';-import { InvalidClientError } from '@modelcontextprotocol/sdk/server/auth/errors.js';+import { InvalidClientError, InvalidClientMetadataError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';import type {AuthorizationServerMetadata,@@ -51,9 +51,8 @@ export interface CompleteMcpAuthorizationResult {export const DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS = 3600;/**- * Prefer `client_secret_post` (confidential). Authorization servers that only issue public- * clients or only accept other methods can reject that; retry once without the field (same as- * servicefoundry outbound DCR), then surface. Not a loop.+ * Prefer `client_secret_post` (confidential). Retry without the field only when the AS rejects+ * that metadata (`invalid_client_metadata`); other failures (network, 5xx, etc.) surface as-is.*/async function registerMcpClientWithAuthMethodFallback(params: {authorizationServerUrl: string;@@ -73,8 +72,15 @@ async function registerMcpClientWithAuthMethodFallback(params: {clientMetadata: { ...clientMetadata, token_endpoint_auth_method: 'client_secret_post' },});} catch (firstError: unknown) {+ if (!(firstError instanceof InvalidClientMetadataError)) {+ throw new McpConnectionError(+ `Failed to dynamically register OAuth client for MCP server '${mcpServerName}'`,+ 400,+ { cause: firstError instanceof Error ? firstError : undefined },+ );+ }try {- // Omit method so the authorization server applies its default (parity with servicefoundry).+ // Omit method so the authorization server applies its default.fullInfo = await registerClient(authorizationServerUrl, {metadata,clientMetadata,@@ -132,6 +138,16 @@ export async function createMcpOAuthClient(params: {);}+ // Only reject when the AS explicitly advertises PKCE methods that omit S256.+ // Missing/omitted advertisement → still try S256 (many servers support it but do not publish).+ const pkceMethods = metadata.code_challenge_methods_supported;+ if (pkceMethods && !pkceMethods.includes('S256')) {+ throw new McpConnectionError(+ `Authorization server for MCP server '${mcpServerName}' advertises PKCE methods without S256`,+ 400,+ );+ }+return registerMcpClientWithAuthMethodFallback({authorizationServerUrl,metadata,@@ -188,24 +204,26 @@ export async function buildMcpAuthorizationUrl(params: {clientName: params.clientName,});- if (client.server.codeChallengeMethodsSupported?.includes('S256') !== true) {- throw new McpConnectionError(- `Authorization server for MCP server '${params.mcpServerName}' does not advertise PKCE S256; S256 is required`,- 400,- );- }-const state = randomBytes(32).toString('base64url');const redirectUri = mcpOAuthCallbackUrl();const resource = resourceUrlFromServerUrl(params.mcpServerUrl);- const started = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {- metadata: mcpAuthorizationServerMetadata(client.server),- clientInformation: mcpClientInformation(client.client),- redirectUrl: redirectUri,- resource,- state,- });+ // MCP SDK always sends PKCE S256; it only rejects when metadata lists methods that omit S256.+ // When we stored null (AS did not advertise), reconstructed metadata omits the field → try S256.+ let started: Awaited<ReturnType<typeof startAuthorization>>;+ try {+ started = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {+ metadata: mcpAuthorizationServerMetadata(client.server),+ clientInformation: mcpClientInformation(client.client),+ redirectUrl: redirectUri,+ resource,+ state,+ });+ } catch (error: unknown) {+ throw new McpConnectionError(`Failed to start OAuth authorization for MCP server '${params.mcpServerName}'`, 400, {+ cause: error instanceof Error ? error : undefined,+ });+ }await params.tokenStore.savePendingAuthorization({state,@@ -265,11 +283,13 @@ export async function resolveMcpAuth(params: {await params.tokenStore.saveToken({ id: params.serverId, token: saved });return { headers: { Authorization: `Bearer ${saved.accessToken}` } };} catch {- // Any refresh failure → full re-authorize (do not inspect the error).+ // Refresh failed → drop the unusable token and fall through to full re-authorize.}}}+ // Only reached when there is no usable/refreshable token. Clear the stale row before re-auth+ // (successful refresh returns above and never deletes).if (token) {await params.tokenStore.deleteToken({ id: params.serverId });}diff --git a/packages/harness/src/core/mcp/auth/redirectUri.ts b/packages/harness/src/core/mcp/auth/redirectUri.tsnew file mode 100644index 000000000..2c5fe7896--- /dev/null+++ b/packages/harness/src/core/mcp/auth/redirectUri.ts@@ -0,0 +1,19 @@+/**+ * Shape/scheme checks for redirect URLs (http/https only).+ */+import { McpConnectionError } from '../../errors';++/** Validates redirect URLs parse as http(s). */+export function validateRedirectUris({ redirectUris }: { redirectUris: string[] }): void {+ for (const redirectUri of redirectUris) {+ let parsed: URL;+ try {+ parsed = new URL(redirectUri);+ } catch {+ throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);+ }+ }+}diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.tsindex 84bd7df5f..281520626 100644--- a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts+++ b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts@@ -76,7 +76,10 @@ const AS_METADATA = {function stubOauthFetch(options: {registrationFailFirst?: boolean;registrationFailAlways?: boolean;+ /** Non-OAuth registration failure (e.g. 500) — must not trigger auth-method fallback. */+ registrationHttpError?: { status: number; body?: string };skipRegistrationEndpoint?: boolean;+ codeChallengeMethodsSupported?: string[] | null;registeredClient?: { client_id: string; client_secret?: string; token_endpoint_auth_method?: string };tokenResponse?: { access_token: string; refresh_token?: string; expires_in?: number; token_type?: string };tokenFail?: boolean;@@ -104,15 +107,26 @@ function stubOauthFetch(options: {}if (url.includes('oauth-authorization-server') || url.includes('openid-configuration')) {- const metadata = options.skipRegistrationEndpoint- ? Object.fromEntries(Object.entries(AS_METADATA).filter(([k]) => k !== 'registration_endpoint'))- : AS_METADATA;+ const metadata: Record<string, unknown> = { ...AS_METADATA };+ if (options.skipRegistrationEndpoint) {+ delete metadata['registration_endpoint'];+ }+ if (options.codeChallengeMethodsSupported === null) {+ delete metadata['code_challenge_methods_supported'];+ } else if (options.codeChallengeMethodsSupported !== undefined) {+ metadata['code_challenge_methods_supported'] = options.codeChallengeMethodsSupported;+ }return json(metadata);}if (url === `${AS_ORIGIN}/register` && init?.method === 'POST') {registerCalls += 1;registerBodies.push(JSON.parse(String(init.body)));+ if (options.registrationHttpError) {+ return new Response(options.registrationHttpError.body ?? 'server error', {+ status: options.registrationHttpError.status,+ });+ }if (options.registrationFailAlways || (options.registrationFailFirst && registerCalls === 1)) {return json({ error: 'invalid_client_metadata' }, 400);}@@ -209,7 +223,7 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {expect(body['redirect_uris']).toEqual([mcpOAuthCallbackUrl()]);});- it('retries registration without token_endpoint_auth_method when the first attempt fails', async () => {+ it('retries registration without token_endpoint_auth_method on invalid_client_metadata', async () => {const { mcpServerStore } = newStores();const { registerBodies, registerCallCount } = stubOauthFetch({registrationFailFirst: true,@@ -231,6 +245,24 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {expect((registerBodies[1] as Record<string, unknown>)['token_endpoint_auth_method']).toBeUndefined();});+ it('does not retry registration on non-metadata failures', async () => {+ const { mcpServerStore } = newStores();+ const { registerCallCount } = stubOauthFetch({+ registrationHttpError: { status: 500, body: 'boom' },+ });++ await expect(+ ensureMcpClientRegistered({+ mcpServerStore,+ serverId: SERVER_ID,+ mcpServerUrl: SERVER_URL,+ mcpServerName: SERVER_NAME,+ clientName: CLIENT_NAME,+ }),+ ).rejects.toBeInstanceOf(McpConnectionError);+ expect(registerCallCount()).toBe(1);+ });+it('throws when the AS has no registration_endpoint', async () => {const { mcpServerStore } = newStores();stubOauthFetch({ skipRegistrationEndpoint: true });@@ -315,7 +347,7 @@ describe('buildMcpAuthorizationUrl', () => {expect(pending?.codeVerifier).toBeTruthy();});- it('throws when the AS does not advertise S256', async () => {+ it('still uses PKCE S256 when the AS does not advertise code_challenge_methods', async () => {const { tokenStore, mcpServerStore } = newStores();await mcpServerStore.saveClient({id: SERVER_ID,@@ -325,22 +357,36 @@ describe('buildMcpAuthorizationUrl', () => {},});+ const authUrl = await buildMcpAuthorizationUrl({+ tokenStore,+ mcpServerStore,+ serverId: SERVER_ID,+ mcpServerUrl: SERVER_URL,+ mcpServerName: SERVER_NAME,+ clientName: CLIENT_NAME,+ });++ expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');+ expect(authUrl.searchParams.get('code_challenge')).toBeTruthy();+ });++ it('rejects at registration when the AS advertises PKCE methods without S256', async () => {+ stubOauthFetch({ codeChallengeMethodsSupported: ['plain'] });+await expect(- buildMcpAuthorizationUrl({- tokenStore,- mcpServerStore,- serverId: SERVER_ID,+ createMcpOAuthClient({mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,+ redirectUri: mcpOAuthCallbackUrl(),clientName: CLIENT_NAME,}),).rejects.toMatchObject({name: 'McpConnectionError',- message: expect.stringContaining('PKCE S256'),+ message: expect.stringContaining('without S256'),});});- it('throws when only non-S256 methods are advertised', async () => {+ it('throws when stored client metadata lists only non-S256 methods', async () => {const { tokenStore, mcpServerStore } = newStores();await mcpServerStore.saveClient({id: SERVER_ID,@@ -361,7 +407,7 @@ describe('buildMcpAuthorizationUrl', () => {}),).rejects.toMatchObject({name: 'McpConnectionError',- message: expect.stringContaining('PKCE S256'),+ message: expect.stringContaining('Failed to start OAuth authorization'),});});});diff --git a/packages/harness/tests/core/mcp/auth/redirectUri.test.ts b/packages/harness/tests/core/mcp/auth/redirectUri.test.tsnew file mode 100644index 000000000..03b7cb655--- /dev/null+++ b/packages/harness/tests/core/mcp/auth/redirectUri.test.ts@@ -0,0 +1,28 @@+import { McpConnectionError } from '../../../../src/core/errors';+import { validateRedirectUris } from '../../../../src/core/mcp/auth/redirectUri';++describe('validateRedirectUris', () => {+ it('accepts http(s) URLs', () => {+ expect(() =>+ validateRedirectUris({+ redirectUris: ['https://harness.example.com/settings', 'http://localhost:3000/cb'],+ }),+ ).not.toThrow();+ });++ it('rejects non-http(s) URIs', () => {+ expect(() =>+ validateRedirectUris({+ redirectUris: ['javascript:alert(1)'],+ }),+ ).toThrow(/Must be a valid URL/);+ });++ it('rejects malformed URIs', () => {+ expect(() =>+ validateRedirectUris({+ redirectUris: ['not-a-url'],+ }),+ ).toThrow(McpConnectionError);+ });+});diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.jsonindex 98f46d1b5..6a109de55 100644--- a/packages/sdk/.fern/metadata.json+++ b/packages/sdk/.fern/metadata.json@@ -26,9 +26,10 @@"streamType": "web","useDefaultRequestParameterValues": true},- "originGitCommit": "8937bc865fb2ba0ef37d2fc6e7dcf1676058abfa",+ "originGitCommit": "dfb013c3f50f4f86afdb1d8910c410516e907cc6","originGitCommitIsDirty": true,- "invokedBy": "manual",+ "invokedBy": "ci","requestedVersion": "0.0.0",+ "ciProvider": "github","sdkVersion": "0.0.0"}diff --git a/packages/sdk/reference.md b/packages/sdk/reference.mdindex f3fd7bb79..6e16dd24d 100644--- a/packages/sdk/reference.md+++ b/packages/sdk/reference.md@@ -1186,79 +1186,6 @@ await client.legacy.mcpServers.list();</dl>-</dd>-</dl>-</details>--<details><summary><code>client.legacy.mcpServers.<a href="/src/api/resources/legacy/resources/mcpServers/client/Client.ts">authorize</a>(name, { ...params }) -> TrueHarness.McpAuthorizeResponse</code></summary>-<dl>-<dd>--#### 📝 Description--<dl>-<dd>--<dl>-<dd>--Registers a DCR client for this server if none exists yet, then returns an authorization URL to redirect the user to so they can complete the OAuth consent flow. Short-circuits to `{status: authenticated}` with no URL if the server is already connected.-</dd>-</dl>-</dd>-</dl>--#### 🔌 Usage--<dl>-<dd>--<dl>-<dd>--```typescript-await client.legacy.mcpServers.authorize("name", {- redirectUrl: "redirect_url"-});--```-</dd>-</dl>-</dd>-</dl>--#### ⚙️ Parameters--<dl>-<dd>--<dl>-<dd>--**name:** `string` — MCP server name from mcp.yaml.--</dd>-</dl>--<dl>-<dd>--**request:** `TrueHarness.legacy.AuthorizeMcpServersRequest`--</dd>-</dl>--<dl>-<dd>--**requestOptions:** `McpServersClient.RequestOptions`--</dd>-</dl>-</dd>-</dl>--</dd></dl></details>@@ -1627,7 +1554,7 @@ await client.settings.mcpServers.catalog();<dl><dd>-Stub: returns authenticated when the server has no auth or header credentials on the row; auth_required with a placeholder authorization URL when auth.type is dcr. Real DCR lands in a follow-up.+For servers without auth or with header credentials, returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).</dd></dl></dd>@@ -1642,9 +1569,7 @@ Stub: returns authenticated when the server has no auth or header credentials on<dd>```typescript-await client.settings.mcpServers.authorize("name", {- redirectUrl: "redirect_url"-});+await client.settings.mcpServers.authorize("name");```</dd>diff --git a/packages/sdk/src/api/errors/InternalServerError.ts b/packages/sdk/src/api/errors/InternalServerError.tsnew file mode 100644index 000000000..09ae3b71b--- /dev/null+++ b/packages/sdk/src/api/errors/InternalServerError.ts@@ -0,0 +1,24 @@+// This file was auto-generated by Fern from our API Definition.++import type * as core from "../../core/index.js";+import * as errors from "../../errors/index.js";+import type * as TrueHarness from "../index.js";++export class InternalServerError extends errors.TrueHarnessError {+ public declare readonly body: TrueHarness.RequestErrorResponse;++ constructor(body: TrueHarness.RequestErrorResponse, rawResponse?: core.RawResponse) {+ super({+ message: "InternalServerError",+ statusCode: 500,+ body: body,+ rawResponse: rawResponse,+ });+ Object.setPrototypeOf(this, new.target.prototype);+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, this.constructor);+ }++ this.name = "InternalServerError";+ }+}diff --git a/packages/sdk/src/api/errors/index.ts b/packages/sdk/src/api/errors/index.tsindex 925fe86d6..5d65048fb 100644--- a/packages/sdk/src/api/errors/index.ts+++ b/packages/sdk/src/api/errors/index.ts@@ -1,5 +1,6 @@export * from "./BadGatewayError.js";export * from "./BadRequestError.js";+export * from "./InternalServerError.js";export * from "./NotFoundError.js";export * from "./PreconditionFailedError.js";export * from "./UnauthorizedError.js";diff --git a/packages/sdk/src/api/resources/legacy/resources/index.ts b/packages/sdk/src/api/resources/legacy/resources/index.tsindex 280dc2e8c..8b6053ca7 100644--- a/packages/sdk/src/api/resources/legacy/resources/index.ts+++ b/packages/sdk/src/api/resources/legacy/resources/index.ts@@ -1,4 +1,3 @@-export * from "./mcpServers/client/requests/index.js";export * as mcpServers from "./mcpServers/index.js";export * as models from "./models/index.js";export * as server from "./server/index.js";diff --git a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/Client.tsindex a3a139f0d..69973d07e 100644--- a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/Client.ts+++ b/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/Client.ts@@ -82,102 +82,6 @@ export class McpServersClient {return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/legacy/mcp-servers");}- /**- * Registers a DCR client for this server if none exists yet, then returns an authorization URL to redirect the user to so they can complete the OAuth consent flow. Short-circuits to `{status: authenticated}` with no URL if the server is already connected.- *- * @param {string} name - MCP server name from mcp.yaml.- * @param {TrueHarness.legacy.AuthorizeMcpServersRequest} request- * @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.- *- * @throws {@link TrueHarness.NotFoundError}- * @throws {@link errors.TrueHarnessError}- * @throws {@link errors.TrueHarnessTimeoutError}- *- * @example- * await client.legacy.mcpServers.authorize("name", {- * redirectUrl: "redirect_url"- * })- */- public authorize(- name: string,- request: TrueHarness.legacy.AuthorizeMcpServersRequest,- requestOptions?: McpServersClient.RequestOptions,- ): core.HttpResponsePromise<TrueHarness.McpAuthorizeResponse> {- return core.HttpResponsePromise.fromPromise(this.__authorize(name, request, requestOptions));- }-- private async __authorize(- name: string,- request: TrueHarness.legacy.AuthorizeMcpServersRequest,- requestOptions?: McpServersClient.RequestOptions,- ): Promise<core.WithRawResponse<TrueHarness.McpAuthorizeResponse>> {- const { redirectUrl } = request;- const _queryParams: Record<string, unknown> = {- redirect_url: redirectUrl,- };- const _headers: core.Fetcher.Args["headers"] = mergeHeaders(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/legacy/mcp-servers/${core.url.encodePathParam(name)}/authorize`,- ),- 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.McpAuthorizeResponse.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 404:- throw new TrueHarness.NotFoundError(- serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {- unrecognizedObjectKeys: "passthrough",- allowUnrecognizedUnionMembers: true,- allowUnrecognizedEnumValues: true,- skipValidation: true,- breadcrumbsPrefix: ["response"],- }),- _response.rawResponse,- );- default:- throw new errors.TrueHarnessError({- statusCode: _response.error.statusCode,- body: _response.error.body,- rawResponse: _response.rawResponse,- });- }- }-- return handleNonStatusCodeError(- _response.error,- _response.rawResponse,- "GET",- "/api/v1/legacy/mcp-servers/{name}/authorize",- );- }-/*** All tools exposed by the given MCP server (non-paginated), as returned by the MCP `tools/list` call. No agent-spec tool selectors are applied — this is the raw server catalog.*diff --git a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/index.ts b/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/index.tsindex 195f9aa8a..cb0ff5c3b 100644--- a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/index.ts+++ b/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/index.ts@@ -1 +1 @@-export * from "./requests/index.js";+export {};diff --git a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts b/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.tsdeleted file mode 100644index ef097a479..000000000--- a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts+++ /dev/null@@ -1,12 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--/**- * @example- * {- * redirectUrl: "redirect_url"- * }- */-export interface AuthorizeMcpServersRequest {- /** Where to send the browser after OAuth completes. */- redirectUrl: string;-}diff --git a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/requests/index.ts b/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/requests/index.tsdeleted file mode 100644index 9f3c48ef4..000000000--- a/packages/sdk/src/api/resources/legacy/resources/mcpServers/client/requests/index.ts+++ /dev/null@@ -1 +0,0 @@-export type { AuthorizeMcpServersRequest } from "./AuthorizeMcpServersRequest.js";diff --git a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.tsindex a8fffde58..302f3125f 100644--- a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts+++ b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/Client.ts@@ -244,24 +244,24 @@ export class McpServersClient {}/**- * Stub: returns authenticated when the server has no auth or header credentials on the row; auth_required with a placeholder authorization URL when auth.type is dcr. Real DCR lands in a follow-up.+ * For servers without auth or with header credentials, returns authenticated (no browser flow). For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise runs DCR if needed and returns auth_required with an authorization URL. Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).** @param {string} name - Configured MCP server name.* @param {TrueHarness.settings.AuthorizeMcpServersRequest} request* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.*+ * @throws {@link TrueHarness.BadRequestError}* @throws {@link TrueHarness.NotFoundError}+ * @throws {@link TrueHarness.InternalServerError}* @throws {@link errors.TrueHarnessError}* @throws {@link errors.TrueHarnessTimeoutError}** @example- * await client.settings.mcpServers.authorize("name", {- * redirectUrl: "redirect_url"- * })+ * await client.settings.mcpServers.authorize("name")*/public authorize(name: string,- request: TrueHarness.settings.AuthorizeMcpServersRequest,+ request: TrueHarness.settings.AuthorizeMcpServersRequest = {},requestOptions?: McpServersClient.RequestOptions,): core.HttpResponsePromise<TrueHarness.ConfiguredMcpAuthorizeResponse> {return core.HttpResponsePromise.fromPromise(this.__authorize(name, request, requestOptions));@@ -269,7 +269,7 @@ export class McpServersClient {private async __authorize(name: string,- request: TrueHarness.settings.AuthorizeMcpServersRequest,+ request: TrueHarness.settings.AuthorizeMcpServersRequest = {},requestOptions?: McpServersClient.RequestOptions,): Promise<core.WithRawResponse<TrueHarness.ConfiguredMcpAuthorizeResponse>> {const { redirectUrl } = request;@@ -311,6 +311,17 @@ export class McpServersClient {if (_response.error.reason === "status-code") {switch (_response.error.statusCode) {+ case 400:+ throw new TrueHarness.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );case 404:throw new TrueHarness.NotFoundError(serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {@@ -322,6 +333,17 @@ export class McpServersClient {}),_response.rawResponse,);+ case 500:+ throw new TrueHarness.InternalServerError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );default:throw new errors.TrueHarnessError({statusCode: _response.error.statusCode,diff --git a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.tsindex ef097a479..417ced069 100644--- a/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts+++ b/packages/sdk/src/api/resources/settings/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts@@ -2,11 +2,9 @@/*** @example- * {- * redirectUrl: "redirect_url"- * }+ * {}*/export interface AuthorizeMcpServersRequest {- /** Where to send the browser after OAuth completes. */- redirectUrl: string;+ /** Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet). */+ redirectUrl?: string;}diff --git a/packages/sdk/src/api/types/McpAuthorizeResponse.ts b/packages/sdk/src/api/types/McpAuthorizeResponse.tsdeleted file mode 100644index 21acd88d4..000000000--- a/packages/sdk/src/api/types/McpAuthorizeResponse.ts+++ /dev/null@@ -1,9 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--import type * as TrueHarness from "../index.js";--export interface McpAuthorizeResponse {- /** Present only when status is authentication_required. */- authUrl?: string;- status: TrueHarness.McpAuthorizeResponseStatus;-}diff --git a/packages/sdk/src/api/types/McpAuthorizeResponseStatus.ts b/packages/sdk/src/api/types/McpAuthorizeResponseStatus.tsdeleted file mode 100644index 4ccfb74aa..000000000--- a/packages/sdk/src/api/types/McpAuthorizeResponseStatus.ts+++ /dev/null@@ -1,7 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--export const McpAuthorizeResponseStatus = {- Authenticated: "authenticated",- AuthenticationRequired: "authentication_required",-} as const;-export type McpAuthorizeResponseStatus = (typeof McpAuthorizeResponseStatus)[keyof typeof McpAuthorizeResponseStatus];diff --git a/packages/sdk/src/api/types/McpServerEntry.ts b/packages/sdk/src/api/types/McpServerEntry.tsindex 5419b8b03..2d86436d2 100644--- a/packages/sdk/src/api/types/McpServerEntry.ts+++ b/packages/sdk/src/api/types/McpServerEntry.ts@@ -4,7 +4,7 @@ import type * as TrueHarness from "../index.js";export interface McpServerEntry {auth?: TrueHarness.McpServerAuthSettings;- /** Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, so an expired-but-refreshable token still reads as `authentication_required` here — call `/authorize` to actually resolve it. `not_required` for servers without `auth` configured. */+ /** Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, so an expired-but-refreshable token still reads as `authentication_required` here. `not_required` for servers without `auth` configured. */authStatus: TrueHarness.McpServerEntryAuthStatus;name: string;url: string;diff --git a/packages/sdk/src/api/types/McpServerEntryAuthStatus.ts b/packages/sdk/src/api/types/McpServerEntryAuthStatus.tsindex b6c56a23a..0309ae0cf 100644--- a/packages/sdk/src/api/types/McpServerEntryAuthStatus.ts+++ b/packages/sdk/src/api/types/McpServerEntryAuthStatus.ts@@ -1,6 +1,6 @@// This file was auto-generated by Fern from our API Definition.-/** Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, so an expired-but-refreshable token still reads as `authentication_required` here — call `/authorize` to actually resolve it. `not_required` for servers without `auth` configured. */+/** Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, so an expired-but-refreshable token still reads as `authentication_required` here. `not_required` for servers without `auth` configured. */export const McpServerEntryAuthStatus = {Authenticated: "authenticated",AuthenticationRequired: "authentication_required",diff --git a/packages/sdk/src/api/types/index.ts b/packages/sdk/src/api/types/index.tsindex 62e13f4d9..0320056fb 100644--- a/packages/sdk/src/api/types/index.ts+++ b/packages/sdk/src/api/types/index.ts@@ -68,8 +68,6 @@ export * from "./ListSkillsResponse.js";export * from "./ListTurnEventsOrder.js";export * from "./ListTurnEventsResponse.js";export * from "./ListTurnsResponse.js";-export * from "./McpAuthorizeResponse.js";-export * from "./McpAuthorizeResponseStatus.js";export * from "./McpAuthRequiredEvent.js";export * from "./McpAuthStatus.js";export * from "./McpAuthStatusStatus.js";diff --git a/packages/sdk/src/serialization/types/McpAuthorizeResponse.ts b/packages/sdk/src/serialization/types/McpAuthorizeResponse.tsdeleted file mode 100644index b8ff5955a..000000000--- a/packages/sdk/src/serialization/types/McpAuthorizeResponse.ts+++ /dev/null@@ -1,21 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--import type * as TrueHarness from "../../api/index.js";-import * as core from "../../core/index.js";-import type * as serializers from "../index.js";-import { McpAuthorizeResponseStatus } from "./McpAuthorizeResponseStatus.js";--export const McpAuthorizeResponse: core.serialization.ObjectSchema<- serializers.McpAuthorizeResponse.Raw,- TrueHarness.McpAuthorizeResponse-> = core.serialization.object({- authUrl: core.serialization.property("auth_url", core.serialization.string().optional()),- status: McpAuthorizeResponseStatus,-});--export declare namespace McpAuthorizeResponse {- export interface Raw {- auth_url?: string | null;- status: McpAuthorizeResponseStatus.Raw;- }-}diff --git a/packages/sdk/src/serialization/types/McpAuthorizeResponseStatus.ts b/packages/sdk/src/serialization/types/McpAuthorizeResponseStatus.tsdeleted file mode 100644index e49db8d9c..000000000--- a/packages/sdk/src/serialization/types/McpAuthorizeResponseStatus.ts+++ /dev/null@@ -1,14 +0,0 @@-// This file was auto-generated by Fern from our API Definition.--import type * as TrueHarness from "../../api/index.js";-import * as core from "../../core/index.js";-import type * as serializers from "../index.js";--export const McpAuthorizeResponseStatus: core.serialization.Schema<- serializers.McpAuthorizeResponseStatus.Raw,- TrueHarness.McpAuthorizeResponseStatus-> = core.serialization.enum_(["authenticated", "authentication_required"]);--export declare namespace McpAuthorizeResponseStatus {- export type Raw = "authenticated" | "authentication_required";-}diff --git a/packages/sdk/src/serialization/types/index.ts b/packages/sdk/src/serialization/types/index.tsindex 62e13f4d9..0320056fb 100644--- a/packages/sdk/src/serialization/types/index.ts+++ b/packages/sdk/src/serialization/types/index.ts@@ -68,8 +68,6 @@ export * from "./ListSkillsResponse.js";export * from "./ListTurnEventsOrder.js";export * from "./ListTurnEventsResponse.js";export * from "./ListTurnsResponse.js";-export * from "./McpAuthorizeResponse.js";-export * from "./McpAuthorizeResponseStatus.js";export * from "./McpAuthRequiredEvent.js";export * from "./McpAuthStatus.js";export * from "./McpAuthStatusStatus.js";diff --git a/packages/sdk/tests/wire/legacy/mcpServers.test.ts b/packages/sdk/tests/wire/legacy/mcpServers.test.tsindex 997f01505..731d40d33 100644--- a/packages/sdk/tests/wire/legacy/mcpServers.test.ts+++ b/packages/sdk/tests/wire/legacy/mcpServers.test.ts@@ -36,50 +36,6 @@ describe("McpServersClient", () => {});});- test("authorize (1)", async () => {- const server = mockServerPool.createServer();- const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });-- const rawResponseBody = { auth_url: "auth_url", status: "authenticated" };-- server- .mockEndpoint()- .get("/api/v1/legacy/mcp-servers/name/authorize")- .respondWith()- .statusCode(200)- .jsonBody(rawResponseBody)- .build();-- const response = await client.legacy.mcpServers.authorize("name", {- redirectUrl: "redirect_url",- });- expect(response).toEqual({- authUrl: "auth_url",- status: "authenticated",- });- });-- test("authorize (2)", async () => {- const server = mockServerPool.createServer();- const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });-- const rawResponseBody = { error: { message: "message" } };-- server- .mockEndpoint()- .get("/api/v1/legacy/mcp-servers/name/authorize")- .respondWith()- .statusCode(404)- .jsonBody(rawResponseBody)- .build();-- await expect(async () => {- return await client.legacy.mcpServers.authorize("name", {- redirectUrl: "redirect_url",- });- }).rejects.toThrow(TrueHarnessTypes.NotFoundError);- });-test("list_tools (1)", async () => {const server = mockServerPool.createServer();const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });diff --git a/packages/sdk/tests/wire/settings/mcpServers.test.ts b/packages/sdk/tests/wire/settings/mcpServers.test.tsindex 499d4391b..9d4be501e 100644--- a/packages/sdk/tests/wire/settings/mcpServers.test.ts+++ b/packages/sdk/tests/wire/settings/mcpServers.test.ts@@ -156,9 +156,7 @@ describe("McpServersClient", () => {.jsonBody(rawResponseBody).build();- const response = await client.settings.mcpServers.authorize("name", {- redirectUrl: "redirect_url",- });+ const response = await client.settings.mcpServers.authorize("name");expect(response).toEqual({authorizationUrl: "authorization_url",status: "authenticated",@@ -171,6 +169,25 @@ describe("McpServersClient", () => {const rawResponseBody = { error: { message: "message" } };+ server+ .mockEndpoint()+ .get("/api/v1/settings/mcp-servers/name/authorize")+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.settings.mcpServers.authorize("name");+ }).rejects.toThrow(TrueHarnessTypes.BadRequestError);+ });++ test("authorize (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };+server.mockEndpoint().get("/api/v1/settings/mcp-servers/name/authorize")@@ -180,12 +197,29 @@ describe("McpServersClient", () => {.build();await expect(async () => {- return await client.settings.mcpServers.authorize("name", {- redirectUrl: "redirect_url",- });+ return await client.settings.mcpServers.authorize("name");}).rejects.toThrow(TrueHarnessTypes.NotFoundError);});+ test("authorize (4)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .get("/api/v1/settings/mcp-servers/name/authorize")+ .respondWith()+ .statusCode(500)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.settings.mcpServers.authorize("name");+ }).rejects.toThrow(TrueHarnessTypes.InternalServerError);+ });+test("list_tools (1)", async () => {const server = mockServerPool.createServer();const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });diff --git a/packages/server/scripts/write-openapi.ts b/packages/server/scripts/write-openapi.tsindex f63a2b823..017e2f479 100644--- a/packages/server/scripts/write-openapi.ts+++ b/packages/server/scripts/write-openapi.ts@@ -21,6 +21,7 @@ import { SqliteMcpServerStore } from '../src/db/sqlite/mcp-server-store/SqliteMcimport { SqliteModelProviderStore } from '../src/db/sqlite/model-provider-store/SqliteModelProviderStore';import { SqliteSandboxProviderStore } from '../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';import { SqliteSkillStore } from '../src/db/sqlite/skill-store/SqliteSkillStore';+import { SqliteOAuthTokenStore } from '../src/db/sqlite/token-store/SqliteOAuthTokenStore';import { McpStore } from '../src/legacy-registry-store/McpStore';import { ModelStore } from '../src/legacy-registry-store/ModelStore';import { SkillStore } from '../src/legacy-registry-store/SkillStore';@@ -55,6 +56,7 @@ const app = createServerApp({modelProviderStore: new SqliteModelProviderStore(db),mcpCatalog: McpCatalog.load(),mcpServerStore: new SqliteMcpServerStore(db),+ tokenStore: new SqliteOAuthTokenStore(db),mcpStore: McpStore.load(),skillCatalog: SkillCatalog.load(),skillStore: new SqliteSkillStore(db),diff --git a/packages/server/src/apis/legacyMcp.ts b/packages/server/src/apis/legacyMcp.tsindex 9efc15c52..1690be1a1 100644--- a/packages/server/src/apis/legacyMcp.ts+++ b/packages/server/src/apis/legacyMcp.ts@@ -2,7 +2,7 @@ import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/utils/core';import type { Logger } from 'winston';import type { McpStore } from '../legacy-registry-store/McpStore';-import { authorizeMcpServerRoute, listMcpServersRoute, listMcpToolsRoute } from '../routes/legacyMcpRoutes';+import { listMcpServersRoute, listMcpToolsRoute } from '../routes/legacyMcpRoutes';export interface LegacyMcpRouterDeps {mcpStore: McpStore;@@ -67,21 +67,8 @@ export function createLegacyMcpRouter(deps: LegacyMcpRouterDeps) {}};- const authorizeMcpServerHandler: RouteHandler<typeof authorizeMcpServerRoute> = c => {- const { name } = c.req.valid('param');- const { redirect_url: redirectUrl } = c.req.valid('query');- const entry = deps.mcpStore.get(name);- if (!entry) {- return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);- }- // TODO: actual implementation.- const stubAuthUrl = `https://example-authorization-server.invalid/authorize?client_id=stub&redirect_uri=${encodeURIComponent(redirectUrl)}`;- return c.json({ status: 'authentication_required' as const, auth_url: stubAuthUrl }, 200);- };-const router = new OpenAPIHono();router.openapi(listMcpServersRoute, listMcpServersHandler);router.openapi(listMcpToolsRoute, listMcpToolsHandler);- router.openapi(authorizeMcpServerRoute, authorizeMcpServerHandler);return router;}diff --git a/packages/server/src/apis/legacyMcpOAuth.ts b/packages/server/src/apis/legacyMcpOAuth.tsdeleted file mode 100644index a3c63f053..000000000--- a/packages/server/src/apis/legacyMcpOAuth.ts+++ /dev/null@@ -1,34 +0,0 @@-import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';-import type { Logger } from 'winston';-import { mcpOAuthCallbackRoute } from '../routes/legacyMcpOAuthRoutes';--export interface LegacyMcpOAuthRouterDeps {- logger: Logger;-}--// STUB: fix this.-const STUB_CONNECTED_REDIRECT = '/mcp/oauth/connected';-const STUB_FAILED_REDIRECT = '/mcp/oauth/failed';--export function createLegacyMcpOAuthRouter(deps: LegacyMcpOAuthRouterDeps) {- const callbackHandler: RouteHandler<typeof mcpOAuthCallbackRoute> = c => {- const { state, code, error, error_description: errorDescription } = c.req.valid('query');-- if (error) {- deps.logger.warn('MCP OAuth callback returned an error', { state, error, errorDescription });- return c.redirect(STUB_FAILED_REDIRECT, 302);- }-- if (!code) {- return c.json({ error: { message: 'OAuth callback is missing both `code` and `error`' } }, 400);- }-- // STUB: real implementation exchanges `code` for a token here; no lookup/exchange happens yet.- deps.logger.info('MCP OAuth callback received (stub — no token exchange performed)', { state });- return c.redirect(STUB_CONNECTED_REDIRECT, 302);- };-- const router = new OpenAPIHono();- router.openapi(mcpOAuthCallbackRoute, callbackHandler);- return router;-}diff --git a/packages/server/src/apis/mcpOAuth.ts b/packages/server/src/apis/mcpOAuth.tsnew file mode 100644index 000000000..a595051f9--- /dev/null+++ b/packages/server/src/apis/mcpOAuth.ts@@ -0,0 +1,54 @@+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';+import {+ completeMcpAuthorization,+ extractErrorLogFields,+ McpConnectionError,+ type IOAuthClientStore,+ type IOAuthTokenStore,+} from '@truefoundry/utils/core';+import type { Logger } from 'winston';+import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';++export interface McpOAuthRouterDeps {+ tokenStore: IOAuthTokenStore;+ mcpServerStore: IOAuthClientStore;+ logger: Logger;+}++/** Shared OAuth callback (mounted at /api/v1/mcp-servers/oauth). */+export function createMcpOAuthRouter(deps: McpOAuthRouterDeps) {+ const callbackHandler: RouteHandler<typeof mcpOAuthCallbackRoute> = async c => {+ const { state, code, error, error_description: errorDescription } = c.req.valid('query');++ if (error) {+ deps.logger.warn('MCP OAuth callback returned an error', { state, error, errorDescription });+ await deps.tokenStore.consumePendingAuthorization({ state });+ return c.json({ error: { message: errorDescription ? `${error}: ${errorDescription}` : error } }, 400);+ }++ if (!code) {+ return c.json({ error: { message: 'OAuth callback is missing both `code` and `error`' } }, 400);+ }++ try {+ await completeMcpAuthorization({+ tokenStore: deps.tokenStore,+ mcpServerStore: deps.mcpServerStore,+ state,+ code,+ });+ return c.json({ success: true as const }, 200);+ } catch (err) {+ if (err instanceof McpConnectionError) {+ deps.logger.warn('MCP OAuth callback token exchange failed', extractErrorLogFields(err));+ return c.json({ error: { message: err.message } }, 400);+ }+ deps.logger.error('MCP OAuth callback unexpected failure', extractErrorLogFields(err));+ return c.json({ error: { message: 'Internal server error' } }, 500);+ }+ };++ const router = new OpenAPIHono();+ router.openapi(mcpOAuthCallbackRoute, callbackHandler);+ return router;+}diff --git a/packages/server/src/apis/mcpServers.ts b/packages/server/src/apis/mcpServers.tsindex c310e0cfe..484cb8aa5 100644--- a/packages/server/src/apis/mcpServers.ts+++ b/packages/server/src/apis/mcpServers.ts@@ -1,7 +1,17 @@import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';-import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/utils/core';+import {+ extractErrorLogFields,+ isAuthRequired,+ isMcpAuthRequired,+ McpConnectionError,+ RemoteMCP,+ resolveMcpAuth,+ validateRedirectUris,+ type IOAuthTokenStore,+} from '@truefoundry/utils/core';import type { Logger } from 'winston';import type { McpCatalog } from '../catalog/McpCatalog';+import configuration from '../config';import type { IMcpServerStore, McpServerRecord } from '../db/mcpServerStore';import {authorizeConfiguredMcpServerRoute,@@ -18,6 +28,7 @@ import { TENANT_ID } from './sessions';export interface McpServersRouterDeps {mcpCatalog: McpCatalog;mcpServerStore: IMcpServerStore;+ tokenStore: IOAuthTokenStore;logger: Logger;}@@ -104,9 +115,35 @@ export function createMcpServersRouter(deps: McpServersRouterDeps) {if (record.manifest.auth?.type !== 'dcr') {return c.json({ status: 'authenticated' as const }, 200);}- // STUB: real DCR + authorize URL minting lands with the OAuth follow-up.- const stubAuthUrl = `https://example-authorization-server.invalid/authorize?client_id=stub&redirect_uri=${encodeURIComponent(redirectUrl)}`;- return c.json({ status: 'auth_required' as const, authorization_url: stubAuthUrl }, 200);+ try {+ if (redirectUrl) {+ validateRedirectUris({ redirectUris: [redirectUrl] });+ }+ // Reuses a usable/refreshable token when present; only builds an auth URL when needed.+ const result = await resolveMcpAuth({+ tokenStore: deps.tokenStore,+ mcpServerStore: deps.mcpServerStore,+ serverId: record.id,+ mcpServerUrl: record.manifest.url,+ mcpServerName: record.name,+ clientName: configuration.OAUTH_CLIENT_NAME,+ ...(redirectUrl !== undefined ? { redirectUrl } : {}),+ });+ if (isMcpAuthRequired(result)) {+ return c.json({ status: 'auth_required' as const, authorization_url: result.authUrl.href }, 200);+ }+ return c.json({ status: 'authenticated' as const }, 200);+ } catch (error) {+ if (error instanceof McpConnectionError) {+ deps.logger.warn(`MCP authorize failed for "${name}"`, extractErrorLogFields(error));+ if (error.statusCode === 400) {+ return c.json({ error: { message: error.message } }, 400);+ }+ return c.json({ error: { message: error.message } }, 500);+ }+ deps.logger.error(`MCP authorize unexpected failure for "${name}"`, extractErrorLogFields(error));+ return c.json({ error: { message: 'Internal server error' } }, 500);+ }};const router = new OpenAPIHono();diff --git a/packages/server/src/apis/settings.ts b/packages/server/src/apis/settings.tsindex 6aff89972..b45756fe8 100644--- a/packages/server/src/apis/settings.ts+++ b/packages/server/src/apis/settings.ts@@ -4,6 +4,7 @@* a single policy can wrap the whole tree later without touching each resource.*/import { OpenAPIHono } from '@hono/zod-openapi';+import type { IOAuthTokenStore } from '@truefoundry/utils/core';import type { Logger } from 'winston';import type { McpCatalog } from '../catalog/McpCatalog';import type { ModelCatalog } from '../catalog/ModelCatalog';@@ -23,6 +24,7 @@ export interface SettingsRouterDeps {modelProviderStore: IModelProviderStore;mcpCatalog: McpCatalog;mcpServerStore: IMcpServerStore;+ tokenStore: IOAuthTokenStore;skillCatalog: SkillCatalog;skillStore: ISkillStore;sandboxCatalog: SandboxCatalog;@@ -44,6 +46,7 @@ export function createSettingsRouter(deps: SettingsRouterDeps) {createMcpServersRouter({mcpCatalog: deps.mcpCatalog,mcpServerStore: deps.mcpServerStore,+ tokenStore: deps.tokenStore,logger: deps.logger,}),);diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex f42000600..d82b95a84 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -2,6 +2,7 @@import { swaggerUI } from '@hono/swagger-ui';import { OpenAPIHono } from '@hono/zod-openapi';import type { ISessionStore, Sessions, TurnSandboxFactory, TurnStreamingEvent } from '@truefoundry/utils/agent-session';+import type { IOAuthTokenStore } from '@truefoundry/utils/core';import type { RequestReplyRouter } from '@truefoundry/utils/request-reply';import type { Context } from 'hono';import { HTTPException } from 'hono/http-exception';@@ -10,9 +11,9 @@ import type { Logger } from 'winston';import { createCapabilitiesRouter } from './apis/capabilities';import { createLegacyCapabilitiesRouter } from './apis/legacyCapabilities';import { createLegacyMcpRouter } from './apis/legacyMcp';-import { createLegacyMcpOAuthRouter } from './apis/legacyMcpOAuth';import { createLegacyModelsRouter } from './apis/legacyModels';import { createLegacySkillsRouter } from './apis/legacySkills';+import { createMcpOAuthRouter } from './apis/mcpOAuth';import { createAvailableMcpServersRouter } from './apis/mcpServers';import { createModelsRouter } from './apis/models';import { createSessionsRouter } from './apis/sessions';@@ -57,6 +58,7 @@ export interface ServerDeps {modelProviderStore: IModelProviderStore;mcpCatalog: McpCatalog;mcpServerStore: IMcpServerStore;+ tokenStore: IOAuthTokenStore;mcpStore: McpStore;skillCatalog: SkillCatalog;skillStore: ISkillStore;@@ -85,6 +87,15 @@ export function createServerApp(deps: ServerDeps) {app.route('/api/v1/capabilities', createCapabilitiesRouter({ sandboxProviderStore: deps.sandboxProviderStore }));app.route('/api/v1/models', createModelsRouter(deps.modelProviderStore));app.route('/api/v1/mcp-servers', createAvailableMcpServersRouter(deps.mcpServerStore));+ // Shared OAuth callback — path must match MCP_OAUTH_CALLBACK_PATH in the harness package.+ app.route(+ '/api/v1/mcp-servers/oauth',+ createMcpOAuthRouter({+ tokenStore: deps.tokenStore,+ mcpServerStore: deps.mcpServerStore,+ logger: deps.logger,+ }),+ );app.route('/api/v1/skills', createAvailableSkillsRouter(deps.skillStore));app.route('/api/v1/settings',@@ -93,6 +104,7 @@ export function createServerApp(deps: ServerDeps) {modelProviderStore: deps.modelProviderStore,mcpCatalog: deps.mcpCatalog,mcpServerStore: deps.mcpServerStore,+ tokenStore: deps.tokenStore,skillCatalog: deps.skillCatalog,skillStore: deps.skillStore,sandboxCatalog: deps.sandboxCatalog,@@ -103,7 +115,6 @@ export function createServerApp(deps: ServerDeps) {// YAML registry surfaces — still used by sessions/turns and the legacy UI paths.app.route('/api/v1/legacy/models', createLegacyModelsRouter(deps.modelStore));app.route('/api/v1/legacy/mcp-servers', createLegacyMcpRouter({ mcpStore: deps.mcpStore, logger: deps.logger }));- app.route('/api/v1/legacy/mcp-servers/oauth', createLegacyMcpOAuthRouter({ logger: deps.logger }));app.route('/api/v1/legacy/skills', createLegacySkillsRouter(deps.legacySkillStore));app.route('/api/v1/legacy/capabilities',diff --git a/packages/server/src/main.ts b/packages/server/src/main.tsindex cbdca1363..14c5808e3 100644--- a/packages/server/src/main.ts+++ b/packages/server/src/main.ts@@ -30,6 +30,7 @@ try {{ PostgresModelProviderStore },{ McpCatalog },{ PostgresMcpServerStore },+ { PostgresOAuthTokenStore },{ SkillCatalog },{ PostgresSkillStore },{ SandboxCatalog },@@ -54,6 +55,7 @@ try {import('./db/postgres/model-provider-store/PostgresModelProviderStore'),import('./catalog/McpCatalog'),import('./db/postgres/mcp-server-store/PostgresMcpServerStore'),+ import('./db/postgres/token-store/PostgresOAuthTokenStore'),import('./catalog/SkillCatalog'),import('./db/postgres/skill-store/PostgresSkillStore'),import('./catalog/SandboxCatalog'),@@ -97,6 +99,7 @@ try {modelProviderStore: new PostgresModelProviderStore(db),mcpCatalog: McpCatalog.load(),mcpServerStore: new PostgresMcpServerStore(db),+ tokenStore: new PostgresOAuthTokenStore(db),mcpStore: McpStore.load(),skillCatalog: SkillCatalog.load(),skillStore: new PostgresSkillStore(db),diff --git a/packages/server/src/routes/legacyMcpRoutes.ts b/packages/server/src/routes/legacyMcpRoutes.tsindex a0398e92a..ebc28c7db 100644--- a/packages/server/src/routes/legacyMcpRoutes.ts+++ b/packages/server/src/routes/legacyMcpRoutes.ts@@ -11,8 +11,8 @@ const McpServerResponseSchema = McpServerEntrySchema.extend({.enum(['authenticated', 'authentication_required', 'not_required']).describe('Passive check only: whether a stored, unexpired token exists. Never attempts a live refresh, ' +- 'so an expired-but-refreshable token still reads as `authentication_required` here — call `/authorize` to ' +- 'actually resolve it. `not_required` for servers without `auth` configured.',+ 'so an expired-but-refreshable token still reads as `authentication_required` here. ' ++ '`not_required` for servers without `auth` configured.',),}).openapi('McpServerEntry');@@ -88,41 +88,3 @@ export const listMcpToolsRoute = createRoute({},},});--const McpAuthorizeQuerySchema = z.object({- redirect_url: z.string().url().describe('Where to send the browser after OAuth completes.'),-});--const McpAuthorizeResponseSchema = z- .object({- status: z.enum(['authenticated', 'authentication_required']),- auth_url: z.string().url().optional().describe('Present only when status is authentication_required.'),- })- .openapi('McpAuthorizeResponse');--export const authorizeMcpServerRoute = createRoute({- method: 'get',- path: '/{name}/authorize',- tags: [MCP_SERVERS_TAG],- summary: 'Start (or short-circuit) the auth flow for an MCP server',- 'x-fern-sdk-group-name': ['legacy', 'mcp_servers'],- 'x-fern-sdk-method-name': 'authorize',- description:- 'Registers a DCR client for this server if none exists yet, then returns an authorization URL to ' +- 'redirect the user to so they can complete the OAuth consent flow. Short-circuits to ' +- '`{status: authenticated}` with no URL if the server is already connected.',- request: {- params: McpServerNameParamsSchema,- query: McpAuthorizeQuerySchema,- },- responses: {- 200: {- content: { 'application/json': { schema: McpAuthorizeResponseSchema } },- description: 'Either already authenticated, or an authorization URL to redirect to.',- },- 404: {- content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'MCP server not found.',- },- },-});diff --git a/packages/server/src/routes/legacyMcpOAuthRoutes.ts b/packages/server/src/routes/mcpOAuthRoutes.tssimilarity index 63%rename from packages/server/src/routes/legacyMcpOAuthRoutes.tsrename to packages/server/src/routes/mcpOAuthRoutes.tsindex 5e30d9b51..007212ca1 100644--- a/packages/server/src/routes/legacyMcpOAuthRoutes.ts+++ b/packages/server/src/routes/mcpOAuthRoutes.ts@@ -1,7 +1,7 @@import { createRoute, z } from '@hono/zod-openapi';import { RequestErrorResponseSchema } from '../schemas/errors';-const MCP_OAUTH_TAG = 'Legacy MCP OAuth';+const MCP_OAUTH_TAG = 'MCP OAuth';const McpOAuthCallbackQuerySchema = z.object({state: z.string().min(1).describe('Opaque token; correlates this callback to its pending authorization.'),@@ -13,6 +13,12 @@ const McpOAuthCallbackQuerySchema = z.object({error_description: z.string().optional(),});+const McpOAuthCallbackSuccessSchema = z+ .object({+ success: z.literal(true),+ })+ .openapi('McpOAuthCallbackSuccess');+export const mcpOAuthCallbackRoute = createRoute({method: 'get',path: '/callback',@@ -24,12 +30,17 @@ export const mcpOAuthCallbackRoute = createRoute({query: McpOAuthCallbackQuerySchema,},responses: {- 302: {- description: 'Redirects to the original `redirect_url` on success, or a failure page if `error` was present.',+ 200: {+ content: { 'application/json': { schema: McpOAuthCallbackSuccessSchema } },+ description: 'Token exchanged successfully; no browser redirect.',},400: {content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Unknown or expired `state` (no matching pending authorization), or `code`/`error` both missing.',+ description: 'IdP `error`, unknown/expired `state`, token exchange failure, or `code`/`error` both missing.',+ },+ 500: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Unexpected failure during token exchange.',},},});diff --git a/packages/server/src/routes/mcpServerRoutes.ts b/packages/server/src/routes/mcpServerRoutes.tsindex 63ad76d5b..cd55fe339 100644--- a/packages/server/src/routes/mcpServerRoutes.ts+++ b/packages/server/src/routes/mcpServerRoutes.ts@@ -139,7 +139,11 @@ export const listMcpServerToolsRoute = createRoute({});const McpAuthorizeQuerySchema = z.object({- redirect_url: z.string().url().describe('Where to send the browser after OAuth completes.'),+ redirect_url: z+ .string()+ .url()+ .optional()+ .describe('Optional FE landing URL after OAuth (stored on pending auth; callback does not redirect yet).'),});const ConfiguredMcpAuthorizeResponseSchema = z@@ -157,8 +161,10 @@ export const authorizeConfiguredMcpServerRoute = createRoute({'x-fern-sdk-group-name': ['settings', 'mcpServers'],'x-fern-sdk-method-name': 'authorize',description:- 'Stub: returns authenticated when the server has no auth or header credentials on the row; ' +- 'auth_required with a placeholder authorization URL when auth.type is dcr. Real DCR lands in a follow-up.',+ 'For servers without auth or with header credentials, returns authenticated (no browser flow). ' ++ 'For auth.type dcr, returns authenticated when a usable (or refreshable) token exists; otherwise ' ++ 'runs DCR if needed and returns auth_required with an authorization URL. ' ++ 'Optional redirect_url is stored for a future FE landing redirect (callback currently returns JSON only).',request: {params: McpServerNameParamsSchema,query: McpAuthorizeQuerySchema,@@ -168,9 +174,17 @@ export const authorizeConfiguredMcpServerRoute = createRoute({content: { 'application/json': { schema: ConfiguredMcpAuthorizeResponseSchema } },description: 'Either already authenticated, or an authorization URL to redirect to.',},+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'DCR or authorize URL construction failed (e.g. server lacks registration_endpoint).',+ },404: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description: 'MCP server not found.',},+ 500: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Server misconfiguration (e.g. PUBLIC_BASE_URL unset).',+ },},});diff --git a/packages/server/tests/unit/apis/mcpOAuth.test.ts b/packages/server/tests/unit/apis/mcpOAuth.test.tsnew file mode 100644index 000000000..c596f5cd9--- /dev/null+++ b/packages/server/tests/unit/apis/mcpOAuth.test.ts@@ -0,0 +1,155 @@+/**+ * Authorize + OAuth callback against real sqlite stores with fetch stubbed+ * (same pattern as packages/harness MCP OAuth tests).+ */+import { mcpOAuthCallbackUrl } from '@truefoundry/utils/core';+import winston from 'winston';+import { createMcpOAuthRouter } from '../../../src/apis/mcpOAuth';+import { createMcpServersRouter } from '../../../src/apis/mcpServers';+import { McpCatalog } from '../../../src/catalog/McpCatalog';+import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';+import { createSqliteDb } from '../../../src/db/sqlite/client';+import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';+import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';++const AS_ORIGIN = 'https://auth.example.com';+const MCP_URL = 'https://mcp.example.com/sse';+const FE_REDIRECT = 'https://app.example.com/mcp/connected';++const AS_METADATA = {+ issuer: AS_ORIGIN,+ authorization_endpoint: `${AS_ORIGIN}/authorize`,+ token_endpoint: `${AS_ORIGIN}/token`,+ registration_endpoint: `${AS_ORIGIN}/register`,+ response_types_supported: ['code'],+ code_challenge_methods_supported: ['S256'],+ grant_types_supported: ['authorization_code'],+ token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],+};++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });+}++function stubOauthFetch(): void {+ globalThis.fetch = (async (input, init) => {+ const url = String(input);++ if (url.includes('oauth-protected-resource')) {+ return json({ resource: MCP_URL, authorization_servers: [AS_ORIGIN] });+ }++ if (url.includes('oauth-authorization-server') || url.includes('openid-configuration')) {+ return json(AS_METADATA);+ }++ if (url === `${AS_ORIGIN}/register` && init?.method === 'POST') {+ return json({+ client_id: 'dyn-client-1',+ client_secret: 'dyn-secret-1',+ token_endpoint_auth_method: 'client_secret_post',+ redirect_uris: [mcpOAuthCallbackUrl()],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ });+ }++ if (url === `${AS_ORIGIN}/token` && init?.method === 'POST') {+ return json({+ access_token: 'access-1',+ refresh_token: 'refresh-1',+ expires_in: 3600,+ token_type: 'Bearer',+ });+ }++ return new Response(`unexpected url: ${url}`, { status: 404 });+ }) as typeof fetch;+}++describe('MCP OAuth authorize + callback', () => {+ const realFetch = globalThis.fetch;+ let settingsRouter: ReturnType<typeof createMcpServersRouter>;+ let oauthRouter: ReturnType<typeof createMcpOAuthRouter>;+ let mcpServerStore: SqliteMcpServerStore;+ let tokenStore: SqliteOAuthTokenStore;++ beforeAll(async () => {+ const db = createSqliteDb(':memory:');+ await migrateSqliteToLatest(db);+ mcpServerStore = new SqliteMcpServerStore(db);+ tokenStore = new SqliteOAuthTokenStore(db);+ const logger = winston.createLogger({ silent: true });+ settingsRouter = createMcpServersRouter({+ mcpCatalog: McpCatalog.load(),+ mcpServerStore,+ tokenStore,+ logger,+ });+ oauthRouter = createMcpOAuthRouter({ tokenStore, mcpServerStore, logger });+ });++ beforeEach(() => {+ stubOauthFetch();+ });++ afterEach(() => {+ globalThis.fetch = realFetch;+ });++ it('authorize runs DCR and returns an authorization URL; callback exchanges the code', async () => {+ const put = await settingsRouter.request('/', {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ type: 'remote',+ name: 'oauth-mcp',+ url: MCP_URL,+ auth: { type: 'dcr' },+ }),+ });+ expect(put.status).toBe(200);++ const authorize = await settingsRouter.request(+ `/oauth-mcp/authorize?redirect_url=${encodeURIComponent(FE_REDIRECT)}`,+ );+ expect(authorize.status).toBe(200);+ const authorizeBody = (await authorize.json()) as { status: string; authorization_url?: string };+ expect(authorizeBody.status).toBe('auth_required');+ expect(authorizeBody.authorization_url).toBeDefined();++ const authUrl = new URL(authorizeBody.authorization_url ?? '');+ expect(authUrl.origin).toBe(AS_ORIGIN);+ expect(authUrl.searchParams.get('redirect_uri')).toBe(mcpOAuthCallbackUrl());+ const state = authUrl.searchParams.get('state');+ expect(state).toBeTruthy();++ const callback = await oauthRouter.request(`/callback?state=${encodeURIComponent(state ?? '')}&code=auth-code-1`);+ expect(callback.status).toBe(200);+ expect(await callback.json()).toEqual({ success: true });++ const record = await mcpServerStore.getServer({ tenant_id: 'default', name: 'oauth-mcp' });+ expect(record).toBeDefined();+ const token = await tokenStore.getToken({ id: record?.id ?? '' });+ expect(token?.accessToken).toBe('access-1');+ expect(token?.refreshToken).toBe('refresh-1');++ const reauthorize = await settingsRouter.request(+ `/oauth-mcp/authorize?redirect_url=${encodeURIComponent(FE_REDIRECT)}`,+ );+ expect(reauthorize.status).toBe(200);+ expect(await reauthorize.json()).toEqual({ status: 'authenticated' });+ });++ it('callback returns 400 for unknown state and IdP error', async () => {+ const unknown = await oauthRouter.request('/callback?state=no-such-state&code=x');+ expect(unknown.status).toBe(400);++ const denied = await oauthRouter.request('/callback?state=any&error=access_denied&error_description=user%20denied');+ expect(denied.status).toBe(400);+ expect(await denied.json()).toEqual({ error: { message: 'access_denied: user denied' } });+ });+});diff --git a/packages/server/tests/unit/apis/mcpServers.test.ts b/packages/server/tests/unit/apis/mcpServers.test.tsindex 5fe4c0ee6..69f4befb4 100644--- a/packages/server/tests/unit/apis/mcpServers.test.ts+++ b/packages/server/tests/unit/apis/mcpServers.test.ts@@ -4,6 +4,7 @@ import { McpCatalog } from '../../../src/catalog/McpCatalog';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';+import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';const putBody = {type: 'remote' as const,@@ -44,9 +45,11 @@ describe('mcp-servers routers', () => {const db = createSqliteDb(':memory:');await migrateSqliteToLatest(db);const mcpServerStore = new SqliteMcpServerStore(db);+ const tokenStore = new SqliteOAuthTokenStore(db);settingsRouter = createMcpServersRouter({mcpCatalog: McpCatalog.load(),mcpServerStore,+ tokenStore,logger: winston.createLogger({ silent: true }),});availableRouter = createAvailableMcpServersRouter(mcpServerStore);@@ -120,7 +123,7 @@ describe('mcp-servers routers', () => {expect(emptyHeaders.status).toBe(400);});- it('GET /{name}/authorize stubs auth for configured servers', async () => {+ it('GET /{name}/authorize short-circuits non-DCR servers and 404s unknowns', async () => {const authenticated = await settingsRouter.request('/deepwiki/authorize?redirect_url=https://example.com/callback');expect(authenticated.status).toBe(200);expect(await authenticated.json()).toEqual({ status: 'authenticated' });@@ -129,13 +132,78 @@ describe('mcp-servers routers', () => {expect(headerAuth.status).toBe(200);expect(await headerAuth.json()).toEqual({ status: 'authenticated' });- const required = await settingsRouter.request('/linear/authorize?redirect_url=https://example.com/callback');- expect(required.status).toBe(200);- const body = (await required.json()) as { status: string; authorization_url?: string };- expect(body.status).toBe('auth_required');- expect(body.authorization_url?.includes('redirect_uri=')).toBe(true);-const missing = await settingsRouter.request('/missing/authorize?redirect_url=https://example.com/callback');expect(missing.status).toBe(404);});++ it('GET /{name}/authorize for DCR returns auth_required with an authorization_url', async () => {+ const asOrigin = 'https://auth.example.com';+ const mcpUrl = 'https://mcp.example.com/sse';+ const realFetch = globalThis.fetch;+ globalThis.fetch = (async (input, init) => {+ const url = String(input);+ if (url.includes('oauth-protected-resource')) {+ return new Response(JSON.stringify({ resource: mcpUrl, authorization_servers: [asOrigin] }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ });+ }+ if (url.includes('oauth-authorization-server') || url.includes('openid-configuration')) {+ return new Response(+ JSON.stringify({+ issuer: asOrigin,+ authorization_endpoint: `${asOrigin}/authorize`,+ token_endpoint: `${asOrigin}/token`,+ registration_endpoint: `${asOrigin}/register`,+ response_types_supported: ['code'],+ code_challenge_methods_supported: ['S256'],+ grant_types_supported: ['authorization_code', 'refresh_token'],+ token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ );+ }+ if (url.includes('/register') && init?.method === 'POST') {+ return new Response(+ JSON.stringify({+ client_id: 'dyn-client-1',+ client_secret: 'dyn-secret-1',+ token_endpoint_auth_method: 'client_secret_post',+ redirect_uris: [`${process.env['PUBLIC_BASE_URL'] ?? ''}/api/v1/mcp-servers/oauth/callback`],+ grant_types: ['authorization_code', 'refresh_token'],+ response_types: ['code'],+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ );+ }+ return new Response(`unexpected url: ${url}`, { status: 404 });+ }) as typeof fetch;++ try {+ const put = await settingsRouter.request(+ '/',+ putInit({+ type: 'remote',+ name: 'oauth-mcp',+ url: mcpUrl,+ auth: { type: 'dcr' },+ }),+ );+ expect(put.status).toBe(200);++ const authorize = await settingsRouter.request(+ '/oauth-mcp/authorize?redirect_url=https://example.com/after-oauth',+ );+ expect(authorize.status).toBe(200);+ const body = (await authorize.json()) as { status: string; authorization_url?: string };+ expect(body.status).toBe('auth_required');+ expect(body.authorization_url).toBeDefined();+ const authUrl = new URL(body.authorization_url ?? '');+ expect(authUrl.origin).toBe(asOrigin);+ expect(authUrl.searchParams.get('client_id')).toBe('dyn-client-1');+ expect(authUrl.searchParams.get('state')).toBeTruthy();+ } finally {+ globalThis.fetch = realFetch;+ }+ });});diff --git a/packages/server/tests/unit/apis/modelProviders.test.ts b/packages/server/tests/unit/apis/modelProviders.test.tsindex 15a72e607..bdfa4357a 100644--- a/packages/server/tests/unit/apis/modelProviders.test.ts+++ b/packages/server/tests/unit/apis/modelProviders.test.ts@@ -11,6 +11,7 @@ import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/Sqimport { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';+import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';const putBody = {type: 'anthropic',@@ -47,6 +48,7 @@ describe('settings model-providers and models routers', () => {modelProviderStore,mcpCatalog: McpCatalog.load(),mcpServerStore: new SqliteMcpServerStore(db),+ tokenStore: new SqliteOAuthTokenStore(db),skillCatalog: SkillCatalog.load(),skillStore: new SqliteSkillStore(db),sandboxCatalog: SandboxCatalog.load(),