Skip to content

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

AGE-1463:add token store postgres/sqllite impl (#30)

Heer Ambavide882c847be7
diff --git a/packages/harness/src/core/auth/IOAuthClientStore.ts b/packages/harness/src/core/auth/IOAuthClientStore.ts
new file mode 100644
index 000000000..d4ec91e77
--- /dev/null
+++ b/packages/harness/src/core/auth/IOAuthClientStore.ts
@@ -0,0 +1,28 @@
+/** Authorization-server endpoints, discovered and cached at registration time (mirrors `oauth_server`). */
+export interface OAuthServerMetadata {
+ authorizationEndpoint: string;
+ tokenEndpoint: string;
+ codeChallengeMethodsSupported: string[] | null;
+}
+
+/** Credentials for a dynamically-registered client, RFC 7591 (mirrors `oauth_client`). */
+export interface OAuthClientCredentials {
+ clientId: string;
+ clientSecret: string | null;
+}
+
+/**
+ * A client registered against a specific authorization server — the two halves the DCR flow
+ * produces, kept distinct because they come from different responses (discovery vs registration)
+ * and only `client` carries a secret.
+ */
+export interface OAuthClientRecord {
+ server: OAuthServerMetadata;
+ client: OAuthClientCredentials;
+}
+
+export interface IOAuthClientStore {
+ saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void>;
+
+ getClient(params: { id: string }): Promise<OAuthClientRecord | undefined>;
+}
diff --git a/packages/harness/src/core/auth/IOAuthTokenStore.ts b/packages/harness/src/core/auth/IOAuthTokenStore.ts
new file mode 100644
index 000000000..1736c49b3
--- /dev/null
+++ b/packages/harness/src/core/auth/IOAuthTokenStore.ts
@@ -0,0 +1,39 @@
+/** In-flight authorization awaiting the OAuth callback (keyed by CSRF `state`). */
+export interface OAuthPendingAuthorization {
+ /** The OAuth wire `state` param — also this store's lookup key for the pending row. */
+ state: string;
+ /** The resource this pending authorization is for — same `id` used everywhere else here. */
+ id: string;
+ /** `null` when the authorization server does not advertise PKCE support. */
+ codeVerifier: string | null;
+ /** FE landing URL after OAuth completes; not the OAuth redirect_uri. `null` when unset. */
+ redirectUrl: string | null;
+}
+
+/** Stored access token for one resource. */
+export interface OAuthToken {
+ accessToken: string;
+ refreshToken: string | null;
+ expiresAt: string;
+ /** Space-delimited, single string. `null` when unset. */
+ scope: string | null;
+}
+
+export interface IOAuthTokenStore {
+ savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void>;
+
+ /**
+ * 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.
+ */
+ 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>;
+
+ saveToken(params: { id: string; token: OAuthToken }): Promise<void>;
+
+ getToken(params: { id: string }): Promise<OAuthToken | undefined>;
+
+ deleteToken(params: { id: string }): Promise<void>;
+}
diff --git a/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts b/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts
new file mode 100644
index 000000000..32909f4eb
--- /dev/null
+++ b/packages/harness/src/core/auth/InMemoryOAuthClientStore.ts
@@ -0,0 +1,19 @@
+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).
+ */
+/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async for IOAuthClientStore callers */
+export class InMemoryOAuthClientStore implements IOAuthClientStore {
+ private readonly clients = new Map<string, OAuthClientRecord>();
+
+ async saveClient(params: { id: string; record: OAuthClientRecord }): Promise<void> {
+ this.clients.set(params.id, params.record);
+ }
+
+ async getClient(params: { id: string }): Promise<OAuthClientRecord | undefined> {
+ return this.clients.get(params.id);
+ }
+}
+/* eslint-enable @typescript-eslint/require-await */
diff --git a/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts b/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts
new file mode 100644
index 000000000..e7701e5fa
--- /dev/null
+++ b/packages/harness/src/core/auth/InMemoryOAuthTokenStore.ts
@@ -0,0 +1,43 @@
+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from './IOAuthTokenStore';
+
+/** This implementation's read-expiry window; the SQL-backed stores pick their own. */
+const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;
+
+/**
+ * In-memory `IOAuthTokenStore` — for tests and any dev/no-DB usage. Not for production use (no
+ * persistence across process restarts, no multi-replica sharing).
+ */
+/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async for IOAuthTokenStore callers */
+export class InMemoryOAuthTokenStore implements IOAuthTokenStore {
+ private readonly tokens = new Map<string, OAuthToken>();
+ private readonly pending = new Map<string, { row: OAuthPendingAuthorization; createdAtMs: number }>();
+
+ async savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void> {
+ this.pending.set(pending.state, { row: pending, createdAtMs: Date.now() });
+ }
+
+ async getPendingAuthorization(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);
+ }
+
+ async saveToken(params: { id: string; token: OAuthToken }): Promise<void> {
+ this.tokens.set(params.id, params.token);
+ }
+
+ async getToken(params: { id: string }): Promise<OAuthToken | undefined> {
+ return this.tokens.get(params.id);
+ }
+
+ async deleteToken(params: { id: string }): Promise<void> {
+ this.tokens.delete(params.id);
+ }
+}
+/* eslint-enable @typescript-eslint/require-await */
diff --git a/packages/harness/src/core/index.ts b/packages/harness/src/core/index.ts
index 96d1b7b4d..676ae22fa 100644
--- a/packages/harness/src/core/index.ts
+++ b/packages/harness/src/core/index.ts
@@ -47,6 +47,17 @@ export {
} from './capabilities/builtins/LargeToolResponse';
export { openUI } from './capabilities/builtins/OpenUI';
+// Auth contracts
+export { InMemoryOAuthClientStore } from './auth/InMemoryOAuthClientStore';
+export { InMemoryOAuthTokenStore } from './auth/InMemoryOAuthTokenStore';
+export type {
+ IOAuthClientStore,
+ OAuthClientCredentials,
+ OAuthClientRecord,
+ OAuthServerMetadata,
+} from './auth/IOAuthClientStore';
+export type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from './auth/IOAuthTokenStore';
+
// MCP contracts
export type { ApprovalDecision } from './events/schema';
export { ClientSideTool } from './mcp/ClientSideTool';
@@ -135,28 +146,21 @@ export type {
export { AgentHarnessError, McpConnectionError } from './errors';
export { extractErrorLogFields } from './util/errorLogFields';
-// MCP OAuth / DCR (token store contract + registration + auth URL + resolve)
+// MCP OAuth
export {
DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
- InMemoryMcpTokenStore,
MCP_OAUTH_CALLBACK_PATH,
- McpAuthStatus,
buildMcpAuthorizationUrl,
createMcpOAuthClient,
ensureMcpClientRegistered,
+ isMcpAuthRequired,
mcpAuthorizationServerMetadata,
mcpAuthorizationServerOrigin,
mcpClientInformation,
mcpOAuthCallbackUrl,
resolveMcpAuth,
} from './mcp/auth';
-export type {
- IMcpTokenStore,
- McpOAuthClientRecord,
- McpOAuthPendingAuthorization,
- McpOAuthToken,
- ResolveMcpAuthResult,
-} from './mcp/auth';
+export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcp/auth';
// Sandbox (concrete implementation; provider details exported for composition)
export {
diff --git a/packages/harness/src/core/mcp/auth/IMcpTokenStore.ts b/packages/harness/src/core/mcp/auth/IMcpTokenStore.ts
deleted file mode 100644
index ba5150899..000000000
--- a/packages/harness/src/core/mcp/auth/IMcpTokenStore.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Pure state store for MCP OAuth. One logical (server) row set keyed by mcp_server.id.
- * Implementations: Postgres/SQLite later; InMemory for tests/dev.
- */
-import type { McpOAuthClientRecord, McpOAuthPendingAuthorization, McpOAuthToken } from './types';
-
-export interface IMcpTokenStore {
- saveOAuthClient(params: { serverId: string; record: McpOAuthClientRecord }): Promise<void>;
-
- getOAuthClient(params: { serverId: string }): Promise<McpOAuthClientRecord | undefined>;
-
- savePendingAuthorization(pending: McpOAuthPendingAuthorization): Promise<void>;
-
- getPendingAuthorization(params: { state: string }): Promise<McpOAuthPendingAuthorization | undefined>;
-
- saveToken(params: { serverId: string; token: McpOAuthToken }): Promise<void>;
-
- getToken(params: { serverId: string }): Promise<McpOAuthToken | undefined>;
-
- /** Drops token only (keeps DCR client for re-authorization). */
- deleteToken(params: { serverId: string }): Promise<void>;
-
- /** Clears client, token, and pending rows for this MCP server id. */
- delete(params: { serverId: string }): Promise<void>;
-}
diff --git a/packages/harness/src/core/mcp/auth/InMemoryMcpTokenStore.ts b/packages/harness/src/core/mcp/auth/InMemoryMcpTokenStore.ts
deleted file mode 100644
index 613d60f15..000000000
--- a/packages/harness/src/core/mcp/auth/InMemoryMcpTokenStore.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import type { IMcpTokenStore } from './IMcpTokenStore';
-import type { McpOAuthClientRecord, McpOAuthPendingAuthorization, McpOAuthToken } from './types';
-
-/* eslint-disable @typescript-eslint/require-await -- in-memory store is synchronous; methods stay async for IMcpTokenStore callers */
-export class InMemoryMcpTokenStore implements IMcpTokenStore {
- private readonly clients = new Map<string, McpOAuthClientRecord>();
- private readonly tokens = new Map<string, McpOAuthToken>();
- private readonly pending = new Map<string, McpOAuthPendingAuthorization>();
-
- async saveOAuthClient(params: { serverId: string; record: McpOAuthClientRecord }): Promise<void> {
- this.clients.set(params.serverId, params.record);
- }
-
- async getOAuthClient(params: { serverId: string }): Promise<McpOAuthClientRecord | undefined> {
- return this.clients.get(params.serverId);
- }
-
- async savePendingAuthorization(pending: McpOAuthPendingAuthorization): Promise<void> {
- this.pending.set(pending.state, pending);
- }
-
- async getPendingAuthorization(params: { state: string }): Promise<McpOAuthPendingAuthorization | undefined> {
- return this.pending.get(params.state);
- }
-
- async saveToken(params: { serverId: string; token: McpOAuthToken }): Promise<void> {
- this.tokens.set(params.serverId, params.token);
- }
-
- async getToken(params: { serverId: string }): Promise<McpOAuthToken | undefined> {
- return this.tokens.get(params.serverId);
- }
-
- async deleteToken(params: { serverId: string }): Promise<void> {
- this.tokens.delete(params.serverId);
- }
-
- async delete(params: { serverId: string }): Promise<void> {
- this.clients.delete(params.serverId);
- this.tokens.delete(params.serverId);
- for (const [state, row] of this.pending) {
- if (row.serverId === params.serverId) {
- this.pending.delete(state);
- }
- }
- }
-}
-/* eslint-enable @typescript-eslint/require-await */
diff --git a/packages/harness/src/core/mcp/auth/index.ts b/packages/harness/src/core/mcp/auth/index.ts
index c3693311f..2cdaa04af 100644
--- a/packages/harness/src/core/mcp/auth/index.ts
+++ b/packages/harness/src/core/mcp/auth/index.ts
@@ -1,13 +1,12 @@
-export type { IMcpTokenStore } from './IMcpTokenStore';
-export { InMemoryMcpTokenStore } from './InMemoryMcpTokenStore';
export {
DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
buildMcpAuthorizationUrl,
createMcpOAuthClient,
ensureMcpClientRegistered,
+ isMcpAuthRequired,
resolveMcpAuth,
} from './mcpDcr';
-export type { ResolveMcpAuthResult } from './mcpDcr';
+export type { McpAuthRequiredResult, McpAuthResolvedResult, ResolveMcpAuthResult } from './mcpDcr';
export {
MCP_OAUTH_CALLBACK_PATH,
mcpAuthorizationServerMetadata,
@@ -15,5 +14,3 @@ export {
mcpClientInformation,
mcpOAuthCallbackUrl,
} from './mcpOAuthHelpers';
-export { McpAuthStatus } from './types';
-export type { McpOAuthClientRecord, McpOAuthPendingAuthorization, McpOAuthToken } from './types';
diff --git a/packages/harness/src/core/mcp/auth/mcpDcr.ts b/packages/harness/src/core/mcp/auth/mcpDcr.ts
index 6f894a335..514f57212 100644
--- a/packages/harness/src/core/mcp/auth/mcpDcr.ts
+++ b/packages/harness/src/core/mcp/auth/mcpDcr.ts
@@ -11,19 +11,29 @@ import type {
OAuthTokens,
} 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 { IMcpTokenStore } from './IMcpTokenStore';
import {
mcpAuthorizationServerMetadata,
mcpAuthorizationServerOrigin,
mcpClientInformation,
mcpOAuthCallbackUrl,
} from './mcpOAuthHelpers';
-import { McpAuthStatus, type McpOAuthClientRecord, type McpOAuthToken } from './types';
-export type ResolveMcpAuthResult =
- | { status: McpAuthStatus.Authenticated; headers: Record<string, string> }
- | { status: McpAuthStatus.AuthenticationRequired; authUrl: URL };
+export interface McpAuthResolvedResult {
+ headers: Record<string, string>;
+}
+
+export interface McpAuthRequiredResult {
+ authUrl: URL;
+}
+
+export type ResolveMcpAuthResult = McpAuthResolvedResult | McpAuthRequiredResult;
+
+export function isMcpAuthRequired(result: ResolveMcpAuthResult): result is McpAuthRequiredResult {
+ return 'authUrl' in result;
+}
/**
* When the token response omits `expires_in` (allowed by RFC 6749), use a 1h TTL so
@@ -43,7 +53,7 @@ async function registerMcpClientWithAuthMethodFallback(params: {
mcpServerName: string;
authorizationEndpoint: string;
tokenEndpoint: string;
-}): Promise<McpOAuthClientRecord> {
+}): Promise<OAuthClientRecord> {
const { authorizationServerUrl, metadata, clientMetadata, mcpServerName, authorizationEndpoint, tokenEndpoint } =
params;
@@ -71,17 +81,21 @@ async function registerMcpClientWithAuthMethodFallback(params: {
if (!fullInfo.client_id) {
throw new McpConnectionError(
- `Authorization server for MCP server '${mcpServerName}' returned a registration response without client_id`,
+ `Authorization server for MCP server '${mcpServerName}' returned a client response without client_id`,
400,
);
}
return {
- clientId: fullInfo.client_id,
- clientSecret: fullInfo.client_secret ?? null,
- authorizationEndpoint,
- tokenEndpoint,
- codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? null,
+ server: {
+ authorizationEndpoint,
+ tokenEndpoint,
+ codeChallengeMethodsSupported: metadata.code_challenge_methods_supported ?? null,
+ },
+ client: {
+ clientId: fullInfo.client_id,
+ clientSecret: fullInfo.client_secret ?? null,
+ },
};
}
@@ -90,7 +104,7 @@ export async function createMcpOAuthClient(params: {
mcpServerName: string;
redirectUri: string;
clientName: string;
-}): Promise<McpOAuthClientRecord> {
+}): Promise<OAuthClientRecord> {
const { mcpServerUrl, mcpServerName, redirectUri, clientName } = params;
const { authorizationServerUrl, authorizationServerMetadata: metadata } = await discoverOAuthServerInfo(mcpServerUrl);
@@ -125,31 +139,32 @@ export async function createMcpOAuthClient(params: {
}
export async function ensureMcpClientRegistered(params: {
- tokenStore: IMcpTokenStore;
+ clientStore: IOAuthClientStore;
serverId: string;
mcpServerUrl: string;
mcpServerName: string;
publicBaseUrl: string;
clientName: string;
-}): Promise<McpOAuthClientRecord> {
- const existing = await params.tokenStore.getOAuthClient({ serverId: params.serverId });
+}): Promise<OAuthClientRecord> {
+ const existing = await params.clientStore.getClient({ id: params.serverId });
if (existing) {
return existing;
}
- const record = await createMcpOAuthClient({
+ const client = await createMcpOAuthClient({
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
redirectUri: mcpOAuthCallbackUrl(params.publicBaseUrl),
clientName: params.clientName,
});
- await params.tokenStore.saveOAuthClient({ serverId: params.serverId, record });
- return record;
+ await params.clientStore.saveClient({ id: params.serverId, record: client });
+ return client;
}
export async function buildMcpAuthorizationUrl(params: {
- tokenStore: IMcpTokenStore;
+ tokenStore: IOAuthTokenStore;
+ clientStore: IOAuthClientStore;
serverId: string;
mcpServerUrl: string;
mcpServerName: string;
@@ -159,7 +174,7 @@ export async function buildMcpAuthorizationUrl(params: {
redirectUrl?: string;
}): Promise<URL> {
const client = await ensureMcpClientRegistered({
- tokenStore: params.tokenStore,
+ clientStore: params.clientStore,
serverId: params.serverId,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
@@ -167,11 +182,10 @@ export async function buildMcpAuthorizationUrl(params: {
clientName: params.clientName,
});
- // CSRF correlation: opaque state is the pending-row primary key.
const state = randomBytes(32).toString('base64url');
- const { authorizationUrl, codeVerifier } = await startAuthorization(mcpAuthorizationServerOrigin(client), {
- metadata: mcpAuthorizationServerMetadata(client),
- clientInformation: mcpClientInformation(client),
+ const { authorizationUrl, codeVerifier } = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {
+ metadata: mcpAuthorizationServerMetadata(client.server),
+ clientInformation: mcpClientInformation(client.client),
redirectUrl: mcpOAuthCallbackUrl(params.publicBaseUrl),
resource: resourceUrlFromServerUrl(params.mcpServerUrl),
state,
@@ -179,7 +193,7 @@ export async function buildMcpAuthorizationUrl(params: {
await params.tokenStore.savePendingAuthorization({
state,
- serverId: params.serverId,
+ id: params.serverId,
codeVerifier,
redirectUrl: params.redirectUrl ?? null,
});
@@ -192,11 +206,7 @@ function isMcpAccessTokenUsable(expiresAtIso: string, nowMs: number): boolean {
return !Number.isNaN(expiresAtMs) && expiresAtMs > nowMs;
}
-function oauthTokensToMcpOAuthToken(
- tokens: OAuthTokens,
- nowMs: number,
- fallbackRefreshToken: string | null,
-): McpOAuthToken {
+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 {
@@ -208,7 +218,8 @@ function oauthTokensToMcpOAuthToken(
}
export async function resolveMcpAuth(params: {
- tokenStore: IMcpTokenStore;
+ tokenStore: IOAuthTokenStore;
+ clientStore: IOAuthClientStore;
serverId: string;
mcpServerUrl: string;
mcpServerName: string;
@@ -219,31 +230,25 @@ export async function resolveMcpAuth(params: {
nowMs?: number;
}): Promise<ResolveMcpAuthResult> {
const nowMs = params.nowMs ?? Date.now();
- const token = await params.tokenStore.getToken({ serverId: params.serverId });
+ const token = await params.tokenStore.getToken({ id: params.serverId });
if (token && isMcpAccessTokenUsable(token.expiresAt, nowMs)) {
- return {
- status: McpAuthStatus.Authenticated,
- headers: { Authorization: `Bearer ${token.accessToken}` },
- };
+ return { headers: { Authorization: `Bearer ${token.accessToken}` } };
}
if (token?.refreshToken) {
- const client = await params.tokenStore.getOAuthClient({ serverId: params.serverId });
+ const client = await params.clientStore.getClient({ id: params.serverId });
if (client) {
try {
- const refreshed = await refreshAuthorization(mcpAuthorizationServerOrigin(client), {
- metadata: mcpAuthorizationServerMetadata(client),
- clientInformation: mcpClientInformation(client),
+ const refreshed = await refreshAuthorization(mcpAuthorizationServerOrigin(client.server), {
+ metadata: mcpAuthorizationServerMetadata(client.server),
+ clientInformation: mcpClientInformation(client.client),
refreshToken: token.refreshToken,
resource: resourceUrlFromServerUrl(params.mcpServerUrl),
});
- const saved = oauthTokensToMcpOAuthToken(refreshed, nowMs, token.refreshToken);
- await params.tokenStore.saveToken({ serverId: params.serverId, token: saved });
- return {
- status: McpAuthStatus.Authenticated,
- headers: { Authorization: `Bearer ${saved.accessToken}` },
- };
+ const saved = oauthTokensToOAuthToken(refreshed, nowMs, token.refreshToken);
+ await params.tokenStore.saveToken({ id: params.serverId, token: saved });
+ return { headers: { Authorization: `Bearer ${saved.accessToken}` } };
} catch {
// Any refresh failure → full re-authorize (do not inspect the error).
}
@@ -251,11 +256,12 @@ export async function resolveMcpAuth(params: {
}
if (token) {
- await params.tokenStore.deleteToken({ serverId: params.serverId });
+ await params.tokenStore.deleteToken({ id: params.serverId });
}
const authUrl = await buildMcpAuthorizationUrl({
tokenStore: params.tokenStore,
+ clientStore: params.clientStore,
serverId: params.serverId,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
@@ -263,5 +269,5 @@ export async function resolveMcpAuth(params: {
clientName: params.clientName,
...(params.redirectUrl !== undefined ? { redirectUrl: params.redirectUrl } : {}),
});
- return { status: McpAuthStatus.AuthenticationRequired, authUrl };
+ return { authUrl };
}
diff --git a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts
index 0fca1cc86..a373af7f3 100644
--- a/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts
+++ b/packages/harness/src/core/mcp/auth/mcpOAuthHelpers.ts
@@ -6,8 +6,8 @@ import type {
AuthorizationServerMetadata,
OAuthClientInformationMixed,
} from '@modelcontextprotocol/sdk/shared/auth.js';
+import type { OAuthClientCredentials, OAuthServerMetadata } from '../../auth/IOAuthClientStore';
import { McpConnectionError } from '../../errors';
-import type { McpOAuthClientRecord } from './types';
/** Fixed OAuth callback path for every MCP server (matches server mount). */
export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-servers/oauth/callback';
@@ -24,7 +24,7 @@ export function mcpOAuthCallbackUrl(publicBaseUrl: string): string {
* Same policy as servicefoundry outbound: form-body secret when present (client_secret_post),
* otherwise public (none). Method is not stored on the client record.
*/
-export function mcpClientInformation(client: McpOAuthClientRecord): OAuthClientInformationMixed {
+export function mcpClientInformation(client: OAuthClientCredentials): OAuthClientInformationMixed {
return client.clientSecret !== null
? {
client_id: client.clientId,
@@ -38,18 +38,18 @@ export function mcpClientInformation(client: McpOAuthClientRecord): OAuthClientI
}
/** Reconstruct authorization-server metadata enough for startAuthorization / token calls. */
-export function mcpAuthorizationServerMetadata(client: McpOAuthClientRecord): AuthorizationServerMetadata {
+export function mcpAuthorizationServerMetadata(server: OAuthServerMetadata): AuthorizationServerMetadata {
return {
- issuer: new URL(client.authorizationEndpoint).origin,
- authorization_endpoint: client.authorizationEndpoint,
- token_endpoint: client.tokenEndpoint,
+ issuer: new URL(server.authorizationEndpoint).origin,
+ authorization_endpoint: server.authorizationEndpoint,
+ token_endpoint: server.tokenEndpoint,
response_types_supported: ['code'],
- ...(client.codeChallengeMethodsSupported !== null
- ? { code_challenge_methods_supported: client.codeChallengeMethodsSupported }
+ ...(server.codeChallengeMethodsSupported !== null
+ ? { code_challenge_methods_supported: server.codeChallengeMethodsSupported }
: {}),
};
}
-export function mcpAuthorizationServerOrigin(client: McpOAuthClientRecord): string {
- return new URL(client.authorizationEndpoint).origin;
+export function mcpAuthorizationServerOrigin(server: OAuthServerMetadata): string {
+ return new URL(server.authorizationEndpoint).origin;
}
diff --git a/packages/harness/src/core/mcp/auth/types.ts b/packages/harness/src/core/mcp/auth/types.ts
deleted file mode 100644
index 09f393546..000000000
--- a/packages/harness/src/core/mcp/auth/types.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * Runtime shapes used by MCP OAuth helpers and {@link IMcpTokenStore}.
- * Not the DB source of truth — server column JSON lives in
- * `packages/server/src/db/mcpOAuthTypes.ts`.
- *
- * Store records use explicit `null` for absence (see packages/harness/AGENTS.md).
- */
-
-export enum McpAuthStatus {
- Authenticated = 'authenticated',
- AuthenticationRequired = 'authentication_required',
-}
-
-/** Discovered/cached authorization-server endpoints used by DCR and authorize. */
-export interface McpOAuthClientRecord {
- clientId: string;
- clientSecret: string | null;
- authorizationEndpoint: string;
- tokenEndpoint: string;
- codeChallengeMethodsSupported: string[] | null;
-}
-
-/** Access token returned by the authorization code exchange. */
-export interface McpOAuthToken {
- accessToken: string;
- refreshToken: string | null;
- /** ISO 8601 */
- expiresAt: string;
- scope: string | null;
-}
-
-/**
- * Pending PKCE authorization. `state` is the OAuth `state` param / pending-row id;
- * `serverId` is the MCP server id.
- */
-export interface McpOAuthPendingAuthorization {
- state: string;
- serverId: string;
- codeVerifier: string | null;
- /** FE post-OAuth landing URL (not the OAuth redirect_uri). */
- redirectUrl: string | null;
-}
diff --git a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts
index a49c52d4a..fab0e1608 100644
--- a/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts
+++ b/packages/harness/tests/core/mcp/auth/mcpOAuth.test.ts
@@ -5,17 +5,28 @@
import { resourceUrlFromServerUrl } from '@modelcontextprotocol/sdk/shared/auth-utils.js';
import {
DEFAULT_MCP_ACCESS_TOKEN_TTL_SECONDS,
- InMemoryMcpTokenStore,
- McpAuthStatus,
+ InMemoryOAuthClientStore,
+ InMemoryOAuthTokenStore,
McpConnectionError,
buildMcpAuthorizationUrl,
createMcpOAuthClient,
ensureMcpClientRegistered,
+ isMcpAuthRequired,
mcpOAuthCallbackUrl,
resolveMcpAuth,
- type McpOAuthClientRecord,
+ type OAuthClientRecord,
} from '../../../../src/core';
+interface Stores {
+ tokenStore: InMemoryOAuthTokenStore;
+ clientStore: InMemoryOAuthClientStore;
+}
+
+/** The two generic stores the helpers consume, freshly backed in memory per test. */
+function newStores(): Stores {
+ return { tokenStore: new InMemoryOAuthTokenStore(), clientStore: new InMemoryOAuthClientStore() };
+}
+
const PUBLIC_BASE_URL = 'https://harness.example.com';
const CLIENT_NAME = 'harness';
const SERVER_URL = 'https://mcp.example.com/sse';
@@ -120,12 +131,16 @@ function stubOauthFetch(options: {
return { registerBodies, registerCallCount: () => registerCalls, tokenBodies, tokenAuthHeaders };
}
-const sampleClient: McpOAuthClientRecord = {
- clientId: 'cached-client',
- clientSecret: 'cached-secret',
- authorizationEndpoint: `${AS_ORIGIN}/authorize`,
- tokenEndpoint: `${AS_ORIGIN}/token`,
- codeChallengeMethodsSupported: ['S256'],
+const sampleClient: OAuthClientRecord = {
+ server: {
+ authorizationEndpoint: `${AS_ORIGIN}/authorize`,
+ tokenEndpoint: `${AS_ORIGIN}/token`,
+ codeChallengeMethodsSupported: ['S256'],
+ },
+ client: {
+ clientId: 'cached-client',
+ clientSecret: 'cached-secret',
+ },
};
describe('resourceUrlFromServerUrl (SDK)', () => {
@@ -138,12 +153,12 @@ describe('resourceUrlFromServerUrl (SDK)', () => {
describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
it('returns the cached client without discovery or registration', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ const { clientStore } = newStores();
+ await clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
const { registerCallCount } = stubOauthFetch({});
const result = await ensureMcpClientRegistered({
- tokenStore: store,
+ clientStore,
serverId: SERVER_ID,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
@@ -156,11 +171,11 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
});
it('discovers, registers confidential client, and saves the record', async () => {
- const store = new InMemoryMcpTokenStore();
+ const { clientStore } = newStores();
const { registerBodies } = stubOauthFetch({});
const result = await ensureMcpClientRegistered({
- tokenStore: store,
+ clientStore,
serverId: SERVER_ID,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
@@ -168,11 +183,11 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
clientName: CLIENT_NAME,
});
- expect(result.clientId).toBe('dyn-client-1');
- expect(result.clientSecret).toBe('dyn-secret-1');
- expect(result.authorizationEndpoint).toBe(`${AS_ORIGIN}/authorize`);
- expect(result.tokenEndpoint).toBe(`${AS_ORIGIN}/token`);
- expect(result.codeChallengeMethodsSupported).toEqual(['S256']);
+ expect(result.client.clientId).toBe('dyn-client-1');
+ expect(result.client.clientSecret).toBe('dyn-secret-1');
+ expect(result.server.authorizationEndpoint).toBe(`${AS_ORIGIN}/authorize`);
+ expect(result.server.tokenEndpoint).toBe(`${AS_ORIGIN}/token`);
+ expect(result.server.codeChallengeMethodsSupported).toEqual(['S256']);
expect(registerBodies).toHaveLength(1);
const body = registerBodies[0] as Record<string, unknown>;
expect(body['token_endpoint_auth_method']).toBe('client_secret_post');
@@ -182,14 +197,14 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
});
it('retries registration without token_endpoint_auth_method when the first attempt fails', async () => {
- const store = new InMemoryMcpTokenStore();
+ const { clientStore } = newStores();
const { registerBodies, registerCallCount } = stubOauthFetch({
registrationFailFirst: true,
registeredClient: { client_id: 'public-client' },
});
const result = await ensureMcpClientRegistered({
- tokenStore: store,
+ clientStore,
serverId: SERVER_ID,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
@@ -197,20 +212,20 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
clientName: CLIENT_NAME,
});
- expect(result.clientId).toBe('public-client');
- expect(result.clientSecret).toBeNull();
+ expect(result.client.clientId).toBe('public-client');
+ expect(result.client.clientSecret).toBeNull();
expect(registerCallCount()).toBe(2);
expect((registerBodies[0] as Record<string, unknown>)['token_endpoint_auth_method']).toBe('client_secret_post');
expect((registerBodies[1] as Record<string, unknown>)['token_endpoint_auth_method']).toBeUndefined();
});
it('throws when the AS has no registration_endpoint', async () => {
- const store = new InMemoryMcpTokenStore();
+ const { clientStore } = newStores();
stubOauthFetch({ skipRegistrationEndpoint: true });
await expect(
ensureMcpClientRegistered({
- tokenStore: store,
+ clientStore,
serverId: SERVER_ID,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
@@ -224,7 +239,7 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
});
it('does not save a client when both registration attempts fail', async () => {
- const store = new InMemoryMcpTokenStore();
+ const { clientStore } = newStores();
const { registerCallCount } = stubOauthFetch({ registrationFailAlways: true });
await expect(
@@ -236,13 +251,13 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
}),
).rejects.toBeInstanceOf(McpConnectionError);
expect(registerCallCount()).toBe(2);
- expect(await store.getOAuthClient({ serverId: SERVER_ID })).toBeUndefined();
+ expect(await clientStore.getClient({ id: SERVER_ID })).toBeUndefined();
});
it('throws when publicBaseUrl is empty (no trimming)', async () => {
await expect(
ensureMcpClientRegistered({
- tokenStore: new InMemoryMcpTokenStore(),
+ clientStore: new InMemoryOAuthClientStore(),
serverId: SERVER_ID,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
@@ -255,12 +270,13 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
describe('buildMcpAuthorizationUrl', () => {
it('saves pending authorization with state and returns a URL object', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ const { tokenStore, clientStore } = newStores();
+ await clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
stubOauthFetch({});
const authUrl = await buildMcpAuthorizationUrl({
- tokenStore: store,
+ tokenStore,
+ clientStore,
serverId: SERVER_ID,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
@@ -271,7 +287,7 @@ describe('buildMcpAuthorizationUrl', () => {
expect(authUrl).toBeInstanceOf(URL);
expect(authUrl.origin + authUrl.pathname).toBe(`${AS_ORIGIN}/authorize`);
- expect(authUrl.searchParams.get('client_id')).toBe(sampleClient.clientId);
+ expect(authUrl.searchParams.get('client_id')).toBe(sampleClient.client.clientId);
expect(authUrl.searchParams.get('redirect_uri')).toBe(mcpOAuthCallbackUrl(PUBLIC_BASE_URL));
expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');
expect(authUrl.searchParams.get('code_challenge')).toBeTruthy();
@@ -279,18 +295,19 @@ describe('buildMcpAuthorizationUrl', () => {
const state = authUrl.searchParams.get('state');
expect(state).toBeTruthy();
- const pending = await store.getPendingAuthorization({ state: state! });
+ const pending = await tokenStore.getPendingAuthorization({ state: state! });
expect(pending).toMatchObject({
state,
- serverId: SERVER_ID,
+ id: SERVER_ID,
redirectUrl: 'https://app.example.com/after',
});
expect(pending?.codeVerifier).toBeTruthy();
});
});
-const resolveParams = (store: InMemoryMcpTokenStore, mcpServerUrl = SERVER_URL) => ({
- tokenStore: store,
+const resolveParams = (stores: Stores, mcpServerUrl = SERVER_URL) => ({
+ tokenStore: stores.tokenStore,
+ clientStore: stores.clientStore,
serverId: SERVER_ID,
mcpServerUrl,
mcpServerName: SERVER_NAME,
@@ -300,9 +317,9 @@ const resolveParams = (store: InMemoryMcpTokenStore, mcpServerUrl = SERVER_URL)
describe('resolveMcpAuth', () => {
it('returns bearer headers when the token is still valid', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveToken({
- serverId: SERVER_ID,
+ const stores = newStores();
+ await stores.tokenStore.saveToken({
+ id: SERVER_ID,
token: {
accessToken: 'live-token',
refreshToken: null,
@@ -311,19 +328,16 @@ describe('resolveMcpAuth', () => {
},
});
- const result = await resolveMcpAuth(resolveParams(store));
+ const result = await resolveMcpAuth(resolveParams(stores));
- expect(result).toEqual({
- status: McpAuthStatus.Authenticated,
- headers: { Authorization: 'Bearer live-token' },
- });
+ expect(result).toEqual({ headers: { Authorization: 'Bearer live-token' } });
});
it('refreshes an expired token when a refresh_token is stored', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
- await store.saveToken({
- serverId: SERVER_ID,
+ const stores = newStores();
+ await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
+ await stores.tokenStore.saveToken({
+ id: SERVER_ID,
token: {
accessToken: 'old-access',
refreshToken: 'old-refresh',
@@ -340,27 +354,24 @@ describe('resolveMcpAuth', () => {
},
});
- const result = await resolveMcpAuth(resolveParams(store));
+ const result = await resolveMcpAuth(resolveParams(stores));
- expect(result).toEqual({
- status: McpAuthStatus.Authenticated,
- headers: { Authorization: 'Bearer new-access' },
- });
+ expect(result).toEqual({ headers: { Authorization: 'Bearer new-access' } });
expect(tokenBodies).toHaveLength(1);
expect(String(tokenBodies[0])).toContain('grant_type=refresh_token');
// Secret present → client_secret_post (form body), not HTTP Basic.
expect(String(tokenBodies[0])).toContain('client_secret=cached-secret');
expect(tokenAuthHeaders[0]).toBe('');
- const saved = await store.getToken({ serverId: SERVER_ID });
+ const saved = await stores.tokenStore.getToken({ id: SERVER_ID });
expect(saved?.accessToken).toBe('new-access');
expect(saved?.refreshToken).toBe('new-refresh');
});
it('uses a default TTL when the token response omits expires_in', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
- await store.saveToken({
- serverId: SERVER_ID,
+ const stores = newStores();
+ await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
+ await stores.tokenStore.saveToken({
+ id: SERVER_ID,
token: {
accessToken: 'old-access',
refreshToken: 'old-refresh',
@@ -377,27 +388,21 @@ describe('resolveMcpAuth', () => {
},
});
- const result = await resolveMcpAuth({ ...resolveParams(store), nowMs });
+ const result = await resolveMcpAuth({ ...resolveParams(stores), nowMs });
- expect(result).toEqual({
- status: McpAuthStatus.Authenticated,
- headers: { Authorization: 'Bearer new-access' },
- });
- const saved = await store.getToken({ serverId: SERVER_ID });
+ 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(store), nowMs: nowMs + 1_000 });
- expect(again).toEqual({
- status: McpAuthStatus.Authenticated,
- headers: { Authorization: 'Bearer new-access' },
- });
+ const again = await resolveMcpAuth({ ...resolveParams(stores), nowMs: nowMs + 1_000 });
+ expect(again).toEqual({ headers: { Authorization: 'Bearer new-access' } });
});
it('returns authentication_required and clears token when refresh fails', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
- await store.saveToken({
- serverId: SERVER_ID,
+ const stores = newStores();
+ await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
+ await stores.tokenStore.saveToken({
+ id: SERVER_ID,
token: {
accessToken: 'old-access',
refreshToken: 'old-refresh',
@@ -407,20 +412,20 @@ describe('resolveMcpAuth', () => {
});
stubOauthFetch({ tokenFail: true });
- const result = await resolveMcpAuth(resolveParams(store));
+ const result = await resolveMcpAuth(resolveParams(stores));
- expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
- if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(isMcpAuthRequired(result)).toBe(true);
+ if (!isMcpAuthRequired(result)) throw new Error('unreachable');
expect(result.authUrl).toBeInstanceOf(URL);
- expect(await store.getToken({ serverId: SERVER_ID })).toBeUndefined();
- expect(await store.getOAuthClient({ serverId: SERVER_ID })).toEqual(sampleClient);
+ expect(await stores.tokenStore.getToken({ id: SERVER_ID })).toBeUndefined();
+ expect(await stores.clientStore.getClient({ id: SERVER_ID })).toEqual(sampleClient);
});
it('returns authentication_required and clears expired token without refresh_token', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
- await store.saveToken({
- serverId: SERVER_ID,
+ const stores = newStores();
+ await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
+ await stores.tokenStore.saveToken({
+ id: SERVER_ID,
token: {
accessToken: 'old-access',
refreshToken: null,
@@ -430,25 +435,25 @@ describe('resolveMcpAuth', () => {
});
stubOauthFetch({});
- const result = await resolveMcpAuth(resolveParams(store));
+ const result = await resolveMcpAuth(resolveParams(stores));
- expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
- if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(isMcpAuthRequired(result)).toBe(true);
+ if (!isMcpAuthRequired(result)) throw new Error('unreachable');
expect(result.authUrl).toBeInstanceOf(URL);
expect(result.authUrl.href).toContain('/authorize');
- expect(await store.getToken({ serverId: SERVER_ID })).toBeUndefined();
- expect(await store.getOAuthClient({ serverId: SERVER_ID })).toEqual(sampleClient);
+ expect(await stores.tokenStore.getToken({ id: SERVER_ID })).toBeUndefined();
+ expect(await stores.clientStore.getClient({ id: SERVER_ID })).toEqual(sampleClient);
});
it('returns authentication_required when no token exists', async () => {
- const store = new InMemoryMcpTokenStore();
- await store.saveOAuthClient({ serverId: SERVER_ID, record: sampleClient });
+ const stores = newStores();
+ await stores.clientStore.saveClient({ id: SERVER_ID, record: sampleClient });
stubOauthFetch({});
- const result = await resolveMcpAuth(resolveParams(store));
+ const result = await resolveMcpAuth(resolveParams(stores));
- expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
- if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(isMcpAuthRequired(result)).toBe(true);
+ if (!isMcpAuthRequired(result)) throw new Error('unreachable');
expect(result.authUrl.searchParams.get('state')).toBeTruthy();
});
});
@@ -457,17 +462,17 @@ describe('end-to-end DCR + authorize with normalised MCP URL', () => {
it('registers, builds auth URL with resource, and resolves auth_required without a token', async () => {
// Mixed-case scheme/host + fragment: resource indicator must still be RFC-8707-safe.
const mixedUrl = 'HTTPS://MCP.Example.COM/sse#fragment';
- const store = new InMemoryMcpTokenStore();
+ const stores = newStores();
const { registerBodies } = stubOauthFetch({});
- const result = await resolveMcpAuth(resolveParams(store, mixedUrl));
+ const result = await resolveMcpAuth(resolveParams(stores, mixedUrl));
- expect(result.status).toBe(McpAuthStatus.AuthenticationRequired);
- if (result.status !== McpAuthStatus.AuthenticationRequired) throw new Error('unreachable');
+ expect(isMcpAuthRequired(result)).toBe(true);
+ if (!isMcpAuthRequired(result)) throw new Error('unreachable');
expect(registerBodies).toHaveLength(1);
- const client = await store.getOAuthClient({ serverId: SERVER_ID });
- expect(client?.clientId).toBe('dyn-client-1');
+ const client = await stores.clientStore.getClient({ id: SERVER_ID });
+ expect(client?.client.clientId).toBe('dyn-client-1');
const url = result.authUrl;
expect(url.searchParams.get('state')).toBeTruthy();
diff --git a/packages/server/src/db/mcpOAuthTypes.ts b/packages/server/src/db/mcpOAuthTypes.ts
index 2b9c42b31..7e848f481 100644
--- a/packages/server/src/db/mcpOAuthTypes.ts
+++ b/packages/server/src/db/mcpOAuthTypes.ts
@@ -1,45 +1,63 @@
/**
* 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
+ * 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';
+
+// Absence is an explicit `| null`, not an optional `?:`
+
+/**
+ * How long a pending authorization stays redeemable — long enough to finish a consent screen,
+ * short enough that an abandoned `state` and its PKCE verifier stop being usable. Applied as a
+ * `created_at` filter on read by both backends, so no sweep job is needed.
+ */
+export const PENDING_AUTHORIZATION_TTL_MS = 10 * 60 * 1000;
/** RFC 8414 AS metadata cached at DCR time (`mcp_server.oauth_server`). */
export interface OAuthServer {
authorizationEndpoint: string;
tokenEndpoint: string;
- codeChallengeMethodsSupported?: string[];
+ codeChallengeMethodsSupported: string[] | null;
}
/** RFC 7591 DCR response (`mcp_server.oauth_client`). */
export interface OAuthClient {
clientId: string;
- clientSecret?: string;
+ clientSecret: string | null;
}
/** `oauth_pending_authorization.auth_data` JSONB. */
-export interface McpOAuthPendingAuthorizationData {
- codeVerifier?: string;
- redirectUrl?: string;
+export interface OAuthPendingAuthorizationData {
+ codeVerifier: string | null;
+ redirectUrl: string | null;
}
/** `oauth_token.token` JSONB. */
-export interface McpOAuthToken {
+export interface OAuthToken {
accessToken: string;
- refreshToken?: string;
+ refreshToken: string | null;
/** ISO 8601 */
expiresAt: string;
- scope?: string;
+ scope: string | null;
}
-/** Joined view of oauth_client + oauth_server (written together at DCR). */
-export type McpOAuthClientRecord = OAuthClient & OAuthServer;
+export function toStoredOAuthToken(token: ContractOAuthToken): OAuthToken {
+ return {
+ accessToken: token.accessToken,
+ refreshToken: token.refreshToken,
+ expiresAt: token.expiresAt,
+ scope: token.scope,
+ };
+}
-/**
- * Pending auth envelope for store APIs.
- * `state` is `oauth_pending_authorization.id` (OAuth wire `state`).
- * `serverId` is `mcp_server.id` / `oauth_server_id` FK.
- */
-export type McpOAuthPendingAuthorization = McpOAuthPendingAuthorizationData & {
- state: string;
- serverId: string;
-};
+export function fromStoredOAuthToken(stored: OAuthToken): ContractOAuthToken {
+ return {
+ accessToken: stored.accessToken,
+ refreshToken: stored.refreshToken,
+ expiresAt: stored.expiresAt,
+ scope: stored.scope,
+ };
+}
diff --git a/packages/server/src/db/postgres/sqlExpressions.ts b/packages/server/src/db/postgres/sqlExpressions.ts
index 24b4b04d3..90e44bc8d 100644
--- a/packages/server/src/db/postgres/sqlExpressions.ts
+++ b/packages/server/src/db/postgres/sqlExpressions.ts
@@ -25,3 +25,7 @@ export function jsonbSet<T = unknown>(
export function now(): RawBuilder<Date> {
return sql<Date>`now()`;
}
+
+export function nowMinusMs(ms: number): RawBuilder<Date> {
+ return sql<Date>`now() - ${ms}::double precision * interval '1 millisecond'`;
+}
diff --git a/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts
new file mode 100644
index 000000000..97dcd0083
--- /dev/null
+++ b/packages/server/src/db/postgres/token-store/PostgresOAuthTokenStore.ts
@@ -0,0 +1,39 @@
+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@truefoundry/utils/core';
+import type { Kysely } from 'kysely';
+import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';
+import type { Database } from '../types';
+import {
+ deletePendingAuthorization,
+ getPendingAuthorization,
+ savePendingAuthorization,
+} from './queries/pendingAuthorization';
+import { deleteToken, getToken, saveToken } from './queries/token';
+
+export class PostgresOAuthTokenStore implements IOAuthTokenStore {
+ constructor(private readonly db: Kysely<Database>) {}
+
+ savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void> {
+ 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);
+ }
+
+ saveToken(params: { id: string; token: OAuthToken }): Promise<void> {
+ return saveToken(this.db, { id: params.id, token: toStoredOAuthToken(params.token) });
+ }
+
+ async getToken(params: { id: string }): Promise<OAuthToken | undefined> {
+ const stored = await getToken(this.db, params);
+ return stored === undefined ? undefined : fromStoredOAuthToken(stored);
+ }
+
+ deleteToken(params: { id: string }): Promise<void> {
+ return deleteToken(this.db, params);
+ }
+}
diff --git a/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts b/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts
new file mode 100644
index 000000000..a60ef69ae
--- /dev/null
+++ b/packages/server/src/db/postgres/token-store/queries/pendingAuthorization.ts
@@ -0,0 +1,53 @@
+import type { OAuthPendingAuthorization } from '@truefoundry/utils/core';
+import type { Kysely } from 'kysely';
+import { PENDING_AUTHORIZATION_TTL_MS, type OAuthPendingAuthorizationData } from '../../../mcpOAuthTypes';
+import { json, now, nowMinusMs } from '../../sqlExpressions';
+import type { Database } from '../../types';
+
+export async function savePendingAuthorization(
+ db: Kysely<Database>,
+ pending: OAuthPendingAuthorization,
+): Promise<void> {
+ // `state` and `id` are their own columns; only the remainder goes in the blob.
+ const authData: OAuthPendingAuthorizationData = {
+ codeVerifier: pending.codeVerifier,
+ redirectUrl: pending.redirectUrl,
+ };
+
+ await db
+ .insertInto('oauth_pending_authorization')
+ .values({
+ id: pending.state,
+ oauth_server_id: pending.id,
+ auth_data: json(authData),
+ created_at: now(),
+ })
+ .execute();
+}
+
+export async function getPendingAuthorization(
+ db: Kysely<Database>,
+ params: { state: string },
+): Promise<OAuthPendingAuthorization | undefined> {
+ const row = await db
+ .selectFrom('oauth_pending_authorization')
+ .select(['id', 'oauth_server_id', 'auth_data'])
+ .where('id', '=', params.state)
+ .where('created_at', '>', nowMinusMs(PENDING_AUTHORIZATION_TTL_MS))
+ .executeTakeFirst();
+
+ if (row === undefined) {
+ return undefined;
+ }
+
+ return {
+ state: row.id,
+ id: row.oauth_server_id,
+ 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/postgres/token-store/queries/token.ts b/packages/server/src/db/postgres/token-store/queries/token.ts
new file mode 100644
index 000000000..0a6c2877b
--- /dev/null
+++ b/packages/server/src/db/postgres/token-store/queries/token.ts
@@ -0,0 +1,35 @@
+import { sql, type Kysely } from 'kysely';
+import type { OAuthToken } from '../../../mcpOAuthTypes';
+import { json, now } from '../../sqlExpressions';
+import type { Database } from '../../types';
+
+export async function saveToken(db: Kysely<Database>, params: { id: string; token: OAuthToken }): Promise<void> {
+ await db
+ .insertInto('oauth_token')
+ .values({
+ oauth_server_id: params.id,
+ token: json(params.token),
+ updated_at: now(),
+ })
+ .onConflict(oc =>
+ oc.column('oauth_server_id').doUpdateSet({
+ token: sql`excluded.token`,
+ updated_at: sql`excluded.updated_at`,
+ }),
+ )
+ .execute();
+}
+
+export async function getToken(db: Kysely<Database>, params: { id: string }): Promise<OAuthToken | undefined> {
+ const row = await db
+ .selectFrom('oauth_token')
+ .select('token')
+ .where('oauth_server_id', '=', params.id)
+ .executeTakeFirst();
+
+ return row === undefined ? undefined : 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/postgres/types.ts b/packages/server/src/db/postgres/types.ts
index f75e5085f..6f32a0d3b 100644
--- a/packages/server/src/db/postgres/types.ts
+++ b/packages/server/src/db/postgres/types.ts
@@ -17,7 +17,7 @@ import type { ColumnType, Generated, JSONColumnType } from 'kysely';
import type { McpServerManifest } from '../../schemas/mcpServer';
import type { ProviderManifest } from '../../schemas/modelProvider';
import type { SkillManifest } from '../../schemas/skill';
-import type { McpOAuthPendingAuthorizationData, McpOAuthToken, OAuthClient, OAuthServer } from '../mcpOAuthTypes';
+import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpOAuthTypes';
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -349,7 +349,7 @@ export interface OAuthTokenTable {
/** FK -> mcp_server.id, ON DELETE CASCADE */
oauth_server_id: string;
/** access_token, refresh_token, expires_at, scope. */
- token: JSONColumnType<McpOAuthToken, McpOAuthToken, McpOAuthToken>;
+ token: JSONColumnType<OAuthToken, OAuthToken, OAuthToken>;
updated_at: Date;
}
@@ -364,11 +364,11 @@ export interface OAuthPendingAuthorizationTable {
/** FK -> mcp_server.id, ON DELETE CASCADE */
oauth_server_id: string;
auth_data: JSONColumnType<
- McpOAuthPendingAuthorizationData,
- McpOAuthPendingAuthorizationData,
- McpOAuthPendingAuthorizationData
+ OAuthPendingAuthorizationData,
+ OAuthPendingAuthorizationData,
+ OAuthPendingAuthorizationData
>;
- /** used for TTL expiry on read, no sweep job */
+ /** filtered against `PENDING_AUTHORIZATION_TTL_MS` on read, no sweep job */
created_at: Date;
}
diff --git a/packages/server/src/db/sqlite/client.ts b/packages/server/src/db/sqlite/client.ts
index 6be122d72..87e035052 100644
--- a/packages/server/src/db/sqlite/client.ts
+++ b/packages/server/src/db/sqlite/client.ts
@@ -137,6 +137,10 @@ const JSON_RESULT_COLUMNS = new Set([
'thread_checkpoint',
'event',
'manifest',
+ 'oauth_server',
+ 'oauth_client',
+ 'token',
+ 'auth_data',
]);
/** Top-level row field only — `$[0]."body"`, not `$[0]."body"."content"`. */
diff --git a/packages/server/src/db/sqlite/sqlExpressions.ts b/packages/server/src/db/sqlite/sqlExpressions.ts
index d588c848a..76e4fefe1 100644
--- a/packages/server/src/db/sqlite/sqlExpressions.ts
+++ b/packages/server/src/db/sqlite/sqlExpressions.ts
@@ -30,3 +30,7 @@ export function jsonText<T>(column: Expression<unknown>): RawBuilder<T> {
export function nowIso(): string {
return new Date().toISOString();
}
+
+export function isoMsAgo(ms: number): string {
+ return new Date(Date.now() - ms).toISOString();
+}
diff --git a/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts
new file mode 100644
index 000000000..2cd78a323
--- /dev/null
+++ b/packages/server/src/db/sqlite/token-store/SqliteOAuthTokenStore.ts
@@ -0,0 +1,39 @@
+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@truefoundry/utils/core';
+import type { Kysely } from 'kysely';
+import { fromStoredOAuthToken, toStoredOAuthToken } from '../../mcpOAuthTypes';
+import type { Database } from '../types';
+import {
+ deletePendingAuthorization,
+ getPendingAuthorization,
+ savePendingAuthorization,
+} from './queries/pendingAuthorization';
+import { deleteToken, getToken, saveToken } from './queries/token';
+
+export class SqliteOAuthTokenStore implements IOAuthTokenStore {
+ constructor(private readonly db: Kysely<Database>) {}
+
+ savePendingAuthorization(pending: OAuthPendingAuthorization): Promise<void> {
+ 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);
+ }
+
+ saveToken(params: { id: string; token: OAuthToken }): Promise<void> {
+ return saveToken(this.db, { id: params.id, token: toStoredOAuthToken(params.token) });
+ }
+
+ async getToken(params: { id: string }): Promise<OAuthToken | undefined> {
+ const stored = await getToken(this.db, params);
+ return stored === undefined ? undefined : fromStoredOAuthToken(stored);
+ }
+
+ deleteToken(params: { id: string }): Promise<void> {
+ return deleteToken(this.db, params);
+ }
+}
diff --git a/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts b/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts
new file mode 100644
index 000000000..a26fa2f62
--- /dev/null
+++ b/packages/server/src/db/sqlite/token-store/queries/pendingAuthorization.ts
@@ -0,0 +1,53 @@
+import type { OAuthPendingAuthorization } from '@truefoundry/utils/core';
+import { sql, type Kysely } from 'kysely';
+import { PENDING_AUTHORIZATION_TTL_MS, type OAuthPendingAuthorizationData } from '../../../mcpOAuthTypes';
+import { isoMsAgo, jsonbBind, jsonText, nowIso } from '../../sqlExpressions';
+import type { Database } from '../../types';
+
+export async function savePendingAuthorization(
+ db: Kysely<Database>,
+ pending: OAuthPendingAuthorization,
+): Promise<void> {
+ // `state` and `id` are their own columns; only the remainder goes in the blob.
+ const authData: OAuthPendingAuthorizationData = {
+ codeVerifier: pending.codeVerifier,
+ redirectUrl: pending.redirectUrl,
+ };
+
+ await db
+ .insertInto('oauth_pending_authorization')
+ .values({
+ id: pending.state,
+ oauth_server_id: pending.id,
+ auth_data: jsonbBind(authData),
+ created_at: nowIso(),
+ })
+ .execute();
+}
+
+export async function getPendingAuthorization(
+ 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')])
+ .where('id', '=', params.state)
+ .where('created_at', '>', isoMsAgo(PENDING_AUTHORIZATION_TTL_MS))
+ .executeTakeFirst();
+
+ if (row === undefined) {
+ return undefined;
+ }
+
+ return {
+ state: row.id,
+ id: row.oauth_server_id,
+ 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/token-store/queries/token.ts b/packages/server/src/db/sqlite/token-store/queries/token.ts
new file mode 100644
index 000000000..7c5fcd96f
--- /dev/null
+++ b/packages/server/src/db/sqlite/token-store/queries/token.ts
@@ -0,0 +1,35 @@
+import { sql, type Kysely } from 'kysely';
+import type { OAuthToken } from '../../../mcpOAuthTypes';
+import { jsonbBind, jsonText, nowIso } from '../../sqlExpressions';
+import type { Database } from '../../types';
+
+export async function saveToken(db: Kysely<Database>, params: { id: string; token: OAuthToken }): Promise<void> {
+ await db
+ .insertInto('oauth_token')
+ .values({
+ oauth_server_id: params.id,
+ token: jsonbBind(params.token),
+ updated_at: nowIso(),
+ })
+ .onConflict(oc =>
+ oc.column('oauth_server_id').doUpdateSet({
+ token: sql`excluded.token`,
+ updated_at: sql`excluded.updated_at`,
+ }),
+ )
+ .execute();
+}
+
+export async function getToken(db: Kysely<Database>, params: { id: string }): Promise<OAuthToken | undefined> {
+ const row = await db
+ .selectFrom('oauth_token')
+ .select(jsonText<OAuthToken>(sql.ref('token')).as('token'))
+ .where('oauth_server_id', '=', params.id)
+ .executeTakeFirst();
+
+ return row === undefined ? undefined : 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/types.ts b/packages/server/src/db/sqlite/types.ts
index e9712c27a..095f78c43 100644
--- a/packages/server/src/db/sqlite/types.ts
+++ b/packages/server/src/db/sqlite/types.ts
@@ -20,7 +20,7 @@ import type { ColumnType, Generated, JSONColumnType } from 'kysely';
import type { McpServerManifest } from '../../schemas/mcpServer';
import type { ProviderManifest } from '../../schemas/modelProvider';
import type { SkillManifest } from '../../schemas/skill';
-import type { McpOAuthPendingAuthorizationData, McpOAuthToken, OAuthClient, OAuthServer } from '../mcpOAuthTypes';
+import type { OAuthClient, OAuthPendingAuthorizationData, OAuthServer, OAuthToken } from '../mcpOAuthTypes';
/**
* Trace-level state for one thread at one turn (`turn_thread.checkpoint`).
@@ -200,7 +200,7 @@ export interface McpServerTable {
export interface OAuthTokenTable {
/** FK -> mcp_server.id, ON DELETE CASCADE */
oauth_server_id: string;
- token: JsonbColumn<McpOAuthToken>;
+ token: JsonbColumn<OAuthToken>;
updated_at: string;
}
@@ -212,7 +212,7 @@ export interface OAuthPendingAuthorizationTable {
/** FK -> mcp_server.id, ON DELETE CASCADE */
oauth_server_id: string;
/** { codeVerifier?, redirectUrl? } — same writer/lifecycle for both, so merged into one column */
- auth_data: JsonbColumn<McpOAuthPendingAuthorizationData>;
+ auth_data: JsonbColumn<OAuthPendingAuthorizationData>;
created_at: string;
}
diff --git a/packages/server/tests/db/oauthTokenStoreContractSuite.ts b/packages/server/tests/db/oauthTokenStoreContractSuite.ts
new file mode 100644
index 000000000..059a655d6
--- /dev/null
+++ b/packages/server/tests/db/oauthTokenStoreContractSuite.ts
@@ -0,0 +1,134 @@
+/**
+ * Backend-agnostic behavioural contract for IOAuthTokenStore.
+ * Runs under jest against a fresh store per test (see backend test files).
+ *
+ * The store's rows are FK'd to `mcp_server.id`, and pending authorizations expire on read, so
+ * each backend supplies `seedResource` (create the FK parent) and `expirePending` (backdate a
+ * pending row past its TTL).
+ */
+import type { IOAuthTokenStore, OAuthPendingAuthorization, OAuthToken } from '@truefoundry/utils/core';
+
+export interface OAuthTokenStoreHarness {
+ store: IOAuthTokenStore;
+ seedResource: (id: string) => Promise<void>;
+ expirePending: (state: string) => Promise<void>;
+}
+
+const RESOURCE_ID = 'mcp-server-1';
+const OTHER_RESOURCE_ID = 'mcp-server-2';
+
+function token(overrides: Partial<OAuthToken> = {}): OAuthToken {
+ return {
+ accessToken: 'access-1',
+ refreshToken: 'refresh-1',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ scope: 'read write',
+ ...overrides,
+ };
+}
+
+function pending(overrides: Partial<OAuthPendingAuthorization> = {}): OAuthPendingAuthorization {
+ return {
+ state: 'state-1',
+ id: RESOURCE_ID,
+ codeVerifier: 'verifier-1',
+ redirectUrl: 'https://app.example.com/done',
+ ...overrides,
+ };
+}
+
+export function runOAuthTokenStoreContractSuite(getHarness: () => OAuthTokenStoreHarness): void {
+ it('saveToken round-trips the token, including null fields', async () => {
+ const h = getHarness();
+ await h.seedResource(RESOURCE_ID);
+ const saved = token({ refreshToken: null, scope: null });
+
+ await h.store.saveToken({ id: RESOURCE_ID, token: saved });
+
+ expect(await h.store.getToken({ id: RESOURCE_ID })).toEqual(saved);
+ });
+
+ it('saveToken replaces the token for an existing resource', async () => {
+ const h = getHarness();
+ await h.seedResource(RESOURCE_ID);
+ await h.store.saveToken({ id: RESOURCE_ID, token: token() });
+
+ await h.store.saveToken({ id: RESOURCE_ID, token: token({ accessToken: 'access-2' }) });
+
+ expect(await h.store.getToken({ id: RESOURCE_ID })).toEqual(token({ accessToken: 'access-2' }));
+ });
+
+ it('getToken is undefined before save and after delete', async () => {
+ const h = getHarness();
+ await h.seedResource(RESOURCE_ID);
+ expect(await h.store.getToken({ id: RESOURCE_ID })).toBeUndefined();
+
+ await h.store.saveToken({ id: RESOURCE_ID, token: token() });
+ await h.store.deleteToken({ id: RESOURCE_ID });
+
+ expect(await h.store.getToken({ id: RESOURCE_ID })).toBeUndefined();
+ });
+
+ it('tokens are scoped per resource', async () => {
+ const h = getHarness();
+ await h.seedResource(RESOURCE_ID);
+ await h.seedResource(OTHER_RESOURCE_ID);
+ const other = token({ accessToken: 'access-other' });
+ await h.store.saveToken({ id: RESOURCE_ID, token: token() });
+ await h.store.saveToken({ id: OTHER_RESOURCE_ID, token: other });
+
+ await h.store.deleteToken({ id: RESOURCE_ID });
+
+ expect(await h.store.getToken({ id: RESOURCE_ID })).toBeUndefined();
+ expect(await h.store.getToken({ id: OTHER_RESOURCE_ID })).toEqual(other);
+ });
+
+ it('savePendingAuthorization 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);
+ });
+
+ it('getPendingAuthorization is undefined for an unknown state', async () => {
+ const h = getHarness();
+ expect(await h.store.getPendingAuthorization({ state: 'unknown' })).toBeUndefined();
+ });
+
+ it('deletePendingAuthorization 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();
+ });
+
+ it('pending authorizations are keyed by state, not by resource', async () => {
+ const h = getHarness();
+ await h.seedResource(RESOURCE_ID);
+ await h.seedResource(OTHER_RESOURCE_ID);
+ const other = pending({ state: 'state-2', id: OTHER_RESOURCE_ID, codeVerifier: 'verifier-2' });
+ await 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);
+ });
+
+ it('getPendingAuthorization 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();
+ });
+}
diff --git a/packages/server/tests/db/postgres/token-store/contract.test.ts b/packages/server/tests/db/postgres/token-store/contract.test.ts
new file mode 100644
index 000000000..af6ecc927
--- /dev/null
+++ b/packages/server/tests/db/postgres/token-store/contract.test.ts
@@ -0,0 +1,63 @@
+import { sql } from 'kysely';
+
+import { json, now } from '../../../../src/db/postgres/sqlExpressions';
+import { PostgresOAuthTokenStore } from '../../../../src/db/postgres/token-store/PostgresOAuthTokenStore';
+import type { McpServerManifest } from '../../../../src/schemas/mcpServer';
+import { runOAuthTokenStoreContractSuite, type OAuthTokenStoreHarness } from '../../oauthTokenStoreContractSuite';
+import { createPostgresTestDatabase, type PostgresTestDatabase } from '../testDatabase';
+
+const describePg = process.env['PG_STORE_TESTS_ENABLED'] === '1' ? describe : describe.skip;
+
+describePg('PostgresOAuthTokenStore (IOAuthTokenStore contract)', () => {
+ let env: PostgresTestDatabase | undefined;
+
+ beforeAll(async () => {
+ env = await createPostgresTestDatabase();
+ if (env === undefined) {
+ throw new Error('Postgres test environment unavailable despite globalSetup probe');
+ }
+ }, 120_000);
+
+ afterAll(async () => {
+ await env?.teardown();
+ });
+
+ beforeEach(async () => {
+ if (env !== undefined) {
+ await sql`TRUNCATE TABLE mcp_server, oauth_token, oauth_pending_authorization CASCADE`.execute(env.db);
+ }
+ });
+
+ runOAuthTokenStoreContractSuite((): OAuthTokenStoreHarness => {
+ if (env === undefined) {
+ throw new Error('Postgres test environment not initialized');
+ }
+ const db = env.db;
+ return {
+ store: new PostgresOAuthTokenStore(db),
+ async seedResource(id) {
+ const manifest: McpServerManifest = { type: 'remote', name: id, url: 'https://mcp.example.com/sse' };
+ await db
+ .insertInto('mcp_server')
+ .values({
+ id,
+ tenant_id: 'default',
+ name: id,
+ manifest: json(manifest),
+ oauth_server: null,
+ oauth_client: null,
+ created_at: now(),
+ updated_at: now(),
+ })
+ .execute();
+ },
+ async expirePending(state) {
+ await db
+ .updateTable('oauth_pending_authorization')
+ .set({ created_at: sql`now() - interval '1 hour'` })
+ .where('id', '=', state)
+ .execute();
+ },
+ };
+ });
+});
diff --git a/packages/server/tests/db/sqlite/token-store/contract.test.ts b/packages/server/tests/db/sqlite/token-store/contract.test.ts
new file mode 100644
index 000000000..cb4369653
--- /dev/null
+++ b/packages/server/tests/db/sqlite/token-store/contract.test.ts
@@ -0,0 +1,51 @@
+import { jsonbBind, nowIso } from '../../../../src/db/sqlite/sqlExpressions';
+import { SqliteOAuthTokenStore } from '../../../../src/db/sqlite/token-store/SqliteOAuthTokenStore';
+import type { McpServerManifest } from '../../../../src/schemas/mcpServer';
+import { runOAuthTokenStoreContractSuite, type OAuthTokenStoreHarness } from '../../oauthTokenStoreContractSuite';
+import { createSqliteTestDatabase, type SqliteTestDatabase } from '../testDatabase';
+
+describe('SqliteOAuthTokenStore (IOAuthTokenStore contract)', () => {
+ let env: SqliteTestDatabase | undefined;
+
+ beforeEach(async () => {
+ env = await createSqliteTestDatabase();
+ }, 120_000);
+
+ afterEach(async () => {
+ await env?.teardown();
+ env = undefined;
+ });
+
+ runOAuthTokenStoreContractSuite((): OAuthTokenStoreHarness => {
+ if (env === undefined) {
+ throw new Error('SQLite test database not initialized');
+ }
+ const db = env.db;
+ return {
+ store: new SqliteOAuthTokenStore(db),
+ async seedResource(id) {
+ const manifest: McpServerManifest = { type: 'remote', name: id, url: 'https://mcp.example.com/sse' };
+ await db
+ .insertInto('mcp_server')
+ .values({
+ id,
+ tenant_id: 'default',
+ name: id,
+ manifest: jsonbBind(manifest),
+ oauth_server: null,
+ oauth_client: null,
+ created_at: nowIso(),
+ updated_at: nowIso(),
+ })
+ .execute();
+ },
+ async expirePending(state) {
+ await db
+ .updateTable('oauth_pending_authorization')
+ .set({ created_at: new Date(Date.now() - 3_600_000).toISOString() })
+ .where('id', '=', state)
+ .execute();
+ },
+ };
+ });
+});