Skip to content
Open
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
29 changes: 28 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@jitl/quickjs-wasmfile-release-sync": "0.32.0",
"@proxy/backends": "workspace:*",
"@proxy/contracts": "workspace:*",
"@proxy/db": "workspace:*",
Expand All @@ -27,7 +28,9 @@
"mailparser": "^3.9.36",
"mammoth": "^1.13.0",
"nodemailer": "^10.0.15",
"quickjs-emscripten-core": "0.32.0",
"resend": "^6.7.0",
"sucrase": "3.35.1",
"tldts": "^7.4.19",
"ts-results-es": "^7.1.0",
"unpdf": "^1.9.1",
Expand Down
34 changes: 34 additions & 0 deletions packages/api/src/agent-side/summaries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import {findIntegration, integrationFor, type Tool} from '@proxy/integrations';
import type {AgentConnection} from '@proxy/contracts/agent-side';

/**
* Connections and tools as an agent is given them, by `pap.connections()` and `pap.tools()` in a
* script and in the instructions it is given when it connects.
*/

// "Read, Archive, Send": what the actions are called, in the catalog's order; a custom server's
// tools by their titles.
export function describeActions(connection: AgentConnection): string {
const integration = integrationFor(connection);
return (integration?.actions ?? [])
.filter((action) => connection.actions.includes(action.id))
.map((action) => action.label)
.join(', ');
}

/** A connection by its integration, and the name the person gave it where they did. */
export function connectionSummary(connection: AgentConnection) {
return {
connection: connection.id,
integration: findIntegration(connection.integrationId)?.name ?? connection.integrationId,
...(connection.name === null ? {} : {name: connection.name}),
account: connection.account,
shared: connection.shared,
can: describeActions(connection),
};
}

/** A tool: what it does, and its params as JSON Schema. */
export function toolSummary(tool: Tool) {
return {name: tool.name, description: tool.description, params: tool.inputSchema};
}
22 changes: 4 additions & 18 deletions packages/api/src/agent-side/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -330,18 +330,6 @@ describe('runAgentTool', () => {
expect(connector.list.mock.calls[0]?.[1]).toMatchObject({filter: null});
});

test('limited to tools that read, or to those that change something, any other is refused unlogged', async () => {
const {runAgentTool} = await import('./tools');
const readingAWrite = await runAgentTool(caller, 'vault-1', 'entries_create', {title: 'New'}, {readOnly: true});
const runningARead = await runAgentTool(caller, 'vault-1', 'entries_list', {}, {readOnly: false});

expect(readingAWrite.unwrapErr()).toMatchObject({kind: 'validation_error', message: 'entries_create changes something: use run for it'});
expect(runningARead.unwrapErr()).toMatchObject({kind: 'validation_error', message: 'entries_list only reads: use read for it'});
expect(connector.create).not.toHaveBeenCalled();
expect(connector.list).not.toHaveBeenCalled();
expect(logAgentRequest).not.toHaveBeenCalled();
});

