diff --git a/packages/api/src/connections/custom/custom-mcp.ts b/packages/api/src/connections/custom/custom-mcp.ts index bca912a8..7080c681 100644 --- a/packages/api/src/connections/custom/custom-mcp.ts +++ b/packages/api/src/connections/custom/custom-mcp.ts @@ -8,7 +8,7 @@ import {readStoredJson} from '../../utils/stored-json'; import {callMcpTool, listMcpTools} from '../mcp/mcp-client'; import {noAuthSchema, oauthAuthSchema, tokenAuthSchema} from '../mcp/mcp-credential'; import {mcpEndpointsSchema, type McpEndpoint, type McpServer} from '../mcp/mcp-oauth'; -import {withMcpSignIn} from '../mcp/mcp-session'; +import {withMcpCredential} from '../mcp/mcp-session'; /** * A custom MCP server, by its address: connected with no sign-in where the server asks for none, @@ -70,7 +70,7 @@ function withCustomServer(connection: StoredConnection, use: (server: McpEndp return $(await use(customEndpoint(credential.url), credential.token)); } const server = customServer(credential); - return $(await withMcpSignIn(server, connection, customSignInSchema, (accessToken) => use(server, accessToken))); + return $(await withMcpCredential(server, connection, customSignInSchema, (accessToken) => use(server, accessToken))); }); } diff --git a/packages/api/src/connections/custom/route.ts b/packages/api/src/connections/custom/route.ts index dc61cc46..a663394d 100644 --- a/packages/api/src/connections/custom/route.ts +++ b/packages/api/src/connections/custom/route.ts @@ -4,11 +4,11 @@ import {z} from 'zod'; import {ApiErr, type ApiError, Do, parseSchema} from '@proxy/utils'; import {findAccountConnection} from '@proxy/db/connection'; -import {type Connection, connectMcpBodySchema, type connectMcpSchema, type CustomMcpServer, editMcpServerBodySchema} from '@proxy/contracts/connections'; +import {type Connection, connectMcpBodySchema, type connectMcpSchema, type CustomMcpServer, editMcpServerBodySchema, type ReturnTo} from '@proxy/contracts/connections'; import type {AuthenticatedRequest} from '../../server/middleware/require-auth'; import {sendResult} from '../../server/response'; -import {requireViewer} from '../../utils/user-org'; +import {requireViewer, type OrgViewer} from '../../utils/user-org'; import {builtInForHost} from '../built-in-mcp'; import {respond} from '../connection-response'; import {saveConnection, signInFlow, type SignInRequest} from '../connect-flow'; @@ -66,7 +66,37 @@ const {beginSignIn, handleCallback: handleCustomMcpCallbackRoute} = signInFlow({ export {handleCustomMcpCallbackRoute}; -function connectCustomMcp(request: AuthenticatedRequest, res: Response): Promise, ApiError>> { +type ConnectMcpAnswer = z.infer; + +// Where a custom server connected at an address goes: a new connection, named and maybe shared, or +// one moved to it on its page, which keeps its own name and is the one its sign-in renews +// (`fromConnection` in connect-flow.ts). +type Destination = {kind: 'new'; name: string; shared: boolean; returnTo: ReturnTo | undefined} | {kind: 'moved'; connectionId: string}; + +// The server at `url` asked for its tools, with the token where there is one, and the connection +// saved; or, where the server asks for a sign-in, the sign-in begun, which comes back to the +// callback above. +function connectServer(res: Response, viewer: OrgViewer, at: {url: URL; token: string | null; desktop: boolean}, destination: Destination): Promise> { + return Do(async ($) => { + const {url, token, desktop} = at; + const probe = $(await probeMcpServer(url, token)); + if (probe.kind === 'signIn') { + const server = $(await discoverMcpServer(url)); + const kept = destination.kind === 'new' ? {name: destination.name} : {edit: true as const}; + const start = (signIn: SignInRequest) => startMcpSignIn(server, signIn, {server: mcpEndpoints(server), ...kept}); + const back = destination.kind === 'new' ? {returnTo: destination.returnTo, shared: destination.shared} : {returnTo: undefined, connectionId: destination.connectionId}; + return {kind: 'signIn' as const, url: $(await beginSignIn(res, {viewer, desktop, account: null, start, ...back}))}; + } + const credential: CustomCredential = token === null ? {auth: 'none', url: url.toString()} : {auth: 'token', url: url.toString(), token}; + const found = {account: mcpAccount(url), credential, defaults: readOnlyToolNames(probe.tools), tools: probe.tools}; + const connected = destination.kind === 'new' ? {...found, name: destination.name} : {...found, fromConnection: true as const}; + const options = destination.kind === 'new' ? {shared: destination.shared} : {connectionId: destination.connectionId}; + const {row} = $(await saveConnection(viewer, 'mcp', connected, options)); + return {kind: 'connected' as const, connection: $(await respond({...row, credential: JSON.stringify(credential)}))}; + }); +} + +function connectCustomMcp(request: AuthenticatedRequest, res: Response): Promise> { return Do(async ($) => { const body = $(parseSchema(connectMcpBodySchema, request.body)); const url = $(await parseMcpServerUrl(body.url)); @@ -89,15 +119,7 @@ function connectCustomMcp(request: AuthenticatedRequest, res: Response): Promise if (builtIn) { return {kind: 'signIn' as const, url: $(await beginBuiltInSignIn(builtIn, res, {viewer, returnTo: body.returnTo, desktop, name: body.name, shared}))}; } - const probe = $(await probeMcpServer(url, token)); - if (probe.kind === 'signIn') { - const server = $(await discoverMcpServer(url)); - const start = (signIn: SignInRequest) => startMcpSignIn(server, signIn, {server: mcpEndpoints(server), name: body.name}); - return {kind: 'signIn' as const, url: $(await beginSignIn(res, {viewer, returnTo: body.returnTo, desktop, account: null, shared, start}))}; - } - const credential: CustomCredential = token === null ? {auth: 'none', url: url.toString()} : {auth: 'token', url: url.toString(), token}; - const {row} = $(await saveConnection(viewer, 'mcp', {account: mcpAccount(url), credential, defaults: readOnlyToolNames(probe.tools), tools: probe.tools, name: body.name}, {shared})); - return {kind: 'connected' as const, connection: $(await respond({...row, credential: JSON.stringify(credential)}))}; + return $(await connectServer(res, viewer, {url, token, desktop}, {kind: 'new', name: body.name, shared, returnTo: body.returnTo})); }); } @@ -143,7 +165,7 @@ function keptToken(current: CustomCredential, url: URL): Result, ApiError>> { +function editCustomMcp(request: AuthenticatedRequest, res: Response): Promise> { return Do(async ($) => { const body = $(parseSchema(editMcpServerBodySchema, request.body)); const viewer = $(await requireViewer(request)); @@ -162,17 +184,7 @@ function editCustomMcp(request: AuthenticatedRequest, res: Response): Promise startMcpSignIn(server, signIn, {server: mcpEndpoints(server), edit: true as const}); - const desktop = body.desktop ?? false; - return {kind: 'signIn' as const, url: $(await beginSignIn(res, {viewer, returnTo: undefined, desktop, account: null, connectionId: row.id, start}))}; - } - const credential: CustomCredential = token === null ? {auth: 'none', url: url.toString()} : {auth: 'token', url: url.toString(), token}; - const connected = {account, credential, defaults: readOnlyToolNames(probe.tools), tools: probe.tools, fromConnection: true as const}; - const saved = $(await saveConnection(viewer, 'mcp', connected, {connectionId: row.id})); - return {kind: 'connected' as const, connection: $(await respond({...saved.row, credential: JSON.stringify(credential)}))}; + return $(await connectServer(res, viewer, {url, token, desktop: body.desktop ?? false}, {kind: 'moved', connectionId: row.id})); }); } diff --git a/packages/api/src/connections/mcp/mcp-credential.ts b/packages/api/src/connections/mcp/mcp-credential.ts index 89f355d7..8792d0be 100644 --- a/packages/api/src/connections/mcp/mcp-credential.ts +++ b/packages/api/src/connections/mcp/mcp-credential.ts @@ -23,13 +23,3 @@ export const builtInCredentialSchema = z.discriminatedUnion('auth', [tokenAuthSc export type BuiltInCredential = z.infer; export type OAuthCredential = z.infer; - -// Before every MCP credential said how it signs in, an integration built in stored a key as -// `{auth: 'key', key}` and a sign-in's tokens bare. Read as they are now until the data migration -// `unify-mcp-credentials` has rewritten them, on every instance; it, and these, can then go. -const legacyKeySchema = z.object({auth: z.literal('key'), key: z.string()}).transform(({key}): BuiltInCredential => ({auth: 'token', token: key})); - -const legacyTokensSchema = mcpTokensSchema.transform((tokens): BuiltInCredential => ({auth: 'oauth', ...tokens})); - -/** A built-in integration's credential as stored, in the shape it has now or the one it had before. */ -export const storedBuiltInCredentialSchema = z.union([builtInCredentialSchema, legacyKeySchema, legacyTokensSchema]); diff --git a/packages/api/src/connections/mcp/mcp-session.test.ts b/packages/api/src/connections/mcp/mcp-session.test.ts index 745150b3..bc372cf2 100644 --- a/packages/api/src/connections/mcp/mcp-session.test.ts +++ b/packages/api/src/connections/mcp/mcp-session.test.ts @@ -74,16 +74,6 @@ describe('callMcpToolFor', () => { expect(updateConnectionCredential).toHaveBeenCalledWith({connectionId: 'conn-1', credential: `enc:${JSON.stringify({auth: 'oauth', ...fresh})}`, previous: connection.credential}); }); - test('tokens stored bare, as before every MCP credential said how it signs in, are read, and saved in the shape they have now', async () => { - const {callMcpToolFor} = await import('./mcp-session'); - const bare = {clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: new Date(Date.now() + 10_000).toISOString()}; - const connection = {id: 'conn-1', credential: `enc:${JSON.stringify(bare)}`}; - await callMcpToolFor(SERVER, connection, 'list_meetings', {}); - - expect(refreshMcpTokens).toHaveBeenCalledWith(SERVER, {auth: 'oauth', ...bare}); - expect(updateConnectionCredential.mock.calls[0]?.[0]).toMatchObject({credential: `enc:${JSON.stringify({auth: 'oauth', ...fresh})}`}); - }); - test('calls at once on a running-out token share one refresh', async () => { const {callMcpToolFor} = await import('./mcp-session'); const connection = connectionWith(new Date(Date.now() + 10_000).toISOString()); @@ -104,7 +94,7 @@ describe('callMcpToolFor', () => { }); test('a custom server’s sign-in keeps its address beside the new tokens', async () => { - const {withMcpSignIn} = await import('./mcp-session'); + const {withMcpCredential} = await import('./mcp-session'); const {oauthAuthSchema} = await import('./mcp-credential'); const credential = { auth: 'oauth', @@ -115,7 +105,7 @@ describe('callMcpToolFor', () => { expiresAt: new Date(Date.now() + 10_000).toISOString(), }; const connection = {id: 'conn-1', credential: `enc:${JSON.stringify(credential)}`}; - await withMcpSignIn(SERVER, connection, oauthAuthSchema.extend({url: z.string()}), (accessToken) => callMcpTool(SERVER, accessToken, 'search', {})); + await withMcpCredential(SERVER, connection, oauthAuthSchema.extend({url: z.string()}), (accessToken) => callMcpTool(SERVER, accessToken, 'search', {})); const saved = updateConnectionCredential.mock.calls[0]?.[0] as {credential: string}; expect(JSON.parse(saved.credential.replace(/^enc:/, ''))).toEqual({auth: 'oauth', url: 'https://mcp.example.com/mcp', ...fresh}); @@ -134,13 +124,6 @@ describe('callMcpToolFor', () => { describe('callMcpToolFor with an API key', () => { const connection = {id: 'conn-2', credential: `enc:${JSON.stringify({auth: 'token', token: 'exa-key-1'})}`}; - test('a key stored as before, `{auth: "key"}`, is sent as it is', async () => { - const {callMcpToolFor} = await import('./mcp-session'); - const legacy = {id: 'conn-2', credential: `enc:${JSON.stringify({auth: 'key', key: 'exa-key-1'})}`}; - expect((await callMcpToolFor(SERVER, legacy, 'web_search_exa', {})).unwrap()).toBe('answer'); - expect(callMcpTool).toHaveBeenCalledWith(SERVER, 'exa-key-1', 'web_search_exa', {}); - }); - test('sends the key as the token, and never refreshes it', async () => { const {callMcpToolFor} = await import('./mcp-session'); const text = (await callMcpToolFor(SERVER, connection, 'web_search_exa', {query: 'bun'})).unwrap(); diff --git a/packages/api/src/connections/mcp/mcp-session.ts b/packages/api/src/connections/mcp/mcp-session.ts index c899c813..fa2c0166 100644 --- a/packages/api/src/connections/mcp/mcp-session.ts +++ b/packages/api/src/connections/mcp/mcp-session.ts @@ -5,21 +5,19 @@ import {ApiErr, type ApiError} from '@proxy/utils'; import {callWithToken, type TokenRefresher} from '../token-session'; import {callMcpTool} from './mcp-client'; -import {storedBuiltInCredentialSchema, type BuiltInCredential, type OAuthCredential} from './mcp-credential'; +import {builtInCredentialSchema, type BuiltInCredential, type OAuthCredential} from './mcp-credential'; import {isExpiring, refreshMcpTokens, type McpServer} from './mcp-oauth'; type StoredConnection = {id: string; credential: string | null}; -// A credential the session can send: a token or key, or a sign-in's, with whatever else it holds +// A credential the session sends is a token or key, or a sign-in's, with whatever else it holds // beside them, as a custom server's address and endpoints, kept as it is when the tokens are replaced. -type Sendable = Extract | OAuthCredential; - -function isSignIn(credential: C): credential is C & OAuthCredential { +function isSignIn(credential: C): credential is C & OAuthCredential { return credential.auth === 'oauth'; } // A token or key is sent as it is and never refreshed: one the server turns down has to be replaced. -function mcpRefresher(server: McpServer, schema: z.ZodType): TokenRefresher { +function mcpRefresher(server: McpServer, schema: z.ZodType): TokenRefresher { return { name: server.name, schema, @@ -34,7 +32,7 @@ function mcpRefresher(server: McpServer, schema: z.ZodType( +export function withMcpCredential( server: McpServer, connection: StoredConnection, schema: z.ZodType, @@ -61,7 +61,7 @@ export function withMcpSignIn( * `credentials_rejected`, and has to be signed in to again or given a new key. */ export function withMcpToken(server: McpServer, connection: StoredConnection, use: (accessToken: string) => Promise>): Promise> { - return withMcpSignIn(server, connection, storedBuiltInCredentialSchema, use); + return withMcpCredential(server, connection, builtInCredentialSchema, use); } /** Calls one of a server's tools with a connection's token, refreshed as `withMcpToken` does. */ diff --git a/packages/api/src/connections/mcp/unify-credentials.ts b/packages/api/src/connections/mcp/unify-credentials.ts index 25155aec..5ad3bf91 100644 --- a/packages/api/src/connections/mcp/unify-credentials.ts +++ b/packages/api/src/connections/mcp/unify-credentials.ts @@ -1,4 +1,5 @@ import {Err, Ok, type Result} from 'ts-results-es'; +import {z} from 'zod'; import {ApiErr, type ApiError, Do} from '@proxy/utils'; import {listIntegrationCredentials, rewriteConnectionCredential, type StoredCredentialRow} from '@proxy/db/connection'; @@ -8,19 +9,30 @@ import {log, serializeError} from '../../observability/log'; import {encryptSecret} from '../../utils/secret-crypto'; import {readStoredJson} from '../../utils/stored-json'; import {builtInMcps} from '../built-in-mcp'; -import {builtInCredentialSchema, storedBuiltInCredentialSchema} from './mcp-credential'; +import {builtInCredentialSchema, type BuiltInCredential} from './mcp-credential'; +import {mcpTokensSchema} from './mcp-oauth'; /** - * The data migration `unify-mcp-credentials` (`data-migrations/run.ts`): every connection of an + * The data migration `unify-mcp-credentials-again` (`data-migrations/run.ts`): every connection of an * integration built on its MCP server given its credential in the shape every MCP credential has * now (`mcp-credential.ts`), a key as `{auth: 'token', token}` rather than `{auth: 'key', key}`, and * a sign-in's tokens under `{auth: 'oauth'}` rather than bare. A custom server's were in it already. * Each is rewritten only while it is still the one read, so tokens refreshed meanwhile are never * undone; one that changed meanwhile, or couldn't be saved, has the migration tried again on the * next start. One that can't be read at all, as after a change of `ENCRYPTION_KEY`, is logged and - * passed over, as it was unusable before too. + * passed over, as it was unusable before too. Until it has run, a connection in the old shape can't + * be used: the api reads only the shape credentials have now. */ +// Before every MCP credential said how it signs in, an integration built in stored a key as +// `{auth: 'key', key}` and a sign-in's tokens bare. Only this migration reads them now. +const legacyKeySchema = z.object({auth: z.literal('key'), key: z.string()}).transform(({key}): BuiltInCredential => ({auth: 'token', token: key})); + +const legacyTokensSchema = mcpTokensSchema.transform((tokens): BuiltInCredential => ({auth: 'oauth', ...tokens})); + +// A built-in integration's credential as stored, in the shape it had before. +const legacyCredentialSchema = z.union([legacyKeySchema, legacyTokensSchema]); + // What became of one connection's credential. type Rewrite = 'rewritten' | 'current' | 'changed'; @@ -29,7 +41,7 @@ function rewrite(row: StoredCredentialRow): Promise> { if (readStoredJson(row.credential, builtInCredentialSchema).isOk()) { return 'current' as const; } - const credential = $(readStoredJson(row.credential, storedBuiltInCredentialSchema)); + const credential = $(readStoredJson(row.credential, legacyCredentialSchema)); const encrypted = $(encryptSecret(JSON.stringify(credential))); const saved = $(await rewriteConnectionCredential({connectionId: row.id, previous: row.credential, credential: encrypted})); return saved ? ('rewritten' as const) : ('changed' as const); diff --git a/packages/api/src/data-migrations/run.ts b/packages/api/src/data-migrations/run.ts index 9493dd7c..8a48a1f9 100644 --- a/packages/api/src/data-migrations/run.ts +++ b/packages/api/src/data-migrations/run.ts @@ -23,7 +23,9 @@ export type DataMigration = {id: string; run: () => Promise