Open History to see the last commit
1// @vitest-environment jsdom
2import { renderHook, waitFor } from '@testing-library/react'
3import { toolDefinition } from '@tanstack/ai/client'
4import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
5import {
6 usePageWebMCPTools,
7 useRegisterWebMCPTools,
8 useWebMCPTools,
9} from '../src'
10import type { AnyClientTool } from '@tanstack/ai/client'
11import type { UseRegisterWebMCPToolsOptions } from '../src'
12
13interface RegisteredWebMCPTool {
14 name: string
15 title?: string
16}
17
18interface ModelContextOptions {
19 failOn?: string
20 pending?: boolean
21}
22
23function installModelContext({ failOn, pending }: ModelContextOptions = {}) {
24 const tools = new Map<string, RegisteredWebMCPTool>()
25 const modelContext = {
26 tools,
27 async registerTool(
28 tool: RegisteredWebMCPTool,
29 options: { signal: AbortSignal },
30 ) {
31 if (tool.name === failOn) {
32 throw new Error(`${tool.name} registration failed`)
33 }
34
35 tools.set(tool.name, tool)
36 if (pending) {
37 await new Promise<void>((_resolve, reject) => {
38 options.signal.addEventListener(
39 'abort',
40 () => {
41 tools.delete(tool.name)
42 reject(new Error(`${tool.name} registration aborted`))
43 },
44 { once: true },
45 )
46 })
47 return
48 }
49
50 options.signal.addEventListener('abort', () => tools.delete(tool.name), {
51 once: true,
52 })
53 },
54 }
55
56 Object.defineProperty(document, 'modelContext', {
57 configurable: true,
58 value: modelContext,
59 })
60 return modelContext
61}
62
63const statusTool = toolDefinition({
64 name: 'status',
65 description: 'Read the status',
66}).client(async () => ({ ok: true }))
67const firstTool = toolDefinition({
68 name: 'first',
69 description: 'Run the first tool',
70}).client(async () => 'first')
71const secondTool = toolDefinition({
72 name: 'second',
73 description: 'Run the second tool',
74}).client(async () => 'second')
75
76afterEach(() => {
77 Reflect.deleteProperty(document, 'modelContext')
78})
79
80describe('useRegisterWebMCPTools', () => {
81 it('removes registered tools on unmount', async () => {
82 const modelContext = installModelContext()
83 const tools = [statusTool] as const
84 const { unmount } = renderHook(() => useRegisterWebMCPTools(tools))
85
86 await waitFor(() => expect(modelContext.tools.has('status')).toBe(true))
87 unmount()
88
89 expect(modelContext.tools.size).toBe(0)
90 })
91
92 it('replaces registered tools when the list changes', async () => {
93 const modelContext = installModelContext()
94 const initialTools: ReadonlyArray<AnyClientTool> = [firstTool]
95 const nextTools: ReadonlyArray<AnyClientTool> = [secondTool]
96 const { rerender, unmount } = renderHook(
97 (tools: ReadonlyArray<AnyClientTool>) => useRegisterWebMCPTools(tools),
98 { initialProps: initialTools },
99 )
100
101 await waitFor(() =>
102 expect([...modelContext.tools.keys()]).toEqual(['first']),
103 )
104 rerender(nextTools)
105 await waitFor(() =>
106 expect([...modelContext.tools.keys()]).toEqual(['second']),
107 )
108 unmount()
109 })
110
111 it('replaces registered tools when options change', async () => {
112 const modelContext = installModelContext()
113 const tools = [statusTool] as const
114 const initialOptions: UseRegisterWebMCPToolsOptions<typeof tools> = {
115 toolOptions: { status: { title: 'Initial status' } },
116 }
117 const nextOptions: UseRegisterWebMCPToolsOptions<typeof tools> = {
118 toolOptions: { status: { title: 'Current status' } },
119 }
120 const { rerender, unmount } = renderHook(
121 (options: UseRegisterWebMCPToolsOptions<typeof tools>) =>
122 useRegisterWebMCPTools(tools, options),
123 { initialProps: initialOptions },
124 )
125
126 await waitFor(() =>
127 expect(modelContext.tools.get('status')?.title).toBe('Initial status'),
128 )
129 rerender(nextOptions)
130 await waitFor(() =>
131 expect(modelContext.tools.get('status')?.title).toBe('Current status'),
132 )
133 unmount()
134 })
135
136 it('reports asynchronous registration failures', async () => {
137 installModelContext({ failOn: 'status' })
138 const onError = vi.fn<(error: unknown) => void>()
139 const tools = [statusTool] as const
140 const { unmount } = renderHook(() =>
141 useRegisterWebMCPTools(tools, { onError }),
142 )
143
144 await waitFor(() => expect(onError).toHaveBeenCalledOnce())
145 expect(onError).toHaveBeenCalledWith(
146 expect.objectContaining({ message: 'status registration failed' }),
147 )
148 unmount()
149 })
150
151 it('does not report aborted pending registrations', async () => {
152 const modelContext = installModelContext({ pending: true })
153 const onError = vi.fn<(error: unknown) => void>()
154 const initialTools: ReadonlyArray<AnyClientTool> = [firstTool]
155 const nextTools: ReadonlyArray<AnyClientTool> = [secondTool]
156 const { rerender, unmount } = renderHook(
157 (tools: ReadonlyArray<AnyClientTool>) =>
158 useRegisterWebMCPTools(tools, { onError }),
159 { initialProps: initialTools },
160 )
161
162 await waitFor(() => expect(modelContext.tools.has('first')).toBe(true))
163 rerender(nextTools)
164 await waitFor(() => expect(modelContext.tools.has('second')).toBe(true))
165 await new Promise((resolve) => setTimeout(resolve, 0))
166 expect(onError).not.toHaveBeenCalled()
167
168 unmount()
169 await new Promise((resolve) => setTimeout(resolve, 0))
170 expect(modelContext.tools.size).toBe(0)
171 expect(onError).not.toHaveBeenCalled()
172 })
173
174 it('preserves inferred tool options and required context', () => {
175 const tools = [statusTool, firstTool] as const
176 const options: UseRegisterWebMCPToolsOptions<typeof tools> = {
177 toolOptions: { status: { title: 'Status' } },
178 }
179 expectTypeOf(options.toolOptions?.status?.title).toEqualTypeOf<
180 string | undefined
181 >()
182
183 const contextualTool = toolDefinition({
184 name: 'contextual',
185 description: 'Read tenant context',
186 }).client<{ tenantId: string }>(
187 (_input, context) => context.context.tenantId,
188 )
189 const contextualTools = [contextualTool] as const
190 const checkCalls = () => {
191 useRegisterWebMCPTools(tools, {
192 toolOptions: {
193 // @ts-expect-error options only accept names from the tool list
194 unknown: {},
195 },
196 })
197 // @ts-expect-error contextual tools require context
198 useRegisterWebMCPTools(contextualTools)
199 useRegisterWebMCPTools(contextualTools, {
200 context: { tenantId: 'tenant-1' },
201 })
202 }
203 void checkCalls
204 })
205})
206
207describe('useWebMCPTools', () => {
208 it('is a deprecated alias of useRegisterWebMCPTools', () => {
209 expect(useWebMCPTools).toBe(useRegisterWebMCPTools)
210 })
211})
212
213function installPageTools(names: Array<string>) {
214 const target = new EventTarget()
215 const modelContext = {
216 names,
217 getTools: async () =>
218 modelContext.names.map((name) => ({
219 name,
220 description: `Run ${name}`,
221 origin: 'https://example.com',
222 })),
223 executeTool: async () => '"done"',
224 addEventListener: target.addEventListener.bind(target),
225 removeEventListener: target.removeEventListener.bind(target),
226 change(nextNames: Array<string>) {
227 modelContext.names = nextNames
228 target.dispatchEvent(new Event('toolchange'))
229 },
230 }
231 Object.defineProperty(document, 'modelContext', {
232 configurable: true,
233 value: modelContext,
234 })
235 return modelContext
236}
237
238describe('usePageWebMCPTools', () => {
239 it('returns filtered page tools and updates on toolchange', async () => {
240 const modelContext = installPageTools(['first', 'blocked'])
241 const { result, unmount } = renderHook(() =>
242 usePageWebMCPTools({ filter: (tool) => tool.name !== 'blocked' }),
243 )
244
245 expect(result.current).toEqual([])
246 await waitFor(() =>
247 expect(result.current.map((tool) => tool.name)).toEqual(['first']),
248 )
249 modelContext.change(['first', 'second'])
250 await waitFor(() =>
251 expect(result.current.map((tool) => tool.name)).toEqual([
252 'first',
253 'second',
254 ]),
255 )
256 await expect(result.current[0]?.execute?.({})).resolves.toBe('done')
257 unmount()
258 })
259})