test('a connection outside the organization or a tool the integration lacks is not found and not logged', async () => {
const {runAgentTool} = await import('./tools');
const tool = await runAgentTool(caller, 'vault-1', 'entries_send', {});
Expand Down Expand Up @@ -665,7 +653,7 @@ describe('custom MCP servers', () => {

test('runs a tool the agent may run with its params as given, and logs it by name with them', async () => {
const {runAgentTool} = await import('./tools');
const result = await runAgentTool(caller, 'mcp-1', 'search_docs', {query: 'invoices', limit: 3}, {readOnly: true});
const result = await runAgentTool(caller, 'mcp-1', 'search_docs', {query: 'invoices', limit: 3});

expect(result.unwrap()).toEqual({text: '3 results'});
expect(callCustomTool).toHaveBeenCalledWith(customConnection, 'search_docs', {query: 'invoices', limit: 3});
Expand All @@ -680,13 +668,12 @@ describe('custom MCP servers', () => {
});
});

test('a tool the agent may not run is refused and logged as denied; a tool that changes something is not run with read', async () => {
test('a tool the agent may not run is refused and logged as denied; params that are not an object are refused unlogged', async () => {
const {runAgentTool} = await import('./tools');
expect((await runAgentTool(caller, 'mcp-1', 'publish_doc', {id: 'doc-1'})).unwrapErr().kind).toBe('forbidden');
expect(callCustomTool).not.toHaveBeenCalled();
expect(logAgentRequest.mock.calls[0]?.[0]).toMatchObject({collectionId: 'tools', action: 'publish_doc', query: '{"id":"doc-1"}', outcome: 'denied'});

expect((await runAgentTool(caller, 'mcp-1', 'publish_doc', {}, {readOnly: true})).unwrapErr().kind).toBe('validation_error');
expect((await runAgentTool(caller, 'mcp-1', 'search_docs', 'invoices')).unwrapErr().kind).toBe('validation_error');
expect(logAgentRequest).toHaveBeenCalledTimes(1);
});
Expand Down Expand Up @@ -750,7 +737,7 @@ describe("an integration's own tools", () => {

test('run by the runner with the params as given, for the caller on the connection, and logged by name with them', async () => {
const {runAgentTool} = await import('./tools');
const result = await runAgentTool(caller, 'vault-1', 'entries_count', {type: 'Address'}, {readOnly: true});
const result = await runAgentTool(caller, 'vault-1', 'entries_count', {type: 'Address'});

expect(result.unwrap()).toEqual({text: '3 entries'});
expect(countEntries).toHaveBeenCalledWith({caller, connection: vaultConnection, params: {type: 'Address'}});
Expand All @@ -764,14 +751,13 @@ describe("an integration's own tools", () => {
});
});

test('one the agent lacks the action for is refused and logged as denied; one that changes something is not run with read', async () => {
test('one the agent lacks the action for is refused and logged as denied', async () => {
getAgentById.mockResolvedValue(Ok({...agent, grants: []}));
const {runAgentTool} = await import('./tools');

expect((await runAgentTool(caller, 'vault-1', 'entries_purge', {days: 30})).unwrapErr().kind).toBe('forbidden');
expect(purgeEntries).not.toHaveBeenCalled();
expect(logAgentRequest.mock.calls[0]?.[0]).toMatchObject({collectionId: 'tools', action: 'entries_purge', query: '{"days":30}', outcome: 'denied'});
expect((await runAgentTool(caller, 'vault-1', 'entries_purge', {days: 30}, {readOnly: true})).unwrapErr().kind).toBe('validation_error');
expect(logAgentRequest).toHaveBeenCalledTimes(1);
});

Expand Down
14 changes: 4 additions & 10 deletions packages/api/src/agent-side/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ import {parseRecordValues} from '../records/record-values';
import {loadConnection} from '../records/target';
import {log as serverLog} from '../observability/log';
import {integrationOf} from '../utils/connection-actions';
import {requireOpenTaskIfAny} from '../mcp/pre-task-clients';
import {ensureSandboxConnections} from '../native/sandbox/connections';
import type {NativeToolRun} from '../native/tool';
import {requireOpenTask} from './tasks';
import {isPlainObject, parseToolParams} from './tool-params';

/**
Expand Down Expand Up @@ -132,8 +132,7 @@ export function listAgentTools(signedIn: SignedInAgent, connectionId: string): P
export type AgentCaller = {agent: SignedInAgent; via: 'web' | 'mcp' | 'harness'};

/** Who runs a tool, and the task it is run for, by its id. */
// PRE-TASK CLIENTS: null for a pre-task client's call (mcp/pre-task-clients.ts).
export type TaskCaller = AgentCaller & {taskId: string | null};
export type TaskCaller = AgentCaller & {taskId: string};

// `actions` are what the agent can do with the connection, and `refuse` why it can't do another;
// `startedAt` is when the call came in, so the log can say how long it took.
Expand Down Expand Up @@ -234,25 +233,20 @@ function logFailure<T>(run: ToolRun, answer: Result<T, ApiError>, title: string
* doesn't have is refused and logged as denied, saying how to allow it where the connection's
* sign-in didn't cover the action. A run the provider fails, turning it down or out of reach, is
* logged as failed, with what went wrong.
* `readOnly` limits the run to tools that only read, or only to those that change something, as
* the MCP server's `read` and `run` do; any other is refused, unlogged.
*/
export function runAgentTool(caller: TaskCaller, connectionId: string, toolName: string, params: unknown, options: {readOnly?: boolean} = {}): Promise<Result<ToolResult, ApiError>> {
export function runAgentTool(caller: TaskCaller, connectionId: string, toolName: string, params: unknown): Promise<Result<ToolResult, ApiError>> {
return Do(async ($) => {
const startedAt = Date.now();
// None of the three needs another's answer, so they are read at once; a refusal still comes in this order.
const [agentRead, taskRead, connectionRead] = await Promise.all([
requireAgent(caller.agent),
requireOpenTaskIfAny(caller.agent, caller.taskId),
requireOpenTask(caller.agent, caller.taskId),
loadConnection(agentViewer(caller.agent), connectionId),
]);
const agent = $(agentRead);
$(taskRead);
const {connection, integration} = $(connectionRead);
const tool = $(requirePresent(findTool(integration, toolName), ApiErr.notFound('tool', toolName)));
if (options.readOnly !== undefined && options.readOnly !== tool.readOnly) {
return $(Err(ApiErr.validationError(tool.readOnly ? `${tool.name} only reads: use read for it` : `${tool.name} changes something: use run for it`)));
}
if (tool.kind === 'call' || tool.kind === 'native') {
return $(await runParamsTool(caller, agent, connection, integration, tool, params, startedAt));
}
Expand Down
Loading
Loading