Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

web-mcp-tools.ts

395 lines11.6 KB

1import {
2 convertSchemaToJsonSchema,
3 validateWithStandardSchema,
4} from '@tanstack/ai/client'
5import type { AnyClientTool } from '@tanstack/ai/client'
6import type {
7 ClientContextOptionFromTools,
8 InferredClientContext,
9} from './types'
10​
11interface WebMCPTool {
12 name: string
13 title?: string
14 description: string
15 inputSchema?: object
16 annotations?: WebMCPToolAnnotations
17 execute: (
18 input: object,
19 options?: { signal?: AbortSignal },
20 ) => Promise<unknown>
22​
23interface WebMCPModelContext {
24 registerTool: (
25 tool: WebMCPTool,
26 options: { signal: AbortSignal },
27 ) => Promise<void>
29​
30/** WebMCP behavior hints for one registered tool. */
31export interface WebMCPToolAnnotations {
32 /** Indicates that the tool does not modify state. */
33 readOnlyHint?: boolean
34 /** Indicates that the tool can return content that the application does not trust. */
35 untrustedContentHint?: boolean
37​
38/** Display and behavior options for one WebMCP tool. */
39export interface WebMCPToolOptions {
40 /** A human-readable title for browser user interfaces. */
41 title?: string
42 /** Optional behavior hints for browser agents. */
43 annotations?: WebMCPToolAnnotations
45​
46/** WebMCP options keyed by the inferred names in a client tool list. */
47export type WebMCPToolOptionsByName<
48 TTools extends ReadonlyArray<AnyClientTool>,
49> = Partial<{
50 [TName in TTools[number]['name']]: WebMCPToolOptions
51}>
52​
53/**
54 * Options for {@link registerWebMCPTools}.
55 *
56 * The signal controls the registration lifetime. Context is required when a
57 * client tool declares a required runtime context.
58 */
59export type RegisterWebMCPToolsOptions<
60 TTools extends ReadonlyArray<AnyClientTool>,
61 TContext = InferredClientContext<TTools>,
62> = {
63 /** Removes all tools from this call when the signal aborts. */
64 signal: AbortSignal
65 /** Per-tool display and behavior options. */
66 toolOptions?: WebMCPToolOptionsByName<TTools>
67} & ClientContextOptionFromTools<TTools, TContext>
68​
69function isWebMCPModelContext(value: unknown): value is WebMCPModelContext {
70 return (
71 value !== null &&
72 typeof value === 'object' &&
73 'registerTool' in value &&
74 typeof value.registerTool === 'function'
75 )
77​
78function getToolOptions<TName extends string>(
79 toolOptions: Partial<Record<TName, WebMCPToolOptions>> | undefined,
80 name: TName,
81) {
82 return toolOptions?.[name]
84​
85async function validateSchemaValue(schema: unknown, value: unknown) {
86 const result = await validateWithStandardSchema(schema, value)
87 if (result.success) {
88 return result.data
89 }
90​
91 throw new Error(
92 `Validation failed: ${result.issues.map((issue) => issue.message).join(', ')}`,
93 )
95​
96/**
97 * Registers executable TanStack client tools with the browser WebMCP API.
98 *
99 * Unsupported browsers and server environments resolve without registration.
100 * Abort `options.signal` to remove every tool registered by this call.
101 *
102 * @param tools - The executable client tools to expose through WebMCP.
103 * @param options - The registration signal, runtime context, and per-tool options.
104 *
105 * @example
106 * ```ts
107 * const controller = new AbortController()
108 * await registerWebMCPTools(tools, { signal: controller.signal })
109 * controller.abort()
110 * ```
111 */
112export async function registerWebMCPTools<
113 const TTools extends ReadonlyArray<AnyClientTool>,
114 TContext = InferredClientContext<TTools>,
115>(tools: TTools, options: RegisterWebMCPToolsOptions<TTools, TContext>) {
116 if (
117 typeof document === 'undefined' ||
118 (typeof isSecureContext !== 'undefined' && !isSecureContext) ||
119 !('modelContext' in document) ||
120 !isWebMCPModelContext(document.modelContext)
121 ) {
122 return
123 }
124 if (tools.length === 0) {
125 return
126 }
127​
128 const names = new Set<string>()
129 const webMCPTools = tools.map((tool) => {
130 if (!/^[A-Za-z0-9_.-]{1,128}$/.test(tool.name)) {
131 throw new Error(
132 `WebMCP tool name "${tool.name}" must contain 1 to 128 ASCII letters, numbers, underscores, hyphens, or periods.`,
133 )
134 }
135 if (names.has(tool.name)) {
136 throw new Error(`Duplicate WebMCP tool name "${tool.name}".`)
137 }
138 if (tool.description.trim() === '') {
139 throw new Error(`WebMCP tool "${tool.name}" must have a description.`)
140 }
141 if (typeof tool.execute !== 'function') {
142 throw new Error(
143 `WebMCP tool "${tool.name}" must have an execute handler.`,
144 )
145 }
146 if (tool.needsApproval === true) {
147 throw new Error(
148 `WebMCP tool "${tool.name}" cannot use needsApproval: true.`,
149 )
150 }
151​
152 names.add(tool.name)
153 const toolOptions = getToolOptions(options.toolOptions, tool.name)
154 const inputSchema = tool.inputSchema
155 const outputSchema = tool.outputSchema
156 const convertedInputSchema = convertSchemaToJsonSchema(inputSchema)
157 const inputSchemaType = convertedInputSchema?.type
158 const requiresNonObjectInput =
159 (typeof inputSchemaType === 'string' && inputSchemaType !== 'object') ||
160 (Array.isArray(inputSchemaType) && !inputSchemaType.includes('object'))
161 if (requiresNonObjectInput) {
162 throw new Error(
163 `WebMCP tool "${tool.name}" input schema must accept an object.`,
164 )
165 }
166 const execute = tool.execute
167​
168 return {
169 name: tool.name,
170 description: tool.description,
171 ...(toolOptions?.title !== undefined ? { title: toolOptions.title } : {}),
172 ...(convertedInputSchema !== undefined
173 ? { inputSchema: convertedInputSchema }
174 : {}),
175 ...(toolOptions?.annotations !== undefined
176 ? { annotations: toolOptions.annotations }
177 : {}),
178 async execute(
179 input: object,
180 executionOptions?: { signal?: AbortSignal },
181 ) {
182 const validatedInput = await validateSchemaValue(inputSchema, input)
183 const output = await execute(validatedInput, {
184 abortSignal: executionOptions?.signal,
185 context: options.context,
186 emitCustomEvent() {},
187 })
188 return validateSchemaValue(outputSchema, output)
189 },
190 }
191 })
192​
193 const registrationController = new AbortController()
194 const abortRegistration = () =>
195 registrationController.abort(options.signal.reason)
196​
197 if (options.signal.aborted) {
198 abortRegistration()
199 } else {
200 options.signal.addEventListener('abort', abortRegistration, { once: true })
201 }
202​
203 try {
204 for (const tool of webMCPTools) {
205 await document.modelContext.registerTool(tool, {
206 signal: registrationController.signal,
207 })
208 }
209 } catch (error) {
210 registrationController.abort(error)
211 options.signal.removeEventListener('abort', abortRegistration)
212 throw error
213 }
215​
216/** A tool that a page registered with WebMCP, as `getTools()` returns it. */
217export interface WebMCPPageTool {
218 name: string
219 title?: string
220 description: string
221 /** A JSON Schema object for the tool input. */
222 inputSchema?: object
223 /** The origin of the document that registered the tool. */
224 origin: string
225 annotations?: WebMCPToolAnnotations
227​
228interface WebMCPToolReader {
229 getTools: () => Promise<Array<WebMCPPageTool>>
230 executeTool: (
231 tool: WebMCPPageTool,
232 input: unknown,
233 options: { signal?: AbortSignal },
234 ) => Promise<string>
235 addEventListener: EventTarget['addEventListener']
236 removeEventListener: EventTarget['removeEventListener']
238​
239/** Options for {@link getWebMCPTools}. */
240export interface GetWebMCPToolsOptions {
241 /** Return `false` to skip a tool. */
242 filter?: (tool: WebMCPPageTool) => boolean
244​
245/** Options for {@link subscribeWebMCPTools}. */
246export interface SubscribeWebMCPToolsOptions extends GetWebMCPToolsOptions {
247 /** Stops the subscription when it aborts. */
248 signal: AbortSignal
249 /** Receives a failure from the WebMCP `getTools()` call. */
250 onError?: (error: unknown) => void
252​
253function isWebMCPToolReader(value: unknown): value is WebMCPToolReader {
254 return (
255 value !== null &&
256 typeof value === 'object' &&
257 'getTools' in value &&
258 typeof value.getTools === 'function' &&
259 'executeTool' in value &&
260 typeof value.executeTool === 'function' &&
261 'addEventListener' in value &&
262 typeof value.addEventListener === 'function' &&
263 'removeEventListener' in value &&
264 typeof value.removeEventListener === 'function'
265 )
267​
268function getWebMCPToolReader() {
269 if (
270 typeof document === 'undefined' ||
271 (typeof isSecureContext !== 'undefined' && !isSecureContext) ||
272 !('modelContext' in document) ||
273 !isWebMCPToolReader(document.modelContext)
274 ) {
275 return undefined
276 }
277 return document.modelContext
279​
280function parseToolResult(result: string): unknown {
281 try {
282 return JSON.parse(result)
283 } catch {
284 return result
285 }
287​
288async function readWebMCPTools(
289 reader: WebMCPToolReader,
290 options: GetWebMCPToolsOptions | undefined,
291): Promise<Array<AnyClientTool>> {
292 const pageTools = await reader.getTools()
293 const names = new Set<string>()
294 return pageTools
295 .filter((tool) => options?.filter?.(tool) ?? true)
296 .map((tool) => {
297 if (names.has(tool.name)) {
298 throw new Error(
299 `Duplicate WebMCP tool name "${tool.name}". Use a filter or register tools with unique names.`,
300 )
301 }
302 names.add(tool.name)
303 return {
304 __toolSide: 'client' as const,
305 name: tool.name,
306 description: tool.description,
307 inputSchema: tool.inputSchema ?? { type: 'object' },
308 async execute(input: unknown, context?: { abortSignal?: AbortSignal }) {
309 const result = await reader.executeTool(
310 tool,
311 input,
312 context?.abortSignal ? { signal: context.abortSignal } : {},
313 )
314 return parseToolResult(result)
315 },
316 }
317 })
319​
320/**
321 * Reads the WebMCP tools on the page and returns them as client tools.
322 *
323 * Pass the result to a chat as `tools`. Each tool runs through the WebMCP
324 * `executeTool()` call. Unsupported browsers and server environments return
325 * an empty array.
326 *
327 * @param options - A filter that skips tools.
328 *
329 * @example
330 * ```ts
331 * const tools = await getWebMCPTools({
332 * filter: (tool) => tool.origin === location.origin,
333 * })
334 * ```
335 */
336export async function getWebMCPTools(
337 options?: GetWebMCPToolsOptions,
338): Promise<Array<AnyClientTool>> {
339 const reader = getWebMCPToolReader()
340 return reader ? readWebMCPTools(reader, options) : []
342​
343/**
344 * Calls `listener` with the page WebMCP tools now and after each
345 * `toolchange` event, until `options.signal` aborts.
346 *
347 * Unsupported browsers and server environments call `listener` once with an
348 * empty array. When a read fails, `options.onError` gets the error and the
349 * listener keeps the last list.
350 *
351 * @param listener - Receives the current client tools.
352 * @param options - The subscription signal, a filter, and an error callback.
353 *
354 * @example
355 * ```ts
356 * const controller = new AbortController()
357 * subscribeWebMCPTools((tools) => client.updateOptions({ tools }), {
358 * signal: controller.signal,
359 * })
360 * ```
361 */
362export function subscribeWebMCPTools(
363 listener: (tools: Array<AnyClientTool>) => void,
364 options: SubscribeWebMCPToolsOptions,
365): void {
366 if (options.signal.aborted) return
367 const reader = getWebMCPToolReader()
368 if (!reader) {
369 listener([])
370 return
371 }
372​
373 let latestRead = 0
374 const refresh = () => {
375 const read = ++latestRead
376 const isCurrent = () => read === latestRead && !options.signal.aborted
377 readWebMCPTools(reader, options).then(
378 (tools) => {
379 if (isCurrent()) listener(tools)
380 },
381 (error: unknown) => {
382 if (isCurrent()) options.onError?.(error)
383 },
384 )
385 }
386​
387 // Remove the listener by hand: Zone.js breaks the `signal` listener option.
388 reader.addEventListener('toolchange', refresh)
389 options.signal.addEventListener(
390 'abort',
391 () => reader.removeEventListener('toolchange', refresh),
392 { once: true },
393 )
394 refresh()