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.
package/dist/errors.js ADDED
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Error explanation — turns a failed External API call into text an AI
3
+ * assistant can act on.
4
+ *
5
+ * The panel answers errors with {"status":"error","error":<string|{code,message,…}>,
6
+ * "details"?, "request_id"?}. Scope failures add required_scope / available_scopes;
7
+ * rate limiting adds X-RateLimit-* headers. A raw "403 Forbidden" makes a model
8
+ * retry or guess; naming the missing scope, the bad id, or the reset time lets
9
+ * it do the right next thing (ask the operator, re-list, wait) instead.
10
+ */
11
+ function parseErrorBody(body) {
12
+ let j;
13
+ try {
14
+ j = JSON.parse(body);
15
+ }
16
+ catch {
17
+ return { message: body.trim().slice(0, 500) };
18
+ }
19
+ if (!j || typeof j !== "object")
20
+ return { message: String(body).slice(0, 500) };
21
+ const o = j;
22
+ const err = o.error ?? o.message;
23
+ const out = { message: "" };
24
+ if (typeof err === "string")
25
+ out.message = err;
26
+ else if (err && typeof err === "object") {
27
+ const e = err;
28
+ out.message = String(e.message ?? e.error ?? "");
29
+ if (typeof e.code === "string")
30
+ out.code = e.code;
31
+ if (typeof e.required_scope === "string")
32
+ out.requiredScope = e.required_scope;
33
+ if (Array.isArray(e.available_scopes))
34
+ out.availableScopes = e.available_scopes.map(String);
35
+ if (e.details !== undefined)
36
+ out.details = typeof e.details === "string" ? e.details : JSON.stringify(e.details);
37
+ }
38
+ if (typeof o.details === "string")
39
+ out.details = o.details;
40
+ else if (o.details !== undefined && out.details === undefined)
41
+ out.details = JSON.stringify(o.details);
42
+ if (typeof o.request_id === "string")
43
+ out.requestId = o.request_id;
44
+ if (typeof o.code === "string" && !out.code)
45
+ out.code = o.code;
46
+ return out;
47
+ }
48
+ /**
49
+ * Older panels answered External API errors with the untranslated
50
+ * message key ("apiErrors.external.domain.notFound"). Turn such a key into
51
+ * readable words so the model is not left with an identifier.
52
+ */
53
+ export function humanizeKey(msg) {
54
+ if (!/^api(Errors|Success)\.[A-Za-z0-9_.]+$/.test(msg))
55
+ return msg;
56
+ const last = msg.split(".").slice(2).join(" ");
57
+ const words = last.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/_/g, " ").toLowerCase();
58
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : msg;
59
+ }
60
+ function header(h, name) {
61
+ const k = Object.keys(h).find((x) => x.toLowerCase() === name.toLowerCase());
62
+ return k ? h[k] : undefined;
63
+ }
64
+ const TAG_TEXT = {
65
+ required: "is required",
66
+ min: "is below the minimum length/value",
67
+ max: "exceeds the maximum length/value",
68
+ len: "has the wrong length",
69
+ email: "must be a valid e-mail address",
70
+ url: "must be a valid URL",
71
+ uuid: "must be a UUID", uuid4: "must be a UUID",
72
+ oneof: "must be one of the allowed values (see the enum in the tool schema)",
73
+ gte: "is below the allowed minimum", gt: "is below the allowed minimum",
74
+ lte: "is above the allowed maximum", lt: "is above the allowed maximum",
75
+ alphanum: "must contain only letters and digits", alpha: "must contain only letters", numeric: "must be numeric",
76
+ ip: "must be an IP address", ipv4: "must be an IPv4 address", ipv6: "must be an IPv6 address",
77
+ fqdn: "must be a valid hostname", hostname: "must be a valid hostname",
78
+ startswith: "must start with the expected prefix", endswith: "must end with the expected suffix",
79
+ };
80
+ /**
81
+ * Gin/validator messages look like
82
+ * Key: 'CreateDomainRequest.UserID' Error:Field validation for 'UserID' failed on the 'required' tag
83
+ * Map the Go field back to the JSON name the caller used and say what is wrong.
84
+ */
85
+ export function humanizeValidation(msg, jsonFields = []) {
86
+ const re = /Field validation for '([A-Za-z0-9_]+)' failed on the '([A-Za-z0-9_]+)' tag/g;
87
+ const norm = (x) => x.toLowerCase().replace(/_/g, "");
88
+ const out = [];
89
+ for (const m of msg.matchAll(re)) {
90
+ const goName = m[1];
91
+ const json = jsonFields.find((f) => norm(f) === norm(goName)) ?? goName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
92
+ out.push(`field "${json}" ${TAG_TEXT[m[2]] ?? `failed the "${m[2]}" rule`}`);
93
+ }
94
+ return out.length ? out.join("; ") : undefined;
95
+ }
96
+ /** One paragraph of guidance per status class, followed by the raw body for reference. */
97
+ export function explainError(c, jsonFields = []) {
98
+ const p = parseErrorBody(c.body);
99
+ const where = `${c.method} ${c.path}`;
100
+ const lines = [`Panelica API error ${c.status}${c.statusText ? ` ${c.statusText}` : ""} on ${where}`];
101
+ const validation = p.message ? humanizeValidation(p.message, jsonFields) : undefined;
102
+ if (validation)
103
+ lines.push(`Validation: ${validation}`);
104
+ else if (p.message)
105
+ lines.push(`Message: ${humanizeKey(p.message)}`);
106
+ if (p.details)
107
+ lines.push(`Details: ${p.details.slice(0, 800)}`);
108
+ switch (true) {
109
+ case c.status === 400 || c.status === 422:
110
+ lines.push("What to do: the panel rejected the arguments (missing/invalid field, bad id format or an unsupported value). " +
111
+ "Check the exact parameters with panelica_describe_tool and fix the call; do not repeat it unchanged.");
112
+ break;
113
+ case c.status === 401:
114
+ lines.push("What to do: authentication failed for the API key configured in this MCP server (PANELICA_API_KEY/SECRET) — " +
115
+ "invalid or expired key, wrong secret, or the panel and this machine disagree on the time. " +
116
+ "This is not fixable from the conversation: tell the operator to check the key in the panel (Settings → API Keys) and the server clock. Do not retry.");
117
+ break;
118
+ case c.status === 403 && !!p.requiredScope:
119
+ lines.push(`What to do: the API key lacks the scope "${p.requiredScope}"` +
120
+ (p.availableScopes?.length ? ` (it has: ${p.availableScopes.join(", ")})` : "") +
121
+ ". Retrying cannot help — ask the operator to add that scope to the key in the panel (Settings → API Keys), or use a read-only alternative.");
122
+ break;
123
+ case c.status === 403:
124
+ lines.push("What to do: forbidden for this key's owner — the resource belongs to another account, or the owner's role (user/reseller/admin) may not perform this action. " +
125
+ "Do not retry with guessed ids; re-list the resources visible to this key and, if the action needs higher privileges, tell the operator.");
126
+ break;
127
+ case c.status === 404:
128
+ lines.push("What to do: no such resource for this key's owner. Ids are UUIDs that must come from a list call (e.g. GET /v1/domains, GET /v1/accounts) — " +
129
+ "never invent or reuse one from memory. Re-list, pick the id from the result, then call again.");
130
+ break;
131
+ case c.status === 409:
132
+ lines.push("What to do: conflict — the resource already exists, is in a state that forbids this action, or an integration is not configured " +
133
+ "(e.g. Cloudflare credentials missing). Read the message, check current state with the matching GET tool, and only then decide.");
134
+ break;
135
+ case c.status === 429: {
136
+ const remM = header(c.headers, "X-RateLimit-Remaining-Minute");
137
+ const resetM = header(c.headers, "X-RateLimit-Reset-Minute");
138
+ const retry = header(c.headers, "Retry-After");
139
+ let wait = "";
140
+ if (retry)
141
+ wait = `Retry after ${retry}s.`;
142
+ else if (resetM && /^\d+$/.test(resetM)) {
143
+ const secs = Math.max(1, Number(resetM) - Math.floor(Date.now() / 1000));
144
+ wait = `The per-minute window resets in about ${secs}s.`;
145
+ }
146
+ lines.push(`What to do: rate limit of the API key's tier reached${remM !== undefined ? ` (remaining this minute: ${remM})` : ""}. ${wait} ` +
147
+ "Wait, then continue with fewer calls (prefer one list call over many single GETs). A higher tier is set by the operator on the API key.");
148
+ break;
149
+ }
150
+ case c.status === 503:
151
+ lines.push("What to do: the panel service behind this endpoint is unavailable right now (service down or starting). Wait a moment and retry once; if it persists, tell the operator.");
152
+ break;
153
+ case c.status >= 500:
154
+ lines.push("What to do: the panel failed internally — not caused by your arguments. Do not loop on retries; report the message" +
155
+ (p.requestId ? ` and request_id ${p.requestId}` : "") + " to the operator, and continue with other tasks.");
156
+ break;
157
+ default:
158
+ lines.push("What to do: read the message above; check the tool's parameters with panelica_describe_tool before calling again.");
159
+ }
160
+ if (p.requestId && c.status !== 500)
161
+ lines.push(`request_id: ${p.requestId}`);
162
+ lines.push(`Raw response: ${c.body.slice(0, 1500)}`);
163
+ return lines.join("\n");
164
+ }
165
+ /** Pull _limit/_fields/_match out of the arguments (they never reach the panel). */
166
+ export function takeShaping(args) {
167
+ const { _limit, _fields, _match, ...rest } = args;
168
+ const shaping = {};
169
+ if (_limit !== undefined && _limit !== null && String(_limit) !== "")
170
+ shaping.limit = Math.max(0, Math.floor(Number(_limit)));
171
+ if (typeof _fields === "string" && _fields.trim())
172
+ shaping.fields = _fields.split(",").map((f) => f.trim()).filter(Boolean);
173
+ if (typeof _match === "string" && _match.trim())
174
+ shaping.match = _match.trim().toLowerCase();
175
+ return { rest, shaping };
176
+ }
177
+ /**
178
+ * Apply client-side shaping to a {status, data: [...]} result: filter by
179
+ * substring, project fields, cut to N items. Adds a _shaped note so the model
180
+ * knows what it is looking at. Non-list results pass through untouched.
181
+ */
182
+ export function shapeResult(text, s) {
183
+ if (s.limit === undefined && !s.fields && !s.match)
184
+ return text;
185
+ let j;
186
+ try {
187
+ j = JSON.parse(text);
188
+ }
189
+ catch {
190
+ return text;
191
+ }
192
+ if (!j || !Array.isArray(j.data))
193
+ return text;
194
+ const total = j.data.length;
195
+ let items = j.data;
196
+ if (s.match)
197
+ items = items.filter((it) => JSON.stringify(it).toLowerCase().includes(s.match));
198
+ const matched = items.length;
199
+ if (s.fields) {
200
+ const keep = new Set(s.fields);
201
+ items = items.map((it) => (it && typeof it === "object" && !Array.isArray(it))
202
+ ? Object.fromEntries(Object.entries(it).filter(([k]) => keep.has(k)))
203
+ : it);
204
+ }
205
+ if (s.limit !== undefined)
206
+ items = items.slice(0, s.limit);
207
+ return JSON.stringify({ ...j, data: items, _shaped: { total, matched, shown: items.length, ...(s.fields ? { fields: s.fields } : {}), ...(s.match ? { match: s.match } : {}) } });
208
+ }
209
+ /**
210
+ * Keep successful results within a size the client can hold. Large list
211
+ * responses are cut to the first items with an explicit note (valid JSON
212
+ * stays valid); anything else is truncated as text with a note.
213
+ */
214
+ export function boundResult(text, maxChars) {
215
+ if (text.length <= maxChars)
216
+ return text;
217
+ try {
218
+ const j = JSON.parse(text);
219
+ const data = j?.data;
220
+ if (Array.isArray(data) && data.length > 1) {
221
+ const total = data.length;
222
+ let keep = data.length;
223
+ let out = "";
224
+ // Halve until it fits — a few iterations at most.
225
+ do {
226
+ keep = Math.max(1, Math.floor(keep / 2));
227
+ out = JSON.stringify({ ...j, data: data.slice(0, keep), _truncated: { shown: keep, total, note: `Result too large (${text.length} chars); showing the first ${keep} of ${total} items. Narrow the query (filters, a specific id) to see the rest.` } });
228
+ } while (out.length > maxChars && keep > 1);
229
+ return out;
230
+ }
231
+ }
232
+ catch { /* not JSON */ }
233
+ return text.slice(0, maxChars) + `\n…[truncated: ${text.length - maxChars} more chars — narrow the request to see the rest]`;
234
+ }
package/dist/index.js CHANGED
@@ -2,16 +2,44 @@
2
2
  /**
3
3
  * Panelica MCP Server
4
4
  *
5
- * Exposes the Panelica External API (404 endpoints, HMAC-authenticated) as MCP
6
- * tools so AI assistants like Claude Desktop, Cursor, and ChatGPT can manage
5
+ * Exposes the Panelica External API (HMAC-authenticated) as MCP tools so AI
6
+ * assistants like Claude Desktop, Claude Code, Cursor and Codex can manage
7
7
  * hosting accounts, domains, databases, email, DNS, SSL, FTP, security, and
8
8
  * server resources through natural language.
9
9
  *
10
+ * What the connecting model gets, beyond the tools themselves:
11
+ * - server instructions (MCP initialize): how ids, scopes, envelopes, errors
12
+ * and rate limits work, plus workflow recipes — generated from the catalogue
13
+ * - per-tool "Returns:" lines and id-parameter provenance in every description
14
+ * - panelica_describe_tool for exact parameters + response fields
15
+ * - errors translated into what to do next (missing scope, wrong id, wait…)
16
+ * - resources: panelica://guide, panelica://catalogue, panelica://spec
17
+ *
10
18
  * Environment variables:
11
- * PANELICA_BASE_URL Base URL of the External API (e.g. https://panel.example.com:3002)
12
- * PANELICA_API_KEY External API key (from panel: Settings -> API Keys)
13
- * PANELICA_API_SECRET External API secret (paired with the key above)
14
- * PANELICA_TIMEOUT_MS Optional request timeout (default 30000)
19
+ * PANELICA_BASE_URL Base URL of the External API
20
+ * (e.g. https://panel.example.com:8443/api/external)
21
+ * PANELICA_API_KEY External API key (panel: Settings -> API Keys)
22
+ * PANELICA_API_SECRET API secret paired with the key above
23
+ * PANELICA_TIMEOUT_MS Optional request timeout (default 30000)
24
+ * PANELICA_LIVE_SPEC "1" (default): at startup fetch <BASE_URL>/v1/api-spec
25
+ * from YOUR panel and build the tool list from it, so the
26
+ * catalogue always matches the panel version you run.
27
+ * "0": use only the committed tools/tools.json snapshot.
28
+ * A live fetch that fails (unreachable panel, self-signed
29
+ * certificate not trusted, timeout) falls back to the
30
+ * snapshot — the server always starts.
31
+ * PANELICA_SPEC_TIMEOUT_MS Optional live-spec fetch timeout (default 8000)
32
+ * PANELICA_TOOLSETS Which tools to register (default "core"): "core", "all",
33
+ * "none" or category slugs, comma-separated — see
34
+ * src/toolsets.ts. Three meta tools (panelica_find_tools,
35
+ * panelica_describe_tool, panelica_call) always give
36
+ * access to the whole catalogue.
37
+ * PANELICA_MAX_RESULT_CHARS Optional cap on a tool result (default 60000);
38
+ * larger list results are cut to the first items with a
39
+ * _truncated note so the client context is not flooded.
40
+ * PANELICA_STARTUP_PROBE "1" (default): call GET /v1/me once at startup so the
41
+ * instructions can state the key's scopes/tier (and warn
42
+ * immediately when the credentials are rejected). "0" skips it.
15
43
  *
16
44
  * Run:
17
45
  * panelica-mcp # stdio transport (default for Claude Desktop)
@@ -22,22 +50,56 @@ import { fileURLToPath } from "node:url";
22
50
  import { createHmac } from "node:crypto";
23
51
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
24
52
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
25
- import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
53
+ import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
54
+ import { buildTools, fetchSpec } from "./catalog.js";
55
+ import { boundResult, explainError, shapeResult, takeShaping } from "./errors.js";
56
+ import { buildInstructions } from "./instructions.js";
57
+ import { META_CALL, META_DESCRIBE, META_FIND, describeTool, findTools, metaTools, parseToolsets, selectTools, summarize } from "./toolsets.js";
26
58
  const __dirname = dirname(fileURLToPath(import.meta.url));
27
- const toolsPath = resolve(__dirname, "../tools/tools.json");
28
- const tools = JSON.parse(readFileSync(toolsPath, "utf8"));
29
- const toolMap = new Map(tools.map(t => [t.name, t]));
59
+ // Single source of truth for the version: package.json (bumped by the release
60
+ // workflow). No hand-maintained copies.
61
+ const pkg = JSON.parse(readFileSync(resolve(__dirname, "../package.json"), "utf8"));
62
+ const VERSION = pkg.version;
30
63
  function requireEnv(name) {
31
64
  const v = process.env[name];
32
65
  if (!v) {
33
66
  throw new Error(`Missing required environment variable: ${name}.\n` +
34
67
  `Generate an API key/secret pair in your Panelica panel (Settings -> API Keys) and set:\n` +
35
- ` PANELICA_BASE_URL e.g. https://panel.example.com:3002\n` +
68
+ ` PANELICA_BASE_URL e.g. https://panel.example.com:8443/api/external\n` +
36
69
  ` PANELICA_API_KEY X-API-Key value\n` +
37
70
  ` PANELICA_API_SECRET paired secret`);
38
71
  }
39
72
  return v;
40
73
  }
74
+ // stderr only: stdout is the MCP JSON-RPC channel and must stay clean.
75
+ function log(msg) {
76
+ process.stderr.write(`[panelica-mcp] ${msg}\n`);
77
+ }
78
+ // ── Tool catalogue: live spec (default) with snapshot fallback ────────────────
79
+ const snapshotPath = resolve(__dirname, "../tools/tools.json");
80
+ const snapshotTools = JSON.parse(readFileSync(snapshotPath, "utf8"));
81
+ async function loadTools() {
82
+ const live = (process.env.PANELICA_LIVE_SPEC ?? "1") !== "0";
83
+ const baseUrl = (process.env.PANELICA_BASE_URL ?? "").replace(/\/+$/, "");
84
+ if (!live || !baseUrl) {
85
+ return { tools: snapshotTools, source: `snapshot (${snapshotTools.length} tools)` };
86
+ }
87
+ const timeoutMs = Number(process.env.PANELICA_SPEC_TIMEOUT_MS ?? 8_000);
88
+ try {
89
+ const spec = await fetchSpec(`${baseUrl}/v1/api-spec`, timeoutMs);
90
+ const { tools } = buildTools(spec);
91
+ if (tools.length === 0)
92
+ throw new Error("live spec produced no tools");
93
+ const prov = [spec.panel_version ? `panel ${spec.panel_version}` : "", spec.generated_at ?? ""].filter(Boolean).join(" ");
94
+ return { tools, source: `live spec (${tools.length} tools${prov ? `, ${prov}` : ""})`, spec, panelVersion: spec.panel_version };
95
+ }
96
+ catch (err) {
97
+ const msg = err instanceof Error ? err.message : String(err);
98
+ log(`live spec unavailable (${msg}); using committed snapshot (${snapshotTools.length} tools)`);
99
+ return { tools: snapshotTools, source: `snapshot (${snapshotTools.length} tools)` };
100
+ }
101
+ }
102
+ // ── HMAC client ───────────────────────────────────────────────────────────────
41
103
  function sign(method, fullPath, timestamp, body, secret) {
42
104
  // Backend formula: HMAC-SHA256(METHOD + PATH + TIMESTAMP + BODY, SECRET)
43
105
  // DELETE requests exclude body from the signature.
@@ -52,39 +114,28 @@ function buildPathAndQuery(template, args) {
52
114
  for (const m of template.matchAll(/:([a-zA-Z_][a-zA-Z0-9_]*)/g)) {
53
115
  const key = m[1];
54
116
  const value = args[key];
55
- if (value === undefined || value === null) {
56
- throw new Error(`Missing required path parameter: ${key}`);
117
+ if (value === undefined || value === null || value === "") {
118
+ throw new Error(`Missing required path parameter "${key}" for ${template}. Its value is an id from a list call — see ${META_DESCRIBE}.`);
57
119
  }
58
120
  path = path.replace(`:${key}`, encodeURIComponent(String(value)));
59
121
  used.add(key);
60
122
  }
61
123
  return { path, queryUsed: used };
62
124
  }
63
- async function callPanelica(tool, args) {
125
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
126
+ /** One signed HTTP request. Throws with an explanation on network failure. */
127
+ async function panelicaRequest(method, fullPath, bodyString) {
64
128
  const baseUrl = requireEnv("PANELICA_BASE_URL").replace(/\/+$/, "");
65
129
  const apiKey = requireEnv("PANELICA_API_KEY");
66
130
  const apiSecret = requireEnv("PANELICA_API_SECRET");
67
131
  const timeoutMs = Number(process.env.PANELICA_TIMEOUT_MS ?? 30_000);
68
- const { method, path: pathTemplate } = tool.metadata;
69
- const { path: resolvedPath, queryUsed } = buildPathAndQuery(pathTemplate, args);
70
- // Remaining args that are not path params and not body -> query string.
71
- const queryParams = new URLSearchParams();
72
- for (const [k, v] of Object.entries(args)) {
73
- if (k === "body" || queryUsed.has(k) || v === undefined || v === null)
74
- continue;
75
- queryParams.append(k, String(v));
76
- }
77
- const queryString = queryParams.toString();
78
- const fullPath = queryString ? `${resolvedPath}?${queryString}` : resolvedPath;
79
- const bodyString = args.body !== undefined ? JSON.stringify(args.body) : "";
80
132
  const timestamp = Math.floor(Date.now() / 1000).toString();
81
- const signature = sign(method, fullPath, timestamp, bodyString, apiSecret);
82
133
  const headers = {
83
134
  "X-API-Key": apiKey,
84
135
  "X-Timestamp": timestamp,
85
- "X-Signature": signature,
136
+ "X-Signature": sign(method, fullPath, timestamp, bodyString, apiSecret),
86
137
  "Accept": "application/json",
87
- "User-Agent": "panelica-mcp/0.2.2",
138
+ "User-Agent": `panelica-mcp/${VERSION}`,
88
139
  };
89
140
  if (bodyString)
90
141
  headers["Content-Type"] = "application/json";
@@ -92,49 +143,210 @@ async function callPanelica(tool, args) {
92
143
  const timer = setTimeout(() => ctrl.abort(), timeoutMs);
93
144
  let response;
94
145
  try {
95
- response = await fetch(`${baseUrl}${fullPath}`, {
96
- method,
97
- headers,
98
- body: bodyString || undefined,
99
- signal: ctrl.signal,
100
- });
146
+ response = await fetch(`${baseUrl}${fullPath}`, { method, headers, body: bodyString || undefined, signal: ctrl.signal });
101
147
  }
102
148
  catch (err) {
103
149
  const msg = err instanceof Error ? err.message : String(err);
104
- throw new Error(`Request to ${method} ${fullPath} failed: ${msg}`);
150
+ const why = /abort/i.test(msg)
151
+ ? `timed out after ${timeoutMs} ms — the panel did not answer in time (long operation or unreachable host). Do not loop on retries; try once more later or tell the operator.`
152
+ : `${msg} — the panel is unreachable from this machine (URL, DNS, firewall or TLS). Nothing to fix from the conversation; tell the operator to check PANELICA_BASE_URL.`;
153
+ throw new Error(`Request ${method} ${fullPath} failed: ${why}`);
105
154
  }
106
155
  finally {
107
156
  clearTimeout(timer);
108
157
  }
109
158
  const text = await response.text();
110
- if (!response.ok) {
111
- throw new Error(`Panelica API ${response.status} ${response.statusText} on ${method} ${fullPath}:\n${text.slice(0, 4000)}`);
159
+ const hdrs = {};
160
+ response.headers.forEach((v, k) => { hdrs[k] = v; });
161
+ return { status: response.status, statusText: response.statusText, text, headers: hdrs };
162
+ }
163
+ /** Seconds until the per-minute rate-limit window resets, from the panel's headers. */
164
+ function rateLimitWait(h) {
165
+ const retry = h["retry-after"];
166
+ if (retry && /^\d+$/.test(retry))
167
+ return Number(retry);
168
+ const reset = h["x-ratelimit-reset-minute"];
169
+ if (reset && /^\d+$/.test(reset))
170
+ return Math.max(1, Number(reset) - Math.floor(Date.now() / 1000));
171
+ return undefined;
172
+ }
173
+ async function callPanelica(tool, rawArgs) {
174
+ const { rest, shaping } = takeShaping(rawArgs);
175
+ const args = rest;
176
+ const { method, path: pathTemplate } = tool.metadata;
177
+ const { path: resolvedPath, queryUsed } = buildPathAndQuery(pathTemplate, args);
178
+ // Remaining args that are not path params and not body -> query string.
179
+ const queryParams = new URLSearchParams();
180
+ for (const [k, v] of Object.entries(args)) {
181
+ if (k === "body" || queryUsed.has(k) || v === undefined || v === null)
182
+ continue;
183
+ queryParams.append(k, String(v));
184
+ }
185
+ const queryString = queryParams.toString();
186
+ const fullPath = queryString ? `${resolvedPath}?${queryString}` : resolvedPath;
187
+ const bodyString = args.body !== undefined ? JSON.stringify(args.body) : "";
188
+ let r;
189
+ try {
190
+ r = await panelicaRequest(method, fullPath, bodyString);
112
191
  }
113
- return text;
192
+ catch (err) {
193
+ // A GET is safe to repeat once after a transient network failure.
194
+ if (method !== "GET")
195
+ return { ok: false, text: err instanceof Error ? err.message : String(err) };
196
+ await sleep(1000);
197
+ try {
198
+ r = await panelicaRequest(method, fullPath, bodyString);
199
+ }
200
+ catch (err2) {
201
+ return { ok: false, text: err2 instanceof Error ? err2.message : String(err2) };
202
+ }
203
+ }
204
+ // Short rate-limit windows are waited out once instead of surfacing a 429.
205
+ if (r.status === 429) {
206
+ const wait = rateLimitWait(r.headers);
207
+ if (wait !== undefined && wait <= 15) {
208
+ log(`429 on ${method} ${fullPath}; waiting ${wait}s for the rate-limit window`);
209
+ await sleep((wait + 1) * 1000);
210
+ r = await panelicaRequest(method, fullPath, bodyString);
211
+ }
212
+ }
213
+ if (r.status < 200 || r.status >= 300) {
214
+ const bodySchema = tool.inputSchema.properties?.body;
215
+ const jsonFields = Object.keys(bodySchema?.properties ?? {});
216
+ return { ok: false, text: explainError({ status: r.status, statusText: r.statusText, method, path: fullPath, body: r.text, headers: r.headers }, jsonFields) };
217
+ }
218
+ const shaped = shapeResult(r.text, shaping);
219
+ return { ok: true, text: boundResult(shaped, Number(process.env.PANELICA_MAX_RESULT_CHARS ?? 60_000)) };
114
220
  }
115
- const server = new Server({ name: "panelica-mcp", version: "0.2.2" }, { capabilities: { tools: {} } });
221
+ /**
222
+ * Startup probe: GET /v1/me tells us which key this is and what it may do, so
223
+ * the instructions can say it up front (and a rejected credential is reported
224
+ * before the model wastes calls). Never fatal.
225
+ */
226
+ async function probeIdentity() {
227
+ if ((process.env.PANELICA_STARTUP_PROBE ?? "1") === "0")
228
+ return {};
229
+ if (!process.env.PANELICA_BASE_URL || !process.env.PANELICA_API_KEY || !process.env.PANELICA_API_SECRET)
230
+ return {};
231
+ try {
232
+ const r = await panelicaRequest("GET", "/v1/me", "");
233
+ if (r.status < 200 || r.status >= 300) {
234
+ const text = explainError({ status: r.status, statusText: r.statusText, method: "GET", path: "/v1/me", body: r.text, headers: r.headers });
235
+ return { keyError: text.split("\n").slice(0, 3).join(" ") };
236
+ }
237
+ const j = JSON.parse(r.text);
238
+ const d = j.data ?? {};
239
+ return { key: {
240
+ name: typeof d.name === "string" ? d.name : undefined,
241
+ keyPrefix: typeof d.key_prefix === "string" ? d.key_prefix : undefined,
242
+ scopes: Array.isArray(d.scopes) ? d.scopes.map(String) : undefined,
243
+ tier: typeof d.rate_limit_tier === "string" ? d.rate_limit_tier : undefined,
244
+ status: typeof d.status === "string" ? d.status : undefined,
245
+ expiresAt: typeof d.expires_at === "string" ? d.expires_at : undefined,
246
+ } };
247
+ }
248
+ catch (err) {
249
+ return { keyError: err instanceof Error ? err.message : String(err) };
250
+ }
251
+ }
252
+ // ── Server ────────────────────────────────────────────────────────────────────
253
+ const loaded = await loadTools();
254
+ const { tools, source } = loaded;
255
+ // Full catalogue (reachable through panelica_call) vs. the registered subset
256
+ // (what the client sees in tools/list). See src/toolsets.ts for the rationale.
257
+ const toolMap = new Map(tools.map((t) => [t.name, t]));
258
+ const toolsets = parseToolsets(process.env.PANELICA_TOOLSETS);
259
+ const registered = selectTools(tools, toolsets);
260
+ const exposed = [...metaTools(tools.length, registered.length), ...registered];
261
+ const identity = await probeIdentity();
262
+ // Clock skew: the live spec carries the panel's current time; HMAC timestamps
263
+ // are rejected beyond the panel's tolerance, so warn while the model can still
264
+ // tell the operator instead of watching every call fail with 401.
265
+ let clockSkewSeconds;
266
+ if (loaded.spec?.generated_at) {
267
+ const panelTime = Date.parse(loaded.spec.generated_at);
268
+ if (!Number.isNaN(panelTime))
269
+ clockSkewSeconds = Math.round((Date.now() - panelTime) / 1000);
270
+ }
271
+ const instructions = buildInstructions({ tools, registered, toolsets, source, panelVersion: loaded.panelVersion, key: identity.key, keyError: identity.keyError, clockSkewSeconds });
272
+ log(`v${VERSION} — catalogue from ${source}; toolsets=${toolsets.join(",")} → ${exposed.length} tools registered`);
273
+ if (identity.key)
274
+ log(`key ${identity.key.name ?? "?"} scopes=${(identity.key.scopes ?? []).join(",") || "none"} tier=${identity.key.tier ?? "?"}`);
275
+ else if (identity.keyError)
276
+ log(`startup credential check failed: ${identity.keyError}`);
277
+ if (clockSkewSeconds !== undefined && Math.abs(clockSkewSeconds) > 120)
278
+ log(`WARNING: clock skew of ${clockSkewSeconds}s versus the panel — signed requests may be rejected`);
279
+ const server = new Server({ name: "panelica-mcp", version: VERSION }, { capabilities: { tools: {}, resources: {} }, instructions });
116
280
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
117
- tools: tools.map(t => ({
281
+ tools: exposed.map((t) => ({
118
282
  name: t.name,
119
283
  description: t.description,
120
284
  inputSchema: t.inputSchema,
121
285
  // Safety hints let MCP clients auto-approve read-only calls and warn before
122
- // destructive ones (DELETE). Generated per HTTP method by build-tools.mjs.
286
+ // destructive ones (DELETE). Generated per HTTP method in catalog.ts.
123
287
  ...(t.annotations ? { annotations: t.annotations } : {}),
124
288
  })),
125
289
  }));
290
+ // ── Resources: the same knowledge, attachable by clients that support resources ──
291
+ const RESOURCES = [
292
+ { uri: "panelica://guide", name: "Panelica API guide", description: "How ids, scopes, envelopes, errors and rate limits work; workflow recipes.", mimeType: "text/plain" },
293
+ { uri: "panelica://catalogue", name: "Panelica tool catalogue", description: `All ${tools.length} tools: name, HTTP method/path, category, one-line summary.`, mimeType: "application/json" },
294
+ ...(loaded.spec ? [{ uri: "panelica://spec", name: "Panelica External API spec", description: "The panel's live /v1/api-spec (endpoints, parameters, response fields).", mimeType: "application/json" }] : []),
295
+ ];
296
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: RESOURCES }));
297
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
298
+ const uri = request.params.uri;
299
+ switch (uri) {
300
+ case "panelica://guide":
301
+ return { contents: [{ uri, mimeType: "text/plain", text: instructions }] };
302
+ case "panelica://catalogue":
303
+ return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(tools.map((t) => ({ name: t.name, http: `${t.metadata.method} ${t.metadata.path}`, category: t.metadata.category, summary: t.description.split("\n")[0] }))) }] };
304
+ case "panelica://spec":
305
+ if (loaded.spec)
306
+ return { contents: [{ uri, mimeType: "application/json", text: JSON.stringify(loaded.spec) }] };
307
+ break;
308
+ }
309
+ throw new Error(`Unknown resource: ${uri}`);
310
+ });
126
311
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
127
312
  const { name, arguments: args } = request.params;
