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
27 changes: 22 additions & 5 deletions packages/api/src/connections/connect-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ type SignInAnswer<E> = {redirectUri: string; code: string; verifier: string; kep
* it: a new connection's, or, for a custom server added again, the connection's new name; any other
* connection renewed keeps its own. `anonymous` where the provider said nothing of who signed in,
* as Exa and Parallel don't: the account is only a label, so no existing connection is the same
* account's.
* account's. `fromConnection` where the connection it was begun from is the one to renew, whatever
* account it shows now, as moving a custom MCP server to another address does.
*/
export type Connected<C> = {account: string; accountId?: string; credential: C; defaults: string[]; tools?: McpTool[]; name?: string; anonymous?: true};
export type Connected<C> = {account: string; accountId?: string; credential: C; defaults: string[]; tools?: McpTool[]; name?: string; anonymous?: true; fromConnection?: true};

// The one of the same account among those the viewer sees and may change, if there is one: a
// sign-in to another account is a connection of its own, never one agents were given for the first,
Expand All @@ -88,15 +89,24 @@ export type Connected<C> = {account: string; accountId?: string; credential: C;
// only where its account can't be told apart from another's: the provider said nothing of who
// signed in (`anonymous`), or the connection was never signed in to, as one moved over from a
// custom MCP server without a sign-in of the integration's (`take-over-custom.ts`), and no other
// connection is the account's already, so an account is never connected twice.
// connection is the account's already, so an account is never connected twice. One moved to
// another account on its page (`fromConnection`) renews that one, or nothing, should it be gone.
function connectionToRenew(
viewer: ManagingViewer,
integrationId: IntegrationId,
connected: {account: string; providerAccountId: string | null; anonymous: boolean},
connected: {account: string; providerAccountId: string | null; anonymous: boolean; fromConnection: boolean},
connectionId: string | null,
): Promise<Result<ConnectionRow | null, ApiError>> {
return Do(async ($) => {
const {account, providerAccountId} = connected;
if (connected.fromConnection) {
const begunFrom = connectionId === null ? null : $(await getConnectionWithCredential(viewer, connectionId));
if (begunFrom?.integrationId !== integrationId || !manages(viewer, begunFrom)) {
return $(Err(ApiErr.notFound('connection', connectionId ?? '')));
}
const {credential: _credential, ...row} = begunFrom;
return row;
}
const sameAccount = connected.anonymous ? null : $(await findAccountConnection(viewer, {integrationId, account, providerAccountId}));
if (sameAccount && manages(viewer, sameAccount)) {
return sameAccount;
Expand Down Expand Up @@ -151,7 +161,14 @@ export function saveConnection<C>(
const encrypted = $(encryptSecret(JSON.stringify(connected.credential)));
const providerAccountId = connected.accountId ?? null;
const name = connected.name === undefined ? {} : {name: connected.name};
const existing = $(await connectionToRenew(viewer, integrationId, {account, providerAccountId, anonymous: connected.anonymous === true}, options.connectionId ?? null));
const existing = $(
await connectionToRenew(
viewer,
integrationId,
{account, providerAccountId, anonymous: connected.anonymous === true, fromConnection: connected.fromConnection === true},
options.connectionId ?? null,
),
);
if (!existing) {
return {row: $(await addConnection(viewer, integrationId, connected, encrypted, options.shared === true)), added: true};
}
Expand Down
5 changes: 3 additions & 2 deletions packages/api/src/connections/custom/custom-mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ function customServer(credential: Extract<CustomCredential, {auth: 'oauth'}>): M

type StoredConnection = {id: string; credential: string | null};

function readCredential(connection: StoredConnection): Result<CustomCredential, ApiError> {
/** What a custom MCP connection signs in to its server with, decrypted. */
export function readCustomCredential(connection: StoredConnection): Result<CustomCredential, ApiError> {
return Do<CustomCredential, ApiError>(($) => {
const stored = $(requirePresent(connection.credential, ApiErr.internalError(new Error('Custom MCP connection without a credential'))));
return $(readStoredJson(stored, customCredentialSchema));
Expand All @@ -59,7 +60,7 @@ function readCredential(connection: StoredConnection): Result<CustomCredential,
// typed in, or the access token, refreshed as it runs out.
function withCustomServer<T>(connection: StoredConnection, use: (server: McpEndpoint, accessToken: string | null) => Promise<Result<T, ApiError>>): Promise<Result<T, ApiError>> {
return Do(async ($) => {
const credential = $(readCredential(connection));
const credential = $(readCustomCredential(connection));
if (credential.auth === 'none') {
return $(await use(customEndpoint(credential.url), null));
}
Expand Down
105 changes: 105 additions & 0 deletions packages/api/src/connections/custom/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -387,3 +387,108 @@ describe('handleRefreshCustomMcpToolsRoute', () => {
expect(listCustomTools).not.toHaveBeenCalled();
});
});

describe('handleEditCustomMcpServerRoute', () => {
const tokenCredential = {auth: 'token', url: 'https://mcp.example.com/mcp?v=2', token: 'secret'};

function stored(credential: Record<string, unknown>) {
getConnectionWithCredential.mockResolvedValue(Ok({...row, name: 'Docs', credential: `enc:${JSON.stringify(credential)}`}));
}

async function edit(body: unknown) {
const {handleEditCustomMcpServerRoute} = await import('./route');
const res = makeRes();
await handleEditCustomMcpServerRoute(makeRequest(body, {connectionId: 'mcp-1'}), res as never);
return res;
}

test('moves the connection to another address on the same server, its token, name and settings kept', async () => {
stored(tokenCredential);
const res = await edit({url: 'https://mcp.example.com/v2/mcp'});

expect(probeMcpServer).toHaveBeenCalledWith(new URL('https://mcp.example.com/v2/mcp'), 'secret');
expect(createConnection).not.toHaveBeenCalled();
expect(updateConnectionName).not.toHaveBeenCalled();
expect(renewConnection).toHaveBeenCalledWith({
connectionId: 'mcp-1',
account: 'mcp.example.com/v2/mcp',
providerAccountId: null,
credential: `enc:${JSON.stringify({auth: 'token', url: 'https://mcp.example.com/v2/mcp', token: 'secret'})}`,
});
expect(updateConnectionTools).toHaveBeenCalledWith({connectionId: 'mcp-1', tools: JSON.stringify([search, publish]), actions: ['search_docs', 'publish_doc']});
expect(res.sent).toMatchObject({kind: 'connected', connection: {id: 'mcp-1', name: 'Docs', account: 'mcp.example.com/v2/mcp', tools: [search, publish]}});
});

test('a new token alone keeps the address, its query too', async () => {
stored(tokenCredential);
await edit({token: ' other '});

expect(probeMcpServer).toHaveBeenCalledWith(new URL('https://mcp.example.com/mcp?v=2'), 'other');
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({
connectionId: 'mcp-1',
credential: `enc:${JSON.stringify({auth: 'token', url: 'https://mcp.example.com/mcp?v=2', token: 'other'})}`,
});
});

test('the token is never sent to another server unasked: it is typed again, or dropped', async () => {
stored(tokenCredential);
const refused = await edit({url: 'https://docs.example.org/mcp'});
expect(refused.statusCode).toBe(400);
expect(probeMcpServer).not.toHaveBeenCalled();

await edit({url: 'https://docs.example.org/mcp', token: null});
expect(probeMcpServer).toHaveBeenCalledWith(new URL('https://docs.example.org/mcp'), null);
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({credential: `enc:${JSON.stringify({auth: 'none', url: 'https://docs.example.org/mcp'})}`});
});

test('refuses an address another of the connections has, and a service built in', async () => {
stored(tokenCredential);
findAccountConnection.mockResolvedValue(Ok({...row, id: 'mcp-2', account: 'mcp.example.com/other', name: 'Other docs'}));
const taken = await edit({url: 'https://mcp.example.com/other', token: null});
expect(taken.statusCode).toBe(409);

findAccountConnection.mockResolvedValue(Ok(null));
const builtIn = await edit({url: 'https://mcp.notion.com/mcp', token: null});
expect(builtIn.statusCode).toBe(400);
expect(probeMcpServer).not.toHaveBeenCalled();
expect(renewConnection).not.toHaveBeenCalled();
});

test('only a custom MCP server is edited', async () => {
getConnectionWithCredential.mockResolvedValue(Ok({...row, integrationId: 'notion', credential: 'enc:{}'}));
const res = await edit({url: 'https://mcp.example.com/mcp'});
expect(res.statusCode).toBe(400);
expect(probeMcpServer).not.toHaveBeenCalled();
});

test('a server that asks for a sign-in has it begun for this connection, which the callback renews at its new address', async () => {
stored({auth: 'none', url: 'https://old.example.com/mcp'});
probeMcpServer.mockResolvedValue(Ok({kind: 'signIn'}));
const begun = await edit({url: 'https://mcp.example.com/mcp'});
expect(begun.sent).toMatchObject({kind: 'signIn'});
const state = new URL((begun.sent as {url: string}).url).searchParams.get('state') ?? '';
const cookie = `proxy.mcp-state=${encodeURIComponent(begun.cookies[0]?.value ?? '')}`;

// Another connection of the account would be renewed on a new sign-in; this one is the edited one.
findAccountConnection.mockResolvedValue(Ok({...row, id: 'mcp-2'}));
exchangeMcpCode.mockResolvedValue(Ok({clientId: 'client-1', accessToken: 'access-1', refreshToken: 'refresh-1', expiresAt: null}));
listMcpTools.mockResolvedValue(Ok([search]));
const {handleCustomMcpCallbackRoute} = await import('./route');
const res = makeRes();
await handleCustomMcpCallbackRoute(makeRequest(undefined, {}, {state, code: 'code-1'}, {cookie}), res as never);

expect(createConnection).not.toHaveBeenCalled();
expect(updateConnectionName).not.toHaveBeenCalled();
expect(renewConnection.mock.calls[0]?.[0]).toMatchObject({connectionId: 'mcp-1', account: 'mcp.example.com/mcp'});
expect(res.redirectedTo).toBe('https://app.example.com/org-1/connections/mcp-1');
});
});

describe('handleGetCustomMcpServerRoute', () => {
test('the address without its query, which may hold a key, and how it is signed in to', async () => {
getConnectionWithCredential.mockResolvedValue(Ok({...row, credential: `enc:${JSON.stringify({auth: 'token', url: 'https://mcp.example.com/mcp?key=k-1', token: 'secret'})}`}));
const {handleGetCustomMcpServerRoute} = await import('./route');
const result = (await handleGetCustomMcpServerRoute(makeRequest(undefined, {connectionId: 'mcp-1'}))).unwrap();
expect(result).toEqual({url: 'https://mcp.example.com/mcp', auth: 'token'});
});
});
94 changes: 87 additions & 7 deletions packages/api/src/connections/custom/route.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import type {Response} from 'express';
import {Err, type Result} from 'ts-results-es';
import {Err, Ok, type Result} from 'ts-results-es';
import {z} from 'zod';

import {ApiErr, type ApiError, Do, parseSchema} from '@proxy/utils';
import {type Connection, connectMcpBodySchema, type connectMcpSchema} from '@proxy/contracts/connections';
import {findAccountConnection} from '@proxy/db/connection';
import {type Connection, connectMcpBodySchema, type connectMcpSchema, type CustomMcpServer, editMcpServerBodySchema} from '@proxy/contracts/connections';

import type {AuthenticatedRequest} from '../../server/middleware/require-auth';
import {sendResult} from '../../server/response';
import {requireViewer} from '../../utils/user-org';
import {builtInForHost} from '../built-in-mcp';
import {respond} from '../connection-response';
import {saveConnection, signInFlow, type SignInRequest} from '../connect-flow';
import {requireManagedOf} from '../managed';
import {manages, requireManagedOf} from '../managed';
import {listMcpTools} from '../mcp/mcp-client';
import {keyInAddress} from '../mcp/built-in';
import {beginBuiltInSignIn, connectWithKey, startMcpSignIn} from '../mcp/mcp-connect';
import {exchangeMcpCode, mcpEndpoints, mcpEndpointsSchema} from '../mcp/mcp-oauth';
import {mcpAccount, readOnlyToolNames, type CustomCredential} from './custom-mcp';
import {mcpAccount, readCustomCredential, readOnlyToolNames, type CustomCredential} from './custom-mcp';
import {discoverMcpServer, parseMcpServerUrl, probeMcpServer} from './mcp-discovery';
import {refreshCustomTools} from './refresh-tools';

Expand All @@ -33,14 +34,17 @@ import {refreshCustomTools} from './refresh-tools';
* is connected as that integration instead: with the token typed in, or the key in the address, as
* its API key, where it takes one, else the answer is its sign-in, as signing in to it from the
* catalog begins, which comes back to its callback; a token for one that takes no key is refused.
* A connection's page can move it to another address or token (`PUT …/server`), asked for its tools
* there or signed in to as connecting is, the sign-in renewing that connection.
*/

const {beginSignIn, handleCallback: handleCustomMcpCallbackRoute} = signInFlow({
integrationId: 'mcp',
name: 'MCP server',
// The server found from the address and the name the person gave the connection, beside the
// client registered for the sign-in.
keptSchema: z.object({clientId: z.string(), server: mcpEndpointsSchema, name: z.string()}),
// client registered for the sign-in; or, for a connection moved to the server on its page
// (`edit`), no name, as it keeps its own.
keptSchema: z.object({clientId: z.string(), server: mcpEndpointsSchema, name: z.string().optional(), edit: z.literal(true).optional()}),
// Signed in, the server is asked for its tools with the new token, and the connection keeps its
// endpoints beside the tokens, for refreshing them.
finish: ({redirectUri, code, verifier, kept}) =>
Expand All @@ -49,7 +53,14 @@ const {beginSignIn, handleCallback: handleCustomMcpCallbackRoute} = signInFlow({
const tokens = $(await exchangeMcpCode(server, {clientId: kept.clientId, redirectUri, code, verifier}));
const tools = $(await listMcpTools(server, tokens.accessToken));
const credential: CustomCredential = {auth: 'oauth', url: server.url, server, ...tokens};
return {account: mcpAccount(new URL(server.url)), credential, defaults: readOnlyToolNames(tools), tools, name};
return {
account: mcpAccount(new URL(server.url)),
credential,
defaults: readOnlyToolNames(tools),
tools,
...(name === undefined ? {} : {name}),
...(kept.edit ? {fromConnection: true as const} : {}),
};
}),
});

Expand Down Expand Up @@ -105,3 +116,72 @@ export function handleRefreshCustomMcpToolsRoute(request: AuthenticatedRequest):
return $(await respond(connection));
});
}

const notCustom = ApiErr.validationError('Only a custom MCP server has an address to change');

/** `GET /api/connections/:connectionId/server`: the custom MCP server a connection reaches, for its edit dialog. */
export function handleGetCustomMcpServerRoute(request: AuthenticatedRequest): Promise<Result<CustomMcpServer, ApiError>> {
return Do(async ($) => {
const viewer = $(await requireViewer(request));
const row = $(await requireManagedOf(viewer, request.params.connectionId ?? '', 'mcp', notCustom));
const credential = $(readCustomCredential(row));
const url = new URL(credential.url);
url.search = '';
return {url: url.toString(), auth: credential.auth};
});
}

// The token a connection moved to `url` keeps where none was typed: its own, only while the server
// stays on the origin the token was given for, so it is never sent to another server unasked.
function keptToken(current: CustomCredential, url: URL): Result<string | null, ApiError> {
if (current.auth !== 'token') {
return Ok(null);
}
if (new URL(current.url).origin !== url.origin) {
return Err(ApiErr.validationError(`The token is only sent to the server it was given for. Enter it again for ${url.host}, or remove it`));
}
return Ok(current.token);
}

function editCustomMcp(request: AuthenticatedRequest, res: Response): Promise<Result<z.infer<typeof connectMcpSchema>, ApiError>> {
return Do(async ($) => {
const body = $(parseSchema(editMcpServerBodySchema, request.body));
const viewer = $(await requireViewer(request));
const row = $(await requireManagedOf(viewer, request.params.connectionId ?? '', 'mcp', notCustom));
const current = $(readCustomCredential(row));
const url = body.url === undefined ? new URL(current.url) : $(await parseMcpServerUrl(body.url));
// A service's own server is connected as that service, from the catalog, as a new
// connection: its actions are not this connection's tools.
const builtIn = builtInForHost(url.host);
if (builtIn) {
return $(Err(ApiErr.validationError(`${builtIn.server.name} has an integration of its own: add it from the connections list instead`)));
}
const account = mcpAccount(url);
const taken = $(await findAccountConnection(viewer, {integrationId: 'mcp', account, providerAccountId: null}));
if (taken && taken.id !== row.id && manages(viewer, taken)) {
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)}))};
});
}

/**
* `PUT /api/connections/:connectionId/server` with `{url?, token?, desktop?}`: moves a custom MCP
* connection to another address, another token, or both, after asking the server there for its
* tools, or begins the sign-in it asks for, which comes back to this connection. Its name, its
* agents' settings for the tools still listed and its activity stay.
*/
export async function handleEditCustomMcpServerRoute(request: AuthenticatedRequest, res: Response): Promise<void> {
sendResult(res, await editCustomMcp(request, res));
}
Loading
Loading