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