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,97 @@
|
|
|
1
|
+
import { generateText } from "ai";
|
|
2
|
+
import { createModel } from "./chat.js";
|
|
3
|
+
import { readSettings, resolveKey } from "./keys.js";
|
|
4
|
+
/** How a tool and a view are written. Shared by the tool writer and the chat that builds. */
|
|
5
|
+
export const GUIDE = `A tool is one statement:
|
|
6
|
+
|
|
7
|
+
server.tool(
|
|
8
|
+
{
|
|
9
|
+
name: "get_weather",
|
|
10
|
+
description: "Current weather for a city. Shows a weather card.",
|
|
11
|
+
input: z.object({ city: z.string().describe("City name, for example Lisbon") }),
|
|
12
|
+
},
|
|
13
|
+
async ({ city }) => {
|
|
14
|
+
const data = await fetch("https://example.com/api?q=" + encodeURIComponent(city)).then((r) => r.json());
|
|
15
|
+
return { city, tempC: data.temp };
|
|
16
|
+
},
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
Rules for the tool:
|
|
20
|
+
- "z" (zod) and the global "fetch" are available. Do not write import statements. Use no other packages.
|
|
21
|
+
- The name is lowercase letters, numbers and underscores.
|
|
22
|
+
- The description tells a model what the tool does and when to call it.
|
|
23
|
+
- Every input field has a .describe() with an example.
|
|
24
|
+
- Return a plain object with clear field names. Throw an Error with a readable message when something fails.
|
|
25
|
+
- 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.
|
|
26
|
+
- Use the exact server variable name you are given.
|
|
27
|
+
|
|
28
|
+
A view is an optional React file that draws the tool's result inside the chat:
|
|
29
|
+
|
|
30
|
+
import { useTool } from "plugmcp/view";
|
|
31
|
+
|
|
32
|
+
interface Output { city: string; tempC: number }
|
|
33
|
+
|
|
34
|
+
export default function View() {
|
|
35
|
+
const { output, isPending, isError, text, theme, callTool, sendMessage } = useTool<Output>();
|
|
36
|
+
const dark = theme === "dark";
|
|
37
|
+
if (isPending) return <p style={{ padding: 16, margin: 0 }}>Loading</p>;
|
|
38
|
+
if (isError) return <p style={{ padding: 16, margin: 0, color: "#F87171" }}>{text}</p>;
|
|
39
|
+
if (!output) return null;
|
|
40
|
+
return <div>...</div>;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
Rules for the view:
|
|
44
|
+
- One file, a default-exported component. Import only from "react" and "plugmcp/view".
|
|
45
|
+
- 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.
|
|
46
|
+
- "output" is exactly the object the tool returns. Type it.
|
|
47
|
+
- 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.
|
|
48
|
+
- For charts and diagrams, draw inline SVG yourself and work out the layout in code. No chart or diagram packages.
|
|
49
|
+
- Keep it compact: it is shown inline in a conversation, at most about 420px wide. A diagram may use the full width and scroll.`;
|
|
50
|
+
const RULES = `You write one tool for an MCP server built with the "plugmcp" TypeScript SDK.
|
|
51
|
+
|
|
52
|
+
${GUIDE}
|
|
53
|
+
|
|
54
|
+
Answer with one JSON object and nothing else:
|
|
55
|
+
{"name": "...", "description": "...", "tool": "server.tool(...);", "view": "full file text, or an empty string"}`;
|
|
56
|
+
function parse(text) {
|
|
57
|
+
const start = text.indexOf("{");
|
|
58
|
+
const end = text.lastIndexOf("}");
|
|
59
|
+
if (start === -1 || end <= start)
|
|
60
|
+
throw new Error("The model did not answer with a tool. Try again or use another model.");
|
|
61
|
+
let draft;
|
|
62
|
+
try {
|
|
63
|
+
draft = JSON.parse(text.slice(start, end + 1));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
throw new Error("The model's answer could not be read. Try again or use another model.");
|
|
67
|
+
}
|
|
68
|
+
if (typeof draft.name !== "string" || typeof draft.tool !== "string" || !/\.tool\s*\(/.test(draft.tool)) {
|
|
69
|
+
throw new Error("The model's answer has no tool in it. Try again or use another model.");
|
|
70
|
+
}
|
|
71
|
+
if (/^\s*import\s/m.test(draft.tool))
|
|
72
|
+
throw new Error("The model added imports to the tool, which is not supported. Try again.");
|
|
73
|
+
return {
|
|
74
|
+
name: draft.name,
|
|
75
|
+
description: typeof draft.description === "string" ? draft.description : "",
|
|
76
|
+
tool: draft.tool.trim(),
|
|
77
|
+
view: typeof draft.view === "string" ? draft.view.trim() : "",
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** Ask the user's own model to write a tool, and a view when wanted, from a description. */
|
|
81
|
+
export async function draftTool(input) {
|
|
82
|
+
const { key } = resolveKey(input.provider, input.root);
|
|
83
|
+
const model = createModel(input.provider, input.model, key, readSettings().customBaseUrl);
|
|
84
|
+
const { text } = await generateText({
|
|
85
|
+
model,
|
|
86
|
+
system: RULES,
|
|
87
|
+
prompt: [
|
|
88
|
+
`The server variable is named "${input.variable}".`,
|
|
89
|
+
`The server file now:\n\n${input.source.slice(0, 12_000)}`,
|
|
90
|
+
`Write a new tool for this request: ${input.description}`,
|
|
91
|
+
input.wantView ? "Write a view for it too." : 'No view is wanted. Set "view" to an empty string.',
|
|
92
|
+
"Do not reuse the name of a tool that already exists.",
|
|
93
|
+
].join("\n\n"),
|
|
94
|
+
abortSignal: AbortSignal.timeout(120_000),
|
|
95
|
+
});
|
|
96
|
+
return parse(text);
|
|
97
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export declare const PROVIDERS: {
|
|
2
|
+
readonly openai: {
|
|
3
|
+
readonly label: "OpenAI";
|
|
4
|
+
readonly env: "OPENAI_API_KEY";
|
|
5
|
+
readonly needsKey: true;
|
|
6
|
+
};
|
|
7
|
+
readonly anthropic: {
|
|
8
|
+
readonly label: "Anthropic";
|
|
9
|
+
readonly env: "ANTHROPIC_API_KEY";
|
|
10
|
+
readonly needsKey: true;
|
|
11
|
+
};
|
|
12
|
+
readonly google: {
|
|
13
|
+
readonly label: "Google";
|
|
14
|
+
readonly env: "GOOGLE_GENERATIVE_AI_API_KEY";
|
|
15
|
+
readonly needsKey: true;
|
|
16
|
+
};
|
|
17
|
+
readonly openrouter: {
|
|
18
|
+
readonly label: "OpenRouter";
|
|
19
|
+
readonly env: "OPENROUTER_API_KEY";
|
|
20
|
+
readonly needsKey: true;
|
|
21
|
+
};
|
|
22
|
+
readonly ollama: {
|
|
23
|
+
readonly label: "Ollama (local)";
|
|
24
|
+
readonly env: "";
|
|
25
|
+
readonly needsKey: false;
|
|
26
|
+
};
|
|
27
|
+
readonly custom: {
|
|
28
|
+
readonly label: "OpenAI-compatible";
|
|
29
|
+
readonly env: "OPENAI_COMPATIBLE_API_KEY";
|
|
30
|
+
readonly needsKey: false;
|
|
31
|
+
};
|
|
32
|
+
};
|
|
33
|
+
export type ProviderId = keyof typeof PROVIDERS;
|
|
34
|
+
export interface Settings {
|
|
35
|
+
keys: Partial<Record<ProviderId, string>>;
|
|
36
|
+
provider?: ProviderId;
|
|
37
|
+
models: Partial<Record<ProviderId, string>>;
|
|
38
|
+
/** Base address for the "custom" provider. */
|
|
39
|
+
customBaseUrl?: string;
|
|
40
|
+
}
|
|
41
|
+
export declare const configDir: () => string;
|
|
42
|
+
export declare function readSettings(): Settings;
|
|
43
|
+
export declare function writeSettings(settings: Settings): void;
|
|
44
|
+
/** A key from the project's .env wins over one saved in the home folder, then the shell. */
|
|
45
|
+
export declare function resolveKey(provider: ProviderId, root: string): {
|
|
46
|
+
key?: string;
|
|
47
|
+
source?: "project .env" | "saved" | "environment";
|
|
48
|
+
};
|
|
49
|
+
/** What the browser is allowed to know: which providers are ready, never the keys. */
|
|
50
|
+
export declare function publicSettings(root: string): {
|
|
51
|
+
provider: "anthropic" | "custom" | "google" | "ollama" | "openai" | "openrouter" | undefined;
|
|
52
|
+
models: Partial<Record<"anthropic" | "custom" | "google" | "ollama" | "openai" | "openrouter", string>>;
|
|
53
|
+
customBaseUrl: string;
|
|
54
|
+
providers: {
|
|
55
|
+
id: "anthropic" | "custom" | "google" | "ollama" | "openai" | "openrouter";
|
|
56
|
+
label: "Anthropic" | "Google" | "Ollama (local)" | "OpenAI" | "OpenAI-compatible" | "OpenRouter";
|
|
57
|
+
needsKey: boolean;
|
|
58
|
+
hasKey: boolean;
|
|
59
|
+
source: "environment" | "project .env" | "saved" | null;
|
|
60
|
+
}[];
|
|
61
|
+
};
|
package/dist/dev/keys.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { readEnvFile } from "./project.js";
|
|
5
|
+
export const PROVIDERS = {
|
|
6
|
+
openai: { label: "OpenAI", env: "OPENAI_API_KEY", needsKey: true },
|
|
7
|
+
anthropic: { label: "Anthropic", env: "ANTHROPIC_API_KEY", needsKey: true },
|
|
8
|
+
google: { label: "Google", env: "GOOGLE_GENERATIVE_AI_API_KEY", needsKey: true },
|
|
9
|
+
openrouter: { label: "OpenRouter", env: "OPENROUTER_API_KEY", needsKey: true },
|
|
10
|
+
ollama: { label: "Ollama (local)", env: "", needsKey: false },
|
|
11
|
+
custom: { label: "OpenAI-compatible", env: "OPENAI_COMPATIBLE_API_KEY", needsKey: false },
|
|
12
|
+
};
|
|
13
|
+
export const configDir = () => process.env.PLUGMCP_HOME ?? join(homedir(), ".plugmcp");
|
|
14
|
+
const settingsPath = () => join(configDir(), "keys.json");
|
|
15
|
+
export function readSettings() {
|
|
16
|
+
try {
|
|
17
|
+
const parsed = JSON.parse(readFileSync(settingsPath(), "utf8"));
|
|
18
|
+
return { keys: parsed.keys ?? {}, models: parsed.models ?? {}, provider: parsed.provider, customBaseUrl: parsed.customBaseUrl };
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return { keys: {}, models: {} };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function writeSettings(settings) {
|
|
25
|
+
if (!existsSync(configDir()))
|
|
26
|
+
mkdirSync(configDir(), { recursive: true });
|
|
27
|
+
writeFileSync(settingsPath(), JSON.stringify(settings, null, 2), { mode: 0o600 });
|
|
28
|
+
}
|
|
29
|
+
/** A key from the project's .env wins over one saved in the home folder, then the shell. */
|
|
30
|
+
export function resolveKey(provider, root) {
|
|
31
|
+
const env = PROVIDERS[provider].env;
|
|
32
|
+
const fromFile = env ? readEnvFile(root)[env] : undefined;
|
|
33
|
+
if (fromFile)
|
|
34
|
+
return { key: fromFile, source: "project .env" };
|
|
35
|
+
const saved = readSettings().keys[provider];
|
|
36
|
+
if (saved)
|
|
37
|
+
return { key: saved, source: "saved" };
|
|
38
|
+
const fromShell = env ? process.env[env] : undefined;
|
|
39
|
+
if (fromShell)
|
|
40
|
+
return { key: fromShell, source: "environment" };
|
|
41
|
+
return {};
|
|
42
|
+
}
|
|
43
|
+
/** What the browser is allowed to know: which providers are ready, never the keys. */
|
|
44
|
+
export function publicSettings(root) {
|
|
45
|
+
const settings = readSettings();
|
|
46
|
+
return {
|
|
47
|
+
provider: settings.provider,
|
|
48
|
+
models: settings.models,
|
|
49
|
+
customBaseUrl: settings.customBaseUrl ?? "",
|
|
50
|
+
providers: Object.keys(PROVIDERS).map((id) => {
|
|
51
|
+
const { source } = resolveKey(id, root);
|
|
52
|
+
return { id, label: PROVIDERS[id].label, needsKey: PROVIDERS[id].needsKey, hasKey: Boolean(source), source: source ?? null };
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface Project {
|
|
2
|
+
root: string;
|
|
3
|
+
name: string;
|
|
4
|
+
/** Entry file, relative to root, with forward slashes. */
|
|
5
|
+
entry: string;
|
|
6
|
+
viewsDir: string;
|
|
7
|
+
/** Short name used in addresses and by the Studio. "main" for the server at the top of the folder. */
|
|
8
|
+
id: string;
|
|
9
|
+
/** The folder `plugmcp dev` was started in. Keys and .env are read from here. */
|
|
10
|
+
home: string;
|
|
11
|
+
/** Path from home to root with a trailing slash, or an empty string. */
|
|
12
|
+
rel: string;
|
|
13
|
+
/** Where this server answers MCP requests in dev. */
|
|
14
|
+
mount: string;
|
|
15
|
+
}
|
|
16
|
+
export declare function resolveProject(root: string, entry?: string): Project;
|
|
17
|
+
export declare const SERVER_ID: RegExp;
|
|
18
|
+
/**
|
|
19
|
+
* Every MCP server in a folder: the one at the top, and one per folder in servers/.
|
|
20
|
+
* Each has its own server file and its own views.
|
|
21
|
+
*/
|
|
22
|
+
export declare function resolveWorkspace(home: string, entry?: string): Project[];
|
|
23
|
+
/** Tool name to view file (relative to root), from views/<tool>.tsx. */
|
|
24
|
+
export declare function listViews(project: Project): Record<string, string>;
|
|
25
|
+
/** Read KEY=value pairs from the project's .env without touching process.env. */
|
|
26
|
+
export declare function readEnvFile(root: string): Record<string, string>;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
const ENTRIES = ["server.ts", "server.tsx", "src/server.ts", "index.ts", "src/index.ts", "server.js", "index.js"];
|
|
4
|
+
export function resolveProject(root, entry) {
|
|
5
|
+
const found = entry ?? ENTRIES.find((file) => existsSync(join(root, file)));
|
|
6
|
+
if (!found || !existsSync(join(root, found))) {
|
|
7
|
+
throw new Error(`No server file found in ${root}. Create server.ts that default-exports createServer(...), or pass --entry.`);
|
|
8
|
+
}
|
|
9
|
+
return { root, name: basename(root), entry: found.replace(/\\/g, "/"), viewsDir: join(root, "views"), id: "main", home: root, rel: "", mount: "/mcp" };
|
|
10
|
+
}
|
|
11
|
+
export const SERVER_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
12
|
+
/**
|
|
13
|
+
* Every MCP server in a folder: the one at the top, and one per folder in servers/.
|
|
14
|
+
* Each has its own server file and its own views.
|
|
15
|
+
*/
|
|
16
|
+
export function resolveWorkspace(home, entry) {
|
|
17
|
+
const list = [];
|
|
18
|
+
let missing;
|
|
19
|
+
try {
|
|
20
|
+
list.push(resolveProject(home, entry));
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
missing = error;
|
|
24
|
+
}
|
|
25
|
+
const dir = join(home, "servers");
|
|
26
|
+
if (existsSync(dir)) {
|
|
27
|
+
for (const item of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
28
|
+
if (!item.isDirectory() || !SERVER_ID.test(item.name) || item.name === "main")
|
|
29
|
+
continue;
|
|
30
|
+
const root = join(dir, item.name);
|
|
31
|
+
const found = ENTRIES.find((file) => existsSync(join(root, file)));
|
|
32
|
+
if (!found)
|
|
33
|
+
continue;
|
|
34
|
+
list.push({ root, name: item.name, entry: found, viewsDir: join(root, "views"), id: item.name, home, rel: `servers/${item.name}/`, mount: `/mcp/${item.name}` });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
if (list.length === 0)
|
|
38
|
+
throw missing;
|
|
39
|
+
return list;
|
|
40
|
+
}
|
|
41
|
+
/** Tool name to view file (relative to root), from views/<tool>.tsx. */
|
|
42
|
+
export function listViews(project) {
|
|
43
|
+
if (!existsSync(project.viewsDir))
|
|
44
|
+
return {};
|
|
45
|
+
const views = {};
|
|
46
|
+
for (const file of readdirSync(project.viewsDir)) {
|
|
47
|
+
const match = /^(.+)\.(tsx|jsx)$/.exec(file);
|
|
48
|
+
if (match?.[1])
|
|
49
|
+
views[match[1]] = `views/${file}`;
|
|
50
|
+
}
|
|
51
|
+
return views;
|
|
52
|
+
}
|
|
53
|
+
/** Read KEY=value pairs from the project's .env without touching process.env. */
|
|
54
|
+
export function readEnvFile(root) {
|
|
55
|
+
const out = {};
|
|
56
|
+
for (const file of [".env", ".env.local"]) {
|
|
57
|
+
const path = join(root, file);
|
|
58
|
+
if (!existsSync(path))
|
|
59
|
+
continue;
|
|
60
|
+
for (const line of readFileSync(path, "utf8").split(/\r?\n/)) {
|
|
61
|
+
const match = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/.exec(line);
|
|
62
|
+
if (!match?.[1])
|
|
63
|
+
continue;
|
|
64
|
+
out[match[1]] = (match[2] ?? "").replace(/^(['"])(.*)\1$/, "$2");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { ProviderId } from "./keys.js";
|
|
2
|
+
import type { Project } from "./project.js";
|
|
3
|
+
/** An agent made in the Studio: a prompt, a model and the tools it may use. */
|
|
4
|
+
export interface Agent {
|
|
5
|
+
id: string;
|
|
6
|
+
name: string;
|
|
7
|
+
description?: string;
|
|
8
|
+
instructions: string;
|
|
9
|
+
provider?: ProviderId;
|
|
10
|
+
model?: string;
|
|
11
|
+
/** Tool ids the agent may call. `null` means every tool. */
|
|
12
|
+
tools: string[] | null;
|
|
13
|
+
/** Opening messages offered in the chat. */
|
|
14
|
+
starters?: string[];
|
|
15
|
+
}
|
|
16
|
+
export declare function writeJson(project: Project, file: string, value: unknown): void;
|
|
17
|
+
export declare const readAgents: (project: Project) => Agent[];
|
|
18
|
+
export declare const writeAgents: (project: Project, agents: Agent[]) => void;
|
|
19
|
+
/** A saved call of a tool and what it should give back. `plugmcp test` and the Studio run these. */
|
|
20
|
+
export interface SavedTest {
|
|
21
|
+
id: string;
|
|
22
|
+
tool: string;
|
|
23
|
+
name: string;
|
|
24
|
+
arguments: Record<string, unknown>;
|
|
25
|
+
/** The call should end in an error. Default false. */
|
|
26
|
+
expectError?: boolean;
|
|
27
|
+
/** Text the result must contain, compared without regard to case. */
|
|
28
|
+
contains?: string;
|
|
29
|
+
}
|
|
30
|
+
export declare const readTests: (project: Project) => SavedTest[];
|
|
31
|
+
export declare const writeTests: (project: Project, tests: SavedTest[]) => void;
|
|
32
|
+
/** One tool call seen by the dev server, from the Studio or from any connected client. */
|
|
33
|
+
export interface CallRecord {
|
|
34
|
+
id: number;
|
|
35
|
+
at: number;
|
|
36
|
+
tool: string;
|
|
37
|
+
server: string;
|
|
38
|
+
ms: number;
|
|
39
|
+
ok: boolean;
|
|
40
|
+
input: unknown;
|
|
41
|
+
output: unknown;
|
|
42
|
+
}
|
|
43
|
+
/** Read the saved log from this folder and keep writing to it. */
|
|
44
|
+
export declare function keepCalls(home: string): void;
|
|
45
|
+
export declare function recordCall(entry: Omit<CallRecord, "id" | "at">): void;
|
|
46
|
+
export declare const callLog: () => {
|
|
47
|
+
total: number;
|
|
48
|
+
failed: number;
|
|
49
|
+
calls: CallRecord[];
|
|
50
|
+
};
|
|
51
|
+
/** How many calls one server has handled since the dev server started. */
|
|
52
|
+
export declare const callsFor: (server: string) => {
|
|
53
|
+
total: number;
|
|
54
|
+
failed: number;
|
|
55
|
+
};
|
|
56
|
+
export declare function clearCalls(): void;
|
|
57
|
+
/**
|
|
58
|
+
* Tools report each call through a process-wide hook, so calls from Cursor,
|
|
59
|
+
* Claude or any other client show in the Studio next to the Studio's own.
|
|
60
|
+
*/
|
|
61
|
+
export declare function listenForCalls(home?: string): void;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
const dir = (project) => join(project.root, ".plugmcp");
|
|
4
|
+
function readJson(path, fallback) {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return fallback;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function writeJson(project, file, value) {
|
|
13
|
+
if (!existsSync(dir(project)))
|
|
14
|
+
mkdirSync(dir(project), { recursive: true });
|
|
15
|
+
writeFileSync(join(dir(project), file), JSON.stringify(value, null, 2));
|
|
16
|
+
}
|
|
17
|
+
export const readAgents = (project) => readJson(join(dir(project), "agents.json"), []);
|
|
18
|
+
export const writeAgents = (project, agents) => writeJson(project, "agents.json", agents);
|
|
19
|
+
export const readTests = (project) => readJson(join(dir(project), "tests.json"), []);
|
|
20
|
+
export const writeTests = (project, tests) => writeJson(project, "tests.json", tests);
|
|
21
|
+
const MAX = 300;
|
|
22
|
+
const calls = [];
|
|
23
|
+
let nextId = 1;
|
|
24
|
+
let total = 0;
|
|
25
|
+
let failed = 0;
|
|
26
|
+
const perServer = new Map();
|
|
27
|
+
// The log is kept on disk too, so it is still there after the dev server restarts.
|
|
28
|
+
let file = null;
|
|
29
|
+
let saving = null;
|
|
30
|
+
function save() {
|
|
31
|
+
if (!file || saving)
|
|
32
|
+
return;
|
|
33
|
+
saving = setTimeout(() => {
|
|
34
|
+
saving = null;
|
|
35
|
+
if (!file)
|
|
36
|
+
return;
|
|
37
|
+
try {
|
|
38
|
+
const folder = join(file, "..");
|
|
39
|
+
if (!existsSync(folder))
|
|
40
|
+
mkdirSync(folder, { recursive: true });
|
|
41
|
+
writeFileSync(file, JSON.stringify({ calls }));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
// A log that cannot be saved is still shown until the server stops.
|
|
45
|
+
}
|
|
46
|
+
}, 400);
|
|
47
|
+
saving.unref?.();
|
|
48
|
+
}
|
|
49
|
+
/** Read the saved log from this folder and keep writing to it. */
|
|
50
|
+
export function keepCalls(home) {
|
|
51
|
+
file = join(home, ".plugmcp", "calls.json");
|
|
52
|
+
const saved = readJson(file, {}).calls ?? [];
|
|
53
|
+
calls.length = 0;
|
|
54
|
+
perServer.clear();
|
|
55
|
+
total = 0;
|
|
56
|
+
failed = 0;
|
|
57
|
+
for (const call of saved.slice(0, MAX)) {
|
|
58
|
+
calls.push(call);
|
|
59
|
+
total += 1;
|
|
60
|
+
if (!call.ok)
|
|
61
|
+
failed += 1;
|
|
62
|
+
const count = perServer.get(call.server) ?? { total: 0, failed: 0 };
|
|
63
|
+
count.total += 1;
|
|
64
|
+
if (!call.ok)
|
|
65
|
+
count.failed += 1;
|
|
66
|
+
perServer.set(call.server, count);
|
|
67
|
+
nextId = Math.max(nextId, call.id + 1);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const clip = (value) => {
|
|
71
|
+
const text = JSON.stringify(value) ?? "";
|
|
72
|
+
return text.length > 20_000 ? `${text.slice(0, 20_000)} ... (cut)` : value;
|
|
73
|
+
};
|
|
74
|
+
export function recordCall(entry) {
|
|
75
|
+
total += 1;
|
|
76
|
+
if (!entry.ok)
|
|
77
|
+
failed += 1;
|
|
78
|
+
const count = perServer.get(entry.server) ?? { total: 0, failed: 0 };
|
|
79
|
+
count.total += 1;
|
|
80
|
+
if (!entry.ok)
|
|
81
|
+
count.failed += 1;
|
|
82
|
+
perServer.set(entry.server, count);
|
|
83
|
+
calls.unshift({ ...entry, input: clip(entry.input), output: clip(entry.output), id: nextId++, at: Date.now() });
|
|
84
|
+
if (calls.length > MAX)
|
|
85
|
+
calls.length = MAX;
|
|
86
|
+
save();
|
|
87
|
+
}
|
|
88
|
+
export const callLog = () => ({ total, failed, calls });
|
|
89
|
+
/** How many calls one server has handled since the dev server started. */
|
|
90
|
+
export const callsFor = (server) => perServer.get(server) ?? { total: 0, failed: 0 };
|
|
91
|
+
export function clearCalls() {
|
|
92
|
+
calls.length = 0;
|
|
93
|
+
total = 0;
|
|
94
|
+
failed = 0;
|
|
95
|
+
perServer.clear();
|
|
96
|
+
save();
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Tools report each call through a process-wide hook, so calls from Cursor,
|
|
100
|
+
* Claude or any other client show in the Studio next to the Studio's own.
|
|
101
|
+
*/
|
|
102
|
+
export function listenForCalls(home) {
|
|
103
|
+
if (home)
|
|
104
|
+
keepCalls(home);
|
|
105
|
+
globalThis[Symbol.for("plugmcp.calls")] = (entry) => recordCall({
|
|
106
|
+
tool: entry.tool,
|
|
107
|
+
server: entry.server ?? "local",
|
|
108
|
+
ms: entry.ms,
|
|
109
|
+
ok: entry.result.isError !== true,
|
|
110
|
+
input: entry.input,
|
|
111
|
+
output: entry.result.structuredContent ?? entry.result.content,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Plugin } from "vite";
|
|
2
|
+
export declare const VIEW_ENTRY_PREFIX = "/@plugmcp-view/";
|
|
3
|
+
/** The page every view is mounted in. Kept tiny so hosts can load it fast. */
|
|
4
|
+
export declare function viewShell(tool: string): string;
|
|
5
|
+
/**
|
|
6
|
+
* Serves one small entry module per view. It mounts views/<tool>.tsx inside
|
|
7
|
+
* ViewRoot, so a view file is only a default-exported component.
|
|
8
|
+
*/
|
|
9
|
+
export declare function viewEntryPlugin(views: () => Record<string, string>): Plugin;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export const VIEW_ENTRY_PREFIX = "/@plugmcp-view/";
|
|
2
|
+
/** The page every view is mounted in. Kept tiny so hosts can load it fast. */
|
|
3
|
+
export function viewShell(tool) {
|
|
4
|
+
return `<!doctype html>
|
|
5
|
+
<html lang="en">
|
|
6
|
+
<head>
|
|
7
|
+
<meta charset="utf-8">
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
9
|
+
<style>
|
|
10
|
+
:root{color-scheme:dark;font-family:Geist,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;font-size:14px;line-height:1.5}
|
|
11
|
+
:root[data-theme="light"]{color-scheme:light}
|
|
12
|
+
html,body{margin:0;background:transparent}
|
|
13
|
+
body{padding:0}
|
|
14
|
+
</style>
|
|
15
|
+
</head>
|
|
16
|
+
<body>
|
|
17
|
+
<div id="root"></div>
|
|
18
|
+
<script type="module" src="${VIEW_ENTRY_PREFIX}${tool}.js"></script>
|
|
19
|
+
</body>
|
|
20
|
+
</html>`;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Serves one small entry module per view. It mounts views/<tool>.tsx inside
|
|
24
|
+
* ViewRoot, so a view file is only a default-exported component.
|
|
25
|
+
*/
|
|
26
|
+
export function viewEntryPlugin(views) {
|
|
27
|
+
return {
|
|
28
|
+
name: "plugmcp:view-entry",
|
|
29
|
+
resolveId(id) {
|
|
30
|
+
if (id.startsWith(VIEW_ENTRY_PREFIX))
|
|
31
|
+
return id;
|
|
32
|
+
return null;
|
|
33
|
+
},
|
|
34
|
+
load(id) {
|
|
35
|
+
if (!id.startsWith(VIEW_ENTRY_PREFIX))
|
|
36
|
+
return null;
|
|
37
|
+
const key = id.slice(VIEW_ENTRY_PREFIX.length).replace(/\.js$/, "");
|
|
38
|
+
const file = views()[key];
|
|
39
|
+
// In a folder with several servers the key is "<server>~<tool>".
|
|
40
|
+
const tool = key.slice(key.lastIndexOf("~") + 1);
|
|
41
|
+
if (!file)
|
|
42
|
+
return `document.getElementById("root").textContent = "No view file for ${tool}.";`;
|
|
43
|
+
return [
|
|
44
|
+
`import { createElement } from "react";`,
|
|
45
|
+
`import { createRoot } from "react-dom/client";`,
|
|
46
|
+
`import { ViewRoot } from "plugmcp/view";`,
|
|
47
|
+
`import View from "/${file}";`,
|
|
48
|
+
`createRoot(document.getElementById("root")).render(`,
|
|
49
|
+
` createElement(ViewRoot, { name: ${JSON.stringify(tool)} }, createElement(View)),`,
|
|
50
|
+
`);`,
|
|
51
|
+
].join("\n");
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { IncomingMessage, Server, ServerResponse } from "node:http";
|
|
2
|
+
import type { BuildOptions, PlugServer } from "./index.js";
|
|
3
|
+
export interface ServeHttpOptions extends BuildOptions {
|
|
4
|
+
port?: number;
|
|
5
|
+
/** Interface to bind. Defaults to 127.0.0.1; use 0.0.0.0 on a host. */
|
|
6
|
+
host?: string;
|
|
7
|
+
/**
|
|
8
|
+
* Hostnames allowed in the Host and Origin headers. Defaults to localhost only.
|
|
9
|
+
* Pass ["*"] when the server is public and sits behind your own auth or proxy.
|
|
10
|
+
*/
|
|
11
|
+
allowedHosts?: string[];
|
|
12
|
+
/** Show the HTML landing page on a browser GET of /mcp. Default true. */
|
|
13
|
+
landing?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface RunningServer {
|
|
16
|
+
url: string;
|
|
17
|
+
port: number;
|
|
18
|
+
server: Server;
|
|
19
|
+
close: () => Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export type NodeHandler = (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
|
|
22
|
+
export interface HttpHandlerOptions extends Pick<ServeHttpOptions, "allowedHosts" | "landing"> {
|
|
23
|
+
getViews?: () => BuildOptions["views"] | Promise<BuildOptions["views"]>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A node:http handler for the MCP endpoint. `getServer` is read on every
|
|
27
|
+
* request, so `plugmcp dev` can swap in freshly reloaded code.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createHttpHandler(getServer: () => PlugServer | Promise<PlugServer>, options?: HttpHandlerOptions): NodeHandler;
|
|
30
|
+
/** Serve a server over Streamable HTTP at /mcp. */
|
|
31
|
+
export declare function serveHttp(server: PlugServer, options?: ServeHttpOptions): Promise<RunningServer>;
|
|
32
|
+
/** Listen on `port`, moving up one at a time if it is taken. */
|
|
33
|
+
export declare function listen(server: Server, port: number, host: string, tries?: number): Promise<number>;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { createServer as createNodeServer } from "node:http";
|
|
2
|
+
import { createMcpHandler } from "@modelcontextprotocol/server";
|
|
3
|
+
import { hostHeaderValidation, originValidation, toNodeHandler } from "@modelcontextprotocol/node";
|
|
4
|
+
import { landingPage } from "./landing.js";
|
|
5
|
+
const LOCAL = ["localhost", "127.0.0.1", "[::1]"];
|
|
6
|
+
/**
|
|
7
|
+
* A node:http handler for the MCP endpoint. `getServer` is read on every
|
|
8
|
+
* request, so `plugmcp dev` can swap in freshly reloaded code.
|
|
9
|
+
*/
|
|
10
|
+
export function createHttpHandler(getServer, options = {}) {
|
|
11
|
+
const open = options.allowedHosts?.includes("*") ?? false;
|
|
12
|
+
const hosts = [...LOCAL, ...(options.allowedHosts ?? [])];
|
|
13
|
+
const checkHost = hostHeaderValidation(hosts);
|
|
14
|
+
const checkOrigin = originValidation(hosts);
|
|
15
|
+
return async (req, res) => {
|
|
16
|
+
res.setHeader("Access-Control-Allow-Origin", req.headers.origin ?? "*");
|
|
17
|
+
res.setHeader("Access-Control-Allow-Headers", "content-type, accept, authorization, mcp-session-id, mcp-protocol-version, mcp-method, mcp-name");
|
|
18
|
+
res.setHeader("Access-Control-Expose-Headers", "mcp-session-id");
|
|
19
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
|
|
20
|
+
if (req.method === "OPTIONS") {
|
|
21
|
+
res.writeHead(204).end();
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (!open && (!checkHost(req, res) || !checkOrigin(req, res)))
|
|
25
|
+
return;
|
|
26
|
+
const server = await getServer();
|
|
27
|
+
const wantsHtml = req.method === "GET" && (req.headers.accept ?? "").includes("text/html");
|
|
28
|
+
if (wantsHtml && options.landing !== false) {
|
|
29
|
+
const proto = req.headers["x-forwarded-proto"] ?? "http";
|
|
30
|
+
const html = landingPage(server, `${proto}://${req.headers.host}/mcp`);
|
|
31
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(html);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const views = await options.getViews?.();
|
|
35
|
+
const handler = createMcpHandler(() => server.build({ views }));
|
|
36
|
+
await toNodeHandler(handler)(req, res);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** Serve a server over Streamable HTTP at /mcp. */
|
|
40
|
+
export async function serveHttp(server, options = {}) {
|
|
41
|
+
const host = options.host ?? "127.0.0.1";
|
|
42
|
+
const mcp = createHttpHandler(() => server, { ...options, getViews: () => options.views });
|
|
43
|
+
const node = createNodeServer((req, res) => {
|
|
44
|
+
const path = (req.url ?? "/").split("?")[0];
|
|
45
|
+
if (path === "/mcp" || path === "/")
|
|
46
|
+
return void mcp(req, res);
|
|
47
|
+
if (path === "/health") {
|
|
48
|
+
return void res.writeHead(200, { "content-type": "application/json" }).end('{"ok":true}');
|
|
49
|
+
}
|
|
50
|
+
res.writeHead(404, { "content-type": "application/json" }).end('{"error":"Not found. The MCP endpoint is /mcp."}');
|
|
51
|
+
});
|
|
52
|
+
const port = await listen(node, options.port ?? Number(process.env.PORT ?? 3333), host);
|
|
53
|
+
const shown = host === "0.0.0.0" || host === "::" ? "localhost" : host;
|
|
54
|
+
return {
|
|
55
|
+
url: `http://${shown}:${port}/mcp`,
|
|
56
|
+
port,
|
|
57
|
+
server: node,
|
|
58
|
+
close: () => new Promise((resolve) => node.close(() => resolve())),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Listen on `port`, moving up one at a time if it is taken. */
|
|
62
|
+
export function listen(server, port, host, tries = 20) {
|
|
63
|
+
return new Promise((resolve, reject) => {
|
|
64
|
+
const attempt = (p, left) => {
|
|
65
|
+
const onError = (error) => {
|
|
66
|
+
if (error.code === "EADDRINUSE" && left > 0)
|
|
67
|
+
attempt(p + 1, left - 1);
|
|
68
|
+
else
|
|
69
|
+
reject(error);
|
|
70
|
+
};
|
|
71
|
+
server.once("error", onError);
|
|
72
|
+
server.listen(p, host, () => {
|
|
73
|
+
server.off("error", onError);
|
|
74
|
+
resolve(p);
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
attempt(port, tries);
|
|
78
|
+
});
|
|
79
|
+
}
|