The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: implement completeMcpAuthorization method and enhance MCP OAuthflow (#32)
Sujai Kumar Gupta0debd643a502
diff --git a/packages/harness/src/core/auth/IOAuthClientStore.ts b/packages/harness/src/core/auth/IOAuthClientStore.tsindex d4ec91e77..46cbfb6cc 100644--- a/packages/harness/src/core/auth/IOAuthClientStore.ts+++ b/packages/harness/src/core/auth/IOAuthClientStore.ts@@ -21,8 +21,15 @@ export interface OAuthClientRecord {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.tsindex 1736c49b3..57cd96481 100644--- a/packages/harness/src/core/auth/IOAuthTokenStore.ts+++ b/packages/harness/src/core/auth/IOAuthTokenStore.ts@@ -4,6 +4,11 @@ export interface OAuthPendingAuthorization {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. */@@ -23,13 +28,11 @@ export interface IOAuthTokenStore {savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void>;/**- * Expires on read: a pending authorization past its age limit is never returned, so nothing- * has to sweep the store. The limit itself is the implementation's to choose.+ * 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.*/- getPendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined>;-- /** Makes `state` single-use — call once the callback has been redeemed or abandoned. */- deletePendingAuthorization(params: { state: string }): Promise<void>;+ consumePendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined>;saveToken(params: { id: string; token: OAuthToken }): Promise<void>;diff --git a/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts b/packages/harness/src/core/auth/InMemoryOAuthClientStore.tsindex 32909f4eb..a0a1825ee 100644--- a/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts+++ b/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts@@ -1,8 +1,8 @@import type { IOAuthClientStore, OAuthClientRecord } from './IOAuthClientStore';/**- * In-memory `IOAuthClientStore` — for tests and any dev/no-DB usage. Not for production use (no- * persistence across process restarts, no multi-replica sharing).+ * 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 {@@ -15,5 +15,9 @@ export class InMemoryOAuthClientStore implements IOAuthClientStore {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/InMemoryOAuthTokenStore.ts b/packages/harness/src/core/auth/InMemoryOAuthTokenStore.tsindex e7701e5fa..ccbb1d5cb 100644--- a/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts+++ b/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts@@ -16,16 +16,13 @@ export class InMemoryOAuthTokenStore implements IOAuthTokenStore {this.pending.set(pending.state, { row: pending, createdAtMs: Date.now() });}- async getPendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined> {+ async consumePendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined> {const entry = this.pending.get(params.state);if (entry === undefined || entry.createdAtMs <= Date.now() - PENDING_AUTHORIZATION_TTL_MS) {return undefined;}- return entry.row;- }-- async deletePendingAuthorization(params: { state: string }): Promise<void> {this.pending.delete(params.state);+ return entry.row;}async saveToken(params: { id: string; token: OAuthToken }): Promise<void> {diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.tsindex 676ae22fa..6455664dc 100644--- a/packages/harness/src/core/index.ts+++ b/packages/harness/src/core/index.ts@@ -151,6 +151,7 @@ export {DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,MCP_OAUTH_CALLBACK_PATH,buildMcpAuthorizationUrl,+ completeMcpAuthorization,createMcpOAuthClient,ensureMcpClientRegistered,isMcpAuthRequired,@@ -160,7 +161,12 @@ export {mcpOAuthCallbackUrl,resolveMcpAuth,} from './mcp/auth';-export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcp/auth';+export type {+ CompleteMcpAuthorizationResult,+ McpAuthRequiredResult,+ McpAuthResolvedResult,+ ResolveMcpAuthResult,+} from './mcp/auth';// Sandbox (concrete implementation; provider details exported for composition)export {diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.tsindex 2cdaa04af..44e93e908 100644--- a/packages/harness/src/core/mcp/auth/index.ts+++ b/packages/harness/src/core/mcp/auth/index.ts@@ -1,12 +1,18 @@export {DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,buildMcpAuthorizationUrl,+ completeMcpAuthorization,createMcpOAuthClient,ensureMcpClientRegistered,isMcpAuthRequired,resolveMcpAuth,} from './mcpDcr';-export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcpDcr';+export type {+ CompleteMcpAuthorizationResult,+ McpAuthRequiredResult,+ McpAuthResolvedResult,+ ResolveMcpAuthResult,+} from './mcpDcr';export {MCP_OAUTH_CALLBACK_PATH,mcpAuthorizationServerMetadata,diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/harness/src/core/mcp/auth/mcpDcr.tsindex 514f57212..94c345c5d 100644--- a/packages/harness/src/core/mcp/auth/mcpDcr.ts+++ b/packages/harness/src/core/mcp/auth/mcpDcr.ts@@ -1,9 +1,11 @@import {discoverOAuthServerInfo,+ exchangeAuthorization,refreshAuthorization,registerClient,startAuthorization,} from '@modelcontextprotocol/sdk/client/auth.js';+import { InvalidClientError } from '@modelcontextprotocol/sdk/server/auth/errors.js';import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';import type {AuthorizationServerMetadata,@@ -35,6 +37,13 @@ export function isMcpAuthRequired(result: ResolveMcpAuthResult): result is McpAureturn 'authUrl' in result;}+/** Result of a successful `completeMcpAuthorization` (token saved, pending cleared). */+export interface CompleteMcpAuthorizationResult {+ serverId: string;+ /** FE post-OAuth landing URL from the original authorize call. */+ redirectUrl: string | null;+}+/*** 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`.@@ -139,14 +148,13 @@ export async function createMcpOAuthClient(params: {}export async function ensureMcpClientRegistered(params: {- clientStore: IOAuthClientStore;+ mcpServerStore: IOAuthClientStore;serverId: string;mcpServerUrl: string;mcpServerName: string;- publicBaseUrl: string;clientName: string;}): Promise<OAuthClientRecord> {- const existing = await params.clientStore.getClient({ id: params.serverId });+ const existing = await params.mcpServerStore.getClient({ id: params.serverId });if (existing) {return existing;}@@ -154,51 +162,60 @@ export async function ensureMcpClientRegistered(params: {const client = await createMcpOAuthClient({mcpServerUrl: params.mcpServerUrl,mcpServerName: params.mcpServerName,- redirectUri: mcpOAuthCallbackUrl(params.publicBaseUrl),+ redirectUri: mcpOAuthCallbackUrl(),clientName: params.clientName,});- await params.clientStore.saveClient({ id: params.serverId, record: client });+ await params.mcpServerStore.saveClient({ id: params.serverId, record: client });return client;}export async function buildMcpAuthorizationUrl(params: {tokenStore: IOAuthTokenStore;- clientStore: IOAuthClientStore;+ mcpServerStore: IOAuthClientStore;serverId: string;mcpServerUrl: string;mcpServerName: string;- publicBaseUrl: string;clientName: string;/** FE post-OAuth landing URL (not the OAuth redirect_uri). */redirectUrl?: string;}): Promise<URL> {const client = await ensureMcpClientRegistered({- clientStore: params.clientStore,+ mcpServerStore: params.mcpServerStore,serverId: params.serverId,mcpServerUrl: params.mcpServerUrl,mcpServerName: params.mcpServerName,- publicBaseUrl: params.publicBaseUrl,clientName: params.clientName,});+ if (client.server.codeChallengeMethodsSupported?.includes('S256') !== true) {+ throw new McpConnectionError(+ `Authorization server for MCP server '${params.mcpServerName}' does not advertise PKCE S256; S256 is required`,+ 400,+ );+ }+const state = randomBytes(32).toString('base64url');- const { authorizationUrl, codeVerifier } = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {+ const redirectUri = mcpOAuthCallbackUrl();+ const resource = resourceUrlFromServerUrl(params.mcpServerUrl);++ const started = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {metadata: mcpAuthorizationServerMetadata(client.server),clientInformation: mcpClientInformation(client.client),- redirectUrl: mcpOAuthCallbackUrl(params.publicBaseUrl),- resource: resourceUrlFromServerUrl(params.mcpServerUrl),+ redirectUrl: redirectUri,+ resource,state,});await params.tokenStore.savePendingAuthorization({state,id: params.serverId,- codeVerifier,+ mcpServerUrl: params.mcpServerUrl,+ codeVerifier: started.codeVerifier,redirectUrl: params.redirectUrl ?? null,});- return authorizationUrl;+ return started.authorizationUrl;}function isMcpAccessTokenUsable(expiresAtIso: string, nowMs: number): boolean {@@ -219,17 +236,15 @@ function oauthTokensToOAuthToken(tokens: OAuthTokens, nowMs: number, fallbackRefexport async function resolveMcpAuth(params: {tokenStore: IOAuthTokenStore;- clientStore: IOAuthClientStore;+ mcpServerStore: IOAuthClientStore;serverId: string;mcpServerUrl: string;mcpServerName: string;- publicBaseUrl: string;clientName: string;/** FE post-OAuth landing URL (not the OAuth redirect_uri). */redirectUrl?: string;- nowMs?: number;}): Promise<ResolveMcpAuthResult> {- const nowMs = params.nowMs ?? Date.now();+ const nowMs = Date.now();const token = await params.tokenStore.getToken({ id: params.serverId });if (token && isMcpAccessTokenUsable(token.expiresAt, nowMs)) {@@ -237,7 +252,7 @@ export async function resolveMcpAuth(params: {}if (token?.refreshToken) {- const client = await params.clientStore.getClient({ id: params.serverId });+ const client = await params.mcpServerStore.getClient({ id: params.serverId });if (client) {try {const refreshed = await refreshAuthorization(mcpAuthorizationServerOrigin(client.server), {@@ -261,13 +276,76 @@ export async function resolveMcpAuth(params: {const authUrl = await buildMcpAuthorizationUrl({tokenStore: params.tokenStore,- clientStore: params.clientStore,+ mcpServerStore: params.mcpServerStore,serverId: params.serverId,mcpServerUrl: params.mcpServerUrl,mcpServerName: params.mcpServerName,- publicBaseUrl: params.publicBaseUrl,clientName: params.clientName,...(params.redirectUrl !== undefined ? { redirectUrl: params.redirectUrl } : {}),});return { authUrl };}++/**+ * OAuth callback: exchange `code` for tokens. Route must already reject IdP `error` params.+ * Claims pending state atomically (`consumePendingAuthorization`) so duplicate callbacks lose+ * the race; `mcpServerUrl` for the RFC 8707 `resource` comes from that pending row.+ * On `invalid_client`, clears stored client + token so the next authorize re-registers.+ */+export async function completeMcpAuthorization(params: {+ tokenStore: IOAuthTokenStore;+ mcpServerStore: IOAuthClientStore;+ state: string;+ code: string;+}): Promise<CompleteMcpAuthorizationResult> {+ const nowMs = Date.now();++ // Consume first so a concurrent/duplicate callback cannot redeem the same state.+ const pending = await params.tokenStore.consumePendingAuthorization({ state: params.state });+ if (!pending) {+ throw new McpConnectionError('Unknown or expired OAuth state', 400);+ }++ const client = await params.mcpServerStore.getClient({ id: pending.id });+ if (!client) {+ throw new McpConnectionError(+ `No OAuth client registered for MCP server id '${pending.id}'; re-run authorize first`,+ 400,+ );+ }++ const { codeVerifier } = pending;+ if (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,+ redirectUri: mcpOAuthCallbackUrl(),+ resource: resourceUrlFromServerUrl(pending.mcpServerUrl),+ });+ } catch (error: unknown) {+ if (error instanceof InvalidClientError) {+ await params.tokenStore.deleteToken({ id: pending.id });+ await params.mcpServerStore.deleteClient({ id: pending.id });+ throw new McpConnectionError('OAuth client registration is invalid; please retry connecting', 400, {+ cause: error,+ });+ }+ throw new McpConnectionError('OAuth token exchange failed', 400, {+ cause: error instanceof Error ? error : undefined,+ });+ }++ await params.tokenStore.saveToken({+ id: pending.id,+ token: oauthTokensToOAuthToken(tokens, nowMs, null),+ });++ return { serverId: pending.id, redirectUrl: pending.redirectUrl };+}diff --git a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.tsindex a373af7f3..2e00748a8 100644--- a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts+++ b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts@@ -12,8 +12,12 @@ 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';-/** OAuth callback redirect_uri = publicBaseUrl + fixed path. No trimming of the base. */-export function mcpOAuthCallbackUrl(publicBaseUrl: string): string {+/**+ * OAuth callback redirect_uri = `PUBLIC_BASE_URL` + fixed path. No trimming of the base.+ * Reads from process env (same source as server config).+ */+export function mcpOAuthCallbackUrl(): string {+ const publicBaseUrl = process.env['PUBLIC_BASE_URL'] ?? '';if (publicBaseUrl === '') {throw new McpConnectionError('PUBLIC_BASE_URL is required for MCP OAuth registration but was empty', 500);}diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.tsindex fab0e1608..84bd7df5f 100644--- a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts+++ b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts@@ -9,6 +9,7 @@ import {InMemoryOAuthTokenStore,McpConnectionError,buildMcpAuthorizationUrl,+ completeMcpAuthorization,createMcpOAuthClient,ensureMcpClientRegistered,isMcpAuthRequired,@@ -19,12 +20,12 @@ import {interface Stores {tokenStore: InMemoryOAuthTokenStore;- clientStore: InMemoryOAuthClientStore;+ mcpServerStore: InMemoryOAuthClientStore;}-/** The two generic stores the helpers consume, freshly backed in memory per test. */+/** Token store + MCP-server OAuth-client facet, freshly backed in memory per test. */function newStores(): Stores {- return { tokenStore: new InMemoryOAuthTokenStore(), clientStore: new InMemoryOAuthClientStore() };+ return { tokenStore: new InMemoryOAuthTokenStore(), mcpServerStore: new InMemoryOAuthClientStore() };}const PUBLIC_BASE_URL = 'https://harness.example.com';@@ -35,9 +36,23 @@ const SERVER_ID = 'mcp-server-id-1';const SERVER_NAME = 'svc';const realFetch = globalThis.fetch;+const previousPublicBaseUrl = process.env['PUBLIC_BASE_URL'];++beforeAll(() => {+ process.env['PUBLIC_BASE_URL'] = PUBLIC_BASE_URL;+});++afterAll(() => {+ if (previousPublicBaseUrl === undefined) {+ delete process.env['PUBLIC_BASE_URL'];+ } else {+ process.env['PUBLIC_BASE_URL'] = previousPublicBaseUrl;+ }+});afterEach(() => {globalThis.fetch = realFetch;+ process.env['PUBLIC_BASE_URL'] = PUBLIC_BASE_URL;});function json(body: unknown, status = 200): Response {@@ -103,7 +118,7 @@ function stubOauthFetch(options: {}return json({...registered,- redirect_uris: [mcpOAuthCallbackUrl(PUBLIC_BASE_URL)],+ redirect_uris: [mcpOAuthCallbackUrl()],grant_types: ['authorization_code', 'refresh_token'],response_types: ['code'],});@@ -153,16 +168,15 @@ describe('resourceUrlFromServerUrl (SDK)', () => {describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {it('returns the cached client without discovery or registration', async () => {- const { clientStore } = newStores();- await clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ const { mcpServerStore } = newStores();+ await mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });const { registerCallCount } = stubOauthFetch({});const result = await ensureMcpClientRegistered({- clientStore,+ mcpServerStore,serverId: SERVER_ID,mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- publicBaseUrl: PUBLIC_BASE_URL,clientName: CLIENT_NAME,});@@ -171,15 +185,14 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {});it('discovers, registers confidential client, and saves the record', async () => {- const { clientStore } = newStores();+ const { mcpServerStore } = newStores();const { registerBodies } = stubOauthFetch({});const result = await ensureMcpClientRegistered({- clientStore,+ mcpServerStore,serverId: SERVER_ID,mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- publicBaseUrl: PUBLIC_BASE_URL,clientName: CLIENT_NAME,});@@ -193,22 +206,21 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {expect(body['token_endpoint_auth_method']).toBe('client_secret_post');expect(body['grant_types']).toEqual(['authorization_code', 'refresh_token']);expect(body['client_name']).toBe(CLIENT_NAME);- expect(body['redirect_uris']).toEqual([mcpOAuthCallbackUrl(PUBLIC_BASE_URL)]);+ expect(body['redirect_uris']).toEqual([mcpOAuthCallbackUrl()]);});it('retries registration without token_endpoint_auth_method when the first attempt fails', async () => {- const { clientStore } = newStores();+ const { mcpServerStore } = newStores();const { registerBodies, registerCallCount } = stubOauthFetch({registrationFailFirst: true,registeredClient: { client_id: 'public-client' },});const result = await ensureMcpClientRegistered({- clientStore,+ mcpServerStore,serverId: SERVER_ID,mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- publicBaseUrl: PUBLIC_BASE_URL,clientName: CLIENT_NAME,});@@ -220,16 +232,15 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {});it('throws when the AS has no registration_endpoint', async () => {- const { clientStore } = newStores();+ const { mcpServerStore } = newStores();stubOauthFetch({ skipRegistrationEndpoint: true });await expect(ensureMcpClientRegistered({- clientStore,+ mcpServerStore,serverId: SERVER_ID,mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- publicBaseUrl: PUBLIC_BASE_URL,clientName: CLIENT_NAME,}),).rejects.toMatchObject({@@ -239,29 +250,29 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {});it('does not save a client when both registration attempts fail', async () => {- const { clientStore } = newStores();+ const { mcpServerStore } = newStores();const { registerCallCount } = stubOauthFetch({ registrationFailAlways: true });await expect(createMcpOAuthClient({mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- redirectUri: mcpOAuthCallbackUrl(PUBLIC_BASE_URL),+ redirectUri: mcpOAuthCallbackUrl(),clientName: CLIENT_NAME,}),).rejects.toBeInstanceOf(McpConnectionError);expect(registerCallCount()).toBe(2);- expect(await clientStore.getClient({ id: SERVER_ID })).toBeUndefined();+ expect(await mcpServerStore.getClient({ id: SERVER_ID })).toBeUndefined();});- it('throws when publicBaseUrl is empty (no trimming)', async () => {+ it('throws when PUBLIC_BASE_URL is empty (no trimming)', async () => {+ process.env['PUBLIC_BASE_URL'] = '';await expect(ensureMcpClientRegistered({- clientStore: new InMemoryOAuthClientStore(),+ mcpServerStore: new InMemoryOAuthClientStore(),serverId: SERVER_ID,mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- publicBaseUrl: '',clientName: CLIENT_NAME,}),).rejects.toMatchObject({ message: expect.stringContaining('PUBLIC_BASE_URL') });@@ -269,18 +280,17 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {});describe('buildMcpAuthorizationUrl', () => {- it('saves pending authorization with state and returns a URL object', async () => {- const { tokenStore, clientStore } = newStores();- await clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ it('saves pending authorization with PKCE when the AS advertises S256', async () => {+ const { tokenStore, mcpServerStore } = newStores();+ await mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });stubOauthFetch({});const authUrl = await buildMcpAuthorizationUrl({tokenStore,- clientStore,+ mcpServerStore,serverId: SERVER_ID,mcpServerUrl: SERVER_URL,mcpServerName: SERVER_NAME,- publicBaseUrl: PUBLIC_BASE_URL,clientName: CLIENT_NAME,redirectUrl: 'https://app.example.com/after',});@@ -288,30 +298,80 @@ describe('buildMcpAuthorizationUrl', () => {expect(authUrl).toBeInstanceOf(URL);expect(authUrl.origin + authUrl.pathname).toBe(`${AS_ORIGIN}/authorize`);expect(authUrl.searchParams.get('client_id')).toBe(sampleClient.client.clientId);- expect(authUrl.searchParams.get('redirect_uri')).toBe(mcpOAuthCallbackUrl(PUBLIC_BASE_URL));+ expect(authUrl.searchParams.get('redirect_uri')).toBe(mcpOAuthCallbackUrl());expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');expect(authUrl.searchParams.get('code_challenge')).toBeTruthy();expect(authUrl.searchParams.get('resource')).toBe(resourceUrlFromServerUrl(SERVER_URL).href);const state = authUrl.searchParams.get('state');expect(state).toBeTruthy();- const pending = await tokenStore.getPendingAuthorization({ state: state! });+ const pending = await tokenStore.consumePendingAuthorization({ state: state! });expect(pending).toMatchObject({state,id: SERVER_ID,+ mcpServerUrl: SERVER_URL,redirectUrl: 'https://app.example.com/after',});expect(pending?.codeVerifier).toBeTruthy();});++ it('throws when the AS does not advertise S256', async () => {+ const { tokenStore, mcpServerStore } = newStores();+ await mcpServerStore.saveClient({+ id: SERVER_ID,+ record: {+ ...sampleClient,+ server: { ...sampleClient.server, codeChallengeMethodsSupported: null },+ },+ });++ await expect(+ buildMcpAuthorizationUrl({+ tokenStore,+ mcpServerStore,+ serverId: SERVER_ID,+ mcpServerUrl: SERVER_URL,+ mcpServerName: SERVER_NAME,+ clientName: CLIENT_NAME,+ }),+ ).rejects.toMatchObject({+ name: 'McpConnectionError',+ message: expect.stringContaining('PKCE S256'),+ });+ });++ it('throws when only non-S256 methods are advertised', async () => {+ const { tokenStore, mcpServerStore } = newStores();+ await mcpServerStore.saveClient({+ id: SERVER_ID,+ record: {+ ...sampleClient,+ server: { ...sampleClient.server, codeChallengeMethodsSupported: ['plain'] },+ },+ });++ await expect(+ buildMcpAuthorizationUrl({+ tokenStore,+ mcpServerStore,+ serverId: SERVER_ID,+ mcpServerUrl: SERVER_URL,+ mcpServerName: SERVER_NAME,+ clientName: CLIENT_NAME,+ }),+ ).rejects.toMatchObject({+ name: 'McpConnectionError',+ message: expect.stringContaining('PKCE S256'),+ });+ });});const resolveParams = (stores: Stores, mcpServerUrl = SERVER_URL) => ({tokenStore: stores.tokenStore,- clientStore: stores.clientStore,+ mcpServerStore: stores.mcpServerStore,serverId: SERVER_ID,mcpServerUrl,mcpServerName: SERVER_NAME,- publicBaseUrl: PUBLIC_BASE_URL,clientName: CLIENT_NAME,});@@ -335,7 +395,7 @@ describe('resolveMcpAuth', () => {it('refreshes an expired token when a refresh_token is stored', async () => {const stores = newStores();- await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });await stores.tokenStore.saveToken({id: SERVER_ID,token: {@@ -369,7 +429,7 @@ describe('resolveMcpAuth', () => {it('uses a default TTL when the token response omits expires_in', async () => {const stores = newStores();- await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });await stores.tokenStore.saveToken({id: SERVER_ID,token: {@@ -379,7 +439,6 @@ describe('resolveMcpAuth', () => {scope: null,},});- const nowMs = Date.now();stubOauthFetch({tokenResponse: {access_token: 'new-access',@@ -388,19 +447,23 @@ describe('resolveMcpAuth', () => {},});- const result = await resolveMcpAuth({ ...resolveParams(stores), nowMs });+ const beforeMs = Date.now();+ const result = await resolveMcpAuth(resolveParams(stores));+ const afterMs = Date.now();expect(result).toEqual({ headers: { Authorization: 'Bearer new-access' } });const saved = await stores.tokenStore.getToken({ id: SERVER_ID });- expect(saved?.expiresAt).toBe(new Date(nowMs + DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS * 1000).toISOString());- // Still usable on the next resolve with a slightly later clock.- const again = await resolveMcpAuth({ ...resolveParams(stores), nowMs: nowMs + 1_000 });+ const expiresAtMs = Date.parse(saved!.expiresAt);+ expect(expiresAtMs).toBeGreaterThanOrEqual(beforeMs + DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS * 1000);+ expect(expiresAtMs).toBeLessThanOrEqual(afterMs + DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS * 1000);+ // Still usable on the next resolve.+ const again = await resolveMcpAuth(resolveParams(stores));expect(again).toEqual({ headers: { Authorization: 'Bearer new-access' } });});it('returns authentication_required and clears token when refresh fails', async () => {const stores = newStores();- await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });await stores.tokenStore.saveToken({id: SERVER_ID,token: {@@ -418,12 +481,12 @@ describe('resolveMcpAuth', () => {if (!isMcpAuthRequired(result)) throw new Error('unreachable');expect(result.authUrl).toBeInstanceOf(URL);expect(await stores.tokenStore.getToken({ id: SERVER_ID })).toBeUndefined();- expect(await stores.clientStore.getClient({ id: SERVER_ID })).toEqual(sampleClient);+ expect(await stores.mcpServerStore.getClient({ id: SERVER_ID })).toEqual(sampleClient);});it('returns authentication_required and clears expired token without refresh_token', async () => {const stores = newStores();- await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });await stores.tokenStore.saveToken({id: SERVER_ID,token: {@@ -442,12 +505,12 @@ describe('resolveMcpAuth', () => {expect(result.authUrl).toBeInstanceOf(URL);expect(result.authUrl.href).toContain('/authorize');expect(await stores.tokenStore.getToken({ id: SERVER_ID })).toBeUndefined();- expect(await stores.clientStore.getClient({ id: SERVER_ID })).toEqual(sampleClient);+ expect(await stores.mcpServerStore.getClient({ id: SERVER_ID })).toEqual(sampleClient);});it('returns authentication_required when no token exists', async () => {const stores = newStores();- await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });stubOauthFetch({});const result = await resolveMcpAuth(resolveParams(stores));@@ -471,7 +534,7 @@ describe('end-to-end DCR + authorize with normalised MCP URL', () => {if (!isMcpAuthRequired(result)) throw new Error('unreachable');expect(registerBodies).toHaveLength(1);- const client = await stores.clientStore.getClient({ id: SERVER_ID });+ const client = await stores.mcpServerStore.getClient({ id: SERVER_ID });expect(client?.client.clientId).toBe('dyn-client-1');const url = result.authUrl;@@ -482,3 +545,100 @@ describe('end-to-end DCR + authorize with normalised MCP URL', () => {expect(url.searchParams.get('resource')).not.toContain('#');});});++describe('completeMcpAuthorization', () => {+ it('exchanges the code, saves the token, clears pending, and returns redirectUrl', async () => {+ const stores = newStores();+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });++ const authUrl = await buildMcpAuthorizationUrl({+ ...resolveParams(stores),+ redirectUrl: 'https://app.example.com/connected',+ });+ const state = authUrl.searchParams.get('state')!;++ const { tokenBodies } = stubOauthFetch({+ tokenResponse: {+ access_token: 'exchanged-access',+ refresh_token: 'exchanged-refresh',+ expires_in: 1800,+ token_type: 'Bearer',+ },+ });++ const beforeMs = Date.now();+ const result = await completeMcpAuthorization({+ tokenStore: stores.tokenStore,+ mcpServerStore: stores.mcpServerStore,+ state,+ code: 'auth-code-1',+ });+ const afterMs = Date.now();++ expect(result).toEqual({+ serverId: SERVER_ID,+ redirectUrl: 'https://app.example.com/connected',+ });+ // Complete claimed the pending row; a second callback would fail.+ expect(await stores.tokenStore.consumePendingAuthorization({ state })).toBeUndefined();+ const saved = await stores.tokenStore.getToken({ id: SERVER_ID });+ expect(saved?.accessToken).toBe('exchanged-access');+ expect(saved?.refreshToken).toBe('exchanged-refresh');+ const expiresAtMs = Date.parse(saved!.expiresAt);+ expect(expiresAtMs).toBeGreaterThanOrEqual(beforeMs + 1800 * 1000);+ expect(expiresAtMs).toBeLessThanOrEqual(afterMs + 1800 * 1000);+ expect(tokenBodies).toHaveLength(1);+ const tokenBody = new URLSearchParams(String(tokenBodies[0]));+ expect(tokenBody.get('grant_type')).toBe('authorization_code');+ expect(tokenBody.get('code')).toBe('auth-code-1');+ expect(tokenBody.get('code_verifier')).toBeTruthy();+ expect(tokenBody.get('resource')).toBe(resourceUrlFromServerUrl(SERVER_URL).href);+ });++ it('throws on unknown state', async () => {+ const stores = newStores();+ await expect(+ completeMcpAuthorization({+ tokenStore: stores.tokenStore,+ mcpServerStore: stores.mcpServerStore,+ state: 'missing-state',+ code: 'code',+ }),+ ).rejects.toMatchObject({+ name: 'McpConnectionError',+ message: expect.stringContaining('Unknown or expired'),+ });+ });++ it('clears client state on invalid_client and surfaces a re-connect error', async () => {+ const stores = newStores();+ await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });+ const authUrl = await buildMcpAuthorizationUrl({+ ...resolveParams(stores),+ redirectUrl: 'https://app.example.com/after',+ });+ const state = authUrl.searchParams.get('state')!;++ globalThis.fetch = (async (input, init) => {+ const url = String(input);+ if (url === `${AS_ORIGIN}/token` && init?.method === 'POST') {+ return json({ error: 'invalid_client', error_description: 'client gone' }, 401);+ }+ return new Response(`unexpected url: ${url}`, { status: 404 });+ }) as typeof fetch;++ await expect(+ completeMcpAuthorization({+ tokenStore: stores.tokenStore,+ mcpServerStore: stores.mcpServerStore,+ state,+ code: 'auth-code-1',+ }),+ ).rejects.toMatchObject({+ name: 'McpConnectionError',+ message: expect.stringContaining('registration is invalid'),+ });+ expect(await stores.mcpServerStore.getClient({ id: SERVER_ID })).toBeUndefined();+ expect(await stores.tokenStore.getToken({ id: SERVER_ID })).toBeUndefined();+ });+});diff --git a/packages/server/src/db/mcpOAuthTypes.ts b/packages/server/src/db/mcpOAuthTypes.tsindex 7e848f481..48f1538a2 100644--- a/packages/server/src/db/mcpOAuthTypes.ts+++ b/packages/server/src/db/mcpOAuthTypes.ts@@ -2,10 +2,13 @@* Canonical JSON shapes for MCP OAuth columns (`mcp_server`, `oauth_token`,* `oauth_pending_authorization`). Owned by the server DB layer — not the harness.*- * `OAuthToken` happens to match the `IOAuthTokenStore` contract field for field today, so the+ * Contract types from `@truefoundry/utils/core` happen to match field for field today, so the* converters at the bottom are the seam that lets either side change without the other noticing.*/-import type { OAuthToken as ContractOAuthToken } from '@truefoundry/utils/core';+import type {+ OAuthClientRecord as ContractOAuthClientRecord,+ OAuthToken as ContractOAuthToken,+} from '@truefoundry/utils/core';// Absence is an explicit `| null`, not an optional `?:`@@ -31,6 +34,8 @@ export interface OAuthClient {/** `oauth_pending_authorization.auth_data` JSONB. */export interface OAuthPendingAuthorizationData {+ /** MCP server URL from authorize time — needed by the shared callback for RFC 8707 `resource`. */+ mcpServerUrl: string;codeVerifier: string | null;redirectUrl: string | null;}@@ -61,3 +66,37 @@ export function fromStoredOAuthToken(stored: OAuthToken): ContractOAuthToken {scope: stored.scope,};}++export function toStoredOAuthClientRecord(record: ContractOAuthClientRecord): {+ server: OAuthServer;+ client: OAuthClient;+} {+ return {+ server: {+ authorizationEndpoint: record.server.authorizationEndpoint,+ tokenEndpoint: record.server.tokenEndpoint,+ codeChallengeMethodsSupported: record.server.codeChallengeMethodsSupported,+ },+ client: {+ clientId: record.client.clientId,+ clientSecret: record.client.clientSecret,+ },+ };+}++export function fromStoredOAuthClientRecord(params: {+ server: OAuthServer;+ client: OAuthClient;+}): ContractOAuthClientRecord {+ return {+ server: {+ authorizationEndpoint: params.server.authorizationEndpoint,+ tokenEndpoint: params.server.tokenEndpoint,+ codeChallengeMethodsSupported: params.server.codeChallengeMethodsSupported,+ },+ client: {+ clientId: params.client.clientId,+ clientSecret: params.client.clientSecret,+ },+ };+}diff --git a/packages/server/src/db/mcpServerStore.ts b/packages/server/src/db/mcpServerStore.tsindex 33e5681b6..ae7af6f5a 100644--- a/packages/server/src/db/mcpServerStore.ts+++ b/packages/server/src/db/mcpServerStore.ts@@ -2,7 +2,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.+ *+ * Also owns the DCR registration columns (`oauth_server` / `oauth_client`) via+ * `IOAuthClientStore` — those are not a separate persistence root.*/+import type { IOAuthClientStore } from '@truefoundry/utils/core';import type { ResourceName } from '../schemas/common';import type { McpServerManifest } from '../schemas/mcpServer';@@ -28,7 +32,7 @@ export interface UpsertMcpServerInput {manifest: McpServerManifest;}-export interface IMcpServerStore {+export interface IMcpServerStore extends IOAuthClientStore {listServers(tenantId: string): Promise<McpServerRecord[]>;getServer(input: GetMcpServerInput): Promise<McpServerRecord | undefined>;/**diff --git a/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts b/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.tsindex bab8ebbc8..0e5dedd63 100644--- a/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts+++ b/packages/server/src/db/postgres/mcp-server-store/PostgresMcpServerStore.ts@@ -1,5 +1,7 @@+import type { OAuthClientRecord } from '@truefoundry/utils/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 { json, now } from '../sqlExpressions';import type { Database, McpServerTable } from '../types';@@ -65,4 +67,39 @@ export class PostgresMcpServerStore implements IMcpServerStore {.executeTakeFirstOrThrow();return toRecord(row);}++ async getClient(params: { id: string }): Promise<OAuthClientRecord | undefined> {+ const row = await this.#db+ .selectFrom('mcp_server')+ .select(['oauth_server', 'oauth_client'])+ .where('id', '=', params.id)+ .executeTakeFirst();+ if (row?.oauth_server == null || row.oauth_client == null) {+ return undefined;+ }+ return fromStoredOAuthClientRecord({ server: row.oauth_server, client: row.oauth_client });+ }++ async saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void> {+ const stored = toStoredOAuthClientRecord(params.record);+ await this.#db+ .updateTable('mcp_server')+ .set({+ oauth_server: json(stored.server),+ oauth_client: json(stored.client),+ })+ .where('id', '=', params.id)+ .execute();+ }++ async deleteClient(params: { id: string }): Promise<void> {+ await this.#db+ .updateTable('mcp_server')+ .set({+ oauth_server: null,+ oauth_client: null,+ })+ .where('id', '=', params.id)+ .execute();+ }}diff --git a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.tsindex 97dcd0083..45118913a 100644--- a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts+++ b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts@@ -2,11 +2,7 @@ import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@timport type { Kysely } from 'kysely';import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';import type { Database } from '../types';-import {- deletePendingAuthorization,- getPendingAuthorization,- savePendingAuthorization,-} from './queries/pendingAuthorization';+import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';import { deleteToken, getToken, saveToken } from './queries/token';export class PostgresOAuthTokenStore implements IOAuthTokenStore {@@ -16,12 +12,8 @@ export class PostgresOAuthTokenStore implements IOAuthTokenStore {return savePendingAuthorization(this.db, pending);}- getPendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined> {- return getPendingAuthorization(this.db, params);- }-- deletePendingAuthorization(params: { state: string }): Promise<void> {- return deletePendingAuthorization(this.db, params);+ consumePendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined> {+ return consumePendingAuthorization(this.db, params);}saveToken(params: { id: string; token: OAuthToken }): Promise<void> {diff --git a/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts b/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.tsindex a60ef69ae..0d8de3b55 100644--- a/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts+++ b/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts@@ -10,6 +10,7 @@ export async function savePendingAuthorization(): Promise<void> {// `state` and `id` are their own columns; only the remainder goes in the blob.const authData: OAuthPendingAuthorizationData = {+ mcpServerUrl: pending.mcpServerUrl,codeVerifier: pending.codeVerifier,redirectUrl: pending.redirectUrl,};@@ -25,15 +26,19 @@ export async function savePendingAuthorization(.execute();}-export async function getPendingAuthorization(+/**+ * Single-use claim: DELETE … RETURNING under the TTL filter so only one concurrent+ * callback wins the row.+ */+export async function consumePendingAuthorization(db: Kysely<Database>,params: { state: string },): Promise<OAuthPendingAuthorization | undefined> {const row = await db- .selectFrom('oauth_pending_authorization')- .select(['id', 'oauth_server_id', 'auth_data'])+ .deleteFrom('oauth_pending_authorization').where('id', '=', params.state).where('created_at', '>', nowMinusMs(PENDING_AUTHORIZATION_TTL_MS))+ .returning(['id', 'oauth_server_id', 'auth_data']).executeTakeFirst();if (row === undefined) {@@ -43,11 +48,8 @@ export async function getPendingAuthorization(return {state: row.id,id: row.oauth_server_id,+ mcpServerUrl: row.auth_data.mcpServerUrl,codeVerifier: row.auth_data.codeVerifier,redirectUrl: row.auth_data.redirectUrl,};}--export async function deletePendingAuthorization(db: Kysely<Database>, params: { state: string }): Promise<void> {- await db.deleteFrom('oauth_pending_authorization').where('id', '=', params.state).execute();-}diff --git a/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts b/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.tsindex 383924f45..3bafedf98 100644--- a/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts+++ b/packages/server/src/db/sqlite/mcp-server-store/SqliteMcpServerStore.ts@@ -1,6 +1,9 @@+import type { OAuthClientRecord } from '@truefoundry/utils/core';import type { ExpressionBuilder, Kysely } from 'kysely';import { ulid } from 'ulid';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 { jsonbBind, jsonText, nowIso } from '../sqlExpressions';import type { Database } from '../types';@@ -65,4 +68,42 @@ export class SqliteMcpServerStore implements IMcpServerStore {.returning(recordColumns).executeTakeFirstOrThrow();}++ async getClient(params: { id: string }): Promise<OAuthClientRecord | undefined> {+ const row = await this.#db+ .selectFrom('mcp_server')+ .select(eb => [+ jsonText<OAuthServer | null>(eb.ref('oauth_server')).as('oauth_server'),+ jsonText<OAuthClient | null>(eb.ref('oauth_client')).as('oauth_client'),+ ])+ .where('id', '=', params.id)+ .executeTakeFirst();+ if (row?.oauth_server == null || row.oauth_client == null) {+ return undefined;+ }+ return fromStoredOAuthClientRecord({ server: row.oauth_server, client: row.oauth_client });+ }++ async saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void> {+ const stored = toStoredOAuthClientRecord(params.record);+ await this.#db+ .updateTable('mcp_server')+ .set({+ oauth_server: jsonbBind(stored.server),+ oauth_client: jsonbBind(stored.client),+ })+ .where('id', '=', params.id)+ .execute();+ }++ async deleteClient(params: { id: string }): Promise<void> {+ await this.#db+ .updateTable('mcp_server')+ .set({+ oauth_server: null,+ oauth_client: null,+ })+ .where('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 2cd78a323..cf581d5c1 100644--- a/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts+++ b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts@@ -2,11 +2,7 @@ import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@timport type { Kysely } from 'kysely';import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';import type { Database } from '../types';-import {- deletePendingAuthorization,- getPendingAuthorization,- savePendingAuthorization,-} from './queries/pendingAuthorization';+import { consumePendingAuthorization, savePendingAuthorization } from './queries/pendingAuthorization';import { deleteToken, getToken, saveToken } from './queries/token';export class SqliteOAuthTokenStore implements IOAuthTokenStore {@@ -16,12 +12,8 @@ export class SqliteOAuthTokenStore implements IOAuthTokenStore {return savePendingAuthorization(this.db, pending);}- getPendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined> {- return getPendingAuthorization(this.db, params);- }-- deletePendingAuthorization(params: { state: string }): Promise<void> {- return deletePendingAuthorization(this.db, params);+ consumePendingAuthorization(params: { state: string }): Promise<OAuthPendingAuthorization | undefined> {+ return consumePendingAuthorization(this.db, params);}saveToken(params: { id: string; token: OAuthToken }): Promise<void> {diff --git a/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts b/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.tsindex a26fa2f62..5f420a497 100644--- a/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts+++ b/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts@@ -10,6 +10,7 @@ export async function savePendingAuthorization(): Promise<void> {// `state` and `id` are their own columns; only the remainder goes in the blob.const authData: OAuthPendingAuthorizationData = {+ mcpServerUrl: pending.mcpServerUrl,codeVerifier: pending.codeVerifier,redirectUrl: pending.redirectUrl,};@@ -25,15 +26,19 @@ export async function savePendingAuthorization(.execute();}-export async function getPendingAuthorization(+/**+ * Single-use claim: DELETE … RETURNING under the TTL filter so only one concurrent+ * callback wins the row.+ */+export async function consumePendingAuthorization(db: Kysely<Database>,params: { state: string },): Promise<OAuthPendingAuthorization | undefined> {const row = await db- .selectFrom('oauth_pending_authorization')- .select(['id', 'oauth_server_id', jsonText<OAuthPendingAuthorizationData>(sql.ref('auth_data')).as('auth_data')])+ .deleteFrom('oauth_pending_authorization').where('id', '=', params.state).where('created_at', '>', isoMsAgo(PENDING_AUTHORIZATION_TTL_MS))+ .returning(['id', 'oauth_server_id', jsonText<OAuthPendingAuthorizationData>(sql.ref('auth_data')).as('auth_data')]).executeTakeFirst();if (row === undefined) {@@ -43,11 +48,8 @@ export async function getPendingAuthorization(return {state: row.id,id: row.oauth_server_id,+ mcpServerUrl: row.auth_data.mcpServerUrl,codeVerifier: row.auth_data.codeVerifier,redirectUrl: row.auth_data.redirectUrl,};}--export async function deletePendingAuthorization(db: Kysely<Database>, params: { state: string }): Promise<void> {- await db.deleteFrom('oauth_pending_authorization').where('id', '=', params.state).execute();-}diff --git a/packages/server/src/db/sqlite/types.ts b/packages/server/src/db/sqlite/types.tsindex 095f78c43..f3b1a99d1 100644--- a/packages/server/src/db/sqlite/types.ts+++ b/packages/server/src/db/sqlite/types.ts@@ -211,7 +211,7 @@ export interface OAuthPendingAuthorizationTable {id: string;/** FK -> mcp_server.id, ON DELETE CASCADE */oauth_server_id: string;- /** { codeVerifier?, redirectUrl? } — same writer/lifecycle for both, so merged into one column */+ /** { mcpServerUrl, codeVerifier, redirectUrl } — same writer/lifecycle, so merged into one column */auth_data: JsonbColumn<OAuthPendingAuthorizationData>;created_at: string;}diff --git a/packages/server/tests/db/mcpServerStoreContractSuite.ts b/packages/server/tests/db/mcpServerStoreContractSuite.tsindex ba4ac00d7..83f4946f0 100644--- a/packages/server/tests/db/mcpServerStoreContractSuite.ts+++ b/packages/server/tests/db/mcpServerStoreContractSuite.ts@@ -2,6 +2,7 @@* 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';import type { IMcpServerStore } from '../../src/db/mcpServerStore';import type { McpServerManifest } from '../../src/schemas/mcpServer';@@ -17,6 +18,18 @@ function manifest(overrides: Partial<McpServerManifest> = {}): McpServerManifest};}+const sampleOAuthClient: OAuthClientRecord = {+ server: {+ authorizationEndpoint: 'https://auth.example.com/authorize',+ tokenEndpoint: 'https://auth.example.com/token',+ codeChallengeMethodsSupported: ['S256'],+ },+ client: {+ clientId: 'client-1',+ clientSecret: 'secret-1',+ },+};+const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;export function runMcpServerStoreContractSuite(getStore: () => IMcpServerStore): void {@@ -85,4 +98,44 @@ export function runMcpServerStoreContractSuite(getStore: () => IMcpServerStore):expect(servers.map(server => server.name)).toEqual(['deepwiki', 'linear']);expect(servers.every(server => server.tenant_id === TENANT)).toBe(true);});++ it('upsert leaves oauth columns null and does not clear a saved OAuth client', async () => {+ const store = getStore();+ const created = await store.upsertServer({+ tenant_id: TENANT,+ name: 'linear',+ manifest: manifest(),+ });+ expect(await store.getClient({ id: created.id })).toBeUndefined();++ await store.saveClient({ id: created.id, record: sampleOAuthClient });+ expect(await store.getClient({ id: created.id })).toEqual(sampleOAuthClient);++ await store.upsertServer({+ tenant_id: TENANT,+ name: 'linear',+ manifest: manifest({ url: 'https://mcp.linear.app/mcp/v2' }),+ });+ expect(await store.getClient({ id: created.id })).toEqual(sampleOAuthClient);+ });++ it('save/get/delete OAuth client round-trips and clears registration', async () => {+ const store = getStore();+ const created = await store.upsertServer({+ tenant_id: TENANT,+ name: 'linear',+ manifest: manifest(),+ });++ await store.saveClient({ id: created.id, record: sampleOAuthClient });+ expect(await store.getClient({ id: created.id })).toEqual(sampleOAuthClient);++ await store.deleteClient({ id: created.id });+ expect(await store.getClient({ id: created.id })).toBeUndefined();+ });++ it('getClient returns undefined for unknown server ids', async () => {+ const store = getStore();+ expect(await store.getClient({ id: 'missing-id' })).toBeUndefined();+ });}diff --git a/packages/server/tests/db/oauthTokenStoreContractSuite.ts b/packages/server/tests/db/oauthTokenStoreContractSuite.tsindex 059a655d6..a8ea2fdab 100644--- a/packages/server/tests/db/oauthTokenStoreContractSuite.ts+++ b/packages/server/tests/db/oauthTokenStoreContractSuite.ts@@ -31,6 +31,7 @@ function pending(overrides: Partial<OAuthPendingAuthorization> = {}): OAuthPendireturn {state: 'state-1',id: RESOURCE_ID,+ mcpServerUrl: 'https://mcp.example.com/sse',codeVerifier: 'verifier-1',redirectUrl: 'https://app.example.com/done',...overrides,@@ -83,29 +84,28 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStorexpect(await h.store.getToken({ id: OTHER_RESOURCE_ID })).toEqual(other);});- it('savePendingAuthorization round-trips, including null fields', async () => {+ it('savePendingAuthorization + consumePendingAuthorization round-trips, including null fields', async () => {const h = getHarness();await h.seedResource(RESOURCE_ID);const saved = pending({ codeVerifier: null, redirectUrl: null });await h.store.savePendingAuthorization(saved);- expect(await h.store.getPendingAuthorization({ state: 'state-1' })).toEqual(saved);+ expect(await h.store.consumePendingAuthorization({ state: 'state-1' })).toEqual(saved);});- it('getPendingAuthorization is undefined for an unknown state', async () => {+ it('consumePendingAuthorization is undefined for an unknown state', async () => {const h = getHarness();- expect(await h.store.getPendingAuthorization({ state: 'unknown' })).toBeUndefined();+ expect(await h.store.consumePendingAuthorization({ state: 'unknown' })).toBeUndefined();});- it('deletePendingAuthorization makes the state single-use', async () => {+ it('consumePendingAuthorization makes the state single-use', async () => {const h = getHarness();await h.seedResource(RESOURCE_ID);await h.store.savePendingAuthorization(pending());- await h.store.deletePendingAuthorization({ state: 'state-1' });-- expect(await h.store.getPendingAuthorization({ state: 'state-1' })).toBeUndefined();+ expect(await h.store.consumePendingAuthorization({ state: 'state-1' })).toEqual(pending());+ expect(await h.store.consumePendingAuthorization({ state: 'state-1' })).toBeUndefined();});it('pending authorizations are keyed by state, not by resource', async () => {@@ -116,19 +116,17 @@ export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStorawait h.store.savePendingAuthorization(pending());await h.store.savePendingAuthorization(other);- await h.store.deletePendingAuthorization({ state: 'state-1' });-- expect(await h.store.getPendingAuthorization({ state: 'state-1' })).toBeUndefined();- expect(await h.store.getPendingAuthorization({ state: 'state-2' })).toEqual(other);+ expect(await h.store.consumePendingAuthorization({ state: 'state-1' })).toEqual(pending());+ expect(await h.store.consumePendingAuthorization({ state: 'state-2' })).toEqual(other);});- it('getPendingAuthorization drops a row past its TTL', async () => {+ it('consumePendingAuthorization drops a row past its TTL', async () => {const h = getHarness();await h.seedResource(RESOURCE_ID);await h.store.savePendingAuthorization(pending());await h.expirePending('state-1');- expect(await h.store.getPendingAuthorization({ state: 'state-1' })).toBeUndefined();+ expect(await h.store.consumePendingAuthorization({ state: 'state-1' })).toBeUndefined();});}