Repository navigation
Expand file tree
/
Copy pathwebmcp.ts
More file actions
262 lines (243 loc) · 6.44 KB
/
Copy pathwebmcp.ts
File metadata and controls
262 lines (243 loc) · 6.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/**
* WebMCP registration for WordPress Playground.
*
* Registers playground tools with `document.modelContext` (the
* Chrome WebMCP API) so that browser-side AI agents can interact
* with the running Playground site.
*/
import type { PlaygroundClient } from '@wp-playground/remote';
import {
toolDefinitions,
getSiteToolDefinitions,
formatStorageLabel,
paramsToJsonSchema,
stringifyError,
} from './tools/tool-definitions';
import { toolExecutors, createToolClient } from './tools/tool-executors';
import type { PlaygroundBridgeConfig } from './bridge-client';
const siteToolDefinitions = getSiteToolDefinitions();
// -- WebMCP type declarations --
export interface ModelContextTool {
name: string;
description: string;
inputSchema?: Record<string, unknown>;
execute: (
input: Record<string, unknown>,
client: ModelContextClient
) => Promise<unknown>;
annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean };
}
interface ModelContextClient {
requestUserInteraction(callback: () => Promise<unknown>): Promise<unknown>;
}
interface ModelContext {
provideContext(options: { tools: ModelContextTool[] }): void;
registerTool(
tool: ModelContextTool,
options?: { signal?: AbortSignal }
): Promise<void> | void;
readonly tools: ModelContextTool[];
}
declare global {
interface Document {
modelContext?: ModelContext;
}
}
// -- Registration --
let registrationController: AbortController | null = null;
function getActiveSite(config: PlaygroundBridgeConfig) {
const sites = config.list();
const active = sites.find((s) => s.isActive);
if (!active) {
throw new Error('No active Playground site');
}
return active;
}
export async function registerWebMCPTools(
config: PlaygroundBridgeConfig
): Promise<void> {
const modelContext = getModelContext();
if (!modelContext) {
return;
}
// Abort any previous registration before re-registering.
registrationController?.abort();
registrationController = new AbortController();
const controller = registrationController;
const signal = controller.signal;
function getActiveClient(): PlaygroundClient {
const client = config.getClient();
if (!client) {
throw new Error('No client for active site');
}
return client;
}
// Per-site tools
const tools: ModelContextTool[] = Object.entries(toolDefinitions).map(
([name, def]) => ({
name,
description: def.description,
inputSchema: paramsToJsonSchema(def.params),
annotations: def.annotations,
execute: async (input) => {
try {
const executor = toolExecutors[name];
if (!executor) {
return {
error: `No executor for "${name}"`,
};
}
const adapter = createToolClient(getActiveClient());
return await executor(adapter, input);
} catch (error) {
return {
error: `${def.errorPrefix}: ${stringifyError(error)}`,
};
}
},
})
);
// Site management tools
tools.push(...createSiteManagementTools(config));
const results = await Promise.allSettled(
tools.map(async (tool) => {
await modelContext.registerTool(tool, { signal });
})
);
const failedRegistrations: Array<{ name: string; reason: unknown }> = [];
for (const [index, result] of results.entries()) {
if (result.status === 'rejected') {
failedRegistrations.push({
name: tools[index].name,
reason: result.reason,
});
}
}
if (failedRegistrations.length > 0) {
controller.abort();
if (registrationController === controller) {
registrationController = null;
}
throw new Error(
'Failed to register WebMCP tools: ' +
failedRegistrations
.map(
({ name, reason }) =>
`${name} (${stringifyError(reason)})`
)
.join(', ')
);
}
}
export function getModelContext(): ModelContext | undefined {
if (typeof document === 'undefined') {
return undefined;
}
const modelContext = document.modelContext;
return typeof modelContext?.registerTool === 'function'
? modelContext
: undefined;
}
function createSiteManagementTools(
config: PlaygroundBridgeConfig
): ModelContextTool[] {
const listDef = siteToolDefinitions['playground_list_sites'];
const saveDef = siteToolDefinitions['playground_save_in_browser'];
const renameDef = siteToolDefinitions['playground_rename_site'];
const websiteUrlDef = siteToolDefinitions['playground_get_website_url'];
return [
{
name: 'playground_list_sites',
description: listDef.description,
annotations: listDef.annotations,
execute: async () => {
try {
return {
connectedTabs: 1,
sites: config.list().map((s) => ({
siteId: s.slug,
name: s.name,
storage: formatStorageLabel(s.storage),
isActive: s.isActive,
})),
};
} catch (error) {
return {
error: `${listDef.errorPrefix}: ${stringifyError(error)}`,
};
}
},
},
{
name: 'playground_save_in_browser',
description: saveDef.description,
annotations: saveDef.annotations,
execute: async () => {
try {
const site = getActiveSite(config);
const storage = formatStorageLabel(site.storage);
if (storage !== 'temporary') {
return {
success: true,
alreadySaved: true,
siteId: site.slug,
name: site.name,
storage,
};
}
const saved = await config.saveInBrowser();
return {
success: true,
alreadySaved: false,
siteId: saved.slug,
name: site.name ?? saved.slug,
storage: formatStorageLabel(saved.storage),
};
} catch (error) {
return {
error: `${saveDef.errorPrefix}: ${stringifyError(error)}`,
};
}
},
},
{
name: 'playground_rename_site',
description: renameDef.description,
inputSchema: paramsToJsonSchema(renameDef.params),
annotations: renameDef.annotations,
execute: async (input) => {
try {
const newName = input['newName'] as string;
const sites = config.list();
const activeSite = sites.find((s) => s.isActive);
await config.rename(newName);
return {
success: true,
siteId: activeSite?.slug,
newName,
};
} catch (error) {
return {
error: `${renameDef.errorPrefix}: ${stringifyError(error)}`,
};
}
},
},
{
name: 'playground_get_website_url',
description: websiteUrlDef.description,
annotations: websiteUrlDef.annotations,
execute: async () => {
try {
return {
url: window.location.href,
};
} catch (error) {
return {
error: `${websiteUrlDef.errorPrefix}: ${stringifyError(error)}`,
};
}
},
},
];
}