-
-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathmcp-tools.js
More file actions
480 lines (466 loc) · 20.8 KB
/
mcp-tools.js
File metadata and controls
480 lines (466 loc) · 20.8 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { z } from "zod";
const DEFAULT_MAX_CHARS = 10000;
function _trimToCharBudget(lines, maxChars) {
let total = 0;
// Walk backwards (newest first) to keep the most recent entries
let startIdx = lines.length;
for (let i = lines.length - 1; i >= 0; i--) {
const cost = lines[i].length + 1; // +1 for newline
if (total + cost > maxChars) { break; }
total += cost;
startIdx = i;
}
return { lines: lines.slice(startIdx), trimmed: startIdx };
}
export function registerTools(server, processManager, wsControlServer, phoenixDesktopPath) {
server.tool(
"start_phoenix",
"Start the Phoenix Code desktop app (Electron). Launches npm run serve:electron in the phoenix-desktop directory.",
{},
async () => {
try {
if (processManager.isRunning()) {
return {
content: [{
type: "text",
text: JSON.stringify({
success: false,
error: "Phoenix is already running",
pid: processManager.getPid()
})
}]
};
}
const result = await processManager.start(phoenixDesktopPath);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
pid: result.pid,
wsPort: wsControlServer.getPort()
})
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ success: false, error: err.message })
}]
};
}
}
);
server.tool(
"stop_phoenix",
"Stop the running Phoenix Code desktop app.",
{},
async () => {
try {
const result = await processManager.stop();
return {
content: [{
type: "text",
text: JSON.stringify(result)
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ success: false, error: err.message })
}]
};
}
}
);
server.tool(
"get_terminal_logs",
"Get stdout/stderr output from the Electron process. Returns last 50 entries by default. " +
"USAGE: Start with default tail=50. Use filter (regex) to narrow results (e.g. filter='error|warn'). " +
"Use before=N (from previous totalEntries) to page back. Avoid tail=0 unless necessary — " +
"prefer filter + small tail to keep responses compact.",
{
clear: z.boolean().default(false).describe("If true, return all logs and clear the buffer. If false, return only new logs since last read."),
tail: z.number().default(50).describe("Return last N entries. 0 = all."),
before: z.number().optional().describe("Cursor: return entries before this totalEntries position. Use the totalEntries value from a previous response to page back stably."),
filter: z.string().optional().describe("Optional regex to filter log entries by text content. Applied before tail/before."),
maxChars: z.number().default(DEFAULT_MAX_CHARS).describe("Max character budget for log content. Oldest entries are dropped first to fit. 0 = unlimited.")
},
async ({ clear, tail, before, filter, maxChars }) => {
let logs;
if (clear) {
logs = processManager.getTerminalLogs(false);
processManager.clearTerminalLogs();
} else {
logs = processManager.getTerminalLogs(true);
}
const totalEntries = processManager.getTerminalLogsTotalPushed();
let filterRe;
if (filter) {
try {
filterRe = new RegExp(filter, "i");
} catch (e) {
return {
content: [{
type: "text",
text: `Invalid filter regex: ${e.message}`
}]
};
}
logs = logs.filter(e => filterRe.test(e.text));
}
const matchedEntries = logs.length;
const endIdx = before != null ? Math.max(0, Math.min(matchedEntries, before)) : matchedEntries;
if (tail > 0) {
const startIdx = Math.max(0, endIdx - tail);
logs = logs.slice(startIdx, endIdx);
} else {
logs = logs.slice(0, endIdx);
}
let lines = logs.map(e => `[${e.stream}] ${e.text}`);
let trimmed = 0;
if (maxChars > 0) {
const result = _trimToCharBudget(lines, maxChars);
lines = result.lines;
trimmed = result.trimmed;
}
const showing = lines.length;
const rangeEnd = endIdx;
const rangeStart = rangeEnd - logs.length;
const actualStart = rangeStart + trimmed;
const hasMore = actualStart > 0;
let header = `[Logs: ${totalEntries} total`;
if (filter) {
header += `, ${matchedEntries} matched /${filter}/i`;
}
header += `, showing ${actualStart}-${rangeEnd} (${showing} entries).`;
if (trimmed > 0) {
header += ` ${trimmed} entries trimmed to fit maxChars=${maxChars}.`;
}
if (hasMore) {
header += ` hasMore=true, use before=${actualStart} to page back.`;
}
header += `]`;
const text = lines.join("");
return {
content: [{
type: "text",
text: text ? header + "\n" + text : "(no terminal logs)"
}]
};
}
);
server.tool(
"get_browser_console_logs",
"Get console logs from the Phoenix browser runtime. Returns last 50 entries by default. " +
"This includes both browser-side console logs and Node.js (PhNode) logs, which are prefixed with 'PhNode:'. " +
"USAGE: Start with default tail=50. Use filter (regex) to narrow results (e.g. filter='error|warn'). " +
"Use before=N (from previous totalEntries) to page back. Avoid tail=0 unless necessary — " +
"prefer filter + small tail to keep responses compact.",
{
instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected."),
tail: z.number().default(50).describe("Return last N entries. 0 = all."),
before: z.number().optional().describe("Cursor: return entries before this totalEntries position. Use the totalEntries value from a previous response to page back stably."),
filter: z.string().optional().describe("Optional regex to filter log entries by message content. Applied before tail/before."),
maxChars: z.number().default(DEFAULT_MAX_CHARS).describe("Max character budget for log content. Oldest entries are dropped first to fit. 0 = unlimited.")
},
async ({ instance, tail, before, filter, maxChars }) => {
try {
const result = await wsControlServer.requestLogs(instance, { tail, before, filter });
const entries = result.entries || [];
const totalEntries = result.totalEntries || entries.length;
const matchedEntries = result.matchedEntries != null ? result.matchedEntries : entries.length;
const rangeEnd = result.rangeEnd != null ? result.rangeEnd : matchedEntries;
let lines = entries.map(e => {
let ts = "";
if (e.timestamp) {
// Show HH:MM:SS.mmm for compact display
const d = new Date(e.timestamp);
ts = d.toTimeString().slice(0, 8) + "." +
String(d.getMilliseconds()).padStart(3, "0") + " ";
}
return `[${ts}${e.level}] ${e.message}`;
});
let trimmed = 0;
if (maxChars > 0) {
const trimResult = _trimToCharBudget(lines, maxChars);
lines = trimResult.lines;
trimmed = trimResult.trimmed;
}
const showing = lines.length;
const rangeStart = rangeEnd - entries.length;
const actualStart = rangeStart + trimmed;
const hasMore = actualStart > 0;
let header = `[Logs: ${totalEntries} total`;
if (filter) {
header += `, ${matchedEntries} matched /${filter}/i`;
}
header += `, showing ${actualStart}-${rangeEnd} (${showing} entries).`;
if (trimmed > 0) {
header += ` ${trimmed} entries trimmed to fit maxChars=${maxChars}.`;
}
if (hasMore) {
header += ` hasMore=true, use before=${actualStart} to page back.`;
}
header += `]`;
if (showing === 0) {
return {
content: [{
type: "text",
text: "(no browser logs)"
}]
};
}
const text = lines.join("\n");
return {
content: [{
type: "text",
text: header + "\n" + text
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"take_screenshot",
"Take a screenshot of the Phoenix Code app window. Returns a PNG image.",
{
selector: z.string().optional().describe("Optional CSS selector to capture a specific element"),
instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.")
},
async ({ selector, instance }) => {
try {
const base64Data = await wsControlServer.requestScreenshot(selector, instance);
return {
content: [{
type: "image",
data: base64Data,
mimeType: "image/png"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"reload_phoenix",
"Reload the Phoenix Code app. Closes all open files (prompting to save unsaved changes) then reloads the app.",
{
instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.")
},
async ({ instance }) => {
try {
const result = await wsControlServer.requestReload(false, instance);
return {
content: [{
type: "text",
text: JSON.stringify({ success: true, message: "Phoenix is reloading" })
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"force_reload_phoenix",
"Force reload the Phoenix Code app without saving. Closes all open files without saving unsaved changes, then reloads the app.",
{
instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.")
},
async ({ instance }) => {
try {
const result = await wsControlServer.requestReload(true, instance);
return {
content: [{
type: "text",
text: JSON.stringify({ success: true, message: "Phoenix is force reloading (unsaved changes discarded)" })
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"exec_js",
"Execute JavaScript in the Phoenix Code browser runtime and return the result. " +
"Code runs async in the page context with access to: " +
"$ (jQuery) for DOM queries/clicks, " +
"brackets.test.CommandManager, brackets.test.EditorManager, brackets.test.ProjectManager, " +
"brackets.test.DocumentManager, brackets.test.FileSystem, brackets.test.FileUtils, " +
"and 50+ other modules on brackets.test.* — " +
"supports await.",
{
code: z.string().describe("JavaScript code to execute in Phoenix"),
instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.")
},
async ({ code, instance }) => {
try {
const result = await wsControlServer.requestExecJs(code, instance);
return {
content: [{
type: "text",
text: result !== undefined ? String(result) : "(undefined)"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"exec_js_in_live_preview",
"Execute JavaScript in the live preview iframe (the page being previewed), NOT in Phoenix itself. " +
"Auto-opens the live preview panel if it is not already visible. " +
"Code is evaluated via eval() in the global scope of the previewed page. " +
"Note: eval() is synchronous — async/await is NOT supported. " +
"Only available when an HTML file is selected in the live preview — " +
"does not work for markdown or other non-HTML file types. " +
"Use this to inspect or manipulate the user's live-previewed web page (e.g. document.title, DOM queries).",
{
code: z.string().describe("JavaScript code to execute in the live preview iframe"),
instance: z.string().optional().describe("Target a specific Phoenix instance by name (e.g. 'Phoenix-a3f2'). Required when multiple instances are connected.")
},
async ({ code, instance }) => {
try {
const result = await wsControlServer.requestExecJsLivePreview(code, instance);
return {
content: [{
type: "text",
text: result !== undefined ? String(result) : "(undefined)"
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"run_tests",
"Run tests in the Phoenix test runner (SpecRunner.html). Reloads the test runner with the specified " +
"category and optional spec filter. The test runner must already be open in a browser with MCP enabled. " +
"Supported categories: unit, integration, LegacyInteg, livepreview, mainview. " +
"WARNING: Do NOT use 'all', 'performance', 'extension', or 'individualrun' categories — they are " +
"not actively supported and the full 'all' suite should never be run. " +
"To run all tests in a category, omit the spec parameter. " +
"To run a single suite, pass the suite name as spec (e.g. spec='unit: HTML Code Hinting'). " +
"Suite names are prefixed with the category and a colon, e.g. 'unit: Editor', 'unit: CSS Parsing'. " +
"You can also run individual specs by passing the full spec name, but note that individual specs " +
"may fail when run alone because suites often run tests in order with shared state — prefer " +
"running the full suite instead of individual specs. " +
"After calling run_tests, use get_test_results to poll for results.",
{
category: z.string().describe("Test category to run: unit, integration, LegacyInteg, livepreview, or mainview."),
spec: z.string().optional().describe("Optional suite or spec name to run within the category. " +
"Use the full name including category prefix, e.g. 'unit: CSS Parsing' for a suite. " +
"Prefer running full suites over individual specs, as specs may depend on suite execution order. " +
"Omit to run all tests in the category."),
instance: z.string().optional().describe("Target a specific test runner instance by name. Required when multiple instances are connected.")
},
async ({ category, spec, instance }) => {
try {
const result = await wsControlServer.requestRunTests(category, spec, instance);
return {
content: [{
type: "text",
text: JSON.stringify({
success: true,
message: result.message || "Test runner is reloading with category=" + category
})
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"get_test_results",
"Get structured test results from the Phoenix test runner. Returns running status, pass/fail counts, " +
"failure details, and the currently executing spec. The test runner must already be open with MCP enabled.",
{
instance: z.string().optional().describe("Target a specific test runner instance by name. Required when multiple instances are connected.")
},
async ({ instance }) => {
try {
const result = await wsControlServer.requestTestResults(instance);
// Remove internal WS fields
delete result.type;
delete result.id;
return {
content: [{
type: "text",
text: JSON.stringify(result, null, 2)
}]
};
} catch (err) {
return {
content: [{
type: "text",
text: JSON.stringify({ error: err.message })
}]
};
}
}
);
server.tool(
"get_phoenix_status",
"Check the status of the Phoenix process and WebSocket connection.",
{},
async () => {
return {
content: [{
type: "text",
text: JSON.stringify({
processRunning: processManager.isRunning(),
pid: processManager.getPid(),
wsConnected: wsControlServer.isClientConnected(),
connectedInstances: wsControlServer.getConnectedInstances(),
wsPort: wsControlServer.getPort()
})
}]
};
}
);
}