@edgegap/mcp 0.18.0 → 0.19.1

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.1`) 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);