Skip to content

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

AGE-1467: Add MCP OAuth Dynamic Client Registration schema and stub auth endpoints (#24)

Heer Ambavi1f4fc7d6769a
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.json
index b8db3dd3c..1c142ec67 100644
--- a/fern/openapi/openapi.json
+++ b/fern/openapi/openapi.json
@@ -907,9 +907,59 @@
],
"type": "object"
},
+ "McpAuthorizeResponse": {
+ "properties": {
+ "auth_url": {
+ "description": "Present only when status is authentication_required.",
+ "format": "uri",
+ "type": "string"
+ },
+ "status": {
+ "enum": [
+ "authenticated",
+ "authentication_required"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "type": "object"
+ },
+ "McpServerAuthSettings": {
+ "oneOf": [
+ {
+ "properties": {
+ "type": {
+ "enum": [
+ "dcr"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "type"
+ ],
+ "type": "object"
+ }
+ ]
+ },
"McpServerEntry": {
"additionalProperties": false,
"properties": {
+ "auth": {
+ "$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.",
+ "enum": [
+ "authenticated",
+ "authentication_required",
+ "not_required"
+ ],
+ "type": "string"
+ },
"name": {
"minLength": 1,
"type": "string"
@@ -921,7 +971,8 @@
},
"required": [
"name",
- "url"
+ "url",
+ "auth_status"
],
"type": "object"
},
@@ -2496,7 +2547,7 @@
},
"/api/v1/mcp-servers": {
"get": {
- "description": "MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.",
+ "description": "MCP servers declared in mcp.yaml, each with a passive auth_status snapshot. Auth headers are configured via env vars and never returned.",
"responses": {
"200": {
"content": {
@@ -2519,6 +2570,131 @@
"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": {
+ "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": [
+ "MCP OAuth"
+ ],
+ "x-fern-ignore": true
+ }
+ },
+ "/api/v1/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": [
+ "MCP Servers"
+ ],
+ "x-fern-sdk-group-name": [
+ "mcp_servers"
+ ],
+ "x-fern-sdk-method-name": "authorize"
+ }
+ },
"/api/v1/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.",
diff --git a/packages/frontend/src/catalog.ts b/packages/frontend/src/catalog.ts
index 8c88948ff..5fb5da14a 100644
--- a/packages/frontend/src/catalog.ts
+++ b/packages/frontend/src/catalog.ts
@@ -6,9 +6,16 @@ export interface ModelEntry {
reasoning_efforts?: string[];
}
+/** Mirrors `McpServerAuthSettingsSchema` in packages/server/src/store/schemas.ts. */
+export interface McpServerAuthSettings {
+ type: 'dcr';
+}
+
export interface McpServerEntry {
name: string;
url: string;
+ /** Absent = today's static-header behavior (no OAuth). */
+ auth?: McpServerAuthSettings;
}
export interface SkillEntry {
diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.json
index 1159405c8..8547fb5bc 100644
--- a/packages/sdk/.fern/metadata.json
+++ b/packages/sdk/.fern/metadata.json
@@ -26,7 +26,7 @@
"streamType": "web",
"useDefaultRequestParameterValues": true
},
- "originGitCommit": "3f8a9c36b25d9afae08083043597d641199b100c",
+ "originGitCommit": "2bf85043c33eb3621f5a106baf173a70e21daf7f",
"originGitCommitIsDirty": true,
"invokedBy": "ci",
"requestedVersion": "0.0.0",
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index fae45d4b7..ab161a5c8 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -62,7 +62,7 @@ following namespace:
```typescript
import { TrueHarness } from "trueharness";
-const request: TrueHarness.ListSessionsRequest = {
+const request: TrueHarness.AuthorizeMcpServersRequest = {
...
};
```
diff --git a/packages/sdk/reference.md b/packages/sdk/reference.md
index eccfcc639..1b39b208f 100644
--- a/packages/sdk/reference.md
+++ b/packages/sdk/reference.md
@@ -68,7 +68,7 @@ await client.server.getCapabilities();
<dl>
<dd>
-MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.
+MCP servers declared in mcp.yaml, each with a passive auth_status snapshot. Auth headers are configured via env vars and never returned.
</dd>
</dl>
</dd>
@@ -107,6 +107,79 @@ await client.mcpServers.list();
</dl>
+</dd>
+</dl>
+</details>
+
+<details><summary><code>client.mcpServers.<a href="/src/api/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.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.AuthorizeMcpServersRequest`
+
+</dd>
+</dl>
+
+<dl>
+<dd>
+
+**requestOptions:** `McpServersClient.RequestOptions`
+
+</dd>
+</dl>
+</dd>
+</dl>
+
+
</dd>
</dl>
</details>
diff --git a/packages/sdk/src/api/resources/index.ts b/packages/sdk/src/api/resources/index.ts
index 3d67338a4..fc0b050b6 100644
--- a/packages/sdk/src/api/resources/index.ts
+++ b/packages/sdk/src/api/resources/index.ts
@@ -1,3 +1,4 @@
+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/mcpServers/client/Client.ts b/packages/sdk/src/api/resources/mcpServers/client/Client.ts
index 6d9421bb6..66e9df918 100644
--- a/packages/sdk/src/api/resources/mcpServers/client/Client.ts
+++ b/packages/sdk/src/api/resources/mcpServers/client/Client.ts
@@ -23,7 +23,7 @@ export class McpServersClient {
}
/**
- * MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.
+ * MCP servers declared in mcp.yaml, each with a passive auth_status snapshot. Auth headers are configured via env vars and never returned.
*
* @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.
*
@@ -82,6 +82,102 @@ export class McpServersClient {
return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/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.AuthorizeMcpServersRequest} request
+ * @param {McpServersClient.RequestOptions} requestOptions - Request-specific configuration.
+ *
+ * @throws {@link TrueHarness.NotFoundError}
+ * @throws {@link errors.TrueHarnessError}
+ * @throws {@link errors.TrueHarnessTimeoutError}
+ *
+ * @example
+ * await client.mcpServers.authorize("name", {
+ * redirectUrl: "redirect_url"
+ * })
+ */
+ public authorize(
+ name: string,
+ request: TrueHarness.AuthorizeMcpServersRequest,
+ requestOptions?: McpServersClient.RequestOptions,
+ ): core.HttpResponsePromise<TrueHarness.McpAuthorizeResponse> {
+ return core.HttpResponsePromise.fromPromise(this.__authorize(name, request, requestOptions));
+ }
+
+ private async __authorize(
+ name: string,
+ request: TrueHarness.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/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/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/mcpServers/client/index.ts b/packages/sdk/src/api/resources/mcpServers/client/index.ts
index cb0ff5c3b..195f9aa8a 100644
--- a/packages/sdk/src/api/resources/mcpServers/client/index.ts
+++ b/packages/sdk/src/api/resources/mcpServers/client/index.ts
@@ -1 +1 @@
-export {};
+export * from "./requests/index.js";
diff --git a/packages/sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts b/packages/sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts
new file mode 100644
index 000000000..ef097a479
--- /dev/null
+++ b/packages/sdk/src/api/resources/mcpServers/client/requests/AuthorizeMcpServersRequest.ts
@@ -0,0 +1,12 @@
+// 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/mcpServers/client/requests/index.ts b/packages/sdk/src/api/resources/mcpServers/client/requests/index.ts
new file mode 100644
index 000000000..9f3c48ef4
--- /dev/null
+++ b/packages/sdk/src/api/resources/mcpServers/client/requests/index.ts
@@ -0,0 +1 @@
+export type { AuthorizeMcpServersRequest } from "./AuthorizeMcpServersRequest.js";
diff --git a/packages/sdk/src/api/types/McpAuthorizeResponse.ts b/packages/sdk/src/api/types/McpAuthorizeResponse.ts
new file mode 100644
index 000000000..21acd88d4
--- /dev/null
+++ b/packages/sdk/src/api/types/McpAuthorizeResponse.ts
@@ -0,0 +1,9 @@
+// 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.ts
new file mode 100644
index 000000000..4ccfb74aa
--- /dev/null
+++ b/packages/sdk/src/api/types/McpAuthorizeResponseStatus.ts
@@ -0,0 +1,7 @@
+// 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/McpServerAuthSettings.ts b/packages/sdk/src/api/types/McpServerAuthSettings.ts
new file mode 100644
index 000000000..8263d1c66
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerAuthSettings.ts
@@ -0,0 +1,5 @@
+// This file was auto-generated by Fern from our API Definition.
+
+export interface McpServerAuthSettings {
+ type: "dcr";
+}
diff --git a/packages/sdk/src/api/types/McpServerEntry.ts b/packages/sdk/src/api/types/McpServerEntry.ts
index 739ada4ef..5419b8b03 100644
--- a/packages/sdk/src/api/types/McpServerEntry.ts
+++ b/packages/sdk/src/api/types/McpServerEntry.ts
@@ -1,6 +1,11 @@
// This file was auto-generated by Fern from our API Definition.
+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. */
+ authStatus: TrueHarness.McpServerEntryAuthStatus;
name: string;
url: string;
}
diff --git a/packages/sdk/src/api/types/McpServerEntryAuthStatus.ts b/packages/sdk/src/api/types/McpServerEntryAuthStatus.ts
new file mode 100644
index 000000000..b6c56a23a
--- /dev/null
+++ b/packages/sdk/src/api/types/McpServerEntryAuthStatus.ts
@@ -0,0 +1,9 @@
+// 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. */
+export const McpServerEntryAuthStatus = {
+ Authenticated: "authenticated",
+ AuthenticationRequired: "authentication_required",
+ NotRequired: "not_required",
+} as const;
+export type McpServerEntryAuthStatus = (typeof McpServerEntryAuthStatus)[keyof typeof McpServerEntryAuthStatus];
diff --git a/packages/sdk/src/api/types/index.ts b/packages/sdk/src/api/types/index.ts
index 5361e4cfc..4b6ec142f 100644
--- a/packages/sdk/src/api/types/index.ts
+++ b/packages/sdk/src/api/types/index.ts
@@ -39,13 +39,17 @@ 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 "./McpInitializeEvent.js";
export * from "./McpServer.js";
export * from "./McpServerAuthInfo.js";
+export * from "./McpServerAuthSettings.js";
export * from "./McpServerDisableToolsItem.js";
export * from "./McpServerEnableToolsItem.js";
export * from "./McpServerEntry.js";
+export * from "./McpServerEntryAuthStatus.js";
export * from "./McpServerInitInfo.js";
export * from "./McpServerInitInfoTransportType.js";
export * from "./McpServerPreloadToolsItem.js";
diff --git a/packages/sdk/src/serialization/types/McpAuthorizeResponse.ts b/packages/sdk/src/serialization/types/McpAuthorizeResponse.ts
new file mode 100644
index 000000000..b8ff5955a
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpAuthorizeResponse.ts
@@ -0,0 +1,21 @@
+// 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.ts
new file mode 100644
index 000000000..e49db8d9c
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpAuthorizeResponseStatus.ts
@@ -0,0 +1,14 @@
+// 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/McpServerAuthSettings.ts b/packages/sdk/src/serialization/types/McpServerAuthSettings.ts
new file mode 100644
index 000000000..0302c6d1d
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerAuthSettings.ts
@@ -0,0 +1,18 @@
+// 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 McpServerAuthSettings: core.serialization.ObjectSchema<
+ serializers.McpServerAuthSettings.Raw,
+ TrueHarness.McpServerAuthSettings
+> = core.serialization.object({
+ type: core.serialization.stringLiteral("dcr"),
+});
+
+export declare namespace McpServerAuthSettings {
+ export interface Raw {
+ type: "dcr";
+ }
+}
diff --git a/packages/sdk/src/serialization/types/McpServerEntry.ts b/packages/sdk/src/serialization/types/McpServerEntry.ts
index 105e11008..0ac096df3 100644
--- a/packages/sdk/src/serialization/types/McpServerEntry.ts
+++ b/packages/sdk/src/serialization/types/McpServerEntry.ts
@@ -3,17 +3,23 @@
import type * as TrueHarness from "../../api/index.js";
import * as core from "../../core/index.js";
import type * as serializers from "../index.js";
+import { McpServerAuthSettings } from "./McpServerAuthSettings.js";
+import { McpServerEntryAuthStatus } from "./McpServerEntryAuthStatus.js";
export const McpServerEntry: core.serialization.ObjectSchema<
serializers.McpServerEntry.Raw,
TrueHarness.McpServerEntry
> = core.serialization.object({
+ auth: McpServerAuthSettings.optional(),
+ authStatus: core.serialization.property("auth_status", McpServerEntryAuthStatus),
name: core.serialization.string(),
url: core.serialization.string(),
});
export declare namespace McpServerEntry {
export interface Raw {
+ auth?: McpServerAuthSettings.Raw | null;
+ auth_status: McpServerEntryAuthStatus.Raw;
name: string;
url: string;
}
diff --git a/packages/sdk/src/serialization/types/McpServerEntryAuthStatus.ts b/packages/sdk/src/serialization/types/McpServerEntryAuthStatus.ts
new file mode 100644
index 000000000..0e44d3065
--- /dev/null
+++ b/packages/sdk/src/serialization/types/McpServerEntryAuthStatus.ts
@@ -0,0 +1,14 @@
+// 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 McpServerEntryAuthStatus: core.serialization.Schema<
+ serializers.McpServerEntryAuthStatus.Raw,
+ TrueHarness.McpServerEntryAuthStatus
+> = core.serialization.enum_(["authenticated", "authentication_required", "not_required"]);
+
+export declare namespace McpServerEntryAuthStatus {
+ export type Raw = "authenticated" | "authentication_required" | "not_required";
+}
diff --git a/packages/sdk/src/serialization/types/index.ts b/packages/sdk/src/serialization/types/index.ts
index 5361e4cfc..4b6ec142f 100644
--- a/packages/sdk/src/serialization/types/index.ts
+++ b/packages/sdk/src/serialization/types/index.ts
@@ -39,13 +39,17 @@ 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 "./McpInitializeEvent.js";
export * from "./McpServer.js";
export * from "./McpServerAuthInfo.js";
+export * from "./McpServerAuthSettings.js";
export * from "./McpServerDisableToolsItem.js";
export * from "./McpServerEnableToolsItem.js";
export * from "./McpServerEntry.js";
+export * from "./McpServerEntryAuthStatus.js";
export * from "./McpServerInitInfo.js";
export * from "./McpServerInitInfoTransportType.js";
export * from "./McpServerPreloadToolsItem.js";
diff --git a/packages/sdk/tests/wire/mcpServers.test.ts b/packages/sdk/tests/wire/mcpServers.test.ts
index fed495e8a..0c86e32b1 100644
--- a/packages/sdk/tests/wire/mcpServers.test.ts
+++ b/packages/sdk/tests/wire/mcpServers.test.ts
@@ -9,7 +9,9 @@ describe("McpServersClient", () => {
const server = mockServerPool.createServer();
const client = new TrueHarness({ maxRetries: 0, environment: server.baseUrl });
- const rawResponseBody = { data: [{ name: "name", url: "url" }] };
+ const rawResponseBody = {
+ data: [{ auth: { type: "dcr" }, auth_status: "authenticated", name: "name", url: "url" }],
+ };
server
.mockEndpoint()
@@ -23,6 +25,10 @@ describe("McpServersClient", () => {
expect(response).toEqual({
data: [
{
+ auth: {
+ type: "dcr",
+ },
+ authStatus: "authenticated",
name: "name",
url: "url",
},
@@ -30,6 +36,50 @@ 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/mcp-servers/name/authorize")
+ .respondWith()
+ .statusCode(200)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ const response = await client.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/mcp-servers/name/authorize")
+ .respondWith()
+ .statusCode(404)
+ .jsonBody(rawResponseBody)
+ .build();
+
+ await expect(async () => {
+ return await client.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/server/registry-example/mcp.yaml b/packages/server/registry-example/mcp.yaml
index 1fe84ee8d..fbd8978d1 100644
--- a/packages/server/registry-example/mcp.yaml
+++ b/packages/server/registry-example/mcp.yaml
@@ -9,3 +9,6 @@ mcp_servers:
# TODO(oss): replace internal endpoint with a placeholder before the repo
# goes public.
url: https://internal.devtest.truefoundry.tech/api/llm/truefoundry/mcp/github-remote/server
+ # Optional `auth` field.
+ # auth:
+ # type: dcr
diff --git a/packages/server/src/apis/mcp.ts b/packages/server/src/apis/mcp.ts
index de2fbf3e6..0ea57d7f7 100644
--- a/packages/server/src/apis/mcp.ts
+++ b/packages/server/src/apis/mcp.ts
@@ -1,7 +1,7 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { extractErrorLogFields, isAuthRequired, McpConnectionError, RemoteMCP } from '@truefoundry/utils/core';
import type { Logger } from 'winston';
-import { listMcpServersRoute, listMcpToolsRoute } from '../routes/mcpRoutes';
+import { authorizeMcpServerRoute, listMcpServersRoute, listMcpToolsRoute } from '../routes/mcpRoutes';
import type { McpStore } from '../store/McpStore';
export interface McpRouterDeps {
@@ -21,8 +21,16 @@ function omitUndefinedEntries(obj: Record<string, unknown>): Record<string, unkn
}
export function createMcpRouter(deps: McpRouterDeps) {
+ // auth_status here is a passive check only (no live refresh attempt); `authentication_required`
+ // vs `not_required` — see route description.
+ // TODO(mcp-dcr): once IMcpTokenStore lands, batch-check stored tokens for all DCR-configured
+ // servers in one query instead of this config-only stub (never per-row — see db/postgres/AGENTS.md).
const listMcpServersHandler: RouteHandler<typeof listMcpServersRoute> = c => {
- return c.json({ data: deps.mcpStore.list() }, 200);
+ const data = deps.mcpStore.list().map(entry => ({
+ ...entry,
+ auth_status: entry.auth ? ('authentication_required' as const) : ('not_required' as const),
+ }));
+ return c.json({ data }, 200);
};
// Live MCP `tools/list` call against the configured server, no selectors applied.
@@ -59,8 +67,21 @@ export function createMcpRouter(deps: McpRouterDeps) {
}
};
+ 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/mcpOAuth.ts b/packages/server/src/apis/mcpOAuth.ts
new file mode 100644
index 000000000..d5f2c3b03
--- /dev/null
+++ b/packages/server/src/apis/mcpOAuth.ts
@@ -0,0 +1,34 @@
+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
+import type { Logger } from 'winston';
+import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';
+
+export interface McpOAuthRouterDeps {
+ logger: Logger;
+}
+
+// STUB: fix this.
+const STUB_CONNECTED_REDIRECT = '/mcp/oauth/connected';
+const STUB_FAILED_REDIRECT = '/mcp/oauth/failed';
+
+export function createMcpOAuthRouter(deps: McpOAuthRouterDeps) {
+ 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/app.ts b/packages/server/src/app.ts
index a60596828..325d03950 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -9,6 +9,7 @@ import type { RedisClientType } from 'redis';
import type { Logger } from 'winston';
import { createCapabilitiesRouter } from './apis/capabilities';
import { createMcpRouter } from './apis/mcp';
+import { createMcpOAuthRouter } from './apis/mcpOAuth';
import { createModelsRouter } from './apis/models';
import { createSessionsRouter } from './apis/sessions';
import { createSkillsRouter } from './apis/skills';
@@ -60,6 +61,7 @@ export function createServerApp(deps: ServerDeps) {
app.route('/api/v1/capabilities', createCapabilitiesRouter({ sandboxEnabled: deps.sandboxFactory !== undefined }));
app.route('/api/v1/models', createModelsRouter(deps.modelStore));
app.route('/api/v1/mcp-servers', createMcpRouter({ mcpStore: deps.mcpStore, logger: deps.logger }));
+ app.route('/api/v1/mcp-servers/oauth', createMcpOAuthRouter({ logger: deps.logger }));
app.route('/api/v1/skills', createSkillsRouter(deps.skillStore));
app.route(
'/api/v1/sessions',
diff --git a/packages/server/src/db/postgres/migrations/20260803_000001_mcp_oauth.ts b/packages/server/src/db/postgres/migrations/20260803_000001_mcp_oauth.ts
new file mode 100644
index 000000000..002f8a30e
--- /dev/null
+++ b/packages/server/src/db/postgres/migrations/20260803_000001_mcp_oauth.ts
@@ -0,0 +1,46 @@
+import type { Kysely } from 'kysely';
+
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await db.schema
+ .createTable('mcp_server')
+ .addColumn('id', 'text', c => c.notNull())
+ .addColumn('tenant_id', 'text', c => c.notNull())
+ .addColumn('name', 'text', c => c.notNull())
+ .addColumn('manifest', 'jsonb', c => c.notNull())
+ .addColumn('oauth_server', 'jsonb')
+ .addColumn('oauth_client', 'jsonb')
+ .addColumn('created_at', 'timestamptz', c => c.notNull())
+ .addColumn('updated_at', 'timestamptz', c => c.notNull())
+ .addPrimaryKeyConstraint('mcp_server_pkey', ['id'])
+ .execute();
+
+ await db.schema
+ .createIndex('mcp_server_tenant_name_idx')
+ .on('mcp_server')
+ .columns(['tenant_id', 'name'])
+ .unique()
+ .execute();
+
+ await db.schema
+ .createTable('oauth_token')
+ .addColumn('oauth_server_id', 'text', c => c.notNull().references('mcp_server.id').onDelete('cascade'))
+ .addColumn('token', 'jsonb', c => c.notNull())
+ .addColumn('updated_at', 'timestamptz', c => c.notNull())
+ .addPrimaryKeyConstraint('oauth_token_pkey', ['oauth_server_id'])
+ .execute();
+
+ await db.schema
+ .createTable('oauth_pending_authorization')
+ .addColumn('id', 'text', c => c.notNull())
+ .addColumn('oauth_server_id', 'text', c => c.notNull().references('mcp_server.id').onDelete('cascade'))
+ .addColumn('auth_data', 'jsonb', c => c.notNull())
+ .addColumn('created_at', 'timestamptz', c => c.notNull()) // used for TTL expiry on read
+ .addPrimaryKeyConstraint('oauth_pending_authorization_pkey', ['id'])
+ .execute();
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await db.schema.dropTable('oauth_pending_authorization').ifExists().cascade().execute();
+ await db.schema.dropTable('oauth_token').ifExists().cascade().execute();
+ await db.schema.dropTable('mcp_server').ifExists().cascade().execute();
+}
diff --git a/packages/server/src/db/postgres/types.ts b/packages/server/src/db/postgres/types.ts
index 8017e35b5..aa617379d 100644
--- a/packages/server/src/db/postgres/types.ts
+++ b/packages/server/src/db/postgres/types.ts
@@ -14,6 +14,43 @@ import type {
} from '@truefoundry/utils/core';
import type { CurrentContextUsage } from '@truefoundry/utils/core/runtime/contextUsage';
import type { ColumnType, Generated, JSONColumnType } from 'kysely';
+import type { McpServerManifest } from '../../store/schemas';
+
+/**
+ * `mcp_server.oauth_server` JSONB shape — RFC 8414 authorization-server metadata, discovered once
+ * at registration time. Own column, not merged with oauth_client: different source HTTP call
+ * (metadata discovery vs. DCR registration), and this one never carries a secret.
+ */
+export interface OAuthServer {
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+ codeChallengeMethodsSupported?: string[];
+}
+
+/** `mcp_server.oauth_client` JSONB shape — RFC 7591 DCR registration response for this server. */
+export interface OAuthClient {
+ clientId: string;
+ clientSecret?: string;
+}
+
+/** `oauth_pending_authorization.auth_data` JSONB shape. */
+export interface McpOAuthPendingAuthorizationData {
+ /** absent when the authorization server doesn't advertise PKCE support */
+ codeVerifier?: string;
+ /** absent when triggered mid-turn by resolveAuth, not by the authorize() endpoint */
+ redirectUrl?: string;
+}
+
+/** `oauth_token.token` JSONB shape — matches SF's MCPUserAuthModel.authData. */
+export interface McpOAuthToken {
+ accessToken: string;
+ /** absent: some grants don't issue one */
+ refreshToken?: string;
+ /** ISO 8601; always filled — see "missing expires_in" fallback in the design doc */
+ expiresAt: string;
+ /** scope is a single space-delimited case-sensitive string, not a list. */
+ scope?: string;
+}
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -290,15 +327,74 @@ export interface ThreadCapabilityStateTable {
updated_at: Date;
}
+/**
+ * PRIMARY KEY (id)
+ * UNIQUE (tenant_id, name) — the natural lookup key.
+ */
+export interface McpServerTable {
+ id: string;
+ tenant_id: string;
+ /** the uniqueness target; also duplicated inside `manifest` (the full mcp.yaml entry) */
+ name: string;
+ manifest: JSONColumnType<McpServerManifest, McpServerManifest, McpServerManifest>;
+ /** OAuthServer — { authorizationEndpoint, tokenEndpoint, codeChallengeMethodsSupported? }.
+ * RFC 8414 authorization-server metadata, discovered once at registration time.
+ */
+ oauth_server: JSONColumnType<OAuthServer, OAuthServer, OAuthServer> | null;
+ /** OAuthClient — { clientId, clientSecret? }. RFC 7591 DCR registration response.
+ * clientSecret's presence alone decides the auth method on every later call; validated at the
+ * application layer when read back via getOAuthClient/saveOAuthClient.
+ * Both oauth_server and oauth_client are null until the first successful DCR registration for
+ * this server.
+ */
+ oauth_client: JSONColumnType<OAuthClient, OAuthClient, OAuthClient> | null;
+ created_at: Date;
+ updated_at: Date;
+}
+
+/**
+ * PRIMARY KEY (oauth_server_id)
+ * No `tenant_id` — already 1:1 with tenant via the FK. Any tenant-scoped read resolves
+ * `oauth_server_id` through mcp_server (by tenant_id + name) first; this table is never
+ * queried by tenant_id directly.
+ */
+export interface OAuthTokenTable {
+ /** FK -> mcp_server.id, ON DELETE CASCADE */
+ oauth_server_id: string;
+ /** access_token, refresh_token, expires_at, scope. */
+ token: JSONColumnType<McpOAuthToken, McpOAuthToken, McpOAuthToken>;
+ updated_at: Date;
+}
+
+/**
+ * PRIMARY KEY (id)
+ *
+ * `id` is this table's own identity column, used as the OAuth wire `state` query
+ * parameter.
+ */
+export interface OAuthPendingAuthorizationTable {
+ id: string;
+ /** FK -> mcp_server.id, ON DELETE CASCADE */
+ oauth_server_id: string;
+ auth_data: JSONColumnType<
+ McpOAuthPendingAuthorizationData,
+ McpOAuthPendingAuthorizationData,
+ McpOAuthPendingAuthorizationData
+ >;
+ /** used for TTL expiry on read, no sweep job */
+ created_at: Date;
+}
+
/**
* Write-heat summary: `turn_thread` is the one deliberately-hot table with its hot
* columns (`context_ids`, `current_context_usage`) isolated from the pointer-carried
* big ones (`agent_info`, `checkpoint`); `session`, `turn`, and
* `thread_capability_state` take small bounded HOT-friendly updates; the two logs
* are pure insert. Nothing ever rewrites a large value except the array concat
- * itself — the documented, bounded cost of the raw-array model.
+ * itself — the documented, bounded cost of the raw-array model. `mcp_server` and the two
+ * `oauth_*` tables are low-write, low-volume (one row per tenant/server, or short-lived).
*
- * Canonical Kysely database — six session-store tables.
+ * Canonical Kysely database.
*/
export interface Database {
session: SessionTable;
@@ -307,4 +403,7 @@ export interface Database {
session_event: SessionEventTable;
thread_context_log: ThreadContextLogTable;
thread_capability_state: ThreadCapabilityStateTable;
+ mcp_server: McpServerTable;
+ oauth_token: OAuthTokenTable;
+ oauth_pending_authorization: OAuthPendingAuthorizationTable;
}
diff --git a/packages/server/src/db/sqlite/migrations/20260807_000001_mcp_oauth.ts b/packages/server/src/db/sqlite/migrations/20260807_000001_mcp_oauth.ts
new file mode 100644
index 000000000..6e707c3dc
--- /dev/null
+++ b/packages/server/src/db/sqlite/migrations/20260807_000001_mcp_oauth.ts
@@ -0,0 +1,52 @@
+import { type Kysely, sql } from 'kysely';
+
+/**
+ * MCP Dynamic Client Registration (RFC 7591) tables for SQLite — mirrors
+ * db/postgres/migrations/20260803_000001_mcp_oauth.ts, including the `mcp_server.id`
+ * FK target (application-generated ulid) for the two child tables.
+ */
+export async function up(db: Kysely<unknown>): Promise<void> {
+ await sql`
+ CREATE TABLE mcp_server (
+ id TEXT NOT NULL,
+ tenant_id TEXT NOT NULL,
+ name TEXT NOT NULL,
+ manifest BLOB NOT NULL,
+ oauth_server BLOB,
+ oauth_client BLOB,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (id)
+ ) STRICT
+ `.execute(db);
+
+ await sql`
+ CREATE UNIQUE INDEX mcp_server_tenant_name_idx
+ ON mcp_server (tenant_id, name)
+ `.execute(db);
+
+ await sql`
+ CREATE TABLE oauth_token (
+ oauth_server_id TEXT NOT NULL REFERENCES mcp_server (id) ON DELETE CASCADE,
+ token BLOB NOT NULL,
+ updated_at TEXT NOT NULL,
+ PRIMARY KEY (oauth_server_id)
+ ) STRICT
+ `.execute(db);
+
+ await sql`
+ CREATE TABLE oauth_pending_authorization (
+ id TEXT NOT NULL,
+ oauth_server_id TEXT NOT NULL REFERENCES mcp_server (id) ON DELETE CASCADE,
+ auth_data BLOB NOT NULL,
+ created_at TEXT NOT NULL,
+ PRIMARY KEY (id)
+ ) STRICT
+ `.execute(db);
+}
+
+export async function down(db: Kysely<unknown>): Promise<void> {
+ await sql`DROP TABLE IF EXISTS oauth_pending_authorization`.execute(db);
+ await sql`DROP TABLE IF EXISTS oauth_token`.execute(db);
+ await sql`DROP TABLE IF EXISTS mcp_server`.execute(db);
+}
diff --git a/packages/server/src/db/sqlite/types.ts b/packages/server/src/db/sqlite/types.ts
index 194e7fdb0..2010a32ef 100644
--- a/packages/server/src/db/sqlite/types.ts
+++ b/packages/server/src/db/sqlite/types.ts
@@ -17,6 +17,42 @@ import type {
} from '@truefoundry/utils/core';
import type { CurrentContextUsage } from '@truefoundry/utils/core/runtime/contextUsage';
import type { ColumnType, Generated, JSONColumnType } from 'kysely';
+import type { McpServerManifest } from '../../store/schemas';
+
+/**
+ * `mcp_server.oauth_server` JSONB shape — RFC 8414 authorization-server metadata, discovered once
+ * at registration time. Own column, not merged with oauth_client: different source HTTP call
+ * (metadata discovery vs. DCR registration), and this one never carries a secret.
+ */
+export interface OAuthServer {
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+ codeChallengeMethodsSupported?: string[];
+}
+
+/** `mcp_server.oauth_client` JSONB shape — RFC 7591 DCR registration response for this server. */
+export interface OAuthClient {
+ clientId: string;
+ clientSecret?: string;
+}
+
+/** `oauth_pending_authorization.auth_data` JSONB shape. */
+export interface McpOAuthPendingAuthorizationData {
+ /** absent when the authorization server doesn't advertise PKCE support */
+ codeVerifier?: string;
+ /** absent when triggered mid-turn by resolveAuth, not by the authorize() endpoint */
+ redirectUrl?: string;
+}
+
+/** `oauth_token.token` JSONB shape — matches SF's MCPUserAuthModel.authData. */
+export interface McpOAuthToken {
+ accessToken: string;
+ /** absent: some grants don't issue one */
+ refreshToken?: string;
+ /** ISO 8601; always filled — see "missing expires_in" fallback in the design doc */
+ expiresAt: string;
+ scope?: string;
+}
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -143,6 +179,54 @@ export interface ThreadCapabilityStateTable {
updated_at: string;
}
+/**
+ * PRIMARY KEY (id)
+ * UNIQUE (tenant_id, name) — the natural lookup key;
+ */
+export interface McpServerTable {
+ /** application-generated (ulid); FK target, never re-derived from tenant_id/name */
+ id: string;
+ tenant_id: string;
+ /** the uniqueness target; also duplicated inside `manifest` (the full mcp.yaml entry) */
+ name: string;
+ manifest: JsonbColumn<McpServerManifest>;
+ /**
+ * Both null until the first successful DCR registration, written together in that one call;
+ * always null when `manifest.auth` is absent. Two columns rather than one blob: different
+ * source HTTP response (metadata discovery vs. registration), and only `oauth_client` carries
+ * a secret.
+ */
+ oauth_server: JsonbColumn<OAuthServer> | null;
+ oauth_client: JsonbColumn<OAuthClient> | null;
+ created_at: string;
+ updated_at: string;
+}
+
+/**
+ * PRIMARY KEY (oauth_server_id)
+ * No `tenant_id` — already 1:1 with tenant via the FK. Any tenant-scoped read resolves
+ * `oauth_server_id` through mcp_server (by tenant_id + name) first; this table is never
+ * queried by tenant_id directly.
+ */
+export interface OAuthTokenTable {
+ /** FK -> mcp_server.id, ON DELETE CASCADE */
+ oauth_server_id: string;
+ token: JsonbColumn<McpOAuthToken>;
+ updated_at: string;
+}
+
+/**
+ * PRIMARY KEY (id) ( used for callback state.)
+ */
+export interface OAuthPendingAuthorizationTable {
+ id: string;
+ /** FK -> mcp_server.id, ON DELETE CASCADE */
+ oauth_server_id: string;
+ /** { codeVerifier?, redirectUrl? } — same writer/lifecycle for both, so merged into one column */
+ auth_data: JsonbColumn<McpOAuthPendingAuthorizationData>;
+ created_at: string;
+}
+
export interface Database {
session: SessionTable;
turn: TurnTable;
@@ -151,4 +235,7 @@ export interface Database {
session_event: SessionEventTable;
thread_context_log: ThreadContextLogTable;
thread_capability_state: ThreadCapabilityStateTable;
+ mcp_server: McpServerTable;
+ oauth_token: OAuthTokenTable;
+ oauth_pending_authorization: OAuthPendingAuthorizationTable;
}
diff --git a/packages/server/src/routes/mcpOAuthRoutes.ts b/packages/server/src/routes/mcpOAuthRoutes.ts
new file mode 100644
index 000000000..afdf2e852
--- /dev/null
+++ b/packages/server/src/routes/mcpOAuthRoutes.ts
@@ -0,0 +1,35 @@
+import { createRoute, z } from '@hono/zod-openapi';
+import { RequestErrorResponseSchema } from '../schemas/errors';
+
+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.'),
+ code: z.string().min(1).optional().describe('Authorization code, present when the user granted consent.'),
+ error: z
+ .string()
+ .optional()
+ .describe('OAuth error code, present instead of `code` if the user denied consent or the IdP errored.'),
+ error_description: z.string().optional(),
+});
+
+export const mcpOAuthCallbackRoute = createRoute({
+ method: 'get',
+ path: '/callback',
+ tags: [MCP_OAUTH_TAG],
+ summary: 'OAuth callback for MCP authorization',
+ // Browser-redirect target hit directly by the authorization server, never called by SDK.
+ 'x-fern-ignore': true,
+ request: {
+ query: McpOAuthCallbackQuerySchema,
+ },
+ responses: {
+ 302: {
+ description: 'Redirects to the original `redirect_url` on success, or a failure page if `error` was present.',
+ },
+ 400: {
+ content: { 'application/json': { schema: RequestErrorResponseSchema } },
+ description: 'Unknown or expired `state` (no matching pending authorization), or `code`/`error` both missing.',
+ },
+ },
+});
diff --git a/packages/server/src/routes/mcpRoutes.ts b/packages/server/src/routes/mcpRoutes.ts
index d07b604ed..8df46d513 100644
--- a/packages/server/src/routes/mcpRoutes.ts
+++ b/packages/server/src/routes/mcpRoutes.ts
@@ -4,9 +4,21 @@ import { McpServerEntrySchema } from '../store/schemas';
const MCP_SERVERS_TAG = 'MCP Servers';
+// Extends the yaml-validation schema with a response-only field — `auth_status` isn't a valid
+// mcp.yaml key, so it's added here rather than on McpServerEntrySchema itself.
+const McpServerResponseSchema = McpServerEntrySchema.extend({
+ auth_status: z
+ .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.',
+ ),
+}).openapi('McpServerEntry');
+
const ListMcpServersResponseSchema = z
.object({
- data: z.array(McpServerEntrySchema),
+ data: z.array(McpServerResponseSchema),
})
.openapi('ListMcpServersResponse');
@@ -15,7 +27,9 @@ export const listMcpServersRoute = createRoute({
path: '/',
tags: [MCP_SERVERS_TAG],
summary: 'List MCP servers',
- description: 'MCP servers declared in mcp.yaml. Auth headers are configured via env vars and never returned.',
+ description:
+ 'MCP servers declared in mcp.yaml, each with a passive auth_status snapshot. Auth headers are ' +
+ 'configured via env vars and never returned.',
'x-fern-sdk-group-name': ['mcp_servers'],
'x-fern-sdk-method-name': 'list',
responses: {
@@ -74,3 +88,41 @@ 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': ['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/store/schemas.ts b/packages/server/src/store/schemas.ts
index b7d51e804..eb8e220b7 100644
--- a/packages/server/src/store/schemas.ts
+++ b/packages/server/src/store/schemas.ts
@@ -67,13 +67,25 @@ export const ModelsFileSchema = z
uniqueEnvNames(file.models, ctx);
});
+export const McpServerAuthSettingsSchema = z
+ .discriminatedUnion('type', [z.object({ type: z.literal('dcr') })])
+ .openapi('McpServerAuthSettings');
+
export const McpServerEntrySchema = z
.object({
name: z.string().min(1),
url: z.string().url(),
+ auth: McpServerAuthSettingsSchema.optional(),
})
- .strict()
- .openapi('McpServerEntry');
+ .strict();
+
+/**
+ * `mcp_server.manifest` JSONB shape — the full mcp.yaml entry, including `name` (also kept as its
+ * own DB column for the uniqueness index — duplicated, not split out, so the manifest blob always
+ * round-trips the whole yaml entry as-is). Reuses `McpServerEntrySchema` directly rather than a
+ * hand-written type, so the DB's stored shape can never drift from the yaml-validated one.
+ */
+export const McpServerManifestSchema = McpServerEntrySchema;
export const McpFileSchema = z
.object({
@@ -110,5 +122,7 @@ export const SkillsFileSchema = z
});
export type ModelEntry = z.infer<typeof ModelEntrySchema>;
+export type McpServerAuthSettings = z.infer<typeof McpServerAuthSettingsSchema>;
export type McpServerEntry = z.infer<typeof McpServerEntrySchema>;
+export type McpServerManifest = z.infer<typeof McpServerManifestSchema>;
export type SkillEntry = z.infer<typeof SkillEntrySchema>;