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

web-mcp-tools.ts

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