plugmcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +232 -2
  3. package/dist/agent.d.ts +20 -0
  4. package/dist/agent.js +35 -0
  5. package/dist/build.d.ts +13 -0
  6. package/dist/build.js +83 -0
  7. package/dist/cli/cloud.d.ts +20 -0
  8. package/dist/cli/cloud.js +56 -0
  9. package/dist/cli/index.d.ts +2 -0
  10. package/dist/cli/index.js +326 -0
  11. package/dist/dev/api.d.ts +37 -0
  12. package/dist/dev/api.js +788 -0
  13. package/dist/dev/chat.d.ts +63 -0
  14. package/dist/dev/chat.js +159 -0
  15. package/dist/dev/dev.d.ts +22 -0
  16. package/dist/dev/dev.js +188 -0
  17. package/dist/dev/edit.d.ts +22 -0
  18. package/dist/dev/edit.js +147 -0
  19. package/dist/dev/generate.d.ts +21 -0
  20. package/dist/dev/generate.js +97 -0
  21. package/dist/dev/keys.d.ts +61 -0
  22. package/dist/dev/keys.js +55 -0
  23. package/dist/dev/project.d.ts +26 -0
  24. package/dist/dev/project.js +68 -0
  25. package/dist/dev/store.d.ts +61 -0
  26. package/dist/dev/store.js +113 -0
  27. package/dist/dev/views.d.ts +9 -0
  28. package/dist/dev/views.js +54 -0
  29. package/dist/http.d.ts +33 -0
  30. package/dist/http.js +79 -0
  31. package/dist/index.d.ts +77 -0
  32. package/dist/index.js +118 -0
  33. package/dist/install.d.ts +13 -0
  34. package/dist/install.js +54 -0
  35. package/dist/landing.d.ts +3 -0
  36. package/dist/landing.js +62 -0
  37. package/dist/stdio.d.ts +3 -0
  38. package/dist/stdio.js +5 -0
  39. package/dist/view/index.d.ts +34 -0
  40. package/dist/view/index.js +90 -0
  41. package/package.json +114 -4
  42. package/studio-dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  43. package/studio-dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  44. package/studio-dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  45. package/studio-dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  46. package/studio-dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
  47. package/studio-dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
  48. package/studio-dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
  49. package/studio-dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
  50. package/studio-dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
  51. package/studio-dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
  52. package/studio-dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  53. package/studio-dist/assets/index-BSR7LH_V.css +1 -0
  54. package/studio-dist/assets/index-D_yIYje_.js +137 -0
  55. package/studio-dist/index.html +15 -0
