Skip to content

Commit 50a0147

Browse files
authored
fix(devframe): use WebMCP draft tool hints and honor abort signal (#496)
* fix(devframe): use WebMCP draft tool hints and honor abort signal * fix(devframe): notify when a browser tool manifest changes under the same id
1 parent 06d41e3 commit 50a0147

6 files changed

Lines changed: 111 additions & 10 deletions

File tree

‎docs/content/1.guide/15.agent-native.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ Restart; tools appear in the drawer, resources as `devframe://resource/<id>` / `
148148

149149
## Browser-side tools over WebMCP
150150

151-
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.
151+
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.
152152

153153
```ts
154154
const rpc = await connectDevframe()

‎packages/devframe/src/client/webmcp.test.ts‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,13 @@ describe('registerWebMcpTools', () => {
7373
additionalProperties: false,
7474
})
7575
// `query` (default type) infers read-only.
76-
expect(tool.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false })
76+
expect(tool.title).toBe('my-plugin:greet')
77+
expect(tool.annotations).toMatchObject({
78+
readOnlyHint: true,
79+
consequentialHint: false,
80+
debugging: true,
81+
destructiveHint: false,
82+
})
7783

7884
dispose()
7985
expect(tools.size).toBe(0)
@@ -121,6 +127,49 @@ describe('registerWebMcpTools', () => {
121127
expect(result.content[0]!.text).toBe('Error: nope')
122128
})
123129

