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
3 changes: 3 additions & 0 deletions packages/api/scripts/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ const meetings = await connect({
account: '[email protected]',
credential: encrypt(
JSON.stringify({
auth: 'oauth',
clientId: 'demo-client',
accessToken: 'demo-access-token',
refreshToken: null,
Expand All @@ -223,6 +224,7 @@ const wiki = await connect({
account: '[email protected] · Acme',
credential: encrypt(
JSON.stringify({
auth: 'oauth',
clientId: 'demo-client',
accessToken: 'demo-access-token',
refreshToken: null,
Expand All @@ -239,6 +241,7 @@ const tracker = await connect({
account: '[email protected] · Acme',
credential: encrypt(
JSON.stringify({
auth: 'oauth',
clientId: 'demo-client',
accessToken: 'demo-access-token',
refreshToken: null,
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/connections/cloudflare/built-in.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ describe('the sign-in', () => {
expect(toolCalls[0]?.headers.get('authorization')).toBe('Bearer access-1');
const created = createConnection.mock.calls[0]?.[0];
expect(created).toMatchObject({orgId: 'org-1', integrationId: 'cloudflare', account: '[email protected]', defaults: ['read']});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'});
expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added');
});
});
Expand Down Expand Up @@ -200,7 +200,7 @@ describe('keyConnectRoute', () => {
expect(calls.map((call) => JSON.parse(call.body).method)).toEqual(['tools/list', 'tools/call']);
expect(findAccountConnection).toHaveBeenCalledWith(expect.objectContaining({orgId: 'org-1', userId: 'user-1'}), {integrationId: 'cloudflare', account: 'Acme', providerAccountId: 'account:acc-1'});
expect(createConnection.mock.calls[0]?.[0]).toMatchObject({account: 'Acme', providerAccountId: 'account:acc-1'});
expect(JSON.parse(String(createConnection.mock.calls[0]?.[0].credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'account-token'});
expect(JSON.parse(String(createConnection.mock.calls[0]?.[0].credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'account-token'});
expect(connection).toMatchObject({id: 'conn-1', account: 'Acme'});
});

Expand Down
22 changes: 12 additions & 10 deletions packages/api/src/connections/custom/custom-mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import {mcpToolReadsOnly, type McpTool} from '@proxy/integrations';

import {readStoredJson} from '../../utils/stored-json';
import {callMcpTool, listMcpTools} from '../mcp/mcp-client';
import {mcpCredentialSchema, mcpEndpointsSchema, type McpEndpoint, type McpServer} from '../mcp/mcp-oauth';
import {withMcpToken} from '../mcp/mcp-session';
import {noAuthSchema, oauthAuthSchema, tokenAuthSchema} from '../mcp/mcp-credential';
import {mcpEndpointsSchema, type McpEndpoint, type McpServer} from '../mcp/mcp-oauth';
import {withMcpSignIn} from '../mcp/mcp-session';

/**
* A custom MCP server, by its address: connected with no sign-in where the server asks for none,
Expand All @@ -16,13 +17,14 @@ import {withMcpToken} from '../mcp/mcp-session';
* the agent as the server wrote it (`mcp-discovery.ts` finds out how a server is signed in to).
*/

/** What a custom MCP connection stores, encrypted: the server's address and how it is signed in to. */
export const customCredentialSchema = z.discriminatedUnion('auth', [
z.object({auth: z.literal('none'), url: z.string()}),
z.object({auth: z.literal('token'), url: z.string(), token: z.string()}),
// Signed in: the server's endpoints beside the tokens, so refreshing needs nothing else.
z.object({auth: z.literal('oauth'), url: z.string(), server: mcpEndpointsSchema, ...mcpCredentialSchema.shape}),
]);
// Signed in: the server's endpoints beside the tokens, so refreshing needs nothing else.
const customSignInSchema = oauthAuthSchema.extend({url: z.string(), server: mcpEndpointsSchema});

/**
* What a custom MCP connection stores, encrypted: an MCP credential (`mcp-credential.ts`) with the
* server's address beside it.
*/
export const customCredentialSchema = z.discriminatedUnion('auth', [noAuthSchema.extend({url: z.string()}), tokenAuthSchema.extend({url: z.string()}), customSignInSchema]);

export type CustomCredential = z.infer<typeof customCredentialSchema>;

Expand Down Expand Up @@ -68,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 withMcpToken(server, connection, (accessToken) => use(server, accessToken)));
return $(await withMcpSignIn(server, connection, customSignInSchema, (accessToken) => use(server, accessToken)));
});
}

Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/connections/custom/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ describe('handleConnectCustomMcpRoute', () => {
] as const) {
const res = await connect({name: 'Web search', url, token: 'key-1234'});
expect(res.sent).toMatchObject({kind: 'connected', connection: {name: 'Web search', account}});
expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId, name: 'Web search', credential: `enc:${JSON.stringify({auth: 'key', key: 'key-1234'})}`});
expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId, name: 'Web search', credential: `enc:${JSON.stringify({auth: 'token', token: 'key-1234'})}`});
}
expect(probeMcpServer).not.toHaveBeenCalled();
});
Expand All @@ -314,7 +314,7 @@ describe('handleConnectCustomMcpRoute', () => {
const res = await connect({name: 'Linear test', url: 'https://mcp.linear.app/mcp', token: 'key-1234'});

expect(createConnection).not.toHaveBeenCalled();
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'linear-1', credential: `enc:${JSON.stringify({auth: 'key', key: 'key-1234'})}`});
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'linear-1', credential: `enc:${JSON.stringify({auth: 'token', token: 'key-1234'})}`});
expect(updateConnectionName).not.toHaveBeenCalled();
expect(res.sent).toMatchObject({kind: 'connected', connection: {id: 'linear-1', name: 'Work', account: '[email protected] · Acme'}});
});
Expand All @@ -324,7 +324,7 @@ describe('handleConnectCustomMcpRoute', () => {
const res = await connect({name: 'Web search', url: 'https://mcp.exa.ai/mcp?exaApiKey=key-5678'});

expect(res.sent).toMatchObject({kind: 'connected', connection: {name: 'Web search', account: 'API key ending 5678'}});
expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId: 'exa', credential: `enc:${JSON.stringify({auth: 'key', key: 'key-5678'})}`});
expect(createConnection.mock.calls.at(-1)?.[0]).toMatchObject({integrationId: 'exa', credential: `enc:${JSON.stringify({auth: 'token', token: 'key-5678'})}`});
});

