@edgegap/mcp 0.18.0 → 0.19.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/README.md CHANGED
@@ -213,15 +213,15 @@ To keep your API token on your own machine, run the server locally instead. Leav
213
213
  }
214
214
  ```
215
215
 
216
- Needs Node 18+. Pin a version in production (`@edgegap/mcp@0.18.0`) rather than floating on latest. Registered in the official MCP registry as `dev.edgegap/mcp`.
216
+ Needs Node 18+. Pin a version in production (`@edgegap/mcp@0.19.0`) rather than floating on latest. Registered in the official MCP registry as `dev.edgegap/mcp`.
217
217
 
218
- The local server can also limit what an agent can do. These variables have no effect on the hosted endpoint at `mcp.edgegap.dev`:
218
+ The local server can also limit what an agent can do. These variables have no effect on the hosted endpoint at `mcp.edgegap.dev`, which takes the two main ones as connection headers instead (see below):
219
219
 
220
220
  | Variable | Default | Purpose |
221
221
  | --- | --- | --- |
222
222
  | `EDGEGAP_API_TOKEN` | *(prompted)* | API token. Optional: omit it and you're asked at first use. The `token ` prefix is added for you. Never pass it as a command-line argument. |
223
223
  | `EDGEGAP_READ_ONLY` | `0` | Set to `1` and the tools that change something (marked ● in [Tools](#-tools)) are never registered, so the agent cannot be talked into calling them. |
224
- | `EDGEGAP_APP_ALLOWLIST` | *(empty)* | Comma-separated application names. Limits what the agent can create and deploy into. Reading (listing apps and versions) is not limited, and neither is touching deployments once running. See [DESIGN.md](DESIGN.md#scope-of-the-allowlist). |
224
+ | `EDGEGAP_APP_ALLOWLIST` | *(empty)* | Comma-separated application names. Limits what the agent can create and deploy into, and which deployments it can stop, tag or report. Reading (listing apps, versions, deployments, logs) is not limited. See [DESIGN.md](DESIGN.md#scope-of-the-allowlist). |
225
225
  | `EDGEGAP_MAX_DURATION_MINUTES` | `60` | Ceiling on `max_duration` the agent may set on a version. `edgegap_deploy` also refuses a version whose `max_duration` is above it, or unlimited, unless the agent passes `allow_long_running: true` after asking you. |
226
226
  | `EDGEGAP_MAX_AGENT_DEPLOYMENTS` | `5` | `edgegap_deploy` refuses while this many deployments tagged `edgegap-mcp` are running. `0` turns the cap off. |
227
227
  | `EDGEGAP_MAX_DEPLOYS_PER_RUN` | `20` | Deploys one server process may send, failed ones included. Restart the server to reset it. `0` turns it off. |
@@ -230,6 +230,15 @@ The local server can also limit what an agent can do. These variables have no ef
230
230
  | `EDGEGAP_TIMEOUT_MS` | `30000` | Per-request HTTP timeout. |
231
231
  | `EDGEGAP_SKILLS_CHECK` | `on` | Set to `off` and the skill tools never read the latest skills version from GitHub. |
232
232
 
233
+ On the hosted endpoint (and the self-hosted Docker image), send these headers on the MCP connection, next to `Authorization`. They can only narrow what the server allows, never widen it:
234
+
235
+ | Header | Purpose |
236
+ | --- | --- |
237
+ | `X-Edgegap-Read-Only: 1` | Same as `EDGEGAP_READ_ONLY=1`: no tool that changes something is offered. Use it for an ops or monitoring agent. |
238
+ | `X-Edgegap-App-Allowlist: my-game,my-game-staging` | Same as `EDGEGAP_APP_ALLOWLIST`, for this connection. Combined with a server allowlist, only applications in both are allowed. |
239
+
240
+ Your token stays organization-wide: Edgegap cannot scope tokens yet. These limit what this server's tools do with it.
241
+
233
242
  #### Windows
234
243
 
235
244
  The local server runs on Windows with Node.js 18 or newer, and CI runs the build and the stdio tests on Windows.
@@ -294,7 +303,7 @@ Your agent picks the right tool from your request. You don't need to name them,
294
303
  | `edgegap_validate_server_config` | Checks an existing Dockerfile, ports, resources, and image tag before you build. Catches ARM or Windows images (Edgegap runs `linux/amd64`), Unreal servers running as root, missing Unity `-batchmode -nographics`, servers bound to `localhost`, ports that don't match your netcode transport, and the `latest` tag. |
295
304
  | `edgegap_get_registry_credentials` ● | Returns push credentials for your private Edgegap container registry, with the exact `docker login`, build, and push commands. Edgegap only gives these to the Unity/Unreal plugins' quick-start token; with a regular API token, it tells your agent to ask you for the login from the dashboard's **Container Registry** page instead. |
296
305
  | `edgegap_list_registry_tags` | Confirms your image push landed before you register it. Takes the image name only, e.g. `my-game-server`: the project comes from your token. |
297
- | `edgegap_delete_registry_tag` ● | Deletes one tag, and the image it points to, to clean up old builds. One exact tag per call; `latest`, wildcards and lists are refused. |
306
+ | `edgegap_delete_registry_tag` ● | Deletes one tag, and the image it points to, to clean up old builds. One exact tag per call; `latest`, wildcards and lists are refused. Needs `confirm: true`. |
298
307
 
299
308
  ### Dedicated Servers (Recommended)
300
309
 
@@ -307,8 +316,8 @@ Your agent picks the right tool from your request. You don't need to name them,
307
316
  | `edgegap_get_app_version` | Reads one version in full: image, resources, ports, max duration, image caching, restart policy, and env var names (never values). |
308
317
  | `edgegap_create_app_version` ● | Registers a container image as a deployable version. Supports TLS Upgrade on WS and HTTP ports, which browser (WebGL) clients need for `wss://`. |
309
318
  | `edgegap_update_app_version` ● | Changes an existing version: a new image tag, on/off, CPU and memory (both together), max duration, registry login, image caching (`force_cache`), shutdown grace period, ports, env vars, and the Endpoint Storage its logs go to. Only the fields passed change, but `ports` and `env` replace the whole list. Running deployments keep the old settings. |
310
- | `edgegap_delete_app_version` ● | Deletes one version, to clean up test versions. Refused while a deployment of it runs. The registry image is kept. |
311
- | `edgegap_delete_app` ● | Deletes an application and its versions. Refused while any of its deployments runs, and while it has more versions than `max_versions` (default 0). |
319
+ | `edgegap_delete_app_version` ● | Deletes one version, to clean up test versions. Refused while a deployment of it runs. Needs `confirm: true`. The registry image is kept. |
320
+ | `edgegap_delete_app` ● | Deletes an application and its versions. Refused while any of its deployments runs, and while it has more versions than `max_versions` (default 0). Needs `confirm: true`. |
312
321
  | `edgegap_list_locations` | Lists the cities Edgegap deploys to, or, for one version, only those with capacity right now. |
313
322
  | `edgegap_list_ping_beacons` | Lists the ping beacons game clients measure their latency to each region against. |
314
323
  | `edgegap_deploy` ● | Deploys an authoritative dedicated server close to your players. Always tagged `edgegap-mcp`, and reports when Edgegap will stop it. Optional: CPU and memory for this deployment only, webhooks Edgegap calls when the server is ready, fails or ends, `require_cached_locations` for faster starts, and `private_host_ids` to place it on your private fleet first. |
@@ -317,8 +326,11 @@ Your agent picks the right tool from your request. You don't need to name them,
317
326
  | `edgegap_get_deployment` | Reads a deployment's status. |
