diff --git a/packages/api/src/agent-side/tools.test.ts b/packages/api/src/agent-side/tools.test.ts index fc898226..1be2ee7e 100644 --- a/packages/api/src/agent-side/tools.test.ts +++ b/packages/api/src/agent-side/tools.test.ts @@ -1,4 +1,4 @@ -import {beforeEach, describe, expect, mock, test} from 'bun:test'; +import {afterEach, beforeEach, describe, expect, mock, spyOn, test} from 'bun:test'; import {Err, Ok, type Result} from 'ts-results-es'; import {ApiErr, type ApiError} from '@proxy/utils'; @@ -27,7 +27,14 @@ mock.module('@proxy/db/task', () => ({ const listConnectionsWithCredential = mock(); const markCredentialRejected = mock(async () => Ok(true)); -mock.module('@proxy/db/connection', () => ({markCredentialRejected, listConnectionsWithCredential, updateConnectionCredential: mock(), getConnectionCredential: mock(async () => Ok(null))})); +const updateConnectionTools = mock(async () => Ok(undefined)); +mock.module('@proxy/db/connection', () => ({ + markCredentialRejected, + listConnectionsWithCredential, + updateConnectionCredential: mock(), + getConnectionCredential: mock(async () => Ok(null)), + updateConnectionTools, +})); // Readable stand-ins for encryption, so a test can write the credential it means. mock.module('../utils/secret-crypto', () => ({ @@ -43,8 +50,9 @@ mock.module('../records/target', () => ({loadConnection})); mock.module('../records/connectors', () => ({connectorFor: () => connector})); const callCustomTool = mock(); +const listCustomTools = mock(); -mock.module('../connections/custom/custom-mcp', () => ({callCustomTool})); +mock.module('../connections/custom/custom-mcp', () => ({callCustomTool, listCustomTools})); // Of the integrations' modules, Google's partial consent alone, read from its credential. const {unavailableGoogleConnectionActions} = await import('../connections/google/unavailable'); @@ -53,6 +61,8 @@ const apiIntegration = mock((id: string): unknown => (id === 'google' ? {id, con mock.module('../connections/integrations', () => ({apiIntegration})); +const {forgetAskedForTests} = await import('../connections/custom/refresh-tools'); + function integration(id: string): Integration { const found = findIntegration(id); if (!found) { @@ -707,9 +717,11 @@ describe('custom MCP servers', () => { }; beforeEach(() => { + forgetAskedForTests(); loadConnection.mockResolvedValue(Ok({connection: customConnection, integration: integrationFor({integrationId: 'mcp', tools: [search, publish]})})); listConnectionsWithCredential.mockResolvedValue(Ok([customConnection])); callCustomTool.mockResolvedValue(Ok('3 results')); + listCustomTools.mockResolvedValue(Ok([search, publish])); }); test('lists the connection with the tools the agent may run as its actions, and only those tools', async () => { @@ -764,6 +776,151 @@ describe('custom MCP servers', () => { expect(failed).toEqual(ApiErr.validationError('query is required')); expect(logAgentRequest).toHaveBeenCalledTimes(1); expect(logAgentRequest.mock.calls[0]?.[0]).toMatchObject({collectionId: 'tools', action: 'search_docs', query: null, outcome: 'failed', error: 'validation_error'}); + expect(listCustomTools).not.toHaveBeenCalled(); + }); +}); + +// A custom server's tools, kept on the connection, asked for again as they may have changed. +describe("a custom MCP server's tools asked for again", () => { + const search = {name: 'search_docs', inputSchema: {type: 'object', properties: {query: {type: 'string'}}}, annotations: {readOnlyHint: true}}; + const publish = {name: 'publish_doc', inputSchema: {type: 'object', properties: {id: {type: 'string'}}}}; + const timeline = {name: 'get_timeline', inputSchema: {type: 'object', properties: {id: {type: 'string'}}}, annotations: {readOnlyHint: true}}; + const customConnection = { + id: 'mcp-1', + integrationId: 'mcp', + orgId: 'org-1', + ownerUserId: 'user-1', + sharedWithEveryone: false, + shares: [], + account: 'mcp.example.com/mcp', + createdAt: new Date(), + tools: JSON.stringify([search, publish]), + name: null, + defaults: [{actionId: 'search_docs'}], + credentialRejectedAt: null, + credential: 'v1.x.y.z', + }; + let clock = 0; + let now: ReturnType>; + + beforeEach(() => { + forgetAskedForTests(); + clock = Date.UTC(2026, 10, 21); + now = spyOn(Date, 'now').mockImplementation(() => clock); + loadConnection.mockResolvedValue(Ok({connection: customConnection, integration: integrationFor({integrationId: 'mcp', tools: [search, publish]})})); + callCustomTool.mockResolvedValue(Ok('3 results')); + listCustomTools.mockResolvedValue(Ok([search, publish, timeline])); + }); + + afterEach(() => { + now.mockRestore(); + }); + + test('an agent reading them has the server asked again once they are an hour old, and keeps what it lists', async () => { + const {listAgentTools} = await import('./tools'); + expect((await listAgentTools(signedIn, 'mcp-1')).unwrap().map((tool) => tool.name)).toEqual(['search_docs']); + expect(updateConnectionTools).toHaveBeenCalledWith({connectionId: 'mcp-1', tools: JSON.stringify([search, publish, timeline]), actions: ['search_docs', 'publish_doc', 'get_timeline']}); + + clock += 59 * 60 * 1000; + await listAgentTools(signedIn, 'mcp-1'); + expect(listCustomTools).toHaveBeenCalledTimes(1); + + clock += 2 * 60 * 1000; + await listAgentTools(signedIn, 'mcp-1'); + expect(listCustomTools).toHaveBeenCalledTimes(2); + }); + + test('a server that can’t be asked leaves the kept list to read, and isn’t asked again at once', async () => { + listCustomTools.mockResolvedValue(Err(ApiErr.providerUnreachable(new Error('down')))); + const {listAgentTools} = await import('./tools'); + expect((await listAgentTools(signedIn, 'mcp-1')).unwrap().map((tool) => tool.name)).toEqual(['search_docs']); + await listAgentTools(signedIn, 'mcp-1'); + + expect(listCustomTools).toHaveBeenCalledTimes(1); + expect(updateConnectionTools).not.toHaveBeenCalled(); + }); + + test('two reads at once ask the server once', async () => { + const {listAgentTools} = await import('./tools'); + await Promise.all([listAgentTools(signedIn, 'mcp-1'), listAgentTools(signedIn, 'mcp-1')]); + + expect(listCustomTools).toHaveBeenCalledTimes(1); + }); + + test('a call naming a tool the list lacks asks the server again, and finds one it added, off until the person turns it on', async () => { + const {runAgentTool} = await import('./tools'); + expect((await runAgentTool(caller, 'mcp-1', 'get_timeline', {id: 'rec-1'})).unwrapErr().kind).toBe('forbidden'); + + expect(listCustomTools).toHaveBeenCalledTimes(1); + expect(callCustomTool).not.toHaveBeenCalled(); + expect(logAgentRequest.mock.calls[0]?.[0]).toMatchObject({action: 'get_timeline', outcome: 'denied'}); + }); + + test('a call naming a tool the server doesn’t list either is not found, and asks again no sooner than a minute later', async () => { + listCustomTools.mockResolvedValue(Ok([search, publish])); + const {runAgentTool} = await import('./tools'); + expect((await runAgentTool(caller, 'mcp-1', 'get_everything', {})).unwrapErr()).toMatchObject({kind: 'not_found', resource: 'tool'}); + await runAgentTool(caller, 'mcp-1', 'get_everything', {}); + expect(listCustomTools).toHaveBeenCalledTimes(1); + + clock += 61 * 1000; + await runAgentTool(caller, 'mcp-1', 'get_everything', {}); + expect(listCustomTools).toHaveBeenCalledTimes(2); + expect(logAgentRequest).not.toHaveBeenCalled(); + }); + + test('a tool the server says it no longer has, and no longer lists, is not found; one it still lists fails as the server said', async () => { + const gone = ApiErr.validationError('MCP error -32602: Tool search_docs not found'); + callCustomTool.mockResolvedValue(Err(gone)); + listCustomTools.mockResolvedValue(Ok([publish, timeline])); + const {runAgentTool} = await import('./tools'); + expect((await runAgentTool(caller, 'mcp-1', 'search_docs', {query: 'q'})).unwrapErr()).toMatchObject({kind: 'not_found', resource: 'tool', id: 'search_docs'}); + expect(updateConnectionTools).toHaveBeenCalledWith({connectionId: 'mcp-1', tools: JSON.stringify([publish, timeline]), actions: ['publish_doc', 'get_timeline']}); + expect(logAgentRequest.mock.calls[0]?.[0]).toMatchObject({action: 'search_docs', outcome: 'failed'}); + + forgetAskedForTests(); + listCustomTools.mockResolvedValue(Ok([search, publish])); + expect((await runAgentTool(caller, 'mcp-1', 'search_docs', {query: 'q'})).unwrapErr()).toEqual(gone); + }); + + test('a tool failing for any other reason doesn’t ask the server for its tools', async () => { + callCustomTool.mockResolvedValue(Err(ApiErr.validationError('No card abc was found'))); + const {runAgentTool} = await import('./tools'); + await runAgentTool(caller, 'mcp-1', 'search_docs', {query: 'q'}); + + expect(listCustomTools).not.toHaveBeenCalled(); + }); + + test('refreshAgentTools asks the server now, answering with the tools the agent has and the names of the rest', async () => { + const {listAgentTools, refreshAgentTools} = await import('./tools'); + await listAgentTools(signedIn, 'mcp-1'); + const refreshed = (await refreshAgentTools(signedIn, 'mcp-1')).unwrap(); + + expect(listCustomTools).toHaveBeenCalledTimes(2); + expect(refreshed.tools.map((tool) => tool.name)).toEqual(['search_docs']); + expect(refreshed.notAllowed.toSorted()).toEqual(['get_timeline', 'publish_doc']); + }); + + test('refreshAgentTools passes on what the server failed with, noting a sign-in it turned down', async () => { + listCustomTools.mockResolvedValue(Err(ApiErr.credentialsRejected())); + const {refreshAgentTools} = await import('./tools'); + + expect((await refreshAgentTools(signedIn, 'mcp-1')).unwrapErr().kind).toBe('credentials_rejected'); + expect(markCredentialRejected).toHaveBeenCalledWith({connectionId: 'mcp-1', credential: 'v1.x.y.z'}); + }); + + test('refreshAgentTools refuses a built-in integration’s connection, one the agent can do nothing with, and one to sign in to again, without asking', async () => { + const {refreshAgentTools} = await import('./tools'); + useConnection(vaultConnection); + expect((await refreshAgentTools(signedIn, 'vault-1')).unwrapErr().kind).toBe('validation_error'); + + loadConnection.mockResolvedValue(Ok({connection: {...customConnection, defaults: []}, integration: integrationFor({integrationId: 'mcp', tools: [search, publish]})})); + expect((await refreshAgentTools(signedIn, 'mcp-1')).unwrapErr()).toMatchObject({kind: 'not_found', resource: 'connection'}); + + loadConnection.mockResolvedValue(Ok({connection: {...customConnection, credentialRejectedAt: new Date()}, integration: integrationFor({integrationId: 'mcp', tools: [search, publish]})})); + expect((await refreshAgentTools(signedIn, 'mcp-1')).isErr()).toBe(true); + + expect(listCustomTools).not.toHaveBeenCalled(); }); }); diff --git a/packages/api/src/agent-side/tools.ts b/packages/api/src/agent-side/tools.ts index 69ffff0e..fa3a8e30 100644 --- a/packages/api/src/agent-side/tools.ts +++ b/packages/api/src/agent-side/tools.ts @@ -27,6 +27,7 @@ import { } from '@proxy/integrations'; import {callCustomTool} from '../connections/custom/custom-mcp'; +import {listsOwnTools, refreshCustomTools, unlessToolGone, withFreshTools, withToolListed} from '../connections/custom/refresh-tools'; import {apiIntegration} from '../connections/integrations'; import {toolMetrics} from '../observability/metrics'; import {noteRejectedSignIn} from '../connections/rejected-sign-in'; @@ -115,15 +116,49 @@ export function listAgentConnections(signedIn: SignedInAgent): Promise> { return Do(async ($) => { const agent = $(await requireAgent(signedIn)); - const {connection, integration} = $(await loadConnection(agentViewer(signedIn), connectionId)); + const {connection, integration} = await withFreshTools($(await loadConnection(agentViewer(signedIn), connectionId))); return allowedTools(integration, actionsOf(agent, connection, integration, unavailableActions(connection))); }); } +/** A custom server's tools asked for again: those the agent has now, and the names of the rest, which the person can turn on. */ +export type RefreshedTools = {tools: Tool[]; notAllowed: string[]}; + +/** + * Asks a custom MCP server for its tools again and keeps the new list, as the person can from the + * connection's page, for an agent that can use the connection, or could once it is signed in to + * again; any other is not found, as it isn't among the agent's connections. Any other integration's + * tools are built in, so there is nothing to ask for. + */ +export function refreshAgentTools(signedIn: SignedInAgent, connectionId: string): Promise> { + return Do(async ($) => { + const agent = $(await requireAgent(signedIn)); + const {connection, integration} = $(await loadConnection(agentViewer(signedIn), connectionId)); + if (actionsOf(agent, connection, integration, []).length === 0) { + return $(Err(ApiErr.notFound('connection', connectionId))); + } + if (!listsOwnTools(connection)) { + return $(Err(ApiErr.validationError(`${integration.name}’s tools are built in: only a custom MCP server’s can be asked for again.`))); + } + if (needsSignIn(connection)) { + return $(Err(signInNeededError(integration, connection.account))); + } + const refreshed = $(await refreshCustomTools(connection)); + const actions = actionsOf(agent, refreshed.connection, refreshed.integration, unavailableActions(refreshed.connection)); + return { + tools: allowedTools(refreshed.integration, actions), + notAllowed: refreshed.integration.actions.map((action) => action.id).filter((id) => !actions.includes(id)), + }; + }); +} + // Who calls and which way it came in: the web app's agent page, the MCP server, the built-in // agent's own loop, or code in a sandbox, with the CLI's token (cli/route.ts). export type AgentCaller = {agent: SignedInAgent; via: 'web' | 'mcp' | 'harness' | 'cli'}; @@ -244,10 +279,14 @@ export function runAgentTool(caller: TaskCaller, connectionId: string, toolName: ]); const agent = $(agentRead); $(taskRead); - const {connection, integration} = $(connectionRead); + // A custom server's tool the kept list lacks may be one the server added since. + const loaded = await withToolListed($(connectionRead), toolName); + const {connection, integration} = loaded; const tool = $(requirePresent(findTool(integration, toolName), ApiErr.notFound('tool', toolName))); if (tool.kind === 'call' || tool.kind === 'native') { - return $(await noteRejectedSignIn(connection, connection.credential, await runParamsTool({caller, agent, connection, integration, startedAt}, tool, params))); + const ran = await noteRejectedSignIn(connection, connection.credential, await runParamsTool({caller, agent, connection, integration, startedAt}, tool, params)); + // And one it has may be one the server took away since. + return $(tool.kind === 'call' ? await unlessToolGone(loaded, toolName, ran) : ran); } const collection = $(requirePresent(findCollection(integration, tool.collectionId), ApiErr.notFound('tool', toolName))); diff --git a/packages/api/src/cli/route.test.ts b/packages/api/src/cli/route.test.ts index fb7b171c..539f69c0 100644 --- a/packages/api/src/cli/route.test.ts +++ b/packages/api/src/cli/route.test.ts @@ -41,9 +41,10 @@ mock.module('../agent-side/tasks', () => ({...realTasks, requireOpenTask})); const listAgentConnections = mock(); const listAgentTools = mock(); +const refreshAgentTools = mock(); const runAgentTool = mock(); -mock.module('../agent-side/tools', () => ({...realTools, listAgentConnections, listAgentTools, runAgentTool})); +mock.module('../agent-side/tools', () => ({...realTools, listAgentConnections, listAgentTools, refreshAgentTools, runAgentTool})); const loadConnection = mock(); @@ -251,6 +252,14 @@ describe('POST /api/cli/call', () => { expect(listAgentTools).toHaveBeenCalledWith(signedIn, 'mail-1'); }); + test('refreshTools asks a custom server for its tools again', async () => { + refreshAgentTools.mockResolvedValue(Ok({tools: [], notAllowed: ['get_timeline']})); + const res = await call({method: 'refreshTools', args: ['mcp-1']}); + + expect(res).toEqual({status: 200, body: {result: {tools: [], notAllowed: ['get_timeline']}}}); + expect(refreshAgentTools).toHaveBeenCalledWith(signedIn, 'mcp-1'); + }); + test('a Sandboxes connection’s tools are refused from inside a sandbox', async () => { const tools = await call({method: 'tools', args: ['sandboxes-1']}); const run = await call({method: 'call', args: ['sandboxes-1', 'sandbox_exec', {sandbox: 'sandbox-1', command: 'ls'}]}); diff --git a/packages/api/src/connections/custom/refresh-tools.ts b/packages/api/src/connections/custom/refresh-tools.ts new file mode 100644 index 00000000..5c72005d --- /dev/null +++ b/packages/api/src/connections/custom/refresh-tools.ts @@ -0,0 +1,145 @@ +import {Err, type Result} from 'ts-results-es'; + +import {ApiErr, type ApiError, Do, requirePresent} from '@proxy/utils'; +import {type ConnectionRow, updateConnectionTools} from '@proxy/db/connection'; +import {findTool} from '@proxy/integrations'; + +import {log} from '../../observability/log'; +import type {LoadedConnection} from '../../records/target'; +import {integrationOf} from '../../utils/connection-actions'; +import {noteRejectedSignIn} from '../rejected-sign-in'; +import {needsSignIn} from '../unavailable'; +import {listCustomTools} from './custom-mcp'; + +/** + * A custom MCP server's tools as its connection keeps them, asked for again for agents, as the + * person does from the connection's page (route.ts): by an agent itself (`pap.refreshTools`); by + * an agent reading them once the list is an hour old; and, at most once a minute, by a call naming + * a tool the list lacks, or one the server says it doesn't have, since a server adds and takes away + * tools without telling anyone. The new list replaces + * the old as the page's does: what agents may do with a tool the server no longer lists is dropped, + * and one it lists now is off until the person turns it on. + * + * When each connection was last asked is kept by this instance alone, so another instance, or this + * one once restarted, may ask again sooner; asking is cheap and changes nothing when the list is + * the same. A connection asked for twice at once is asked once. + */ + +/** How old a connection's tools may be before an agent reading them has the server asked again. */ +const TOOLS_MAX_AGE_MS = 60 * 60 * 1000; + +/** How soon after the server was last asked a call naming a tool it lacks may ask again. */ +const MISSING_TOOL_RETRY_MS = 60 * 1000; + +const CUSTOM_MCP = 'mcp'; + +type StoredConnection = ConnectionRow & {credential: string | null}; + +// When this instance last asked each connection's server, whatever it answered, so a server that +// is down isn't asked again on every read. +const askedAt = new Map(); + +// The asking under way for each connection, which a second ask waits for. +const asking = new Map>>(); + +/** Whether the connection is a custom MCP server's, whose tools can be asked for again. */ +export function listsOwnTools(connection: Pick): boolean { + return connection.integrationId === CUSTOM_MCP; +} + +// Asks the server for its tools and keeps them, the connection given back with them; a sign-in the +// server turns down is noted on the connection, as a tool run's is. +function askAndKeep(connection: StoredConnection): Promise> { + return Do(async ($) => { + askedAt.set(connection.id, Date.now()); + const tools = $(await noteRejectedSignIn(connection, connection.credential, await listCustomTools(connection))); + const stored = JSON.stringify(tools); + $(await updateConnectionTools({connectionId: connection.id, tools: stored, actions: tools.map((tool) => tool.name)})); + const refreshed = {...connection, tools: stored}; + const integration = $(requirePresent(integrationOf(refreshed), ApiErr.notFound('connection', connection.id))); + return {connection: refreshed, integration}; + }); +} + +/** + * Asks a custom MCP server for its tools now and keeps the new list, the connection given back with + * its integration built from it. The caller checks it is one (`listsOwnTools`). + */ +export function refreshCustomTools(connection: StoredConnection): Promise> { + const running = asking.get(connection.id); + if (running) { + return running; + } + const started = askAndKeep(connection).finally(() => asking.delete(connection.id)); + asking.set(connection.id, started); + return started; +} + +// The connection with its tools asked for again where the server was last asked longer than +// `maxAgeMs` ago, by this instance; as it was where it isn't a custom server's, needs signing in +// to again, or asking fails, which is logged: the kept list is still the best there is. +async function refreshedIfOlder(loaded: LoadedConnection, maxAgeMs: number): Promise { + const {connection} = loaded; + if (!listsOwnTools(connection) || needsSignIn(connection)) { + return loaded; + } + const last = askedAt.get(connection.id); + if (last !== undefined && Date.now() - last < maxAgeMs) { + return loaded; + } + const refreshed = await refreshCustomTools(connection); + if (refreshed.isErr()) { + log.warn('A custom MCP server’s tools could not be asked for again', {connectionId: connection.id, errorKind: refreshed.error.kind}); + return loaded; + } + return refreshed.value; +} + +/** The connection, with a custom server's tools asked for again where the list is older than an hour. */ +export function withFreshTools(loaded: LoadedConnection): Promise { + return refreshedIfOlder(loaded, TOOLS_MAX_AGE_MS); +} + +/** + * The connection, with a custom server's tools asked for again where they lack `toolName` and the + * server wasn't asked in the last minute, so a tool it added since is found. + */ +export function withToolListed(loaded: LoadedConnection, toolName: string): Promise { + if (findTool(loaded.integration, toolName)) { + return Promise.resolve(loaded); + } + return refreshedIfOlder(loaded, MISSING_TOOL_RETRY_MS); +} + +// Whether a tool's failure is the server saying it has no such tool: the MCP spec's code for it, +// Invalid params, or words naming the tool as unknown or not found. A failure taken for one wrongly +// only has the server asked again, once a minute at most, and is answered as it was. +function saysToolIsGone(error: ApiError, toolName: string): boolean { + const said = 'message' in error ? (error.message ?? '') : ''; + if (said.includes('-32602')) { + return true; + } + return said.includes(toolName) && /\b(not found|unknown|no such)\b/i.test(said); +} + +/** + * What a custom server's tool answered, but not found where the server said it has no such tool + * and, asked for its tools again, no longer lists it, so the agent is told as for any tool the list + * lacks. Any other answer is passed on as it was. + */ +export async function unlessToolGone(loaded: LoadedConnection, toolName: string, answer: Result): Promise> { + if (answer.isOk() || !saysToolIsGone(answer.error, toolName)) { + return answer; + } + const refreshed = await refreshedIfOlder(loaded, MISSING_TOOL_RETRY_MS); + if (findTool(refreshed.integration, toolName)) { + return answer; + } + return Err(ApiErr.notFound('tool', toolName)); +} + +/** Forgets when each server was asked, for tests. */ +export function forgetAskedForTests(): void { + askedAt.clear(); + asking.clear(); +} diff --git a/packages/api/src/connections/custom/route.ts b/packages/api/src/connections/custom/route.ts index 15c931df..a521aa1f 100644 --- a/packages/api/src/connections/custom/route.ts +++ b/packages/api/src/connections/custom/route.ts @@ -3,7 +3,6 @@ import {Err, type Result} from 'ts-results-es'; import {z} from 'zod'; import {ApiErr, type ApiError, Do, parseSchema} from '@proxy/utils'; -import {updateConnectionTools} from '@proxy/db/connection'; import {type Connection, connectMcpBodySchema, type connectMcpSchema} from '@proxy/contracts/connections'; import type {AuthenticatedRequest} from '../../server/middleware/require-auth'; @@ -17,8 +16,9 @@ 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 {listCustomTools, mcpAccount, readOnlyToolNames, type CustomCredential} from './custom-mcp'; +import {mcpAccount, readOnlyToolNames, type CustomCredential} from './custom-mcp'; import {discoverMcpServer, parseMcpServerUrl, probeMcpServer} from './mcp-discovery'; +import {refreshCustomTools} from './refresh-tools'; /** * Connecting a custom MCP server by its address, under a name the person gives it, since a server @@ -101,9 +101,7 @@ export function handleRefreshCustomMcpToolsRoute(request: AuthenticatedRequest): const viewer = $(await requireViewer(request)); const connectionId = request.params.connectionId ?? ''; const row = $(await requireManagedOf(viewer, connectionId, 'mcp', ApiErr.validationError('Only a custom MCP server has tools to ask for again'))); - const tools = $(await listCustomTools(row)); - const stored = JSON.stringify(tools); - $(await updateConnectionTools({connectionId, tools: stored, actions: tools.map((tool) => tool.name)})); - return $(await respond({...row, tools: stored})); + const {connection} = $(await refreshCustomTools(row)); + return $(await respond(connection)); }); } diff --git a/packages/api/src/mcp/route.test.ts b/packages/api/src/mcp/route.test.ts index e7119ce9..968ee399 100644 --- a/packages/api/src/mcp/route.test.ts +++ b/packages/api/src/mcp/route.test.ts @@ -11,7 +11,8 @@ const listAgentConnections = mock(); const listAgentTools = mock(); const runAgentTool = mock(); -mock.module('../agent-side/tools', () => ({agentViewer: mock(), listAgentConnections, listAgentTools, runAgentTool})); +const refreshAgentTools = mock(); +mock.module('../agent-side/tools', () => ({agentViewer: mock(), listAgentConnections, listAgentTools, refreshAgentTools, runAgentTool})); const sendAgentFeedback = mock(); @@ -325,6 +326,28 @@ describe('handleMcpRoute', () => { }); }); + test('asks a custom server for its tools again, for an open task, answering with those the agent has and the names of the rest', async () => { + refreshAgentTools.mockResolvedValue( + Ok({ + tools: [{name: 'search_docs', title: 'Search docs', description: 'Searches the docs', readOnly: true, risk: 'low', inputSchema: {type: 'object', properties: {}}}], + notAllowed: ['get_timeline'], + }), + ); + const answer = await script(`const {tools, notAllowed} = await pap.refreshTools('mcp-1'); return {tools: tools.map((tool) => tool.name), notAllowed};`, 'task-1'); + + expect(requireOpenTask).toHaveBeenCalledWith(signedIn, 'task-1'); + expect(refreshAgentTools).toHaveBeenCalledWith(signedIn, 'mcp-1'); + expect(JSON.parse(answer.text)).toEqual({tools: ['search_docs'], notAllowed: ['get_timeline']}); + }); + + test('asking for tools again needs an open task, and is refused before the server is asked', async () => { + requireOpenTask.mockResolvedValue(Err(ApiErr.notFound('task', 'task-9'))); + const answer = await script(`return await pap.refreshTools('mcp-1');`, 'task-9'); + + expect(answer.text).toContain('No task task-9'); + expect(refreshAgentTools).not.toHaveBeenCalled(); + }); + test('finishes the script’s task and sends feedback for it', async () => { sendAgentFeedback.mockResolvedValue(Ok({sent: true})); const answer = await script(`await pap.feedback({message: 'emails_list ignored the folder', tool: 'emails_list'}); return await pap.finishTask({outcome: 'Archived 12 newsletters'});`, 'task-1'); diff --git a/packages/api/src/mcp/tools.ts b/packages/api/src/mcp/tools.ts index 2270aeae..8bb40f12 100644 --- a/packages/api/src/mcp/tools.ts +++ b/packages/api/src/mcp/tools.ts @@ -58,6 +58,7 @@ export function scriptToolDescription(via: 'mcp' | 'web' | 'harness'): string { : []), 'pap.connections() → [{connection, integration, name?, account, shared, can}]', 'pap.tools(connection) → [{name, description, params}], params as JSON Schema', + 'pap.refreshTools(connection) → {tools, notAllowed}: asks a custom MCP server for its tools again, when they seem out of date; notAllowed names the ones the person hasn’t turned on for you.', 'pap.call(connection, tool, params?) → what the tool answers', ...(withTasks ? ['pap.finishTask({outcome?}): ends the task, saying what was done.'] : []), 'pap.feedback({message, connection?, tool?}): tells the makers of Personal Agent Proxy what didn’t work as expected.', diff --git a/packages/api/src/script/agent-host.ts b/packages/api/src/script/agent-host.ts index 1c680c74..56e83d00 100644 --- a/packages/api/src/script/agent-host.ts +++ b/packages/api/src/script/agent-host.ts @@ -10,7 +10,7 @@ import {sendAgentFeedback} from '../agent-side/feedback'; import {blobDownloadUrl, blobUploadUrl, ownerOf} from '../blobs/blobs'; import {connectionSummary, toolSummary} from '../agent-side/summaries'; import {finishAgentTask, requireOpenTask, startAgentTask} from '../agent-side/tasks'; -import {type AgentCaller, agentViewer, listAgentConnections, listAgentTools, runAgentTool} from '../agent-side/tools'; +import {type AgentCaller, agentViewer, listAgentConnections, listAgentTools, refreshAgentTools, runAgentTool} from '../agent-side/tools'; import {log, serializeError} from '../observability/log'; import {loadConnection} from '../records/target'; import {jsonSchema, type Json} from './protocol'; @@ -25,6 +25,8 @@ import type {PapAnswer, ScriptHost} from './run-script'; * - `pap.finishTask({outcome?})`: finishes the script's task. * - `pap.connections()`: the connections the agent can use. * - `pap.tools(connection)`: a connection's tools. + * - `pap.refreshTools(connection)`: a custom MCP server's tools asked for again, and kept: those + * the agent has now, and the names of the ones it hasn't, which the person can turn on. * - `pap.call(connection, tool, params?)`: runs a tool, one that reads or one that changes something. * - `pap.feedback({message, connection?, tool?})`: feedback for the makers of Personal Agent Proxy. * - `pap.upload()`: a URL to PUT files to, each made a blob of the agent's (blobs/). @@ -47,6 +49,7 @@ const NO_SANDBOXES = 'Sandboxes can’t be used from inside a sandbox: run sandb const ARGS = { connections: z.tuple([]), tools: z.tuple([z.string().min(1)]), + refreshTools: z.tuple([z.string().min(1)]), call: z.tuple([z.string().min(1), z.string().min(1), z.record(z.string(), jsonSchema).optional()]), startTask: z.tuple([z.object({title: z.string(), goal: z.string(), parent: z.string().optional()})]), finishTask: z.tuple([z.object({outcome: z.string().optional()}).optional()]), @@ -61,6 +64,7 @@ const ARGS = { const SCRIPT_USAGE: Record = { connections: 'pap.connections()', tools: 'pap.tools(connection)', + refreshTools: 'pap.refreshTools(connection)', call: 'pap.call(connection, tool, params)', startTask: 'pap.startTask({title, goal, parent?})', finishTask: 'pap.finishTask({outcome?})', @@ -73,6 +77,7 @@ const CLI_USAGE: Record = { ...SCRIPT_USAGE, connections: '`pap connections`', tools: '`pap tools `', + refreshTools: '`pap tools --refresh`', call: '`pap call [json]`', feedback: '`pap feedback [--connection ] [--tool ]`', upload: '`pap upload `', @@ -206,6 +211,16 @@ function answer(signedIn: SignedInAgent, options: HostOptions, state: HostState, $(task); return $(tools).map(toolSummary); } + if (method === 'refreshTools') { + const [connection] = $(argsOf(options.via, method, ARGS.refreshTools, args)); + if (!options.sandboxes) { + $(await refuseSandboxes(signedIn, connection)); + } + // The task first, as asking the server changes what the connection keeps. + $(await requireOpenTask(signedIn, taskId)); + const {tools, notAllowed} = $(await refreshAgentTools(signedIn, connection)); + return {tools: tools.map(toolSummary), notAllowed}; + } const [connection, tool, params] = $(argsOf(options.via, method, ARGS.call, args)); if (!options.sandboxes) { $(await refuseSandboxes(signedIn, connection)); diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index f3152aff..0ed74394 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -139,7 +139,7 @@ async function filesMain(args: string[], io: Io): Promise { } const CONNECTIONS = 'pap connections'; -const TOOLS = 'pap tools '; +const TOOLS = 'pap tools [--refresh]'; const CALL = 'pap call [json|-] [--all]'; const FEEDBACK = 'pap feedback [--connection ] [--tool ]'; @@ -158,12 +158,16 @@ export const COMMANDS: Record = { tools: jsonCommand('tools', { usage: TOOLS, summary: "a connection's tools and their params", - help: `${TOOLS}\nA connection's tools, with the params each takes.\n`, - flags: {}, + help: `${TOOLS} +A connection's tools, with the params each takes. +--refresh for a custom MCP server: asks it for its tools again, as {tools, notAllowed}, notAllowed the ones the person hasn't turned on for you. +`, + flags: {refresh: 'switch'}, run: (parsed, io) => Do(async ($) => { const [connection = ''] = $(positionals(parsed, 1, 1, TOOLS)); - return $(await $(clientFrom(io)).call('tools', [connection])); + const method = parsed.switches.has('refresh') ? 'refreshTools' : 'tools'; + return $(await $(clientFrom(io)).call(method, [connection])); }), }), call: jsonCommand('call', { diff --git a/packages/cli/src/run.test.ts b/packages/cli/src/run.test.ts index 39c17123..5a9eeaa4 100644 --- a/packages/cli/src/run.test.ts +++ b/packages/cli/src/run.test.ts @@ -42,10 +42,11 @@ describe('pap', () => { expect(output).toEqual({out: '[{"connection":"mail-1","integration":"Email"}]\n', err: ''}); }); - test('tools, call and feedback send their arguments as a script passes them', async () => { + test('tools, a refresh of them, call and feedback send their arguments as a script passes them', async () => { const {sent, pap} = harness(() => ok(null)); await pap('tools', 'mail-1'); + await pap('tools', 'mcp-1', '--refresh'); await pap('call', 'mail-1', 'emails_list', '{"search":"invoice"}'); await pap('call', 'mail-1', 'emails_list'); await pap( @@ -62,6 +63,7 @@ describe('pap', () => { expect(sent.map((one) => one.body)).toEqual([ {method: 'tools', args: ['mail-1']}, + {method: 'refreshTools', args: ['mcp-1']}, {method: 'call', args: ['mail-1', 'emails_list', {search: 'invoice'}]}, {method: 'call', args: ['mail-1', 'emails_list', {}]}, { diff --git a/packages/contracts/src/cli-constants.ts b/packages/contracts/src/cli-constants.ts index 33ec3daa..0ee1b380 100644 --- a/packages/contracts/src/cli-constants.ts +++ b/packages/contracts/src/cli-constants.ts @@ -7,6 +7,7 @@ export const PAP_METHODS = [ 'connections', 'tools', + 'refreshTools', 'call', 'startTask', 'finishTask', diff --git a/packages/contracts/src/cli.ts b/packages/contracts/src/cli.ts index c465cb49..de71b3b0 100644 --- a/packages/contracts/src/cli.ts +++ b/packages/contracts/src/cli.ts @@ -25,6 +25,8 @@ export { * - `{method: 'connections', args: []}`: the connections the agent can use, a sandbox's own * Sandboxes connection left out. * - `{method: 'tools', args: [connection]}`: a connection's tools. + * - `{method: 'refreshTools', args: [connection]}`: a custom MCP server's tools asked for again, + * `{tools, notAllowed}`: those the agent has now, and the names of the rest. * - `{method: 'call', args: [connection, tool, params?]}`: runs a tool, logged under the token's task. * - `{method: 'feedback', args: [{message, connection?, tool?}]}`: feedback for the makers. * - `{method: 'upload', args: []}`: a URL to PUT files to, each made a blob of the agent's diff --git a/packages/db/src/connection.ts b/packages/db/src/connection.ts index bf22e386..0f29f3cb 100644 --- a/packages/db/src/connection.ts +++ b/packages/db/src/connection.ts @@ -385,6 +385,8 @@ export async function markCredentialRejected(data: { * Replaces a custom MCP server's tools, as JSON, once the server lists them again, and drops the * defaults and agents' settings for actions no longer among `actions`, the tools' names: a setting * kept for a tool the server no longer lists would apply to whatever it later lists by that name. + * Only while it is still a custom connection: one moved to a built-in integration since it was + * read (`takeOverConnection`) keeps its settings, which are that integration's now. */ export async function updateConnectionTools(data: { connectionId: string; @@ -392,13 +394,19 @@ export async function updateConnectionTools(data: { actions: string[]; }): Promise> { const {connectionId, tools, actions} = data; - return wrapDb(async () => { - await db.$transaction([ - db.connection.update({where: {id: connectionId}, data: {tools}}), - db.connectionDefault.deleteMany({where: {connectionId, actionId: {notIn: actions}}}), - db.agentGrant.deleteMany({where: {connectionId, actionId: {notIn: actions}}}), - ]); - }); + return wrapDb(() => + db.$transaction(async (tx) => { + const {count} = await tx.connection.updateMany({ + where: {id: connectionId, integrationId: 'mcp'}, + data: {tools}, + }); + if (count === 0) { + return; + } + await tx.connectionDefault.deleteMany({where: {connectionId, actionId: {notIn: actions}}}); + await tx.agentGrant.deleteMany({where: {connectionId, actionId: {notIn: actions}}}); + }), + ); } /** Renames a connection; null is no name of its own, so it shows as its integration again. */ diff --git a/packages/docs/content/agents/mcp.mdx b/packages/docs/content/agents/mcp.mdx index 998f9e85..f8386212 100644 --- a/packages/docs/content/agents/mcp.mdx +++ b/packages/docs/content/agents/mcp.mdx @@ -81,6 +81,7 @@ the script calls these functions: | `pap.startTask({title, goal, parent?})` | Where an agent starts: it says what it is about to do for you, with a title and a goal, and gets the task's id, which it gives with every later script. Part of a task handed to a sub-agent is started as a sub-task of it. | | `pap.connections()` | The accounts it can use, such as a mailbox, each with its id and what it may do with it. | | `pap.tools(connection)` | A connection's own tools, such as `emails_list` or `emails_archive`, each with what it does and the JSON Schema of its params. Only the tools the login has are listed. | +| `pap.refreshTools(connection)` | Asks a [custom MCP server](/connections/custom-mcp) for its tools again, when they seem out of date, and keeps the new list. Answers with the tools the login has, and the names of those you haven't turned on for it. | | `pap.call(connection, tool, params)` | Runs one of those tools, one that reads, such as listing emails, or one that changes something, such as archiving or sending one. | | `pap.finishTask({outcome})` | Marks the task done, saying what was done. The agent starts a new task for the next thing you ask for. | | `pap.feedback({message})` | Tells the makers of Personal Agent Proxy about something that didn't work as the agent expected. It goes to them, not to you, and changes nothing in your accounts. | diff --git a/packages/docs/content/agents/web.mdx b/packages/docs/content/agents/web.mdx index a3f11bfb..3ce5c53e 100644 --- a/packages/docs/content/agents/web.mdx +++ b/packages/docs/content/agents/web.mdx @@ -48,10 +48,10 @@ agent's next request. Under the text field, the page tells the agent what it would be told connecting over MCP: the connections the login can use, each with what it may do with it, the vault, and what a script can -call: `pap.startTask`, `pap.connections`, `pap.tools`, `pap.call`, `pap.finishTask` and -`pap.feedback`. A script is JavaScript or TypeScript run as the body of an async function, so one -script can look in several accounts at once and answer with only what the agent needs. The answer is -what the script logged, then what it returned, or the error it threw. +call: `pap.startTask`, `pap.connections`, `pap.tools`, `pap.refreshTools`, `pap.call`, +`pap.finishTask` and `pap.feedback`. A script is JavaScript or TypeScript run as the body of an +async function, so one script can look in several accounts at once and answer with only what the +agent needs. The answer is what the script logged, then what it returned, or the error it threw. ## Tasks diff --git a/packages/docs/content/connections/custom-mcp.mdx b/packages/docs/content/connections/custom-mcp.mdx index 49fe4e28..2bde79ad 100644 --- a/packages/docs/content/connections/custom-mcp.mdx +++ b/packages/docs/content/connections/custom-mcp.mdx @@ -67,7 +67,9 @@ The activity log shows each run by the tool's name, with the params the agent ga A server's tools can change. The connection's page has a button that asks the server for its tools -again and keeps the new list. A tool that appears later is off until you turn it on, and the +again and keeps the new list. Agents ask too: their list is asked for again once it is an hour old, +when an agent calls a tool the list doesn't have or the server says it no longer has, and when an +agent asks with `pap.refreshTools`. A tool that appears later is off until you turn it on, and the settings for a tool the server no longer lists are dropped, so they can't carry over to a different tool the server later lists by that name.