test('a token for a built-in integration that takes no key is refused, rather than dropped for a sign-in', async () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/connections/exa/built-in.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ describe('keyConnectRoute', () => {
const created = createConnection.mock.calls[0]?.[0];
expect(created).toMatchObject({orgId: 'org-1', integrationId: 'exa', account: 'API key ending 1234', defaults: ['search', 'fetch']});
expect(created.name).toBeUndefined();
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'exa-key-1234'});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'exa-key-1234'});
expect(connection).toMatchObject({id: 'conn-1', name: null, unavailable: []});
});

Expand Down Expand Up @@ -278,7 +278,7 @@ describe('keyConnectRoute', () => {
const connection = (await connectWithKey({connection: 'conn-0', key: 'exa-key-5678'})).unwrap();

expect(createConnection).not.toHaveBeenCalled();
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'conn-0', account: 'API key ending 5678', credential: `enc:${JSON.stringify({auth: 'key', key: 'exa-key-5678'})}`});
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'conn-0', account: 'API key ending 5678', credential: `enc:${JSON.stringify({auth: 'token', token: 'exa-key-5678'})}`});
expect(updateConnectionName).not.toHaveBeenCalled();
expect(connection).toMatchObject({id: 'conn-0', name: 'Team Exa'});
});
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/connections/granola/built-in.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ describe('handleGranolaCallbackRoute', () => {
).toBe(authorizeUrl.searchParams.get('code_challenge') ?? '');
const created = createConnection.mock.calls[0]?.[0];
expect(created).toMatchObject({orgId: 'org-1', integrationId: 'granola', account: '[email protected]', defaults: ['readNotes', 'readTranscripts']});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'});
expect(res.clearCookie).toHaveBeenCalled();
expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added');
});
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/connections/linear/built-in.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ describe('handleLinearCallbackRoute', () => {
]);
const created = createConnection.mock.calls[0]?.[0];
expect(created).toMatchObject({orgId: 'org-1', integrationId: 'linear', account: '[email protected] · Acme', defaults: ['read']});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toMatchObject({auth: 'oauth', clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1'});
expect(res.redirect).toHaveBeenCalledWith('https://app.example.com/org-1/connections/conn-1?added');
});

