diff --git a/docs/content/1.guide/15.agent-native.md b/docs/content/1.guide/15.agent-native.md index 28b96536..be86a0c1 100644 --- a/docs/content/1.guide/15.agent-native.md +++ b/docs/content/1.guide/15.agent-native.md @@ -148,7 +148,7 @@ Restart; tools appear in the drawer, resources as `devframe://resource/` / ` ## Browser-side tools over WebMCP -The same `agent` signature works on the browser side: a client RPC function (a function the node side calls on the browser, registered on `rpc.client` or through a scoped `client.scope('my-plugin').rpc.register(...)`) carrying an `agent` field is mirrored onto the page's [WebMCP](https://github.com/webmachinelearning/webmcp) model context (`document.modelContext` / `navigator.modelContext`) as a callable tool, so in-page and browser-integrated agents can drive browser-side functionality directly. Wire names, `arg0`/`arg1`/… input schemas, and safety annotations match the MCP projection above. +The same `agent` signature works on the browser side: a client RPC function (a function the node side calls on the browser, registered on `rpc.client` or through a scoped `client.scope('my-plugin').rpc.register(...)`) carrying an `agent` field is mirrored onto the page's [WebMCP](https://github.com/webmachinelearning/webmcp) model context (`document.modelContext` / `navigator.modelContext`) as a callable tool, so in-page and browser-integrated agents can drive browser-side functionality directly. Wire names, `arg0`/`arg1`/… input schemas, and safety match the MCP projection above. WebMCP has its own hint names: `read` sets `readOnlyHint`, `destructive` sets `consequentialHint`, and every tool sets `debugging`, because devframe tools are developer tooling. When the agent cancels a call, the tool rejects with the abort reason. The handler keeps running, and its result is dropped. ```ts const rpc = await connectDevframe() diff --git a/packages/devframe/src/client/webmcp.test.ts b/packages/devframe/src/client/webmcp.test.ts index 70eb334b..ebaaf910 100644 --- a/packages/devframe/src/client/webmcp.test.ts +++ b/packages/devframe/src/client/webmcp.test.ts @@ -73,7 +73,13 @@ describe('registerWebMcpTools', () => { additionalProperties: false, }) // `query` (default type) infers read-only. - expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false }) + expect(tool.title).toBe('my-plugin:greet') + expect(tool.annotations).toMatchObject({ + readOnlyHint: true, + consequentialHint: false, + debugging: true, + destructiveHint: false, + }) dispose() expect(tools.size).toBe(0) @@ -121,6 +127,49 @@ describe('registerWebMcpTools', () => { expect(result.content[0]!.text).toBe('Error: nope') }) + it('marks destructive tools as consequential', () => { + const collector = createCollector() + collector.register({ + name: 'wipe', + type: 'action', + jsonSerializable: true, + agent: { description: 'Wipe the cache.', safety: 'destructive' }, + handler: () => 'done', + }) + + const { modelContext, tools } = createFakeModelContext() + registerWebMcpTools(collector, { modelContext }) + + expect(tools.get('wipe')!.annotations).toMatchObject({ + readOnlyHint: false, + consequentialHint: true, + destructiveHint: true, + }) + }) + + it('rejects with the abort reason when the call is aborted', async () => { + const collector = createCollector() + collector.register({ + name: 'slow', + type: 'action', + jsonSerializable: true, + agent: { description: 'Never settles.' }, + handler: () => new Promise(() => {}), + }) + + const { modelContext, tools } = createFakeModelContext() + registerWebMcpTools(collector, { modelContext }) + + const controller = new AbortController() + const pending = tools.get('slow')!.execute({}, { signal: controller.signal }) + const reason = new Error('cancelled') + controller.abort(reason) + await expect(pending).rejects.toBe(reason) + + // An already aborted signal rejects before the handler runs. + await expect(tools.get('slow')!.execute({}, { signal: controller.signal })).rejects.toBe(reason) + }) + it('follows later register/update calls until disposed', async () => { const collector = createCollector() const { modelContext, tools } = createFakeModelContext() diff --git a/packages/devframe/src/client/webmcp.ts b/packages/devframe/src/client/webmcp.ts index 91f9c281..0bbe02a2 100644 --- a/packages/devframe/src/client/webmcp.ts +++ b/packages/devframe/src/client/webmcp.ts @@ -21,14 +21,23 @@ export interface WebMcpToolResult { /** A tool descriptor as passed to {@link WebMcpModelContext.registerTool}. */ export interface WebMcpToolDescriptor { name: string + title?: string description: string inputSchema?: unknown + /** + * Hints from the current draft's `ToolAnnotations`. `title` and + * `destructiveHint` are also set for earlier drafts and polyfills that + * follow the MCP annotation shape. + */ annotations?: { title?: string readOnlyHint?: boolean + consequentialHint?: boolean + untrustedContentHint?: boolean + debugging?: boolean destructiveHint?: boolean } - execute: (args: Record) => Promise + execute: (args: Record, options?: { signal?: AbortSignal }) => Promise } /** @@ -134,16 +143,21 @@ export function registerWebMcpTools( const controller = new AbortController() const safety = resolveAgentSafety(def.type, agent) + const title = agent.title ?? def.name const result = modelContext.registerTool({ name, + title, description: agent.description, inputSchema: argsToJsonSchema(def.args), annotations: { - title: agent.title ?? def.name, + title, readOnlyHint: safety === 'read', + consequentialHint: safety === 'destructive', + // Every devframe tool is developer tooling. + debugging: true, destructiveHint: safety === 'destructive', }, - execute: args => executeRpcTool(def, clientRpc.context, args), + execute: (args, options) => executeRpcTool(def, clientRpc.context, args, options?.signal), }, { signal: controller.signal }) // Registration may reject when the frame's permissions policy denies // `tools`; the surface is simply unavailable there. @@ -190,11 +204,15 @@ async function executeRpcTool( def: RpcFunctionDefinitionAnyWithContext, context: SetupContext, args: Record, + signal?: AbortSignal, ): Promise { + // An aborted call rejects with the signal's reason, as the draft expects. + // The handler itself cannot be stopped; its late result is dropped. + signal?.throwIfAborted() try { const positional = toolInputToRpcArgs(args, def.args?.length) const handler = await getRpcHandler(def, context) - const result = await handler(...positional) + const result = await raceAbort(Promise.resolve(handler(...positional)), signal) return { content: [ { @@ -205,6 +223,8 @@ async function executeRpcTool( } } catch (error) { + if (signal?.aborted && error === signal.reason) + throw error return { isError: true, content: [ @@ -217,6 +237,18 @@ async function executeRpcTool( } } +function raceAbort(promise: Promise, signal: AbortSignal | undefined): Promise { + if (!signal) + return promise + if (signal.aborted) + return Promise.reject(signal.reason) + return new Promise((resolve, reject) => { + const onAbort = () => reject(signal.reason) + signal.addEventListener('abort', onAbort, { once: true }) + promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort)) + }) +} + /** * Agent-exposed functions are strict-JSON by contract (`jsonSerializable: * true` is enforced at registration), so plain `JSON.stringify` suffices. diff --git a/packages/devframe/src/node/__tests__/client-agent.test.ts b/packages/devframe/src/node/__tests__/client-agent.test.ts index 917edfc4..190385a2 100644 --- a/packages/devframe/src/node/__tests__/client-agent.test.ts +++ b/packages/devframe/src/node/__tests__/client-agent.test.ts @@ -245,4 +245,16 @@ describe('client agent tools', () => { vi.useRealTimers() } }) + + it('republishes the tool list when a manifest changes under the same id', () => { + const h = harness() + const a = h.session('tab-a') + h.sync(a) + expect(h.notifyChanged).toHaveBeenCalledTimes(1) + + const changed = { ...h.refetch, description: 'Refetch queries by key.' } + syncClientAgentTools(h.context, a.session, a.id, [changed], a.info) + expect(h.notifyChanged).toHaveBeenCalledTimes(2) + expect(h.tool(changed.id).description).toBe('Refetch queries by key.') + }) }) diff --git a/packages/devframe/src/node/client-agent.ts b/packages/devframe/src/node/client-agent.ts index 22db397d..46010452 100644 --- a/packages/devframe/src/node/client-agent.ts +++ b/packages/devframe/src/node/client-agent.ts @@ -214,9 +214,11 @@ export function syncClientAgentTools( ? now : previous?.focusedAt ?? 0, }) - // Focus/visibility re-syncs leave the tool surface as it was. - const sameTools = previous && previous.tools.length === tools.length - && previous.tools.every((tool, i) => tool.id === tools[i]!.id) + // Focus/visibility re-syncs leave the tool surface as it was. Compare the + // whole manifest: a changed description or schema under the same id must + // still notify. Manifests are plain JSON from the wire. + const sameTools = previous + && JSON.stringify(previous.tools) === JSON.stringify(tools) if (!sameTools) state.notifyChanged() } diff --git a/tests/__snapshots__/tsnapi/devframe/client.snapshot.d.ts b/tests/__snapshots__/tsnapi/devframe/client.snapshot.d.ts index 6692c51b..c1b5817b 100644 --- a/tests/__snapshots__/tsnapi/devframe/client.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/devframe/client.snapshot.d.ts @@ -154,14 +154,20 @@ export interface WebMcpRegisteredTool { } export interface WebMcpToolDescriptor { name: string; + title?: string; description: string; inputSchema?: unknown; annotations?: { title?: string; readOnlyHint?: boolean; + consequentialHint?: boolean; + untrustedContentHint?: boolean; + debugging?: boolean; destructiveHint?: boolean; }; - execute: (_: Record) => Promise; + execute: (_: Record, _?: { + signal?: AbortSignal; + }) => Promise; } export interface WebMcpToolResult { content: {