130+
it('marks destructive tools as consequential', () => {
131+
const collector = createCollector()
132+
collector.register({
133+
name: 'wipe',
134+
type: 'action',
135+
jsonSerializable: true,
136+
agent: { description: 'Wipe the cache.', safety: 'destructive' },
137+
handler: () => 'done',
138+
})
139+
140+
const { modelContext, tools } = createFakeModelContext()
141+
registerWebMcpTools(collector, { modelContext })
142+
143+
expect(tools.get('wipe')!.annotations).toMatchObject({
144+
readOnlyHint: false,
145+
consequentialHint: true,
146+
destructiveHint: true,
147+
})
148+
})
149+
150+
it('rejects with the abort reason when the call is aborted', async () => {
151+
const collector = createCollector()
152+
collector.register({
153+
name: 'slow',
154+
type: 'action',
155+
jsonSerializable: true,
156+
agent: { description: 'Never settles.' },
157+
handler: () => new Promise(() => {}),
158+
})
159+
160+
const { modelContext, tools } = createFakeModelContext()
161+
registerWebMcpTools(collector, { modelContext })
162+
163+
const controller = new AbortController()
164+
const pending = tools.get('slow')!.execute({}, { signal: controller.signal })
165+
const reason = new Error('cancelled')
166+
controller.abort(reason)
167+
await expect(pending).rejects.toBe(reason)
168+
169+
// An already aborted signal rejects before the handler runs.
170+
await expect(tools.get('slow')!.execute({}, { signal: controller.signal })).rejects.toBe(reason)
171+
})
172+
124173
it('follows later register/update calls until disposed', async () => {
125174
const collector = createCollector()
126175
const { modelContext, tools } = createFakeModelContext()

‎packages/devframe/src/client/webmcp.ts‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,23 @@ export interface WebMcpToolResult {
2121
/** A tool descriptor as passed to {@link WebMcpModelContext.registerTool}. */
2222
export interface WebMcpToolDescriptor {
2323
name: string
24+
title?: string
2425
description: string
2526
inputSchema?: unknown
27+
/**
28+
* Hints from the current draft's `ToolAnnotations`. `title` and
29+
* `destructiveHint` are also set for earlier drafts and polyfills that
30+
* follow the MCP annotation shape.
31+
*/
2632
annotations?: {
2733
title?: string
2834
readOnlyHint?: boolean
35+
consequentialHint?: boolean
36+
untrustedContentHint?: boolean
37+
debugging?: boolean
2938
destructiveHint?: boolean
3039
}
31-
execute: (args: Record<string, unknown>) => Promise<WebMcpToolResult>
40+
execute: (args: Record<string, unknown>, options?: { signal?: AbortSignal }) => Promise<WebMcpToolResult>
3241
}
3342

3443
/**
@@ -134,16 +143,21 @@ export function registerWebMcpTools<LocalFunctions, SetupContext>(
134143

135144
const controller = new AbortController()
136145
const safety = resolveAgentSafety(def.type, agent)
146+
const title = agent.title ?? def.name
137147
const result = modelContext.registerTool({
138148
name,
149+
title,
139150
description: agent.description,
140151
inputSchema: argsToJsonSchema(def.args),
141152
annotations: {
142-
title: agent.title ?? def.name,
153+
title,
143154
readOnlyHint: safety === 'read',
155+
consequentialHint: safety === 'destructive',
156+
// Every devframe tool is developer tooling.
157+
debugging: true,
144158
destructiveHint: safety === 'destructive',
145159
},
146-
execute: args => executeRpcTool(def, clientRpc.context, args),
160+
execute: (args, options) => executeRpcTool(def, clientRpc.context, args, options?.signal),
147161
}, { signal: controller.signal })
148162
// Registration may reject when the frame's permissions policy denies
149163
// `tools`; the surface is simply unavailable there.
@@ -190,11 +204,15 @@ async function executeRpcTool<SetupContext>(
190204
def: RpcFunctionDefinitionAnyWithContext<SetupContext>,
191205
context: SetupContext,
192206
args: Record<string, unknown>,
207+
signal?: AbortSignal,
193208
): Promise<WebMcpToolResult> {
209+
// An aborted call rejects with the signal's reason, as the draft expects.
210+
// The handler itself cannot be stopped; its late result is dropped.
211+
signal?.throwIfAborted()
194212
try {
195213
const positional = toolInputToRpcArgs(args, def.args?.length)
196214
const handler = await getRpcHandler(def, context)
197-
const result = await handler(...positional)
215+
const result = await raceAbort(Promise.resolve(handler(...positional)), signal)
198216
return {
199217
content: [
200218
{
@@ -205,6 +223,8 @@ async function executeRpcTool<SetupContext>(
205223
}
206224
}
207225
catch (error) {
226+
if (signal?.aborted && error === signal.reason)
227+
throw error
208228
return {
209229
isError: true,
210230
content: [
@@ -217,6 +237,18 @@ async function executeRpcTool<SetupContext>(
217237
}
218238
}
219239

240+
function raceAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
241+
if (!signal)
242+
return promise
243+
if (signal.aborted)
244+
return Promise.reject(signal.reason)
245+
return new Promise<T>((resolve, reject) => {
246+
const onAbort = () => reject(signal.reason)
247+
signal.addEventListener('abort', onAbort, { once: true })
248+
promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort))
249+
})
250+
}
251+
220252
/**
221253
* Agent-exposed functions are strict-JSON by contract (`jsonSerializable:
222254
* true` is enforced at registration), so plain `JSON.stringify` suffices.

‎packages/devframe/src/node/__tests__/client-agent.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,4 +245,16 @@ describe('client agent tools', () => {
245245
vi.useRealTimers()
246246
}
247247
})
248+
249+
it('republishes the tool list when a manifest changes under the same id', () => {
250+
const h = harness()
251+
const a = h.session('tab-a')
252+
h.sync(a)
253+
expect(h.notifyChanged).toHaveBeenCalledTimes(1)
254+
255+
const changed = { ...h.refetch, description: 'Refetch queries by key.' }
256+
syncClientAgentTools(h.context, a.session, a.id, [changed], a.info)
257+
expect(h.notifyChanged).toHaveBeenCalledTimes(2)
258+
expect(h.tool(changed.id).description).toBe('Refetch queries by key.')
259+
})
248260
})

‎packages/devframe/src/node/client-agent.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,11 @@ export function syncClientAgentTools(
214214
? now
215215
: previous?.focusedAt ?? 0,
216216
})
217-
// Focus/visibility re-syncs leave the tool surface as it was.
218-
const sameTools = previous && previous.tools.length === tools.length
219-
&& previous.tools.every((tool, i) => tool.id === tools[i]!.id)
217+
// Focus/visibility re-syncs leave the tool surface as it was. Compare the
218+
// whole manifest: a changed description or schema under the same id must
219+
// still notify. Manifests are plain JSON from the wire.
220+
const sameTools = previous
221+
&& JSON.stringify(previous.tools) === JSON.stringify(tools)
220222
if (!sameTools)
221223
state.notifyChanged()
222224
}

‎tests/__snapshots__/tsnapi/devframe/client.snapshot.d.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,14 +154,20 @@ export interface WebMcpRegisteredTool {
154154
}
155155
export interface WebMcpToolDescriptor {
156156
name: string;
157+
title?: string;
157158
description: string;
158159
inputSchema?: unknown;
159160
annotations?: {
160161
title?: string;
161162
readOnlyHint?: boolean;
163+
consequentialHint?: boolean;
164+
untrustedContentHint?: boolean;
165+
debugging?: boolean;
162166
destructiveHint?: boolean;
163167
};
164-
execute: (_: Record<string, unknown>) => Promise<WebMcpToolResult>;
168+
execute: (_: Record<string, unknown>, _?: {
169+
signal?: AbortSignal;
170+
}) => Promise<WebMcpToolResult>;
165171
}
166172
export interface WebMcpToolResult {
167173
content: {

0 commit comments

Comments
 (0)