Skip to content

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

refactor(mcp): move DCR authorize/status/revoke onto Store (#549)

Heer Ambavi541d65d9b393
diff --git a/.changeset/mcp-server-store-auth.md b/.changeset/mcp-server-store-auth.md
new file mode 100644
index 000000000..0f635c373
--- /dev/null
+++ b/.changeset/mcp-server-store-auth.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge": patch
+---
+
+Split MCP server persistence (`IMcpServerStore`) from Connect UX auth (`IMcpServerWithAuthStore` / `McpServerWithAuthStore`) so DB backends stay CRUD + OAuth client columns while authorize/status/revoke compose in via a token store.
diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.ts
index 0613b9fe7..5e3436195 100644
--- a/packages/trueforge/scripts/write-openapi.ts
+++ b/packages/trueforge/scripts/write-openapi.ts
@@ -18,6 +18,8 @@ import { McpCatalog } from '../src/catalog/McpCatalog';
import { ModelCatalog } from '../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../src/catalog/SandboxCatalog';
import { SkillCatalog } from '../src/catalog/SkillCatalog';
+import configuration from '../src/config';
+import { McpServerWithAuthStore } from '../src/db/McpServerWithAuthStore';
import { SqliteAgentStore } from '../src/db/sqlite/agent-store/SqliteAgentStore';
import { createSqliteDb } from '../src/db/sqlite/client';
import { SqliteMcpServerStore } from '../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
@@ -56,13 +58,18 @@ function canonicalise(value: unknown): unknown {
// Unconnected stand-ins suffice: route registration never reads a dependency.
const sessionStore = new InMemorySessionStore();
const db = createSqliteDb(':memory:');
+const tokenStore = new SqliteOAuthTokenStore(db);
const app = createServerApp({
modelCatalog: ModelCatalog.load(),
resolveModelProviderStore: () => new SqliteModelProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),
mcpCatalog: McpCatalog.load(),
- mcpServerStore: new SqliteMcpServerStore(db),
- tokenStore: new SqliteOAuthTokenStore(db),
+ mcpServerStore: new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ }),
+ tokenStore,
skillCatalog: SkillCatalog.load(),
skillStore: new SqliteSkillStore(db),
sandboxCatalog: SandboxCatalog.load(),
diff --git a/packages/trueforge/src/apis/mcpServers.ts b/packages/trueforge/src/apis/mcpServers.ts
index 8a1c1d128..fd26008b1 100644
--- a/packages/trueforge/src/apis/mcpServers.ts
+++ b/packages/trueforge/src/apis/mcpServers.ts
@@ -4,11 +4,16 @@ import type { Logger } from 'winston';
import type { ResolveUserContext } from '../auth/identity';
import { safeReturnTo } from '../auth/safeReturnTo';
import configuration from '../config';
-import { McpServerNameConflictError, type IMcpServerStore, type McpServerRecord } from '../db/mcpServerStore';
+import {
+ McpServerNameConflictError,
+ McpServerNotFoundError,
+ type IMcpServerWithAuthStore,
+ type McpServerRecord,
+} from '../db/mcpServerStore';
import type { WithTransaction } from '../db/transaction';
-import { createMcpOAuthClient, isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';
+import { createMcpOAuthClient } from '../mcp/auth/mcpDcr';
import { mcpOAuthCallbackUrl } from '../mcp/auth/mcpOAuthHelpers';
-import type { IOAuthTokenStore, OAuthClientRecord, OAuthToken } from '../mcp/auth/types';
+import type { IOAuthTokenStore, OAuthClientRecord } from '../mcp/auth/types';
import {
authorizeMcpServerRoute,
createMcpServerRoute,
@@ -28,12 +33,11 @@ import type {
McpServerManifest,
UpdateMcpServerRequest,
} from '../schemas/mcpServer';
-import { resolveMcpAuthStatus } from '../schemas/mcpServer';
import { MissingStoredSecretError, resolveStoredSecretValue, toRedactedSecretValue } from '../utils/secretRedaction';
import { TENANT_ID } from './sessions';
export interface McpServersRouterDeps<TTransaction> {
- mcpServerStore: IMcpServerStore<TTransaction>;
+ mcpServerStore: IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
logger: Logger;
@@ -95,44 +99,19 @@ function resolveMcpServerManifestForWrite({
};
}
-/**
- * `token` is the calling user's DCR access token for this server (keyed by `record.id` +
- * `userRef`), or undefined for header/no-auth servers and DCR servers that have never
- * authorized for this user. Only DCR reads it.
- */
-function toConfiguredMcpServer({
- record,
- token,
-}: {
+async function toConfiguredMcpServer<TTransaction>(params: {
+ store: IMcpServerWithAuthStore<TTransaction>;
record: McpServerRecord;
- token: OAuthToken | undefined;
-}): ConfiguredMcpServer {
- return {
- name: record.name,
- manifest: redactMcpServerManifest(record.manifest),
- auth_status: resolveMcpAuthStatus({
- manifest: record.manifest,
- ...(token !== undefined ? { token } : {}),
- }),
- };
-}
-
-function toAvailableMcpServer({
- record,
- token,
-}: {
- record: McpServerRecord;
- token: OAuthToken | undefined;
-}): AvailableMcpServer {
- const authType = record.manifest.auth?.type;
+ userRef: string;
+}): Promise<ConfiguredMcpServer> {
+ const statuses = await params.store.resolveAuthStatuses({
+ records: [params.record],
+ userRef: params.userRef,
+ });
return {
- name: record.name,
- url: record.manifest.url,
- ...(authType !== undefined ? { auth: { type: authType } } : {}),
- auth_status: resolveMcpAuthStatus({
- manifest: record.manifest,
- ...(token !== undefined ? { token } : {}),
- }),
+ name: params.record.name,
+ manifest: redactMcpServerManifest(params.record.manifest),
+ auth_status: statuses.get(params.record.name) ?? { status: 'auth_required' },
};
}
@@ -140,28 +119,33 @@ function toAvailableMcpServer({
export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listMcpServersRoute> = async c => {
const userRef = deps.resolveUserContext(c).userRef;
- const records = await deps.mcpServerStore.listServers({ tenant_id: TENANT_ID, names: undefined });
- // Only DCR servers have tokens; batch the lookup for this user.
- const dcrIds = records.filter(record => record.manifest.auth?.type === 'dcr').map(record => record.id);
- const tokens = await deps.tokenStore.getTokens({ ids: dcrIds, userRef });
- return c.json(
- { data: records.map(record => toConfiguredMcpServer({ record, token: tokens.get(record.id) })) },
- 200,
- );
+ const records = await deps.mcpServerStore.listServers({
+ tenant_id: TENANT_ID,
+ names: undefined,
+ });
+ const statuses = await deps.mcpServerStore.resolveAuthStatuses({
+ records,
+ userRef,
+ });
+ const data: ConfiguredMcpServer[] = records.map(record => ({
+ name: record.name,
+ manifest: redactMcpServerManifest(record.manifest),
+ auth_status: statuses.get(record.name) ?? { status: 'auth_required' },
+ }));
+ return c.json({ data }, 200);
};
const getHandler: RouteHandler<typeof getMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
const userRef = deps.resolveUserContext(c).userRef;
- const record = await deps.mcpServerStore.getServer({ tenant_id: TENANT_ID, name });
+ const record = await deps.mcpServerStore.getServer({
+ tenant_id: TENANT_ID,
+ name,
+ });
if (!record) {
return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
}
- let token: OAuthToken | undefined;
- if (record.manifest.auth?.type === 'dcr') {
- token = await deps.tokenStore.getToken({ id: record.id, userRef });
- }
- return c.json({ data: toConfiguredMcpServer({ record, token }) }, 200);
+ return c.json({ data: await toConfiguredMcpServer({ store: deps.mcpServerStore, record, userRef }) }, 200);
};
const createHandler: RouteHandler<typeof createMcpServerRoute> = async c => {
@@ -217,7 +201,16 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
return saved;
});
- return c.json({ data: toConfiguredMcpServer({ record, token: undefined }) }, 201);
+ return c.json(
+ {
+ data: await toConfiguredMcpServer({
+ store: deps.mcpServerStore,
+ record,
+ userRef: deps.resolveUserContext(c).userRef,
+ }),
+ },
+ 201,
+ );
} catch (error) {
if (error instanceof McpServerNameConflictError) {
return c.json({ error: { message: error.message } }, 409);
@@ -287,11 +280,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRou
return saved;
});
- // A re-upsert preserves `id`, so a DCR server may already carry a token from a prior authorize
- // (unless this PUT changed the URL and cleared all tokens above).
- const token =
- record.manifest.auth?.type === 'dcr' ? await deps.tokenStore.getToken({ id: record.id, userRef }) : undefined;
- return c.json({ data: toConfiguredMcpServer({ record, token }) }, 200);
+ return c.json({ data: await toConfiguredMcpServer({ store: deps.mcpServerStore, record, userRef }) }, 200);
} catch (error) {
if (error instanceof MissingStoredSecretError) {
return c.json({ error: { message: 'Header secret is required' } }, 400);
@@ -321,38 +310,23 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const { name } = c.req.valid('param');
const { return_to: returnTo } = c.req.valid('query');
const userRef = deps.resolveUserContext(c).userRef;
- const record = await deps.mcpServerStore.getServer({ tenant_id: TENANT_ID, name });
- if (!record) {
- return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
- }
-
- if (record.manifest.auth?.type !== 'dcr') {
- return c.json(resolveMcpAuthStatus({ manifest: record.manifest }), 200);
- }
if (returnTo && safeReturnTo(returnTo) !== returnTo) {
return c.json({ error: { message: 'Invalid return_to: must be a same-origin relative path' } }, 400);
}
try {
- // Reuses a usable/refreshable token when present; only builds an auth URL when needed.
- // Client is usually already registered at create/put; concurrent Connect races are harmless
- // (last saveClient wins; rare orphan AS registration).
- const result = await resolveMcpAuth({
- tokenStore: deps.tokenStore,
- mcpServerStore: deps.mcpServerStore,
- serverId: record.id,
+ const authStatus: McpAuthStatus = await deps.mcpServerStore.authorize({
+ tenant_id: TENANT_ID,
+ name,
userRef,
- mcpServerUrl: record.manifest.url,
- mcpServerName: record.name,
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
...(returnTo !== undefined ? { returnTo } : {}),
});
- const authStatus: McpAuthStatus = isMcpAuthRequired(result)
- ? { status: 'auth_required', authorization_url: result.authUrl.href }
- : { status: 'authenticated' };
return c.json(authStatus, 200);
} catch (error) {
+ if (error instanceof McpServerNotFoundError) {
+ return c.json({ error: { message: error.message } }, 404);
+ }
if (error instanceof McpConnectionError) {
deps.logger.warn(`MCP authorize failed for "${name}"`, extractErrorLogFields(error));
if (error.statusCode === 400) {
@@ -418,30 +392,54 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
const deleteAuthorizationHandler: RouteHandler<typeof deleteAuthorizationMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
const userRef = deps.resolveUserContext(c).userRef;
- const record = await deps.mcpServerStore.getServer({ tenant_id: TENANT_ID, name });
- if (!record) {
- return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
- }
- // DCR: drop this user's token only — keep oauth_server / oauth_client so re-authorize can skip DCR.
- // Header / no-auth: no-op.
- if (record.manifest.auth?.type === 'dcr') {
- await deps.tokenStore.deleteToken({ id: record.id, userRef });
+ try {
+ const record = await deps.mcpServerStore.getServer({
+ tenant_id: TENANT_ID,
+ name,
+ });
+ if (!record) {
+ return c.json({ error: { message: `MCP server not found: ${name}` } }, 404);
+ }
+ await deps.mcpServerStore.deleteAuthorization({
+ tenant_id: TENANT_ID,
+ name,
+ userRef,
+ });
+ return c.json(
+ {
+ data: await toConfiguredMcpServer({ store: deps.mcpServerStore, record, userRef }),
+ },
+ 200,
+ );
+ } catch (error) {
+ if (error instanceof McpServerNotFoundError) {
+ return c.json({ error: { message: error.message } }, 404);
+ }
+ throw error;
}
- return c.json({ data: toConfiguredMcpServer({ record, token: undefined }) }, 200);
};
const router = new OpenAPIHono();
router.openapi(listAvailableMcpServersRoute, async c => {
const userRef = deps.resolveUserContext(c).userRef;
- const records = await deps.mcpServerStore.listServers({ tenant_id: TENANT_ID, names: undefined });
- const dcrIds = records.filter(record => record.manifest.auth?.type === 'dcr').map(record => record.id);
- const tokens = await deps.tokenStore.getTokens({ ids: dcrIds, userRef });
- return c.json(
- {
- data: records.map(record => toAvailableMcpServer({ record, token: tokens.get(record.id) })),
- },
- 200,
- );
+ const records = await deps.mcpServerStore.listServers({
+ tenant_id: TENANT_ID,
+ names: undefined,
+ });
+ const statuses = await deps.mcpServerStore.resolveAuthStatuses({
+ records,
+ userRef,
+ });
+ const data: AvailableMcpServer[] = records.map(record => {
+ const authType = record.manifest.auth?.type;
+ return {
+ name: record.name,
+ url: record.manifest.url,
+ ...(authType !== undefined ? { auth: { type: authType } } : {}),
+ auth_status: statuses.get(record.name) ?? { status: 'auth_required' },
+ };
+ });
+ return c.json({ data }, 200);
});
router.openapi(listMcpServerToolsRoute, listToolsHandler);
router.openapi(authorizeMcpServerRoute, authorizeHandler);
diff --git a/packages/trueforge/src/apis/settings.ts b/packages/trueforge/src/apis/settings.ts
index c87ec231e..c3ddb9e2c 100644
--- a/packages/trueforge/src/apis/settings.ts
+++ b/packages/trueforge/src/apis/settings.ts
@@ -7,7 +7,7 @@ import { OpenAPIHono } from '@hono/zod-openapi';
import type { Context } from 'hono';
import type { Logger } from 'winston';
import type { ResolveUserContext } from '../auth/identity';
-import type { IMcpServerStore } from '../db/mcpServerStore';
+import type { IMcpServerWithAuthStore } from '../db/mcpServerStore';
import type { IModelProviderStore } from '../db/modelProviderStore';
import type { ISandboxProviderStore } from '../db/sandboxProviderStore';
import type { ISkillStore } from '../db/skillStore';
@@ -20,7 +20,7 @@ import { createSkillsRouter } from './skills';
export interface SettingsRouterDeps<TTransaction> {
resolveModelProviderStore: (c: Context) => IModelProviderStore<TTransaction>;
- mcpServerStore: IMcpServerStore<TTransaction>;
+ mcpServerStore: IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts
index caf963a70..2e04247dc 100644
--- a/packages/trueforge/src/app.ts
+++ b/packages/trueforge/src/app.ts
@@ -31,7 +31,7 @@ import type { SandboxCatalog } from './catalog/SandboxCatalog';
import type { SkillCatalog } from './catalog/SkillCatalog';
import configuration from './config';
import type { IAgentStore } from './db/agentStore';
-import type { IMcpServerStore } from './db/mcpServerStore';
+import type { IMcpServerWithAuthStore } from './db/mcpServerStore';
import type { IModelProviderStore } from './db/modelProviderStore';
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
import type { IScheduleStore } from './db/scheduleStore';
@@ -171,7 +171,7 @@ export interface ServerDeps<TTransaction> {
*/
resolveModelProviderStore: (c?: Context) => IModelProviderStore<TTransaction>;
withTransaction: WithTransaction<TTransaction>;
- mcpServerStore: IMcpServerStore<TTransaction>;
+ mcpServerStore: IMcpServerWithAuthStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
skillStore: ISkillStore<TTransaction>;
sandboxProviderStore: ISandboxProviderStore<TTransaction>;
diff --git a/packages/trueforge/src/db/McpServerWithAuthStore.ts b/packages/trueforge/src/db/McpServerWithAuthStore.ts
new file mode 100644
index 000000000..9828d27fb
--- /dev/null
+++ b/packages/trueforge/src/db/McpServerWithAuthStore.ts
@@ -0,0 +1,119 @@
+/**
+ * Wraps a DB-backed {@link IMcpServerStore} with local DCR authorize / status / revoke
+ * so API handlers can call auth methods on the store without depending on a token store.
+ */
+import { isMcpAuthRequired, resolveMcpAuth } from '../mcp/auth/mcpDcr';
+import type { IOAuthTokenStore, OAuthClientRecord } from '../mcp/auth/types';
+import { resolveMcpAuthStatus, type McpAuthStatus } from '../schemas/mcpServer';
+import {
+ McpServerNotFoundError,
+ type AuthorizeMcpServerInput,
+ type CreateMcpServerInput,
+ type DeleteMcpAuthorizationInput,
+ type GetMcpServerInput,
+ type IMcpServerStore,
+ type IMcpServerWithAuthStore,
+ type ListMcpServersInput,
+ type McpServerRecord,
+ type ResolveMcpAuthStatusesInput,
+ type UpsertMcpServerInput,
+} from './mcpServerStore';
+
+export class McpServerWithAuthStore<TTransaction = never> implements IMcpServerWithAuthStore<TTransaction> {
+ readonly #store: IMcpServerStore<TTransaction>;
+ readonly #tokenStore: IOAuthTokenStore<TTransaction>;
+ readonly #clientName: string;
+
+ constructor(input: {
+ store: IMcpServerStore<TTransaction>;
+ tokenStore: IOAuthTokenStore<TTransaction>;
+ clientName: string;
+ }) {
+ this.#store = input.store;
+ this.#tokenStore = input.tokenStore;
+ this.#clientName = input.clientName;
+ }
+
+ listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]> {
+ return this.#store.listServers(input, transaction);
+ }
+
+ getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined> {
+ return this.#store.getServer(input, transaction);
+ }
+
+ getServerForUpdate(input: GetMcpServerInput, transaction: TTransaction): Promise<McpServerRecord | undefined> {
+ return this.#store.getServerForUpdate(input, transaction);
+ }
+
+ createServer(input: CreateMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {
+ return this.#store.createServer(input, transaction);
+ }
+
+ upsertServer(input: UpsertMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord> {
+ return this.#store.upsertServer(input, transaction);
+ }
+
+ saveClient(params: { id: string; record: OAuthClientRecord }, transaction?: TTransaction): Promise<void> {
+ return this.#store.saveClient(params, transaction);
+ }
+
+ getClient(params: { id: string }, transaction?: TTransaction): Promise<OAuthClientRecord | undefined> {
+ return this.#store.getClient(params, transaction);
+ }
+
+ deleteClient(params: { id: string }, transaction?: TTransaction): Promise<void> {
+ return this.#store.deleteClient(params, transaction);
+ }
+
+ async resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>> {
+ const dcrIds = input.records.filter(record => record.manifest.auth?.type === 'dcr').map(record => record.id);
+ const tokens = await this.#tokenStore.getTokens({ ids: dcrIds, userRef: input.userRef });
+ const out = new Map<string, McpAuthStatus>();
+ for (const record of input.records) {
+ const token = tokens.get(record.id);
+ out.set(
+ record.name,
+ resolveMcpAuthStatus({
+ manifest: record.manifest,
+ ...(token !== undefined ? { token } : {}),
+ }),
+ );
+ }
+ return out;
+ }
+
+ async authorize(input: AuthorizeMcpServerInput): Promise<McpAuthStatus> {
+ void input.redirectURL;
+ const record = await this.#store.getServer({ tenant_id: input.tenant_id, name: input.name });
+ if (record === undefined) {
+ throw new McpServerNotFoundError(input.name);
+ }
+ if (record.manifest.auth?.type !== 'dcr') {
+ return resolveMcpAuthStatus({ manifest: record.manifest });
+ }
+ const result = await resolveMcpAuth({
+ tokenStore: this.#tokenStore,
+ mcpServerStore: this.#store,
+ serverId: record.id,
+ userRef: input.userRef,
+ mcpServerUrl: record.manifest.url,
+ mcpServerName: record.name,
+ clientName: this.#clientName,
+ ...(input.returnTo !== undefined ? { returnTo: input.returnTo } : {}),
+ });
+ return isMcpAuthRequired(result)
+ ? { status: 'auth_required', authorization_url: result.authUrl.href }
+ : { status: 'authenticated' };
+ }
+
+ async deleteAuthorization(input: DeleteMcpAuthorizationInput): Promise<void> {
+ const record = await this.#store.getServer({ tenant_id: input.tenant_id, name: input.name });
+ if (record === undefined) {
+ throw new McpServerNotFoundError(input.name);
+ }
+ if (record.manifest.auth?.type === 'dcr') {
+ await this.#tokenStore.deleteToken({ id: record.id, userRef: input.userRef });
+ }
+ }
+}
diff --git a/packages/trueforge/src/db/mcpServerStore.ts b/packages/trueforge/src/db/mcpServerStore.ts
index 762f736c8..8bb6f5ea1 100644
--- a/packages/trueforge/src/db/mcpServerStore.ts
+++ b/packages/trueforge/src/db/mcpServerStore.ts
@@ -1,10 +1,11 @@
/**
- * DB-backed configured MCP servers: one row per server per tenant,
- * identity as columns plus a Zod-validated `McpServerManifest` jsonb document.
- * Implementations: PostgresMcpServerStore and SqliteMcpServerStore.
+ * Configured MCP servers: one row per server per tenant, identity as columns plus a
+ * Zod-validated `McpServerManifest` jsonb document.
*
- * Also owns the DCR registration columns (`oauth_server` / `oauth_client`) via
- * `IOAuthClientStore` — those are not a separate persistence root.
+ * - {@link IMcpServerStore}: DB CRUD + DCR client columns (`IOAuthClientStore`).
+ * Implemented by PostgresMcpServerStore / SqliteMcpServerStore.
+ * - {@link IMcpServerWithAuthStore}: persistence + authorize / status / revoke;
+ * {@link McpServerWithAuthStore} (separate module) composes an {@link IMcpServerStore} + a token store.
*
* OAuth JSONB wire shapes (snake_case) and camelCase ↔ storage mappers live here
* alongside the store contract — absence is an explicit `| null`, not an optional `?:`.
@@ -16,7 +17,7 @@ import type {
IOAuthClientStore,
} from '../mcp/auth/types';
import type { ResourceName } from '../schemas/common';
-import type { McpServerManifest } from '../schemas/mcpServer';
+import type { McpAuthStatus, McpServerManifest } from '../schemas/mcpServer';
export interface McpServerRecord {
id: string;
@@ -62,6 +63,39 @@ export class McpServerNameConflictError extends Error {
}
}
+/** Thrown when authorize/revoke/status targets an unknown server name. */
+export class McpServerNotFoundError extends Error {
+ readonly server_name: string;
+
+ constructor(name: string) {
+ super(`MCP server not found: ${name}`);
+ this.name = 'McpServerNotFoundError';
+ this.server_name = name;
+ }
+}
+
+export interface ResolveMcpAuthStatusesInput {
+ records: readonly McpServerRecord[];
+ userRef: string;
+}
+
+export interface AuthorizeMcpServerInput {
+ tenant_id: string;
+ name: string;
+ userRef: string;
+ /** Relative same-origin path for local DCR pending-auth return. */
+ returnTo?: string;
+ /** Absolute redirect URL when a remote auth backend needs a full callback URL. */
+ redirectURL?: string;
+}
+
+export interface DeleteMcpAuthorizationInput {
+ tenant_id: string;
+ name: string;
+ userRef: string;
+}
+
+/** Row persistence + DCR client columns — no authorize/status/revoke. */
export interface IMcpServerStore<TTransaction = never> extends IOAuthClientStore<TTransaction> {
listServers(input: ListMcpServersInput, transaction?: TTransaction): Promise<McpServerRecord[]>;
getServer(input: GetMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord | undefined>;
@@ -80,6 +114,22 @@ export interface IMcpServerStore<TTransaction = never> extends IOAuthClientStore
upsertServer(input: UpsertMcpServerInput, transaction?: TTransaction): Promise<McpServerRecord>;
}
+/**
+ * Settings/MCP API store: persistence plus Connect UX auth.
+ * McpServerWithAuthStore implements via a token store; remote-backed stores may call
+ * an upstream status/authorize API instead.
+ */
+export interface IMcpServerWithAuthStore<TTransaction = never> extends IMcpServerStore<TTransaction> {
+ /** Wire `auth_status` for Connect UX, keyed by server name. */
+ resolveAuthStatuses(input: ResolveMcpAuthStatusesInput): Promise<ReadonlyMap<string, McpAuthStatus>>;
+
+ /** Start or resume authorization; returns `auth_required` + URL or `authenticated`. */
+ authorize(input: AuthorizeMcpServerInput): Promise<McpAuthStatus>;
+
+ /** Revoke this subject's authorization for the named server. */
+ deleteAuthorization(input: DeleteMcpAuthorizationInput): Promise<void>;
+}
+
/**
* 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
diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts
index 9b76a49d0..4ad4d3e72 100644
--- a/packages/trueforge/src/main.ts
+++ b/packages/trueforge/src/main.ts
@@ -56,7 +56,8 @@ import { SkillCatalog } from './catalog/SkillCatalog';
import { type DistributedServerConfiguration } from './config';
import { createController } from './controller';
import type { IAgentStore } from './db/agentStore';
-import type { IMcpServerStore } from './db/mcpServerStore';
+import type { IMcpServerStore, IMcpServerWithAuthStore } from './db/mcpServerStore';
+import { McpServerWithAuthStore } from './db/McpServerWithAuthStore';
import type { IModelProviderStore } from './db/modelProviderStore';
import type { Database as PostgresDatabase } from './db/postgres/types';
import type { ISandboxProviderStore } from './db/sandboxProviderStore';
@@ -252,7 +253,7 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
sessionMetricsStore,
resolveModelProviderStore,
withTransaction,
- mcpServerStore,
+ mcpServerStore: persistenceMcpServerStore,
tokenStore,
skillStore,
sandboxProviderStore,
@@ -262,6 +263,12 @@ async function createServerRuntime<TTransaction>(persistence: ServerPersistence<
redis,
} = persistence;
+ const mcpServerStore: IMcpServerWithAuthStore<TTransaction> = new McpServerWithAuthStore({
+ store: persistenceMcpServerStore,
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
+
const activeTurns = new ActiveTurnRegistry();
const requestReplyRouter = new RequestReplyRouter();
const eventSubscriptions = new EventSubscriptionRegistry<TurnStreamingEvent>(redis);
diff --git a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
index d340f3f7d..cad1a0d23 100644
--- a/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpOAuth.test.ts
@@ -6,6 +6,9 @@ import winston from 'winston';
import { createMcpOAuthRouter } from '../../../src/apis/mcpOAuth';
import { createMcpServersRouter, createSettingsMcpServersRouter } from '../../../src/apis/mcpServers';
import { LOCAL_USER_CONTEXT } from '../../../src/auth/identity';
+import configuration from '../../../src/config';
+import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
+import type { IMcpServerWithAuthStore } from '../../../src/db/mcpServerStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { createSqliteDb } from '../../../src/db/sqlite/client';
import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
@@ -75,7 +78,7 @@ describe('MCP OAuth authorize + callback', () => {
let settingsRouter: ReturnType<typeof createSettingsMcpServersRouter>;
let mcpServersRouter: ReturnType<typeof createMcpServersRouter>;
let oauthRouter: ReturnType<typeof createMcpOAuthRouter>;
- let mcpServerStore: SqliteMcpServerStore;
+ let mcpServerStore: IMcpServerWithAuthStore;
let tokenStore: SqliteOAuthTokenStore;
let withTransaction: <T>(callback: (transaction: unknown) => Promise<T>) => Promise<T>;
let logger: ReturnType<typeof winston.createLogger>;
@@ -83,8 +86,12 @@ describe('MCP OAuth authorize + callback', () => {
beforeAll(async () => {
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
- mcpServerStore = new SqliteMcpServerStore(db);
tokenStore = new SqliteOAuthTokenStore(db);
+ mcpServerStore = new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
withTransaction = callback => db.transaction().execute(callback);
logger = winston.createLogger({ silent: true });
settingsRouter = createSettingsMcpServersRouter({
diff --git a/packages/trueforge/tests/unit/apis/mcpServers.test.ts b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
index 725c73239..25afde3e5 100644
--- a/packages/trueforge/tests/unit/apis/mcpServers.test.ts
+++ b/packages/trueforge/tests/unit/apis/mcpServers.test.ts
@@ -7,6 +7,9 @@ import { McpCatalog } from '../../../src/catalog/McpCatalog';
import { ModelCatalog } from '../../../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../../../src/catalog/SandboxCatalog';
import { SkillCatalog } from '../../../src/catalog/SkillCatalog';
+import configuration from '../../../src/config';
+import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
+import type { IMcpServerWithAuthStore } from '../../../src/db/mcpServerStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import { createSqliteDb } from '../../../src/db/sqlite/client';
import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';
@@ -83,7 +86,7 @@ describe('mcp-servers routers', () => {
let settingsRouter: ReturnType<typeof createSettingsMcpServersRouter>;
let catalogRouter: ReturnType<typeof createCatalogRouter>;
let mcpServersRouter: ReturnType<typeof createMcpServersRouter>;
- let mcpServerStore: SqliteMcpServerStore;
+ let mcpServerStore: IMcpServerWithAuthStore;
let tokenStore: SqliteOAuthTokenStore;
let withTransaction: <T>(callback: (transaction: unknown) => Promise<T>) => Promise<T>;
let logger: ReturnType<typeof winston.createLogger>;
@@ -97,8 +100,12 @@ describe('mcp-servers routers', () => {
}) as typeof fetch;
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
- mcpServerStore = new SqliteMcpServerStore(db);
tokenStore = new SqliteOAuthTokenStore(db);
+ mcpServerStore = new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
withTransaction = callback => db.transaction().execute(callback);
logger = winston.createLogger({ silent: true });
settingsRouter = createSettingsMcpServersRouter({
diff --git a/packages/trueforge/tests/unit/apis/modelProviders.test.ts b/packages/trueforge/tests/unit/apis/modelProviders.test.ts
index 98808aec3..d235ada59 100644
--- a/packages/trueforge/tests/unit/apis/modelProviders.test.ts
+++ b/packages/trueforge/tests/unit/apis/modelProviders.test.ts
@@ -8,6 +8,8 @@ import { McpCatalog } from '../../../src/catalog/McpCatalog';
import { ModelCatalog } from '../../../src/catalog/ModelCatalog';
import { SandboxCatalog } from '../../../src/catalog/SandboxCatalog';
import { SkillCatalog } from '../../../src/catalog/SkillCatalog';
+import configuration from '../../../src/config';
+import { McpServerWithAuthStore } from '../../../src/db/McpServerWithAuthStore';
import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';
import type { IModelProviderStore } from '../../../src/db/modelProviderStore';
import { createSqliteDb } from '../../../src/db/sqlite/client';
@@ -92,11 +94,16 @@ async function createRouters(): Promise<{
const db = createSqliteDb(':memory:');
await migrateSqliteToLatest(db);
const modelProviderStore = new SqliteModelProviderStore(db);
+ const tokenStore = new SqliteOAuthTokenStore(db);
return {
settingsRouter: createSettingsRouter({
resolveModelProviderStore: () => modelProviderStore,
- mcpServerStore: new SqliteMcpServerStore(db),
- tokenStore: new SqliteOAuthTokenStore(db),
+ mcpServerStore: new McpServerWithAuthStore({
+ store: new SqliteMcpServerStore(db),
+ tokenStore,
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ }),
+ tokenStore,
skillStore: new SqliteSkillStore(db),
sandboxProviderStore: new SqliteSandboxProviderStore(db),
withTransaction: callback => db.transaction().execute(callback),