318
327
  | `edgegap_list_deployments` | Lists running deployments, filtered by application, version, status, tags and more, and sorted by age. Finds servers left running; `only_agent_deployments: true` lists every one an agent started. See [Filter Deployments](https://docs.edgegap.com/learn/orchestration/deployments#filter-deployments). |
319
328
  | `edgegap_get_deployment_logs` | Reads container logs and crash details while the deployment runs. After it stops, logs are only kept if Endpoint Storage was set up. |
320
- | `edgegap_get_deployment_metrics` | Summarises CPU, CPU throttling, memory and network use (latest, average, peak), to size a version or check a crash. |
321
- | `edgegap_stop_deployment` ● | Stops one deployment, by its exact request ID. No bulk stop. |
329
+ | `edgegap_get_deployment_metrics` | Summarises CPU, CPU throttling, memory and network use (latest, average, p95, peak) and flags anomalies: spikes, a rising trend such as a memory leak, CPU throttling. To size a version or check a crash. |
330
+ | `edgegap_fleet_health` | One call for "is anything wrong right now?": running deployments by status, the ones in error or stuck starting, and totals per location and version with unhealthy ones flagged. `check_crashes: true` adds restarts and exit codes. |
331
+ | `edgegap_search_deployment_logs` | Searches the logs of many running deployments at once and groups matching lines by error, e.g. every crash in one version since yesterday. |
332
+ | `edgegap_compare_versions` | Compares two versions of an application from their running deployments: errors, crash restarts, and CPU and memory against what each version requests, for a rollback decision. |
333
+ | `edgegap_stop_deployment` ● | Stops one deployment, by its exact request ID. No bulk stop. A deployment the agent did not start needs `confirm: true`. |
322
334
  | `edgegap_tag_deployment` ● | Adds or removes tags on a running deployment, e.g. to mark a match. The `edgegap-mcp` tag stays. |
323
335
  | `edgegap_report_deployment` ● | Reports a deployment to Edgegap with a reason, for a studio's moderation backend. It keeps running. |
324
336
 
@@ -365,6 +377,7 @@ Your API token can do anything in your organization, so the server adds its own
365
377
 
366
378
  | Guardrail | What it does |
367
379
  | --- | --- |
380
+ | Confirm | `edgegap_delete_app`, `edgegap_delete_app_version`, `edgegap_delete_registry_tag`, and `edgegap_stop_deployment` on a running deployment the agent did not start, send nothing without `confirm: true`. They return a preview of what would be stopped or deleted for the agent to show you first. |
368
381
  | Dry run | Every tool that changes something takes `dry_run: true`: it returns the exact method, host, path and body, with the token, registry tokens and env values masked, and sends nothing. Local checks still run. |
369
382
  | No token in containers | A deploy or version is refused, with nothing sent, if your API token appears in an env var name or value, a tag, or a webhook URL. Env values are never echoed back. |
370
383
  | Agent tag | Every deployment gets the `edgegap-mcp` tag, even when the agent passes its own tags. `edgegap_list_deployments` with `only_agent_deployments: true` finds them all. |
package/dist/hosted.js CHANGED
@@ -68,3 +68,30 @@ export function unavailableMessage(problem) {
68
68
  'on the MCP connection.\n\n' +
69
69
  common);
70
70
  }
71
+ /** Shown as the allowlist when the connection's and the server's lists share no application. */
72
+ export const NO_SHARED_APPS = '(none: the X-Edgegap-App-Allowlist header and the server allowlist share no application)';
73
+ /**
74
+ * Narrows a hosted request's config from its headers, so a developer on the
75
+ * hosted endpoint gets the same limits EDGEGAP_READ_ONLY and
76
+ * EDGEGAP_APP_ALLOWLIST give the local server:
77
+ *
78
+ * X-Edgegap-Read-Only: 1 no write tool is registered
79
+ * X-Edgegap-App-Allowlist: a,b writes only in these applications
80
+ *
81
+ * Headers can only narrow: read-only cannot be switched off, and an allowlist
82
+ * already set on the server is intersected, never widened. The token is still
83
+ * organization-wide; this limits what this connection's tools will do with it.
84
+ */
85
+ export function narrowConfig(config, header) {
86
+ const ro = header('x-edgegap-read-only')?.trim().toLowerCase();
87
+ const readOnly = config.readOnly || ro === '1' || ro === 'true';
88
+ const raw = header('x-edgegap-app-allowlist');
89
+ let appAllowlist = config.appAllowlist;
90
+ if (raw !== null && raw !== undefined && raw.trim() !== '') {
91
+ const asked = [...new Set(raw.split(',').map((s) => s.trim()).filter((s) => /^[A-Za-z0-9._-]{1,128}$/.test(s)))].slice(0, 50);
92
+ const narrowed = config.appAllowlist.length ? asked.filter((a) => config.appAllowlist.includes(a)) : asked;
93
+ // A header naming no valid or shared application must not fall back to "all".
94
+ appAllowlist = narrowed.length ? narrowed : [NO_SHARED_APPS];
95
+ }
96
+ return { ...config, readOnly, appAllowlist };
97
+ }
package/dist/http.js CHANGED
@@ -18,7 +18,7 @@ import { EdgegapClient } from './client.js';
18
18
  import { registerTools, serverInstructions } from './tools.js';
19
19
  import { VERSION } from './version.js';
20
20
  import { StaticTokenProvider } from './auth.js';
21
- import { extractToken, unavailableMessage } from './hosted.js';
21
+ import { extractToken, narrowConfig, unavailableMessage } from './hosted.js';
22
22
  const MAX_BODY_BYTES = 1_000_000;
