The open-source agent harness - the runtime layer that turns an LLM into a working agent.
move mcp auth out of harness to server (#58)
Heer Ambavif3849e8bf7eb
diff --git a/packages/harness/src/core/auth/IOAuthClientStore.ts b/packages/harness/src/core/auth/IOAuthClientStore.tsdeleted file mode 100644index 46cbfb6cc..000000000--- a/packages/harness/src/core/auth/IOAuthClientStore.ts+++ /dev/null@@ -1,35 +0,0 @@-/** Authorization-server endpoints, discovered and cached at registration time (mirrors `oauth_server`). */-export interface OAuthServerMetadata {- authorizationEndpoint: string;- tokenEndpoint: string;- codeChallengeMethodsSupported: string[] | null;-}--/** Credentials for a dynamically-registered client, RFC 7591 (mirrors `oauth_client`). */-export interface OAuthClientCredentials {- clientId: string;- clientSecret: string | null;-}--/**- * A client registered against a specific authorization server — the two halves the DCR flow- * produces, kept distinct because they come from different responses (discovery vs registration)- * and only `client` carries a secret.- */-export interface OAuthClientRecord {- server: OAuthServerMetadata;- client: OAuthClientCredentials;-}--/**- * OAuth client registration columns on an MCP server row (`oauth_server` + `oauth_client`).- * Implemented by the MCP server store — not a separate persistence root.- */-export interface IOAuthClientStore {- saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void>;-- getClient(params: { id: string }): Promise<OAuthClientRecord | undefined>;-- /** Drop a stale registration so the next authorize can re-run DCR (e.g. invalid_client). */- deleteClient(params: { id: string }): Promise<void>;-}diff --git a/packages/harness/src/core/auth/IOAuthTokenStore.ts b/packages/harness/src/core/auth/IOAuthTokenStore.tsdeleted file mode 100644index 5d2dc4620..000000000--- a/packages/harness/src/core/auth/IOAuthTokenStore.ts+++ /dev/null@@ -1,44 +0,0 @@-/** In-flight authorization awaiting the OAuth callback (keyed by CSRF `state`). */-export interface OAuthPendingAuthorization {- /** The OAuth wire `state` param — also this store's lookup key for the pending row. */- state: string;- /** The resource this pending authorization is for — same `id` used everywhere else here. */- id: string;- /**- * MCP server URL used at authorize time. The shared OAuth callback only receives `state`/`code`,- * so this is stashed so token exchange can rebuild the same RFC 8707 `resource`.- */- mcpServerUrl: string;- /** `null` when the authorization server does not advertise PKCE support. */- codeVerifier: string | null;- /** FE landing URL after OAuth completes; not the OAuth redirect_uri. `null` when unset. */- redirectUrl: string | null;-}--/** Stored access token for one resource. */-export interface OAuthToken {- accessToken: string;- refreshToken: string | null;- expiresAt: string;- /** Space-delimited, single string. `null` when unset. */- scope: string | null;-}--export interface IOAuthTokenStore {- savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void>;-- /**- * Atomically load and delete a pending authorization for `state` so a callback can be redeemed- * only once (safe under concurrent duplicate redirects). Past-TTL rows are never returned- * (same rule as a pure read would apply); the TTL itself is the implementation's to choose.- */- consumePendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined>;-- saveToken(params: { id: string; token: OAuthToken }): Promise<void>;-- getToken(params: { id: string }): Promise<OAuthToken | undefined>;-- getTokens(params: { ids: string[] }): Promise<Map<string, OAuthToken>>;-- deleteToken(params: { id: string }): Promise<void>;-}diff --git a/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts b/packages/harness/src/core/auth/InMemoryOAuthClientStore.tsdeleted file mode 100644index a0a1825ee..000000000--- a/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts+++ /dev/null@@ -1,23 +0,0 @@-import type { IOAuthClientStore, OAuthClientRecord } from './IOAuthClientStore';--/**- * In-memory OAuth-client facet of an MCP server store — for tests and any dev/no-DB usage.- * Not for production use (no persistence across process restarts, no multi-replica sharing).- */-/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async for IOAuthClientStore callers */-export class InMemoryOAuthClientStore implements IOAuthClientStore {- private readonly clients = new Map<string, OAuthClientRecord>();-- async saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void> {- this.clients.set(params.id, params.record);- }-- async getClient(params: { id: string }): Promise<OAuthClientRecord | undefined> {- return this.clients.get(params.id);- }-- async deleteClient(params: { id: string }): Promise<void> {- this.clients.delete(params.id);- }-}-/* eslint-enable @typescript-eslint/require-await */diff --git a/packages/harness/src/core/auth/oauthToken.ts b/packages/harness/src/core/auth/oauthToken.tsdeleted file mode 100644index 57e33d480..000000000--- a/packages/harness/src/core/auth/oauthToken.ts+++ /dev/null@@ -1,5 +0,0 @@-/** True when `expiresAtIso` parses and is strictly in the future relative to `nowMs`. */-export function isOAuthAccessTokenUsable(expiresAtIso: string, nowMs: number): boolean {- const expiresAtMs = Date.parse(expiresAtIso);- return !Number.isNaN(expiresAtMs) && expiresAtMs > nowMs;-}diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsindex 82c32d30b..b6e4678f6 100644--- a/packages/harness/src/core/index.ts+++ b/packages/harness/src/core/index.ts@@ -47,18 +47,6 @@ export {} from './capabilities/builtins/LargeToolResponse';export { openUI } from './capabilities/builtins/OpenUI';-// Auth contracts-export { InMemoryOAuthClientStore } from './auth/InMemoryOAuthClientStore';-export { InMemoryOAuthTokenStore } from './auth/InMemoryOAuthTokenStore';-export type {- IOAuthClientStore,- OAuthClientCredentials,- OAuthClientRecord,- OAuthServerMetadata,-} from './auth/IOAuthClientStore';-export type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from './auth/IOAuthTokenStore';-export { isOAuthAccessTokenUsable } from './auth/oauthToken';-// MCP contractsexport type { ApprovalDecision } from './events/schema';export { ClientSideTool } from './mcp/ClientSideTool';@@ -148,24 +136,6 @@ export { AgentHarnessError, McpConnectionError, McpDcrConfigurationError } fromexport { extractErrorLogFields } from './util/errorLogFields';export { PromiseTimeoutError, withTimeout } from './util/promiseUtils';-// MCP OAuth-export {- DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,- MCP_OAUTH_CALLBACK_PATH,- buildMcpAuthorizationUrl,- completeMcpAuthorization,- createMcpOAuthClient,- ensureMcpClientRegistered,- isMcpAuthRequired,- mcpAuthorizationServerMetadata,- mcpAuthorizationServerOrigin,- mcpClientInformation,- mcpOAuthCallbackUrl,- resolveMcpAuth,- validateRedirectUris,-} from './mcp/auth';-export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcp/auth';-// Sandbox (concrete implementation; provider details exported for composition)export { DaytonaSandboxProvider } from './sandbox/provider/DaytonaProvider';export type { DaytonaSandboxProviderOptions } from './sandbox/provider/DaytonaProvider';diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.tsdeleted file mode 100644index ea9cca1df..000000000--- a/packages/harness/src/core/mcp/auth/index.ts+++ /dev/null@@ -1,18 +0,0 @@-export {- buildMcpAuthorizationUrl,- completeMcpAuthorization,- createMcpOAuthClient,- ensureMcpClientRegistered,- isMcpAuthRequired,- resolveMcpAuth,-} from './mcpDcr';-export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcpDcr';-export {- DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,- MCP_OAUTH_CALLBACK_PATH,- mcpAuthorizationServerMetadata,- mcpAuthorizationServerOrigin,- mcpClientInformation,- mcpOAuthCallbackUrl,-} from './mcpOAuthHelpers';-export { validateRedirectUris } from './redirectUri';diff --git a/packages/harness/src/core/mcp/auth/redirectUri.ts b/packages/harness/src/core/mcp/auth/redirectUri.tsdeleted file mode 100644index 2c5fe7896..000000000--- a/packages/harness/src/core/mcp/auth/redirectUri.ts+++ /dev/null@@ -1,19 +0,0 @@-/**- * Shape/scheme checks for redirect URLs (http/https only).- */-import { McpConnectionError } from '../../errors';--/** Validates redirect URLs parse as http(s). */-export function validateRedirectUris({ redirectUris }: { redirectUris: string[] }): void {- for (const redirectUri of redirectUris) {- let parsed: URL;- try {- parsed = new URL(redirectUri);- } catch {- throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);- }- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {- throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);- }- }-}diff --git a/packages/harness/tests/core/mcp/auth/redirectUri.test.ts b/packages/harness/tests/core/mcp/auth/redirectUri.test.tsdeleted file mode 100644index 03b7cb655..000000000--- a/packages/harness/tests/core/mcp/auth/redirectUri.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { McpConnectionError } from '../../../../src/core/errors';-import { validateRedirectUris } from '../../../../src/core/mcp/auth/redirectUri';--describe('validateRedirectUris', () => {- it('accepts http(s) URLs', () => {- expect(() =>- validateRedirectUris({- redirectUris: ['https://harness.example.com/settings', 'http://localhost:3000/cb'],- }),- ).not.toThrow();- });-- it('rejects non-http(s) URIs', () => {- expect(() =>- validateRedirectUris({- redirectUris: ['javascript:alert(1)'],- }),- ).toThrow(/Must be a valid URL/);- });-- it('rejects malformed URIs', () => {- expect(() =>- validateRedirectUris({- redirectUris: ['not-a-url'],- }),- ).toThrow(McpConnectionError);- });-});diff --git a/packages/server/package.json b/packages/server/package.jsonindex 0ffbd8fc6..8ca71ea23 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -29,6 +29,7 @@"@hono/node-server": "^2.0.11","@hono/swagger-ui": "^0.2.1","@hono/zod-openapi": "^1.5.1",+ "@modelcontextprotocol/sdk": "^1.29.0","@truefoundry/utils-core": "workspace:*","better-sqlite3": "^13.0.2","hono": "^4.12.34",diff --git a/packages/server/src/apis/mcpOAuth.ts b/packages/server/src/apis/mcpOAuth.tsindex a053422f3..d903518b1 100644--- a/packages/server/src/apis/mcpOAuth.ts+++ b/packages/server/src/apis/mcpOAuth.ts@@ -1,13 +1,8 @@import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';-import {- completeMcpAuthorization,- extractErrorLogFields,- McpConnectionError,- type IOAuthClientStore,- type IOAuthTokenStore,- type OAuthPendingAuthorization,-} from '@truefoundry/utils-core/core';+import { extractErrorLogFields, McpConnectionError } from '@truefoundry/utils-core/core';import type { Logger } from 'winston';+import { completeMcpAuthorization } from '../mcp/auth/mcpDcr';+import type { IOAuthClientStore, IOAuthTokenStore, OAuthPendingAuthorization } from '../mcp/auth/types';import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';export interface McpOAuthRouterDeps {diff --git a/packages/server/src/apis/mcpServers.ts b/packages/server/src/apis/mcpServers.tsindex b61a18e75..39fa8e90f 100644--- a/packages/server/src/apis/mcpServers.ts+++ b/packages/server/src/apis/mcpServers.ts@@ -1,16 +1,10 @@import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';import {- ensureMcpClientRegistered,extractErrorLogFields,- type IOAuthTokenStore,isAuthRequired,- isMcpAuthRequired,McpConnectionError,McpDcrConfigurationError,- type OAuthToken,RemoteMCP,- resolveMcpAuth,- validateRedirectUris,withTimeout,} from '@truefoundry/utils-core/core';import { HTTPException } from 'hono/http-exception';@@ -18,6 +12,9 @@ import type { Logger } from 'winston';import type { McpCatalog } from '../catalog/McpCatalog';import configuration from '../config';import type { IMcpServerStore, McpServerRecord } from '../db/mcpServerStore';+import { ensureMcpClientRegistered, isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';+import { validateRedirectUris } from '../mcp/auth/mcpOAuthHelpers';+import type { IOAuthTokenStore, OAuthToken } from '../mcp/auth/types';import {authorizeConfiguredMcpServerRoute,deleteConfiguredMcpServerAuthRoute,diff --git a/packages/server/src/apis/settings.ts b/packages/server/src/apis/settings.tsindex 723cf7e30..da6156f77 100644--- a/packages/server/src/apis/settings.ts+++ b/packages/server/src/apis/settings.ts@@ -4,7 +4,6 @@* a single policy can wrap the whole tree later without touching each resource.*/import { OpenAPIHono } from '@hono/zod-openapi';-import type { IOAuthTokenStore } from '@truefoundry/utils-core/core';import type { Logger } from 'winston';import type { McpCatalog } from '../catalog/McpCatalog';import type { ModelCatalog } from '../catalog/ModelCatalog';@@ -14,6 +13,7 @@ import type { IMcpServerStore } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { ISkillStore } from '../db/skillStore';+import type { IOAuthTokenStore } from '../mcp/auth/types';import { createMcpServersRouter } from './mcpServers';import { createModelProvidersRouter } from './modelProviders';import { createSandboxProvidersRouter } from './sandboxProviders';diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.tsindex f9c780702..894f86a4f 100644--- a/packages/server/src/apis/turns.ts+++ b/packages/server/src/apis/turns.ts@@ -20,7 +20,6 @@ import {isFileContentPart,McpConnectionError,VercelAILLM,- type IOAuthTokenStore,type VercelAIProviderConfig,} from '@truefoundry/utils-core/core';import type { Context } from 'hono';@@ -32,6 +31,7 @@ import type { IMcpServerStore } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { ISkillStore } from '../db/skillStore';+import type { IOAuthTokenStore } from '../mcp/auth/types';import {createAndExecuteTurnRoute,getTurnRoute,diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex d421d5e62..9cfdf1529 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -2,7 +2,6 @@import { swaggerUI } from '@hono/swagger-ui';import { OpenAPIHono } from '@hono/zod-openapi';import type { ISessionStore, Sessions, TurnStreamingEvent } from '@truefoundry/utils-core/agent-session';-import type { IOAuthTokenStore } from '@truefoundry/utils-core/core';import type { RequestReplyRouter } from '@truefoundry/utils-core/request-reply';import type { Context } from 'hono';import { HTTPException } from 'hono/http-exception';@@ -24,6 +23,7 @@ import type { IMcpServerStore } from './db/mcpServerStore';import type { IModelProviderStore } from './db/modelProviderStore';import type { ISandboxProviderStore } from './db/sandboxProviderStore';import type { ISkillStore } from './db/skillStore';+import type { IOAuthTokenStore } from './mcp/auth/types';import type { ActiveTurnRegistry } from './runtime/activeTurns';import type { EventSubscriptionRegistry } from './runtime/event-subscription';@@ -75,7 +75,7 @@ export function createServerApp(deps: ServerDeps) {app.route('/api/v1/capabilities', createCapabilitiesRouter({ sandboxProviderStore: deps.sandboxProviderStore }));app.route('/api/v1/models', createModelsRouter(deps.modelProviderStore));app.route('/api/v1/mcp-servers', createAvailableMcpServersRouter(deps.mcpServerStore));- // Shared OAuth callback — path must match MCP_OAUTH_CALLBACK_PATH in the harness package.+ // Shared OAuth callback — path must match the server-owned MCP_OAUTH_CALLBACK_PATH.app.route('/api/v1/mcp-servers/oauth',createMcpOAuthRouter({diff --git a/packages/server/src/db/mcpOAuthTypes.ts b/packages/server/src/db/mcpOAuthTypes.tsdeleted file mode 100644index a19aaa04a..000000000--- a/packages/server/src/db/mcpOAuthTypes.ts+++ /dev/null@@ -1,117 +0,0 @@-import type {- OAuthClientRecord as ContractOAuthClientRecord,- OAuthPendingAuthorization as ContractOAuthPendingAuthorization,- OAuthToken as ContractOAuthToken,-} from '@truefoundry/utils-core/core';--// Absence is an explicit `| null`, not an optional `?:`--/**- * How long a pending authorization stays redeemable — long enough to finish a consent screen,- * short enough that an abandoned `state` and its PKCE verifier stop being usable. Applied as a- * `created_at` filter on read by both backends, so no sweep job is needed.- */-export const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;--/** RFC 8414 AS metadata cached at DCR time (`mcp_server.oauth_server`). */-export interface OAuthServer {- authorization_endpoint: string;- token_endpoint: string;- code_challenge_methods_supported: string[] | null;-}--/** RFC 7591 DCR response (`mcp_server.oauth_client`). */-export interface OAuthClient {- client_id: string;- client_secret: string | null;-}--/** `oauth_pending_authorization.auth_data` JSONB. */-export interface OAuthPendingAuthorizationData {- /** MCP server URL from authorize time — needed by the shared callback for RFC 8707 `resource`. */- mcp_server_url: string;- code_verifier: string | null;- redirect_url: string | null;-}--/** `oauth_token.token` JSONB. */-export interface OAuthToken {- access_token: string;- refresh_token: string | null;- /** ISO 8601 */- expires_at: string;- scope: string | null;-}--export function toStoredOAuthToken(token: ContractOAuthToken): OAuthToken {- return {- access_token: token.accessToken,- refresh_token: token.refreshToken,- expires_at: token.expiresAt,- scope: token.scope,- };-}--export function fromStoredOAuthToken(stored: OAuthToken): ContractOAuthToken {- return {- accessToken: stored.access_token,- refreshToken: stored.refresh_token,- expiresAt: stored.expires_at,- scope: stored.scope,- };-}--export function toStoredOAuthClientRecord(record: ContractOAuthClientRecord): {- server: OAuthServer;- client: OAuthClient;-} {- return {- server: {- authorization_endpoint: record.server.authorizationEndpoint,- token_endpoint: record.server.tokenEndpoint,- code_challenge_methods_supported: record.server.codeChallengeMethodsSupported,- },- client: {- client_id: record.client.clientId,- client_secret: record.client.clientSecret,- },- };-}--export function fromStoredOAuthClientRecord(params: {- server: OAuthServer;- client: OAuthClient;-}): ContractOAuthClientRecord {- return {- server: {- authorizationEndpoint: params.server.authorization_endpoint,- tokenEndpoint: params.server.token_endpoint,- codeChallengeMethodsSupported: params.server.code_challenge_methods_supported,- },- client: {- clientId: params.client.client_id,- clientSecret: params.client.client_secret,- },- };-}--/** The blob half of a pending authorization; `state`/`id` live in their own columns. */-export function toStoredOAuthPendingAuthorizationData(- pending: ContractOAuthPendingAuthorization,-): OAuthPendingAuthorizationData {- return {- mcp_server_url: pending.mcpServerUrl,- code_verifier: pending.codeVerifier,- redirect_url: pending.redirectUrl,- };-}--export function fromStoredOAuthPendingAuthorizationData(- stored: OAuthPendingAuthorizationData,-): Pick<ContractOAuthPendingAuthorization, 'mcpServerUrl' | 'codeVerifier' | 'redirectUrl'> {- return {- mcpServerUrl: stored.mcp_server_url,- codeVerifier: stored.code_verifier,- redirectUrl: stored.redirect_url,- };-}diff --git a/packages/server/src/db/mcpServerStore.ts b/packages/server/src/db/mcpServerStore.tsindex bfd2c021e..bda019cfb 100644--- a/packages/server/src/db/mcpServerStore.ts+++ b/packages/server/src/db/mcpServerStore.ts@@ -5,8 +5,16 @@** Also owns the DCR registration columns (`oauth_server` / `oauth_client`) via* `IOAuthClientStore` — those are not a separate persistence root.+ *+ * OAuth JSONB wire shapes (snake_case) and camelCase ↔ storage mappers live here+ * alongside the store contract — absence is an explicit `| null`, not an optional `?:`.*/-import type { IOAuthClientStore } from '@truefoundry/utils-core/core';+import type {+ OAuthClientRecord as ContractOAuthClientRecord,+ OAuthPendingAuthorization as ContractOAuthPendingAuthorization,+ OAuthToken as ContractOAuthToken,+ IOAuthClientStore,+} from '../mcp/auth/types';import type { ResourceName } from '../schemas/common';import type { McpServerManifest } from '../schemas/mcpServer';@@ -41,3 +49,113 @@ export interface IMcpServerStore extends IOAuthClientStore {*/upsertServer(input: UpsertMcpServerInput): Promise<McpServerRecord>;}++/**+ * How long a pending authorization stays redeemable — long enough to finish a consent screen,+ * short enough that an abandoned `state` and its PKCE verifier stop being usable. Applied as a+ * `created_at` filter on read by both backends, so no sweep job is needed.+ */+export const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;++/** RFC 8414 AS metadata cached at DCR time (`mcp_server.oauth_server`). */+export interface OAuthServer {+ authorization_endpoint: string;+ token_endpoint: string;+ code_challenge_methods_supported: string[] | null;+}++/** RFC 7591 DCR response (`mcp_server.oauth_client`). */+export interface OAuthClient {+ client_id: string;+ client_secret: string | null;+}++/** `oauth_pending_authorization.auth_data` JSONB. */+export interface OAuthPendingAuthorizationData {+ /** MCP server URL from authorize time — needed by the shared callback for RFC 8707 `resource`. */+ mcp_server_url: string;+ code_verifier: string | null;+ redirect_url: string | null;+}++/** `oauth_token.token` JSONB. */+export interface OAuthToken {+ access_token: string;+ refresh_token: string | null;+ /** ISO 8601 */+ expires_at: string;+ scope: string | null;+}++export function toStoredOAuthToken(token: ContractOAuthToken): OAuthToken {+ return {+ access_token: token.accessToken,+ refresh_token: token.refreshToken,+ expires_at: token.expiresAt,+ scope: token.scope,+ };+}++export function fromStoredOAuthToken(stored: OAuthToken): ContractOAuthToken {+ return {+ accessToken: stored.access_token,+ refreshToken: stored.refresh_token,+ expiresAt: stored.expires_at,+ scope: stored.scope,+ };+}++export function toStoredOAuthClientRecord(record: ContractOAuthClientRecord): {+ server: OAuthServer;+ client: OAuthClient;+} {+ return {+ server: {+ authorization_endpoint: record.server.authorizationEndpoint,+ token_endpoint: record.server.tokenEndpoint,+ code_challenge_methods_supported: record.server.codeChallengeMethodsSupported,+ },+ client: {+ client_id: record.client.clientId,+ client_secret: record.client.clientSecret,+ },+ };+}++export function fromStoredOAuthClientRecord(params: {+ server: OAuthServer;+ client: OAuthClient;+}): ContractOAuthClientRecord {+ return {+ server: {+ authorizationEndpoint: params.server.authorization_endpoint,+ tokenEndpoint: params.server.token_endpoint,+ codeChallengeMethodsSupported: params.server.code_challenge_methods_supported,+ },+ client: {+ clientId: params.client.client_id,+ clientSecret: params.client.client_secret,+ },+ };+}++/** The blob half of a pending authorization; `state`/`id` live in their own columns. */+export function toStoredOAuthPendingAuthorizationData(+ pending: ContractOAuthPendingAuthorization,+): OAuthPendingAuthorizationData {+ return {+ mcp_server_url: pending.mcpServerUrl,+ code_verifier: pending.codeVerifier,+ redirect_url: pending.redirectUrl,+ };+}++export function fromStoredOAuthPendingAuthorizationData(+ stored: OAuthPendingAuthorizationData,+): Pick<ContractOAuthPendingAuthorization, 'mcpServerUrl' | 'codeVerifier' | 'redirectUrl'> {+ return {+ mcpServerUrl: stored.mcp_server_url,+ codeVerifier: stored.code_verifier,+ redirectUrl: stored.redirect_url,+ };+}diff --git a/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts b/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.tsindex 7f77d365f..7900c6bec 100644--- a/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts+++ b/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts@@ -1,8 +1,14 @@-import type { OAuthClientRecord } from '@truefoundry/utils-core/core';import type { Kysely, Selectable } from 'kysely';import { ulid } from 'ulid';-import { fromStoredOAuthClientRecord, toStoredOAuthClientRecord } from '../../mcpOAuthTypes';-import type { GetMcpServerInput, IMcpServerStore, McpServerRecord, UpsertMcpServerInput } from '../../mcpServerStore';+import type { OAuthClientRecord } from '../../../mcp/auth/types';+import {+ fromStoredOAuthClientRecord,+ toStoredOAuthClientRecord,+ type GetMcpServerInput,+ type IMcpServerStore,+ type McpServerRecord,+ type UpsertMcpServerInput,+} from '../../mcpServerStore';import { json, now } from '../sqlExpressions';import type { Database, McpServerTable } from '../types';diff --git a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.tsindex 2deebf4aa..50aca7972 100644--- a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts+++ b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts@@ -1,6 +1,6 @@-import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@truefoundry/utils-core/core';import type { Kysely } from 'kysely';-import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '../../../mcp/auth/types';+import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpServerStore';import type { Database } from '../types';import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';import { deleteToken, getToken, getTokens, saveToken } from './queries/token';diff --git a/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts b/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.tsindex 36884ef49..f0616745a 100644--- a/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts+++ b/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts@@ -1,10 +1,10 @@-import type { OAuthPendingAuthorization } from '@truefoundry/utils-core/core';import type { Kysely } from 'kysely';+import type { OAuthPendingAuthorization } from '../../../../mcp/auth/types';import {fromStoredOAuthPendingAuthorizationData,PENDING_AUTHORIZATION_TTL_MS,toStoredOAuthPendingAuthorizationData,-} from '../../../mcpOAuthTypes';+} from '../../../mcpServerStore';import { json, now, nowMinusMs } from '../../sqlExpressions';import type { Database } from '../../types';diff --git a/packages/server/src/db/postgres/token-store/queries/token.ts b/packages/server/src/db/postgres/token-store/queries/token.tsindex 43187ddfc..b846a84c5 100644--- a/packages/server/src/db/postgres/token-store/queries/token.ts+++ b/packages/server/src/db/postgres/token-store/queries/token.ts@@ -1,5 +1,5 @@import { sql, type Kysely } from 'kysely';-import type { OAuthToken } from '../../../mcpOAuthTypes';+import type { OAuthToken } from '../../../mcpServerStore';import { json, now } from '../../sqlExpressions';import type { Database } from '../../types';diff --git a/packages/server/src/db/postgres/types.ts b/packages/server/src/db/postgres/types.tsindex e8eef19cb..f0f05bede 100644--- a/packages/server/src/db/postgres/types.ts+++ b/packages/server/src/db/postgres/types.ts@@ -18,7 +18,7 @@ import type { McpServerManifest } from '../../schemas/mcpServer';import type { ModelProviderManifest } from '../../schemas/modelProvider';import type { SandboxProviderManifest } from '../../schemas/sandboxProvider';import type { SkillManifest } from '../../schemas/skill';-import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpOAuthTypes';+import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpServerStore';/*** Trace-level state for one thread at one turn (`turn_thread.checkpoint`).diff --git a/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts b/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.tsindex 38e1891c4..551484c08 100644--- a/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts+++ b/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts@@ -1,10 +1,17 @@-import type { OAuthClientRecord } from '@truefoundry/utils-core/core';import type { ExpressionBuilder, Kysely } from 'kysely';import { ulid } from 'ulid';+import type { OAuthClientRecord } from '../../../mcp/auth/types';import type { McpServerManifest } from '../../../schemas/mcpServer';-import type { OAuthClient, OAuthServer } from '../../mcpOAuthTypes';-import { fromStoredOAuthClientRecord, toStoredOAuthClientRecord } from '../../mcpOAuthTypes';-import type { GetMcpServerInput, IMcpServerStore, McpServerRecord, UpsertMcpServerInput } from '../../mcpServerStore';+import {+ fromStoredOAuthClientRecord,+ toStoredOAuthClientRecord,+ type GetMcpServerInput,+ type IMcpServerStore,+ type McpServerRecord,+ type OAuthClient,+ type OAuthServer,+ type UpsertMcpServerInput,+} from '../../mcpServerStore';import { jsonbBind, jsonText, nowIso } from '../sqlExpressions';import type { Database } from '../types';diff --git a/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.tsindex e4090a452..553ccf1fb 100644--- a/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts+++ b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts@@ -1,6 +1,6 @@-import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@truefoundry/utils-core/core';import type { Kysely } from 'kysely';-import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '../../../mcp/auth/types';+import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpServerStore';import type { Database } from '../types';import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';import { deleteToken, getToken, getTokens, saveToken } from './queries/token';diff --git a/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts b/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.tsindex 7a7ddc060..e2f62b297 100644--- a/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts+++ b/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts@@ -1,11 +1,11 @@-import type { OAuthPendingAuthorization } from '@truefoundry/utils-core/core';import { sql, type Kysely } from 'kysely';+import type { OAuthPendingAuthorization } from '../../../../mcp/auth/types';import {fromStoredOAuthPendingAuthorizationData,PENDING_AUTHORIZATION_TTL_MS,toStoredOAuthPendingAuthorizationData,type OAuthPendingAuthorizationData,-} from '../../../mcpOAuthTypes';+} from '../../../mcpServerStore';import { isoMsAgo, jsonbBind, jsonText, nowIso } from '../../sqlExpressions';import type { Database } from '../../types';diff --git a/packages/server/src/db/sqlite/token-store/queries/token.ts b/packages/server/src/db/sqlite/token-store/queries/token.tsindex 8084d932d..8fc4be148 100644--- a/packages/server/src/db/sqlite/token-store/queries/token.ts+++ b/packages/server/src/db/sqlite/token-store/queries/token.ts@@ -1,5 +1,5 @@import { sql, type Kysely } from 'kysely';-import type { OAuthToken } from '../../../mcpOAuthTypes';+import type { OAuthToken } from '../../../mcpServerStore';import { jsonbBind, jsonText, nowIso } from '../../sqlExpressions';import type { Database } from '../../types';diff --git a/packages/server/src/db/sqlite/types.ts b/packages/server/src/db/sqlite/types.tsindex d555cca8c..b95d1fc47 100644--- a/packages/server/src/db/sqlite/types.ts+++ b/packages/server/src/db/sqlite/types.ts@@ -21,7 +21,7 @@ import type { McpServerManifest } from '../../schemas/mcpServer';import type { ModelProviderManifest } from '../../schemas/modelProvider';import type { SandboxProviderManifest } from '../../schemas/sandboxProvider';import type { SkillManifest } from '../../schemas/skill';-import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpOAuthTypes';+import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpServerStore';/*** Trace-level state for one thread at one turn (`turn_thread.checkpoint`).diff --git a/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts b/packages/server/src/mcp/auth/inMemoryStores.tssimilarity index 56%rename from packages/harness/src/core/auth/InMemoryOAuthTokenStore.tsrename to packages/server/src/mcp/auth/inMemoryStores.tsindex e76c1fd5c..9b0cd3eeb 100644--- a/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts+++ b/packages/server/src/mcp/auth/inMemoryStores.ts@@ -1,13 +1,15 @@-import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from './IOAuthTokenStore';+import type {+ IOAuthClientStore,+ IOAuthTokenStore,+ OAuthClientRecord,+ OAuthPendingAuthorization,+ OAuthToken,+} from './types';-/** This implementation's read-expiry window; the SQL-backed stores pick their own. */const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;-/**- * In-memory `IOAuthTokenStore` — for tests and any dev/no-DB usage. Not for production use (no- * persistence across process restarts, no multi-replica sharing).- */-/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async for IOAuthTokenStore callers */+/** In-memory OAuth token store for tests and development without a database. */+/* eslint-disable @typescript-eslint/require-await -- synchronous implementation of an async store contract */export class InMemoryOAuthTokenStore implements IOAuthTokenStore {private readonly tokens = new Map<string, OAuthToken>();private readonly pending = new Map<string, { row: OAuthPendingAuthorization; createdAtMs: number }>();@@ -34,18 +36,35 @@ export class InMemoryOAuthTokenStore implements IOAuthTokenStore {}async getTokens(params: { ids: string[] }): Promise<Map<string, OAuthToken>> {- const out = new Map<string, OAuthToken>();+ const tokens = new Map<string, OAuthToken>();for (const id of params.ids) {const token = this.tokens.get(id);- if (token) {- out.set(id, token);+ if (token !== undefined) {+ tokens.set(id, token);}}- return out;+ return tokens;}async deleteToken(params: { id: string }): Promise<void> {this.tokens.delete(params.id);}}++/** In-memory OAuth client store for tests and development without a database. */+export class InMemoryOAuthClientStore implements IOAuthClientStore {+ private readonly clients = new Map<string, OAuthClientRecord>();++ async saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void> {+ this.clients.set(params.id, params.record);+ }++ async getClient(params: { id: string }): Promise<OAuthClientRecord | undefined> {+ return this.clients.get(params.id);+ }++ async deleteClient(params: { id: string }): Promise<void> {+ this.clients.delete(params.id);+ }+}/* eslint-enable @typescript-eslint/require-await */diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/server/src/mcp/auth/mcpDcr.tssimilarity index 79%rename from packages/harness/src/core/mcp/auth/mcpDcr.tsrename to packages/server/src/mcp/auth/mcpDcr.tsindex 4f4c71558..8d3c28379 100644--- a/packages/harness/src/core/mcp/auth/mcpDcr.ts+++ b/packages/server/src/mcp/auth/mcpDcr.ts@@ -12,40 +12,29 @@ import type {OAuthClientMetadata,OAuthTokens,} from '@modelcontextprotocol/sdk/shared/auth.js';+import { McpConnectionError, McpDcrConfigurationError } from '@truefoundry/utils-core/core';import { randomBytes } from 'node:crypto';-import type { IOAuthClientStore, OAuthClientRecord } from '../../auth/IOAuthClientStore';-import type { IOAuthTokenStore, OAuthPendingAuthorization } from '../../auth/IOAuthTokenStore';-import { isOAuthAccessTokenUsable } from '../../auth/oauthToken';-import { McpConnectionError, McpDcrConfigurationError } from '../../errors';import {+ isOAuthAccessTokenUsable,mcpAuthorizationServerMetadata,mcpAuthorizationServerOrigin,mcpClientInformation,mcpOAuthCallbackUrl,oauthTokensToOAuthToken,} from './mcpOAuthHelpers';--export interface McpAuthResolvedResult {- headers: Record<string, string>;-}--export interface McpAuthRequiredResult {- authUrl: URL;-}--export type ResolveMcpAuthResult = McpAuthResolvedResult | McpAuthRequiredResult;+import type {+ IOAuthClientStore,+ IOAuthTokenStore,+ McpAuthRequiredResult,+ OAuthClientRecord,+ OAuthPendingAuthorization,+ ResolveMcpAuthResult,+} from './types';export function isMcpAuthRequired(result: ResolveMcpAuthResult): result is McpAuthRequiredResult {return 'authUrl' in result;}-/**- * 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.- * 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`.- */async function registerMcpClientWithAuthMethodFallback(params: {authorizationServerUrl: string;metadata: AuthorizationServerMetadata;@@ -56,7 +45,6 @@ async function registerMcpClientWithAuthMethodFallback(params: {}): Promise<OAuthClientRecord> {const { authorizationServerUrl, metadata, clientMetadata, mcpServerName, authorizationEndpoint, tokenEndpoint } =params;-let fullInfo;try {fullInfo = await registerClient(authorizationServerUrl, {@@ -72,11 +60,7 @@ async function registerMcpClientWithAuthMethodFallback(params: {);}try {- // Omit method so the authorization server applies its default.- fullInfo = await registerClient(authorizationServerUrl, {- metadata,- clientMetadata,- });+ fullInfo = await registerClient(authorizationServerUrl, { metadata, clientMetadata });} catch (secondError: unknown) {throw new McpConnectionError(`Failed to dynamically register OAuth client for MCP server '${mcpServerName}'`,@@ -85,14 +69,12 @@ async function registerMcpClientWithAuthMethodFallback(params: {);}}-if (!fullInfo.client_id) {throw new McpConnectionError(`Authorization server for MCP server '${mcpServerName}' returned a client response without client_id`,400,);}-return {server: {authorizationEndpoint,@@ -113,30 +95,23 @@ export async function createMcpOAuthClient(params: {clientName: string;}): Promise<OAuthClientRecord> {const { mcpServerUrl, mcpServerName, redirectUri, clientName } = params;-const { authorizationServerUrl, authorizationServerMetadata: metadata } = await discoverOAuthServerInfo(mcpServerUrl);-if (!metadata?.registration_endpoint) {throw new McpDcrConfigurationError(`MCP server '${mcpServerName}' has no DCR support (missing registration_endpoint); auth.type: dcr is misconfigured for this server`,);}-if (!metadata.authorization_endpoint || !metadata.token_endpoint) {throw new McpDcrConfigurationError(`Authorization server for MCP server '${mcpServerName}' is missing authorization_endpoint or token_endpoint`,);}-- // Only reject when the AS explicitly advertises PKCE methods that omit S256.- // Missing/omitted advertisement → still try S256 (many servers support it but do not publish).const pkceMethods = metadata.code_challenge_methods_supported;if (pkceMethods && !pkceMethods.includes('S256')) {throw new McpDcrConfigurationError(`Authorization server for MCP server '${mcpServerName}' advertises PKCE methods without S256`,);}-return registerMcpClientWithAuthMethodFallback({authorizationServerUrl,metadata,@@ -163,14 +138,12 @@ export async function ensureMcpClientRegistered(params: {if (existing) {return existing;}-const client = await createMcpOAuthClient({mcpServerUrl: params.mcpServerUrl,mcpServerName: params.mcpServerName,redirectUri: mcpOAuthCallbackUrl(),clientName: params.clientName,});-await params.mcpServerStore.saveClient({ id: params.serverId, record: client });return client;}@@ -182,7 +155,6 @@ export async function buildMcpAuthorizationUrl(params: {mcpServerUrl: string;mcpServerName: string;clientName: string;- /** FE post-OAuth landing URL (not the OAuth redirect_uri). */redirectUrl?: string;}): Promise<URL> {const client = await ensureMcpClientRegistered({@@ -192,20 +164,15 @@ export async function buildMcpAuthorizationUrl(params: {mcpServerName: params.mcpServerName,clientName: params.clientName,});-const state = randomBytes(32).toString('base64url');const redirectUri = mcpOAuthCallbackUrl();- const resource = resourceUrlFromServerUrl(params.mcpServerUrl);-- // MCP SDK always sends PKCE S256; it only rejects when metadata lists methods that omit S256.- // When we stored null (AS did not advertise), reconstructed metadata omits the field → try S256.let started: Awaited<ReturnType<typeof startAuthorization>>;try {started = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {metadata: mcpAuthorizationServerMetadata(client.server),clientInformation: mcpClientInformation(client.client),redirectUrl: redirectUri,- resource,+ resource: resourceUrlFromServerUrl(params.mcpServerUrl),state,});} catch (error: unknown) {@@ -213,7 +180,6 @@ export async function buildMcpAuthorizationUrl(params: {cause: error instanceof Error ? error : undefined,});}-await params.tokenStore.savePendingAuthorization({state,id: params.serverId,@@ -221,7 +187,6 @@ export async function buildMcpAuthorizationUrl(params: {codeVerifier: started.codeVerifier,redirectUrl: params.redirectUrl ?? null,});-return started.authorizationUrl;}@@ -232,16 +197,13 @@ export async function resolveMcpAuth(params: {mcpServerUrl: string;mcpServerName: string;clientName: string;- /** FE post-OAuth landing URL (not the OAuth redirect_uri). */redirectUrl?: string;}): Promise<ResolveMcpAuthResult> {const nowMs = Date.now();const token = await params.tokenStore.getToken({ id: params.serverId });-if (token && isOAuthAccessTokenUsable(token.expiresAt, nowMs)) {return { headers: { Authorization: `Bearer ${token.accessToken}` } };}-if (token?.refreshToken) {const client = await params.mcpServerStore.getClient({ id: params.serverId });if (client) {@@ -256,17 +218,13 @@ export async function resolveMcpAuth(params: {await params.tokenStore.saveToken({ id: params.serverId, token: saved });return { headers: { Authorization: `Bearer ${saved.accessToken}` } };} catch {- // Refresh failed → drop the unusable token and fall through to full re-authorize.+ // Refresh failure falls through to a fresh authorization.}}}-- // Only reached when there is no usable/refreshable token. Clear the stale row before re-auth- // (successful refresh returns above and never deletes).if (token) {await params.tokenStore.deleteToken({ id: params.serverId });}-const authUrl = await buildMcpAuthorizationUrl({tokenStore: params.tokenStore,mcpServerStore: params.mcpServerStore,@@ -280,11 +238,10 @@ export async function resolveMcpAuth(params: {}/**- * OAuth callback: exchange `code` for tokens against an already-claimed `pending` row. The caller- * claims it with `consumePendingAuthorization` (so duplicate callbacks lose the race) and keeps it- * for its FE landing URL; `mcpServerUrl` for the RFC 8707 `resource` comes from that row.- * Route must already reject IdP `error` params.- * On `invalid_client`, clears stored client + token so the next authorize re-registers.+ * Exchanges `code` for tokens against an already-claimed `pending` row: the caller claims it with+ * `consumePendingAuthorization` so duplicate callbacks lose the race, and keeps it for its FE+ * landing URL. Route must already reject IdP `error` params. On `invalid_client`, clears the stored+ * client and token so the next authorize re-registers.*/export async function completeMcpAuthorization(params: {tokenStore: IOAuthTokenStore;@@ -302,19 +259,16 @@ export async function completeMcpAuthorization(params: {400,);}-- const { codeVerifier } = pending;- if (codeVerifier === null) {+ if (pending.codeVerifier === null) {throw new McpConnectionError('Pending authorization is missing PKCE code_verifier; re-run authorize', 400);}-let tokens: OAuthTokens;try {tokens = await exchangeAuthorization(mcpAuthorizationServerOrigin(client.server), {metadata: mcpAuthorizationServerMetadata(client.server),clientInformation: mcpClientInformation(client.client),authorizationCode: params.code,- codeVerifier,+ codeVerifier: pending.codeVerifier,redirectUri: mcpOAuthCallbackUrl(),resource: resourceUrlFromServerUrl(pending.mcpServerUrl),});@@ -330,7 +284,6 @@ export async function completeMcpAuthorization(params: {cause: error instanceof Error ? error : undefined,});}-await params.tokenStore.saveToken({id: pending.id,token: oauthTokensToOAuthToken(tokens, nowMs, null),diff --git a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts b/packages/server/src/mcp/auth/mcpOAuthHelpers.tssimilarity index 58%rename from packages/harness/src/core/mcp/auth/mcpOAuthHelpers.tsrename to packages/server/src/mcp/auth/mcpOAuthHelpers.tsindex 267ebfc70..98644f43b 100644--- a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts+++ b/packages/server/src/mcp/auth/mcpOAuthHelpers.ts@@ -1,29 +1,18 @@-/**- * Shared MCP OAuth URL / client-metadata helpers.- * Protocol work stays in the MCP SDK (`client/auth.js`).- */import type {AuthorizationServerMetadata,OAuthClientInformationMixed,OAuthTokens,} from '@modelcontextprotocol/sdk/shared/auth.js';-import type { OAuthClientCredentials, OAuthServerMetadata } from '../../auth/IOAuthClientStore';-import type { OAuthToken } from '../../auth/IOAuthTokenStore';-import { McpConnectionError } from '../../errors';+import { McpConnectionError } from '@truefoundry/utils-core/core';+import type { OAuthClientCredentials, OAuthServerMetadata, OAuthToken } from './types';-/** Fixed OAuth callback path for every MCP server (matches server mount). */+/** Fixed OAuth callback path for every MCP server. */export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-servers/oauth/callback';-/**- * 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`.- */+/** Fallback TTL when an RFC 6749 token response omits `expires_in`. */export const DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS = 3600;-/**- * OAuth callback redirect_uri = `PUBLIC_BASE_URL` + fixed path. No trimming of the base.- * Reads from process env (same source as server config).- */+/** Builds the server-owned MCP OAuth callback URL. */export function mcpOAuthCallbackUrl(): string {const publicBaseUrl = process.env['PUBLIC_BASE_URL'] ?? '';if (publicBaseUrl === '') {@@ -32,10 +21,7 @@ export function mcpOAuthCallbackUrl(): string {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.- */+/** Uses form-body client authentication when a secret is present. */export function mcpClientInformation(client: OAuthClientCredentials): OAuthClientInformationMixed {return client.clientSecret !== null? {@@ -49,7 +35,7 @@ export function mcpClientInformation(client: OAuthClientCredentials): OAuthClien};}-/** Reconstruct authorization-server metadata enough for startAuthorization / token calls. */+/** Reconstructs the metadata required by the MCP SDK authorization helpers. */export function mcpAuthorizationServerMetadata(server: OAuthServerMetadata): AuthorizationServerMetadata {return {issuer: new URL(server.authorizationEndpoint).origin,@@ -72,11 +58,31 @@ export function oauthTokensToOAuthToken(fallbackRefreshToken: string | null,): OAuthToken {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(),+ expiresAt: new Date(nowMs + expiresInSeconds * 1000).toISOString(),scope: tokens.scope ?? null,};}++/** True when the expiry parses and is strictly in the future. */+export function isOAuthAccessTokenUsable(expiresAtIso: string, nowMs: number): boolean {+ const expiresAtMs = Date.parse(expiresAtIso);+ return !Number.isNaN(expiresAtMs) && expiresAtMs > nowMs;+}++/** Validates redirect URLs parse as HTTP(S). */+export function validateRedirectUris({ redirectUris }: { redirectUris: string[] }): void {+ for (const redirectUri of redirectUris) {+ let parsed: URL;+ try {+ parsed = new URL(redirectUri);+ } catch {+ throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {+ throw new McpConnectionError(`Invalid redirect URI: ${redirectUri}. Must be a valid URL.`, 400);+ }+ }+}diff --git a/packages/server/src/mcp/auth/types.ts b/packages/server/src/mcp/auth/types.tsnew file mode 100644index 000000000..f7c578823--- /dev/null+++ b/packages/server/src/mcp/auth/types.ts@@ -0,0 +1,59 @@+/** In-flight authorization awaiting the OAuth callback (keyed by CSRF `state`). */+export interface OAuthPendingAuthorization {+ state: string;+ id: string;+ mcpServerUrl: string;+ codeVerifier: string | null;+ redirectUrl: string | null;+}++/** Stored access token for one resource. */+export interface OAuthToken {+ accessToken: string;+ refreshToken: string | null;+ expiresAt: string;+ scope: string | null;+}++export interface IOAuthTokenStore {+ savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void>;+ consumePendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined>;+ saveToken(params: { id: string; token: OAuthToken }): Promise<void>;+ getToken(params: { id: string }): Promise<OAuthToken | undefined>;+ getTokens(params: { ids: string[] }): Promise<Map<string, OAuthToken>>;+ deleteToken(params: { id: string }): Promise<void>;+}++/** Authorization-server endpoints discovered and cached at registration time. */+export interface OAuthServerMetadata {+ authorizationEndpoint: string;+ tokenEndpoint: string;+ codeChallengeMethodsSupported: string[] | null;+}++/** Credentials for a dynamically registered client. */+export interface OAuthClientCredentials {+ clientId: string;+ clientSecret: string | null;+}++export interface OAuthClientRecord {+ server: OAuthServerMetadata;+ client: OAuthClientCredentials;+}++export interface IOAuthClientStore {+ saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void>;+ getClient(params: { id: string }): Promise<OAuthClientRecord | undefined>;+ deleteClient(params: { id: string }): Promise<void>;+}++export interface McpAuthResolvedResult {+ headers: Record<string, string>;+}++export interface McpAuthRequiredResult {+ authUrl: URL;+}++export type ResolveMcpAuthResult = McpAuthResolvedResult | McpAuthRequiredResult;diff --git a/packages/server/src/runtime/sessionResources.ts b/packages/server/src/runtime/sessionResources.tsindex cc3972e77..18ca9d180 100644--- a/packages/server/src/runtime/sessionResources.ts+++ b/packages/server/src/runtime/sessionResources.ts@@ -5,13 +5,10 @@ import { Daytona } from '@daytona/sdk';import type { AgentSpec } from '@truefoundry/utils-core/agent-session';import {DaytonaSandboxProvider,- isMcpAuthRequired,- resolveMcpAuth,Sandbox,SkillMounter,type AgentTracing,type GitSkill,- type IOAuthTokenStore,type RemoteMcpHeaders,type SandboxProvider,type VercelAIProviderConfig,@@ -23,6 +20,8 @@ import type { IMcpServerStore, McpServerRecord } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';import type { ISkillStore } from '../db/skillStore';+import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';+import type { IOAuthTokenStore } from '../mcp/auth/types';import { resolveConfiguredMcpRequestHeaders } from '../schemas/mcpServer';import { PROVIDER_DEFAULT_BASE_URLS } from '../schemas/modelProvider';import { toDaytonaSandboxProviderInput } from '../schemas/sandboxProvider';diff --git a/packages/server/src/schemas/mcpServer.ts b/packages/server/src/schemas/mcpServer.tsindex 15ccc616b..d4de0eb31 100644--- a/packages/server/src/schemas/mcpServer.ts+++ b/packages/server/src/schemas/mcpServer.ts@@ -7,7 +7,8 @@* turn execution resolves DCR tokens via resolveMcpAuth.*/import { z } from '@hono/zod-openapi';-import { isOAuthAccessTokenUsable, type OAuthToken } from '@truefoundry/utils-core/core';+import { isOAuthAccessTokenUsable } from '../mcp/auth/mcpOAuthHelpers';+import type { OAuthToken } from '../mcp/auth/types';import { NameSchema } from './common';/** Transport/kind of MCP server. Extend when non-remote kinds ship. */diff --git a/packages/server/tests/db/mcpServerStoreContractSuite.ts b/packages/server/tests/db/mcpServerStoreContractSuite.tsindex b5192be36..7b9e7e3a2 100644--- a/packages/server/tests/db/mcpServerStoreContractSuite.ts+++ b/packages/server/tests/db/mcpServerStoreContractSuite.ts@@ -2,8 +2,8 @@* Backend-agnostic behavioural contract for IMcpServerStore.* Runs under jest against a fresh store per test (see backend test files).*/-import type { OAuthClientRecord } from '@truefoundry/utils-core/core';import type { IMcpServerStore } from '../../src/db/mcpServerStore';+import type { OAuthClientRecord } from '../../src/mcp/auth/types';import type { McpServerManifest } from '../../src/schemas/mcpServer';const TENANT = 'default';diff --git a/packages/server/tests/db/oauthTokenStoreContractSuite.ts b/packages/server/tests/db/oauthTokenStoreContractSuite.tsindex 890632dbf..7f1944099 100644--- a/packages/server/tests/db/oauthTokenStoreContractSuite.ts+++ b/packages/server/tests/db/oauthTokenStoreContractSuite.ts@@ -6,7 +6,7 @@* each backend supplies `seedResource` (create the FK parent) and `expirePending` (backdate a* pending row past its TTL).*/-import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@truefoundry/utils-core/core';+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '../../src/mcp/auth/types';export interface OAuthTokenStoreHarness {store: IOAuthTokenStore;diff --git a/packages/server/tests/unit/apis/mcpOAuth.test.ts b/packages/server/tests/unit/apis/mcpOAuth.test.tsindex 01d768bf3..dc52f723a 100644--- a/packages/server/tests/unit/apis/mcpOAuth.test.ts+++ b/packages/server/tests/unit/apis/mcpOAuth.test.ts@@ -1,8 +1,7 @@/*** Authorize + OAuth callback against real sqlite stores with fetch stubbed- * (same pattern as packages/harness MCP OAuth tests).+ * (same pattern as the server MCP OAuth helper tests).*/-import { mcpOAuthCallbackUrl } from '@truefoundry/utils-core/core';import winston from 'winston';import { createMcpOAuthRouter } from '../../../src/apis/mcpOAuth';import { createMcpServersRouter } from '../../../src/apis/mcpServers';@@ -11,6 +10,7 @@ import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';import { SqliteOAuthTokenStore } from '../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';+import { mcpOAuthCallbackUrl } from '../../../src/mcp/auth/mcpOAuthHelpers';const AS_ORIGIN = 'https://auth.example.com';const MCP_URL = 'https://mcp.example.com/sse';diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/server/tests/unit/mcp/auth/mcpOAuth.test.tssimilarity index 96%rename from packages/harness/tests/core/mcp/auth/mcpOAuth.test.tsrename to packages/server/tests/unit/mcp/auth/mcpOAuth.test.tsindex 23143f276..34cdbb363 100644--- a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts+++ b/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts@@ -3,20 +3,22 @@* Global fetch is stubbed; production code uses real fetch only.*/import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';+import { McpConnectionError } from '@truefoundry/utils-core/core';+import { InMemoryOAuthClientStore, InMemoryOAuthTokenStore } from '../../../../src/mcp/auth/inMemoryStores';import {- DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,- InMemoryOAuthClientStore,- InMemoryOAuthTokenStore,- McpConnectionError,buildMcpAuthorizationUrl,completeMcpAuthorization,createMcpOAuthClient,ensureMcpClientRegistered,isMcpAuthRequired,- mcpOAuthCallbackUrl,resolveMcpAuth,- type OAuthClientRecord,-} from '../../../../src/core';+} from '../../../../src/mcp/auth/mcpDcr';+import {+ DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,+ mcpOAuthCallbackUrl,+ validateRedirectUris,+} from '../../../../src/mcp/auth/mcpOAuthHelpers';+import type { OAuthClientRecord } from '../../../../src/mcp/auth/types';interface Stores {tokenStore: InMemoryOAuthTokenStore;@@ -701,3 +703,21 @@ describe('completeMcpAuthorization', () => {expect(await stores.tokenStore.getToken({ id: SERVER_ID })).toBeUndefined();});});++describe('validateRedirectUris', () => {+ it('accepts http(s) URLs', () => {+ expect(() =>+ validateRedirectUris({+ redirectUris: ['https://harness.example.com/settings', 'http://localhost:3000/cb'],+ }),+ ).not.toThrow();+ });++ it('rejects non-http(s) URIs', () => {+ expect(() => validateRedirectUris({ redirectUris: ['javascript:alert(1)'] })).toThrow(/Must be a valid URL/);+ });++ it('rejects malformed URIs', () => {+ expect(() => validateRedirectUris({ redirectUris: ['not-a-url'] })).toThrow(McpConnectionError);+ });+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex ae808372a..08afe18fc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -213,6 +213,9 @@ importers:'@hono/zod-openapi':specifier: ^1.5.1version: 1.5.1([email protected])([email protected])+ '@modelcontextprotocol/sdk':+ specifier: ^1.29.0+ version: 1.29.0([email protected])([email protected])'@truefoundry/utils-core':specifier: workspace:*version: link:../harness@@ -4092,10 +4095,6 @@ packages:resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==}engines: {node: '>=0.10.0'}- resolution: {integrity: sha512-zJIHFrl6bq3RDd2YusFNCDlM8qUprxKswyi/OPzPyzKDdyBXDqWx8bZlZ7R+saTdSTatUmb3O7K4SspGPaEOQg==}- engines: {node: '>=16.9.0'}-resolution: {integrity: sha512-jhunvfHWxd7J5EFfSgH4xsYJzSe/lfqbUCxiyyeaQasUsXeEHXtzVid+7EOGByc5JnFa23SSFL3Y2RV/z1T+eQ==}engines: {node: '>=16.9.0'}@@ -6928,9 +6927,9 @@ snapshots:protobufjs: 7.6.5yargs: 17.7.3- '@hono/[email protected]([email protected])':+ '@hono/[email protected]([email protected])':dependencies:- hono: 4.12.31+ hono: 4.13.0'@hono/[email protected]([email protected])':dependencies:@@ -7193,7 +7192,7 @@ snapshots:dependencies:- '@hono/node-server': 1.19.14([email protected])+ '@hono/node-server': 1.19.14([email protected])ajv: 8.20.0ajv-formats: 3.0.1([email protected])content-type: 1.0.5@@ -7203,7 +7202,7 @@ snapshots:eventsource-parser: 3.1.0express: 5.2.1([email protected])- hono: 4.12.31+ hono: 4.13.0jose: 6.2.4json-schema-typed: 8.0.2pkce-challenge: 5.0.1@@ -10107,8 +10106,6 @@ snapshots:dependencies:parse-passwd: 1.0.0- [email protected]: {}-