The open-source agent harness - the runtime layer that turns an LLM into a working agent.
AGE-1552: Support DCR in create, update, list MCP APIs (#42)
Heer Ambavi2e3a65676c38
diff --git a/packages/harness/src/core/auth/IOAuthTokenStore.ts b/packages/harness/src/core/auth/IOAuthTokenStore.tsindex 57cd96481..5d2dc4620 100644--- a/packages/harness/src/core/auth/IOAuthTokenStore.ts+++ b/packages/harness/src/core/auth/IOAuthTokenStore.ts@@ -38,5 +38,7 @@ export interface IOAuthTokenStore {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/InMemoryOAuthTokenStore.ts b/packages/harness/src/core/auth/InMemoryOAuthTokenStore.tsindex ccbb1d5cb..e76c1fd5c 100644--- a/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts+++ b/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts@@ -33,6 +33,17 @@ export class InMemoryOAuthTokenStore implements IOAuthTokenStore {return this.tokens.get(params.id);}+ async getTokens(params: { ids: string[] }): Promise<Map<string, OAuthToken>> {+ const out = new Map<string, OAuthToken>();+ for (const id of params.ids) {+ const token = this.tokens.get(id);+ if (token) {+ out.set(id, token);+ }+ }+ return out;+ }+async deleteToken(params: { id: string }): Promise<void> {this.tokens.delete(params.id);}diff --git a/packages/harness/src/core/auth/oauthToken.ts b/packages/harness/src/core/auth/oauthToken.tsnew file mode 100644index 000000000..57e33d480--- /dev/null+++ b/packages/harness/src/core/auth/oauthToken.ts@@ -0,0 +1,5 @@+/** 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/errors.ts b/packages/harness/src/core/errors.tsindex 4689a5dae..554133bd4 100644--- a/packages/harness/src/core/errors.ts+++ b/packages/harness/src/core/errors.ts@@ -60,3 +60,13 @@ export class McpConnectionError extends AgentHarnessError {this.name = 'McpConnectionError';}}++/**+ * An MCP server's `auth.type: dcr` is unsatisfiable by configuration, not by a transient fault+ */+export class McpDcrConfigurationError extends McpConnectionError {+ constructor(message: string, options?: ErrorOptions) {+ super(message, 400, options);+ this.name = 'McpDcrConfigurationError';+ }+}diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsindex a916baccf..6f0b38d70 100644--- a/packages/harness/src/core/index.ts+++ b/packages/harness/src/core/index.ts@@ -57,6 +57,7 @@ export type {OAuthServerMetadata,} from './auth/IOAuthClientStore';export type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from './auth/IOAuthTokenStore';+export { isOAuthAccessTokenUsable } from './auth/oauthToken';// MCP contractsexport type { ApprovalDecision } from './events/schema';@@ -143,8 +144,9 @@ export type {} from './tracing/AgentTracing';// Errors / utils-export { AgentHarnessError, McpConnectionError } from './errors';+export { AgentHarnessError, McpConnectionError, McpDcrConfigurationError } from './errors';export { extractErrorLogFields } from './util/errorLogFields';+export { PromiseTimeoutError, withTimeout } from './util/promiseUtils';// MCP OAuthexport {diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.tsindex 9e176dfcb..11b3fc362 100644--- a/packages/harness/src/core/mcp/auth/index.ts+++ b/packages/harness/src/core/mcp/auth/index.ts@@ -1,5 +1,4 @@export {- DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,buildMcpAuthorizationUrl,completeMcpAuthorization,createMcpOAuthClient,@@ -14,6 +13,7 @@ export type {ResolveMcpAuthResult,} from './mcpDcr';export {+ DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,MCP_OAUTH_CALLBACK_PATH,mcpAuthorizationServerMetadata,mcpAuthorizationServerOrigin,diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/harness/src/core/mcp/auth/mcpDcr.tsindex 6ce31ab05..be2620798 100644--- a/packages/harness/src/core/mcp/auth/mcpDcr.ts+++ b/packages/harness/src/core/mcp/auth/mcpDcr.ts@@ -14,13 +14,15 @@ import type {} from '@modelcontextprotocol/sdk/shared/auth.js';import { randomBytes } from 'node:crypto';import type { IOAuthClientStore, OAuthClientRecord } from '../../auth/IOAuthClientStore';-import type { IOAuthTokenStore, OAuthToken } from '../../auth/IOAuthTokenStore';-import { McpConnectionError } from '../../errors';+import type { IOAuthTokenStore } from '../../auth/IOAuthTokenStore';+import { isOAuthAccessTokenUsable } from '../../auth/oauthToken';+import { McpConnectionError, McpDcrConfigurationError } from '../../errors';import {mcpAuthorizationServerMetadata,mcpAuthorizationServerOrigin,mcpClientInformation,mcpOAuthCallbackUrl,+ oauthTokensToOAuthToken,} from './mcpOAuthHelpers';export interface McpAuthResolvedResult {@@ -45,15 +47,12 @@ export interface CompleteMcpAuthorizationResult {}/**+ * 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`.*/-export const DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS = 3600;--/**- * Prefer `client_secret_post` (confidential). Retry without the field only when the AS rejects- * that metadata (`invalid_client_metadata`); other failures (network, 5xx, etc.) surface as-is.- */async function registerMcpClientWithAuthMethodFallback(params: {authorizationServerUrl: string;metadata: AuthorizationServerMetadata;@@ -125,16 +124,14 @@ export async function createMcpOAuthClient(params: {const { authorizationServerUrl, authorizationServerMetadata: metadata } = await discoverOAuthServerInfo(mcpServerUrl);if (!metadata?.registration_endpoint) {- throw new McpConnectionError(+ throw new McpDcrConfigurationError(`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(+ throw new McpDcrConfigurationError(`Authorization server for MCP server '${mcpServerName}' is missing authorization_endpoint or token_endpoint`,- 400,);}@@ -142,9 +139,8 @@ export async function createMcpOAuthClient(params: {// Missing/omitted advertisement → still try S256 (many servers support it but do not publish).const pkceMethods = metadata.code_challenge_methods_supported;if (pkceMethods && !pkceMethods.includes('S256')) {- throw new McpConnectionError(+ throw new McpDcrConfigurationError(`Authorization server for MCP server '${mcpServerName}' advertises PKCE methods without S256`,- 400,);}@@ -236,22 +232,6 @@ export async function buildMcpAuthorizationUrl(params: {return started.authorizationUrl;}-function isMcpAccessTokenUsable(expiresAtIso: string, nowMs: number): boolean {- const expiresAtMs = Date.parse(expiresAtIso);- return !Number.isNaN(expiresAtMs) && expiresAtMs > nowMs;-}--function oauthTokensToOAuthToken(tokens: OAuthTokens, nowMs: number, 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(),- scope: tokens.scope ?? null,- };-}-export async function resolveMcpAuth(params: {tokenStore: IOAuthTokenStore;mcpServerStore: IOAuthClientStore;@@ -265,7 +245,7 @@ export async function resolveMcpAuth(params: {const nowMs = Date.now();const token = await params.tokenStore.getToken({ id: params.serverId });- if (token && isMcpAccessTokenUsable(token.expiresAt, nowMs)) {+ if (token && isOAuthAccessTokenUsable(token.expiresAt, nowMs)) {return { headers: { Authorization: `Bearer ${token.accessToken}` } };}diff --git a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.tsindex 2e00748a8..267ebfc70 100644--- a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts+++ b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts@@ -5,13 +5,21 @@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';/** Fixed OAuth callback path for every MCP server (matches server mount). */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`.+ */+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).@@ -57,3 +65,18 @@ export function mcpAuthorizationServerMetadata(server: OAuthServerMetadata): Autexport function mcpAuthorizationServerOrigin(server: OAuthServerMetadata): string {return new URL(server.authorizationEndpoint).origin;}++export function oauthTokensToOAuthToken(+ tokens: OAuthTokens,+ nowMs: number,+ 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(),+ scope: tokens.scope ?? null,+ };+}diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.tsindex 281520626..e1b717be9 100644--- a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts+++ b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts@@ -276,7 +276,7 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {clientName: CLIENT_NAME,}),).rejects.toMatchObject({- name: 'McpConnectionError',+ name: 'McpDcrConfigurationError',message: expect.stringContaining('no DCR support'),});});@@ -381,7 +381,7 @@ describe('buildMcpAuthorizationUrl', () => {clientName: CLIENT_NAME,}),).rejects.toMatchObject({- name: 'McpConnectionError',+ name: 'McpDcrConfigurationError',message: expect.stringContaining('without S256'),});});diff --git a/packages/server/src/apis/mcpServers.ts b/packages/server/src/apis/mcpServers.tsindex 1b82f0702..45ecc8bdc 100644--- a/packages/server/src/apis/mcpServers.ts+++ b/packages/server/src/apis/mcpServers.ts@@ -1,13 +1,17 @@import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';import {+ ensureMcpClientRegistered,extractErrorLogFields,+ type IOAuthTokenStore,isAuthRequired,isMcpAuthRequired,McpConnectionError,+ McpDcrConfigurationError,+ type OAuthToken,RemoteMCP,resolveMcpAuth,validateRedirectUris,- type IOAuthTokenStore,+ withTimeout,} from '@truefoundry/utils-core/core';import type { Logger } from 'winston';import type { McpCatalog } from '../catalog/McpCatalog';@@ -22,9 +26,12 @@ import {putMcpServerRoute,} from '../routes/mcpServerRoutes';import type { ConfiguredMcpServer, McpServerManifest } from '../schemas/mcpServer';-import { resolveConfiguredMcpRequestHeaders, toStubAuthStatus } from '../schemas/mcpServer';+import { resolveConfiguredMcpRequestHeaders, resolveMcpAuthStatus } from '../schemas/mcpServer';import { TENANT_ID } from './sessions';+/** Registering a DCR OAuth client hits the MCP server's authorization server, so bound that call. */+export const MCP_DCR_REGISTRATION_TIMEOUT_MS = 10_000;+export interface McpServersRouterDeps {mcpCatalog: McpCatalog;mcpServerStore: IMcpServerStore;@@ -43,22 +50,54 @@ function omitUndefinedEntries(obj: Record<string, unknown>): Record<string, unknreturn out;}-function toConfiguredMcpServer(record: McpServerRecord): ConfiguredMcpServer {+/**+ * `token` is the DCR access token stored for this server (keyed by `record.id`), or undefined for+ * header/no-auth servers and DCR servers that have never authorized. Only DCR reads it.+ */+function toConfiguredMcpServer(+ record: McpServerRecord,+ token: OAuthToken | undefined,+ nowMs: number,+): ConfiguredMcpServer {return {...record.manifest,- auth_status: toStubAuthStatus(record.manifest),+ auth_status: resolveMcpAuthStatus(record.manifest, token, nowMs),};}-/** Admin/settings MCP CRUD (mounted at /api/v1/settings/mcp-servers). */+/** Admin/settings MCP CRUD (mounted at /api/v1/settings/mcp-servers).+ * TODO: Remove the server via txn if DCR fails to register+ */export function createMcpServersRouter(deps: McpServersRouterDeps) {+ const registerDcrClient = async (params: {+ serverId: string;+ mcpServerUrl: string;+ mcpServerName: string;+ }): Promise<void> => {+ await withTimeout(+ ensureMcpClientRegistered({+ mcpServerStore: deps.mcpServerStore,+ serverId: params.serverId,+ mcpServerUrl: params.mcpServerUrl,+ mcpServerName: params.mcpServerName,+ clientName: configuration.OAUTH_CLIENT_NAME,+ }),+ MCP_DCR_REGISTRATION_TIMEOUT_MS,+ `DCR client registration for MCP server "${params.mcpServerName}"`,+ );+ };+const catalogHandler: RouteHandler<typeof getMcpServerCatalogRoute> = c => {return c.json({ data: [...deps.mcpCatalog.list()] }, 200);};const listConfiguredHandler: RouteHandler<typeof listConfiguredMcpServersRoute> = async c => {const records = await deps.mcpServerStore.listServers(TENANT_ID);- return c.json({ data: records.map(toConfiguredMcpServer) }, 200);+ const nowMs = Date.now();+ // Only DCR servers have tokens; batch the lookup.+ const dcrIds = records.filter(record => record.manifest.auth?.type === 'dcr').map(record => record.id);+ const tokens = await deps.tokenStore.getTokens({ ids: dcrIds });+ return c.json({ data: records.map(record => toConfiguredMcpServer(record, tokens.get(record.id), nowMs)) }, 200);};const putHandler: RouteHandler<typeof putMcpServerRoute> = async c => {@@ -68,7 +107,34 @@ export function createMcpServersRouter(deps: McpServersRouterDeps) {name: manifest.name,manifest,});- return c.json({ data: toConfiguredMcpServer(record) }, 200);+ if (record.manifest.auth?.type === 'dcr') {+ try {+ await registerDcrClient({+ serverId: record.id,+ mcpServerUrl: record.manifest.url,+ mcpServerName: record.manifest.name,+ });+ } catch (error) {+ // Permanent config error (server advertises no DCR support): a retry can never succeed, so+ // surface it now as a 400 for immediate feedback instead of a silently-broken server.+ if (error instanceof McpDcrConfigurationError) {+ deps.logger.error(+ `DCR misconfiguration for "${record.manifest.name}"; rejecting upsert`,+ extractErrorLogFields(error),+ );+ return c.json({ error: { message: error.message } }, 400);+ }+ // Transient (network / timeout / flaky authorization server): keep the saved server and let+ // the next authorize retry, rather than failing the upsert on a temporary fault.+ deps.logger.warn(+ `Eager DCR client registration failed for "${record.manifest.name}"; will retry on authorize`,+ extractErrorLogFields(error),+ );+ }+ }+ // A re-upsert preserves `id`, so a DCR server may already carry a token from a prior authorize.+ const token = record.manifest.auth?.type === 'dcr' ? await deps.tokenStore.getToken({ id: record.id }) : undefined;+ return c.json({ data: toConfiguredMcpServer(record, token, Date.now()) }, 200);};const listToolsHandler: RouteHandler<typeof listMcpServerToolsRoute> = async c => {diff --git a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.tsindex 7331a9f79..2deebf4aa 100644--- a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts+++ b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts@@ -3,7 +3,7 @@ import type { Kysely } from 'kysely';import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';import type { Database } from '../types';import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';-import { deleteToken, getToken, saveToken } from './queries/token';+import { deleteToken, getToken, getTokens, saveToken } from './queries/token';export class PostgresOAuthTokenStore implements IOAuthTokenStore {constructor(private readonly db: Kysely<Database>) {}@@ -25,6 +25,11 @@ export class PostgresOAuthTokenStore implements IOAuthTokenStore {return stored === undefined ? undefined : fromStoredOAuthToken(stored);}+ async getTokens(params: { ids: string[] }): Promise<Map<string, OAuthToken>> {+ const stored = await getTokens(this.db, params);+ return new Map([...stored].map(([id, token]) => [id, fromStoredOAuthToken(token)]));+ }+deleteToken(params: { id: string }): Promise<void> {return deleteToken(this.db, params);}diff --git a/packages/server/src/db/postgres/token-store/queries/token.ts b/packages/server/src/db/postgres/token-store/queries/token.tsindex 0a6c2877b..43187ddfc 100644--- a/packages/server/src/db/postgres/token-store/queries/token.ts+++ b/packages/server/src/db/postgres/token-store/queries/token.ts@@ -30,6 +30,19 @@ export async function getToken(db: Kysely<Database>, params: { id: string }): Prreturn row === undefined ? undefined : row.token;}+export async function getTokens(db: Kysely<Database>, params: { ids: string[] }): Promise<Map<string, OAuthToken>> {+ if (params.ids.length === 0) {+ return new Map();+ }+ const rows = await db+ .selectFrom('oauth_token')+ .select(['oauth_server_id', 'token'])+ .where('oauth_server_id', 'in', params.ids)+ .execute();++ return new Map(rows.map(row => [row.oauth_server_id, row.token]));+}+export async function deleteToken(db: Kysely<Database>, params: { id: string }): Promise<void> {await db.deleteFrom('oauth_token').where('oauth_server_id', '=', params.id).execute();}diff --git a/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.tsindex 39d02b678..e4090a452 100644--- a/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts+++ b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts@@ -3,7 +3,7 @@ import type { Kysely } from 'kysely';import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';import type { Database } from '../types';import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';-import { deleteToken, getToken, saveToken } from './queries/token';+import { deleteToken, getToken, getTokens, saveToken } from './queries/token';export class SqliteOAuthTokenStore implements IOAuthTokenStore {constructor(private readonly db: Kysely<Database>) {}@@ -25,6 +25,11 @@ export class SqliteOAuthTokenStore implements IOAuthTokenStore {return stored === undefined ? undefined : fromStoredOAuthToken(stored);}+ async getTokens(params: { ids: string[] }): Promise<Map<string, OAuthToken>> {+ const stored = await getTokens(this.db, params);+ return new Map([...stored].map(([id, token]) => [id, fromStoredOAuthToken(token)]));+ }+deleteToken(params: { id: string }): Promise<void> {return deleteToken(this.db, params);}diff --git a/packages/server/src/db/sqlite/token-store/queries/token.ts b/packages/server/src/db/sqlite/token-store/queries/token.tsindex 7c5fcd96f..8084d932d 100644--- a/packages/server/src/db/sqlite/token-store/queries/token.ts+++ b/packages/server/src/db/sqlite/token-store/queries/token.ts@@ -30,6 +30,19 @@ export async function getToken(db: Kysely<Database>, params: { id: string }): Prreturn row === undefined ? undefined : row.token;}+export async function getTokens(db: Kysely<Database>, params: { ids: string[] }): Promise<Map<string, OAuthToken>> {+ if (params.ids.length === 0) {+ return new Map();+ }+ const rows = await db+ .selectFrom('oauth_token')+ .select(['oauth_server_id', jsonText<OAuthToken>(sql.ref('token')).as('token')])+ .where('oauth_server_id', 'in', params.ids)+ .execute();++ return new Map(rows.map(row => [row.oauth_server_id, row.token]));+}+export async function deleteToken(db: Kysely<Database>, params: { id: string }): Promise<void> {await db.deleteFrom('oauth_token').where('oauth_server_id', '=', params.id).execute();}diff --git a/packages/server/src/schemas/mcpServer.ts b/packages/server/src/schemas/mcpServer.tsindex fd3f24773..2ebe20ae9 100644--- a/packages/server/src/schemas/mcpServer.ts+++ b/packages/server/src/schemas/mcpServer.ts@@ -8,6 +8,7 @@* token exchange lands.*/import { z } from '@hono/zod-openapi';+import { isOAuthAccessTokenUsable, type OAuthToken } from '@truefoundry/utils-core/core';import { NameSchema } from './common';/** Transport/kind of MCP server. Extend when non-remote kinds ship. */@@ -104,14 +105,14 @@ export function resolveConfiguredMcpRequestHeaders(manifest: McpServerManifest):return {};}-/**- * Stub auth_status until OAuth/token store backs a real check.- * Header credentials are already on the row → authenticated.- * DCR still needs a user authorize flow → auth_required.- */-export function toStubAuthStatus(manifest: McpServerManifest): McpAuthStatus {+export function resolveMcpAuthStatus(+ manifest: McpServerManifest,+ token: OAuthToken | undefined,+ nowMs: number,+): McpAuthStatus {if (manifest.auth?.type === 'dcr') {- return { status: 'auth_required' };+ const authenticated = token && isOAuthAccessTokenUsable(token.expiresAt, nowMs);+ return authenticated ? { status: 'authenticated' } : { status: 'auth_required' };}return { status: 'authenticated' };}diff --git a/packages/server/tests/db/oauthTokenStoreContractSuite.ts b/packages/server/tests/db/oauthTokenStoreContractSuite.tsindex 9beeb3196..890632dbf 100644--- a/packages/server/tests/db/oauthTokenStoreContractSuite.ts+++ b/packages/server/tests/db/oauthTokenStoreContractSuite.ts@@ -70,6 +70,23 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStorexpect(await h.store.getToken({ id: RESOURCE_ID })).toBeUndefined();});+ it('getTokens batches only the ids that have a stored token', async () => {+ const h = getHarness();+ await h.seedResource(RESOURCE_ID);+ await h.seedResource(OTHER_RESOURCE_ID);+ const first = token();+ await h.store.saveToken({ id: RESOURCE_ID, token: first });++ const found = await h.store.getTokens({ ids: [RESOURCE_ID, OTHER_RESOURCE_ID, 'mcp-server-absent'] });++ expect(found).toEqual(new Map([[RESOURCE_ID, first]]));+ });++ it('getTokens returns an empty map for no ids', async () => {+ const h = getHarness();+ expect(await h.store.getTokens({ ids: [] })).toEqual(new Map());+ });+it('tokens are scoped per resource', async () => {const h = getHarness();await h.seedResource(RESOURCE_ID);diff --git a/packages/server/tests/unit/apis/mcpServers.test.ts b/packages/server/tests/unit/apis/mcpServers.test.tsindex 69f4befb4..9e947095e 100644--- a/packages/server/tests/unit/apis/mcpServers.test.ts+++ b/packages/server/tests/unit/apis/mcpServers.test.ts@@ -1,5 +1,6 @@import winston from 'winston';import { createAvailableMcpServersRouter, createMcpServersRouter } from '../../../src/apis/mcpServers';+import { TENANT_ID } from '../../../src/apis/sessions';import { McpCatalog } from '../../../src/catalog/McpCatalog';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';import { createSqliteDb } from '../../../src/db/sqlite/client';@@ -40,12 +41,20 @@ function putInit(body: unknown): RequestInit {describe('mcp-servers routers', () => {let settingsRouter: ReturnType<typeof createMcpServersRouter>;let availableRouter: ReturnType<typeof createAvailableMcpServersRouter>;+ let mcpServerStore: SqliteMcpServerStore;+ let tokenStore: SqliteOAuthTokenStore;+ const originalFetch = globalThis.fetch;beforeAll(async () => {+ // Eager DCR registration dials the MCP server's authorization server. Fail that outbound call+ // fast so DCR upserts stay hermetic; the handler treats it as transient and still returns 200.+ globalThis.fetch = (async () => {+ throw new Error('network disabled in tests');+ }) as typeof fetch;const db = createSqliteDb(':memory:');await migrateSqliteToLatest(db);- const mcpServerStore = new SqliteMcpServerStore(db);- const tokenStore = new SqliteOAuthTokenStore(db);+ mcpServerStore = new SqliteMcpServerStore(db);+ tokenStore = new SqliteOAuthTokenStore(db);settingsRouter = createMcpServersRouter({mcpCatalog: McpCatalog.load(),mcpServerStore,@@ -55,6 +64,10 @@ describe('mcp-servers routers', () => {availableRouter = createAvailableMcpServersRouter(mcpServerStore);});+ afterAll(() => {+ globalThis.fetch = originalFetch;+ });+it('GET /catalog returns the shipped catalog verbatim', async () => {const response = await settingsRouter.request('/catalog');expect(response.status).toBe(200);@@ -66,7 +79,7 @@ describe('mcp-servers routers', () => {);});- it('PUT upserts a server and returns stub auth_status', async () => {+ it('PUT upserts a server and returns authenticated auth_status for no-auth servers', async () => {const response = await settingsRouter.request('/', putInit(putBody));expect(response.status).toBe(200);expect(await response.json()).toEqual({@@ -80,7 +93,7 @@ describe('mcp-servers routers', () => {});});- it('PUT with DCR auth stubs auth_required without authorization_url', async () => {+ it('PUT with DCR auth reports auth_required while no token is stored', async () => {const response = await settingsRouter.request('/', putInit(putBodyWithDcr));expect(response.status).toBe(200);expect(await response.json()).toEqual({@@ -88,6 +101,46 @@ describe('mcp-servers routers', () => {});});+ it('DCR server reads authenticated once an unexpired token is stored, auth_required once expired', async () => {+ await settingsRouter.request('/', putInit(putBodyWithDcr));+ const record = await mcpServerStore.getServer({ tenant_id: TENANT_ID, name: putBodyWithDcr.name });+ if (record === undefined) throw new Error('expected DCR server to exist');++ await tokenStore.saveToken({+ id: record.id,+ token: {+ accessToken: 'access-1',+ refreshToken: 'refresh-1',+ expiresAt: '2099-01-01T00:00:00.000Z',+ scope: null,+ },+ });++ const authed = await settingsRouter.request('/');+ const authedBody = (await authed.json()) as { data: { name: string; auth_status: { status: string } }[] };+ expect(authedBody.data.find(server => server.name === putBodyWithDcr.name)?.auth_status).toEqual({+ status: 'authenticated',+ });++ await tokenStore.saveToken({+ id: record.id,+ token: {+ accessToken: 'access-1',+ refreshToken: 'refresh-1',+ expiresAt: '2000-01-01T00:00:00.000Z',+ scope: null,+ },+ });++ const expired = await settingsRouter.request('/');+ const expiredBody = (await expired.json()) as { data: { name: string; auth_status: { status: string } }[] };+ expect(expiredBody.data.find(server => server.name === putBodyWithDcr.name)?.auth_status).toEqual({+ status: 'auth_required',+ });++ await tokenStore.deleteToken({ id: record.id });+ });+it('PUT with header auth stores headers and reports authenticated', async () => {const response = await settingsRouter.request('/', putInit(putBodyWithHeaderAuth));expect(response.status).toBe(200);