Expand Down Expand Up @@ -296,7 +296,7 @@ describe('keyConnectRoute', () => {
});
const created = createConnection.mock.calls[0]?.[0];
expect(created).toMatchObject({integrationId: 'linear', account: '[email protected] · Acme', defaults: ['read']});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'key', key: 'lin_api_1234'});
expect(JSON.parse(String(created.credential).replace(/^enc:/, ''))).toEqual({auth: 'token', token: 'lin_api_1234'});
expect(connection).toMatchObject({id: 'conn-1', account: '[email protected] · Acme'});
});

Expand Down
13 changes: 7 additions & 6 deletions packages/api/src/connections/mcp/mcp-connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import {saveConnection, signInFlow, signInRoutes, type Connected, type SaveOptio
import type {ApiIntegration} from '../integration';
import {requireManaged, type ManagingViewer} from '../managed';
import type {BuiltInMcp, ProviderAccount} from './built-in';
import {exchangeMcpCode, mcpAuthorizeUrl, registerMcpClient, type McpCredential, type McpServer} from './mcp-oauth';
import type {McpKeyCredential} from './mcp-session';
import {exchangeMcpCode, mcpAuthorizeUrl, registerMcpClient, type McpServer} from './mcp-oauth';
import type {BuiltInCredential} from './mcp-credential';

/**
* Connecting an integration built on its MCP server: by signing in to it, as Granola, Notion and
Expand Down Expand Up @@ -63,9 +63,10 @@ function builtInSignIn(builtIn: BuiltInMcp) {
keptSchema,
start: (request: SignInRequest) => startMcpSignIn(server, request, {}),
finish: ({redirectUri, code, verifier, kept}: {redirectUri: string; code: string; verifier: string; kept: Kept}) =>
Do<Connected<McpCredential>, ApiError>(async ($) => {
const credential = $(await exchangeMcpCode(server, {clientId: kept.clientId, redirectUri, code, verifier}));
const account = $(await accountOf(builtIn, credential.accessToken));
Do<Connected<BuiltInCredential>, ApiError>(async ($) => {
const tokens = $(await exchangeMcpCode(server, {clientId: kept.clientId, redirectUri, code, verifier}));
const credential: BuiltInCredential = {auth: 'oauth', ...tokens};
const account = $(await accountOf(builtIn, tokens.accessToken));
return {...account, credential, defaults: builtIn.defaults, ...anonymity(builtIn), ...(kept.name ? {name: kept.name} : {})};
}),
};
Expand Down Expand Up @@ -138,7 +139,7 @@ export function connectWithKey(builtIn: BuiltInMcp, viewer: ManagingViewer, args
return $(Err(ApiErr.validationError('An API key has no spaces')));
}
const account = $(await checkedKeyAccount(builtIn, args.key));
const credential: McpKeyCredential = {auth: 'key', key: args.key};
const credential: BuiltInCredential = {auth: 'token', token: args.key};
const connected = {...account, credential, defaults: builtIn.defaults, ...anonymity(builtIn), ...(args.name === undefined ? {} : {name: args.name})};
const {row} = $(await saveConnection(viewer, builtIn.integrationId, connected, {shared: args.shared, connectionId: args.connectionId}));
// A key opens all of the integration: how the response reads the credential, which never leaves the api.
Expand Down
35 changes: 35 additions & 0 deletions packages/api/src/connections/mcp/mcp-credential.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {z} from 'zod';

import {mcpTokensSchema} from './mcp-oauth';

/**
* What every connection to an MCP server stores, encrypted, built in or custom, in one shape: how
* it signs in (`auth`) and what with. `none`: nothing, as a custom server that asks for no sign-in.
* `token`: a token or API key, sent as the bearer token, or as written where it starts with its
* scheme, as `Basic …` (`mcp-client.ts`). `oauth`: a sign-in, its client and tokens, refreshed as
* they run out (`mcp-session.ts`). A custom server's adds its address, and a sign-in's the server's
* endpoints (`custom/custom-mcp.ts`).
*/

export const noAuthSchema = z.object({auth: z.literal('none')});

export const tokenAuthSchema = z.object({auth: z.literal('token'), token: z.string()});

export const oauthAuthSchema = z.object({auth: z.literal('oauth'), ...mcpTokensSchema.shape});

/** What a connection of an integration built on its MCP server stores: a key, or a sign-in. */
export const builtInCredentialSchema = z.discriminatedUnion('auth', [tokenAuthSchema, oauthAuthSchema]);

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]);
14 changes: 7 additions & 7 deletions packages/api/src/connections/mcp/mcp-oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@ const TIMEOUT_MS = 15_000;
// Refreshed a minute early, so a token doesn't run out between the check and the call.
const EXPIRY_MARGIN_MS = 60_000;

