Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/api/src/connections/custom/custom-mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -70,7 +70,7 @@ function withCustomServer<T>(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)));
});
}

Expand Down
60 changes: 36 additions & 24 deletions packages/api/src/connections/custom/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -66,7 +66,37 @@ const {beginSignIn, handleCallback: handleCustomMcpCallbackRoute} = signInFlow({

export {handleCustomMcpCallbackRoute};

function connectCustomMcp(request: AuthenticatedRequest, res: Response): Promise<Result<z.infer<typeof connectMcpSchema>, ApiError>> {
type ConnectMcpAnswer = z.infer<typeof connectMcpSchema>;

// 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<Result<ConnectMcpAnswer, ApiError>> {
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<Result<ConnectMcpAnswer, ApiError>> {
return Do(async ($) => {
const body = $(parseSchema(connectMcpBodySchema, request.body));
const url = $(await parseMcpServerUrl(body.url));
Expand All @@ -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}));
});
}

Expand Down Expand Up @@ -143,7 +165,7 @@ function keptToken(current: CustomCredential, url: URL): Result<string | null, A
return Ok(current.token);
}

function editCustomMcp(request: AuthenticatedRequest, res: Response): Promise<Result<z.infer<typeof connectMcpSchema>, ApiError>> {
function editCustomMcp(request: AuthenticatedRequest, res: Response): Promise<Result<ConnectMcpAnswer, ApiError>> {
return Do(async ($) => {
const body = $(parseSchema(editMcpServerBodySchema, request.body));
const viewer = $(await requireViewer(request));
Expand All @@ -162,17 +184,7 @@ function editCustomMcp(request: AuthenticatedRequest, res: Response): Promise<Re
return $(Err(ApiErr.conflict(`${account} is connected already, as ${taken.name ?? taken.account}`)));
}
const token = body.token === undefined ? $(keptToken(current, url)) : body.token;
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), 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}));
});
}

Expand Down
10 changes: 0 additions & 10 deletions packages/api/src/connections/mcp/mcp-credential.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,3 @@ export const builtInCredentialSchema = z.discriminatedUnion('auth', [tokenAuthSc
export type BuiltInCredential = z.infer<typeof builtInCredentialSchema>;

export type OAuthCredential = z.infer<typeof oauthAuthSchema>;

// 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]);
21 changes: 2 additions & 19 deletions packages/api/src/connections/mcp/mcp-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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',
Expand All @@ -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});
Expand All @@ -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();
Expand Down
22 changes: 11 additions & 11 deletions packages/api/src/connections/mcp/mcp-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<BuiltInCredential, {auth: 'token'}> | OAuthCredential;

function isSignIn<C extends Sendable>(credential: C): credential is C & OAuthCredential {
function isSignIn<C extends BuiltInCredential>(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<C extends Sendable>(server: McpServer, schema: z.ZodType<C>): TokenRefresher<C> {
function mcpRefresher<C extends BuiltInCredential>(server: McpServer, schema: z.ZodType<C>): TokenRefresher<C> {
return {
name: server.name,
schema,
Expand All @@ -34,18 +32,20 @@ function mcpRefresher<C extends Sendable>(server: McpServer, schema: z.ZodType<C
}

// What is sent: the token or key, or the sign-in's access token.
function sent(credential: Sendable): string {
function sent(credential: BuiltInCredential): string {
if (credential.auth === 'oauth') {
return credential.accessToken;
}
return credential.token;
}

/**
* Runs `use` with a custom server's sign-in, read with `schema`, which keeps its address and
* endpoints beside the tokens when they are refreshed, as `withMcpToken` does (`custom/custom-mcp.ts`).
* Runs `use` with what a connection's credential, read with `schema`, sends: its token or key, or
* its sign-in's access token, refreshed as `withMcpToken` describes. Whatever else the credential
* holds, as a custom server's address and endpoints (`custom/custom-mcp.ts`), is kept beside the
* new tokens.
*/
export function withMcpSignIn<T, C extends Sendable>(
export function withMcpCredential<T, C extends BuiltInCredential>(
server: McpServer,
connection: StoredConnection,
schema: z.ZodType<C>,
Expand All @@ -61,7 +61,7 @@ export function withMcpSignIn<T, C extends Sendable>(
* `credentials_rejected`, and has to be signed in to again or given a new key.
*/
export function withMcpToken<T>(server: McpServer, connection: StoredConnection, use: (accessToken: string) => Promise<Result<T, ApiError>>): Promise<Result<T, ApiError>> {
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. */
Expand Down
20 changes: 16 additions & 4 deletions packages/api/src/connections/mcp/unify-credentials.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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';

Expand All @@ -29,7 +41,7 @@ function rewrite(row: StoredCredentialRow): Promise<Result<Rewrite, ApiError>> {
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);
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/data-migrations/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export type DataMigration = {id: string; run: () => Promise<Result<void, ApiErro
export const DATA_MIGRATIONS: DataMigration[] = [
{id: 'take-over-custom-connections', run: takeOverCustomConnections},
{id: 'convert-old-vault-records', run: convertOldVaultRecords},
{id: 'unify-mcp-credentials', run: unifyMcpCredentials},
// Run again under a new id: an instance from before it may have written the old shapes while the
// first run's deploy rolled over, and only the migration reads them now.
{id: 'unify-mcp-credentials-again', run: unifyMcpCredentials},
];

function metaKey(id: string): string {
Expand Down
Loading