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.
- package/LICENSE +21 -0
- package/README.md +232 -2
- package/dist/agent.d.ts +20 -0
- package/dist/agent.js +35 -0
- package/dist/build.d.ts +13 -0
- package/dist/build.js +83 -0
- package/dist/cli/cloud.d.ts +20 -0
- package/dist/cli/cloud.js +56 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +326 -0
- package/dist/dev/api.d.ts +37 -0
- package/dist/dev/api.js +788 -0
- package/dist/dev/chat.d.ts +63 -0
- package/dist/dev/chat.js +159 -0
- package/dist/dev/dev.d.ts +22 -0
- package/dist/dev/dev.js +188 -0
- package/dist/dev/edit.d.ts +22 -0
- package/dist/dev/edit.js +147 -0
- package/dist/dev/generate.d.ts +21 -0
- package/dist/dev/generate.js +97 -0
- package/dist/dev/keys.d.ts +61 -0
- package/dist/dev/keys.js +55 -0
- package/dist/dev/project.d.ts +26 -0
- package/dist/dev/project.js +68 -0
- package/dist/dev/store.d.ts +61 -0
- package/dist/dev/store.js +113 -0
- package/dist/dev/views.d.ts +9 -0
- package/dist/dev/views.js +54 -0
- package/dist/http.d.ts +33 -0
- package/dist/http.js +79 -0
- package/dist/index.d.ts +77 -0
- package/dist/index.js +118 -0
- package/dist/install.d.ts +13 -0
- package/dist/install.js +54 -0
- package/dist/landing.d.ts +3 -0
- package/dist/landing.js +62 -0
- package/dist/stdio.d.ts +3 -0
- package/dist/stdio.js +5 -0
- package/dist/view/index.d.ts +34 -0
- package/dist/view/index.js +90 -0
- package/package.json +114 -4
- package/studio-dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/studio-dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/studio-dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/studio-dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/studio-dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/studio-dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/studio-dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/studio-dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/studio-dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/studio-dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/studio-dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/studio-dist/assets/index-BSR7LH_V.css +1 -0
- package/studio-dist/assets/index-D_yIYje_.js +137 -0
- package/studio-dist/index.html +15 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
import { Client } from "@modelcontextprotocol/client";
|
|
3
|
+
import type { LanguageModel, ToolSet, UIMessage } from "ai";
|
|
4
|
+
import type { ProviderId } from "./keys.js";
|
|
5
|
+
export interface RemoteServer {
|
|
6
|
+
name: string;
|
|
7
|
+
url: string;
|
|
8
|
+
headers?: Record<string, string>;
|
|
9
|
+
/** Directory slug, when it was added from the PlugMCP directory. */
|
|
10
|
+
slug?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface ToolInfo {
|
|
13
|
+
/** Name the model sees. */
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
server: string;
|
|
17
|
+
title?: string;
|
|
18
|
+
description?: string;
|
|
19
|
+
inputSchema: Record<string, unknown>;
|
|
20
|
+
/** ui:// address of the tool's view, if it has one. */
|
|
21
|
+
view: string | null;
|
|
22
|
+
local: boolean;
|
|
23
|
+
}
|
|
24
|
+
export declare function connect(server: RemoteServer): Promise<Client>;
|
|
25
|
+
export declare function listTools(client: Client, server: RemoteServer, local: boolean): Promise<ToolInfo[]>;
|
|
26
|
+
export declare function createModel(provider: ProviderId, model: string, key: string | undefined, customBaseUrl: string | undefined): LanguageModel;
|
|
27
|
+
/** Ask the provider which models this key can use, so nothing is hard-coded here. */
|
|
28
|
+
export declare function listModels(provider: ProviderId, root: string): Promise<string[]>;
|
|
29
|
+
interface ChatRequest {
|
|
30
|
+
messages: UIMessage[];
|
|
31
|
+
provider: ProviderId;
|
|
32
|
+
model: string;
|
|
33
|
+
}
|
|
34
|
+
export interface McpResult {
|
|
35
|
+
content?: Array<{
|
|
36
|
+
type: string;
|
|
37
|
+
text?: string;
|
|
38
|
+
}>;
|
|
39
|
+
structuredContent?: unknown;
|
|
40
|
+
isError?: boolean;
|
|
41
|
+
}
|
|
42
|
+
/** What the model reads back from a tool call. */
|
|
43
|
+
export declare function resultForModel(result: McpResult): {
|
|
44
|
+
readonly type: "error-text";
|
|
45
|
+
readonly value: string;
|
|
46
|
+
} | {
|
|
47
|
+
readonly type: "text";
|
|
48
|
+
readonly value: string;
|
|
49
|
+
};
|
|
50
|
+
/** Run one chat turn: the model, the tools of every connected server, streamed to the browser. */
|
|
51
|
+
export declare function streamChat(res: ServerResponse, body: ChatRequest, context: {
|
|
52
|
+
root: string;
|
|
53
|
+
servers: Array<{
|
|
54
|
+
server: RemoteServer;
|
|
55
|
+
local: boolean;
|
|
56
|
+
}>;
|
|
57
|
+
instructions?: string;
|
|
58
|
+
/** Tool ids the model may call. Leave out for all of them. */
|
|
59
|
+
allow?: string[] | null;
|
|
60
|
+
/** Tools of the Studio itself, such as the ones that write code. */
|
|
61
|
+
extra?: ToolSet;
|
|
62
|
+
}): Promise<void>;
|
|
63
|
+
export {};
|
package/dist/dev/chat.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
2
|
+
import { createGoogleGenerativeAI } from "@ai-sdk/google";
|
|
3
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
4
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
5
|
+
import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
|
|
6
|
+
import { convertToModelMessages, dynamicTool, isStepCount, jsonSchema, streamText } from "ai";
|
|
7
|
+
import { PROVIDERS, readSettings, resolveKey } from "./keys.js";
|
|
8
|
+
import { recordCall } from "./store.js";
|
|
9
|
+
export async function connect(server) {
|
|
10
|
+
const client = new Client({ name: "plugmcp-studio", version: "0.1.0" });
|
|
11
|
+
await client.connect(new StreamableHTTPClientTransport(new URL(server.url), server.headers ? { requestInit: { headers: server.headers } } : undefined));
|
|
12
|
+
return client;
|
|
13
|
+
}
|
|
14
|
+
const safe = (text) => text.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
15
|
+
export async function listTools(client, server, local) {
|
|
16
|
+
const { tools } = await client.listTools();
|
|
17
|
+
return tools.map((tool) => {
|
|
18
|
+
const meta = tool._meta;
|
|
19
|
+
return {
|
|
20
|
+
id: local ? tool.name : `${safe(server.name)}__${safe(tool.name)}`.slice(0, 64),
|
|
21
|
+
name: tool.name,
|
|
22
|
+
server: server.name,
|
|
23
|
+
title: tool.title,
|
|
24
|
+
description: tool.description,
|
|
25
|
+
inputSchema: tool.inputSchema,
|
|
26
|
+
view: meta?.ui?.resourceUri ?? meta?.["ui/resourceUri"] ?? null,
|
|
27
|
+
local,
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const BASE_URLS = { openrouter: "https://openrouter.ai/api/v1", ollama: "http://localhost:11434/v1" };
|
|
32
|
+
export function createModel(provider, model, key, customBaseUrl) {
|
|
33
|
+
if (PROVIDERS[provider].needsKey && !key) {
|
|
34
|
+
throw new Error(`No ${PROVIDERS[provider].label} key. Add one in the Studio under Models and keys, or as ${PROVIDERS[provider].env} in .env.`);
|
|
35
|
+
}
|
|
36
|
+
switch (provider) {
|
|
37
|
+
case "openai":
|
|
38
|
+
return createOpenAI({ apiKey: key })(model);
|
|
39
|
+
case "anthropic":
|
|
40
|
+
return createAnthropic({ apiKey: key })(model);
|
|
41
|
+
case "google":
|
|
42
|
+
return createGoogleGenerativeAI({ apiKey: key })(model);
|
|
43
|
+
case "openrouter":
|
|
44
|
+
return createOpenAICompatible({ name: "openrouter", baseURL: BASE_URLS.openrouter, apiKey: key })(model);
|
|
45
|
+
case "ollama":
|
|
46
|
+
return createOpenAICompatible({ name: "ollama", baseURL: BASE_URLS.ollama })(model);
|
|
47
|
+
case "custom":
|
|
48
|
+
if (!customBaseUrl)
|
|
49
|
+
throw new Error("Set the base address for the OpenAI-compatible provider first.");
|
|
50
|
+
return createOpenAICompatible({ name: "custom", baseURL: customBaseUrl, apiKey: key })(model);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
/** Ask the provider which models this key can use, so nothing is hard-coded here. */
|
|
54
|
+
export async function listModels(provider, root) {
|
|
55
|
+
const { key } = resolveKey(provider, root);
|
|
56
|
+
const settings = readSettings();
|
|
57
|
+
const get = async (url, headers) => {
|
|
58
|
+
const response = await fetch(url, { headers, signal: AbortSignal.timeout(8000) });
|
|
59
|
+
if (!response.ok)
|
|
60
|
+
throw new Error(`${PROVIDERS[provider].label} answered ${response.status} when listing models.`);
|
|
61
|
+
return (await response.json());
|
|
62
|
+
};
|
|
63
|
+
const ids = (rows, field = "id") => (Array.isArray(rows) ? rows : []).map((row) => String(row[field])).filter(Boolean);
|
|
64
|
+
const bearer = key ? { authorization: `Bearer ${key}` } : {};
|
|
65
|
+
switch (provider) {
|
|
66
|
+
case "openai": {
|
|
67
|
+
const data = (await get("https://api.openai.com/v1/models", bearer)).data;
|
|
68
|
+
const chat = data.filter((m) => /^(gpt|o\d|chatgpt)/.test(m.id) && !/(audio|realtime|tts|transcribe|image|embedding|search|instruct)/.test(m.id));
|
|
69
|
+
return chat.sort((a, b) => (b.created ?? 0) - (a.created ?? 0)).map((m) => m.id);
|
|
70
|
+
}
|
|
71
|
+
case "anthropic":
|
|
72
|
+
return ids((await get("https://api.anthropic.com/v1/models?limit=100", { "x-api-key": key ?? "", "anthropic-version": "2023-06-01" })).data);
|
|
73
|
+
case "google":
|
|
74
|
+
return ids((await get(`https://generativelanguage.googleapis.com/v1beta/models?pageSize=200`, { "x-goog-api-key": key ?? "" })).models, "name")
|
|
75
|
+
.map((name) => name.replace(/^models\//, ""))
|
|
76
|
+
.filter((name) => name.startsWith("gemini"));
|
|
77
|
+
case "openrouter":
|
|
78
|
+
return ids((await get(`${BASE_URLS.openrouter}/models`, bearer)).data);
|
|
79
|
+
case "ollama":
|
|
80
|
+
return ids((await get("http://localhost:11434/api/tags", {})).models, "name");
|
|
81
|
+
case "custom":
|
|
82
|
+
if (!settings.customBaseUrl)
|
|
83
|
+
return [];
|
|
84
|
+
return ids((await get(`${settings.customBaseUrl.replace(/\/$/, "")}/models`, bearer)).data);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** What the model reads back from a tool call. */
|
|
88
|
+
export function resultForModel(result) {
|
|
89
|
+
const text = (result.content ?? []).filter((b) => b.type === "text").map((b) => b.text).join("\n");
|
|
90
|
+
const value = text || JSON.stringify(result.structuredContent ?? {});
|
|
91
|
+
return result.isError ? { type: "error-text", value } : { type: "text", value };
|
|
92
|
+
}
|
|
93
|
+
/** Run one chat turn: the model, the tools of every connected server, streamed to the browser. */
|
|
94
|
+
export async function streamChat(res, body, context) {
|
|
95
|
+
const { key } = resolveKey(body.provider, context.root);
|
|
96
|
+
const model = createModel(body.provider, body.model, key, readSettings().customBaseUrl);
|
|
97
|
+
const clients = [];
|
|
98
|
+
const tools = {};
|
|
99
|
+
const close = async () => {
|
|
100
|
+
await Promise.allSettled(clients.map((client) => client.close()));
|
|
101
|
+
};
|
|
102
|
+
try {
|
|
103
|
+
for (const { server, local } of context.servers) {
|
|
104
|
+
let client;
|
|
105
|
+
try {
|
|
106
|
+
client = await connect(server);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (local)
|
|
110
|
+
throw error;
|
|
111
|
+
continue; // A remote server that is down should not block the chat.
|
|
112
|
+
}
|
|
113
|
+
clients.push(client);
|
|
114
|
+
for (const info of await listTools(client, server, local)) {
|
|
115
|
+
if (context.allow && !context.allow.includes(info.id))
|
|
116
|
+
continue;
|
|
117
|
+
tools[info.id] = dynamicTool({
|
|
118
|
+
description: info.description ?? info.title ?? info.name,
|
|
119
|
+
inputSchema: jsonSchema(info.inputSchema),
|
|
120
|
+
execute: async (input) => {
|
|
121
|
+
const started = performance.now();
|
|
122
|
+
const result = (await client.callTool({ name: info.name, arguments: (input ?? {}) }));
|
|
123
|
+
// Local tools report their own calls. Record the ones that ran somewhere else.
|
|
124
|
+
if (!local) {
|
|
125
|
+
recordCall({
|
|
126
|
+
tool: info.name,
|
|
127
|
+
server: server.name,
|
|
128
|
+
ms: Math.round(performance.now() - started),
|
|
129
|
+
ok: result.isError !== true,
|
|
130
|
+
input,
|
|
131
|
+
output: result.structuredContent ?? result.content,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
return result;
|
|
135
|
+
},
|
|
136
|
+
toModelOutput: ({ output }) => resultForModel(output),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
Object.assign(tools, context.extra);
|
|
141
|
+
const result = streamText({
|
|
142
|
+
model,
|
|
143
|
+
system: context.instructions,
|
|
144
|
+
messages: await convertToModelMessages(body.messages, { tools }),
|
|
145
|
+
tools,
|
|
146
|
+
stopWhen: isStepCount(context.extra ? 24 : 12),
|
|
147
|
+
onFinish: close,
|
|
148
|
+
onError: close,
|
|
149
|
+
onAbort: close,
|
|
150
|
+
});
|
|
151
|
+
await result.pipeUIMessageStreamToResponse(res, {
|
|
152
|
+
onError: (error) => (error instanceof Error ? error.message : String(error)),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
await close();
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface DevOptions {
|
|
2
|
+
root: string;
|
|
3
|
+
entry?: string;
|
|
4
|
+
port?: number;
|
|
5
|
+
/** Serve the Studio. Default true. */
|
|
6
|
+
studio?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface DevServer {
|
|
9
|
+
port: number;
|
|
10
|
+
url: string;
|
|
11
|
+
mcpUrl: string;
|
|
12
|
+
/** Every MCP server in the folder and where it answers. */
|
|
13
|
+
servers: Array<{
|
|
14
|
+
id: string;
|
|
15
|
+
mcpUrl: string;
|
|
16
|
+
}>;
|
|
17
|
+
readyMs: number;
|
|
18
|
+
close: () => Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
/** The prebuilt Studio that ships inside this package. */
|
|
21
|
+
export declare function studioDir(): string;
|
|
22
|
+
export declare function startDev(options: DevOptions): Promise<DevServer>;
|
package/dist/dev/dev.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { createServer as createNodeServer } from "node:http";
|
|
3
|
+
import { dirname, extname, join, normalize } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import react from "@vitejs/plugin-react";
|
|
6
|
+
import { createServer as createViteServer } from "vite";
|
|
7
|
+
import { createHttpHandler, listen } from "../http.js";
|
|
8
|
+
import { isPlugServer } from "../index.js";
|
|
9
|
+
import { handleApi } from "./api.js";
|
|
10
|
+
import { listViews, resolveWorkspace } from "./project.js";
|
|
11
|
+
import { listenForCalls } from "./store.js";
|
|
12
|
+
import { viewEntryPlugin, viewShell } from "./views.js";
|
|
13
|
+
const MIME = {
|
|
14
|
+
".html": "text/html; charset=utf-8",
|
|
15
|
+
".js": "text/javascript; charset=utf-8",
|
|
16
|
+
".css": "text/css; charset=utf-8",
|
|
17
|
+
".svg": "image/svg+xml",
|
|
18
|
+
".png": "image/png",
|
|
19
|
+
".woff2": "font/woff2",
|
|
20
|
+
".json": "application/json",
|
|
21
|
+
".ico": "image/x-icon",
|
|
22
|
+
};
|
|
23
|
+
/** The prebuilt Studio that ships inside this package. */
|
|
24
|
+
export function studioDir() {
|
|
25
|
+
return join(dirname(fileURLToPath(import.meta.url)), "..", "..", "studio-dist");
|
|
26
|
+
}
|
|
27
|
+
export async function startDev(options) {
|
|
28
|
+
const started = performance.now();
|
|
29
|
+
let projects = resolveWorkspace(options.root, options.entry);
|
|
30
|
+
const home = options.root;
|
|
31
|
+
// Views of every server share one dev server. A view outside the main server is "<server>~<tool>".
|
|
32
|
+
const viewKey = (project, tool) => (project.rel ? `${project.id}~${tool}` : tool);
|
|
33
|
+
const allViews = () => {
|
|
34
|
+
const all = {};
|
|
35
|
+
for (const project of projects) {
|
|
36
|
+
for (const [tool, file] of Object.entries(listViews(project)))
|
|
37
|
+
all[viewKey(project, tool)] = `${project.rel}${file}`;
|
|
38
|
+
}
|
|
39
|
+
return all;
|
|
40
|
+
};
|
|
41
|
+
const node = createNodeServer();
|
|
42
|
+
let port = options.port ?? 3333;
|
|
43
|
+
const origin = () => `http://127.0.0.1:${port}`;
|
|
44
|
+
const vite = await createViteServer({
|
|
45
|
+
root: home,
|
|
46
|
+
configFile: false,
|
|
47
|
+
appType: "custom",
|
|
48
|
+
logLevel: "warn",
|
|
49
|
+
clearScreen: false,
|
|
50
|
+
plugins: [react(), viewEntryPlugin(allViews)],
|
|
51
|
+
server: {
|
|
52
|
+
middlewareMode: true,
|
|
53
|
+
hmr: { server: node },
|
|
54
|
+
// Views run in a sandboxed frame with a null origin and load their code from here.
|
|
55
|
+
cors: { origin: true },
|
|
56
|
+
},
|
|
57
|
+
optimizeDeps: {
|
|
58
|
+
entries: ["views/*.tsx", "views/*.jsx", "servers/*/views/*.tsx", "servers/*/views/*.jsx"],
|
|
59
|
+
include: ["react", "react-dom/client", "react/jsx-runtime", "react/jsx-dev-runtime"],
|
|
60
|
+
},
|
|
61
|
+
ssr: { external: ["plugmcp"] },
|
|
62
|
+
});
|
|
63
|
+
const loadServer = async (project) => {
|
|
64
|
+
const module = (await vite.ssrLoadModule(`/${project.rel}${project.entry}`));
|
|
65
|
+
const server = module.default ?? module.server;
|
|
66
|
+
if (!isPlugServer(server)) {
|
|
67
|
+
throw new Error(`${project.rel}${project.entry} must default-export the server: "export default server".`);
|
|
68
|
+
}
|
|
69
|
+
return server;
|
|
70
|
+
};
|
|
71
|
+
const reload = async (project) => {
|
|
72
|
+
vite.moduleGraph.invalidateAll();
|
|
73
|
+
return loadServer(project);
|
|
74
|
+
};
|
|
75
|
+
listenForCalls(home);
|
|
76
|
+
// In dev a view is a small page that loads its code from this server, so edits hot reload.
|
|
77
|
+
const getViews = (project) => {
|
|
78
|
+
const views = {};
|
|
79
|
+
for (const tool of Object.keys(listViews(project))) {
|
|
80
|
+
const key = viewKey(project, tool);
|
|
81
|
+
views[tool] = {
|
|
82
|
+
csp: { connectDomains: [origin(), origin().replace("http", "ws")], resourceDomains: [origin()] },
|
|
83
|
+
html: async () => {
|
|
84
|
+
const html = await vite.transformIndexHtml(`/__view/${key}.html`, viewShell(key));
|
|
85
|
+
return html.replace(/(src=|from\s*|import\s*)(["'])\/(?!\/)/g, `$1$2${origin()}/`);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
return views;
|
|
90
|
+
};
|
|
91
|
+
// One MCP endpoint per server: /mcp for the main one, /mcp/<id> for the others.
|
|
92
|
+
const handlers = new Map();
|
|
93
|
+
const handlerFor = (project) => {
|
|
94
|
+
let handler = handlers.get(project.id);
|
|
95
|
+
if (!handler) {
|
|
96
|
+
handler = createHttpHandler(() => loadServer(project), { getViews: () => getViews(project) });
|
|
97
|
+
handlers.set(project.id, handler);
|
|
98
|
+
}
|
|
99
|
+
return handler;
|
|
100
|
+
};
|
|
101
|
+
const hub = {
|
|
102
|
+
home,
|
|
103
|
+
projects: () => projects,
|
|
104
|
+
rescan: () => {
|
|
105
|
+
projects = resolveWorkspace(options.root, options.entry);
|
|
106
|
+
return projects;
|
|
107
|
+
},
|
|
108
|
+
contextFor: (project) => ({
|
|
109
|
+
project,
|
|
110
|
+
mcpUrl: () => `${origin()}${project.mount}`,
|
|
111
|
+
loadServer: () => loadServer(project),
|
|
112
|
+
reload: () => reload(project),
|
|
113
|
+
}),
|
|
114
|
+
};
|
|
115
|
+
const studio = studioDir();
|
|
116
|
+
const hasStudio = options.studio !== false && existsSync(join(studio, "index.html"));
|
|
117
|
+
const sendFile = (res, file, cache) => {
|
|
118
|
+
res.writeHead(200, {
|
|
119
|
+
"content-type": MIME[extname(file)] ?? "application/octet-stream",
|
|
120
|
+
"cache-control": cache ? "public, max-age=31536000, immutable" : "no-store",
|
|
121
|
+
});
|
|
122
|
+
res.end(readFileSync(file));
|
|
123
|
+
};
|
|
124
|
+
node.on("request", (req, res) => {
|
|
125
|
+
void (async () => {
|
|
126
|
+
const path = (req.url ?? "/").split("?")[0] ?? "/";
|
|
127
|
+
try {
|
|
128
|
+
const target = path === "/mcp" || path.startsWith("/mcp/") ? projects.find((project) => project.mount === path) : undefined;
|
|
129
|
+
if (target) {
|
|
130
|
+
try {
|
|
131
|
+
await handlerFor(target)(req, res);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
// Usually a syntax error in the server file. Say so in MCP terms.
|
|
135
|
+
vite.ssrFixStacktrace(error);
|
|
136
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
137
|
+
if (!res.headersSent) {
|
|
138
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
139
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: text } }));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (await handleApi(req, res, hub))
|
|
145
|
+
return;
|
|
146
|
+
if (hasStudio && path.startsWith("/__studio/")) {
|
|
147
|
+
const file = normalize(join(studio, path.slice("/__studio/".length)));
|
|
148
|
+
if (file.startsWith(studio) && existsSync(file) && statSync(file).isFile())
|
|
149
|
+
return sendFile(res, file, true);
|
|
150
|
+
res.writeHead(404).end();
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
if (path === "/" || path === "/index.html") {
|
|
154
|
+
if (hasStudio)
|
|
155
|
+
return sendFile(res, join(studio, "index.html"), false);
|
|
156
|
+
res.writeHead(302, { location: projects[0]?.mount ?? "/mcp" }).end();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
vite.middlewares(req, res, () => {
|
|
160
|
+
res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
if (!res.headersSent)
|
|
165
|
+
res.writeHead(500, { "content-type": "text/plain" });
|
|
166
|
+
res.end(error instanceof Error ? error.message : String(error));
|
|
167
|
+
}
|
|
168
|
+
})();
|
|
169
|
+
});
|
|
170
|
+
port = await listen(node, port, "127.0.0.1");
|
|
171
|
+
// Load the server once now so the first request is fast and errors show at start.
|
|
172
|
+
for (const project of projects) {
|
|
173
|
+
await loadServer(project).catch((error) => {
|
|
174
|
+
console.error(`\n ${error instanceof Error ? error.message : String(error)}\n`);
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
port,
|
|
179
|
+
url: `http://localhost:${port}`,
|
|
180
|
+
mcpUrl: `${origin()}${projects[0]?.mount ?? "/mcp"}`,
|
|
181
|
+
servers: projects.map((project) => ({ id: project.id, mcpUrl: `http://localhost:${port}${project.mount}` })),
|
|
182
|
+
readyMs: Math.round(performance.now() - started),
|
|
183
|
+
close: async () => {
|
|
184
|
+
await vite.close();
|
|
185
|
+
await new Promise((resolve) => node.close(() => resolve()));
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small, exact edits to a server file: change a tool's input description, or the server's
|
|
3
|
+
* own title and description. Pure text in, text out. Each function throws a plain message
|
|
4
|
+
* when the code is not written in a shape it can change safely, so the Studio can say
|
|
5
|
+
* "change it on the Code tab" instead of guessing.
|
|
6
|
+
*/
|
|
7
|
+
/** Index of the bracket that closes the one at `open`. */
|
|
8
|
+
export declare function matching(source: string, open: number): number;
|
|
9
|
+
/** Index where the expression starting at `from` ends: the comma or closing bracket after it. */
|
|
10
|
+
export declare function expressionEnd(source: string, from: number): number;
|
|
11
|
+
/** Where the `.tool( ... )` call that defines this tool starts and ends. */
|
|
12
|
+
export declare function toolCall(source: string, tool: string): {
|
|
13
|
+
start: number;
|
|
14
|
+
end: number;
|
|
15
|
+
};
|
|
16
|
+
/** Change, or add, the description of one input of a tool. */
|
|
17
|
+
export declare function setInputDescription(source: string, tool: string, field: string, description: string): string;
|
|
18
|
+
/** Change, or add, the title and description passed to createServer. An empty title removes nothing and adds nothing. */
|
|
19
|
+
export declare function setServerInfo(source: string, info: {
|
|
20
|
+
title?: string;
|
|
21
|
+
description?: string;
|
|
22
|
+
}): string;
|
package/dist/dev/edit.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small, exact edits to a server file: change a tool's input description, or the server's
|
|
3
|
+
* own title and description. Pure text in, text out. Each function throws a plain message
|
|
4
|
+
* when the code is not written in a shape it can change safely, so the Studio can say
|
|
5
|
+
* "change it on the Code tab" instead of guessing.
|
|
6
|
+
*/
|
|
7
|
+
const OPEN = "([{";
|
|
8
|
+
const CLOSE = ")]}";
|
|
9
|
+
/** Index just past a string, template or comment that starts at `at`, or `at` when none starts there. */
|
|
10
|
+
function skipQuiet(source, at) {
|
|
11
|
+
const char = source[at];
|
|
12
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
13
|
+
for (let i = at + 1; i < source.length; i += 1) {
|
|
14
|
+
if (source[i] === "\\")
|
|
15
|
+
i += 1;
|
|
16
|
+
else if (source[i] === char)
|
|
17
|
+
return i + 1;
|
|
18
|
+
}
|
|
19
|
+
return source.length;
|
|
20
|
+
}
|
|
21
|
+
if (char === "/" && source[at + 1] === "/") {
|
|
22
|
+
const end = source.indexOf("\n", at);
|
|
23
|
+
return end === -1 ? source.length : end;
|
|
24
|
+
}
|
|
25
|
+
if (char === "/" && source[at + 1] === "*") {
|
|
26
|
+
const end = source.indexOf("*/", at + 2);
|
|
27
|
+
return end === -1 ? source.length : end + 2;
|
|
28
|
+
}
|
|
29
|
+
return at;
|
|
30
|
+
}
|
|
31
|
+
/** Index of the bracket that closes the one at `open`. */
|
|
32
|
+
export function matching(source, open) {
|
|
33
|
+
let depth = 0;
|
|
34
|
+
for (let i = open; i < source.length; i += 1) {
|
|
35
|
+
const skipped = skipQuiet(source, i);
|
|
36
|
+
if (skipped !== i) {
|
|
37
|
+
i = skipped - 1;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (OPEN.includes(source[i]))
|
|
41
|
+
depth += 1;
|
|
42
|
+
else if (CLOSE.includes(source[i])) {
|
|
43
|
+
depth -= 1;
|
|
44
|
+
if (depth === 0)
|
|
45
|
+
return i;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
throw new Error("The brackets in the server file do not match.");
|
|
49
|
+
}
|
|
50
|
+
/** Index where the expression starting at `from` ends: the comma or closing bracket after it. */
|
|
51
|
+
export function expressionEnd(source, from) {
|
|
52
|
+
let depth = 0;
|
|
53
|
+
for (let i = from; i < source.length; i += 1) {
|
|
54
|
+
const skipped = skipQuiet(source, i);
|
|
55
|
+
if (skipped !== i) {
|
|
56
|
+
i = skipped - 1;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const char = source[i];
|
|
60
|
+
if (OPEN.includes(char))
|
|
61
|
+
depth += 1;
|
|
62
|
+
else if (CLOSE.includes(char)) {
|
|
63
|
+
if (depth === 0)
|
|
64
|
+
return i;
|
|
65
|
+
depth -= 1;
|
|
66
|
+
}
|
|
67
|
+
else if (char === "," && depth === 0)
|
|
68
|
+
return i;
|
|
69
|
+
}
|
|
70
|
+
return source.length;
|
|
71
|
+
}
|
|
72
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
73
|
+
const LITERAL = "\"(?:[^\"\\\\\\n]|\\\\.)*\"|'(?:[^'\\\\\\n]|\\\\.)*'|`(?:[^`\\\\$]|\\\\.)*`";
|
|
74
|
+
/** Where the `.tool( ... )` call that defines this tool starts and ends. */
|
|
75
|
+
export function toolCall(source, tool) {
|
|
76
|
+
const named = new RegExp(`name:\\s*["'\`]${escape(tool)}["'\`]`).exec(source);
|
|
77
|
+
if (!named)
|
|
78
|
+
throw new Error(`Could not find the tool ${tool} in the server file.`);
|
|
79
|
+
const before = source.slice(0, named.index);
|
|
80
|
+
const calls = [...before.matchAll(/\.tool\s*\(/g)];
|
|
81
|
+
const last = calls[calls.length - 1];
|
|
82
|
+
if (!last || last.index === undefined)
|
|
83
|
+
throw new Error(`Could not find where ${tool} is defined.`);
|
|
84
|
+
const open = last.index + last[0].length - 1;
|
|
85
|
+
return { start: open, end: matching(source, open) };
|
|
86
|
+
}
|
|
87
|
+
/** Change, or add, the description of one input of a tool. */
|
|
88
|
+
export function setInputDescription(source, tool, field, description) {
|
|
89
|
+
const call = toolCall(source, tool);
|
|
90
|
+
const body = source.slice(call.start, call.end);
|
|
91
|
+
const input = /\binput\s*:/.exec(body);
|
|
92
|
+
if (!input)
|
|
93
|
+
throw new Error(`${tool} has no input in the code. Change it on the Code tab.`);
|
|
94
|
+
const key = new RegExp(`(^|[{,\\s])${escape(field)}\\s*:\\s*`, "g");
|
|
95
|
+
key.lastIndex = input.index + input[0].length;
|
|
96
|
+
const found = key.exec(body);
|
|
97
|
+
if (!found)
|
|
98
|
+
throw new Error(`Could not find the input ${field} of ${tool} in the code. Change it on the Code tab.`);
|
|
99
|
+
const from = call.start + found.index + found[0].length;
|
|
100
|
+
const to = expressionEnd(source, from);
|
|
101
|
+
const expression = source.slice(from, to);
|
|
102
|
+
const text = JSON.stringify(description);
|
|
103
|
+
const described = [...expression.matchAll(new RegExp(`\\.describe\\(\\s*(?:${LITERAL})\\s*\\)`, "g"))];
|
|
104
|
+
const last = described[described.length - 1];
|
|
105
|
+
let next;
|
|
106
|
+
if (last && last.index !== undefined) {
|
|
107
|
+
next = `${expression.slice(0, last.index)}.describe(${text})${expression.slice(last.index + last[0].length)}`;
|
|
108
|
+
}
|
|
109
|
+
else if (/\.describe\s*\(/.test(expression)) {
|
|
110
|
+
throw new Error(`The description of ${field} is not a plain string in the code. Change it on the Code tab.`);
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
const trimmed = expression.trimEnd();
|
|
114
|
+
next = `${trimmed}.describe(${text})${expression.slice(trimmed.length)}`;
|
|
115
|
+
}
|
|
116
|
+
return `${source.slice(0, from)}${next}${source.slice(to)}`;
|
|
117
|
+
}
|
|
118
|
+
/** Change, or add, the title and description passed to createServer. An empty title removes nothing and adds nothing. */
|
|
119
|
+
export function setServerInfo(source, info) {
|
|
120
|
+
const created = /createServer\s*\(\s*\{/.exec(source);
|
|
121
|
+
if (!created)
|
|
122
|
+
throw new Error('Could not find "createServer({ ... })" in the server file. Change it on the Code tab.');
|
|
123
|
+
let out = source;
|
|
124
|
+
for (const key of ["description", "title"]) {
|
|
125
|
+
const value = info[key]?.trim();
|
|
126
|
+
if (!value)
|
|
127
|
+
continue;
|
|
128
|
+
const open = created.index + created[0].length - 1;
|
|
129
|
+
const close = matching(out, open);
|
|
130
|
+
const object = out.slice(open, close);
|
|
131
|
+
const existing = new RegExp(`(^|[{,\\s])${key}\\s*:\\s*`).exec(object);
|
|
132
|
+
if (existing) {
|
|
133
|
+
const from = open + existing.index + existing[0].length;
|
|
134
|
+
const to = expressionEnd(out, from);
|
|
135
|
+
if (!new RegExp(`^(?:${LITERAL})\\s*$`).test(out.slice(from, to))) {
|
|
136
|
+
throw new Error(`The server's ${key} is not a plain string in the code. Change it on the Code tab.`);
|
|
137
|
+
}
|
|
138
|
+
const tail = out.slice(from, to).match(/\s*$/)?.[0] ?? "";
|
|
139
|
+
out = `${out.slice(0, from)}${JSON.stringify(value)}${tail}${out.slice(to)}`;
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
const indent = /\n([ \t]+)\S/.exec(object)?.[1] ?? " ";
|
|
143
|
+
out = `${out.slice(0, open + 1)}\n${indent}${key}: ${JSON.stringify(value)},${/^\s/.test(object.slice(1)) ? "" : " "}${out.slice(open + 1)}`;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { ProviderId } from "./keys.js";
|
|
2
|
+
export interface Draft {
|
|
3
|
+
name: string;
|
|
4
|
+
description: string;
|
|
5
|
+
/** One complete `server.tool(...)` statement. */
|
|
6
|
+
tool: string;
|
|
7
|
+
/** A complete view file, or an empty string for no view. */
|
|
8
|
+
view: string;
|
|
9
|
+
}
|
|
10
|
+
/** How a tool and a view are written. Shared by the tool writer and the chat that builds. */
|
|
11
|
+
export declare const GUIDE = "A tool is one statement:\n\nserver.tool(\n {\n name: \"get_weather\",\n description: \"Current weather for a city. Shows a weather card.\",\n input: z.object({ city: z.string().describe(\"City name, for example Lisbon\") }),\n },\n async ({ city }) => {\n const data = await fetch(\"https://example.com/api?q=\" + encodeURIComponent(city)).then((r) => r.json());\n return { city, tempC: data.temp };\n },\n);\n\nRules for the tool:\n- \"z\" (zod) and the global \"fetch\" are available. Do not write import statements. Use no other packages.\n- The name is lowercase letters, numbers and underscores.\n- The description tells a model what the tool does and when to call it.\n- Every input field has a .describe() with an example.\n- Return a plain object with clear field names. Throw an Error with a readable message when something fails.\n- Use only public APIs that need no key. If the task needs a private API or a key, read the key from process.env and name the variable in the description. If no real data source fits, return realistic sample data and say \"sample data\" in the description.\n- Use the exact server variable name you are given.\n\nA view is an optional React file that draws the tool's result inside the chat:\n\nimport { useTool } from \"plugmcp/view\";\n\ninterface Output { city: string; tempC: number }\n\nexport default function View() {\n const { output, isPending, isError, text, theme, callTool, sendMessage } = useTool<Output>();\n const dark = theme === \"dark\";\n if (isPending) return <p style={{ padding: 16, margin: 0 }}>Loading</p>;\n if (isError) return <p style={{ padding: 16, margin: 0, color: \"#F87171\" }}>{text}</p>;\n if (!output) return null;\n return <div>...</div>;\n}\n\nRules for the view:\n- One file, a default-exported component. Import only from \"react\" and \"plugmcp/view\".\n- Inline styles only. Support both themes: dark uses text #F2EFE9 on #141414 with #2A2A2A borders, light uses text #141414 on #FFFFFF with #E2DFD9 borders. Accent #0099FF. Radius 14px on the card, 10px on controls. No emojis.\n- \"output\" is exactly the object the tool returns. Type it.\n- callTool(name, args) calls a tool on the same server and returns { output }. sendMessage(text) puts a message into the chat. Use them when they make the view more useful.\n- For charts and diagrams, draw inline SVG yourself and work out the layout in code. No chart or diagram packages.\n- Keep it compact: it is shown inline in a conversation, at most about 420px wide. A diagram may use the full width and scroll.";
|
|
12
|
+
/** Ask the user's own model to write a tool, and a view when wanted, from a description. */
|
|
13
|
+
export declare function draftTool(input: {
|
|
14
|
+
root: string;
|
|
15
|
+
provider: ProviderId;
|
|
16
|
+
model: string;
|
|
17
|
+
description: string;
|
|
18
|
+
wantView: boolean;
|
|
19
|
+
variable: string;
|
|
20
|
+
source: string;
|
|
21
|
+
}): Promise<Draft>;
|