23
23
  function readBody(req) {
24
24
  return new Promise((resolve, reject) => {
@@ -93,10 +93,15 @@ function main() {
93
93
  const { token, problem } = extractToken(req.headers.authorization);
94
94
  const auth = new StaticTokenProvider(token, problem ? unavailableMessage(problem) : undefined, problem);
95
95
  const server = new McpServer({ name: 'edgegap', version: VERSION }, { instructions: serverInstructions('hosted') });
96
- const client = new EdgegapClient(config, auth, {
96
+ // Per-connection limits from X-Edgegap-Read-Only / X-Edgegap-App-Allowlist (narrow only).
97
+ const requestConfig = narrowConfig(config, (name) => {
98
+ const v = req.headers[name];
99
+ return Array.isArray(v) ? v.join(',') : v;
100
+ });
101
+ const client = new EdgegapClient(requestConfig, auth, {
97
102
  clientName: () => server.server.getClientVersion()?.name,
98
103
  });
99
- registerTools(server, client, config, auth);
104
+ registerTools(server, client, requestConfig, auth);
100
105
  const transport = new StreamableHTTPServerTransport({
101
106
  sessionIdGenerator: undefined,
102
107
  enableJsonResponse: true,
package/dist/ops.js ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Pure helpers for the operations tools (fleet health, log search, version
3
+ * comparison) and the metrics summaries. No network, so they are unit-tested
4
+ * directly in test/unit.test.mjs.
5
+ */
6
+ const round = (x) => Math.round(x * 100) / 100;
7
+ /** Nearest-rank percentile of already finite numbers; undefined when empty. */
8
+ export function percentile(values, p) {
9
+ if (values.length === 0)
10
+ return undefined;
11
+ const sorted = [...values].sort((a, b) => a - b);
12
+ const rank = Math.ceil((p / 100) * sorted.length);
13
+ return sorted[Math.min(sorted.length, Math.max(1, rank)) - 1];
14
+ }
15
+ export function finiteValues(series) {
16
+ return (series?.datasets ?? []).filter((x) => typeof x === 'number' && Number.isFinite(x));
17
+ }
18
+ /**
19
+ * Latest, average, p95 and peak of one series, plus anomaly flags an agent can
20
+ * act on without reading the raw samples:
21
+ * - spikes: samples above mean + 3 standard deviations (at least 8 samples);
22
+ * - rising: the last quarter averages 25 % above the first quarter (a leak or
23
+ * growing load; at least 8 samples, and only for a series that is not ~0);
24
+ * - nonzero: the share of samples above zero, for throttling.
25
+ * Units are the API's; the flags are relative, so they need no units.
26
+ */
27
+ export function analyzeSeries(series, opts = {}) {
28
+ const values = finiteValues(series);
29
+ if (values.length === 0)
30
+ return undefined;
31
+ const n = values.length;
32
+ const mean = values.reduce((a, b) => a + b, 0) / n;
33
+ const peak = Math.max(...values);
34
+ const anomalies = [];
35
+ if (n >= 8) {
36
+ const sd = Math.sqrt(values.reduce((a, b) => a + (b - mean) ** 2, 0) / n);
37
+ if (sd > 0) {
38
+ const limit = mean + 3 * sd;
39
+ const idx = values.flatMap((v, i) => (v > limit ? [i] : []));
40
+ if (idx.length) {
41
+ const at = series?.timestamps?.[idx[0]];
42
+ anomalies.push(`${idx.length} spike${idx.length === 1 ? '' : 's'} above ${round(limit)} (mean + 3 sd)` +
43
+ (at ? `, first at ${at}` : ''));
44
+ }
45
+ }
46
+ const q = Math.max(2, Math.floor(n / 4));
47
+ const first = values.slice(0, q).reduce((a, b) => a + b, 0) / q;
48
+ const last = values.slice(-q).reduce((a, b) => a + b, 0) / q;
49
+ if (first > 0 && peak > 0 && last > first * 1.25) {
50
+ anomalies.push(`rising: last quarter averages ${Math.round((last / first - 1) * 100)} % above the first quarter`);
51
+ }
52
+ }
53
+ let nonzeroShare;
54
+ if (opts.nonzero) {
55
+ nonzeroShare = round(values.filter((v) => v > 0).length / n);
56
+ if (nonzeroShare > 0)
57
+ anomalies.push(`above zero in ${Math.round(nonzeroShare * 100)} % of samples`);
58
+ }
59
+ return {
60
+ latest: round(values[n - 1]),
61
+ average: round(mean),
62
+ p95: round(percentile(values, 95)),
63
+ peak: round(peak),
64
+ samples: n,
65
+ ...(nonzeroShare !== undefined ? { nonzero_share: nonzeroShare } : {}),
66
+ ...(anomalies.length ? { anomalies } : {}),
67
+ labels: series?.labels?.length ? [...new Set(series.labels)].slice(0, 5) : undefined,
68
+ from: series?.timestamps?.[0],
69
+ to: series?.timestamps?.[series.timestamps.length - 1],
70
+ };
71
+ }
72
+ /** Runs fn over items with at most `limit` in flight; keeps input order. */
73
+ export async function mapLimit(items, limit, fn) {
74
+ const out = new Array(items.length);
75
+ let next = 0;
76
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
77
+ while (next < items.length) {
78
+ const i = next++;
79
+ out[i] = await fn(items[i]);
80
+ }
81
+ });
82
+ await Promise.all(workers);
83
+ return out;
84
+ }
85
+ /**
86
+ * A log line with the parts that differ between occurrences of the same error
87
+ * replaced (timestamps, hex ids, numbers, quoted strings, IPs), so matches can
88
+ * be grouped by what went wrong rather than when or where.
89
+ */
90
+ export function logSignature(line) {
91
+ return line
92
+ .replace(/\d{4}-\d{2}-\d{2}[T ][\d:.,]+Z?/g, '<time>')
93
+ .replace(/\b\d{1,2}:\d{2}:\d{2}(?:[.,]\d+)?\b/g, '<time>')
94
+ .replace(/\b\d{1,3}(?:\.\d{1,3}){3}(?::\d+)?\b/g, '<ip>')
95
+ .replace(/\b0x[0-9a-f]+\b/gi, '<hex>')
96
+ .replace(/\b[0-9a-f]{8,}\b/gi, '<id>')
97
+ .replace(/"[^"]{0,200}"/g, '"…"')
98
+ // Not word-bounded: "30s" and "31s" are the same timeout.
99
+ .replace(/\d+(?:\.\d+)?/g, '<n>')
100
+ .replace(/\s+/g, ' ')
101
+ .trim()
102
+ .slice(0, 200);
103
+ }
104
+ /** Groups matching lines from several deployments by signature, most frequent first. */
105
+ export function groupLogMatches(matches, maxGroups) {
106
+ const groups = new Map();
107
+ for (const m of matches) {
108
+ const sig = logSignature(m.line);
109
+ const g = groups.get(sig) ?? { signature: sig, count: 0, deployments: [], example: m.line.slice(0, 300) };
110
+ g.count++;
111
+ if (!g.deployments.includes(m.request_id))
112
+ g.deployments.push(m.request_id);
113
+ groups.set(sig, g);
114
+ }
115
+ return [...groups.values()].sort((a, b) => b.count - a.count || b.deployments.length - a.deployments.length).slice(0, maxGroups);
116
+ }
117
+ /**
118
+ * A line matcher from an agent-supplied pattern. Plain text matches as a
119
+ * case-insensitive substring. A regex is opt-in, length-capped, and rejected
120
+ * when it nests quantifiers (the usual catastrophic-backtracking shape), since
121
+ * the hosted server runs it on someone else's logs inside a request budget.
122
+ */
123
+ export function lineMatcher(pattern, regex) {
124
+ if (!pattern || pattern.length > 200)
125
+ return { error: 'pattern must be 1-200 characters.' };
126
+ if (!regex) {
127
+ const needle = pattern.toLowerCase();
128
+ return { test: (line) => line.toLowerCase().includes(needle) };
129
+ }
130
+ if (/\([^)]*[+*][^)]*\)[+*{]/.test(pattern)) {
131
+ return { error: 'Nested quantifiers like (a+)+ are refused. Simplify the regex, or search for plain text.' };
132
+ }
133
+ try {
134
+ const re = new RegExp(pattern, 'i');
135
+ return { test: (line) => re.test(line.slice(0, 2000)) };
136
+ }
137
+ catch (err) {
138
+ return { error: `Invalid regex: ${err.message}` };
139
+ }
140
+ }
141
+ /** Default lines that look like a crash or error, for a search with no pattern. */
142
+ export const ERROR_PATTERN = '(error|exception|fatal|panic|segmentation fault|sigsegv|sigabrt|core dumped|unhandled|stack ?trace|assert(ion)? failed|out of memory|oom|killed)';
package/dist/outputs.js CHANGED
@@ -47,7 +47,7 @@ const deployment = {
47
47
  ports: list({ name: str, connect: str, external: num, internal: num, protocol: str }),
48
48
  next_step: str,
49
49
  };
50
- const series = obj({ latest: num, average: num, peak: num, samples: num, labels: strs, from: str, to: str });
50
+ const series = obj({ latest: num, average: num, p95: num, peak: num, samples: num, nonzero_share: num, anomalies: strs, labels: strs, from: str, to: str });
51
51
  /** Loose at the top level too: a raw shape becomes additionalProperties: false
52
52
  * in JSON Schema, and clients that validate results reject extra fields. */
53
53
  const out = (shape) => z.looseObject(shape);
package/dist/tools.js CHANGED
@@ -18,6 +18,7 @@ import { generateDockerfile, DockerfileInputError } from './dockerfile.js';
18
18
  import { buildMatchmakerConfig, DASHBOARD_URL } from './matchmaker.js';
19
19
  import { badImage, badTag, ENCRYPTED_PLACEHOLDER, isEncryptedPlaceholder, looksSecret, TAG_FIX } from './image.js';
20
20
  import { OUTPUT } from './outputs.js';
21
+ import { analyzeSeries, finiteValues, percentile, mapLimit, groupLogMatches, lineMatcher, ERROR_PATTERN } from './ops.js';
21
22
  import { finishReport, codeForStatus } from './callreport.js';
22
23
  import { SKILLS_PACK, findSkill, findSkillFile, fileIndex, mimeType, skillUri } from './skills.js';
23
24
  import { SKILLS_CLI, SKILL_NAME_RE, compareVersions, latestPack, latestSkillVersions, servedPackStatus, skillsCheckFromEnv, } from './skillsversion.js';
@@ -554,6 +555,27 @@ const dryRunParam = z
554
555
  .optional()
555
556
  .describe('Show the exact request (method, host, path, body) with secrets masked, and send nothing. ' +
556
557
  'Local checks still run. Use it to confirm a billable or destructive call before making it.');
558
+ /**
559
+ * The confirm parameter of the destructive tools. Without it they send nothing
560
+ * and return a preview, so an agent has to show the developer what it is about
561
+ * to stop or delete before doing it. Stopping a deployment this server started
562
+ * (tagged edgegap-mcp) needs no confirm: that is the cleanup every task ends with.
563
+ */
564
+ const confirmParam = z
565
+ .boolean()
566
+ .optional()
567
+ .describe('Set true only after the developer approved this exact call. Without it nothing is sent: the result ' +
568
+ 'previews what would be stopped or deleted (status "confirmation_required").');
569
+ function confirmationRequired(action, preview) {
570
+ return withMeta(ok({
571
+ status: 'confirmation_required',
572
+ sent: false,
573
+ action,
574
+ ...preview,
575
+ next_step: 'Nothing was changed. Show this to the developer and ask; if they approve, call again with the same ' +
576
+ 'arguments plus confirm: true.',
577
+ }), { props: { result_state: 'confirmation_required' } });
578
+ }
557
579
  function dryRunResult(requests, notes = []) {
558
580
  return ok({
559
581
  dry_run: true,
@@ -829,7 +851,11 @@ export function registerTools(server, client, config, auth, options = {}) {
829
851
  secret_env: 'env vars named like secrets (TOKEN, SECRET, PASSWORD, API_KEY...) are sent hidden',
830
852
  stop: config.stopOwnOnly
831
853
  ? `one exact request_id per call; no bulk stop; only deployments tagged "${AGENT_TAG}" (EDGEGAP_STOP_OWN_ONLY)`
832
- : 'one exact request_id per call; no bulk stop',
854
+ : `one exact request_id per call; no bulk stop; a running deployment without the "${AGENT_TAG}" tag needs confirm: true`,
855
+ confirm: 'stop (of a deployment this server did not start), delete_app, delete_app_version and delete_registry_tag send nothing without confirm: true and return a preview instead',
856
+ ...(config.appAllowlist.length
857
+ ? { allowlist: 'create, change, delete and deploy in listed applications only; stop, tag and report only deployments of listed applications; reads are not limited' }
858
+ : {}),
833
859
  auto_stop: 'each deploy reports its version\'s max_duration; Edgegap has no per-deployment time limit',
834
860
  long_running: `deploying a version whose max_duration is unlimited or above ${config.maxDurationCeiling} minutes needs allow_long_running: true`,
835
861
  deletes: 'one exact app or version per call; refused while its deployments run; an app with versions needs max_versions',
@@ -1881,25 +1907,54 @@ export function registerTools(server, client, config, auth, options = {}) {
1881
1907
  description: 'Gracefully stop one deployment by request_id, sending SIGTERM to the container. ' +
1882
1908
  'Stop every deployment you started for testing before ending your task. This tool ' +
1883
1909
  'stops exactly one deployment, named by its exact request_id: empty IDs, wildcards ' +
1884
- 'and lists are refused, and bulk stop is deliberately not exposed.',
1910
+ 'and lists are refused, and bulk stop is deliberately not exposed. A deployment this server ' +
1911
+ `started (tagged "${AGENT_TAG}") stops right away; any other running deployment may be serving ` +
1912
+ 'players, so without confirm: true the result only previews it and nothing is sent.',
1885
1913
  inputSchema: {
1886
1914
  request_id: z.string().describe('The exact request_id of the one deployment to stop, e.g. "61b1be8f54d9".'),
1915
+ confirm: confirmParam,
1887
1916
  dry_run: dryRunParam,
1888
1917
  },
1889
1918
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
1890
- }, async ({ request_id, dry_run }) => guarded(auth, NOT_FOUND.deployment, async () => {
1919
+ }, async ({ request_id, confirm, dry_run }) => guarded(auth, NOT_FOUND.deployment, async () => {
1891
1920
  const bad = checkRequestId(request_id);
1892
1921
  if (bad)
1893
1922
  return bad;
1923
+ if (!dry_run) {
1924
+ const blocked = await deploymentOutsideAllowlist(request_id);
1925
+ if (blocked)
1926
+ return blocked;
1927
+ }
1928
+ const isOwn = () => client
1929
+ .listDeploymentTags(request_id)
1930
+ .then((r) => (r.tags ?? []).some((t) => t.name === AGENT_TAG || t.name === 'mcp'));
1894
1931
  if (config.stopOwnOnly && !dry_run) {
1895
- const own = await client
1896
- .listDeploymentTags(request_id)
1897
- .then((r) => (r.tags ?? []).some((t) => t.name === AGENT_TAG || t.name === 'mcp'));
1898
- if (!own) {
1932
+ if (!(await isOwn())) {
1899
1933
  return fail(`Refused: deployment ${request_id} has no "${AGENT_TAG}" tag, so this server did not start it, and ` +
1900
1934
  'EDGEGAP_STOP_OWN_ONLY is on. Nothing was sent. Ask the developer to stop it from the dashboard.');
1901
1935
  }
1902
1936
  }
1937
+ else if (!dry_run && confirm !== true && !(await isOwn().catch(() => false))) {
1938
+ // Not started by an agent: preview it if it is still running. One
1939
+ // that is gone or already stopping goes on to the idempotent path.
1940
+ const s = await client.getDeployment(request_id).catch(() => undefined);
1941
+ if (s && s.running && !(s.current_status ?? '').toUpperCase().includes('TERMINAT')) {
1942
+ const c = compactDeployment(s);
1943
+ return confirmationRequired('stop deployment', {
1944
+ deployment: {
1945
+ request_id,
1946
+ status: c.status,
1947
+ application: c.application,
1948
+ version: c.version,
1949
+ location: c.location,
1950
+ fqdn: c.fqdn,
1951
+ running_for_seconds: c.elapsed_seconds,
1952
+ tags: s.tags,
1953
+ },
1954
+ warning: `Not started through this server (no "${AGENT_TAG}" tag): it may be serving players, and stopping it ends their match.`,
1955
+ });
1956
+ }
1957
+ }
1903
1958
  if (dry_run) {
1904
1959
  const dry = client.dryRun();
1905
1960
  await dry.client.stopDeployment(request_id);
@@ -1969,9 +2024,11 @@ export function registerTools(server, client, config, auth, options = {}) {
1969
2024
  tool('edgegap_get_deployment_metrics', {
1970
2025
  title: 'Get CPU, memory and network use of a deployment',
1971
2026
  description: 'Summarise a deployment\'s resource use over time: CPU, CPU throttling, memory and network, ' +
1972
- 'each as latest, average and peak, with the API\'s own labels. Use it to size a version ' +
1973
- '(cpu_units, memory_mb) from a real match, or to check whether a crash was memory or CPU ' +
1974
- 'starvation before redeploying. Defaults to the whole life of the deployment.',
2027
+ 'each as latest, average, p95 and peak, with the API\'s own labels, plus anomaly flags ' +
2028
+ '(spikes above mean + 3 sd, a rising trend such as a memory leak, any CPU throttling) collected ' +
2029
+ 'in `anomalies`. Use it to size a version (cpu_units, memory_mb) from a real match, or to check ' +
2030
+ 'whether a crash was memory or CPU starvation before redeploying. Defaults to the whole life of ' +
2031
+ 'the deployment. To compare two versions, use edgegap_compare_versions.',
1975
2032
  inputSchema: {
1976
2033
  request_id: z.string().describe('The request_id of the deployment.'),
1977
2034
  start_time: z.string().optional().describe('ISO 8601. Default: when the deployment started.'),
@@ -1985,13 +2042,18 @@ export function registerTools(server, client, config, auth, options = {}) {
1985
2042
  if (bad)
1986
2043
  return bad;
1987
2044
  const m = await client.getDeploymentMetrics(request_id, { start_time, end_time, steps: step });
1988
- return ok({
2045
+ const series = {
2046
+ cpu: analyzeSeries(m.cpu),
2047
+ cpu_throttle_rate: analyzeSeries(m.cpu_throttle_rate, { nonzero: true }),
2048
+ memory: analyzeSeries(m.mem),
2049
+ network_receive: analyzeSeries(m.network?.receive),
2050
+ network_transmit: analyzeSeries(m.network?.transmit),
2051
+ };
2052
+ const anomalies = Object.entries(series).flatMap(([name, s]) => (s?.anomalies ?? []).map((a) => `${name}: ${a}`));
2053
+ return withMeta(ok({
1989
2054
  request_id,
1990
- cpu: summarizeSeries(m.cpu),
1991
- cpu_throttle_rate: summarizeSeries(m.cpu_throttle_rate),
1992
- memory: summarizeSeries(m.mem),
1993
- network_receive: summarizeSeries(m.network?.receive),
1994
- network_transmit: summarizeSeries(m.network?.transmit),
2055
+ ...series,
2056
+ anomalies: anomalies.length ? anomalies : 'none found',
1995
2057
  totals: m.total
1996
2058
  ? {
1997
2059
  received: summarizeSeries(m.total.receive_total)?.latest,
@@ -2000,8 +2062,310 @@ export function registerTools(server, client, config, auth, options = {}) {
2000
2062
  disk_written: summarizeSeries(m.total.disk_write_total)?.latest,
2001
2063
  }
2002
2064
  : undefined,
2003
- note: 'Units are as the API labels them; values are averaged per step.',
2065
+ note: 'Units are as the API labels them; values are averaged per step. p95 is over the steps.',
2066
+ }), { props: { anomaly_count: anomalies.length } });
2067
+ }));
2068
+ // ================================================== operating live games ====
2069
+ // Read-only views across many deployments. The hosted Worker makes one API
2070
+ // call per deployment read, inside a per-request subrequest budget, so it
2071
+ // inspects fewer deployments per call than the local server.
2072
+ const hosted = config.transport === 'hosted';
2073
+ const OPS_CAP = hosted ? 20 : 100;
2074
+ const COMPARE_CAP = hosted ? 6 : 20;
2075
+ /** Running deployments of an application (and version), newest first, at most `limit`. */
2076
+ async function runningDeployments(application, version, limit, startedAfter) {
2077
+ const filters = [];
2078
+ if (application)
2079
+ filters.push({ field: 'application', operator: 'eq', value: application });
2080
+ if (version)
2081
+ filters.push({ field: 'version', operator: 'eq', value: version });
2082
+ if (startedAfter)
2083
+ filters.push({ field: 'created_at', operator: 'gte', value: startedAfter });
2084
+ const query = JSON.stringify({ filters, order_by: [{ field: 'created_at', order: 'desc' }] });
2085
+ const res = await client.listDeployments({ query, limit });
2086
+ const rows = (res.data ?? []).filter((d) => d.request_id);
2087
+ return { rows, total: res.total_count ?? rows.length };
2088
+ }
2089
+ /** Crash facts of one deployment from its logs endpoint; never throws. */
2090
+ async function crashFacts(requestId) {
2091
+ try {
2092
+ const l = await client.getDeploymentLogs(requestId);
2093
+ return {
2094
+ restarts: l.crash_data?.restart_count ?? 0,
2095
+ exit_code: l.crash_data?.exit_code,
2096
+ crash_message: l.crash_data?.message || undefined,
2097
+ logs: [l.logs, l.crash_logs].filter(Boolean).join('\n'),
2098
+ };
2099
+ }
2100
+ catch {
2101
+ return undefined;
2102
+ }
2103
+ }
2104
+ function healthOf(s) {
2105
+ if (!s)
2106
+ return 'unknown';
2107
+ const st = (s.current_status ?? '').toUpperCase();
2108
+ if (s.error || st.includes('ERROR'))
2109
+ return 'error';
2110
+ if (st.includes('TERMINAT'))
2111
+ return 'terminating';
2112
+ if (st.includes('READY'))
2113
+ return 'ready';
2114
+ return 'pending';
2115
+ }
2116
+ const where = (s) => s?.location ? [s.location.city, s.location.country].filter(Boolean).join(', ') || 'unknown' : 'unknown';
2117
+ const scopeOf = (application, version) => application ? `${application}${version ? ` / ${version}` : ''}` : 'all applications';
2118
+ tool('edgegap_fleet_health', {
2119
+ title: 'Summarise the health of running deployments',
2120
+ description: 'One call for "is anything wrong right now?" across running deployments, instead of checking them one ' +
2121
+ 'by one: counts by status, the deployments in error with their error detail, ones stuck starting for ' +
2122
+ 'over 10 minutes, and totals per location and per version with unhealthy ones flagged. ' +
2123
+ 'check_crashes: true also reads each deployment\'s crash data (restarts, exit codes). Covers what ' +
2124
+ 'Edgegap still lists: stopped deployments are gone, so this is current state, not history. ' +
2125
+ `Inspects up to ${OPS_CAP} deployments per call, newest first. Read-only. Next: ` +
2126
+ 'edgegap_search_deployment_logs for what the errors say, edgegap_compare_versions for a rollback decision.',
2127
+ inputSchema: {
2128
+ application: z.string().optional().describe('Only this application. Default: all.'),
2129
+ version: z.string().optional().describe('Only this version (needs application).'),
2130
+ max_deployments: z.number().int().optional().describe(`How many to inspect, 1-${OPS_CAP}. Default ${Math.min(50, OPS_CAP)}.`),
2131
+ check_crashes: z.boolean().optional().describe('Also read crash data (restart count, exit code) per deployment. Default false.'),
2132
+ },
2133
+ annotations: { readOnlyHint: true, openWorldHint: true },
2134
+ }, async ({ application, version, max_deployments, check_crashes }) => guarded(auth, NOT_FOUND.app, async () => {
2135
+ if (version && !application)
2136
+ return fail('version needs application too.');
2137
+ const cap = clamp(max_deployments, 1, OPS_CAP, Math.min(50, OPS_CAP));
2138
+ const { rows, total } = await runningDeployments(application, version, cap);
2139
+ if (rows.length === 0) {
2140
+ return emptyState('empty', { scope: scopeOf(application, version), total: 0 }, 'No deployments are running here, so there is nothing to be unhealthy. Start one with edgegap_deploy.');
2141
+ }
2142
+ const inspected = await mapLimit(rows, 8, async (r) => {
2143
+ const status = await client.getDeployment(r.request_id).catch(() => undefined);
2144
+ const crash = check_crashes ? await crashFacts(r.request_id) : undefined;
2145
+ return { id: r.request_id, status, crash, health: healthOf(status) };
2004
2146
  });
2147
+ const byStatus = {};
2148
+ const errors = [];
2149
+ const stuck = [];
2150
+ const crashes = [];
2151
+ const locs = new Map();
2152
+ const vers = new Map();
2153
+ const bump = (m, k) => {
2154
+ const b = m.get(k) ?? { total: 0, ready: 0, error: 0, pending: 0, restarts: 0 };
2155
+ m.set(k, b);
2156
+ return b;
2157
+ };
2158
+ for (const d of inspected) {
2159
+ byStatus[d.health] = (byStatus[d.health] ?? 0) + 1;
2160
+ const s = d.status;
2161
+ const ver = s ? `${s.app_name} / ${s.app_version}` : 'unknown';
2162
+ for (const b of [bump(locs, where(s)), bump(vers, ver)]) {
2163
+ b.total++;
2164
+ if (d.health === 'ready')
2165
+ b.ready++;
2166
+ if (d.health === 'error')
2167
+ b.error++;
2168
+ if (d.health === 'pending')
2169
+ b.pending++;
2170
+ b.restarts += d.crash?.restarts ?? 0;
2171
+ }
2172
+ if (d.health === 'error') {
2173
+ errors.push({ request_id: d.id, version: ver, location: where(s), detail: s?.error_detail || s?.current_status });
2174
+ }
2175
+ if (d.health === 'pending' && (s?.elapsed_time ?? 0) > 600) {
2176
+ stuck.push({ request_id: d.id, version: ver, location: where(s), status: s?.current_status, elapsed_seconds: s?.elapsed_time });
2177
+ }
2178
+ if (d.crash && (d.crash.restarts > 0 || d.crash.exit_code !== undefined)) {
2179
+ crashes.push({ request_id: d.id, version: ver, restarts: d.crash.restarts, exit_code: d.crash.exit_code, message: d.crash.crash_message });
2180
+ }
2181
+ }
2182
+ const table = (m, key) => [...m.entries()]
2183
+ .map(([k, b]) => ({
2184
+ [key]: k,
2185
+ ...b,
2186
+ error_rate: Math.round((b.error / b.total) * 100) / 100,
2187
+ ...(b.error > 0 || b.restarts > 0 ? { unhealthy: true } : {}),
2188
+ }))
2189
+ .sort((a, b) => b.error - a.error || b.restarts - a.restarts || b.total - a.total);
2190
+ const byLocation = table(locs, 'location');
2191
+ const byVersion = table(vers, 'version');
2192
+ const unhealthyLocations = byLocation.filter((l) => l.unhealthy).map((l) => l.location);
2193
+ const problems = errors.length + stuck.length + crashes.length;
2194
+ return withMeta(ok({
2195
+ scope: scopeOf(application, version),
2196
+ verdict: problems === 0
2197
+ ? `healthy: ${inspected.length} deployment${inspected.length === 1 ? '' : 's'} inspected, none in error${check_crashes ? ' or restarting' : ''}`
2198
+ : `${errors.length} in error, ${stuck.length} stuck starting${check_crashes ? `, ${crashes.length} restarted or crashed` : ''}, out of ${inspected.length} inspected`,
2199
+ running: total,
2200
+ inspected: inspected.length,
2201
+ ...(total > inspected.length ? { not_inspected: total - inspected.length, note: `Only the ${inspected.length} newest were inspected. Narrow by application or version, or raise max_deployments (max ${OPS_CAP}).` } : {}),
2202
+ by_status: byStatus,
2203
+ errors: errors.length ? errors : undefined,
2204
+ stuck_starting: stuck.length ? stuck : undefined,
2205
+ crashes: check_crashes ? (crashes.length ? crashes : 'none') : undefined,
2206
+ unhealthy_locations: unhealthyLocations.length ? unhealthyLocations : undefined,
2207
+ by_location: byLocation,
2208
+ by_version: byVersion,
2209
+ next_step: problems
2210
+ ? 'Read what failed with edgegap_search_deployment_logs (same application/version) or edgegap_get_deployment_logs for one request_id.'
2211
+ : check_crashes ? undefined : 'Pass check_crashes: true to also catch servers that restarted after a crash.',
2212
+ }), { props: { item_count: inspected.length, error_count: errors.length, check_crashes: check_crashes === true } });
2213
+ }));
2214
+ tool('edgegap_search_deployment_logs', {
2215
+ title: 'Search the logs of many deployments at once',
2216
+ description: 'Search the container and crash logs of running deployments of an application (and version) for a ' +
2217
+ 'pattern, and group the matching lines by error, with counts and which deployments printed them: ' +
2218
+ '"every crash in version 1.4.2 since yesterday, grouped by error". Without a pattern it looks for ' +
2219
+ 'errors, exceptions, fatal signals and out-of-memory kills. Also counts crash exit codes. Logs only ' +
2220
+ 'exist while a deployment runs (or in Endpoint Storage), so stopped deployments are not searched. ' +
2221
+ `Searches up to ${OPS_CAP} deployments per call, newest first. Read-only.`,
2222
+ inputSchema: {
2223
+ application: z.string().optional().describe('Only this application. Default: all.'),
2224
+ version: z.string().optional().describe('Only this version (needs application).'),
2225
+ pattern: z.string().optional().describe('Text to find, case-insensitive. Default: common error and crash words.'),
2226
+ regex: z.boolean().optional().describe('Treat pattern as a regular expression. Default false.'),
2227
+ started_after: z.string().optional().describe('Only deployments started after this ISO 8601 time, e.g. "2026-11-12T00:00:00Z" for the last day.'),
2228
+ max_deployments: z.number().int().optional().describe(`How many to search, 1-${OPS_CAP}. Default ${Math.min(30, OPS_CAP)}.`),
2229
+ max_groups: z.number().int().optional().describe('Most error groups to return, 1-50. Default 15.'),
2230
+ },
2231
+ annotations: { readOnlyHint: true, openWorldHint: true },
2232
+ }, async ({ application, version, pattern, regex, started_after, max_deployments, max_groups }) => guarded(auth, NOT_FOUND.app, async () => {
2233
+ if (version && !application)
2234
+ return fail('version needs application too.');
2235
+ if (started_after && Number.isNaN(Date.parse(started_after))) {
2236
+ return fail(`started_after "${started_after.slice(0, 40)}" is not an ISO 8601 time, e.g. "2026-11-12T00:00:00Z".`);
2237
+ }
2238
+ const matcher = pattern ? lineMatcher(pattern, regex === true) : lineMatcher(ERROR_PATTERN, true);
2239
+ if ('error' in matcher)
2240
+ return fail(matcher.error);
2241
+ const cap = clamp(max_deployments, 1, OPS_CAP, Math.min(30, OPS_CAP));
2242
+ const { rows, total } = await runningDeployments(application, version, cap, started_after);
2243
+ if (rows.length === 0) {
2244
+ return emptyState('empty', { scope: scopeOf(application, version), searched: 0 }, 'No running deployment matches, so there are no logs to search. Logs of stopped deployments only exist in Endpoint Storage, if it was set on the version.');
2245
+ }
2246
+ const read = await mapLimit(rows, 8, async (r) => ({ id: r.request_id, crash: await crashFacts(r.request_id) }));
2247
+ const matches = [];
2248
+ const exitCodes = {};
2249
+ const noLogs = [];
2250
+ let matchedDeployments = 0;
2251
+ for (const d of read) {
2252
+ if (!d.crash) {
2253
+ noLogs.push(d.id);
2254
+ continue;
2255
+ }
2256
+ if (d.crash.exit_code !== undefined)
2257
+ exitCodes[String(d.crash.exit_code)] = (exitCodes[String(d.crash.exit_code)] ?? 0) + 1;
2258
+ // The tail is enough: a crash is at the end, and a 1 MB log must not
2259
+ // stall the request.
2260
+ const lines = d.crash.logs.slice(-200_000).split('\n');
2261
+ let hit = false;
2262
+ for (const line of lines) {
2263
+ if (line.trim() && matcher.test(line)) {
2264
+ matches.push({ request_id: d.id, line: line.trim() });
2265
+ hit = true;
2266
+ }
2267
+ }
2268
+ if (hit)
2269
+ matchedDeployments++;
2270
+ }
2271
+ const groups = groupLogMatches(matches, clamp(max_groups, 1, 50, 15));
2272
+ return withMeta(ok({
2273
+ scope: scopeOf(application, version),
2274
+ pattern: pattern ?? 'default: errors, exceptions, fatal signals, out of memory',
2275
+ running: total,
2276
+ searched: read.length - noLogs.length,
2277
+ ...(total > rows.length ? { not_searched: total - rows.length, note: `Only the ${rows.length} newest were searched. Narrow with version or started_after, or raise max_deployments (max ${OPS_CAP}).` } : {}),
2278
+ deployments_with_matches: matchedDeployments,
2279
+ matching_lines: matches.length,
2280
+ groups: groups.length ? groups : undefined,
2281
+ exit_codes: Object.keys(exitCodes).length ? exitCodes : undefined,
2282
+ no_logs: noLogs.length ? noLogs : undefined,
2283
+ next_step: groups.length
2284
+ ? 'Read the full log of one deployment in the top group with edgegap_get_deployment_logs before changing code.'
2285
+ : 'Nothing matched. Try another pattern, or check edgegap_fleet_health for deployments in error.',
2286
+ }), { props: { item_count: read.length, group_count: groups.length, regex: regex === true } });
2287
+ }));
2288
+ tool('edgegap_compare_versions', {
2289
+ title: 'Compare two versions of an application',
2290
+ description: 'Compare two versions of one application from their running deployments, to back a rollback or ' +
2291
+ 'promote decision: deployments in error, crash restarts and exit codes, and CPU and memory (average, ' +
2292
+ 'p95, peak) against each version\'s requested cpu_units and memory_mb, with the differences spelled ' +
2293
+ `out. Reads up to ${COMPARE_CAP} running deployments per version, newest first, so both versions need ` +
2294
+ 'deployments running now (stopped ones keep no logs or status). Read-only.',
2295
+ inputSchema: {
2296
+ application: z.string().describe('Application name.'),
2297
+ version_a: z.string().describe('The baseline version, e.g. the one in production.'),
2298
+ version_b: z.string().describe('The version to compare against it, e.g. the new build.'),
2299
+ max_deployments_per_version: z.number().int().optional().describe(`1-${COMPARE_CAP}. Default ${Math.min(5, COMPARE_CAP)}.`),
2300
+ },
2301
+ annotations: { readOnlyHint: true, openWorldHint: true },
2302
+ }, async ({ application, version_a, version_b, max_deployments_per_version }) => guarded(auth, NOT_FOUND.app, async () => {
2303
+ if (version_a === version_b)
2304
+ return fail('version_a and version_b are the same. Pass two different versions.');
2305
+ const cap = clamp(max_deployments_per_version, 1, COMPARE_CAP, Math.min(5, COMPARE_CAP));
2306
+ const one = async (version) => {
2307
+ const settings = await client.getAppVersion(application, version);
2308
+ const { rows, total } = await runningDeployments(application, version, cap);
2309
+ const deps = await mapLimit(rows, 6, async (r) => {
2310
+ const [status, crash, metrics] = await Promise.all([
2311
+ client.getDeployment(r.request_id).catch(() => undefined),
2312
+ crashFacts(r.request_id),
2313
+ client.getDeploymentMetrics(r.request_id).catch(() => undefined),
2314
+ ]);
2315
+ return { status, crash, metrics };
2316
+ });
2317
+ const pool = (pick) => {
2318
+ const all = deps.flatMap((d) => (d.metrics ? finiteValues(pick(d.metrics)) : []));
2319
+ if (!all.length)
2320
+ return undefined;
2321
+ const r2 = (x) => Math.round(x * 100) / 100;
2322
+ return { average: r2(all.reduce((a, b) => a + b, 0) / all.length), p95: r2(percentile(all, 95)), peak: r2(Math.max(...all)), samples: all.length };
2323
+ };
2324
+ const errors = deps.filter((d) => healthOf(d.status) === 'error').length;
2325
+ const exitCodes = [...new Set(deps.map((d) => d.crash?.exit_code).filter((x) => x !== undefined))];
2326
+ return {
2327
+ version,
2328
+ requested: { cpu_units: settings.req_cpu, memory_mb: settings.req_memory },
2329
+ running: total,
2330
+ inspected: deps.length,
2331
+ in_error: errors,
2332
+ error_rate: deps.length ? Math.round((errors / deps.length) * 100) / 100 : undefined,
2333
+ restarts: deps.reduce((a, d) => a + (d.crash?.restarts ?? 0), 0),
2334
+ deployments_restarted: deps.filter((d) => (d.crash?.restarts ?? 0) > 0).length,
2335
+ exit_codes: exitCodes.length ? exitCodes : undefined,
2336
+ cpu: pool((m) => m.cpu),
2337
+ cpu_throttle_rate: pool((m) => m.cpu_throttle_rate),
2338
+ memory: pool((m) => m.mem),
2339
+ labels: deps.find((d) => d.metrics?.mem?.labels?.length)?.metrics?.mem?.labels?.slice(0, 3),
2340
+ };
2341
+ };
2342
+ const [a, b] = await Promise.all([one(version_a), one(version_b)]);
2343
+ const diff = [];
2344
+ const pct = (x, y) => (y === 0 ? undefined : Math.round(((x - y) / y) * 100));
2345
+ for (const k of ['cpu', 'memory']) {
2346
+ const pa = a[k]?.p95, pb = b[k]?.p95;
2347
+ if (pa !== undefined && pb !== undefined) {
2348
+ const d = pct(pb, pa);
2349
+ if (d !== undefined && Math.abs(d) >= 10)
2350
+ diff.push(`${k} p95 is ${Math.abs(d)} % ${d > 0 ? 'higher' : 'lower'} in ${version_b} (${pb} vs ${pa})`);
2351
+ }
2352
+ }
2353
+ if ((a.error_rate ?? 0) !== (b.error_rate ?? 0))
2354
+ diff.push(`error rate ${b.error_rate ?? 0} in ${version_b} vs ${a.error_rate ?? 0} in ${version_a}`);
2355
+ if (a.restarts !== b.restarts)
2356
+ diff.push(`${b.restarts} crash restarts in ${version_b} vs ${a.restarts} in ${version_a}`);
2357
+ if ((b.cpu_throttle_rate?.peak ?? 0) > 0 && (a.cpu_throttle_rate?.peak ?? 0) === 0)
2358
+ diff.push(`${version_b} is CPU-throttled, ${version_a} is not`);
2359
+ const missing = [a, b].filter((v) => v.inspected === 0).map((v) => v.version);
2360
+ return withMeta(ok({
2361
+ application,
2362
+ a,
2363
+ b,
2364
+ differences: diff.length ? diff : missing.length ? undefined : ['no difference of 10 % or more, and the same error and restart counts'],
2365
+ ...(missing.length
2366
+ ? { note: `No running deployment of ${missing.join(' and ')}: nothing to compare for ${missing.length === 2 ? 'either' : 'it'}. Deploy one (edgegap_deploy) and let it serve a match first.` }
2367
+ : { caveat: `Based on ${a.inspected} and ${b.inspected} running deployments; a handful of servers under different load is a signal, not proof.` }),
2368
+ }), { props: { item_count: a.inspected + b.inspected } });
2005
2369
  }));
2006
2370
  // ============================================= before the first deploy ====
2007
2371
  // -------------------------------------------------------------- 11a ----
@@ -2350,14 +2714,15 @@ export function registerTools(server, client, config, auth, options = {}) {
2350
2714
  'registry, to clean up old builds. Takes exactly one image name and one exact tag; ' +
2351
2715
  'wildcards, lists and "latest" are refused, and there is no bulk delete. A version that ' +
2352
2716
  'still uses the tag can no longer start deployments, so check edgegap_list_app_versions ' +
2353
- 'first. Cannot be undone.',
2717
+ 'first. Cannot be undone, so without confirm: true the result only previews it and nothing is sent.',
2354
2718
  inputSchema: {
2355
2719
  image_name: z.string().min(1).describe('The image name only, e.g. "my-game-server", as for edgegap_list_registry_tags.'),
2356
2720
  tag: z.string().describe('The exact tag to delete, e.g. "build-41".'),
2721
+ confirm: confirmParam,
2357
2722
  dry_run: dryRunParam,
2358
2723
  },
2359
2724
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
2360
- }, async ({ image_name, tag, dry_run }) => guard(auth, async () => {
2725
+ }, async ({ image_name, tag, confirm, dry_run }) => guard(auth, async () => {
2361
2726
  let name = imageNameOnly(image_name);
2362
2727
  if (!/^[a-z0-9][a-z0-9._\/-]{0,254}$/.test(name)) {
2363
2728
  return fail(`"${image_name.slice(0, 80)}" is not a single image name. Pass one, e.g. "my-game-server".`);
@@ -2370,6 +2735,14 @@ export function registerTools(server, client, config, auth, options = {}) {
2370
2735
  await dry.client.deleteRegistryTag(name, tag);
2371
2736
  return dryRunResult(dry.requests, name !== image_name ? [`Looked up "${name}".`] : []);
2372
2737
  }
2738
+ if (confirm !== true) {
2739
+ return confirmationRequired('delete registry tag', {
2740
+ image_name: name,
2741
+ tag,
2742
+ warning: 'Deletes the tag and, if no other tag points to it, the image. Any version still using this tag ' +
2743
+ 'can no longer start deployments (check edgegap_list_app_versions). Cannot be undone.',
2744
+ });
2745
+ }
2373
2746
  const notFound = (err) => err instanceof EdgegapApiError && err.status === 404;
2374
2747
  try {
2375
2748
  let res;
@@ -2433,6 +2806,11 @@ export function registerTools(server, client, config, auth, options = {}) {
2433
2806
  const leak = await tokenLeak(auth, dry_run, toAdd.map((t) => [`tag "${t.slice(0, 8)}…"`, t]));
2434
2807
  if (leak)
2435
2808
  return leak;
2809
+ if (!dry_run) {
2810
+ const blocked = await deploymentOutsideAllowlist(request_id);
2811
+ if (blocked)
2812
+ return blocked;
2813
+ }
2436
2814
  if (dry_run) {
2437
2815
  const dry = client.dryRun();
2438
2816
  for (const t of toAdd)
@@ -2481,6 +2859,11 @@ export function registerTools(server, client, config, auth, options = {}) {
2481
2859
  ]);
2482
2860
  if (leak)
2483
2861
  return leak;
2862
+ if (!dry_run) {
2863
+ const blocked = await deploymentOutsideAllowlist(request_id);
2864
+ if (blocked)
2865
+ return blocked;
2866
+ }
2484
2867
  const body = { reason, ...(metadata ? { metadata } : {}) };
2485
2868
  if (dry_run) {
2486
2869
  const dry = client.dryRun();
@@ -2496,15 +2879,16 @@ export function registerTools(server, client, config, auth, options = {}) {
2496
2879
  title: 'Delete one application version',
2497
2880
  description: 'Delete one version of an application, to clean up test versions. Exactly one exact version name; ' +
2498
2881
  'refused while any deployment of that version is running. The container image stays in the registry ' +
2499
- '(edgegap_delete_registry_tag removes it). Cannot be undone, so confirm with the developer when the ' +
2500
- 'version is not one this conversation created.',
2882
+ '(edgegap_delete_registry_tag removes it). Cannot be undone, so without confirm: true the result only ' +
2883
+ 'previews it and nothing is sent.',
2501
2884
  inputSchema: {
2502
2885
  application: z.string().describe('Application name.'),
2503
2886
  version: z.string().min(1).describe('The exact version name to delete.'),
2887
+ confirm: confirmParam,
2504
2888
  dry_run: dryRunParam,
2505
2889
  },
2506
2890
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
2507
- }, async ({ application, version, dry_run }) => guarded(auth, NOT_FOUND.app, async () => {
2891
+ }, async ({ application, version, confirm, dry_run }) => guarded(auth, NOT_FOUND.app, async () => {
2508
2892
  assertAppAllowed(config, application);
2509
2893
  const badName = exactName(version, 'version');
2510
2894
  if (badName)
@@ -2517,6 +2901,14 @@ export function registerTools(server, client, config, auth, options = {}) {
2517
2901
  const running = await runningOf(application, version);
2518
2902
  if (running.length)
2519
2903
  return refusedRunning(`version "${version}"`, running);
2904
+ if (confirm !== true) {
2905
+ const v = await client.getAppVersion(application, version);
2906
+ return confirmationRequired('delete application version', {
2907
+ application,
2908
+ version: compactVersion(v),
2909
+ warning: 'Matchmakers or scripts that deploy this version will fail afterwards. The registry image is kept. Cannot be undone.',
2910
+ });
2911
+ }
2520
2912
  await client.deleteAppVersion(application, version);
2521
2913
  return ok({ application, deleted_version: version, image_kept: 'The registry image was not touched.' });
2522
2914
  }));
@@ -2525,9 +2917,11 @@ export function registerTools(server, client, config, auth, options = {}) {
2525
2917
  description: 'Delete one application and every version under it, to clean up a test application. Exactly one ' +
2526
2918
  'exact name; refused while any of its deployments is running, and refused when it has more versions ' +
2527
2919
  'than max_versions (default 0: delete its versions first with edgegap_delete_app_version, or raise ' +
2528
- 'max_versions after the developer agreed). Registry images are not touched. Cannot be undone.',
2920
+ 'max_versions after the developer agreed). Registry images are not touched. Cannot be undone, so ' +
2921
+ 'without confirm: true the result only previews it and nothing is sent.',
2529
2922
  inputSchema: {
2530
2923
  application: z.string().min(1).describe('The exact application name to delete.'),
2924
+ confirm: confirmParam,
2531
2925
  max_versions: z
2532
2926
  .number()
2533
2927
  .int()
@@ -2537,7 +2931,7 @@ export function registerTools(server, client, config, auth, options = {}) {
2537
2931
  dry_run: dryRunParam,
2538
2932
  },
2539
2933
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
2540
- }, async ({ application, max_versions, dry_run }) => guarded(auth, NOT_FOUND.app, async () => {
2934
+ }, async ({ application, max_versions, confirm, dry_run }) => guarded(auth, NOT_FOUND.app, async () => {
2541
2935
  assertAppAllowed(config, application);
2542
2936
  const badName = exactName(application, 'application');
2543
2937
  if (badName)
@@ -2558,10 +2952,34 @@ export function registerTools(server, client, config, auth, options = {}) {
2558
2952
  const running = await runningOf(application);
2559
2953
  if (running.length)
2560
2954
  return refusedRunning(`application "${application}"`, running);
2955
+ if (confirm !== true) {
2956
+ return confirmationRequired('delete application', {
2957
+ application,
2958
+ versions_deleted_with_it: versions,
2959
+ warning: 'Deletes the application and every version listed. Registry images are kept. Cannot be undone.',
2960
+ });
2961
+ }
2561
2962
  await client.deleteApp(application);
2562
2963
  return ok({ deleted_application: application, deleted_versions: versions });
2563
2964
  }));
2564
2965
  }
2966
+ /**
2967
+ * With EDGEGAP_APP_ALLOWLIST set, the write tools keyed on request_id (stop,
2968
+ * tag, report) refuse a deployment of an application outside the list. Reads
2969
+ * stay open, as for applications. No allowlist: no extra API call.
2970
+ */
2971
+ async function deploymentOutsideAllowlist(requestId) {
2972
+ if (config.appAllowlist.length === 0)
2973
+ return undefined;
2974
+ const s = await client.getDeployment(requestId);
2975
+ try {
2976
+ assertAppAllowed(config, s.app_name);
2977
+ return undefined;
2978
+ }
2979
+ catch (err) {
2980
+ return fail(`Refused: deployment ${requestId} belongs to "${s.app_name}". ${err.message} Nothing was sent.`);
2981
+ }
2982
+ }
2565
2983
  /** Request IDs of running deployments of an application (and version). */
2566
2984
  async function runningOf(application, version) {
2567
2985
  const filters = [{ field: 'application', operator: 'eq', value: application }];
package/dist/version.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * call, and by edgegap_context. Keep in step with package.json and server.json;
4
4
  * test/package.mjs fails the build when they disagree.
5
5
  */
6
- export const VERSION = '0.18.0';
6
+ export const VERSION = '0.19.0';
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@edgegap/mcp",
3
3
  "mcpName": "dev.edgegap/mcp",
4
- "version": "0.18.0",
4
+ "version": "0.19.0",
5
5
  "description": "Check, push, and deploy game servers on Edgegap from your coding agent, with relays for P2P games. Runs locally; your API token never leaves your machine.",
6
6
  "scripts": {
7
7
  "prebuild": "rm -rf dist",
8
8
  "build": "tsc && node scripts/chmod-bin.mjs",
9
9
  "typecheck": "tsc --noEmit",
10
10
  "typecheck:worker": "tsc -p worker/tsconfig.json --noEmit",
11
- "test": "node --test test/unit.test.mjs && node test/package.mjs && node test/skills.mjs && node test/updateskills.mjs && node test/smoke.mjs && node test/guards.mjs && node test/elicit.mjs && node test/newtools.mjs && node test/emptystates.mjs && node test/reports.mjs && node test/http.mjs && node test/retries.mjs && node test/spec.mjs && node test/snapshot.mjs",
11
+ "test": "node --test test/unit.test.mjs && node test/package.mjs && node test/skills.mjs && node test/updateskills.mjs && node test/smoke.mjs && node test/guards.mjs && node test/elicit.mjs && node test/newtools.mjs && node test/ops.mjs && node test/emptystates.mjs && node test/reports.mjs && node test/http.mjs && node test/retries.mjs && node test/spec.mjs && node test/snapshot.mjs",
12
12
  "test:unit": "node --test test/unit.test.mjs",
13
13
  "snapshot:update": "node test/snapshot.mjs --update",
14
14
  "scan": "node scripts/scan-repo.mjs",