Skip to content
Merged
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
2 changes: 1 addition & 1 deletion docs/content/1.guide/15.agent-native.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ Restart; tools appear in the drawer, resources as `devframe://resource/<id>` / `

## 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()
Expand Down
51 changes: 50 additions & 1 deletion packages/devframe/src/client/webmcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down
40 changes: 36 additions & 4 deletions packages/devframe/src/client/webmcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => Promise<WebMcpToolResult>
execute: (args: Record<string, unknown>, options?: { signal?: AbortSignal }) => Promise<WebMcpToolResult>
}

/**
Expand Down Expand Up @@ -134,16 +143,21 @@ export function registerWebMcpTools<LocalFunctions, SetupContext>(

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.
Expand Down Expand Up @@ -190,11 +204,15 @@ async function executeRpcTool<SetupContext>(
def: RpcFunctionDefinitionAnyWithContext<SetupContext>,
context: SetupContext,
args: Record<string, unknown>,
signal?: AbortSignal,
): Promise<WebMcpToolResult> {
// 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: [
{
Expand All @@ -205,6 +223,8 @@ async function executeRpcTool<SetupContext>(
}
}
catch (error) {
if (signal?.aborted && error === signal.reason)
throw error
return {
isError: true,
content: [
Expand All @@ -217,6 +237,18 @@ async function executeRpcTool<SetupContext>(
}
}

function raceAbort<T>(promise: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
if (!signal)
return promise
if (signal.aborted)
return Promise.reject(signal.reason)
return new Promise<T>((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.
Expand Down
12 changes: 12 additions & 0 deletions packages/devframe/src/node/__tests__/client-agent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.')
})
})
8 changes: 5 additions & 3 deletions packages/devframe/src/node/client-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
8 changes: 7 additions & 1 deletion tests/__snapshots__/tsnapi/devframe/client.snapshot.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>) => Promise<WebMcpToolResult>;
execute: (_: Record<string, unknown>, _?: {
signal?: AbortSignal;
}) => Promise<WebMcpToolResult>;
}
export interface WebMcpToolResult {
content: {
Expand Down
Loading