panelica-mcp 0.2.2 → 0.5.2

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.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Server instructions — the orientation text an MCP client injects into the
3
+ * model's context when it connects (MCP `initialize` → `instructions`).
4
+ *
5
+ * Generated from the loaded catalogue so it never promises a tool or path the
6
+ * panel does not have: category counts come from the tools, and each workflow
7
+ * recipe is included only when every step exists in this catalogue.
8
+ */
9
+ import { META_CALL, META_DESCRIBE, META_FIND } from "./toolsets.js";
10
+ const RECIPES = [
11
+ { title: "Find the id of anything", steps: ["GET /v1/search", "GET /v1/domains", "GET /v1/accounts"] },
12
+ { title: "Provision a hosting account with a site", steps: ["POST /v1/accounts", "POST /v1/domains", "POST /v1/ssl/domains/:domain_id/issue", "POST /v1/databases", "POST /v1/email-accounts"] },
13
+ { title: "Inspect one site", steps: ["GET /v1/domains", "GET /v1/domains/:id", "GET /v1/ssl/domains/:domain_id", "GET /v1/dns/zones/:domain_id/records", "GET /v1/domains/:id/subdomains"] },
14
+ { title: "Change PHP version", steps: ["GET /v1/domains", "PATCH /v1/domains/:id/php"] },
15
+ { title: "Add or fix a DNS record", steps: ["GET /v1/dns/zones/:domain_id/records", "POST /v1/dns/zones/:domain_id/records", "PATCH /v1/dns/records/:id"] },
16
+ { title: "Server health", steps: ["GET /v1/server/status", "GET /v1/server/services", "GET /v1/server/metrics", "POST /v1/server/services/:name/restart"] },
17
+ { title: "Backups", steps: ["GET /v1/backups", "POST /v1/backups", "GET /v1/backup-schedules"] },
18
+ { title: "WordPress maintenance", steps: ["GET /v1/wordpress", "POST /v1/wordpress/:id/update-core"] },
19
+ ];
20
+ export function buildInstructions(i) {
21
+ const have = new Set(i.tools.map((t) => `${t.metadata.method} ${t.metadata.path}`));
22
+ const byCat = new Map();
23
+ for (const t of i.tools)
24
+ byCat.set(t.metadata.category, (byCat.get(t.metadata.category) ?? 0) + 1);
25
+ const cats = [...byCat.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([c, n]) => `${c} (${n})`).join(", ");
26
+ const recipes = RECIPES.filter((r) => r.steps.every((s) => have.has(s)))
27
+ .map((r) => `- ${r.title}: ${r.steps.join(" → ")}`);
28
+ const lists = i.tools.filter((t) => t.metadata.method === "GET" && !t.metadata.path.includes(":")).length;
29
+ const keyLines = [];
30
+ if (i.key) {
31
+ const k = i.key;
32
+ keyLines.push("YOUR API KEY (checked at startup with GET /v1/me)");
33
+ keyLines.push(`- Key: ${k.name ?? "?"}${k.keyPrefix ? ` (${k.keyPrefix}…)` : ""}${k.tier ? `, rate-limit tier ${k.tier}` : ""}${k.status ? `, status ${k.status}` : ""}${k.expiresAt ? `, expires ${k.expiresAt}` : ""}.`);
34
+ const sc = k.scopes ?? [];
35
+ keyLines.push(`- Scopes: ${sc.length ? sc.join(", ") : "none"}. A tool whose required scopes are not covered by these (family wildcards like *:read or domains:* count) will answer 403 — say so and suggest the scope instead of calling it.`);
36
+ const readOnly = sc.length > 0 && sc.every((s) => /:read$/.test(s));
37
+ if (readOnly)
38
+ keyLines.push("- This key is read-only: every POST/PUT/PATCH/DELETE tool will be refused. Offer to explain what you would change and which scope the operator must add.");
39
+ }
40
+ else if (i.keyError) {
41
+ keyLines.push("YOUR API KEY");
42
+ keyLines.push(`- The startup check of the configured credentials failed: ${i.keyError}`);
43
+ keyLines.push("- Every tool call will fail the same way until the operator fixes it — tell the user first instead of trying tools one by one.");
44
+ }
45
+ if (i.clockSkewSeconds !== undefined && Math.abs(i.clockSkewSeconds) > 120) {
46
+ keyLines.push(`- WARNING: this machine's clock is ${Math.round(Math.abs(i.clockSkewSeconds))}s ${i.clockSkewSeconds > 0 ? "ahead of" : "behind"} the panel. Signed requests may be rejected (401) until the clock is synced (NTP).`);
47
+ }
48
+ return [
49
+ `Panelica MCP: ${i.tools.length} tools = the Panelica hosting-panel External API${i.panelVersion ? ` (panel ${i.panelVersion})` : ""}, catalogue from ${i.source}. ` +
50
+ `${i.registered.length} tools are registered directly (toolsets: ${i.toolsets.join(",")}); the rest are one search away.`,
51
+ "",
52
+ "HOW CALLS WORK",
53
+ "- Each tool is one HTTP endpoint (method + path in its description). Authentication (HMAC) is done by this server with the operator's API key — never ask the user for credentials.",
54
+ "- Every id (id, domain_id, user_id, zone_id …) is a UUID that must come from a list call first (GET /v1/domains, GET /v1/accounts …); each parameter's description says where. Never invent, guess or reuse an id from memory.",
55
+ "- Users are called accounts: user_id values come from GET /v1/accounts.",
56
+ `- Success responses are {\"status\":\"success\",\"data\":…} (sometimes with \"total\" or \"message\"). ${lists} list tools return all items the key's owner may see, unpaginated unless the tool has page/limit parameters; oversized results are cut to the first items with a _truncated note.`,
57
+ "- Errors come back as text starting with \"Panelica API error <status>\" plus what to do: 403 = the key lacks a scope (ask the operator, do not retry); 404 = wrong id (re-list); 409 = conflict/not configured; 429 = rate limit (wait for the reset shown); 5xx = panel fault (report, do not loop).",
58
+ "- Read-only keys see 403 on every mutating call; scopes are per family (domains:read, dns:write, *:read …).",
59
+ `- List tools accept _limit, _fields and _match (applied here, not by the panel): on a large panel ask for _fields=\"id,domain_name\" and _match=\"<name>\" instead of reading the whole list.`,
60
+ "",
61
+ ...(keyLines.length ? [...keyLines, ""] : []),
62
+ "FINDING THE RIGHT TOOL",
63
+ `- ${META_FIND}(query) searches all ${i.tools.length} tools by keyword; ${META_DESCRIBE}(tool) returns a tool's exact parameters, body fields and response fields; ${META_CALL}(tool, arguments) runs any catalogue tool, registered or not.`,
64
+ `- Categories: ${cats}.`,
65
+ "- Prefer one list call over many single GETs (rate limits are per minute). Use GET /v1/search when you only have a name.",
66
+ "",
67
+ "SAFETY",
68
+ "- GET tools are safe to run freely. POST/PUT/PATCH change server state; DELETE is permanent. Before deleting, suspending, restoring, restarting services or changing PHP/DNS/SSL, state exactly what will change and get the user's confirmation.",
69
+ "- Act only on resources the user named; if a name matches several resources, show them and ask.",
70
+ "- Do not echo passwords, API secrets or tokens from responses unless the user explicitly asks for them.",
71
+ "",
72
+ recipes.length ? "COMMON WORKFLOWS (all steps exist in this catalogue)" : "",
73
+ ...recipes,
74
+ ].filter((l, idx, arr) => !(l === "" && arr[idx - 1] === "")).join("\n");
75
+ }
@@ -0,0 +1,250 @@
1
+ /**
2
+ * Toolsets — which of the 400+ catalogue tools are registered with the client.
3
+ *
4
+ * Why: MCP clients budget tools. Cursor caps active tools at about 40 across
5
+ * all servers and silently drops the rest; every registered tool also costs
6
+ * prompt tokens on each turn. So by default the server registers a compact
7
+ * "core" set plus three meta tools that reach the whole catalogue:
8
+ *
9
+ * panelica_find_tools — keyword search over every catalogue tool
10
+ * panelica_describe_tool — exact parameters + response fields of one tool
11
+ * panelica_call — run any catalogue tool by name (same HMAC client)
12
+ *
13
+ * PANELICA_TOOLSETS (comma-separated, case-insensitive):
14
+ * core curated everyday set (default)
15
+ * all every catalogue tool (the pre-0.3 behaviour)
16
+ * none only the meta tools
17
+ * <category> a category slug, e.g. domains, dns, ssl, git, docker,
18
+ * file_manager, laravel_apps, node_js_apps, python_apps
19
+ * Entries are unioned: "core,git" = core + all Git tools.
20
+ */
21
+ /** Curated everyday tools (METHOD path). Order is irrelevant; presence is what matters. */
22
+ export const CORE_TOOLS = [
23
+ "GET /v1/me",
24
+ "GET /v1/search",
25
+ "GET /v1/accounts",
26
+ "POST /v1/accounts",
27
+ "GET /v1/accounts/:id",
28
+ "POST /v1/accounts/:id/suspend",
29
+ "POST /v1/accounts/:id/unsuspend",
30
+ "GET /v1/domains",
31
+ "POST /v1/domains",
32
+ "GET /v1/domains/:id",
33
+ "PATCH /v1/domains/:id/php",
34
+ "GET /v1/domains/:id/subdomains",
35
+ "POST /v1/domains/:id/subdomains",
36
+ "GET /v1/dns/zones/:domain_id/records",
37
+ "POST /v1/dns/zones/:domain_id/records",
38
+ "PATCH /v1/dns/records/:id",
39
+ "GET /v1/ssl/domains/:domain_id",
40
+ "POST /v1/ssl/domains/:domain_id/issue",
41
+ "GET /v1/databases",
42
+ "POST /v1/databases",
43
+ "GET /v1/email-accounts",
44
+ "POST /v1/email-accounts",
45
+ "GET /v1/ftp-accounts",
46
+ "POST /v1/ftp-accounts",
47
+ "GET /v1/backups",
48
+ "POST /v1/backups",
49
+ "GET /v1/server/status",
50
+ "GET /v1/server/services",
51
+ "GET /v1/server/metrics",
52
+ "POST /v1/server/services/:name/restart",
53
+ "GET /v1/wordpress",
54
+ "POST /v1/wordpress/:id/update-core",
55
+ "GET /v1/docker/containers",
56
+ "GET /v1/plans",
57
+ ];
58
+ export const META_FIND = "panelica_find_tools";
59
+ export const META_CALL = "panelica_call";
60
+ export const META_DESCRIBE = "panelica_describe_tool";
61
+ export function categorySlug(category) {
62
+ return String(category ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
63
+ }
64
+ /** Parse PANELICA_TOOLSETS; empty/undefined → ["core"]. */
65
+ export function parseToolsets(raw) {
66
+ const parts = String(raw ?? "").split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
67
+ return parts.length ? parts : ["core"];
68
+ }
69
+ /** Select the tools to register for the given toolsets (meta tools excluded). */
70
+ export function selectTools(all, toolsets) {
71
+ if (toolsets.includes("all"))
72
+ return all;
73
+ const core = new Set(CORE_TOOLS);
74
+ const wantCore = toolsets.includes("core");
75
+ const cats = new Set(toolsets.filter((t) => t !== "core" && t !== "none" && t !== "all"));
76
+ return all.filter((t) => {
77
+ const key = `${t.metadata.method} ${t.metadata.path}`;
78
+ if (wantCore && core.has(key))
79
+ return true;
80
+ return cats.has(categorySlug(t.metadata.category));
81
+ });
82
+ }
83
+ /**
84
+ * Vocabulary a user (and therefore a model) uses versus the API's own words.
85
+ * Each query term matches if it or any synonym appears; plurals are stemmed.
86
+ */
87
+ export const SYNONYMS = {
88
+ website: ["domain"], site: ["domain", "wordpress"], webpage: ["domain"], vhost: ["domain"],
89
+ user: ["account"], customer: ["account"], client: ["account"], tenant: ["account"], reseller: ["account"],
90
+ mailbox: ["email"], mail: ["email"], inbox: ["email"], forwarder: ["email"], alias: ["email"],
91
+ certificate: ["ssl"], cert: ["ssl"], https: ["ssl"], tls: ["ssl"], letsencrypt: ["ssl"],
92
+ db: ["database"], mysql: ["database", "mysql"], postgres: ["database"], postgresql: ["database"],
93
+ record: ["dns"], zone: ["dns"], nameserver: ["dns"], mx: ["dns"], txt: ["dns"], cname: ["dns"], spf: ["dns"], dkim: ["dns", "email"],
94
+ container: ["docker"], image: ["docker"], compose: ["docker"],
95
+ cron: ["cron"], schedule: ["cron", "backup"], job: ["cron"],
96
+ restore: ["backup", "snapshot"], snapshot: ["snapshot", "backup"],
97
+ service: ["server", "services"], daemon: ["server"], restart: ["server"], reboot: ["server"],
98
+ disk: ["disk", "server"], memory: ["server", "metrics"], cpu: ["server", "metrics"], load: ["server", "metrics"],
99
+ firewall: ["firewall", "security"], ban: ["security", "ip"], block: ["security", "ip"], malware: ["antivirus", "security"], virus: ["antivirus"],
100
+ wp: ["wordpress"], plugin: ["wordpress"], theme: ["wordpress"],
101
+ key: ["api-keys", "ssh"], token: ["api-keys"], password: ["accounts", "email", "ftp", "database"],
102
+ php: ["php"], version: ["php", "nodejs", "python"],
103
+ log: ["logs"], error: ["logs"], access: ["logs"],
104
+ quota: ["plan", "accounts"], limit: ["plan", "rate"], package: ["plan"],
105
+ suspend: ["suspend"], disable: ["suspend"], enable: ["unsuspend"],
106
+ upload: ["files"], download: ["files", "backup"], file: ["files"], folder: ["files"], directory: ["files"],
107
+ git: ["git"], deploy: ["git", "laravel", "nodejs", "python", "docker"], repo: ["git"], repository: ["git"],
108
+ };
109
+ function stem(term) {
110
+ if (term.length > 4 && term.endsWith("ies"))
111
+ return term.slice(0, -3) + "y";
112
+ if (term.length > 4 && /(sses|shes|ches|xes)$/.test(term))
113
+ return term.slice(0, -2);
114
+ if (term.length > 3 && term.endsWith("s") && !term.endsWith("ss"))
115
+ return term.slice(0, -1);
116
+ return term;
117
+ }
118
+ /** Keyword search: every term (or a synonym of it) must appear in name, path, category or description. */
119
+ export function findTools(all, query, limit = 10) {
120
+ const terms = String(query ?? "").toLowerCase().split(/[\s,]+/).filter(Boolean);
121
+ if (terms.length === 0)
122
+ return [];
123
+ const alternatives = terms.map((term) => {
124
+ const base = stem(term);
125
+ return [...new Set([term, base, ...(SYNONYMS[term] ?? []), ...(SYNONYMS[base] ?? [])])];
126
+ });
127
+ const scored = all.map((t) => {
128
+ const hay = `${t.name} ${t.metadata.method} ${t.metadata.path} ${t.metadata.category} ${t.description}`.toLowerCase();
129
+ let score = 0;
130
+ for (const alts of alternatives) {
131
+ const hit = alts.find((a) => hay.includes(a));
132
+ if (!hit)
133
+ return null;
134
+ // Prefer matches in the path / category over description-only hits,
135
+ // and the user's own word over a synonym.
136
+ if (t.metadata.path.toLowerCase().includes(hit))
137
+ score += 3;
138
+ if (t.metadata.category.toLowerCase().includes(hit))
139
+ score += 2;
140
+ score += hit === alts[0] ? 1 : 0.5;
141
+ }
142
+ if (t.metadata.method === "GET")
143
+ score += 0.5; // reads first when tied
144
+ return { t, score };
145
+ }).filter((x) => x !== null);
146
+ scored.sort((a, b) => b.score - a.score || a.t.name.localeCompare(b.t.name));
147
+ return scored.slice(0, Math.max(1, Math.min(50, limit))).map((x) => x.t);
148
+ }
149
+ /** Compact, LLM-friendly summary of a tool for find results. */
150
+ export function summarize(t) {
151
+ const props = t.inputSchema.properties ?? {};
152
+ const required = (t.inputSchema.required ?? []);
153
+ const params = Object.entries(props).filter(([k]) => k !== "body").map(([k, v]) => `${k}${required.includes(k) ? "*" : ""}:${v.type ?? "string"}`);
154
+ const body = props.body;
155
+ const bodyFields = body?.properties ? Object.keys(body.properties).map((k) => `${k}${(body.required ?? []).includes(k) ? "*" : ""}`) : (body ? ["(free-form object)"] : []);
156
+ const r = t.metadata.response;
157
+ const returns = r ? (r.data_type === "none" ? `{status, ${(r.fields ?? []).map((f) => f.name).join(", ")}}` : `${r.data_type}${r.fields?.length ? ` of {${r.fields.slice(0, 10).map((f) => f.name).join(", ")}${r.fields.length > 10 ? ", …" : ""}}` : ""}`) : undefined;
158
+ return {
159
+ name: t.name,
160
+ http: `${t.metadata.method} ${t.metadata.path}`,
161
+ category: t.metadata.category,
162
+ summary: t.description.split("\n")[0],
163
+ params,
164
+ body: bodyFields,
165
+ ...(returns ? { returns } : {}),
166
+ scopes: t.metadata.scopes,
167
+ };
168
+ }
169
+ /** Everything a caller needs to use one tool correctly: full input schema + response fields. */
170
+ export function describeTool(t) {
171
+ const schema = t.inputSchema;
172
+ const props = schema.properties ?? {};
173
+ const required = new Set(schema.required ?? []);
174
+ const withEnum = (v) => ({ ...(v.enum ? { enum: v.enum } : {}), ...(v.default !== undefined ? { default: v.default } : {}) });
175
+ const params = Object.entries(props).filter(([k]) => k !== "body").map(([k, v]) => ({ name: k, type: v.type ?? "string", required: required.has(k), description: v.description ?? "", ...withEnum(v) }));
176
+ const body = props.body;
177
+ const bodyReq = new Set(body?.required ?? []);
178
+ const bodyFields = body?.properties
179
+ ? Object.entries(body.properties).map(([k, v]) => ({ name: k, type: v.type ?? "string", required: bodyReq.has(k), description: v.description ?? "", ...withEnum(v) }))
180
+ : undefined;
181
+ const r = t.metadata.response;
182
+ return {
183
+ name: t.name,
184
+ http: `${t.metadata.method} ${t.metadata.path}`,
185
+ category: t.metadata.category,
186
+ description: t.description.split("\n")[0],
187
+ scopes: t.metadata.scopes,
188
+ ...(t.metadata.scopeRule ? { scope_rule: t.metadata.scopeRule } : {}),
189
+ ...(t.metadata.roles ? { roles: t.metadata.roles } : {}),
190
+ risk: t.metadata.method === "DELETE" ? "destructive" : (t.metadata.method === "GET" ? "read-only" : "mutating"),
191
+ params,
192
+ body: body ? (bodyFields ?? "free-form object — see the panel's API docs") : "none",
193
+ body_required: required.has("body"),
194
+ response: r
195
+ ? { envelope: r.data_type === "none" ? "{status, …keys}" : `{status, data: ${r.data_type}${r.keys?.length ? ", " + r.keys.join(", ") : ""}}`, fields: r.fields ?? [] }
196
+ : { envelope: "{status, data}", fields: [], note: "field list not available for this panel version" },
197
+ };
198
+ }
199
+ /** The meta tools (find / describe / call), as MCP tool definitions. */
200
+ export function metaTools(catalogueSize, registered) {
201
+ return [
202
+ {
203
+ name: META_FIND,
204
+ description: `Search the full Panelica tool catalogue (${catalogueSize} tools; ${registered} are registered directly). ` +
205
+ `Use this when no registered tool fits: returns matching tools with their parameters, then run one with ${META_CALL}.\n` +
206
+ `Read-only.`,
207
+ inputSchema: {
208
+ type: "object",
209
+ properties: {
210
+ query: { type: "string", description: "Keywords, e.g. 'dns records', 'wordpress update', 'ssl issue'" },
211
+ limit: { type: "integer", description: "Max results (default 10, max 50)" },
212
+ },
213
+ required: ["query"],
214
+ additionalProperties: false,
215
+ },
216
+ annotations: { title: "Find Panelica tools", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
217
+ metadata: { method: "GET", path: "(catalogue)", category: "Meta", scopes: [] },
218
+ },
219
+ {
220
+ name: META_DESCRIBE,
221
+ description: `Describe one Panelica catalogue tool by name: exact path/query parameters, request body fields (types, required) and the response envelope with its data fields. ` +
222
+ `Use it before calling a tool whose arguments or result shape you are unsure about.\nRead-only.`,
223
+ inputSchema: {
224
+ type: "object",
225
+ properties: { tool: { type: "string", description: "Catalogue tool name, e.g. panelica_domains_get_v1_domains_id" } },
226
+ required: ["tool"],
227
+ additionalProperties: false,
228
+ },
229
+ annotations: { title: "Describe a Panelica tool", readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
230
+ metadata: { method: "GET", path: "(catalogue)", category: "Meta", scopes: [] },
231
+ },
232
+ {
233
+ name: META_CALL,
234
+ description: `Run any Panelica catalogue tool by name (as returned by ${META_FIND}) with its arguments. ` +
235
+ `Path params, query params and 'body' follow that tool's schema. ` +
236
+ `Mutating or destructive depending on the underlying tool — check its HTTP method first.`,
237
+ inputSchema: {
238
+ type: "object",
239
+ properties: {
240
+ tool: { type: "string", description: "Catalogue tool name, e.g. panelica_domains_get_v1_domains" },
241
+ arguments: { type: "object", description: "Arguments for that tool", additionalProperties: true },
242
+ },
243
+ required: ["tool"],
244
+ additionalProperties: false,
245
+ },
246
+ annotations: { title: "Call a Panelica tool", readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
247
+ metadata: { method: "ANY", path: "(catalogue)", category: "Meta", scopes: [] },
248
+ },
249
+ ];
250
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "panelica-mcp",
3
- "version": "0.2.2",
3
+ "version": "0.5.2",
4
4
  "description": "MCP server exposing the Panelica hosting panel External API to AI assistants. Manage accounts, domains, databases, email, DNS, SSL, FTP, security, and server resources through natural language.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -15,10 +15,10 @@
15
15
  ],
16
16
  "scripts": {
17
17
  "build": "tsc -p tsconfig.json",
18
- "rebuild-tools": "node tools/build-tools.mjs",
18
+ "rebuild-tools": "npm run build && node tools/build-tools.mjs",
19
19
  "prepare": "npm run build",
20
20
  "start": "node dist/index.js",
21
- "refresh": "node tools/build-tools.mjs # set PANELICA_SPEC_URL to pull the live spec"
21
+ "test": "npm run build && node tools/build-tools.mjs && node --test tests/*.test.mjs"
22
22
  },
23
23
  "keywords": [
24
24
  "mcp",