Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from 'vitest'
2import { toolDefinition } from '@tanstack/ai/client'
3import { z } from 'zod'
4import { registerWebMCPTools } from '../src/web-mcp-tools'
5
6interface RegisteredWebMCPTool {
7 name: string
8 title?: string
9 description: string
10 inputSchema?: unknown
11 annotations?: {
12 readOnlyHint?: boolean
13 untrustedContentHint?: boolean
14 }
15 execute: (
16 input: object,
17 options?: { signal?: AbortSignal },
18 ) => Promise<unknown>
19}
20
21interface ModelContextOptions {
22 failOn?: string
23}
24
25function installModelContext(options: ModelContextOptions = {}) {
26 const tools = new Map<string, RegisteredWebMCPTool>()
27 const modelContext = {
28 tools,
29 async registerTool(
30 tool: RegisteredWebMCPTool,
31 registrationOptions: { signal: AbortSignal },
32 ) {
33 if (registrationOptions.signal.aborted) {
34 throw registrationOptions.signal.reason
35 }
36 if (tool.name === options.failOn) {
37 throw new Error(`${tool.name} registration failed`)
38 }
39 if (tools.has(tool.name)) {
40 throw new Error(`Tool ${tool.name} is already registered`)
41 }
42
43 tools.set(tool.name, tool)
44 registrationOptions.signal.addEventListener(
45 'abort',
46 () => tools.delete(tool.name),
47 { once: true },
48 )
49 },
50 }
51
52 vi.stubGlobal('document', { modelContext })
53 return modelContext
54}
55
56function getRegisteredTool(
57 modelContext: ReturnType<typeof installModelContext>,
58 name: string,
59) {
60 const tool = modelContext.tools.get(name)
61 if (!tool) {
62 throw new Error(`Tool ${name} was not registered`)
63 }
64 return tool
65}
66
67afterEach(() => {
68 vi.unstubAllGlobals()
69})
70
71describe('registerWebMCPTools', () => {
72 it('registers, executes, and removes an executable client tool', async () => {
73 const modelContext = installModelContext()
74 const lifecycle = new AbortController()
75 const execution = new AbortController()
76 const emittedEvents: Array<unknown> = []
77 const echoDefinition = toolDefinition({
78 name: 'echo',
79 description: 'Echo a value',
80 inputSchema: z.object({ value: z.string() }),
81 outputSchema: z.object({
82 value: z.string(),
83 tenantId: z.string(),
84 aborted: z.boolean(),
85 hasToolCallId: z.boolean(),
86 }),
87 })
88 const tool = echoDefinition.client<{ tenantId: string }>(
89 async (input, toolContext) => {
90 toolContext.emitCustomEvent('ignored', { value: input.value })
91 emittedEvents.push('handler ran')
92 return {
93 value: input.value,
94 tenantId: toolContext.context.tenantId,
95 aborted: toolContext.abortSignal === execution.signal,
96 hasToolCallId: Object.hasOwn(toolContext, 'toolCallId'),
97 }
98 },
99 )
100
101 await registerWebMCPTools([tool], {
102 signal: lifecycle.signal,
103 context: { tenantId: 'tenant-1' },
104 toolOptions: {
105 echo: {
106 title: 'Echo value',
107 annotations: {
108 readOnlyHint: true,
109 untrustedContentHint: true,
110 },
111 },
112 },
113 })
114
115 const registered = getRegisteredTool(modelContext, 'echo')
116 expect(registered).toMatchObject({
117 name: 'echo',
118 title: 'Echo value',
119 description: 'Echo a value',
120 annotations: {
121 readOnlyHint: true,
122 untrustedContentHint: true,
123 },
124 })
125 expect(registered.inputSchema).toEqual({
126 type: 'object',
127 properties: { value: { type: 'string' } },
128 required: ['value'],
129 })
130 await expect(
131 registered.execute({ value: 'hello' }, { signal: execution.signal }),
132 ).resolves.toEqual({
133 value: 'hello',
134 tenantId: 'tenant-1',
135 aborted: true,
136 hasToolCallId: false,
137 })
138 expect(emittedEvents).toEqual(['handler ran'])
139
140 lifecycle.abort()
141 expect(modelContext.tools.size).toBe(0)
142 })
143
144 it('executes when the host omits the execution options argument', async () => {
145 const modelContext = installModelContext()
146 const lifecycle = new AbortController()
147 const tool = toolDefinition({
148 name: 'host_omits_options',
149 description: 'Run without host options',
150 inputSchema: z.object({ value: z.string() }),
151 outputSchema: z.object({ value: z.string() }),
152 }).client(async (input) => input)
153
154 await registerWebMCPTools([tool], { signal: lifecycle.signal })
155 const registered = getRegisteredTool(modelContext, 'host_omits_options')
156
157 await expect(registered.execute({ value: 'ok' })).resolves.toEqual({
158 value: 'ok',
159 })
160 })
161
162 it('validates Standard Schema input before execution', async () => {
163 const modelContext = installModelContext()
164 const lifecycle = new AbortController()
165 const execute = vi.fn(async () => ({ ok: true }))
166 const tool = toolDefinition({
167 name: 'validate_input',
168 description: 'Validate input',
169 inputSchema: z.object({ value: z.string() }),
170 }).client(execute)
171
172 await registerWebMCPTools([tool], { signal: lifecycle.signal })
173 const registered = getRegisteredTool(modelContext, 'validate_input')
174
175 await expect(
176 registered.execute(
177 { value: 1 },
178 { signal: new AbortController().signal },
179 ),
180 ).rejects.toThrow('Validation failed')
181 expect(execute).not.toHaveBeenCalled()
182 })
183
184 it('validates Standard Schema output after execution', async () => {
185 const modelContext = installModelContext()
186 const lifecycle = new AbortController()
187 const outputSchema = z
188 .unknown()
189 .refine(
190 (value) =>
191 value !== null &&
192 typeof value === 'object' &&
193 'ok' in value &&
194 typeof value.ok === 'boolean',
195 'Expected a boolean ok value',
196 )
197 const tool = toolDefinition({
198 name: 'validate_output',
199 description: 'Validate output',
200 outputSchema,
201 }).client(async () => ({ ok: 'no' }))
202
203 await registerWebMCPTools([tool], { signal: lifecycle.signal })
204 const registered = getRegisteredTool(modelContext, 'validate_output')
205
206 await expect(
207 registered.execute({}, { signal: new AbortController().signal }),
208 ).rejects.toThrow('Validation failed')
209 })
210
211 it('passes transformed Standard Schema values through execution', async () => {
212 const modelContext = installModelContext()
213 const lifecycle = new AbortController()
214 const receivedInputs: Array<{ value: string }> = []
215 const tool = toolDefinition({
216 name: 'transform_values',
217 description: 'Transform values',
218 inputSchema: z
219 .object({ value: z.string() })
220 .transform(({ value }) => ({ value: value.trim() })),
221 outputSchema: z
222 .object({ value: z.string() })
223 .transform(({ value }) => ({ result: value.toUpperCase() })),
224 }).client(async (input) => {
225 receivedInputs.push(input)
226 return { value: `${input.value}!` }
227 })
228
229 await registerWebMCPTools([tool], { signal: lifecycle.signal })
230 const registered = getRegisteredTool(modelContext, 'transform_values')
231
232 await expect(
233 registered.execute(
234 { value: ' hello ' },
235 { signal: new AbortController().signal },
236 ),
237 ).resolves.toEqual({ result: 'HELLO!' })
238 expect(receivedInputs).toEqual([{ value: 'hello' }])
239 })
240
241 it('uses the schemas captured during registration', async () => {
242 const modelContext = installModelContext()
243 const lifecycle = new AbortController()
244 const tool = toolDefinition({
245 name: 'captured_schemas',
246 description: 'Use captured schemas',
247 inputSchema: z.object({ value: z.string() }),
248 outputSchema: z.object({ value: z.string() }),
249 }).client(async (input) => input)
250
251 await registerWebMCPTools([tool], { signal: lifecycle.signal })
252 tool.inputSchema = z
253 .object({ value: z.string() })
254 .refine(() => false, 'Mutated input schema')
255 tool.outputSchema = z
256 .object({ value: z.string() })
257 .refine(() => false, 'Mutated output schema')
258 const registered = getRegisteredTool(modelContext, 'captured_schemas')
259
260 await expect(
261 registered.execute(
262 { value: 'original' },
263 { signal: new AbortController().signal },
264 ),
265 ).resolves.toEqual({ value: 'original' })
266 })
267
268 it('leaves raw JSON Schema validation to the client handler', async () => {
269 const modelContext = installModelContext()
270 const lifecycle = new AbortController()
271 const rawSchema = {
272 type: ['object', 'null'],
273 properties: { value: { type: 'string' } },
274 required: ['value'],
275 }
276 const tool = toolDefinition({
277 name: 'raw_schema',
278 description: 'Use a raw schema',
279 inputSchema: rawSchema,
280 }).client(async (input) => input)
281
282 await registerWebMCPTools([tool], { signal: lifecycle.signal })
283 const registered = getRegisteredTool(modelContext, 'raw_schema')
284
285 await expect(
286 registered.execute(
287 { value: 1 },
288 { signal: new AbortController().signal },
289 ),
290 ).resolves.toEqual({ value: 1 })
291 })
292
293 it('rejects a scalar top-level input schema', async () => {
294 const modelContext = installModelContext()
295 const lifecycle = new AbortController()
296 const tool = toolDefinition({
297 name: 'scalar_input',
298 description: 'Use scalar input',
299 inputSchema: z.string(),
300 }).client(async (input) => input)
301
302 await expect(
303 registerWebMCPTools([tool], { signal: lifecycle.signal }),
304 ).rejects.toThrow('input schema must accept an object')
305 expect(modelContext.tools.size).toBe(0)
306 })
307
308 it('resolves without registration when WebMCP is unavailable', async () => {
309 const lifecycle = new AbortController()
310 const tool = toolDefinition({
311 name: 'unsupported',
312 description: 'Do not register',
313 }).client(async () => ({ ok: true }))
314
315 vi.stubGlobal('document', {})
316 await expect(
317 registerWebMCPTools([tool], { signal: lifecycle.signal }),
318 ).resolves.toBeUndefined()
319
320 vi.stubGlobal('document', { modelContext: {} })
321 await expect(
322 registerWebMCPTools([tool], { signal: lifecycle.signal }),
323 ).resolves.toBeUndefined()
324
325 const modelContext = installModelContext()
326 vi.stubGlobal('isSecureContext', false)
327 await expect(
328 registerWebMCPTools([tool], { signal: lifecycle.signal }),
329 ).resolves.toBeUndefined()
330 expect(modelContext.tools.size).toBe(0)
331 })
332
333 it('does not register tools for an already-aborted lifetime', async () => {
334 const modelContext = installModelContext()
335 const lifecycle = new AbortController()
336 const abortReason = new Error('registration stopped')
337 const tool = toolDefinition({
338 name: 'already_aborted',
339 description: 'Do not register after abort',
340 }).client(async () => ({ ok: true }))
341 lifecycle.abort(abortReason)
342
343 await expect(
344 registerWebMCPTools([tool], { signal: lifecycle.signal }),
345 ).rejects.toBe(abortReason)
346 expect(modelContext.tools.size).toBe(0)
347 })
348
349 it('does not link the lifecycle signal for an empty tool list', async () => {
350 installModelContext()
351 const lifecycle = new AbortController()
352 const addEventListener = vi.spyOn(lifecycle.signal, 'addEventListener')
353
354 await registerWebMCPTools([], { signal: lifecycle.signal })
355
356 expect(addEventListener).not.toHaveBeenCalled()
357 })
358
359 it('removes partial registrations when registration fails', async () => {
360 const modelContext = installModelContext({ failOn: 'second' })
361 const lifecycle = new AbortController()
362 const first = toolDefinition({
363 name: 'first',
364 description: 'First tool',
365 }).client(async () => 'first')
366 const second = toolDefinition({
367 name: 'second',
368 description: 'Second tool',
369 }).client(async () => 'second')
370
371 await expect(
372 registerWebMCPTools([first, second], { signal: lifecycle.signal }),
373 ).rejects.toThrow('second registration failed')
374 expect(modelContext.tools.size).toBe(0)
375 })
376
377 it.each([
378 {
379 label: 'a missing execute handler',
380 tools: [
381 toolDefinition({
382 name: 'missing_execute',
383 description: 'Missing execute',
384 }).client(),
385 ],
386 error: 'execute',
387 },
388 {
389 label: 'an approval tool',
390 tools: [
391 toolDefinition({
392 name: 'approval',
393 description: 'Approval tool',
394 needsApproval: true,
395 }).client(async () => 'approved'),
396 ],
397 error: 'needsApproval',
398 },
399 {
400 label: 'an invalid name',
401 tools: [
402 toolDefinition({
403 name: 'invalid name',
404 description: 'Invalid name',
405 }).client(async () => 'invalid'),
406 ],
407 error: 'WebMCP tool name',
408 },
409 {
410 label: 'a name longer than 128 characters',
411 tools: [
412 toolDefinition({
413 name: 'a'.repeat(129),
414 description: 'Long name',
415 }).client(async () => 'invalid'),
416 ],
417 error: 'WebMCP tool name',
418 },
419 {
420 label: 'an empty description',
421 tools: [
422 toolDefinition({ name: 'empty_description', description: '' }).client(
423 async () => 'invalid',
424 ),
425 ],
426 error: 'description',
427 },
428 ])('rejects $label before registration', async ({ tools, error }) => {
429 const modelContext = installModelContext()
430 const lifecycle = new AbortController()
431
432 await expect(
433 registerWebMCPTools(tools, { signal: lifecycle.signal }),
434 ).rejects.toThrow(error)
435 expect(modelContext.tools.size).toBe(0)
436 })
437
438 it('rejects duplicate names before registration', async () => {
439 const modelContext = installModelContext()
440 const lifecycle = new AbortController()
441 const first = toolDefinition({
442 name: 'duplicate',
443 description: 'First duplicate',
444 }).client(async () => 'first')
445 const duplicate = toolDefinition({
446 name: 'duplicate',
447 description: 'Second duplicate',
448 }).client(async () => 'second')
449
450 await expect(
451 registerWebMCPTools([first, duplicate], { signal: lifecycle.signal }),
452 ).rejects.toThrow('Duplicate WebMCP tool name')
453 expect(modelContext.tools.size).toBe(0)
454 })
455
456 it('preserves a foreign registration with the same name', async () => {
457 const modelContext = installModelContext()
458 const lifecycle = new AbortController()
459 const foreignTool: RegisteredWebMCPTool = {
460 name: 'foreign_owned',
461 description: 'Foreign tool',
462 async execute(input) {
463 return input
464 },
465 }
466 modelContext.tools.set(foreignTool.name, foreignTool)
467 const tool = toolDefinition({
468 name: 'foreign_owned',
469 description: 'Conflicting tool',
470 }).client(async () => 'local')
471
472 await expect(
473 registerWebMCPTools([tool], { signal: lifecycle.signal }),
474 ).rejects.toThrow('already registered')
475 expect(modelContext.tools.get(foreignTool.name)).toBe(foreignTool)
476 })
477})