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