@@ -0,0 +1,788 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { hostHeaderValidation, originValidation } from "@modelcontextprotocol/node";
4
+ import { slugify } from "../index.js";
5
+ import { DIRECTORY_URL, directoryPage, installSnippets, readmeBadge } from "../install.js";
6
+ import { dynamicTool, jsonSchema } from "ai";
7
+ import { connect, listModels, listTools, resultForModel, streamChat } from "./chat.js";
8
+ import { GUIDE, draftTool } from "./generate.js";
9
+ import { PROVIDERS, publicSettings, readSettings, writeSettings } from "./keys.js";
10
+ import { SERVER_ID, listViews } from "./project.js";
11
+ import { setInputDescription, setServerInfo } from "./edit.js";
12
+ import { callLog, callsFor, clearCalls, readAgents, readTests, writeAgents, writeTests } from "./store.js";
13
+ const LOCAL = ["localhost", "127.0.0.1", "[::1]"];
14
+ const checkHost = hostHeaderValidation(LOCAL);
15
+ const checkOrigin = originValidation(LOCAL);
16
+ const json = (res, status, body) => void res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(body));
17
+ async function readBody(req) {
18
+ if (!(req.headers["content-type"] ?? "").includes("application/json"))
19
+ throw new Error("Send JSON.");
20
+ const chunks = [];
21
+ let size = 0;
22
+ for await (const chunk of req) {
23
+ size += chunk.length;
24
+ if (size > 8 * 1024 * 1024)
25
+ throw new Error("Request is too large.");
26
+ chunks.push(chunk);
27
+ }
28
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
29
+ }
30
+ const message = (error) => (error instanceof Error ? error.message : String(error));
31
+ // Servers added from the directory for this project's chat.
32
+ const serversFile = (project) => join(project.root, ".plugmcp", "servers.json");
33
+ function readServers(project) {
34
+ try {
35
+ return JSON.parse(readFileSync(serversFile(project), "utf8"));
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ }
41
+ export function writeServers(project, servers) {
42
+ const dir = join(project.root, ".plugmcp");
43
+ if (!existsSync(dir))
44
+ mkdirSync(dir, { recursive: true });
45
+ writeFileSync(serversFile(project), JSON.stringify(servers, null, 2));
46
+ }
47
+ const directoryCache = new Map();
48
+ /** Read the public PlugMCP directory. Answers are cached for five minutes. */
49
+ export async function directory(path) {
50
+ const hit = directoryCache.get(path);
51
+ if (hit && Date.now() - hit.at < 5 * 60_000)
52
+ return hit.body;
53
+ const response = await fetch(`${DIRECTORY_URL}/api/v1${path}`, {
54
+ headers: { accept: "application/json", "user-agent": "plugmcp-sdk" },
55
+ signal: AbortSignal.timeout(15_000),
56
+ });
57
+ if (!response.ok)
58
+ throw new Error(`The PlugMCP directory answered ${response.status}.`);
59
+ const body = (await response.json());
60
+ directoryCache.set(path, { at: Date.now(), body });
61
+ return body;
62
+ }
63
+ const TOOL_NAME = /^[a-z][a-z0-9_]{0,63}$/;
64
+ const serverVariable = (source) => /(?:const|let|var)\s+(\w+)\s*=\s*createServer\s*\(/.exec(source)?.[1];
65
+ /** Put a `server.tool(...)` statement into the server file, and a view file next to it when given. */
66
+ function writeTool(project, tool) {
67
+ if (!TOOL_NAME.test(tool.name)) {
68
+ throw new Error("Use lowercase letters, numbers and underscores, starting with a letter. Example: search_orders");
69
+ }
70
+ const entryPath = join(project.root, project.entry);
71
+ const source = readFileSync(entryPath, "utf8");
72
+ if (new RegExp(`name:\\s*["'\`]${tool.name}["'\`]`).test(source))
73
+ throw new Error(`A tool named ${tool.name} already exists.`);
74
+ const block = `${tool.block.trim()}\n\n`;
75
+ const at = source.search(/^export default /m);
76
+ writeFileSync(entryPath, at === -1 ? `${source.trimEnd()}\n\n${block}` : `${source.slice(0, at)}${block}${source.slice(at)}`);
77
+ const files = [project.entry];
78
+ let viewPath = null;
79
+ if (tool.view) {
80
+ if (!existsSync(project.viewsDir))
81
+ mkdirSync(project.viewsDir, { recursive: true });
82
+ const path = join(project.viewsDir, `${tool.name}.tsx`);
83
+ if (!existsSync(path)) {
84
+ writeFileSync(path, `${tool.view.trim()}\n`);
85
+ viewPath = path;
86
+ files.push(`views/${tool.name}.tsx`);
87
+ }
88
+ }
89
+ /** Put the project back the way it was. */
90
+ const undo = () => {
91
+ writeFileSync(entryPath, source);
92
+ if (viewPath)
93
+ rmSync(viewPath, { force: true });
94
+ };
95
+ return { files, undo };
96
+ }
97
+ function addToolToProject(project, input) {
98
+ const name = input.name.trim();
99
+ const source = readFileSync(join(project.root, project.entry), "utf8");
100
+ const variable = serverVariable(source);
101
+ if (!variable)
102
+ throw new Error(`Could not find "const server = createServer(...)" in ${project.entry}. Add the tool by hand.`);
103
+ const description = input.description.trim() || "Describe what this tool does and when to use it.";
104
+ const block = [
105
+ `${variable}.tool(`,
106
+ ` {`,
107
+ ` name: ${JSON.stringify(name)},`,
108
+ ` description: ${JSON.stringify(description)},`,
109
+ ` input: z.object({ text: z.string().describe("Replace with your own fields") }),`,
110
+ ` },`,
111
+ ` async ({ text }) => {`,
112
+ ` return { text };`,
113
+ ` },`,
114
+ `);`,
115
+ ].join("\n");
116
+ const view = input.view
117
+ ? [
118
+ `import { useTool } from "plugmcp/view";`,
119
+ ``,
120
+ `export default function View() {`,
121
+ ` const { output, isPending } = useTool<{ text: string }>();`,
122
+ ` if (isPending) return <p>Loading</p>;`,
123
+ ` return <p>{output?.text}</p>;`,
124
+ `}`,
125
+ ].join("\n")
126
+ : "";
127
+ return { files: writeTool(project, { name, block, view }).files };
128
+ }
129
+ /** Files the Studio may read and write: the server file, the views and exported agents. */
130
+ function editable(project, path) {
131
+ const ok = path === project.entry || /^views\/[A-Za-z0-9_.-]+\.(tsx|jsx)$/.test(path) || /^agents\/[a-z0-9-]+\.ts$/.test(path);
132
+ if (!ok || path.includes(".."))
133
+ throw new Error("The Studio can only open the server file, views and agents.");
134
+ return join(project.root, path);
135
+ }
136
+ const agentId = (name) => slugify(name).slice(0, 40);
137
+ const text = { type: "string" };
138
+ /** Tools that let the Studio chat write tools and views into the project, and the prompt that explains them. */
139
+ function builder(context, local) {
140
+ const { project } = context;
141
+ const source = readFileSync(join(project.root, project.entry), "utf8");
142
+ const variable = serverVariable(source) ?? "server";
143
+ const views = Object.values(listViews(project));
144
+ /** Write, load the server again, and put things back when the new code does not load. */
145
+ const settle = async (undo) => {
146
+ try {
147
+ await context.reload();
148
+ }
149
+ catch (error) {
150
+ undo();
151
+ await context.reload().catch(() => undefined);
152
+ throw new Error(`That code does not load, so nothing was changed. Fix it and call the tool again. (${message(error)})`);
153
+ }
154
+ };
155
+ const tools = {
156
+ studio_add_tool: dynamicTool({
157
+ description: "Add a new tool to the user's MCP server, with an optional view. The tool is live as soon as this returns.",
158
+ inputSchema: jsonSchema({
159
+ type: "object",
160
+ properties: {
161
+ name: { ...text, description: "Tool name: lowercase letters, numbers and underscores" },
162
+ tool: { ...text, description: `One complete ${variable}.tool(...) statement, no imports` },
163
+ view: { ...text, description: "The complete view file, or an empty string for no view" },
164
+ },
165
+ required: ["name", "tool"],
166
+ }),
167
+ execute: async (input) => {
168
+ const draft = input;
169
+ if (typeof draft.tool !== "string" || !/\.tool\s*\(/.test(draft.tool))
170
+ throw new Error(`"tool" must be one ${variable}.tool(...) statement.`);
171
+ if (/^\s*import\s/m.test(draft.tool))
172
+ throw new Error("Do not put import statements in the tool. z and fetch are already available.");
173
+ const written = writeTool(project, { name: String(draft.name ?? "").trim(), block: draft.tool, view: draft.view ?? "" });
174
+ await settle(written.undo);
175
+ return { added: draft.name, files: written.files, next: "Call studio_try_tool with realistic arguments so the user sees it work." };
176
+ },
177
+ }),
178
+ studio_read_file: dynamicTool({
179
+ description: `Read a project file: ${project.entry} or a view such as views/get_weather.tsx.`,
180
+ inputSchema: jsonSchema({ type: "object", properties: { path: text }, required: ["path"] }),
181
+ execute: async (input) => {
182
+ const { path } = input;
183
+ const file = editable(project, path);
184
+ if (!existsSync(file))
185
+ throw new Error(`${path} does not exist.`);
186
+ return { path, content: readFileSync(file, "utf8") };
187
+ },
188
+ }),
189
+ studio_write_file: dynamicTool({
190
+ description: `Replace a whole project file, to change or fix an existing tool or view. Allowed: ${project.entry} and views/<tool_name>.tsx. Send the complete new content.`,
191
+ inputSchema: jsonSchema({ type: "object", properties: { path: text, content: text }, required: ["path", "content"] }),
192
+ execute: async (input) => {
193
+ const { path, content } = input;
194
+ const file = editable(project, path);
195
+ if (typeof content !== "string" || !content.trim())
196
+ throw new Error("Send the complete file content.");
197
+ const before = existsSync(file) ? readFileSync(file, "utf8") : null;
198
+ if (!existsSync(dirname(file)))
199
+ mkdirSync(dirname(file), { recursive: true });
200
+ writeFileSync(file, content);
201
+ await settle(() => (before === null ? rmSync(file, { force: true }) : writeFileSync(file, before)));
202
+ return { saved: path };
203
+ },
204
+ }),
205
+ studio_try_tool: dynamicTool({
206
+ description: "Call any tool on the user's server by name, including one you just added. Its view is shown to the user in the chat.",
207
+ inputSchema: jsonSchema({
208
+ type: "object",
209
+ properties: { name: text, arguments: { type: "object", description: "The tool's input", additionalProperties: true } },
210
+ required: ["name"],
211
+ }),
212
+ execute: async (input) => {
213
+ const call = input;
214
+ const client = await connect(local);
215
+ try {
216
+ return (await client.callTool({ name: call.name, arguments: call.arguments ?? {} }));
217
+ }
218
+ finally {
219
+ await client.close();
220
+ }
221
+ },
222
+ toModelOutput: ({ output }) => resultForModel(output),
223
+ }),
224
+ };
225
+ const system = [
226
+ `You are the assistant inside PlugMCP Studio, working on the user's own MCP server on their machine. It is built with the "plugmcp" TypeScript SDK.`,
227
+ `What things are:\n- An MCP server is a named set of tools behind one address. This chat works on one server, the one described below.\n- A tool is one function a model can call: a name, a description, an input schema and a handler that returns data.\n- An MCP app is a tool that also has a view: a small React page shown inside the chat that draws the tool's result and can call tools back. A server and an app are built the same way; the app just adds a view file.\n- A new, separate MCP server is made with the "New MCP server" button in the Studio, not from this chat. If the user asks for a whole new server, say so in one sentence and offer to add the tools to this one.`,
228
+ `You can build. When the user asks for a tool, an MCP app, a widget, a view or a change to one, do the work yourself with the studio_ tools. Never answer with setup steps, npm commands or code for the user to paste: the project already exists and is running.`,
229
+ `How to build:\n- New tool or app: call studio_add_tool with the tool and, when the result is worth looking at, a view. An "MCP app" means a tool with a view.\n- Then call studio_try_tool with realistic arguments so the user sees it working in the chat.\n- If it fails or looks wrong, read the file with studio_read_file, fix it with studio_write_file and try again.\n- To change an existing tool or view, read the file first, then write the whole file back with the change.\n- Finish with two or three plain sentences: what you built and what the user can ask next. Do not paste the code.`,
230
+ GUIDE,
231
+ `The server variable is named "${variable}". The server file is ${project.entry}. Views are in views/<tool_name>.tsx${views.length ? `; existing: ${views.join(", ")}` : ""}.`,
232
+ `${project.entry} now:\n\n${source.slice(0, 16_000)}`,
233
+ ].join("\n\n");
234
+ return { tools, system };
235
+ }
236
+ /** A runnable Claude Agent SDK script for an agent made in the Studio. */
237
+ function agentCode(agent, project, serverName, remote) {
238
+ const local = slugify(serverName);
239
+ const entry = `../${project.entry.replace(/\.(ts|tsx)$/, ".js")}`;
240
+ const used = remote.filter((server) => agent.tools === null || agent.tools.some((id) => id.startsWith(`${server.name}__`)));
241
+ const allowed = agent.tools === null
242
+ ? null
243
+ : agent.tools.map((id) => {
244
+ const cut = id.indexOf("__");
245
+ return cut === -1 ? `mcp__${local}__${id}` : `mcp__${id.slice(0, cut)}__${id.slice(cut + 2)}`;
246
+ });
247
+ const lines = [
248
+ `// ${agent.name}. Made in PlugMCP Studio.`,
249
+ `//`,
250
+ `// ANTHROPIC_API_KEY=... npx tsx agents/${agent.id}.ts "your message"`,
251
+ ``,
252
+ `import { query } from "@anthropic-ai/claude-agent-sdk";`,
253
+ `import { toAgentSdk } from "plugmcp/agent";`,
254
+ `import server from ${JSON.stringify(entry)};`,
255
+ ``,
256
+ `// The tools from ${project.entry} run inside this process. No server to start.`,
257
+ `const local = toAgentSdk(server);`,
258
+ ``,
259
+ `const prompt = process.argv.slice(2).join(" ") || ${JSON.stringify(agent.starters?.[0] ?? "Hello. What can you do?")};`,
260
+ ``,
261
+ `for await (const message of query({`,
262
+ ` prompt,`,
263
+ ` options: {`,
264
+ ` systemPrompt: ${JSON.stringify(agent.instructions)},`,
265
+ ...(agent.provider === "anthropic" && agent.model ? [` model: ${JSON.stringify(agent.model)},`] : []),
266
+ ` mcpServers: {`,
267
+ ` ...local.mcpServers,`,
268
+ ...used.map((server) => ` ${JSON.stringify(server.name)}: { type: "http", url: ${JSON.stringify(server.url)} },`),
269
+ ` },`,
270
+ allowed
271
+ ? ` allowedTools: ${JSON.stringify(allowed)},`
272
+ : ` allowedTools: [...local.allowedTools${used.map((server) => `, ${JSON.stringify(`mcp__${server.name}`)}`).join("")}],`,
273
+ ` tools: [], // only the tools above, none of the built-in file or shell tools`,
274
+ ` },`,
275
+ `})) {`,
276
+ ` if (message.type !== "assistant") continue;`,
277
+ ` for (const block of message.message.content) {`,
278
+ ` if (block.type === "text") console.log(block.text);`,
279
+ ` if (block.type === "tool_use") console.log(\`[tool] \${block.name} \${JSON.stringify(block.input)}\`);`,
280
+ ` }`,
281
+ `}`,
282
+ ``,
283
+ ];
284
+ return lines.join("\n");
285
+ }
286
+ /** What the Studio shows about one MCP server: its details and its tools. */
287
+ async function describe(context) {
288
+ const { project } = context;
289
+ const base = { id: project.id, project: project.name, entry: project.entry, file: `${project.rel}${project.entry}`, mcpUrl: context.mcpUrl() };
290
+ let server;
291
+ try {
292
+ server = await context.loadServer();
293
+ }
294
+ catch (error) {
295
+ return { ...base, ok: false, error: message(error) };
296
+ }
297
+ const local = { name: "local", url: context.mcpUrl() };
298
+ const client = await connect(local);
299
+ let tools;
300
+ try {
301
+ tools = await listTools(client, local, true);
302
+ }
303
+ finally {
304
+ await client.close();
305
+ }
306
+ const views = listViews(project);
307
+ const unused = Object.keys(views).filter((name) => !tools.some((tool) => tool.name === name));
308
+ const count = callsFor(server.info.name);
309
+ return {
310
+ ...base,
311
+ ok: true,
312
+ name: server.info.name,
313
+ title: server.info.title ?? null,
314
+ description: server.info.description ?? null,
315
+ version: server.info.version ?? "0.1.0",
316
+ tools: tools.map((tool) => ({ ...tool, viewFile: views[tool.name] ?? null })),
317
+ unusedViews: unused.map((name) => views[name]),
318
+ instructions: server.info.instructions ?? null,
319
+ calls: count.total,
320
+ failed: count.failed,
321
+ };
322
+ }
323
+ /** Rewrite the server file with `change`, load it, and put it back if the new code does not load. */
324
+ async function editEntry(context, change) {
325
+ const path = join(context.project.root, context.project.entry);
326
+ const source = readFileSync(path, "utf8");
327
+ const next = change(source);
328
+ if (next === source)
329
+ return;
330
+ writeFileSync(path, next);
331
+ try {
332
+ await context.reload();
333
+ }
334
+ catch (error) {
335
+ writeFileSync(path, source);
336
+ await context.reload().catch(() => undefined);
337
+ throw new Error(`That did not load, so nothing was changed. (${message(error)})`);
338
+ }
339
+ }
340
+ /** Run saved tests against the running server. With no ids, every test of the server. */
341
+ export async function runSavedTests(context, ids) {
342
+ const tests = readTests(context.project).filter((test) => !ids || ids.includes(test.id));
343
+ if (tests.length === 0)
344
+ return [];
345
+ const client = await connect({ name: "local", url: context.mcpUrl() });
346
+ const out = [];
347
+ try {
348
+ for (const test of tests) {
349
+ const started = performance.now();
350
+ let failed = false;
351
+ let output = "";
352
+ try {
353
+ const result = (await client.callTool({ name: test.tool, arguments: test.arguments ?? {} }));
354
+ failed = result.isError === true;
355
+ const words = (result.content ?? []).filter((block) => block.type === "text").map((block) => block.text).join("\n");
356
+ output = words || JSON.stringify(result.structuredContent ?? {});
357
+ }
358
+ catch (error) {
359
+ failed = true;
360
+ output = message(error);
361
+ }
362
+ const wantError = test.expectError === true;
363
+ const missing = test.contains && !output.toLowerCase().includes(test.contains.toLowerCase());
364
+ const reason = failed !== wantError
365
+ ? wantError
366
+ ? "It was expected to fail and it did not."
367
+ : "The tool returned an error."
368
+ : missing
369
+ ? `The result does not contain "${test.contains}".`
370
+ : "";
371
+ out.push({ id: test.id, tool: test.tool, name: test.name, ok: !reason, ms: Math.round(performance.now() - started), reason, output: output.slice(0, 2000) });
372
+ }
373
+ }
374
+ finally {
375
+ await client.close();
376
+ }
377
+ return out;
378
+ }
379
+ /** Start a new, empty MCP server in servers/<id>/. */
380
+ function createMcp(home, input) {
381
+ const title = (input.name ?? "").trim();
382
+ if (!title)
383
+ throw new Error("Give the MCP server a name.");
384
+ const id = slugify(title).slice(0, 40).replace(/-+$/, "");
385
+ if (!SERVER_ID.test(id) || id === "main")
386
+ throw new Error("Use letters and numbers in the name.");
387
+ const dir = join(home, "servers", id);
388
+ if (existsSync(dir))
389
+ throw new Error(`An MCP server named ${id} already exists.`);
390
+ const description = (input.description ?? "").trim();
391
+ mkdirSync(join(dir, "views"), { recursive: true });
392
+ writeFileSync(join(dir, "server.ts"), [
393
+ `import { createServer } from "plugmcp";`,
394
+ `import { z } from "zod";`,
395
+ ``,
396
+ `const server = createServer({`,
397
+ ` name: ${JSON.stringify(id)},`,
398
+ ...(title !== id ? [` title: ${JSON.stringify(title)},`] : []),
399
+ ...(description ? [` description: ${JSON.stringify(description)},`] : []),
400
+ `});`,
401
+ ``,
402
+ `// Tools go here. Add them in the Studio, or write server.tool(...) yourself.`,
403
+ ``,
404
+ `export default server;`,
405
+ ``,
406
+ ].join("\n"));
407
+ return id;
408
+ }
409
+ /** Handle one request under /__studio/api/. Returns false when the path is not ours. */
410
+ export async function handleApi(req, res, hub) {
411
+ const url = new URL(req.url ?? "/", "http://localhost");
412
+ if (!url.pathname.startsWith("/__studio/api/"))
413
+ return false;
414
+ // Only this machine's own Studio page may use the API. Views run in a
415
+ // sandboxed frame with a null origin and are refused here too.
416
+ if (!checkHost(req, res) || !checkOrigin(req, res))
417
+ return true;
418
+ const route = `${req.method} ${url.pathname.slice("/__studio/api".length)}`;
419
+ const projects = hub.projects();
420
+ // Every request names the MCP server it is about. Without a name it is the first one.
421
+ const picked = projects.find((item) => item.id === url.searchParams.get("mcp")) ?? projects[0];
422
+ if (!picked)
423
+ return json(res, 500, { error: "No MCP server in this folder." }), true;
424
+ const context = hub.contextFor(picked);
425
+ const { project } = context;
426
+ const local = { name: "local", url: context.mcpUrl() };
427
+ try {
428
+ switch (route) {
429
+ case "GET /info":
430
+ return json(res, 200, await describe(context)), true;
431
+ case "GET /workspace": {
432
+ // Look again each time, so a server folder added or removed by hand shows up.
433
+ const servers = await Promise.all(hub.rescan().map((item) => describe(hub.contextFor(item))));
434
+ return json(res, 200, { name: basename(hub.home), servers }), true;
435
+ }
436
+ case "POST /workspace/servers": {
437
+ const id = createMcp(hub.home, await readBody(req));
438
+ const made = hub.rescan().find((item) => item.id === id);
439
+ if (!made)
440
+ throw new Error("The new server was written but could not be found. Restart plugmcp dev.");
441
+ await hub.contextFor(made).loadServer();
442
+ return json(res, 200, { id }), true;
443
+ }
444
+ case "POST /call": {
445
+ const body = await readBody(req);
446
+ const target = body.server && body.server !== "local" ? readServers(project).find((s) => s.name === body.server) : local;
447
+ if (!target)
448
+ throw new Error(`No server named ${body.server}.`);
449
+ const client = await connect(target);
450
+ try {
451
+ const started = performance.now();
452
+ const result = await client.callTool({ name: body.name, arguments: body.arguments ?? {} });
453
+ return json(res, 200, { result, ms: Math.round(performance.now() - started) }), true;
454
+ }
455
+ finally {
456
+ await client.close();
457
+ }
458
+ }
459
+ case "GET /view": {
460
+ const uri = url.searchParams.get("uri") ?? "";
461
+ const serverName = url.searchParams.get("server") ?? "local";
462
+ const target = serverName === "local" ? local : readServers(project).find((s) => s.name === serverName);
463
+ if (!target || !uri.startsWith("ui://"))
464
+ throw new Error("Unknown view.");
465
+ const client = await connect(target);
466
+ try {
467
+ const { contents } = await client.readResource({ uri });
468
+ const first = contents[0];
469
+ return json(res, 200, { html: first?.text ?? "", csp: first?._meta?.ui?.csp ?? null }), true;
470
+ }
471
+ finally {
472
+ await client.close();
473
+ }
474
+ }
475
+ case "GET /settings":
476
+ return json(res, 200, publicSettings(project.home)), true;
477
+ case "POST /settings": {
478
+ const body = await readBody(req);
479
+ const settings = readSettings();
480
+ if (body.provider && !(body.provider in PROVIDERS))
481
+ throw new Error("Unknown provider.");
482
+ if (body.provider)
483
+ settings.provider = body.provider;
484
+ if (body.provider && body.model !== undefined)
485
+ settings.models[body.provider] = body.model;
486
+ if (body.provider && body.key === null)
487
+ delete settings.keys[body.provider];
488
+ if (body.provider && typeof body.key === "string" && body.key.trim())
489
+ settings.keys[body.provider] = body.key.trim();
490
+ if (body.customBaseUrl !== undefined)
491
+ settings.customBaseUrl = body.customBaseUrl.trim() || undefined;
492
+ writeSettings(settings);
493
+ return json(res, 200, publicSettings(project.home)), true;
494
+ }
495
+ case "GET /models": {
496
+ const provider = url.searchParams.get("provider");
497
+ if (!(provider in PROVIDERS))
498
+ throw new Error("Unknown provider.");
499
+ return json(res, 200, { models: await listModels(provider, project.home) }), true;
500
+ }
501
+ case "POST /chat": {
502
+ const body = await readBody(req);
503
+ // An agent brings its own prompt, model and tools. A draft agent sends them in the request.
504
+ const agent = body.agent ? readAgents(project).find((item) => item.id === body.agent) : undefined;
505
+ if (agent?.provider && agent.model && !body.instructions) {
506
+ body.provider = agent.provider;
507
+ body.model = agent.model;
508
+ }
509
+ if (!(body.provider in PROVIDERS))
510
+ throw new Error("Pick a provider first.");
511
+ if (!body.model)
512
+ throw new Error("Pick a model first.");
513
+ const server = await context.loadServer();
514
+ // The plain playground chat can also write tools. An agent only uses them.
515
+ const build = body.build === true && !agent ? builder(context, local) : null;
516
+ const instructions = body.instructions?.trim() || agent?.instructions || server.info.instructions;
517
+ await streamChat(res, body, {
518
+ root: project.home,
519
+ instructions: build ? [build.system, instructions ? `Instructions for this chat, from the user:\n${instructions}` : ""].filter(Boolean).join("\n\n") : instructions,
520
+ extra: build?.tools,
521
+ allow: body.tools !== undefined ? body.tools : (agent?.tools ?? null),
522
+ servers: [{ server: local, local: true }, ...readServers(project).map((s) => ({ server: s, local: false }))],
523
+ });
524
+ return true;
525
+ }
526
+ case "GET /servers": {
527
+ const servers = readServers(project);
528
+ const withTools = await Promise.all(servers.map(async (server) => {
529
+ try {
530
+ const client = await connect(server);
531
+ try {
532
+ return { ...server, headers: undefined, ok: true, tools: await listTools(client, server, false) };
533
+ }
534
+ finally {
535
+ await client.close();
536
+ }
537
+ }
538
+ catch (error) {
539
+ return { ...server, headers: undefined, ok: false, error: message(error), tools: [] };
540
+ }
541
+ }));
542
+ return json(res, 200, { servers: withTools }), true;
543
+ }
544
+ case "POST /servers": {
545
+ const body = await readBody(req);
546
+ let entry;
547
+ if (body.slug) {
548
+ const record = (await directory(`/servers/${encodeURIComponent(body.slug)}`));
549
+ if (!record.remote_url)
550
+ throw new Error("This server has no hosted address, so it cannot be added to the chat. Open its page for install steps.");
551
+ entry = { name: slugify(record.name).slice(0, 32), url: record.remote_url, slug: body.slug };
552
+ }
553
+ else if (body.url && /^https?:\/\//.test(body.url)) {
554
+ entry = { name: slugify(body.name ?? new URL(body.url).hostname).slice(0, 32), url: body.url };
555
+ }
556
+ else {
557
+ throw new Error("Give a directory slug or an http address.");
558
+ }
559
+ const client = await connect(entry).catch((error) => {
560
+ throw new Error(`Could not connect to ${entry.url}. It may need sign-in. (${message(error)})`);
561
+ });
562
+ await client.close();
563
+ const servers = readServers(project).filter((s) => s.name !== entry.name);
564
+ writeServers(project, [...servers, entry]);
565
+ return json(res, 200, { added: entry.name }), true;
566
+ }
567
+ case "DELETE /servers": {
568
+ const name = url.searchParams.get("name");
569
+ writeServers(project, readServers(project).filter((s) => s.name !== name));
570
+ return json(res, 200, { removed: name }), true;
571
+ }
572
+ case "GET /directory": {
573
+ const params = new URLSearchParams({ q: url.searchParams.get("q") ?? "" });
574
+ if (url.searchParams.get("remote") === "1")
575
+ params.set("remote", "1");
576
+ if (url.searchParams.get("page"))
577
+ params.set("page", url.searchParams.get("page"));
578
+ return json(res, 200, await directory(`/servers?${params}`)), true;
579
+ }
580
+ case "POST /tools": {
581
+ const body = await readBody(req);
582
+ const added = addToolToProject(project, { name: body.name ?? "", description: body.description ?? "", view: body.view === true });
583
+ // Load the new code now. Waiting for the file watcher can leave the old tool list in place for a moment.
584
+ await context.reload().catch(() => undefined);
585
+ return json(res, 200, added), true;
586
+ }
587
+ case "POST /tools/describe": {
588
+ const body = await readBody(req);
589
+ const name = body.name ?? "";
590
+ const description = (body.description ?? "").trim();
591
+ if (!TOOL_NAME.test(name))
592
+ throw new Error("Unknown tool.");
593
+ if (!description)
594
+ throw new Error("Write a description.");
595
+ const entryPath = join(project.root, project.entry);
596
+ const source = readFileSync(entryPath, "utf8");
597
+ const start = new RegExp(`name:\\s*["'\`]${name}["'\`]`).exec(source);
598
+ if (!start)
599
+ throw new Error(`Could not find ${name} in ${project.entry}.`);
600
+ // Look only inside this tool's own options, up to the next tool.
601
+ const rest = source.slice(start.index);
602
+ const next = rest.slice(1).search(/\.tool\s*\(/);
603
+ const own = next === -1 ? rest : rest.slice(0, next + 1);
604
+ const found = /description:\s*("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\$]|\\.)*`)/.exec(own);
605
+ if (!found)
606
+ throw new Error(`The description of ${name} is not a plain string. Change it on the Code tab.`);
607
+ const at = start.index + found.index;
608
+ writeFileSync(entryPath, `${source.slice(0, at)}description: ${JSON.stringify(description)}${source.slice(at + found[0].length)}`);
609
+ try {
610
+ await context.reload();
611
+ }
612
+ catch (error) {
613
+ writeFileSync(entryPath, source);
614
+ await context.reload().catch(() => undefined);
615
+ throw new Error(`That did not load, so nothing was changed. (${message(error)})`);
616
+ }
617
+ return json(res, 200, { saved: true }), true;
618
+ }
619
+ case "POST /tools/describe-input": {
620
+ const body = await readBody(req);
621
+ const description = (body.description ?? "").trim();
622
+ if (!TOOL_NAME.test(body.tool ?? "") || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(body.field ?? ""))
623
+ throw new Error("Unknown tool or input.");
624
+ if (!description)
625
+ throw new Error("Write a description.");
626
+ await editEntry(context, (source) => setInputDescription(source, body.tool, body.field, description));
627
+ return json(res, 200, { saved: true }), true;
628
+ }
629
+ case "POST /workspace/describe": {
630
+ const body = await readBody(req);
631
+ await editEntry(context, (source) => setServerInfo(source, { title: body.title, description: body.description }));
632
+ return json(res, 200, { saved: true }), true;
633
+ }
634
+ case "GET /tests":
635
+ return json(res, 200, { tests: readTests(project) }), true;
636
+ case "POST /tests": {
637
+ const body = await readBody(req);
638
+ if (!TOOL_NAME.test(body.tool ?? ""))
639
+ throw new Error("Unknown tool.");
640
+ const tests = readTests(project);
641
+ const existing = tests.find((test) => test.id === body.id);
642
+ const test = {
643
+ id: existing?.id ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
644
+ tool: body.tool,
645
+ name: (body.name ?? "").trim().slice(0, 120) || `${body.tool} test ${tests.filter((item) => item.tool === body.tool).length + 1}`,
646
+ arguments: body.arguments && typeof body.arguments === "object" ? body.arguments : {},
647
+ ...(body.expectError === true ? { expectError: true } : {}),
648
+ ...(body.contains?.trim() ? { contains: body.contains.trim().slice(0, 400) } : {}),
649
+ };
650
+ writeTests(project, existing ? tests.map((item) => (item.id === test.id ? test : item)) : [...tests, test]);
651
+ return json(res, 200, { test }), true;
652
+ }
653
+ case "DELETE /tests": {
654
+ const id = url.searchParams.get("id");
655
+ writeTests(project, readTests(project).filter((test) => test.id !== id));
656
+ return json(res, 200, { removed: id }), true;
657
+ }
658
+ case "POST /tests/run": {
659
+ const body = await readBody(req).catch(() => ({}));
660
+ return json(res, 200, { results: await runSavedTests(context, Array.isArray(body.ids) ? body.ids : undefined) }), true;
661
+ }
662
+ case "POST /generate": {
663
+ const body = await readBody(req);
664
+ if (!body.description?.trim())
665
+ throw new Error("Say what the tool should do.");
666
+ if (!body.provider || !(body.provider in PROVIDERS) || !body.model)
667
+ throw new Error("Choose a model first, in Settings.");
668
+ const source = readFileSync(join(project.root, project.entry), "utf8");
669
+ const variable = serverVariable(source);
670
+ if (!variable)
671
+ throw new Error(`Could not find "const server = createServer(...)" in ${project.entry}.`);
672
+ const draft = await draftTool({
673
+ root: project.home,
674
+ provider: body.provider,
675
+ model: body.model,
676
+ description: body.description.trim(),
677
+ wantView: body.view !== false,
678
+ variable,
679
+ source,
680
+ });
681
+ const written = writeTool(project, { name: draft.name, block: draft.tool, view: draft.view });
682
+ try {
683
+ await context.reload();
684
+ }
685
+ catch (error) {
686
+ // Never leave the project broken by code the user did not write.
687
+ written.undo();
688
+ await context.reload().catch(() => undefined);
689
+ throw new Error(`The model wrote code that does not load, so nothing was changed. Try again. (${message(error)})`);
690
+ }
691
+ return json(res, 200, { name: draft.name, files: written.files }), true;
692
+ }
693
+ case "GET /file": {
694
+ const path = url.searchParams.get("path") ?? "";
695
+ const file = editable(project, path);
696
+ return json(res, 200, { path, content: existsSync(file) ? readFileSync(file, "utf8") : "" }), true;
697
+ }
698
+ case "POST /file": {
699
+ const body = await readBody(req);
700
+ const file = editable(project, body.path ?? "");
701
+ if (typeof body.content !== "string")
702
+ throw new Error("Nothing to save.");
703
+ if (!existsSync(dirname(file)))
704
+ mkdirSync(dirname(file), { recursive: true });
705
+ writeFileSync(file, body.content);
706
+ if (body.path !== project.entry)
707
+ return json(res, 200, { saved: true, error: null }), true;
708
+ // Say right away when the server file no longer loads.
709
+ const error = await context.reload().then(() => null, (cause) => message(cause));
710
+ return json(res, 200, { saved: true, error }), true;
711
+ }
712
+ case "GET /logs":
713
+ return json(res, 200, callLog()), true;
714
+ case "DELETE /logs":
715
+ return clearCalls(), json(res, 200, callLog()), true;
716
+ case "GET /agents":
717
+ return json(res, 200, { agents: readAgents(project) }), true;
718
+ case "POST /agents": {
719
+ const body = await readBody(req);
720
+ const name = (body.name ?? "").trim();
721
+ if (!name)
722
+ throw new Error("Give the agent a name.");
723
+ const agents = readAgents(project);
724
+ const known = Boolean(body.id && agents.some((item) => item.id === body.id));
725
+ const id = known ? body.id : agentId(name);
726
+ if (!known && agents.some((item) => item.id === id))
727
+ throw new Error(`An agent named ${name} already exists.`);
728
+ const agent = {
729
+ id,
730
+ name,
731
+ description: body.description?.trim() || undefined,
732
+ instructions: (body.instructions ?? "").trim(),
733
+ provider: body.provider && body.provider in PROVIDERS ? body.provider : undefined,
734
+ model: body.model || undefined,
735
+ tools: Array.isArray(body.tools) ? body.tools : null,
736
+ starters: (body.starters ?? []).map((text) => text.trim()).filter(Boolean).slice(0, 4),
737
+ };
738
+ writeAgents(project, known ? agents.map((item) => (item.id === id ? agent : item)) : [...agents, agent]);
739
+ return json(res, 200, { agent }), true;
740
+ }
741
+ case "DELETE /agents": {
742
+ const id = url.searchParams.get("id");
743
+ writeAgents(project, readAgents(project).filter((item) => item.id !== id));
744
+ return json(res, 200, { removed: id }), true;
745
+ }
746
+ case "GET /agents/code":
747
+ case "POST /agents/code": {
748
+ const id = url.searchParams.get("id");
749
+ const agent = readAgents(project).find((item) => item.id === id);
750
+ if (!agent)
751
+ throw new Error("No such agent. Save it first.");
752
+ const server = await context.loadServer();
753
+ const code = agentCode(agent, project, server.info.name, readServers(project));
754
+ const path = `agents/${agent.id}.ts`;
755
+ if (req.method === "POST") {
756
+ const file = editable(project, path);
757
+ if (!existsSync(dirname(file)))
758
+ mkdirSync(dirname(file), { recursive: true });
759
+ writeFileSync(file, code);
760
+ }
761
+ return json(res, 200, { path, code, saved: req.method === "POST" }), true;
762
+ }
763
+ case "GET /ship": {
764
+ const server = await context.loadServer();
765
+ const slug = slugify(server.info.name);
766
+ return (json(res, 200, {
767
+ name: server.info.name,
768
+ slug,
769
+ snippets: installSnippets(slug, context.mcpUrl().replace("127.0.0.1", "localhost")),
770
+ badge: readmeBadge(slug),
771
+ directoryPage: directoryPage(slug),
772
+ submitUrl: `${DIRECTORY_URL}/mcp/submit`,
773
+ hostUrl: `${DIRECTORY_URL}/app`,
774
+ }),
775
+ true);
776
+ }
777
+ default:
778
+ return json(res, 404, { error: "Unknown Studio route." }), true;
779
+ }
780
+ }
781
+ catch (error) {
782
+ if (!res.headersSent)
783
+ json(res, 400, { error: message(error) });
784
+ else
785
+ res.end();
786
+ return true;
787
+ }
788
+ }