Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

web-mcp-tools.spec.ts

194 lines6.2 KB

1import { expect, test } from './fixtures'
2import type { Page } from '@playwright/test'
3​
4interface WebMCPToolRegistration {
5 name: string
6 title?: string
7 description: string
8 inputSchema?: object
9 annotations?: {
10 readOnlyHint?: boolean
11 untrustedContentHint?: boolean
12 }
13 execute: (input: object, options: { signal: AbortSignal }) => Promise<unknown>
15​
16interface RegisteredWebMCPTool {
17 name: string
18 title: string
19 description: string
20 inputSchema?: object
21 window: Window
22 origin: string
23 annotations?: {
24 readOnlyHint?: boolean
25 untrustedContentHint?: boolean
26 }
28​
29interface WebMCPRegistration {
30 descriptor: RegisteredWebMCPTool
31 execute: WebMCPToolRegistration['execute']
33​
34/**
35 * Installs a WebMCP mock that accepts one `executeTool` input form only:
36 * - `'string'`: the JSON string that Chrome takes today.
37 * - `'object'`: the object that the WebMCP specification takes.
38 * A strict mock makes each test prove the form that its caller sends.
39 */
40async function installModelContext(
41 page: Page,
42 scenario: 'string' | 'object' | 'duplicate-names',
43) {
44 await page.addInitScript((mode) => {
45 const expectedForm = mode === 'duplicate-names' ? 'object' : mode
46 const registrations = new Map<string, WebMCPRegistration>()
47 const modelContext = new (class extends EventTarget {
48 async registerTool(
49 tool: WebMCPToolRegistration,
50 options: { signal: AbortSignal },
51 ) {
52 if (options.signal.aborted) throw options.signal.reason
53 if (registrations.has(tool.name)) {
54 throw new DOMException('Tool already registered', 'InvalidStateError')
55 }
56​
57 const descriptor: RegisteredWebMCPTool = {
58 name: tool.name,
59 title: tool.title ?? '',
60 description: tool.description,
61 ...(tool.inputSchema === undefined
62 ? {}
63 : { inputSchema: structuredClone(tool.inputSchema) }),
64 window,
65 origin: location.origin,
66 ...(tool.annotations === undefined
67 ? {}
68 : { annotations: { ...tool.annotations } }),
69 }
70 const registration = { descriptor, execute: tool.execute }
71 options.signal.addEventListener(
72 'abort',
73 () => {
74 if (registrations.get(tool.name) !== registration) return
75​
76 registrations.delete(tool.name)
77 this.dispatchEvent(new Event('toolchange'))
78 },
79 { once: true },
80 )
81​
82 registrations.set(tool.name, registration)
83 this.dispatchEvent(new Event('toolchange'))
84 }
85​
86 async getTools() {
87 const tools = [...registrations.values()].map(({ descriptor }) => ({
88 ...descriptor,
89 }))
90 // Simulate a second frame exposing the same tool names.
91 return mode === 'duplicate-names' ? [...tools, ...tools] : tools
92 }
93​
94 async executeTool(tool: RegisteredWebMCPTool, inputArguments: unknown) {
95 const registration = registrations.get(tool.name)
96 if (!registration) {
97 throw new DOMException('Tool not found', 'NotFoundError')
98 }
99​
100 const receivedForm =
101 typeof inputArguments === 'string' ? 'string' : 'object'
102 if (receivedForm !== expectedForm) {
103 throw new DOMException(
104 `Expected ${expectedForm} input arguments, got ${receivedForm}`,
105 'UnknownError',
106 )
107 }
108​
109 let input: object
110 try {
111 // The specification serializes an object input to JSON before the
112 // tool runs, so both forms reach the tool as a parsed object.
113 const parsed: unknown =
114 typeof inputArguments === 'string'
115 ? JSON.parse(inputArguments)
116 : JSON.parse(JSON.stringify(inputArguments))
117 if (parsed === null || typeof parsed !== 'object') {
118 throw new Error('input is not an object')
119 }
120 input = parsed
121 } catch {
122 throw new DOMException(
123 'Failed to parse input arguments',
124 'UnknownError',
125 )
126 }
127​
128 // Chrome currently invokes execute(input) with no options argument.
129 const result = await registration.execute(input)
130 const serializedResult = JSON.stringify(result)
131 if (serializedResult === undefined) {
132 throw new TypeError('Tool result is not JSON serializable')
133 }
134​
135 return serializedResult
136 }
137 })()
138​
139 Object.defineProperty(document, 'modelContext', {
140 configurable: true,
141 value: modelContext,
142 })
143 }, scenario)
145​
146test('WebMCP discovers, executes, and removes a React tool', async ({
147 page,
148}) => {
149 // The route calls executeTool with a JSON string, as Chrome does.
150 await installModelContext(page, 'string')
151 await page.goto('/web-mcp-tools')
152​
153 await expect(page.getByTestId('registered-count')).toHaveText('1')
154​
155 await page.getByRole('button', { name: 'Execute WebMCP tool' }).click()
156 await expect(page.getByTestId('tool-result')).toHaveText('Found guitar')
157​
158 await page.getByRole('button', { name: 'Unmount tool owner' }).press('Enter')
159 await expect(page.getByTestId('registered-count')).toHaveText('0')
160})
161​
162test('usePageWebMCPTools sends filtered page tools to useChat and runs them', async ({
163 page,
164 testId,
165}) => {
166 // usePageWebMCPTools calls executeTool with an object, as the spec does.
167 await installModelContext(page, 'object')
168 await page.goto(`/web-mcp-page-tools?testId=${encodeURIComponent(testId)}`)
169​
170 await expect(page.getByTestId('page-tool-names')).toHaveText('find_guitar')
171​
172 await page.getByRole('button', { name: 'Ask the chat' }).click()
173 await expect(page.getByTestId('tool-output')).toHaveText(
174 '{"message":"Found guitar"}',
175 )
176 await expect(page.getByTestId('assistant-text')).toContainText(
177 'WEBMCP_PAGE_OK',
178 )
179})
180​
181test('duplicate page tool names report an error and stay out of chat', async ({
182 page,
183}) => {
184 await installModelContext(page, 'duplicate-names')
185 await page.goto('/web-mcp-page-tools')
186​
187 await expect(page.getByRole('alert')).toContainText(
188 'Duplicate WebMCP tool name "find_guitar"',
189 )
190 await expect(page.getByTestId('page-tool-names')).toBeEmpty()
191 await expect(
192 page.getByRole('button', { name: 'Ask the chat' }),
193 ).toBeDisabled()
194})