|
| 1 | +import type { RpcArgsSchema, RpcFunctionAgentOptions, RpcFunctionType } from 'devframe/rpc' |
| 2 | +import type { WebMcpModelContext, WebMcpToolResult } from './webmcp' |
| 3 | +import { toAgentToolName } from 'devframe/utils/agent-tool-name' |
| 4 | +import { argsToJsonSchema } from '../adapters/mcp/to-json-schema' |
| 5 | +import { coerceAgentPositionalArgs } from '../node/agent-args' |
| 6 | + |
| 7 | +interface WebMcpModelContextCarrier { |
| 8 | + modelContext?: WebMcpModelContext |
| 9 | +} |
| 10 | + |
| 11 | +/** Resolve the experimental WebMCP context provided by the current document. */ |
| 12 | +export function resolveWebMcpModelContext(): WebMcpModelContext | undefined { |
| 13 | + if (typeof document !== 'undefined') { |
| 14 | + const context = (document as WebMcpModelContextCarrier).modelContext |
| 15 | + if (context) |
| 16 | + return context |
| 17 | + } |
| 18 | + if (typeof navigator !== 'undefined') { |
| 19 | + const context = (navigator as WebMcpModelContextCarrier).modelContext |
| 20 | + if (context) |
| 21 | + return context |
| 22 | + } |
| 23 | + return undefined |
| 24 | +} |
| 25 | + |
| 26 | +/** Function metadata required to project one local browser function to WebMCP. */ |
| 27 | +export interface WebMcpFunctionDefinition { |
| 28 | + name: string |
| 29 | + type?: RpcFunctionType |
| 30 | + args?: RpcArgsSchema |
| 31 | + agent?: RpcFunctionAgentOptions |
| 32 | +} |
| 33 | + |
| 34 | +/** A local browser function registry that can be projected to WebMCP. */ |
| 35 | +export interface WebMcpFunctionSource<Definition extends WebMcpFunctionDefinition> { |
| 36 | + definitions: ReadonlyMap<string, Definition> |
| 37 | + invoke: (definition: Definition, args: unknown[]) => unknown | Promise<unknown> |
| 38 | + onChanged?: (listener: (id?: string) => void) => () => void |
| 39 | + resolveToolId?: (definition: Definition) => string |
| 40 | +} |
| 41 | + |
| 42 | +/** Project agent-flagged functions from a local browser registry to WebMCP. */ |
| 43 | +export function registerWebMcpFunctionTools<Definition extends WebMcpFunctionDefinition>( |
| 44 | + source: WebMcpFunctionSource<Definition>, |
| 45 | + modelContext: WebMcpModelContext | undefined, |
| 46 | +): () => void { |
| 47 | + if (!modelContext) |
| 48 | + return () => {} |
| 49 | + const context = modelContext |
| 50 | + |
| 51 | + /** Unregister callbacks keyed by the source registry's definition id. */ |
| 52 | + const registered = new Map<string, () => void>() |
| 53 | + /** Wire name → qualified tool id, to detect sanitization collisions. */ |
| 54 | + const wireNames = new Map<string, string>() |
| 55 | + |
| 56 | + function register(sourceId: string, def: Definition, agent: RpcFunctionAgentOptions): void { |
| 57 | + const toolId = source.resolveToolId?.(def) ?? def.name |
| 58 | + const name = toAgentToolName(toolId) |
| 59 | + const owner = wireNames.get(name) |
| 60 | + if (owner && owner !== toolId) { |
| 61 | + console.warn(`[devframe] WebMCP tool name "${name}" (from "${toolId}") collides with "${owner}"; keeping the first registration.`) |
| 62 | + return |
| 63 | + } |
| 64 | + |
| 65 | + const controller = new AbortController() |
| 66 | + const result = context.registerTool({ |
| 67 | + name, |
| 68 | + description: agent.description, |
| 69 | + inputSchema: argsToJsonSchema(def.args), |
| 70 | + annotations: { |
| 71 | + title: agent.title ?? def.name, |
| 72 | + readOnlyHint: resolveSafety(def, agent) === 'read', |
| 73 | + destructiveHint: resolveSafety(def, agent) === 'destructive', |
| 74 | + }, |
| 75 | + execute: args => executeFunctionTool(def, source.invoke, args), |
| 76 | + }, { signal: controller.signal }) |
| 77 | + // Registration may reject when the frame's permissions policy denies |
| 78 | + // `tools`; the surface is simply unavailable there. |
| 79 | + if (result && 'then' in result) |
| 80 | + void result.then(() => {}, () => {}) |
| 81 | + |
| 82 | + wireNames.set(name, toolId) |
| 83 | + registered.set(sourceId, () => { |
| 84 | + controller.abort() |
| 85 | + if (result && 'unregister' in result && typeof result.unregister === 'function') |
| 86 | + result.unregister() |
| 87 | + wireNames.delete(name) |
| 88 | + }) |
| 89 | + } |
| 90 | + |
| 91 | + function sync(id?: string): void { |
| 92 | + const names = id ? [id] : [...source.definitions.keys()] |
| 93 | + for (const name of names) { |
| 94 | + registered.get(name)?.() |
| 95 | + registered.delete(name) |
| 96 | + const def = source.definitions.get(name) |
| 97 | + const agent = def?.agent |
| 98 | + if (def && agent) |
| 99 | + register(name, def, agent) |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + sync() |
| 104 | + const unsubscribe = source.onChanged?.(id => sync(id)) ?? (() => {}) |
| 105 | + |
| 106 | + return () => { |
| 107 | + unsubscribe() |
| 108 | + for (const unregister of registered.values()) |
| 109 | + unregister() |
| 110 | + registered.clear() |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +function resolveSafety( |
| 115 | + def: WebMcpFunctionDefinition, |
| 116 | + agent: RpcFunctionAgentOptions, |
| 117 | +): 'read' | 'action' | 'destructive' { |
| 118 | + if (agent.safety) |
| 119 | + return agent.safety |
| 120 | + const type: RpcFunctionType = def.type ?? 'query' |
| 121 | + return type === 'static' || type === 'query' ? 'read' : 'action' |
| 122 | +} |
| 123 | + |
| 124 | +async function executeFunctionTool<Definition extends WebMcpFunctionDefinition>( |
| 125 | + def: Definition, |
| 126 | + invoke: WebMcpFunctionSource<Definition>['invoke'], |
| 127 | + args: Record<string, unknown>, |
| 128 | +): Promise<WebMcpToolResult> { |
| 129 | + try { |
| 130 | + const positional = coerceAgentPositionalArgs(args, def.args as readonly unknown[] | undefined, 'wrap') |
| 131 | + const result = await invoke(def, positional) |
| 132 | + return { content: [{ type: 'text', text: stringifyResult(result) }] } |
| 133 | + } |
| 134 | + catch (error) { |
| 135 | + return { |
| 136 | + isError: true, |
| 137 | + content: [{ type: 'text', text: formatError(error) }], |
| 138 | + } |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +function stringifyResult(value: unknown): string { |
| 143 | + if (value === undefined) |
| 144 | + return 'undefined' |
| 145 | + if (typeof value === 'string') |
| 146 | + return value |
| 147 | + return JSON.stringify(value, null, 2) |
| 148 | +} |
| 149 | + |
| 150 | +function formatError(error: unknown): string { |
| 151 | + if (!(error instanceof Error)) |
| 152 | + return String(error) |
| 153 | + const cause = error.cause instanceof Error ? ` (cause: ${error.cause.message})` : '' |
| 154 | + return `${error.name}: ${error.message}${cause}` |
| 155 | +} |
0 commit comments