Skip to content

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

feat: add helper method for mcp dcr auth (#28)

Sujai Kumar Guptacc3227316641
diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.ts
index 71254f4b8..96d1b7b4d 100644
--- a/packages/harness/src/core/index.ts
+++ b/packages/harness/src/core/index.ts
@@ -135,6 +135,29 @@ export type {
export { AgentHarnessError, McpConnectionError } from './errors';
export { extractErrorLogFields } from './util/errorLogFields';
+// MCP OAuth / DCR (token store contract + registration + auth URL + resolve)
+export {
+ DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
+ InMemoryMcpTokenStore,
+ MCP_OAUTH_CALLBACK_PATH,
+ McpAuthStatus,
+ buildMcpAuthorizationUrl,
+ createMcpOAuthClient,
+ ensureMcpClientRegistered,
+ mcpAuthorizationServerMetadata,
+ mcpAuthorizationServerOrigin,
+ mcpClientInformation,
+ mcpOAuthCallbackUrl,
+ resolveMcpAuth,
+} from './mcp/auth';
+export type {
+ IMcpTokenStore,
+ McpOAuthClientRecord,
+ McpOAuthPendingAuthorization,
+ McpOAuthToken,
+ ResolveMcpAuthResult,
+} from './mcp/auth';
+
// Sandbox (concrete implementation; provider details exported for composition)
export {
DaytonaSandboxProviderSettingsSchema,
diff --git a/packages/harness/src/core/mcp/auth/IMcpTokenStore.ts b/packages/harness/src/core/mcp/auth/IMcpTokenStore.ts
new file mode 100644
index 000000000..ba5150899
--- /dev/null
+++ b/packages/harness/src/core/mcp/auth/IMcpTokenStore.ts
@@ -0,0 +1,25 @@
+/**
+ * Pure state store for MCP OAuth. One logical (server) row set keyed by mcp_server.id.
+ * Implementations: Postgres/SQLite later; InMemory for tests/dev.
+ */
+import type { McpOAuthClientRecord, McpOAuthPendingAuthorization, McpOAuthToken } from './types';
+
+export interface IMcpTokenStore {
+ saveOAuthClient(params: { serverId: string; record: McpOAuthClientRecord }): Promise<void>;
+
+ getOAuthClient(params: { serverId: string }): Promise<McpOAuthClientRecord | undefined>;
+
+ savePendingAuthorization(pending: McpOAuthPendingAuthorization): Promise<void>;
+
+ getPendingAuthorization(params: { state: string }): Promise<McpOAuthPendingAuthorization | undefined>;
+
+ saveToken(params: { serverId: string; token: McpOAuthToken }): Promise<void>;
+
+ getToken(params: { serverId: string }): Promise<McpOAuthToken | undefined>;
+
+ /** Drops token only (keeps DCR client for re-authorization). */
+ deleteToken(params: { serverId: string }): Promise<void>;
+
+ /** Clears client, token, and pending rows for this MCP server id. */
+ delete(params: { serverId: string }): Promise<void>;
+}
diff --git a/packages/harness/src/core/mcp/auth/InMemoryMcpTokenStore.ts b/packages/harness/src/core/mcp/auth/InMemoryMcpTokenStore.ts
new file mode 100644
index 000000000..613d60f15
--- /dev/null
+++ b/packages/harness/src/core/mcp/auth/InMemoryMcpTokenStore.ts
@@ -0,0 +1,48 @@
+import type { IMcpTokenStore } from './IMcpTokenStore';
+import type { McpOAuthClientRecord, McpOAuthPendingAuthorization, McpOAuthToken } from './types';
+
+/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async for IMcpTokenStore callers */
+export class InMemoryMcpTokenStore implements IMcpTokenStore {
+ private readonly clients = new Map<string, McpOAuthClientRecord>();
+ private readonly tokens = new Map<string, McpOAuthToken>();
+ private readonly pending = new Map<string, McpOAuthPendingAuthorization>();
+
+ async saveOAuthClient(params: { serverId: string; record: McpOAuthClientRecord }): Promise<void> {
+ this.clients.set(params.serverId, params.record);
+ }
+
+ async getOAuthClient(params: { serverId: string }): Promise<McpOAuthClientRecord | undefined> {
+ return this.clients.get(params.serverId);
+ }
+
+ async savePendingAuthorization(pending: McpOAuthPendingAuthorization): Promise<void> {
+ this.pending.set(pending.state, pending);
+ }
+
+ async getPendingAuthorization(params: { state: string }): Promise<McpOAuthPendingAuthorization | undefined> {
+ return this.pending.get(params.state);
+ }
+
+ async saveToken(params: { serverId: string; token: McpOAuthToken }): Promise<void> {
+ this.tokens.set(params.serverId, params.token);
+ }
+
+ async getToken(params: { serverId: string }): Promise<McpOAuthToken | undefined> {
+ return this.tokens.get(params.serverId);
+ }
+
+ async deleteToken(params: { serverId: string }): Promise<void> {
+ this.tokens.delete(params.serverId);
+ }
+
+ async delete(params: { serverId: string }): Promise<void> {
+ this.clients.delete(params.serverId);
+ this.tokens.delete(params.serverId);
+ for (const [state, row] of this.pending) {
+ if (row.serverId === params.serverId) {
+ this.pending.delete(state);
+ }
+ }
+ }
+}
+/* eslint-enable @typescript-eslint/require-await */
diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.ts
new file mode 100644
index 000000000..c3693311f
--- /dev/null
+++ b/packages/harness/src/core/mcp/auth/index.ts
@@ -0,0 +1,19 @@
+export type { IMcpTokenStore } from './IMcpTokenStore';
+export { InMemoryMcpTokenStore } from './InMemoryMcpTokenStore';
+export {
+ DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
+ buildMcpAuthorizationUrl,
+ createMcpOAuthClient,
+ ensureMcpClientRegistered,
+ resolveMcpAuth,
+} from './mcpDcr';
+export type { ResolveMcpAuthResult } from './mcpDcr';
+export {
+ MCP_OAUTH_CALLBACK_PATH,
+ mcpAuthorizationServerMetadata,
+ mcpAuthorizationServerOrigin,
+ mcpClientInformation,
+ mcpOAuthCallbackUrl,
+} from './mcpOAuthHelpers';
+export { McpAuthStatus } from './types';
+export type { McpOAuthClientRecord, McpOAuthPendingAuthorization, McpOAuthToken } from './types';
diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/harness/src/core/mcp/auth/mcpDcr.ts
new file mode 100644
index 000000000..6f894a335
--- /dev/null
+++ b/packages/harness/src/core/mcp/auth/mcpDcr.ts
@@ -0,0 +1,267 @@
+import {
+ discoverOAuthServerInfo,
+ refreshAuthorization,
+ registerClient,
+ startAuthorization,
+} from '@modelcontextprotocol/sdk/client/auth.js';
+import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';
+import type {
+ AuthorizationServerMetadata,
+ OAuthClientMetadata,
+ OAuthTokens,
+} from '@modelcontextprotocol/sdk/shared/auth.js';
+import { randomBytes } from 'node:crypto';
+import { McpConnectionError } from '../../errors';
+import type { IMcpTokenStore } from './IMcpTokenStore';
+import {
+ mcpAuthorizationServerMetadata,
+ mcpAuthorizationServerOrigin,
+ mcpClientInformation,
+ mcpOAuthCallbackUrl,
+} from './mcpOAuthHelpers';
+import { McpAuthStatus, type McpOAuthClientRecord, type McpOAuthToken } from './types';
+
+export type ResolveMcpAuthResult =
+ | { status: McpAuthStatus.Authenticated; headers: Record<string, string> }
+ | { status: McpAuthStatus.AuthenticationRequired; authUrl: URL };
+
+/**
+ * When the token response omits `expires_in` (allowed by RFC 6749), use a 1h TTL so
+ * the saved token is not treated as already expired on the next `resolveMcpAuth`.
+ */
+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.
+ */
+async function registerMcpClientWithAuthMethodFallback(params: {
+ authorizationServerUrl: string;
+ metadata: AuthorizationServerMetadata;
+ clientMetadata: OAuthClientMetadata;
+ mcpServerName: string;
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+}): Promise<McpOAuthClientRecord> {
+ const { authorizationServerUrl, metadata, clientMetadata, mcpServerName, authorizationEndpoint, tokenEndpoint } =
+ params;
+
+ let fullInfo;
+ try {
+ fullInfo = await registerClient(authorizationServerUrl, {
+ metadata,
+ clientMetadata: { ...clientMetadata, token_endpoint_auth_method: 'client_secret_post' },
+ });
+ } catch (firstError: unknown) {
+ try {
+ // Omit method so the authorization server applies its default (parity with servicefoundry).
+ fullInfo = await registerClient(authorizationServerUrl, {
+ metadata,
+ clientMetadata,
+ });
+ } catch (secondError: unknown) {
+ throw new McpConnectionError(
+ `Failed to dynamically register OAuth client for MCP server '${mcpServerName}'`,
+ 400,
+ { cause: secondError instanceof Error ? secondError : firstError },
+ );
+ }
+ }
+
+ if (!fullInfo.client_id) {
+ throw new McpConnectionError(
+ `Authorization server for MCP server '${mcpServerName}' returned a registration response without client_id`,
+ 400,
+ );
+ }
+
+ return {
+ clientId: fullInfo.client_id,
+ clientSecret: fullInfo.client_secret ?? null,
+ authorizationEndpoint,
+ tokenEndpoint,
+ codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? null,
+ };
+}
+
+export async function createMcpOAuthClient(params: {
+ mcpServerUrl: string;
+ mcpServerName: string;
+ redirectUri: string;
+ clientName: string;
+}): Promise<McpOAuthClientRecord> {
+ const { mcpServerUrl, mcpServerName, redirectUri, clientName } = params;
+
+ const { authorizationServerUrl, authorizationServerMetadata: metadata } = await discoverOAuthServerInfo(mcpServerUrl);
+
+ if (!metadata?.registration_endpoint) {
+ throw new McpConnectionError(
+ `MCP server '${mcpServerName}' has no DCR support (missing registration_endpoint); auth.type: dcr is misconfigured for this server`,
+ 400,
+ );
+ }
+
+ if (!metadata.authorization_endpoint || !metadata.token_endpoint) {
+ throw new McpConnectionError(
+ `Authorization server for MCP server '${mcpServerName}' is missing authorization_endpoint or token_endpoint`,
+ 400,
+ );
+ }
+
+ return registerMcpClientWithAuthMethodFallback({
+ authorizationServerUrl,
+ metadata,
+ clientMetadata: {
+ client_name: clientName,
+ redirect_uris: [redirectUri],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ },
+ mcpServerName,
+ authorizationEndpoint: metadata.authorization_endpoint,
+ tokenEndpoint: metadata.token_endpoint,
+ });
+}
+
+export async function ensureMcpClientRegistered(params: {
+ tokenStore: IMcpTokenStore;
+ serverId: string;
+ mcpServerUrl: string;
+ mcpServerName: string;
+ publicBaseUrl: string;
+ clientName: string;
+}): Promise<McpOAuthClientRecord> {
+ const existing = await params.tokenStore.getOAuthClient({ serverId: params.serverId });
+ if (existing) {
+ return existing;
+ }
+
+ const record = await createMcpOAuthClient({
+ mcpServerUrl: params.mcpServerUrl,
+ mcpServerName: params.mcpServerName,
+ redirectUri: mcpOAuthCallbackUrl(params.publicBaseUrl),
+ clientName: params.clientName,
+ });
+
+ await params.tokenStore.saveOAuthClient({ serverId: params.serverId, record });
+ return record;
+}
+
+export async function buildMcpAuthorizationUrl(params: {
+ tokenStore: IMcpTokenStore;
+ serverId: string;
+ mcpServerUrl: string;
+ mcpServerName: string;
+ publicBaseUrl: string;
+ clientName: string;
+ /** FE post-OAuth landing URL (not the OAuth redirect_uri). */
+ redirectUrl?: string;
+}): Promise<URL> {
+ const client = await ensureMcpClientRegistered({
+ tokenStore: params.tokenStore,
+ serverId: params.serverId,
+ mcpServerUrl: params.mcpServerUrl,
+ mcpServerName: params.mcpServerName,
+ publicBaseUrl: params.publicBaseUrl,
+ clientName: params.clientName,
+ });
+
+ // CSRF correlation: opaque state is the pending-row primary key.
+ const state = randomBytes(32).toString('base64url');
+ const { authorizationUrl, codeVerifier } = await startAuthorization(mcpAuthorizationServerOrigin(client), {
+ metadata: mcpAuthorizationServerMetadata(client),
+ clientInformation: mcpClientInformation(client),
+ redirectUrl: mcpOAuthCallbackUrl(params.publicBaseUrl),
+ resource: resourceUrlFromServerUrl(params.mcpServerUrl),
+ state,
+ });
+
+ await params.tokenStore.savePendingAuthorization({
+ state,
+ serverId: params.serverId,
+ codeVerifier,
+ redirectUrl: params.redirectUrl ?? null,
+ });
+
+ return authorizationUrl;
+}
+
+function isMcpAccessTokenUsable(expiresAtIso: string, nowMs: number): boolean {
+ const expiresAtMs = Date.parse(expiresAtIso);
+ return !Number.isNaN(expiresAtMs) && expiresAtMs > nowMs;
+}
+
+function oauthTokensToMcpOAuthToken(
+ tokens: OAuthTokens,
+ nowMs: number,
+ fallbackRefreshToken: string | null,
+): McpOAuthToken {
+ const expiresInSeconds = tokens.expires_in ?? DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS;
+ const expiresAtMs = nowMs + expiresInSeconds * 1000;
+ return {
+ accessToken: tokens.access_token,
+ refreshToken: tokens.refresh_token ?? fallbackRefreshToken,
+ expiresAt: new Date(expiresAtMs).toISOString(),
+ scope: tokens.scope ?? null,
+ };
+}
+
+export async function resolveMcpAuth(params: {
+ tokenStore: IMcpTokenStore;
+ serverId: string;
+ mcpServerUrl: string;
+ mcpServerName: string;
+ publicBaseUrl: string;
+ clientName: string;
+ /** FE post-OAuth landing URL (not the OAuth redirect_uri). */
+ redirectUrl?: string;
+ nowMs?: number;
+}): Promise<ResolveMcpAuthResult> {
+ const nowMs = params.nowMs ?? Date.now();
+ const token = await params.tokenStore.getToken({ serverId: params.serverId });
+
+ if (token && isMcpAccessTokenUsable(token.expiresAt, nowMs)) {
+ return {
+ status: McpAuthStatus.Authenticated,
+ headers: { Authorization: `Bearer ${token.accessToken}` },
+ };
+ }
+
+ if (token?.refreshToken) {
+ const client = await params.tokenStore.getOAuthClient({ serverId: params.serverId });
+ if (client) {
+ try {
+ const refreshed = await refreshAuthorization(mcpAuthorizationServerOrigin(client), {
+ metadata: mcpAuthorizationServerMetadata(client),
+ clientInformation: mcpClientInformation(client),
+ refreshToken: token.refreshToken,
+ resource: resourceUrlFromServerUrl(params.mcpServerUrl),
+ });
+ const saved = oauthTokensToMcpOAuthToken(refreshed, nowMs, token.refreshToken);
+ await params.tokenStore.saveToken({ serverId: params.serverId, token: saved });
+ return {
+ status: McpAuthStatus.Authenticated,
+ headers: { Authorization: `Bearer ${saved.accessToken}` },
+ };
+ } catch {
+ // Any refresh failure → full re-authorize (do not inspect the error).
+ }
+ }
+ }
+
+ if (token) {
+ await params.tokenStore.deleteToken({ serverId: params.serverId });
+ }
+
+ const authUrl = await buildMcpAuthorizationUrl({
+ tokenStore: params.tokenStore,
+ serverId: params.serverId,
+ mcpServerUrl: params.mcpServerUrl,
+ mcpServerName: params.mcpServerName,
+ publicBaseUrl: params.publicBaseUrl,
+ clientName: params.clientName,
+ ...(params.redirectUrl !== undefined ? { redirectUrl: params.redirectUrl } : {}),
+ });
+ return { status: McpAuthStatus.AuthenticationRequired, authUrl };
+}
diff --git a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts
new file mode 100644
index 000000000..0fca1cc86
--- /dev/null
+++ b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts
@@ -0,0 +1,55 @@
+/**
+ * Shared MCP OAuth URL / client-metadata helpers.
+ * Protocol work stays in the MCP SDK (`client/auth.js`).
+ */
+import type {
+ AuthorizationServerMetadata,
+ OAuthClientInformationMixed,
+} from '@modelcontextprotocol/sdk/shared/auth.js';
+import { McpConnectionError } from '../../errors';
+import type { McpOAuthClientRecord } from './types';
+
+/** Fixed OAuth callback path for every MCP server (matches server mount). */
+export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-servers/oauth/callback';
+
+/** OAuth callback redirect_uri = publicBaseUrl + fixed path. No trimming of the base. */
+export function mcpOAuthCallbackUrl(publicBaseUrl: string): string {
+ if (publicBaseUrl === '') {
+ throw new McpConnectionError('PUBLIC_BASE_URL is required for MCP OAuth registration but was empty', 500);
+ }
+ return `${publicBaseUrl}${MCP_OAUTH_CALLBACK_PATH}`;
+}
+
+/** Client info for SDK token / authorize calls.
+ * Same policy as servicefoundry outbound: form-body secret when present (client_secret_post),
+ * otherwise public (none). Method is not stored on the client record.
+ */
+export function mcpClientInformation(client: McpOAuthClientRecord): OAuthClientInformationMixed {
+ return client.clientSecret !== null
+ ? {
+ client_id: client.clientId,
+ client_secret: client.clientSecret,
+ token_endpoint_auth_method: 'client_secret_post',
+ }
+ : {
+ client_id: client.clientId,
+ token_endpoint_auth_method: 'none',
+ };
+}
+
+/** Reconstruct authorization-server metadata enough for startAuthorization / token calls. */
+export function mcpAuthorizationServerMetadata(client: McpOAuthClientRecord): AuthorizationServerMetadata {
+ return {
+ issuer: new URL(client.authorizationEndpoint).origin,
+ authorization_endpoint: client.authorizationEndpoint,
+ token_endpoint: client.tokenEndpoint,
+ response_types_supported: ['code'],
+ ...(client.codeChallengeMethodsSupported !== null
+ ? { code_challenge_methods_supported: client.codeChallengeMethodsSupported }
+ : {}),
+ };
+}
+
+export function mcpAuthorizationServerOrigin(client: McpOAuthClientRecord): string {
+ return new URL(client.authorizationEndpoint).origin;
+}
diff --git a/packages/harness/src/core/mcp/auth/types.ts b/packages/harness/src/core/mcp/auth/types.ts
new file mode 100644
index 000000000..09f393546
--- /dev/null
+++ b/packages/harness/src/core/mcp/auth/types.ts
@@ -0,0 +1,42 @@
+/**
+ * Runtime shapes used by MCP OAuth helpers and {@link IMcpTokenStore}.
+ * Not the DB source of truth — server column JSON lives in
+ * `packages/server/src/db/mcpOAuthTypes.ts`.
+ *
+ * Store records use explicit `null` for absence (see packages/harness/AGENTS.md).
+ */
+
+export enum McpAuthStatus {
+ Authenticated = 'authenticated',
+ AuthenticationRequired = 'authentication_required',
+}
+
+/** Discovered/cached authorization-server endpoints used by DCR and authorize. */
+export interface McpOAuthClientRecord {
+ clientId: string;
+ clientSecret: string | null;
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+ codeChallengeMethodsSupported: string[] | null;
+}
+
+/** Access token returned by the authorization code exchange. */
+export interface McpOAuthToken {
+ accessToken: string;
+ refreshToken: string | null;
+ /** ISO 8601 */
+ expiresAt: string;
+ scope: string | null;
+}
+
+/**
+ * Pending PKCE authorization. `state` is the OAuth `state` param / pending-row id;
+ * `serverId` is the MCP server id.
+ */
+export interface McpOAuthPendingAuthorization {
+ state: string;
+ serverId: string;
+ codeVerifier: string | null;
+ /** FE post-OAuth landing URL (not the OAuth redirect_uri). */
+ redirectUrl: string | null;
+}
diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts
new file mode 100644
index 000000000..a49c52d4a
--- /dev/null
+++ b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts
@@ -0,0 +1,479 @@
+/**
+ * MCP OAuth / DCR helper tests (node:test style via jest).
+ * Global fetch is stubbed; production code uses real fetch only.
+ */
+import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';
+import {
+ DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
+ InMemoryMcpTokenStore,
+ McpAuthStatus,
+ McpConnectionError,
+ buildMcpAuthorizationUrl,
+ createMcpOAuthClient,
+ ensureMcpClientRegistered,
+ mcpOAuthCallbackUrl,
+ resolveMcpAuth,
+ type McpOAuthClientRecord,
+} from '../../../../src/core';
+
+const PUBLIC_BASE_URL = 'https://harness.example.com';
+const CLIENT_NAME = 'harness';
+const SERVER_URL = 'https://mcp.example.com/sse';
+const AS_ORIGIN = 'https://auth.example.com';
+const SERVER_ID = 'mcp-server-id-1';
+const SERVER_NAME = 'svc';
+
+const realFetch = globalThis.fetch;
+
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+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 stubOauthFetch(options: {
+ registrationFailFirst?: boolean;
+ registrationFailAlways?: boolean;
+ skipRegistrationEndpoint?: boolean;
+ 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;
+}): {
+ registerBodies: unknown[];
+ registerCallCount: () => number;
+ tokenBodies: unknown[];
+ tokenAuthHeaders: string[];
+} {
+ let registerCalls = 0;
+ const registerBodies: unknown[] = [];
+ const tokenBodies: unknown[] = [];
+ const tokenAuthHeaders: string[] = [];
+ const registered = options.registeredClient ?? {
+ client_id: 'dyn-client-1',
+ client_secret: 'dyn-secret-1',
+ token_endpoint_auth_method: 'client_secret_post',
+ };
+
+ globalThis.fetch = (async (input, init) => {
+ const url = String(input);
+
+ if (url.includes('oauth-protected-resource')) {
+ return json({ resource: SERVER_URL, authorization_servers: [AS_ORIGIN] });
+ }
+
+ 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;
+ return json(metadata);
+ }
+
+ if (url === `${AS_ORIGIN}/register` && init?.method === 'POST') {
+ registerCalls += 1;
+ registerBodies.push(JSON.parse(String(init.body)));
+ if (options.registrationFailAlways || (options.registrationFailFirst && registerCalls === 1)) {
+ return json({ error: 'invalid_client_metadata' }, 400);
+ }
+ return json({
+ ...registered,
+ redirect_uris: [mcpOAuthCallbackUrl(PUBLIC_BASE_URL)],
+ grant_types: ['authorization_code', 'refresh_token'],
+ response_types: ['code'],
+ });
+ }
+
+ if (url === `${AS_ORIGIN}/token` && init?.method === 'POST') {
+ tokenBodies.push(String(init.body));
+ const headers = new Headers(init.headers);
+ tokenAuthHeaders.push(headers.get('Authorization') ?? '');
+ if (options.tokenFail) {
+ return json({ error: 'invalid_grant' }, 400);
+ }
+ const tokens = options.tokenResponse ?? {
+ access_token: 'refreshed-access',
+ refresh_token: 'refreshed-refresh',
+ expires_in: 3600,
+ token_type: 'Bearer',
+ };
+ return json({ token_type: 'Bearer', ...tokens });
+ }
+
+ return new Response(`unexpected url: ${url}`, { status: 404 });
+ }) as typeof fetch;
+
+ return { registerBodies, registerCallCount: () => registerCalls, tokenBodies, tokenAuthHeaders };
+}
+
+const sampleClient: McpOAuthClientRecord = {
+ clientId: 'cached-client',
+ clientSecret: 'cached-secret',
+ authorizationEndpoint: `${AS_ORIGIN}/authorize`,
+ tokenEndpoint: `${AS_ORIGIN}/token`,
+ codeChallengeMethodsSupported: ['S256'],
+};
+
+describe('resourceUrlFromServerUrl (SDK)', () => {
+ it('strips fragment (RFC 8707 resource indicator)', () => {
+ const resource = resourceUrlFromServerUrl('https://mcp.example.com/sse#frag');
+ expect(resource.hash).toBe('');
+ expect(resource.pathname).toBe('/sse');
+ });
+});
+
+describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
+ it('returns the cached client without discovery or registration', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ const { registerCallCount } = stubOauthFetch({});
+
+ const result = await ensureMcpClientRegistered({
+ tokenStore: store,
+ serverId: SERVER_ID,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: PUBLIC_BASE_URL,
+ clientName: CLIENT_NAME,
+ });
+
+ expect(result).toEqual(sampleClient);
+ expect(registerCallCount()).toBe(0);
+ });
+
+ it('discovers, registers confidential client, and saves the record', async () => {
+ const store = new InMemoryMcpTokenStore();
+ const { registerBodies } = stubOauthFetch({});
+
+ const result = await ensureMcpClientRegistered({
+ tokenStore: store,
+ serverId: SERVER_ID,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: PUBLIC_BASE_URL,
+ clientName: CLIENT_NAME,
+ });
+
+ expect(result.clientId).toBe('dyn-client-1');
+ expect(result.clientSecret).toBe('dyn-secret-1');
+ expect(result.authorizationEndpoint).toBe(`${AS_ORIGIN}/authorize`);
+ expect(result.tokenEndpoint).toBe(`${AS_ORIGIN}/token`);
+ expect(result.codeChallengeMethodsSupported).toEqual(['S256']);
+ expect(registerBodies).toHaveLength(1);
+ const body = registerBodies[0] as Record<string, unknown>;
+ expect(body['token_endpoint_auth_method']).toBe('client_secret_post');
+ expect(body['grant_types']).toEqual(['authorization_code', 'refresh_token']);
+ expect(body['client_name']).toBe(CLIENT_NAME);
+ expect(body['redirect_uris']).toEqual([mcpOAuthCallbackUrl(PUBLIC_BASE_URL)]);
+ });
+
+ it('retries registration without token_endpoint_auth_method when the first attempt fails', async () => {
+ const store = new InMemoryMcpTokenStore();
+ const { registerBodies, registerCallCount } = stubOauthFetch({
+ registrationFailFirst: true,
+ registeredClient: { client_id: 'public-client' },
+ });
+
+ const result = await ensureMcpClientRegistered({
+ tokenStore: store,
+ serverId: SERVER_ID,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: PUBLIC_BASE_URL,
+ clientName: CLIENT_NAME,
+ });
+
+ expect(result.clientId).toBe('public-client');
+ expect(result.clientSecret).toBeNull();
+ expect(registerCallCount()).toBe(2);
+ expect((registerBodies[0] as Record<string, unknown>)['token_endpoint_auth_method']).toBe('client_secret_post');
+ expect((registerBodies[1] as Record<string, unknown>)['token_endpoint_auth_method']).toBeUndefined();
+ });
+
+ it('throws when the AS has no registration_endpoint', async () => {
+ const store = new InMemoryMcpTokenStore();
+ stubOauthFetch({ skipRegistrationEndpoint: true });
+
+ await expect(
+ ensureMcpClientRegistered({
+ tokenStore: store,
+ serverId: SERVER_ID,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: PUBLIC_BASE_URL,
+ clientName: CLIENT_NAME,
+ }),
+ ).rejects.toMatchObject({
+ name: 'McpConnectionError',
+ message: expect.stringContaining('no DCR support'),
+ });
+ });
+
+ it('does not save a client when both registration attempts fail', async () => {
+ const store = new InMemoryMcpTokenStore();
+ const { registerCallCount } = stubOauthFetch({ registrationFailAlways: true });
+
+ await expect(
+ createMcpOAuthClient({
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ redirectUri: mcpOAuthCallbackUrl(PUBLIC_BASE_URL),
+ clientName: CLIENT_NAME,
+ }),
+ ).rejects.toBeInstanceOf(McpConnectionError);
+ expect(registerCallCount()).toBe(2);
+ expect(await store.getOAuthClient({ serverId: SERVER_ID })).toBeUndefined();
+ });
+
+ it('throws when publicBaseUrl is empty (no trimming)', async () => {
+ await expect(
+ ensureMcpClientRegistered({
+ tokenStore: new InMemoryMcpTokenStore(),
+ serverId: SERVER_ID,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: '',
+ clientName: CLIENT_NAME,
+ }),
+ ).rejects.toMatchObject({ message: expect.stringContaining('PUBLIC_BASE_URL') });
+ });
+});
+
+describe('buildMcpAuthorizationUrl', () => {
+ it('saves pending authorization with state and returns a URL object', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ stubOauthFetch({});
+
+ const authUrl = await buildMcpAuthorizationUrl({
+ tokenStore: store,
+ serverId: SERVER_ID,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: PUBLIC_BASE_URL,
+ clientName: CLIENT_NAME,
+ redirectUrl: 'https://app.example.com/after',
+ });
+
+ expect(authUrl).toBeInstanceOf(URL);
+ expect(authUrl.origin + authUrl.pathname).toBe(`${AS_ORIGIN}/authorize`);
+ expect(authUrl.searchParams.get('client_id')).toBe(sampleClient.clientId);
+ expect(authUrl.searchParams.get('redirect_uri')).toBe(mcpOAuthCallbackUrl(PUBLIC_BASE_URL));
+ expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');
+ expect(authUrl.searchParams.get('code_challenge')).toBeTruthy();
+ expect(authUrl.searchParams.get('resource')).toBe(resourceUrlFromServerUrl(SERVER_URL).href);
+
+ const state = authUrl.searchParams.get('state');
+ expect(state).toBeTruthy();
+ const pending = await store.getPendingAuthorization({ state: state! });
+ expect(pending).toMatchObject({
+ state,
+ serverId: SERVER_ID,
+ redirectUrl: 'https://app.example.com/after',
+ });
+ expect(pending?.codeVerifier).toBeTruthy();
+ });
+});
+
+const resolveParams = (store: InMemoryMcpTokenStore, mcpServerUrl = SERVER_URL) => ({
+ tokenStore: store,
+ serverId: SERVER_ID,
+ mcpServerUrl,
+ mcpServerName: SERVER_NAME,
+ publicBaseUrl: PUBLIC_BASE_URL,
+ clientName: CLIENT_NAME,
+});
+
+describe('resolveMcpAuth', () => {
+ it('returns bearer headers when the token is still valid', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveToken({
+ serverId: SERVER_ID,
+ token: {
+ accessToken: 'live-token',
+ refreshToken: null,
+ expiresAt: new Date(Date.now() + 10 * 60_000).toISOString(),
+ scope: null,
+ },
+ });
+
+ const result = await resolveMcpAuth(resolveParams(store));
+
+ expect(result).toEqual({
+ status: McpAuthStatus.Authenticated,
+ headers: { Authorization: 'Bearer live-token' },
+ });
+ });
+
+ it('refreshes an expired token when a refresh_token is stored', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ await store.saveToken({
+ serverId: SERVER_ID,
+ token: {
+ accessToken: 'old-access',
+ refreshToken: 'old-refresh',
+ expiresAt: new Date(Date.now() - 1000).toISOString(),
+ scope: null,
+ },
+ });
+ const { tokenBodies, tokenAuthHeaders } = stubOauthFetch({
+ tokenResponse: {
+ access_token: 'new-access',
+ refresh_token: 'new-refresh',
+ expires_in: 3600,
+ token_type: 'Bearer',
+ },
+ });
+
+ const result = await resolveMcpAuth(resolveParams(store));
+
+ expect(result).toEqual({
+ status: McpAuthStatus.Authenticated,
+ headers: { Authorization: 'Bearer new-access' },
+ });
+ expect(tokenBodies).toHaveLength(1);
+ expect(String(tokenBodies[0])).toContain('grant_type=refresh_token');
+ // Secret present → client_secret_post (form body), not HTTP Basic.
+ expect(String(tokenBodies[0])).toContain('client_secret=cached-secret');
+ expect(tokenAuthHeaders[0]).toBe('');
+ const saved = await store.getToken({ serverId: SERVER_ID });
+ expect(saved?.accessToken).toBe('new-access');
+ expect(saved?.refreshToken).toBe('new-refresh');
+ });
+
+ it('uses a default TTL when the token response omits expires_in', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ await store.saveToken({
+ serverId: SERVER_ID,
+ token: {
+ accessToken: 'old-access',
+ refreshToken: 'old-refresh',
+ expiresAt: new Date(Date.now() - 1000).toISOString(),
+ scope: null,
+ },
+ });
+ const nowMs = Date.now();
+ stubOauthFetch({
+ tokenResponse: {
+ access_token: 'new-access',
+ refresh_token: 'new-refresh',
+ token_type: 'Bearer',
+ },
+ });
+
+ const result = await resolveMcpAuth({ ...resolveParams(store), nowMs });
+
+ expect(result).toEqual({
+ status: McpAuthStatus.Authenticated,
+ headers: { Authorization: 'Bearer new-access' },
+ });
+ const saved = await store.getToken({ serverId: SERVER_ID });
+ expect(saved?.expiresAt).toBe(new Date(nowMs + DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS * 1000).toISOString());
+ // Still usable on the next resolve with a slightly later clock.
+ const again = await resolveMcpAuth({ ...resolveParams(store), nowMs: nowMs + 1_000 });
+ expect(again).toEqual({
+ status: McpAuthStatus.Authenticated,
+ headers: { Authorization: 'Bearer new-access' },
+ });
+ });
+
+ it('returns authentication_required and clears token when refresh fails', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ await store.saveToken({
+ serverId: SERVER_ID,
+ token: {
+ accessToken: 'old-access',
+ refreshToken: 'old-refresh',
+ expiresAt: new Date(Date.now() - 1000).toISOString(),
+ scope: null,
+ },
+ });
+ stubOauthFetch({ tokenFail: true });
+
+ const result = await resolveMcpAuth(resolveParams(store));
+
+ expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
+ if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(result.authUrl).toBeInstanceOf(URL);
+ expect(await store.getToken({ serverId: SERVER_ID })).toBeUndefined();
+ expect(await store.getOAuthClient({ serverId: SERVER_ID })).toEqual(sampleClient);
+ });
+
+ it('returns authentication_required and clears expired token without refresh_token', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ await store.saveToken({
+ serverId: SERVER_ID,
+ token: {
+ accessToken: 'old-access',
+ refreshToken: null,
+ expiresAt: new Date(Date.now() - 1000).toISOString(),
+ scope: null,
+ },
+ });
+ stubOauthFetch({});
+
+ const result = await resolveMcpAuth(resolveParams(store));
+
+ expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
+ if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(result.authUrl).toBeInstanceOf(URL);
+ expect(result.authUrl.href).toContain('/authorize');
+ expect(await store.getToken({ serverId: SERVER_ID })).toBeUndefined();
+ expect(await store.getOAuthClient({ serverId: SERVER_ID })).toEqual(sampleClient);
+ });
+
+ it('returns authentication_required when no token exists', async () => {
+ const store = new InMemoryMcpTokenStore();
+ await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ stubOauthFetch({});
+
+ const result = await resolveMcpAuth(resolveParams(store));
+
+ expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
+ if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(result.authUrl.searchParams.get('state')).toBeTruthy();
+ });
+});
+
+describe('end-to-end DCR + authorize with normalised MCP URL', () => {
+ it('registers, builds auth URL with resource, and resolves auth_required without a token', async () => {
+ // Mixed-case scheme/host + fragment: resource indicator must still be RFC-8707-safe.
+ const mixedUrl = 'HTTPS://MCP.Example.COM/sse#fragment';
+ const store = new InMemoryMcpTokenStore();
+ const { registerBodies } = stubOauthFetch({});
+
+ const result = await resolveMcpAuth(resolveParams(store, mixedUrl));
+
+ expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
+ if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+
+ expect(registerBodies).toHaveLength(1);
+ const client = await store.getOAuthClient({ serverId: SERVER_ID });
+ expect(client?.clientId).toBe('dyn-client-1');
+
+ const url = result.authUrl;
+ expect(url.searchParams.get('state')).toBeTruthy();
+ expect(url.searchParams.get('code_challenge_method')).toBe('S256');
+ // Fragment stripped; resource is absolute URL for this MCP server.
+ expect(url.searchParams.get('resource')).toBe(resourceUrlFromServerUrl(mixedUrl).href);
+ expect(url.searchParams.get('resource')).not.toContain('#');
+ });
+});
diff --git a/packages/server/.env.example b/packages/server/.env.example
index e2110da97..72adb0300 100644
--- a/packages/server/.env.example
+++ b/packages/server/.env.example
@@ -58,6 +58,14 @@ MODEL_API_KEY=<your-api-key>
# MCP_HEADERS={"Authorization":"Bearer <mcp-token>"}
# MCP_GITHUB_HEADERS={"Authorization":"Bearer <github-mcp-token>"}
+# ---------------------------------------------------------------------------
+# MCP OAuth (DCR). PUBLIC_BASE_URL is required — origin of the fixed callback route
+# {PUBLIC_BASE_URL}/api/v1/mcp-servers/oauth/callback (not trimmed). OAUTH_CLIENT_NAME is
+# the RFC 7591 client_name on the consent screen (default: truefoundry-harness).
+# ---------------------------------------------------------------------------
+PUBLIC_BASE_URL=http://localhost:8790
+# OAUTH_CLIENT_NAME=truefoundry-harness
+
# ---------------------------------------------------------------------------
# Sandbox (optional). When unset, agent specs with config.sandbox.enabled are
# rejected at session creation.
diff --git a/packages/server/.env.test b/packages/server/.env.test
index 2de9f673d..1b4b253c3 100644
--- a/packages/server/.env.test
+++ b/packages/server/.env.test
@@ -6,3 +6,5 @@ POSTGRES_HOST=localhost
POSTGRES_PORT=5432
MODEL_API_KEY=test
REGISTRY_DIR=registry-example
+PUBLIC_BASE_URL=https://harness.example.com
+OAUTH_CLIENT_NAME=truefoundry-harness
diff --git a/packages/server/src/config.ts b/packages/server/src/config.ts
index ddbe87b04..f36f58fbe 100644
--- a/packages/server/src/config.ts
+++ b/packages/server/src/config.ts
@@ -256,6 +256,17 @@ export interface ServerConfiguration {
* Env: `MCP_{NAME}_HEADERS` (see `normalizeEnvName`).
*/
MCP_HEADERS_BY_NAME: Record<string, Record<string, string>>;
+ /**
+ * Public base URL of this server used as the origin of the MCP OAuth callback
+ * (`{PUBLIC_BASE_URL}/api/v1/mcp-servers/oauth/callback`). Not trimmed.
+ * Env: `PUBLIC_BASE_URL` (required).
+ */
+ PUBLIC_BASE_URL: string;
+ /**
+ * RFC 7591 client_name shown on authorization-server consent screens.
+ * Env: `OAUTH_CLIENT_NAME`. Default: "truefoundry-harness".
+ */
+ OAUTH_CLIENT_NAME: string;
/**
* Sandbox provider settings as a JSON object discriminated on `type`
* (see SandboxProviderSettingsSchema in the harness; today: "daytona").
@@ -350,6 +361,8 @@ const configuration: ServerConfiguration = {
MODEL_HEADERS_BY_NAME: parseHeadersByName('MODEL'),
MCP_HEADERS: parseHeaders('MCP_HEADERS', getEnv('MCP_HEADERS')),
MCP_HEADERS_BY_NAME: parseHeadersByName('MCP'),
+ PUBLIC_BASE_URL: getEnv('PUBLIC_BASE_URL', { required: true }) ?? '',
+ OAUTH_CLIENT_NAME: getEnv('OAUTH_CLIENT_NAME', { defaultValue: 'truefoundry-harness' }) ?? 'truefoundry-harness',
SANDBOX_SETTINGS: getEnv('SANDBOX_SETTINGS'),
SANDBOX_API_KEY: getEnv('SANDBOX_API_KEY'),
SANDBOX_FILE_MAX_BYTES: parsePositiveInt({
diff --git a/packages/server/src/db/mcpOAuthTypes.ts b/packages/server/src/db/mcpOAuthTypes.ts
new file mode 100644
index 000000000..2b9c42b31
--- /dev/null
+++ b/packages/server/src/db/mcpOAuthTypes.ts
@@ -0,0 +1,45 @@
+/**
+ * Canonical JSON shapes for MCP OAuth columns (`mcp_server`, `oauth_token`,
+ * `oauth_pending_authorization`). Owned by the server DB layer — not the harness.
+ */
+
+/** RFC 8414 AS metadata cached at DCR time (`mcp_server.oauth_server`). */
+export interface OAuthServer {
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+ codeChallengeMethodsSupported?: string[];
+}
+
+/** RFC 7591 DCR response (`mcp_server.oauth_client`). */
+export interface OAuthClient {
+ clientId: string;
+ clientSecret?: string;
+}
+
+/** `oauth_pending_authorization.auth_data` JSONB. */
+export interface McpOAuthPendingAuthorizationData {
+ codeVerifier?: string;
+ redirectUrl?: string;
+}
+
+/** `oauth_token.token` JSONB. */
+export interface McpOAuthToken {
+ accessToken: string;
+ refreshToken?: string;
+ /** ISO 8601 */
+ expiresAt: string;
+ scope?: string;
+}
+
+/** Joined view of oauth_client + oauth_server (written together at DCR). */
+export type McpOAuthClientRecord = OAuthClient & OAuthServer;
+
+/**
+ * Pending auth envelope for store APIs.
+ * `state` is `oauth_pending_authorization.id` (OAuth wire `state`).
+ * `serverId` is `mcp_server.id` / `oauth_server_id` FK.
+ */
+export type McpOAuthPendingAuthorization = McpOAuthPendingAuthorizationData & {
+ state: string;
+ serverId: string;
+};
diff --git a/packages/server/src/db/postgres/types.ts b/packages/server/src/db/postgres/types.ts
index 361d3a31d..d387c0e7a 100644
--- a/packages/server/src/db/postgres/types.ts
+++ b/packages/server/src/db/postgres/types.ts
@@ -15,42 +15,7 @@ import type {
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;
-}
+import type { McpOAuthPendingAuthorizationData, McpOAuthToken, OAuthClient, OAuthServer } from '../mcpOAuthTypes';
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -331,11 +296,10 @@ export interface McpServerTable {
* 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.
+ /** OAuthClient — { clientId, clientSecret? }. RFC 7591 DCR response.
+ * Token auth is form-body (client_secret_post) when clientSecret is set; presence of secret
+ * alone decides the method (same as servicefoundry outbound DCR). Both oauth_server and
+ * oauth_client are null until first successful DCR.
*/
oauth_client: JSONColumnType<OAuthClient, OAuthClient, OAuthClient> | null;
created_at: Date;
diff --git a/packages/server/src/db/sqlite/types.ts b/packages/server/src/db/sqlite/types.ts
index dc87c9a4f..2d28be7c8 100644
--- a/packages/server/src/db/sqlite/types.ts
+++ b/packages/server/src/db/sqlite/types.ts
@@ -18,41 +18,7 @@ import type {
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;
-}
+import type { McpOAuthPendingAuthorizationData, McpOAuthToken, OAuthClient, OAuthServer } from '../mcpOAuthTypes';
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).