From 26465162d6fe638f0ce0439787de6485644864c2 Mon Sep 17 00:00:00 2001 From: hkonsti <45428767+hkonsti@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:16:47 +0000 Subject: [PATCH] edit a custom MCP server's address or token on its page, the connection, its settings and activity kept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * PUT /api/orgs/:org/connections/:id/server moves a custom MCP connection to another address, another token, or both, after asking the server there for its tools; a server that asks for a sign-in has it begun, and the callback renews this connection (`fromConnection` in connect-flow.ts) rather than making a new one * the address left out keeps the stored one, its query too; the token left out keeps the current one only while the server stays on its origin, so a token is never sent to another server unasked; null drops it * an address another of the person's connections has, or a built-in service's server, is turned down * GET …/server answers the address without its query, which may hold a key, and how it is signed in to, for the dialog * the connection page has a pencil opening the edit dialog; the desktop app hands a sign-in over to the browser as the connect form does * docs: Change the address or token --- packages/api/src/connections/connect-flow.ts | 27 ++- .../api/src/connections/custom/custom-mcp.ts | 5 +- .../api/src/connections/custom/route.test.ts | 105 +++++++++ packages/api/src/connections/custom/route.ts | 94 +++++++- packages/api/src/server/create-api-router.ts | 4 +- packages/contracts/src/connections.ts | 30 +++ .../docs/content/connections/custom-mcp.mdx | 18 ++ packages/web/src/client/connections-client.ts | 31 +++ .../src/components/edit-mcp-server-dialog.tsx | 207 ++++++++++++++++++ packages/web/src/loaders.ts | 30 ++- .../web/src/pages/connection-page.test.tsx | 116 +++++++++- packages/web/src/pages/connection-page.tsx | 29 ++- 12 files changed, 669 insertions(+), 27 deletions(-) create mode 100644 packages/web/src/components/edit-mcp-server-dialog.tsx diff --git a/packages/api/src/connections/connect-flow.ts b/packages/api/src/connections/connect-flow.ts index 7ac8c463..2edcc0aa 100644 --- a/packages/api/src/connections/connect-flow.ts +++ b/packages/api/src/connections/connect-flow.ts @@ -76,9 +76,10 @@ type SignInAnswer = {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 = {account: string; accountId?: string; credential: C; defaults: string[]; tools?: McpTool[]; name?: string; anonymous?: true}; +export type Connected = {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, @@ -88,15 +89,24 @@ export type Connected = {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> { 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; @@ -151,7 +161,14 @@ export function saveConnection( 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}; } diff --git a/packages/api/src/connections/custom/custom-mcp.ts b/packages/api/src/connections/custom/custom-mcp.ts index 68efbb8b..1d12120d 100644 --- a/packages/api/src/connections/custom/custom-mcp.ts +++ b/packages/api/src/connections/custom/custom-mcp.ts @@ -48,7 +48,8 @@ function customServer(credential: Extract): M type StoredConnection = {id: string; credential: string | null}; -function readCredential(connection: StoredConnection): Result { +/** What a custom MCP connection signs in to its server with, decrypted. */ +export function readCustomCredential(connection: StoredConnection): Result { return Do(($) => { const stored = $(requirePresent(connection.credential, ApiErr.internalError(new Error('Custom MCP connection without a credential')))); return $(readStoredJson(stored, customCredentialSchema)); @@ -59,7 +60,7 @@ function readCredential(connection: StoredConnection): Result(connection: StoredConnection, use: (server: McpEndpoint, accessToken: string | null) => Promise>): Promise> { return Do(async ($) => { - const credential = $(readCredential(connection)); + const credential = $(readCustomCredential(connection)); if (credential.auth === 'none') { return $(await use(customEndpoint(credential.url), null)); } diff --git a/packages/api/src/connections/custom/route.test.ts b/packages/api/src/connections/custom/route.test.ts index 07759e6f..819d39a5 100644 --- a/packages/api/src/connections/custom/route.test.ts +++ b/packages/api/src/connections/custom/route.test.ts @@ -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) { + 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'}); + }); +}); diff --git a/packages/api/src/connections/custom/route.ts b/packages/api/src/connections/custom/route.ts index a521aa1f..dc61cc46 100644 --- a/packages/api/src/connections/custom/route.ts +++ b/packages/api/src/connections/custom/route.ts @@ -1,9 +1,10 @@ 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'; @@ -11,12 +12,12 @@ 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'; @@ -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}) => @@ -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} : {}), + }; }), }); @@ -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> { + 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 { + 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, 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 { + sendResult(res, await editCustomMcp(request, res)); +} diff --git a/packages/api/src/server/create-api-router.ts b/packages/api/src/server/create-api-router.ts index 73ceeca6..6a1896a4 100644 --- a/packages/api/src/server/create-api-router.ts +++ b/packages/api/src/server/create-api-router.ts @@ -28,7 +28,7 @@ import {handleGoogleCallbackRoute, handleGoogleStartRoute, handleSignInMethodsRo import {handleSignOutRoute} from '../auth/signout'; import {handleGitHubApiRoute, handleGitHubGitRoute, handleGitHubIdentityRoute} from '../cli/github/route'; import {handleCliCallRoute} from '../cli/route'; -import {handleRefreshCustomMcpToolsRoute} from '../connections/custom/route'; +import {handleEditCustomMcpServerRoute, handleGetCustomMcpServerRoute, handleRefreshCustomMcpToolsRoute} from '../connections/custom/route'; import {handleGitHubInstallationsRoute} from '../connections/github/route'; import type {ApiIntegration} from '../connections/integration'; import {apiIntegrations} from '../connections/integrations'; @@ -209,6 +209,8 @@ export function createApiRouter(): express.Router { org.put('/connections/:connectionId/org', withAuthResult('Move connection route', handleMoveConnectionRoute)); org.put('/connections/:connectionId/sharing', withAuthResult('Set connection sharing route', handleSetConnectionSharingRoute)); org.post('/connections/:connectionId/tools', withAuthResult('Refresh custom MCP server tools route', handleRefreshCustomMcpToolsRoute)); + org.get('/connections/:connectionId/server', withAuthResult('Get custom MCP server route', handleGetCustomMcpServerRoute)); + org.put('/connections/:connectionId/server', withAuth('Edit custom MCP server route', handleEditCustomMcpServerRoute)); // What a GitHub connection reaches, for its page (connections/github/route.ts). org.get('/connections/:connectionId/github/installations', withAuthResult('GitHub installations route', handleGitHubInstallationsRoute)); const records = '/connections/:connectionId/collections/:collectionId/records'; diff --git a/packages/contracts/src/connections.ts b/packages/contracts/src/connections.ts index 33ac90f4..0f268042 100644 --- a/packages/contracts/src/connections.ts +++ b/packages/contracts/src/connections.ts @@ -208,6 +208,36 @@ export const connectMcpSchema = z.discriminatedUnion('kind', [ z.object({kind: z.literal('signIn'), url: z.string()}), ]); +/** + * `GET connections/:connectionId/server`: the custom MCP server a connection reaches, for whoever + * may change it: its address without the query, which may hold a key, and how it is signed in to. + */ +export const customMcpServerSchema = z.object({ + url: z.string(), + auth: z.enum(['none', 'token', 'oauth']), +}); + +export type CustomMcpServer = z.infer; + +/** + * `PUT connections/:connectionId/server`: a custom MCP connection moved to another address, given + * another token, or both, its name, settings and activity kept. `url` left out keeps the address, + * its query too; `token` left out keeps the token while the server stays on the same origin, `null` + * drops it. Answered as connecting is: connected, or the sign-in the server asks for, begun. + */ +export const editMcpServerBodySchema = z.object({ + url: z.string().optional(), + token: z + .string() + .trim() + .min(1, 'Enter the token, or remove it') + .regex(/^[^\r\n]*$/, 'The token can’t have line breaks') + .nullable() + .optional(), + /** Sent from the browser for the desktop app, as connecting is. */ + desktop: z.boolean().optional(), +}); + /** * `POST connections/` for one that takes an API key: a new connection, the person's * own or every member's, or the one given the key. diff --git a/packages/docs/content/connections/custom-mcp.mdx b/packages/docs/content/connections/custom-mcp.mdx index 2bde79ad..e795b390 100644 --- a/packages/docs/content/connections/custom-mcp.mdx +++ b/packages/docs/content/connections/custom-mcp.mdx @@ -52,6 +52,24 @@ on the connection's page or for one agent on the agent's page. +## Change the address or token + +The pencil on the connection's page opens **Edit the server**, where a server that moved gets its +new address, and a token that changed or ran out is replaced. Personal Agent Proxy asks the server +at the address for its tools before it keeps anything, so a wrong address or token changes nothing. +The connection keeps its name, its activity, and the settings for every tool the server still +lists. A server that asks for a sign-in opens its sign-in page, as connecting does, and comes back +to the same connection. + +- The address left as it is keeps anything after its `?` it was connected with, which the dialog + doesn't show, as it may hold a key. +- The token left empty keeps the current one, but only while the address stays on the same server: + a token is never sent to another server unless you enter it again. **Remove the token** connects + without one. +- A connection you signed in to is signed in to again when saved without a token. +- An address another of your connections has already, or a service's own server, such as Notion's, + is turned down: connect that from **Add connection**. + ## What agents can do Each tool the server lists is an action of its own, allowed or not. An agent that may run a tool diff --git a/packages/web/src/client/connections-client.ts b/packages/web/src/client/connections-client.ts index 6f588c52..02e3529f 100644 --- a/packages/web/src/client/connections-client.ts +++ b/packages/web/src/client/connections-client.ts @@ -8,6 +8,8 @@ import { type connectPlaidBodySchema, type createDriveBodySchema, type createVaultBodySchema, + customMcpServerSchema, + type editMcpServerBodySchema, type moveConnectionBodySchema, type connectWithKeyBodySchema, type plaidLinkTokenBodySchema, @@ -150,6 +152,35 @@ export function connectWithKey( return apiRequest('POST', `${orgApi(org)}/connections/${integrationId}`, connectionSchema, input); } +/** The custom MCP server a connection reaches, for whoever may change it: its address without the query, and how it is signed in to. */ +export function getMcpServer(org: string, connectionId: string) { + return apiRequest( + 'GET', + `${orgApi(org)}/connections/${connectionId}/server`, + customMcpServerSchema, + ); +} + +/** + * Moves a custom MCP connection to another address or token, answered as connecting is: the + * connection, or the sign-in the server asks for, begun, which comes back to it. `url` left out + * keeps the address, `token` left out the token, `null` drops it. A 400 says what is wrong, 409 that + * another connection has the address, 422 that the token was turned down, 502 that the server could + * not be reached. + */ +export function editMcpServer( + org: string, + connectionId: string, + input: z.input, +) { + return apiRequest( + 'PUT', + `${orgApi(org)}/connections/${connectionId}/server`, + connectMcpSchema, + input, + ); +} + /** Asks a custom MCP server for its tools again and keeps the new list. */ export function refreshMcpTools(org: string, connectionId: string) { return apiRequest('POST', `${orgApi(org)}/connections/${connectionId}/tools`, connectionSchema); diff --git a/packages/web/src/components/edit-mcp-server-dialog.tsx b/packages/web/src/components/edit-mcp-server-dialog.tsx new file mode 100644 index 00000000..a51ed024 --- /dev/null +++ b/packages/web/src/components/edit-mcp-server-dialog.tsx @@ -0,0 +1,207 @@ +import type {Connection, CustomMcpServer} from '@proxy/contracts/connections'; +import type {FetchError} from '@proxy/utils'; +import {useState} from 'react'; +import {editMcpServer} from '@/client/connections-client'; +import {PillButton} from '@proxy/ui/components/pill-button'; +import {Checkbox} from '@proxy/ui/components/checkbox'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@proxy/ui/components/dialog'; +import {Input} from '@proxy/ui/components/input'; +import {Label} from '@proxy/ui/components/label'; +import {apiMessage} from '@/lib/api-message'; +import {handOffToBrowser, isDesktopApp} from '@/lib/desktop'; +import {NO_PASSWORD_MANAGER} from '@/lib/password-managers'; +import {useOrgSlug} from '@/hooks/use-org'; + +function editErrorMessage(error: FetchError): string { + if (error.kind === 'http' && (error.status === 400 || error.status === 409)) { + return apiMessage(error.body) ?? 'Check the address.'; + } + if (error.kind === 'http' && error.status === 422) { + return 'The server turned the token down. Check it and try again.'; + } + if (error.kind === 'http' && error.status === 502) { + return 'The server could not be reached, or did not answer as an MCP server. Check the address and try again.'; + } + return 'Something went wrong. Try again.'; +} + +// What the token field says, by how the connection signs in now. +function tokenHint(auth: CustomMcpServer['auth']): string { + if (auth === 'token') { + return 'Leave it empty to keep the current token, which is only sent to the same server. A new one is sent as a bearer token, or as written when it starts with its scheme, such as Basic ….'; + } + if (auth === 'oauth') { + return 'Leave it empty to sign in to the server again. Only where the server takes a token or API key instead of a sign-in.'; + } + return 'Only where the server takes a token or API key instead of a sign-in. It is sent as a bearer token, or as written when it starts with its scheme, such as Basic ….'; +} + +// The token the server is sent from now on: none, a new one, or, left out, the current one. +function tokenChange(typed: string, drop: boolean): {token?: string | null} { + if (drop) { + return {token: null}; + } + if (typed.trim() === '') { + return {}; + } + return {token: typed.trim()}; +} + +type Props = { + connection: Connection; + server: CustomMcpServer; + // Filled in as it was in the desktop app, which hands a sign-in over to the browser (`?url=`, + // `?token=none`, `?desktop=1`). + handedOver: {url: string | null; dropToken: boolean; desktop: boolean}; + onClose: () => void; + onSaved: () => void; +}; + +// Moving a custom MCP connection to another address or token: the server there is asked for its +// tools before anything is kept, and one that asks for a sign-in opens it, coming back to this +// connection. The address left as it was keeps the one stored, its query too, which isn't shown; +// the token left empty keeps the current one. In the desktop app a sign-in moves to the browser, +// the dialog filled in there as it was, to be sent again, as the connect form does. +export function EditMcpServerDialog({connection, server, handedOver, onClose, onSaved}: Props) { + const org = useOrgSlug(); + const [url, setUrl] = useState(handedOver.url ?? server.url); + const [token, setToken] = useState(''); + const [dropToken, setDropToken] = useState(handedOver.dropToken); + const [error, setError] = useState(null); + const [notice, setNotice] = useState(null); + const [pending, setPending] = useState<'saving' | 'signingIn' | null>(null); + const ready = url.trim() !== ''; + + return ( + { + if (next) { + return; + } + onClose(); + }} + > + +
{ + event.preventDefault(); + if (!ready) { + return; + } + setPending('saving'); + setError(null); + setNotice(null); + const changedUrl = url.trim() === server.url ? undefined : url.trim(); + const result = await editMcpServer(org, connection.id, { + ...(changedUrl === undefined ? {} : {url: changedUrl}), + ...tokenChange(token, dropToken), + ...(handedOver.desktop ? {desktop: true} : {}), + }); + if (result.isErr()) { + setPending(null); + setError(editErrorMessage(result.error)); + return; + } + if (result.value.kind === 'connected') { + onSaved(); + return; + } + if (isDesktopApp()) { + const here = new URL(window.location.href); + here.searchParams.set('server', 'edit'); + here.searchParams.set('url', url.trim()); + here.searchParams.set('desktop', '1'); + if (dropToken) { + here.searchParams.set('token', 'none'); + } + handOffToBrowser(`${here.pathname}${here.search}`); + setPending(null); + setNotice( + 'Sign in to the server in your browser. The connection shows the new server once you have.', + ); + return; + } + // Only ever a web address: the api has checked it, and the browser goes nowhere else. + if (!/^https?:\/\//.test(result.value.url)) { + setPending(null); + setError('The server’s sign-in page is not a web address.'); + return; + } + setPending('signingIn'); + window.location.assign(result.value.url); + }} + > + + Edit the server + + The server at the address is asked for its tools before anything changes. The + connection keeps its name, its agents’ settings for the tools still listed, and its + activity. + + +
+ + setUrl(event.target.value)} + /> +

+ Left as it is, the address keeps anything after a ? it was connected with. +

+
+
+ + setToken(event.target.value)} + /> +

{tokenHint(server.auth)}

+ {server.auth === 'token' && ( + + )} +
+ {error &&

{error}

} + {notice &&

{notice}

} + + + Cancel + + + {pending === 'signingIn' + ? 'Opening sign-in…' + : pending === 'saving' + ? 'Asking the server…' + : 'Save'} + + +
+
+
+ ); +} diff --git a/packages/web/src/loaders.ts b/packages/web/src/loaders.ts index cbadbcbc..7baad17f 100644 --- a/packages/web/src/loaders.ts +++ b/packages/web/src/loaders.ts @@ -9,7 +9,7 @@ import { listAgents, listMcpClients, } from '@/client/agents-client'; -import {getConnection, listConnections} from '@/client/connections-client'; +import {getConnection, getMcpServer, listConnections} from '@/client/connections-client'; import {getDriveFileHistory, listDriveHistory} from '@/client/drive-history-client'; import {getFile, listFiles, listTrashedFiles} from '@/client/files-client'; import {getGitHubInstallations} from '@/client/github-client'; @@ -162,14 +162,25 @@ export const connectionLoader = later( error: shown?.isErr() ? describeApiError(shown.error) : null, }; }; - const [vaultEntries, vaultSecrets, sandboxes, github, files, history] = await Promise.all([ - kept(VAULT_INTEGRATION_ID, 'entries'), - kept(VAULT_INTEGRATION_ID, VAULT_SECRETS_COLLECTION_ID), - kept(SANDBOX_INTEGRATION_ID, 'sandboxes'), - reached(), - drive(), - driveHistory(), - ]); + // The server a custom MCP connection reaches, for its edit dialog; null for every other + // connection, for one the person only uses, which the api doesn't show them, and while the + // api can't read it, which leaves the page without the dialog rather than failing it. + const server = async () => { + if (found?.integrationId !== 'mcp') { + return null; + } + return (await getMcpServer(org, found.id)).unwrapOr(null); + }; + const [vaultEntries, vaultSecrets, sandboxes, github, files, history, mcpServer] = + await Promise.all([ + kept(VAULT_INTEGRATION_ID, 'entries'), + kept(VAULT_INTEGRATION_ID, VAULT_SECRETS_COLLECTION_ID), + kept(SANDBOX_INTEGRATION_ID, 'sandboxes'), + reached(), + drive(), + driveHistory(), + server(), + ]); return { connection: found, connections: unwrapLoaderResult(connections).connections, @@ -184,6 +195,7 @@ export const connectionLoader = later( github, files, history, + mcpServer, }; }, ); diff --git a/packages/web/src/pages/connection-page.test.tsx b/packages/web/src/pages/connection-page.test.tsx index 34270ce5..15ab750b 100644 --- a/packages/web/src/pages/connection-page.test.tsx +++ b/packages/web/src/pages/connection-page.test.tsx @@ -1,7 +1,7 @@ /// import type {AgentLogin} from '@proxy/contracts/agents'; -import type {Connection} from '@proxy/contracts/connections'; +import type {Connection, CustomMcpServer} from '@proxy/contracts/connections'; import type {Member} from '@proxy/contracts/orgs'; import type {DataRecord} from '@proxy/contracts/records'; import type {DriveHistoryLoaded} from '@/components/drive-history'; @@ -82,6 +82,7 @@ function renderConnectionPage( files: Drive | null = null, history: DriveHistoryLoaded | null = null, vaultSecrets: DataRecord[] | null = vaultEntries === null ? null : [], + mcpServer: CustomMcpServer | null = null, ) { const loads = {count: 0}; const router = createMemoryRouter( @@ -108,6 +109,7 @@ function renderConnectionPage( github, files, history, + mcpServer, }; }), shouldRevalidate: shouldRevalidateTabs, @@ -905,3 +907,115 @@ test('a custom MCP server’s All row saves the defaults of only the tools the s fetch.mockRestore(); } }); + +describe('editing a custom MCP server', () => { + const connection: Connection = { + ...mailbox, + integrationId: 'mcp', + account: 'mcp.example.com/mcp', + name: 'Example server', + defaults: [], + tools: [{name: 'read', inputSchema: {type: 'object'}}], + }; + const server: CustomMcpServer = {url: 'https://mcp.example.com/mcp', auth: 'token'}; + + // The page's edit route, answering it was saved. + function answerSaved() { + return spyOn(globalThis, 'fetch').mockResolvedValue( + new Response(JSON.stringify({kind: 'connected', connection}), { + headers: {'content-type': 'application/json'}, + }), + ); + } + + function edits(fetch: ReturnType): unknown[] { + return fetch.mock.calls + .filter(([url, options]) => String(url).endsWith('/server') && options?.method === 'PUT') + .map(([, options]) => JSON.parse(String(options?.body))); + } + + test('only a custom MCP server the person may change can be edited', async () => { + renderConnectionPage('/acme/connections/conn-1'); + await screen.findByRole('checkbox', {name: 'Read by default'}); + expect(screen.queryByRole('button', {name: 'Edit the server'})).toBeNull(); + }); + + test('sends only what changed: a new address keeps the token', async () => { + const fetch = answerSaved(); + try { + renderConnectionPage( + '/acme/connections/conn-1', + connection, + [claude], + null, + null, + null, + null, + null, + null, + server, + ); + fireEvent.click(await screen.findByRole('button', {name: 'Edit the server'})); + const address = await screen.findByLabelText('Server address'); + expect(address).toHaveProperty('value', 'https://mcp.example.com/mcp'); + fireEvent.change(address, {target: {value: 'https://mcp.example.com/v2/mcp'}}); + fireEvent.click(screen.getByRole('button', {name: 'Save'})); + await waitFor(() => expect(edits(fetch)).toEqual([{url: 'https://mcp.example.com/v2/mcp'}])); + } finally { + fetch.mockRestore(); + } + }); + + test('a new token alone leaves the address out', async () => { + const fetch = answerSaved(); + try { + renderConnectionPage( + '/acme/connections/conn-1', + connection, + [claude], + null, + null, + null, + null, + null, + null, + server, + ); + fireEvent.click(await screen.findByRole('button', {name: 'Edit the server'})); + fireEvent.change(await screen.findByLabelText('New access token'), { + target: {value: ' tok-2 '}, + }); + fireEvent.click(screen.getByRole('button', {name: 'Save'})); + await waitFor(() => expect(edits(fetch)).toEqual([{token: 'tok-2'}])); + } finally { + fetch.mockRestore(); + } + }); + + test('removing the token sends none', async () => { + const fetch = answerSaved(); + try { + renderConnectionPage( + '/acme/connections/conn-1', + connection, + [claude], + null, + null, + null, + null, + null, + null, + server, + ); + fireEvent.click(await screen.findByRole('button', {name: 'Edit the server'})); + fireEvent.click(await screen.findByText('Remove the token')); + await waitFor(() => + expect(screen.getByLabelText('New access token')).toHaveProperty('disabled', true), + ); + fireEvent.click(screen.getByRole('button', {name: 'Save'})); + await waitFor(() => expect(edits(fetch)).toEqual([{token: null}])); + } finally { + fetch.mockRestore(); + } + }); +}); diff --git a/packages/web/src/pages/connection-page.tsx b/packages/web/src/pages/connection-page.tsx index d08cef3b..39c4ca0e 100644 --- a/packages/web/src/pages/connection-page.tsx +++ b/packages/web/src/pages/connection-page.tsx @@ -1,5 +1,5 @@ import type {Connection} from '@proxy/contracts/connections'; -import {ListRestartIcon, UnplugIcon} from 'lucide-react'; +import {ListRestartIcon, PencilIcon, UnplugIcon} from 'lucide-react'; import type {FetchError} from '@proxy/utils'; import {useState} from 'react'; import {useNavigate, useSearchParams} from 'react-router'; @@ -17,6 +17,7 @@ import {ConnectWithKeyDialog} from '@/components/connect-with-key-dialog'; import {SignInAgain} from '@/components/connection-access'; import {ConnectionSharing} from '@/components/connection-sharing'; import {ConfirmDialog} from '@/components/confirm-dialog'; +import {EditMcpServerDialog} from '@/components/edit-mcp-server-dialog'; import {GitHubRepositories} from '@/components/github-repositories'; import {IconButton} from '@/components/icon-button'; import {IntegrationLogo} from '@/components/brand-logo'; @@ -64,6 +65,7 @@ function ConnectionDetail() { github, files, history, + mcpServer, } = useLoaded(); const navigate = useNavigate(); const reload = useReload(); @@ -73,6 +75,8 @@ function ConnectionDetail() { const [disconnecting, setDisconnecting] = useState(false); const [refreshing, setRefreshing] = useState(false); const [replacingKey, setReplacingKey] = useState(false); + // Open from the start when the desktop app handed its sign-in over to the browser (`?server=edit`). + const [editingServer, setEditingServer] = useState(searchParams.get('server') === 'edit'); const [error, setError] = useState(null); // Where the shown part puts its own buttons, on the tabs' row. const [toolbar, setToolbar] = useState(null); @@ -185,6 +189,11 @@ function ConnectionDetail() { } actions={ <> + {mcpServer !== null && mayChange && ( + setEditingServer(true)}> + + + )} {integration.custom && mayChange && ( )} + {editingServer && mcpServer !== null && mayChange && ( + setEditingServer(false)} + onSaved={async () => { + setEditingServer(false); + await reload(); + }} + /> + )} {tab === 'entries' && vaultEntries !== null && (