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