/** What a connection to an MCP server stores, encrypted: the client it signed in with and its tokens. */
export const mcpCredentialSchema = z.object({
/** What a sign-in to an MCP server leaves: the client it signed in with and its tokens, kept in the connection's credential (`mcp-credential.ts`). */
export const mcpTokensSchema = z.object({
clientId: z.string(),
accessToken: z.string(),
refreshToken: z.string().nullable(),
expiresAt: z.string().nullable(),
});

export type McpCredential = z.infer<typeof mcpCredentialSchema>;
export type McpTokens = z.infer<typeof mcpTokensSchema>;

const registrationSchema = z.object({client_id: z.string().min(1)});

Expand Down Expand Up @@ -127,7 +127,7 @@ export function mcpAuthorizeUrl(server: McpServer, args: {clientId: string; redi
return url.toString();
}

async function requestTokens(server: McpServer, clientId: string, params: Record<string, string>, previousRefreshToken: string | null): Promise<Result<McpCredential, ApiError>> {
async function requestTokens(server: McpServer, clientId: string, params: Record<string, string>, previousRefreshToken: string | null): Promise<Result<McpTokens, ApiError>> {
const tokens = await checkedRequest(
server.tokenUrl,
{
Expand All @@ -147,18 +147,18 @@ async function requestTokens(server: McpServer, clientId: string, params: Record
}

/** Trades the code the server sent back for the connection's first tokens. */
export function exchangeMcpCode(server: McpServer, args: {clientId: string; redirectUri: string; code: string; verifier: string}): Promise<Result<McpCredential, ApiError>> {
export function exchangeMcpCode(server: McpServer, args: {clientId: string; redirectUri: string; code: string; verifier: string}): Promise<Result<McpTokens, ApiError>> {
return requestTokens(server, args.clientId, {grant_type: 'authorization_code', code: args.code, redirect_uri: args.redirectUri, code_verifier: args.verifier}, null);
}

/** New tokens for a connection whose access token ran out; turned down once the server revoked it. */
export async function refreshMcpTokens(server: McpServer, credential: McpCredential): Promise<Result<McpCredential, ApiError>> {
export async function refreshMcpTokens(server: McpServer, credential: McpTokens): Promise<Result<McpTokens, ApiError>> {
if (!credential.refreshToken) {
return Err(ApiErr.credentialsRejected());
}
return requestTokens(server, credential.clientId, {grant_type: 'refresh_token', refresh_token: credential.refreshToken}, credential.refreshToken);
}

export function isExpiring(credential: McpCredential): boolean {
export function isExpiring(credential: McpTokens): boolean {
return credential.expiresAt !== null && Date.parse(credential.expiresAt) - EXPIRY_MARGIN_MS < Date.now();
}
Loading
Loading