Open History to see the last commit
1import { Component } from '@angular/core'
2import { TestBed } from '@angular/core/testing'
3import { toolDefinition } from '@tanstack/ai/client'
4import { afterEach, describe, expect, it, vi } from 'vitest'
5import { ChatClient } from '@tanstack/ai-client'
6import {
7 injectChat,
8 injectPageWebMCPTools,
9 injectRegisterWebMCPTools,
10 injectWebMCPTools,
11 type InjectRegisterWebMCPToolsOptions,
12} from '../src'
13import { createMockConnectionAdapter } from './test-utils'
14
15interface RegisteredWebMCPTool {
16 name: string
17 title?: string
18 description: string
19 execute: (input: object, options: { signal: AbortSignal }) => Promise<unknown>
20}
21
22interface ModelContextOptions {
23 failOn?: string
24 pendingUntilAbort?: string
25}
26
27function installModelContext({
28 failOn,
29 pendingUntilAbort,
30}: ModelContextOptions = {}) {
31 const tools = new Map<string, RegisteredWebMCPTool>()
32 const modelContext = {
33 tools,
34 async registerTool(
35 tool: RegisteredWebMCPTool,
36 options: { signal: AbortSignal },
37 ) {
38 if (tool.name === failOn) {
39 throw new Error(`${tool.name} registration failed`)
40 }
41 if (tool.name === pendingUntilAbort) {
42 await new Promise<void>((_resolve, reject) => {
43 options.signal.addEventListener(
44 'abort',
45 () => reject(new Error(`${tool.name} registration aborted`)),
46 { once: true },
47 )
48 })
49 }
50
51 tools.set(tool.name, tool)
52 options.signal.addEventListener('abort', () => tools.delete(tool.name), {
53 once: true,
54 })
55 },
56 }
57
58 Object.defineProperty(document, 'modelContext', {
59 configurable: true,
60 value: modelContext,
61 })
62 vi.stubGlobal('isSecureContext', true)
63 return modelContext
64}
65
66function createInjectionOwner(register: () => void) {
67 @Component({ standalone: true, template: '' })
68 class Host {
69 registration = register()
70 }
71
72 const fixture = TestBed.createComponent(Host)
73 fixture.detectChanges()
74 return fixture
75}
76
77const statusTool = toolDefinition({
78 name: 'status',
79 description: 'Read the current status',
80}).client(async () => ({ status: 'ready' }))
81
82afterEach(() => {
83 TestBed.resetTestingModule()
84 Reflect.deleteProperty(document, 'modelContext')
85 vi.unstubAllGlobals()
86})
87
88describe('injectRegisterWebMCPTools', () => {
89 it('registers client tools with their inferred options', async () => {
90 const modelContext = installModelContext()
91 createInjectionOwner(() =>
92 injectRegisterWebMCPTools([statusTool], {
93 toolOptions: { status: { title: 'Current status' } },
94 }),
95 )
96
97 await vi.waitFor(() => expect(modelContext.tools.has('status')).toBe(true))
98 expect(modelContext.tools.get('status')).toMatchObject({
99 name: 'status',
100 title: 'Current status',
101 description: 'Read the current status',
102 })
103 })
104
105 it('removes registered tools when the injection owner is destroyed', async () => {
106 const modelContext = installModelContext()
107 const fixture = createInjectionOwner(() =>
108 injectRegisterWebMCPTools([statusTool]),
109 )
110 await vi.waitFor(() => expect(modelContext.tools.has('status')).toBe(true))
111
112 fixture.destroy()
113
114 expect(modelContext.tools.size).toBe(0)
115 })
116
117 it('reports asynchronous registration errors', async () => {
118 installModelContext({ failOn: 'status' })
119 const onError = vi.fn()
120 createInjectionOwner(() =>
121 injectRegisterWebMCPTools([statusTool], { onError }),
122 )
123
124 await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce())
125 expect(onError).toHaveBeenCalledWith(
126 expect.objectContaining({ message: 'status registration failed' }),
127 )
128 })
129
130 it('does not report a pending registration error after destruction', async () => {
131 installModelContext({ pendingUntilAbort: 'status' })
132 const onError = vi.fn()
133 const fixture = createInjectionOwner(() =>
134 injectRegisterWebMCPTools([statusTool], { onError }),
135 )
136
137 fixture.destroy()
138 await new Promise((resolve) => setTimeout(resolve, 0))
139
140 expect(onError).not.toHaveBeenCalled()
141 })
142
143 it('preserves inferred tool options and required runtime context', () => {
144 const contextualTool = toolDefinition({
145 name: 'tenant_status',
146 description: 'Read tenant status',
147 }).client<{ tenantId: string }>((_input, context) => {
148 return context.context.tenantId
149 })
150
151 function _scenario() {
152 const options: InjectRegisterWebMCPToolsOptions<
153 readonly [typeof contextualTool]
154 > = {
155 context: { tenantId: 'tenant-1' },
156 toolOptions: { tenant_status: { title: 'Tenant status' } },
157 }
158 injectRegisterWebMCPTools([contextualTool], options)
159
160 // @ts-expect-error contextual tools require runtime context
161 injectRegisterWebMCPTools([contextualTool])
162 injectRegisterWebMCPTools([contextualTool], {
163 context: { tenantId: 'tenant-1' },
164 toolOptions: {
165 // @ts-expect-error tool options only accept inferred tool names
166 unknown_tool: {},
167 },
168 })
169 }
170
171 void _scenario
172 })
173
174 it('throws outside an injection context', () => {
175 expect(() => injectRegisterWebMCPTools([statusTool])).toThrow()
176 })
177})
178
179describe('injectWebMCPTools', () => {
180 it('is a deprecated alias of injectRegisterWebMCPTools', () => {
181 expect(injectWebMCPTools).toBe(injectRegisterWebMCPTools)
182 })
183})
184
185function installPageTools(names: Array<string>) {
186 const target = new EventTarget()
187 const modelContext = {
188 names,
189 getTools: async () =>
190 modelContext.names.map((name) => ({
191 name,
192 description: `Run ${name}`,
193 origin: 'https://example.com',
194 })),
195 executeTool: async () => '"done"',
196 addEventListener: target.addEventListener.bind(target),
197 removeEventListener: target.removeEventListener.bind(target),
198 change(nextNames: Array<string>) {
199 modelContext.names = nextNames
200 target.dispatchEvent(new Event('toolchange'))
201 },
202 }
203 Object.defineProperty(document, 'modelContext', {
204 configurable: true,
205 value: modelContext,
206 })
207 return modelContext
208}
209
210describe('injectPageWebMCPTools', () => {
211 it('returns filtered page tools, updates on toolchange, and syncs injectChat', async () => {
212 const modelContext = installPageTools(['first', 'blocked'])
213 const updateOptions = vi.spyOn(ChatClient.prototype, 'updateOptions')
214
215 @Component({ standalone: true, template: '' })
216 class Host {
217 pageTools = injectPageWebMCPTools({
218 filter: (tool) => tool.name !== 'blocked',
219 })
220 chat = injectChat({
221 connection: createMockConnectionAdapter(),
222 tools: this.pageTools,
223 })
224 }
225 const fixture = TestBed.createComponent(Host)
226 fixture.detectChanges()
227 const tools = fixture.componentInstance.pageTools
228
229 await vi.waitFor(() =>
230 expect(tools().map((tool) => tool.name)).toEqual(['first']),
231 )
232 modelContext.change(['first', 'second'])
233 await vi.waitFor(() => expect(tools()).toHaveLength(2))
234 fixture.detectChanges()
235 expect(updateOptions).toHaveBeenCalledWith({ tools: tools() })
236 await expect(tools()[0]?.execute?.({})).resolves.toBe('done')
237
238 fixture.destroy()
239 updateOptions.mockRestore()
240 })
241
242 it('throws outside an injection context', () => {
243 expect(() => injectPageWebMCPTools()).toThrow()
244 })
245})