128
- const tool = toolMap.get(name);
313
+ const a = (args ?? {});
314
+ if (name === META_FIND) {
315
+ const hits = findTools(tools, String(a.query ?? ""), Number(a.limit ?? 10));
316
+ const text = hits.length
317
+ ? JSON.stringify({ count: hits.length, tools: hits.map(summarize), next: `Run one with ${META_CALL}(tool, arguments); ${META_DESCRIBE}(tool) shows its full parameters and response fields.` }, null, 1)
318
+ : JSON.stringify({ count: 0, hint: "No tool matched every keyword. Try fewer or different words (resource names such as 'domain', 'dns', 'ssl', 'backup', 'wordpress'), or read the panelica://catalogue resource." });
319
+ return { content: [{ type: "text", text }] };
320
+ }
321
+ if (name === META_DESCRIBE) {
322
+ const t = toolMap.get(String(a.tool ?? ""));
323
+ if (!t)
324
+ return { isError: true, content: [{ type: "text", text: `Unknown catalogue tool: ${String(a.tool ?? "")}. Use ${META_FIND} to search.` }] };
325
+ return { content: [{ type: "text", text: JSON.stringify(describeTool(t), null, 1) }] };
326
+ }
327
+ let tool;
328
+ let callArgs;
329
+ if (name === META_CALL) {
330
+ tool = toolMap.get(String(a.tool ?? ""));
331
+ callArgs = (a.arguments ?? {});
332
+ if (!tool) {
333
+ return { isError: true, content: [{ type: "text", text: `Unknown catalogue tool: ${String(a.tool ?? "")}. Use ${META_FIND} to search.` }] };
334
+ }
335
+ }
336
+ else {
337
+ // Direct calls are accepted for every catalogue tool, registered or not.
338
+ tool = toolMap.get(name);
339
+ callArgs = a;
340
+ }
129
341
  if (!tool) {
130
342
  return {
131
343
  isError: true,
132
- content: [{ type: "text", text: `Unknown tool: ${name}` }],
344
+ content: [{ type: "text", text: `Unknown tool: ${name}. Use ${META_FIND} to search the catalogue.` }],
133
345
  };
134
346
  }
135
347
  try {
136
- const body = await callPanelica(tool, (args ?? {}));
137
- return { content: [{ type: "text", text: body }] };
348
+ const r = await callPanelica(tool, callArgs);
349
+ return { ...(r.ok ? {} : { isError: true }), content: [{ type: "text", text: r.text }] };
138
350
  }
139
351
  catch (err) {
140
352
  const msg = err instanceof Error ? err.message : String(err);