Skip to content

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

fix: move DCR remote I/O under txn (#238)

Heer Ambavia90505b844af
diff --git a/packages/server/src/apis/mcpOAuth.ts b/packages/server/src/apis/mcpOAuth.ts
index 62afd6617..7165497a9 100644
--- a/packages/server/src/apis/mcpOAuth.ts
+++ b/packages/server/src/apis/mcpOAuth.ts
@@ -1,7 +1,6 @@
import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';
import { extractErrorLogFields, McpConnectionError } from '@truefoundry/trueforge-core/core';
import type { Logger } from 'winston';
-import type { WithTransaction } from '../db/transaction';
import { completeMcpAuthorization } from '../mcp/auth/mcpDcr';
import type { IOAuthClientStore, IOAuthTokenStore, OAuthPendingAuthorization } from '../mcp/auth/types';
import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';
@@ -9,7 +8,6 @@ import { mcpOAuthCallbackRoute } from '../routes/mcpOAuthRoutes';
export interface McpOAuthRouterDeps<TTransaction> {
tokenStore: IOAuthTokenStore<TTransaction>;
mcpServerStore: IOAuthClientStore<TTransaction>;
- withTransaction: WithTransaction<TTransaction>;
logger: Logger;
}
@@ -77,7 +75,6 @@ export function createMcpOAuthRouter<TTransaction>(deps: McpOAuthRouterDeps<TTra
await completeMcpAuthorization({
tokenStore: deps.tokenStore,
mcpServerStore: deps.mcpServerStore,
- withTransaction: deps.withTransaction,
pending,
code,
});
diff --git a/packages/server/src/apis/mcpServers.ts b/packages/server/src/apis/mcpServers.ts
index 8fee16d88..5d9aac53e 100644
--- a/packages/server/src/apis/mcpServers.ts
+++ b/packages/server/src/apis/mcpServers.ts
@@ -11,7 +11,7 @@ import type { IOAuthTokenStore, OAuthClientRecord, OAuthToken } from '../mcp/aut
import {
authorizeMcpServerRoute,
createMcpServerRoute,
- deleteMcpServerAuthRoute,
+ deleteAuthorizeMcpServerRoute,
getMcpServerRoute,
listAvailableMcpServersRoute,
listMcpServersRoute,
@@ -24,14 +24,6 @@ import { resolveMcpAuthStatus } from '../schemas/mcpServer';
import { MissingStoredSecretError, resolveStoredSecretValue, toRedactedSecretValue } from '../utils/secretRedaction';
import { TENANT_ID } from './sessions';
-export interface SettingsMcpServersRouterDeps<TTransaction> {
- mcpServerStore: IMcpServerStore<TTransaction>;
- tokenStore: IOAuthTokenStore<TTransaction>;
- withTransaction: WithTransaction<TTransaction>;
- logger: Logger;
- resolveUserContext: ResolveUserContext;
-}
-
export interface McpServersRouterDeps<TTransaction> {
mcpServerStore: IMcpServerStore<TTransaction>;
tokenStore: IOAuthTokenStore<TTransaction>;
@@ -136,7 +128,7 @@ function toMcpServerReadEntry({
}
/** Admin/settings MCP CRUD (mounted at /api/v1/settings/mcp-servers). */
-export function createSettingsMcpServersRouter<TTransaction>(deps: SettingsMcpServersRouterDeps<TTransaction>) {
+export function createSettingsMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<TTransaction>) {
const listHandler: RouteHandler<typeof listMcpServersRoute> = async c => {
const userRef = deps.resolveUserContext(c).userRef;
const records = await deps.mcpServerStore.listServers({ tenant_id: TENANT_ID, names: undefined });
@@ -166,7 +158,7 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: SettingsMcpSe
const createHandler: RouteHandler<typeof createMcpServerRoute> = async c => {
const incomingManifest: McpServerManifest = c.req.valid('json');
- // DCR must finish before the txn (remote I/O cannot run inside withTransaction).
+ // DCR finishes before the txn (remote I/O stays out of withTransaction on create).
let dcrClientToSave: OAuthClientRecord | undefined;
if (incomingManifest.auth?.type === 'dcr') {
try {
@@ -188,7 +180,6 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: SettingsMcpSe
let manifest: McpServerManifest;
try {
- // Create has no prior row; redacted header keep resolves to MissingStoredSecretError → 400.
manifest = resolveMcpServerManifestForWrite({
incoming: incomingManifest,
existing: undefined,
@@ -228,45 +219,13 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: SettingsMcpSe
const putHandler: RouteHandler<typeof putMcpServerRoute> = async c => {
const userRef = deps.resolveUserContext(c).userRef;
const incomingManifest: McpServerManifest = c.req.valid('json');
- // Unlocked snapshot only for pre-txn DCR HTTP (remote I/O cannot run inside withTransaction).
- // Header secret keep/rotate is re-resolved under getServerForUpdate inside the txn below.
- const prior = await deps.mcpServerStore.getServer({ tenant_id: TENANT_ID, name: incomingManifest.name });
-
- // DCR HTTP must finish before the txn so a failed registration never leaves a half-written row
- // (txn cannot roll back the AS, and AGENTS forbids remote I/O inside withTransaction).
- // Per-request OAuth timeouts live on mcpOAuthFetch (MCP_OAUTH_HTTP_TIMEOUT_MS) — no outer
- // withTimeout, so hung AS failures surface as TimeoutError with the intended message.
- let dcrClientToSave: OAuthClientRecord | undefined;
- if (incomingManifest.auth?.type === 'dcr') {
- const existingClient = prior !== undefined ? await deps.mcpServerStore.getClient({ id: prior.id }) : undefined;
- // Register when: brand-new server, client was cleared (e.g. invalid_client), or MCP URL changed
- // (resource/AS may differ; reuse would keep stale oauth_server/client for the old AS).
- // TODO: make manifest URL immutable after create so re-DCR / stale OAuth tokens are not possible via PUT.
- const urlChanged = prior !== undefined && prior.manifest.url !== incomingManifest.url;
- const needsDcr = existingClient === undefined || urlChanged;
- if (needsDcr) {
- try {
- dcrClientToSave = await createMcpOAuthClient({
- mcpServerUrl: incomingManifest.url,
- mcpServerName: incomingManifest.name,
- redirectUri: mcpOAuthCallbackUrl(),
- clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
- });
- } catch (error) {
- deps.logger.error(
- `DCR client registration failed for "${incomingManifest.name}"; rejecting upsert`,
- extractErrorLogFields(error),
- );
- const message =
- error instanceof Error ? error.message : 'Failed to register OAuth client for this MCP server';
- return c.json({ error: { message } }, 422);
- }
- }
- }
try {
- // Lock → resolve secrets from that snapshot → upsert, all in one txn so concurrent keep
- // cannot re-write a secret over a rotate that committed in between.
+ // Lock → resolve secrets → DCR (if needed) → upsert + saveClient in one txn.
+ // Exception: MCP put may run `createMcpOAuthClient` inside the write txn that persists
+ // `oauth_server`/`oauth_client` so a failed registration rolls back the server write.
+ // Bounded by `MCP_OAUTH_HTTP_TIMEOUT_MS` (15s);
+ // must stay under `POSTGRES_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS` (30s).
const record = await deps.withTransaction(async transaction => {
const existing = await deps.mcpServerStore.getServerForUpdate(
{ tenant_id: TENANT_ID, name: incomingManifest.name },
@@ -276,6 +235,27 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: SettingsMcpSe
incoming: incomingManifest,
existing: existing?.manifest,
});
+
+ let dcrClientToSave: OAuthClientRecord | undefined;
+ if (manifest.auth?.type === 'dcr') {
+ const existingClient = existing
+ ? await deps.mcpServerStore.getClient({ id: existing.id }, transaction)
+ : undefined;
+ // Register when: brand-new server, client was cleared (e.g. invalid_client), or MCP URL changed
+ // (resource/AS may differ; reuse would keep stale oauth_server/client for the old AS).
+ // TODO: make manifest URL immutable after create so re-DCR / stale OAuth tokens are not possible via PUT.
+ const urlChanged = existing && existing.manifest.url !== manifest.url;
+ const needsDcr = existingClient === undefined || urlChanged;
+ if (needsDcr) {
+ dcrClientToSave = await createMcpOAuthClient({
+ mcpServerUrl: manifest.url,
+ mcpServerName: manifest.name,
+ redirectUri: mcpOAuthCallbackUrl(),
+ clientName: configuration.MCP_DCR_OAUTH_CLIENT_NAME,
+ });
+ }
+ }
+
const saved = await deps.mcpServerStore.upsertServer(
{
tenant_id: TENANT_ID,
@@ -301,6 +281,13 @@ export function createSettingsMcpServersRouter<TTransaction>(deps: SettingsMcpSe
if (error instanceof MissingStoredSecretError) {
return c.json({ error: { message: 'Header secret is required' } }, 400);
}
+ if (error instanceof McpConnectionError) {
+ deps.logger.error(
+ `DCR client registration failed for "${incomingManifest.name}"; rejecting upsert`,
+ extractErrorLogFields(error),
+ );
+ return c.json({ error: { message: error.message } }, 422);
+ }
throw error;
}
};
@@ -379,6 +366,8 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
validateRedirectUris({ redirectUris: [redirectUrl] });
}
// Reuses a usable/refreshable token when present; only builds an auth URL when needed.
+ // Client is usually already registered at create/put; concurrent Connect races are harmless
+ // (last saveClient wins; rare orphan AS registration).
const result = await resolveMcpAuth({
tokenStore: deps.tokenStore,
mcpServerStore: deps.mcpServerStore,
@@ -412,7 +401,7 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
}
};
- const deleteAuthHandler: RouteHandler<typeof deleteMcpServerAuthRoute> = async c => {
+ const deleteAuthorizeHandler: RouteHandler<typeof deleteAuthorizeMcpServerRoute> = async c => {
const { name } = c.req.valid('param');
const userRef = deps.resolveUserContext(c).userRef;
const record = await deps.mcpServerStore.getServer({ tenant_id: TENANT_ID, name });
@@ -441,6 +430,6 @@ export function createMcpServersRouter<TTransaction>(deps: McpServersRouterDeps<
);
});
router.openapi(authorizeMcpServerRoute, authorizeHandler);
- router.openapi(deleteMcpServerAuthRoute, deleteAuthHandler);
+ router.openapi(deleteAuthorizeMcpServerRoute, deleteAuthorizeHandler);
return router;
}
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 2c647ba8b..7441a3616 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -191,7 +191,6 @@ export function createServerApp<TTransaction>(deps: ServerDeps<TTransaction>) {
createMcpOAuthRouter({
tokenStore: deps.tokenStore,
mcpServerStore: deps.mcpServerStore,
- withTransaction: deps.withTransaction,
logger: deps.logger,
}),
);
diff --git a/packages/server/src/mcp/auth/mcpDcr.ts b/packages/server/src/mcp/auth/mcpDcr.ts
index 5324f3cf5..6b87c2258 100644
--- a/packages/server/src/mcp/auth/mcpDcr.ts
+++ b/packages/server/src/mcp/auth/mcpDcr.ts
@@ -15,7 +15,6 @@ import type {
import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
import { McpConnectionError, McpDcrConfigurationError } from '@truefoundry/trueforge-core/core';
import { randomBytes } from 'node:crypto';
-import type { WithTransaction } from '../../db/transaction';
import {
isOAuthAccessTokenUsable,
mcpAuthorizationServerMetadata,
@@ -122,6 +121,11 @@ async function registerMcpClientWithAuthMethodFallback(params: {
};
}
+/**
+ * Discovers the MCP server's authorization server, validates DCR + S256 PKCE support, and
+ * registers a new OAuth client (RFC 7591). Returns AS endpoints + client credentials for the
+ * caller to persist; does not write to the store.
+ */
export async function createMcpOAuthClient(params: {
mcpServerUrl: string;
mcpServerName: string;
@@ -171,6 +175,10 @@ export async function createMcpOAuthClient(params: {
});
}
+/**
+ * Returns the stored OAuth client for `serverId`, or discovers + DCR-registers and persists one.
+ * Used from `resolveMcpAuth` only — callers that already hold the client should pass it through.
+ */
export async function ensureMcpClientRegistered(params: {
mcpServerStore: IOAuthClientStore;
serverId: string;
@@ -182,7 +190,6 @@ export async function ensureMcpClientRegistered(params: {
if (existing) {
return existing;
}
- // Remote DCR finishes before any DB write so we never hold a connection during HTTP.
const client = await createMcpOAuthClient({
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
@@ -193,30 +200,23 @@ export async function ensureMcpClientRegistered(params: {
return client;
}
+/** Builds the AS authorize URL and saves the pending PKCE row. Caller must already have `client`. */
export async function buildMcpAuthorizationUrl(params: {
tokenStore: IOAuthTokenStore;
- mcpServerStore: IOAuthClientStore;
+ client: OAuthClientRecord;
serverId: string;
userRef: string;
mcpServerUrl: string;
mcpServerName: string;
- clientName: string;
redirectUrl?: string;
}): Promise<URL> {
- const client = await ensureMcpClientRegistered({
- mcpServerStore: params.mcpServerStore,
- serverId: params.serverId,
- mcpServerUrl: params.mcpServerUrl,
- mcpServerName: params.mcpServerName,
- clientName: params.clientName,
- });
const state = randomBytes(32).toString('base64url');
const redirectUri = mcpOAuthCallbackUrl();
let started: Awaited<ReturnType<typeof startAuthorization>>;
try {
- started = await startAuthorization(mcpAuthorizationServerOrigin(client.server), {
- metadata: mcpAuthorizationServerMetadata(client.server),
- clientInformation: mcpClientInformation(client.client),
+ started = await startAuthorization(mcpAuthorizationServerOrigin(params.client.server), {
+ metadata: mcpAuthorizationServerMetadata(params.client.server),
+ clientInformation: mcpClientInformation(params.client.client),
redirectUrl: redirectUri,
resource: resourceUrlFromServerUrl(params.mcpServerUrl),
state,
@@ -253,23 +253,27 @@ export async function resolveMcpAuth(params: {
if (token && isOAuthAccessTokenUsable(token.expiresAt, nowMs)) {
return { headers: { Authorization: `Bearer ${token.accessToken}` } };
}
+ const client = await ensureMcpClientRegistered({
+ mcpServerStore: params.mcpServerStore,
+ serverId: params.serverId,
+ mcpServerUrl: params.mcpServerUrl,
+ mcpServerName: params.mcpServerName,
+ clientName: params.clientName,
+ });
if (token?.refreshToken) {
- const client = await params.mcpServerStore.getClient({ id: params.serverId });
- if (client) {
- try {
- const refreshed = await refreshAuthorization(mcpAuthorizationServerOrigin(client.server), {
- metadata: mcpAuthorizationServerMetadata(client.server),
- clientInformation: mcpClientInformation(client.client),
- refreshToken: token.refreshToken,
- resource: resourceUrlFromServerUrl(params.mcpServerUrl),
- fetchFn: mcpOAuthFetch,
- });
- const saved = oauthTokensToOAuthToken(refreshed, nowMs, token.refreshToken);
- await params.tokenStore.saveToken({ ...tokenKey, token: saved });
- return { headers: { Authorization: `Bearer ${saved.accessToken}` } };
- } catch {
- // Refresh failure falls through to a fresh authorization.
- }
+ try {
+ const refreshed = await refreshAuthorization(mcpAuthorizationServerOrigin(client.server), {
+ metadata: mcpAuthorizationServerMetadata(client.server),
+ clientInformation: mcpClientInformation(client.client),
+ refreshToken: token.refreshToken,
+ resource: resourceUrlFromServerUrl(params.mcpServerUrl),
+ fetchFn: mcpOAuthFetch,
+ });
+ const saved = oauthTokensToOAuthToken(refreshed, nowMs, token.refreshToken);
+ await params.tokenStore.saveToken({ ...tokenKey, token: saved });
+ return { headers: { Authorization: `Bearer ${saved.accessToken}` } };
+ } catch {
+ // Refresh failure falls through to a fresh authorization.
}
}
if (token) {
@@ -277,12 +281,11 @@ export async function resolveMcpAuth(params: {
}
const authUrl = await buildMcpAuthorizationUrl({
tokenStore: params.tokenStore,
- mcpServerStore: params.mcpServerStore,
+ client,
serverId: params.serverId,
userRef: params.userRef,
mcpServerUrl: params.mcpServerUrl,
mcpServerName: params.mcpServerName,
- clientName: params.clientName,
...(params.redirectUrl !== undefined ? { redirectUrl: params.redirectUrl } : {}),
});
return { authUrl };
@@ -292,12 +295,11 @@ export async function resolveMcpAuth(params: {
* Exchanges `code` for tokens against an already-claimed `pending` row: the caller claims it with
* `consumePendingAuthorization` so duplicate callbacks lose the race, and keeps it for its FE
* landing URL. Route must already reject IdP `error` params. On `invalid_client`, clears the stored
- * client and token so the next authorize re-registers.
+ * client so the next authorize re-registers (per-user tokens are left; there is usually none yet).
*/
export async function completeMcpAuthorization<TTransaction>(params: {
tokenStore: IOAuthTokenStore<TTransaction>;
mcpServerStore: IOAuthClientStore<TTransaction>;
- withTransaction: WithTransaction<TTransaction>;
pending: OAuthPendingAuthorization;
code: string;
}): Promise<void> {
@@ -327,10 +329,7 @@ export async function completeMcpAuthorization<TTransaction>(params: {
});
} catch (error: unknown) {
if (error instanceof InvalidClientError) {
- await params.withTransaction(async transaction => {
- await params.tokenStore.deleteToken({ id: pending.id, userRef: pending.userRef }, transaction);
- await params.mcpServerStore.deleteClient({ id: pending.id }, transaction);
- });
+ await params.mcpServerStore.deleteClient({ id: pending.id });
throw new McpConnectionError('OAuth client registration is invalid; please retry connecting', 400, {
cause: error,
});
diff --git a/packages/server/src/routes/mcpServerRoutes.ts b/packages/server/src/routes/mcpServerRoutes.ts
index 670274cbc..090189d23 100644
--- a/packages/server/src/routes/mcpServerRoutes.ts
+++ b/packages/server/src/routes/mcpServerRoutes.ts
@@ -254,7 +254,7 @@ export const authorizeMcpServerRoute = createRoute({
},
});
-export const deleteMcpServerAuthRoute = createRoute({
+export const deleteAuthorizeMcpServerRoute = createRoute({
method: 'delete',
path: '/{name}/authorize',
tags: [MCP_SERVERS_TAG],
diff --git a/packages/server/tests/unit/apis/mcpOAuth.test.ts b/packages/server/tests/unit/apis/mcpOAuth.test.ts
index c7fc47d2f..6e2a5eea6 100644
--- a/packages/server/tests/unit/apis/mcpOAuth.test.ts
+++ b/packages/server/tests/unit/apis/mcpOAuth.test.ts
@@ -104,7 +104,6 @@ describe('MCP OAuth authorize + callback', () => {
oauthRouter = createMcpOAuthRouter({
tokenStore,
mcpServerStore,
- withTransaction,
logger,
});
});
diff --git a/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts b/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts
index 56c792a23..b450d4ce2 100644
--- a/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts
+++ b/packages/server/tests/unit/mcp/auth/mcpOAuth.test.ts
@@ -30,8 +30,6 @@ function newStores(): Stores {
return { tokenStore: new InMemoryOAuthTokenStore(), mcpServerStore: new InMemoryOAuthClientStore() };
}
-const withNoTransaction = <T>(callback: (transaction: undefined) => Promise<T>) => callback(undefined);
-
const CLIENT_NAME = 'harness';
const SERVER_URL = 'https://mcp.example.com/sse';
const AS_ORIGIN = 'https://auth.example.com';
@@ -303,18 +301,16 @@ describe('createMcpOAuthClient / ensureMcpClientRegistered', () => {
describe('buildMcpAuthorizationUrl', () => {
it('saves pending authorization with PKCE when the AS advertises S256', async () => {
- const { tokenStore, mcpServerStore } = newStores();
- await mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });
+ const { tokenStore } = newStores();
stubOauthFetch({});
const authUrl = await buildMcpAuthorizationUrl({
tokenStore,
- mcpServerStore,
+ client: sampleClient,
serverId: SERVER_ID,
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
- clientName: CLIENT_NAME,
redirectUrl: 'https://app.example.com/after',
});
@@ -340,23 +336,19 @@ describe('buildMcpAuthorizationUrl', () => {
});
it('still uses PKCE S256 when the AS does not advertise code_challenge_methods', async () => {
- const { tokenStore, mcpServerStore } = newStores();
- await mcpServerStore.saveClient({
- id: SERVER_ID,
- record: {
- ...sampleClient,
- server: { ...sampleClient.server, codeChallengeMethodsSupported: null },
- },
- });
+ const { tokenStore } = newStores();
+ const client: OAuthClientRecord = {
+ ...sampleClient,
+ server: { ...sampleClient.server, codeChallengeMethodsSupported: null },
+ };
const authUrl = await buildMcpAuthorizationUrl({
tokenStore,
- mcpServerStore,
+ client,
serverId: SERVER_ID,
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
- clientName: CLIENT_NAME,
});
expect(authUrl.searchParams.get('code_challenge_method')).toBe('S256');
@@ -380,24 +372,20 @@ describe('buildMcpAuthorizationUrl', () => {
});
it('throws when stored client metadata lists only non-S256 methods', async () => {
- const { tokenStore, mcpServerStore } = newStores();
- await mcpServerStore.saveClient({
- id: SERVER_ID,
- record: {
- ...sampleClient,
- server: { ...sampleClient.server, codeChallengeMethodsSupported: ['plain'] },
- },
- });
+ const { tokenStore } = newStores();
+ const client: OAuthClientRecord = {
+ ...sampleClient,
+ server: { ...sampleClient.server, codeChallengeMethodsSupported: ['plain'] },
+ };
await expect(
buildMcpAuthorizationUrl({
tokenStore,
- mcpServerStore,
+ client,
serverId: SERVER_ID,
userRef: USER_REF,
mcpServerUrl: SERVER_URL,
mcpServerName: SERVER_NAME,
- clientName: CLIENT_NAME,
}),
).rejects.toMatchObject({
name: 'McpConnectionError',
@@ -622,7 +610,12 @@ describe('completeMcpAuthorization', () => {
await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });
const authUrl = await buildMcpAuthorizationUrl({
- ...resolveParams(stores),
+ tokenStore: stores.tokenStore,
+ client: sampleClient,
+ serverId: SERVER_ID,
+ userRef: USER_REF,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
redirectUrl: 'https://app.example.com/connected',
});
const state = authUrl.searchParams.get('state')!;
@@ -646,7 +639,6 @@ describe('completeMcpAuthorization', () => {
await completeMcpAuthorization({
tokenStore: stores.tokenStore,
mcpServerStore: stores.mcpServerStore,
- withTransaction: withNoTransaction,
pending,
code: 'auth-code-1',
});
@@ -674,7 +666,6 @@ describe('completeMcpAuthorization', () => {
completeMcpAuthorization({
tokenStore: stores.tokenStore,
mcpServerStore: stores.mcpServerStore,
- withTransaction: withNoTransaction,
pending: {
state: 'state-1',
id: SERVER_ID,
@@ -693,17 +684,15 @@ describe('completeMcpAuthorization', () => {
it('clears client state on invalid_client and surfaces a re-connect error', async () => {
const stores = newStores();
- const deleteToken = jest.spyOn(stores.tokenStore, 'deleteToken');
const deleteClient = jest.spyOn(stores.mcpServerStore, 'deleteClient');
- const transaction = {};
- let withTransactionCalls = 0;
- const withTransaction = <T>(callback: (transaction: object) => Promise<T>) => {
- withTransactionCalls += 1;
- return callback(transaction);
- };
await stores.mcpServerStore.saveClient({ id: SERVER_ID, record: sampleClient });
const authUrl = await buildMcpAuthorizationUrl({
- ...resolveParams(stores),
+ tokenStore: stores.tokenStore,
+ client: sampleClient,
+ serverId: SERVER_ID,
+ userRef: USER_REF,
+ mcpServerUrl: SERVER_URL,
+ mcpServerName: SERVER_NAME,
redirectUrl: 'https://app.example.com/after',
});
const state = authUrl.searchParams.get('state')!;
@@ -725,7 +714,6 @@ describe('completeMcpAuthorization', () => {
completeMcpAuthorization({
tokenStore: stores.tokenStore,
mcpServerStore: stores.mcpServerStore,
- withTransaction,
pending,
code: 'auth-code-1',
}),
@@ -733,11 +721,8 @@ describe('completeMcpAuthorization', () => {
name: 'McpConnectionError',
message: expect.stringContaining('registration is invalid'),
});
- expect(withTransactionCalls).toBe(1);
- expect(deleteToken).toHaveBeenCalledWith({ id: SERVER_ID, userRef: USER_REF }, transaction);
- expect(deleteClient).toHaveBeenCalledWith({ id: SERVER_ID }, transaction);
+ expect(deleteClient).toHaveBeenCalledWith({ id: SERVER_ID });
expect(await stores.mcpServerStore.getClient({ id: SERVER_ID })).toBeUndefined();
- expect(await stores.tokenStore.getToken({ id: SERVER_ID, userRef: USER_REF })).toBeUndefined();
});
});