@edgegap/mcp 0.6.3 → 0.7.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
@@ -157,7 +157,7 @@ To keep your API token on your own machine, run the server locally instead. Leav
157
157
  }
158
158
  ```
159
159
 
160
- Needs Node 18+. Pin a version in production (`@edgegap/mcp@0.6.3`) rather than floating on latest. Registered in the official MCP registry as `dev.edgegap/mcp`.
160
+ Needs Node 18+. Pin a version in production (`@edgegap/mcp@0.7.0`) rather than floating on latest. Registered in the official MCP registry as `dev.edgegap/mcp`.
161
161
 
162
162
  The local server can also limit what an agent can do. These variables have no effect on the hosted endpoint at `mcp.edgegap.dev`:
163
163
 
@@ -216,6 +216,7 @@ Your agent picks the right tool from your request. You don't need to name them,
216
216
  | `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. |
217
217
  | `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. |
218
218
  | `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. |
219
+ | `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. |
219
220
 
220
221
  ### Dedicated Servers (Recommended)
221
222
 
@@ -223,13 +224,19 @@ Your agent picks the right tool from your request. You don't need to name them,
223
224
  | --- | --- |
224
225
  | `edgegap_list_apps` | Lists your applications. |
225
226
  | `edgegap_create_app` ● | Creates an application. |
227
+ | `edgegap_update_app` ● | Turns an application on or off for new deployments. |
226
228
  | `edgegap_list_app_versions` | Lists versions with their image, resources, ports (with TLS Upgrade), and whether a registry login is set. |
229
+ | `edgegap_get_app_version` | Reads one version in full: image, resources, ports, max duration, image caching, restart policy, and env var names (never values). |
227
230
  | `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://`. |
231
+ | `edgegap_update_app_version` ● | Changes an existing version: a new image tag, on/off, max duration, registry login, image caching (`force_cache`), shutdown grace period. Only the fields passed change; running deployments keep the old settings. |
232
+ | `edgegap_list_locations` | Lists the cities Edgegap deploys to, or, for one version, only those with capacity right now. |
233
+ | `edgegap_list_ping_beacons` | Lists the ping beacons game clients measure latency against before matchmaking. |
228
234
  | `edgegap_deploy` ● | Deploys an authoritative dedicated server close to your players. Always tagged `edgegap-mcp`, and reports when Edgegap will stop it. |
229
235
  | `edgegap_wait_for_deployment` | Waits until the server is ready and returns the connection address. |
230
236
  | `edgegap_get_deployment` | Reads a deployment's status. |
231
237
  | `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). |
232
238
  | `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. |
239
+ | `edgegap_get_deployment_metrics` | Summarises CPU, CPU throttling, memory and network use (latest, average, peak), to size a version or check a crash. |
233
240
  | `edgegap_stop_deployment` ● | Stops one deployment, by its exact request ID. No bulk stop. |
234
241
 
235
242
  ### Matchmaking
@@ -248,7 +255,9 @@ A relay is not a game server: it forwards traffic while one player's game hosts
248
255
  | --- | --- |
249
256
  | `edgegap_create_relay_session` ● | Creates a relay session for your players and returns the relay address and each player's authorization token. |
250
257
  | `edgegap_get_relay_session` | Reads a relay session. |
258
+ | `edgegap_list_relay_sessions` | Lists open relay sessions, to find ones left running. No authorization tokens. |
251
259
  | `edgegap_authorize_relay_user` ● | Adds a player who joins later. |
260
+ | `edgegap_revoke_relay_user` ● | Removes one player from a relay session. |
252
261
  | `edgegap_delete_relay_session` ● | Closes a relay session. |
253
262
 
254
263
  > [!WARNING]
@@ -326,7 +335,7 @@ docker run --rm -p 8080:8080 edgegap-mcp
326
335
 
327
336
  Clients connect to `http://<host>:8080/mcp` with their own `Authorization` header, the same way they connect to the hosted endpoint. The image holds no credential, and `/health` answers without one. `PORT`, `HOST`, `EDGEGAP_READ_ONLY`, `EDGEGAP_APP_ALLOWLIST`, `EDGEGAP_MAX_DURATION_MINUTES` and `EDGEGAP_MAX_AGENT_DEPLOYMENTS` apply. Read [worker/DECISION.md](worker/DECISION.md) before exposing it beyond a private network.
328
337
 
329
- Prebuilt images are published to `ghcr.io/edgegap/edgegap-mcp`, tagged `main` and `sha-<commit>` on every push to `main`, plus the version on `v*` tags:
338
+ Prebuilt images for `linux/amd64` and `linux/arm64` are published to `ghcr.io/edgegap/edgegap-mcp`, tagged `main` and `sha-<commit>` on every push to `main`, plus the version on `v*` tags:
330
339
 
331
340
  ```bash
332
341
  docker run --rm -p 8080:8080 ghcr.io/edgegap/edgegap-mcp:main
@@ -334,6 +343,8 @@ docker run --rm -p 8080:8080 ghcr.io/edgegap/edgegap-mcp:main
334
343
 
335
344
  ## Development
336
345
 
346
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the checks a change has to pass, [CHANGELOG.md](CHANGELOG.md) for what each version changed, and [SECURITY.md](SECURITY.md) to report a vulnerability.
347
+
337
348
  ```bash
338
349
  npm ci
339
350
  npm run build
@@ -350,6 +361,7 @@ npm run check-skills # exit 1 if src/skills.generated.ts differs from the p
350
361
 
351
362
  | Test | Covers |
352
363
  | --- | --- |
364
+ | `test/unit.test.mjs` | Unit tests for the tag, image, secret-name, URL and redaction rules |
353
365
  | `test/package.mjs` | Packaging: one `bin`, runtime dependencies, versions in step |
354
366
  | `test/skills.mjs` | Skills over MCP: tools, prompts, resources, path safety, bundle matches the pin |
355
367
  | `test/smoke.mjs` | Handshake, tool registration, read-only mode |
@@ -357,6 +369,8 @@ npm run check-skills # exit 1 if src/skills.generated.ts differs from the p
357
369
  | `test/elicit.mjs` | Token prompt: accept, refuse acknowledgement, decline, no support |
358
370
  | `test/newtools.mjs` | Validator, Dockerfile generator, registry, deployments, relay and matchmaker tools against a local mock API |
359
371
  | `test/http.mjs` | Self-hosted HTTP server: discovery without a token, per-request tokens, foreign credentials |
372
+ | `test/spec.mjs` | Every endpoint and request-body field the server sends is in `spec/` (write tools checked by dry run) |
373
+ | `test/snapshot.mjs` | Tool names, descriptions, schemas and the instructions match `test/tools.snapshot.json`; `npm run snapshot:update` after a deliberate change |
360
374
  | `test/live-check.mjs` | Not in `npm test`. Runs against the real API with a token from a non-production organization |
361
375
 
362
376
  Design decisions, the security model, and what's deliberately out of scope are in [DESIGN.md](DESIGN.md).
package/dist/client.js CHANGED
@@ -144,6 +144,9 @@ export class EdgegapClient {
144
144
  createApp(body) {
145
145
  return this.request('POST', 'v1', '/v1/app', { body });
146
146
  }
147
+ updateApp(appName, body) {
148
+ return this.request('PATCH', 'v1', `/v1/app/${encodeURIComponent(appName)}`, { body });
149
+ }
147
150
  listAppVersions(appName) {
148
151
  return this.request('GET', 'v1', `/v1/app/${encodeURIComponent(appName)}/versions`);
149
152
  }
@@ -151,6 +154,9 @@ export class EdgegapClient {
151
154
  getAppVersion(appName, versionName) {
152
155
  return this.request('GET', 'v1', `/v1/app/${encodeURIComponent(appName)}/version/${encodeURIComponent(versionName)}`);
153
156
  }
157
+ updateAppVersion(appName, versionName, body) {
158
+ return this.request('PATCH', 'v1', `/v1/app/${encodeURIComponent(appName)}/version/${encodeURIComponent(versionName)}`, { body });
159
+ }
154
160
  createAppVersion(appName, body) {
155
161
  return this.request('POST', 'v1', `/v1/app/${encodeURIComponent(appName)}/version`, { body });
156
162
  }
@@ -168,6 +174,17 @@ export class EdgegapClient {
168
174
  stopDeployment(requestId) {
169
175
  return this.request('DELETE', 'v1', `/v1/stop/${encodeURIComponent(requestId)}`);
170
176
  }
177
+ getDeploymentMetrics(requestId, query = {}) {
178
+ return this.request('GET', 'v1', `/v1/metrics/deployment/${encodeURIComponent(requestId)}`, { query });
179
+ }
180
+ // --- Locations ----------------------------------------------------------
181
+ /** With app and version, only locations with capacity for it right now. */
182
+ listLocations(query = {}) {
183
+ return this.request('GET', 'v1', '/v1/locations', { query });
184
+ }
185
+ listBeacons(query = {}) {
186
+ return this.request('GET', 'v1', '/v1/locations/beacons', { query });
187
+ }
171
188
  getDeploymentLogs(requestId, format = 'text') {
172
189
  return this.request('GET', 'v1', `/v1/deployment/${encodeURIComponent(requestId)}/container-logs`, { query: { format } });
173
190
  }
@@ -195,7 +212,19 @@ export class EdgegapClient {
195
212
  const path = imageName.split('/').map(encodeURIComponent).join('/');
196
213
  return this.request('GET', 'v1', `/v1/container-registry/images/${path}/tags`, { query });
197
214
  }
215
+ /** Deletes one tag and, per the spec, the image it points to. Same
216
+ * image-name rules as listRegistryTags. */
217
+ deleteRegistryTag(imageName, tag) {
218
+ const path = imageName.split('/').map(encodeURIComponent).join('/');
219
+ return this.request('DELETE', 'v1', `/v1/container-registry/images/${path}/tags/${encodeURIComponent(tag)}`);
220
+ }
198
221
  // --- Relays -------------------------------------------------------------
222
+ listRelaySessions() {
223
+ return this.request('GET', 'v1', '/v1/relays/sessions');
224
+ }
225
+ revokeRelayUser(body) {
226
+ return this.request('POST', 'v1', '/v1/relays/sessions:revoke-user', { body });
227
+ }
199
228
  createRelaySession(body) {
200
229
  return this.request('POST', 'v1', '/v1/relays/sessions', { body });
201
230
  }
package/dist/tools.js CHANGED
@@ -109,8 +109,32 @@ const TERMINAL_OK = ['READY', 'STATUS_READY'];
109
109
  const TERMINAL_BAD = ['ERROR', 'STATUS_ERROR', 'TERMINATED', 'STATUS_TERMINATED'];
110
110
  function ok(payload, notice) {
111
111
  const body = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);
112
+ const structured = payload !== null && typeof payload === 'object' && !Array.isArray(payload)
113
+ ? JSON.parse(body)
114
+ : undefined;
112
115
  return {
113
116
  content: [{ type: 'text', text: notice ? `${body}\n\nNOTE: ${notice}` : body }],
117
+ ...(structured ? { structuredContent: structured } : {}),
118
+ };
119
+ }
120
+ /**
121
+ * Strips the API token from a whole result, success or failure. Errors were
122
+ * already redacted at the source; this covers anything the API echoes back in
123
+ * a successful response, and any text a tool builds from it.
124
+ */
125
+ function scrubToken(result, token) {
126
+ if (!token || token.length < 8)
127
+ return result;
128
+ const needles = [token, token.replace(/-/g, '')].filter((n, i, all) => n.length >= 8 && all.indexOf(n) === i);
129
+ const clean = (text) => needles.reduce((t, n) => redact(t, n), text);
130
+ const hit = (text) => needles.some((n) => text.includes(n));
131
+ const structuredText = result.structuredContent ? JSON.stringify(result.structuredContent) : '';
132
+ if (!result.content.some((c) => hit(c.text)) && !hit(structuredText))
133
+ return result;
134
+ return {
135
+ ...result,
136
+ content: result.content.map((c) => ({ ...c, text: clean(c.text) })),
137
+ ...(result.structuredContent ? { structuredContent: JSON.parse(clean(structuredText)) } : {}),
114
138
  };
115
139
  }
116
140
  function fail(message) {
@@ -242,6 +266,52 @@ function compactDeployment(d) {
242
266
  ports,
243
267
  };
244
268
  }
269
+ /** The version fields every version tool shows. Never the registry token. */
270
+ function compactVersion(v) {
271
+ return {
272
+ name: v.name,
273
+ active: v.is_active,
274
+ image: [v.docker_repository, v.docker_image, v.docker_tag].filter(Boolean).join('/'),
275
+ // Whether a login is set, never the login itself: the API returns the
276
+ // registry token in version responses.
277
+ registry_credentials_set: Boolean(v.private_username && v.private_token),
278
+ cpu_units: v.req_cpu,
279
+ memory_mb: v.req_memory,
280
+ max_duration_minutes: v.max_duration,
281
+ ports: v.ports?.map((p) => ({
282
+ name: p.name,
283
+ port: p.port,
284
+ protocol: p.protocol,
285
+ tls_upgrade: p.tls_upgrade ?? false,
286
+ })),
287
+ };
288
+ }
289
+ /** Reduces "registry.edgegap.com/<project>/img:tag" to the image path the
290
+ * registry endpoints take. The project is stripped later only on a 404,
291
+ * because nested image names are valid. */
292
+ function imageNameOnly(input) {
293
+ const parts = input.trim().replace(/@sha256:.*$/, '').split('/');
294
+ if (parts.length > 1 && /[.:]/.test(parts[0]))
295
+ parts.shift();
296
+ parts[parts.length - 1] = parts[parts.length - 1].replace(/:[^:]*$/, '');
297
+ return parts.join('/');
298
+ }
299
+ /** Latest, average and peak of one metrics series, plus its labels. */
300
+ function summarizeSeries(series) {
301
+ const values = (series?.datasets ?? []).filter((x) => typeof x === 'number' && Number.isFinite(x));
302
+ if (values.length === 0)
303
+ return undefined;
304
+ const round = (x) => Math.round(x * 100) / 100;
305
+ return {
306
+ latest: round(values[values.length - 1]),
307
+ average: round(values.reduce((a, b) => a + b, 0) / values.length),
308
+ peak: round(Math.max(...values)),
309
+ samples: values.length,
310
+ labels: series?.labels?.length ? [...new Set(series.labels)].slice(0, 5) : undefined,
311
+ from: series?.timestamps?.[0],
312
+ to: series?.timestamps?.[series.timestamps.length - 1],
313
+ };
314
+ }
245
315
  const userSchema = z
246
316
  .object({
247
317
  ip_addresses: z
@@ -366,7 +436,8 @@ export function registerTools(server, client, config, auth) {
366
436
  // Every result names the API host it came from, first, so a session pointed
367
437
  // at a custom EDGEGAP_BASE_URL can never be mistaken for production.
368
438
  const label = hostLabel(config);
369
- const tool = ((name, def, cb) => server.registerTool(name, def, (async (...a) => withHost(await cb(...a), label))));
439
+ // ...and never carries the API token, whatever the API echoed back.
440
+ const tool = ((name, def, cb) => server.registerTool(name, def, (async (...a) => withHost(scrubToken(await cb(...a), auth.current), label))));
370
441
  // ---------------------------------------------------------------- 0 ----
371
442
  // No token, no network: describes this server's own configuration, so an
372
443
  // agent can check where it is pointed and what is allowed before acting.
@@ -404,7 +475,7 @@ export function registerTools(server, client, config, auth) {
404
475
  forced_deploy_tag: AGENT_TAG,
405
476
  guardrails: {
406
477
  dry_run: mutating
407
- ? 'deploy, stop_deployment, create_app, create_app_version, create/authorize/delete relay'
478
+ ? 'deploy, stop_deployment, create_app, update_app, create_app_version, update_app_version, delete_registry_tag, create/authorize/revoke/delete relay'
408
479
  : 'n/a: read-only, no write tools are registered',
409
480
  token_in_container: 'deploys and versions are refused if the API token appears in an env var, tag or webhook URL',
410
481
  image_tags: 'versions on "latest", an empty or malformed tag, or a docker_image holding a registry or tag are refused; so is deploying a version on "latest"',
@@ -472,6 +543,31 @@ export function registerTools(server, client, config, auth) {
472
543
  });
473
544
  }));
474
545
  }
546
+ // --------------------------------------------------------------- 2b ----
547
+ if (mutating) {
548
+ tool('edgegap_update_app', {
549
+ title: 'Turn an application on or off',
550
+ description: 'Set whether an application accepts new deployments. Turning it off stops new ' +
551
+ 'deployments of every version under it; running deployments keep running. Use it to ' +
552
+ 'pause an application without deleting anything.',
553
+ inputSchema: {
554
+ application: z.string().describe('Application name.'),
555
+ is_active: z.boolean().describe('false blocks new deployments; true allows them again.'),
556
+ dry_run: dryRunParam,
557
+ },
558
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
559
+ }, async ({ application, is_active, dry_run }) => guarded(auth, NOT_FOUND.app, async () => {
560
+ assertAppAllowed(config, application);
561
+ const body = { is_active };
562
+ if (dry_run) {
563
+ const dry = client.dryRun();
564
+ await dry.client.updateApp(application, body);
565
+ return dryRunResult(dry.requests);
566
+ }
567
+ const res = await client.updateApp(application, body);
568
+ return ok({ application: res.name ?? application, active: res.is_active ?? is_active });
569
+ }));
570
+ }
475
571
  // ---------------------------------------------------------------- 3 ----
476
572
  tool('edgegap_list_app_versions', {
477
573
  title: 'List versions of an application',
@@ -489,25 +585,36 @@ export function registerTools(server, client, config, auth) {
489
585
  // limits what the agent can create and deploy into, as documented.
490
586
  guarded(auth, NOT_FOUND.app, async () => {
491
587
  const res = await client.listAppVersions(application);
492
- const versions = (res.versions ?? []).map((v) => ({
493
- name: v.name,
494
- active: v.is_active,
495
- image: [v.docker_repository, v.docker_image, v.docker_tag].filter(Boolean).join('/'),
496
- // Whether a login is set, never the login itself: the API returns
497
- // the registry token in this response.
498
- registry_credentials_set: Boolean(v.private_username && v.private_token),
499
- cpu_units: v.req_cpu,
500
- memory_mb: v.req_memory,
501
- max_duration_minutes: v.max_duration,
502
- ports: v.ports?.map((p) => ({
503
- name: p.name,
504
- port: p.port,
505
- protocol: p.protocol,
506
- tls_upgrade: p.tls_upgrade ?? false,
507
- })),
508
- }));
588
+ const versions = (res.versions ?? []).map(compactVersion);
509
589
  return ok({ application, ...pageInfo(res.total_count, versions.length, 1), versions });
510
590
  }));
591
+ // --------------------------------------------------------------- 3b ----
592
+ tool('edgegap_get_app_version', {
593
+ title: 'Get one application version',
594
+ description: 'Read one version in full: image, resources, ports, max_duration, whether image caching ' +
595
+ '(force_cache) and verify_image are on, restart policy, and the names of its env vars ' +
596
+ '(values are never shown). Use it before edgegap_update_app_version or edgegap_deploy ' +
597
+ 'to check what a version will do.',
598
+ inputSchema: {
599
+ application: z.string().describe('Application name.'),
600
+ version: z.string().describe('Version name, as listed by edgegap_list_app_versions.'),
601
+ },
602
+ annotations: { readOnlyHint: true, openWorldHint: true },
603
+ }, async ({ application, version }) => guarded(auth, NOT_FOUND.app, async () => {
604
+ const v = await client.getAppVersion(application, version);
605
+ return ok({
606
+ application,
607
+ ...compactVersion(v),
608
+ force_cache: v.force_cache,
609
+ caching_percent: v.caching_percent,
610
+ verify_image: v.verify_image,
611
+ restart_policy: v.restart_policy,
612
+ termination_grace_period_seconds: v.termination_grace_period_seconds,
613
+ time_to_deploy_seconds: v.time_to_deploy,
614
+ env: v.envs?.map((e) => ({ key: e.key, hidden: e.is_hidden ?? false })),
615
+ ...autoStop(v.max_duration),
616
+ });
617
+ }));
511
618
  // ---------------------------------------------------------------- 4 ----
512
619
  if (mutating) {
513
620
  tool('edgegap_create_app_version', {
@@ -668,6 +775,157 @@ export function registerTools(server, client, config, auth) {
668
775
  });
669
776
  }));
670
777
  }
778
+ // --------------------------------------------------------------- 4b ----
779
+ if (mutating) {
780
+ tool('edgegap_update_app_version', {
781
+ title: 'Update an application version',
782
+ description: 'Change settings on an existing version instead of creating a new one: point it at a new ' +
783
+ 'image tag, turn it on or off, change max_duration, set the registry login, turn on image ' +
784
+ 'caching (force_cache: Edgegap pre-loads the image so deployments start faster), or set ' +
785
+ 'the shutdown grace period. Only the fields you pass change. Deployments already running ' +
786
+ 'keep their old settings; new deployments get the new ones. Same refusals as ' +
787
+ 'edgegap_create_app_version: "latest" or empty tags, a docker_image holding a host or ' +
788
+ 'tag, and the API token in the registry login. Resources, ports and env vars cannot be ' +
789
+ 'changed here; create a new version for those.',
790
+ inputSchema: {
791
+ application: z.string().describe('Application name.'),
792
+ version: z.string().describe('Version name to change.'),
793
+ is_active: z.boolean().optional().describe('false blocks new deployments of this version.'),
794
+ docker_repository: z.string().optional().describe('Registry host, e.g. "registry.edgegap.com".'),
795
+ docker_image: z.string().optional().describe('Image path, e.g. "my-org-abc123/my-game-server".'),
796
+ docker_tag: z.string().optional().describe('New image tag: a build ID, commit SHA or timestamp.'),
797
+ registry_username: z.string().optional(),
798
+ registry_token: z.string().optional().describe('Registry password or token. Never echoed back.'),
799
+ max_duration_minutes: z
800
+ .number()
801
+ .int()
802
+ .optional()
803
+ .describe('Auto-stop after this many minutes. Capped by EDGEGAP_MAX_DURATION_MINUTES.'),
804
+ force_cache: z.boolean().optional().describe('Pre-load the image on Edgegap so deployments start faster.'),
805
+ verify_image: z.boolean().optional().describe('Check Edgegap can pull the image when saving.'),
806
+ termination_grace_period_seconds: z
807
+ .number()
808
+ .int()
809
+ .min(0)
810
+ .max(3600)
811
+ .optional()
812
+ .describe('Seconds between SIGTERM and SIGKILL when a deployment stops.'),
813
+ dry_run: dryRunParam,
814
+ },
815
+ annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
816
+ }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
817
+ assertAppAllowed(config, args.application);
818
+ const leak = await tokenLeak(auth, args.dry_run, [
819
+ ['registry_username', args.registry_username],
820
+ ['registry_token', args.registry_token],
821
+ ]);
822
+ if (leak)
823
+ return leak;
824
+ if (args.docker_tag !== undefined) {
825
+ const tagProblem = badTag(args.docker_tag);
826
+ if (tagProblem)
827
+ return fail(`Refused: ${tagProblem}. ${TAG_FIX}`);
828
+ }
829
+ if (args.docker_image !== undefined) {
830
+ const imageProblem = badImage(args.docker_repository ?? '', args.docker_image);
831
+ if (imageProblem)
832
+ return fail(`Refused: ${imageProblem}`);
833
+ }
834
+ const capped = args.max_duration_minutes === undefined
835
+ ? undefined
836
+ : Math.min(args.max_duration_minutes, config.maxDurationCeiling);
837
+ const body = {
838
+ is_active: args.is_active,
839
+ docker_repository: args.docker_repository,
840
+ docker_image: args.docker_image,
841
+ docker_tag: args.docker_tag,
842
+ private_username: args.registry_username,
843
+ private_token: args.registry_token,
844
+ max_duration: capped,
845
+ force_cache: args.force_cache,
846
+ verify_image: args.verify_image,
847
+ termination_grace_period_seconds: args.termination_grace_period_seconds,
848
+ };
849
+ for (const k of Object.keys(body))
850
+ if (body[k] === undefined)
851
+ delete body[k];
852
+ if (Object.keys(body).length === 0) {
853
+ return fail('Nothing to change: pass at least one field to update.');
854
+ }
855
+ const notes = capped !== undefined && capped < (args.max_duration_minutes ?? 0)
856
+ ? [`max_duration capped to ${capped} minutes by EDGEGAP_MAX_DURATION_MINUTES.`]
857
+ : [];
858
+ if (args.dry_run) {
859
+ const dry = client.dryRun();
860
+ await dry.client.updateAppVersion(args.application, args.version, body);
861
+ return dryRunResult(dry.requests, notes);
862
+ }
863
+ await client.updateAppVersion(args.application, args.version, body);
864
+ return ok({
865
+ updated: `${args.application}/${args.version}`,
866
+ changed: Object.keys(body).map((k) => (k === 'private_token' ? 'registry_token' : k === 'private_username' ? 'registry_username' : k)),
867
+ notes: notes.length ? notes : undefined,
868
+ next_step: 'Running deployments keep the old settings. Check the result with edgegap_get_app_version.',
869
+ });
870
+ }));
871
+ }
872
+ // --------------------------------------------------------------- 5b ----
873
+ tool('edgegap_list_locations', {
874
+ title: 'List where servers can run',
875
+ description: 'List the cities Edgegap can deploy to. Pass application and version to see only the ' +
876
+ 'locations with capacity for that version right now. Use it to pick geo_coordinates for ' +
877
+ 'edgegap_deploy when you have no player IPs, or to tell a developer where their players ' +
878
+ 'can be served from. For the ping beacons game clients use to measure latency, see ' +
879
+ 'edgegap_list_ping_beacons.',
880
+ inputSchema: {
881
+ application: z.string().optional().describe('With version: only locations with capacity for it now.'),
882
+ version: z.string().optional(),
883
+ page: z.number().int().min(1).optional(),
884
+ limit: z.number().int().min(1).max(200).optional().describe('Default 100.'),
885
+ },
886
+ annotations: { readOnlyHint: true, openWorldHint: true },
887
+ }, async ({ application, version, page, limit }) => guarded(auth, NOT_FOUND.app, async () => {
888
+ if ((application === undefined) !== (version === undefined)) {
889
+ return fail('Pass both application and version to filter by capacity, or neither for every location.');
890
+ }
891
+ const res = await client.listLocations({ app: application, version, page, limit: limit ?? 100 });
892
+ const locations = (res.locations ?? []).map((l) => ({
893
+ city: l.city,
894
+ region: l.administrative_division || undefined,
895
+ country: l.country,
896
+ continent: l.continent,
897
+ latitude: l.latitude,
898
+ longitude: l.longitude,
899
+ }));
900
+ return ok({
901
+ filtered_for: application ? `${application}/${version} (capacity right now)` : undefined,
902
+ ...pageInfo(res.total_count, locations.length, page ?? 1),
903
+ locations,
904
+ messages: res.messages?.length ? res.messages : undefined,
905
+ });
906
+ }));
907
+ tool('edgegap_list_ping_beacons', {
908
+ title: 'List ping beacons',
909
+ description: 'List Edgegap\'s ping beacons: one host per region that a game client can ping (UDP or ' +
910
+ 'TCP) to measure its latency before matchmaking. The matchmaker\'s latency rules use these ' +
911
+ 'measurements. Read-only; the game client does the pinging, not this tool.',
912
+ inputSchema: {
913
+ page: z.number().int().min(1).optional(),
914
+ limit: z.number().int().min(1).max(200).optional().describe('Default 100.'),
915
+ },
916
+ annotations: { readOnlyHint: true, openWorldHint: true },
917
+ }, async ({ page, limit }) => guard(auth, async () => {
918
+ const res = await client.listBeacons({ page, limit: limit ?? 100 });
919
+ const beacons = (res.locations ?? []).map((b) => ({
920
+ host: b.fqdn ?? b.host,
921
+ udp_port: b.udp_port,
922
+ tcp_port: b.tcp_port,
923
+ city: b.location?.city,
924
+ country: b.location?.country,
925
+ continent: b.location?.continent,
926
+ }));
927
+ return ok({ total: res.count ?? beacons.length, beacons });
928
+ }));
671
929
  // ---------------------------------------------------------------- 5 ----
672
930
  if (mutating) {
673
931
  tool('edgegap_deploy', {
@@ -695,8 +953,13 @@ export function registerTools(server, client, config, auth) {
695
953
  .array(z.string().min(1).max(40))
696
954
  .optional()
697
955
  .describe(`Extra tags for filtering later, e.g. ["agent-test"]. "${AGENT_TAG}" is always added.`),
698
- cpu_units: z.number().int().min(256).optional().describe('Override the version CPU.'),
699
- memory_mb: z.number().int().min(256).optional().describe('Override the version memory.'),
956
+ cpu_units: z
957
+ .number()
958
+ .int()
959
+ .min(256)
960
+ .optional()
961
+ .describe('Override the version CPU (with memory_mb). Not in the published v2 spec, so the API may ignore it; a version with the size you need is the reliable way.'),
962
+ memory_mb: z.number().int().min(256).optional().describe('Override the version memory (with cpu_units). Same caveat as cpu_units.'),
700
963
  dry_run: dryRunParam,
701
964
  },
702
965
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
@@ -773,6 +1036,13 @@ export function registerTools(server, client, config, auth) {
773
1036
  status: 'starting',
774
1037
  tags,
775
1038
  ...autoStop(version.max_duration),
1039
+ // "resources" is not in the published v2 deploy schema
1040
+ // (test/spec.mjs). Say so rather than promise the override.
1041
+ resources_note: body.resources
1042
+ ? 'cpu_units/memory_mb were sent, but the published v2 API does not document a per-deployment ' +
1043
+ 'override, so the deployment may run with the version\'s size. For a different size, create a ' +
1044
+ 'version with it.'
1045
+ : undefined,
776
1046
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
777
1047
  });
778
1048
  }));
@@ -961,6 +1231,43 @@ export function registerTools(server, client, config, auth) {
961
1231
  storage_link: res.logs_link ?? undefined,
962
1232
  });
963
1233
  }));
1234
+ // --------------------------------------------------------------- 10b ----
1235
+ tool('edgegap_get_deployment_metrics', {
1236
+ title: 'Get CPU, memory and network use of a deployment',
1237
+ description: 'Summarise a deployment\'s resource use over time: CPU, CPU throttling, memory and network, ' +
1238
+ 'each as latest, average and peak, with the API\'s own labels. Use it to size a version ' +
1239
+ '(cpu_units, memory_mb) from a real match, or to check whether a crash was memory or CPU ' +
1240
+ 'starvation before redeploying. Defaults to the whole life of the deployment.',
1241
+ inputSchema: {
1242
+ request_id: z.string().describe('The request_id of the deployment.'),
1243
+ start_time: z.string().optional().describe('ISO 8601. Default: when the deployment started.'),
1244
+ end_time: z.string().optional().describe('ISO 8601. Default: now, or when it stopped.'),
1245
+ step: z.string().optional().describe('Averaging step, e.g. "30s" or "5m". Default: the API\'s.'),
1246
+ },
1247
+ annotations: { readOnlyHint: true, openWorldHint: true },
1248
+ }, async ({ request_id, start_time, end_time, step }) => guarded(auth, NOT_FOUND.deployment, async () => {
1249
+ const bad = checkRequestId(request_id);
1250
+ if (bad)
1251
+ return bad;
1252
+ const m = await client.getDeploymentMetrics(request_id, { start_time, end_time, steps: step });
1253
+ return ok({
1254
+ request_id,
1255
+ cpu: summarizeSeries(m.cpu),
1256
+ cpu_throttle_rate: summarizeSeries(m.cpu_throttle_rate),
1257
+ memory: summarizeSeries(m.mem),
1258
+ network_receive: summarizeSeries(m.network?.receive),
1259
+ network_transmit: summarizeSeries(m.network?.transmit),
1260
+ totals: m.total
1261
+ ? {
1262
+ received: summarizeSeries(m.total.receive_total)?.latest,
1263
+ transmitted: summarizeSeries(m.total.transmit_total)?.latest,
1264
+ disk_read: summarizeSeries(m.total.disk_read_total)?.latest,
1265
+ disk_written: summarizeSeries(m.total.disk_write_total)?.latest,
1266
+ }
1267
+ : undefined,
1268
+ note: 'Units are as the API labels them; values are averaged per step.',
1269
+ });
1270
+ }));
964
1271
  // ============================================= before the first deploy ====
965
1272
  // -------------------------------------------------------------- 11a ----
966
1273
  // Pure text generation: no token, no network, so it is always registered and
@@ -1227,11 +1534,7 @@ export function registerTools(server, client, config, auth) {
1227
1534
  }, async ({ image_name, page, limit }) => guard(auth, async () => {
1228
1535
  // Agents often pass the full reference they pushed. Reduce it to what
1229
1536
  // the API wants: no "registry.edgegap.com/" host, no ":tag".
1230
- const parts = image_name.replace(/@sha256:.*$/, '').split('/');
1231
- if (parts.length > 1 && /[.:]/.test(parts[0]))
1232
- parts.shift();
1233
- parts[parts.length - 1] = parts[parts.length - 1].replace(/:[^:]*$/, '');
1234
- let name = parts.join('/');
1537
+ let name = imageNameOnly(image_name);
1235
1538
  const query = { page, limit: limit ?? 20 };
1236
1539
  const notFound = (err) => err instanceof EdgegapApiError && err.status === 404;
1237
1540
  let res;
@@ -1277,6 +1580,64 @@ export function registerTools(server, client, config, auth) {
1277
1580
  tags,
1278
1581
  });
1279
1582
  }));
1583
+ // --------------------------------------------------------------- 13b ----
1584
+ if (mutating) {
1585
+ tool('edgegap_delete_registry_tag', {
1586
+ title: 'Delete one image tag from the Edgegap registry',
1587
+ description: 'Delete one tag, and the image it points to, from this organization\'s Edgegap container ' +
1588
+ 'registry, to clean up old builds. Takes exactly one image name and one exact tag; ' +
1589
+ 'wildcards, lists and "latest" are refused, and there is no bulk delete. A version that ' +
1590
+ 'still uses the tag can no longer start deployments, so check edgegap_list_app_versions ' +
1591
+ 'first. Cannot be undone.',
1592
+ inputSchema: {
1593
+ image_name: z.string().min(1).describe('The image name only, e.g. "my-game-server", as for edgegap_list_registry_tags.'),
1594
+ tag: z.string().describe('The exact tag to delete, e.g. "build-41".'),
1595
+ dry_run: dryRunParam,
1596
+ },
1597
+ annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
1598
+ }, async ({ image_name, tag, dry_run }) => guard(auth, async () => {
1599
+ let name = imageNameOnly(image_name);
1600
+ if (!/^[a-z0-9][a-z0-9._\/-]{0,254}$/.test(name)) {
1601
+ return fail(`"${image_name.slice(0, 80)}" is not a single image name. Pass one, e.g. "my-game-server".`);
1602
+ }
1603
+ if (badTag(tag) || tag.toLowerCase() === 'latest') {
1604
+ return fail(`"${tag.slice(0, 80)}" is not one exact tag. Pass a single tag as listed by edgegap_list_registry_tags; "latest" and wildcards are refused.`);
1605
+ }
1606
+ if (dry_run) {
1607
+ const dry = client.dryRun();
1608
+ await dry.client.deleteRegistryTag(name, tag);
1609
+ return dryRunResult(dry.requests, name !== image_name ? [`Looked up "${name}".`] : []);
1610
+ }
1611
+ const notFound = (err) => err instanceof EdgegapApiError && err.status === 404;
1612
+ try {
1613
+ let res;
1614
+ try {
1615
+ res = await client.deleteRegistryTag(name, tag);
1616
+ }
1617
+ catch (err) {
1618
+ // As in edgegap_list_registry_tags: "<project>/<image>" 404s, and
1619
+ // a 404 deleted nothing, so retry once without the project.
1620
+ if (!notFound(err) || !name.includes('/'))
1621
+ throw err;
1622
+ name = name.slice(name.indexOf('/') + 1);
1623
+ res = await client.deleteRegistryTag(name, tag);
1624
+ }
1625
+ return ok({
1626
+ image_name: name,
1627
+ deleted_tag: res.deleted_tag ?? tag,
1628
+ image_deleted: res.artifact?.artifact_deleted,
1629
+ freed_mb: res.artifact?.artifact_deleted ? res.artifact?.size_mb : undefined,
1630
+ tags_still_on_that_image: res.artifact?.remaining_tags?.length ? res.artifact.remaining_tags : undefined,
1631
+ });
1632
+ }
1633
+ catch (err) {
1634
+ if (notFound(err)) {
1635
+ return fail(`No tag "${tag}" on image "${name}" in this organization's registry. List tags with edgegap_list_registry_tags.`);
1636
+ }
1637
+ throw err;
1638
+ }
1639
+ }));
1640
+ }
1280
1641
  // ================================================== peer-to-peer relays ====
1281
1642
  // --------------------------------------------------------------- 14 ----
1282
1643
  if (mutating) {
@@ -1352,6 +1713,28 @@ export function registerTools(server, client, config, auth) {
1352
1713
  inputSchema: { session_id: z.string().describe('Returned by edgegap_create_relay_session.') },
1353
1714
  annotations: { readOnlyHint: true, openWorldHint: true },
1354
1715
  }, async ({ session_id }) => guarded(auth, NOT_FOUND.relay, async () => ok(compactRelay(await client.getRelaySession(session_id)))));
1716
+ // --------------------------------------------------------------- 15b ----
1717
+ tool('edgegap_list_relay_sessions', {
1718
+ title: 'List relay sessions',
1719
+ description: 'List this organization\'s active relay sessions: id, status, readiness and player count. ' +
1720
+ 'Relay sessions bill while open, so use this to find ones left over from earlier sessions ' +
1721
+ 'and delete them with edgegap_delete_relay_session. Authorization tokens are not listed; ' +
1722
+ 'read one session with edgegap_get_relay_session.',
1723
+ inputSchema: {},
1724
+ annotations: { readOnlyHint: true, openWorldHint: true },
1725
+ }, async () => guard(auth, async () => {
1726
+ const res = await client.listRelaySessions();
1727
+ const sessions = (res.sessions ?? []).map((r) => ({
1728
+ session_id: r.session_id,
1729
+ status: r.status,
1730
+ ready: r.ready,
1731
+ linked: r.linked,
1732
+ players: r.session_users?.length ?? 0,
1733
+ relay: r.relay?.host ?? r.relay?.ip ?? undefined,
1734
+ error: r.error || undefined,
1735
+ }));
1736
+ return ok({ ...pageInfo(res.total_count, sessions.length, 1), sessions });
1737
+ }));
1355
1738
  if (mutating) {
1356
1739
  // ------------------------------------------------------------- 16 ----
1357
1740
  tool('edgegap_authorize_relay_user', {
@@ -1378,6 +1761,31 @@ export function registerTools(server, client, config, auth) {
1378
1761
  session_authorization_token: res.authorization_token,
1379
1762
  });
1380
1763
  }));
1764
+ // ------------------------------------------------------------- 16b ----
1765
+ tool('edgegap_revoke_relay_user', {
1766
+ title: 'Remove a player from a relay session',
1767
+ description: 'Revoke one player\'s access to a relay session, by that player\'s authorization token ' +
1768
+ '(from edgegap_get_relay_session or edgegap_authorize_relay_user). The player loses the ' +
1769
+ 'relay connection; the session and the other players stay.',
1770
+ inputSchema: {
1771
+ session_id: z.string().describe('The relay session_id, e.g. "0724828881e2-S".'),
1772
+ user_authorization_token: z.number().int().describe('The player\'s authorization token, not the session\'s.'),
1773
+ dry_run: dryRunParam,
1774
+ },
1775
+ annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
1776
+ }, async ({ session_id, user_authorization_token, dry_run }) => guarded(auth, NOT_FOUND.relay, async () => {
1777
+ if (!SESSION_ID.test(session_id)) {
1778
+ return fail(`"${session_id.slice(0, 80)}" is not a single relay session_id. Pass exactly one, e.g. "0724828881e2-S".`);
1779
+ }
1780
+ const body = { session_id, authorization_token: user_authorization_token };
1781
+ if (dry_run) {
1782
+ const dry = client.dryRun();
1783
+ await dry.client.revokeRelayUser(body);
1784
+ return dryRunResult(dry.requests);
1785
+ }
1786
+ const res = await client.revokeRelayUser(body);
1787
+ return ok({ ...compactRelay(res), revoked: user_authorization_token });
1788
+ }));
1381
1789
  // ------------------------------------------------------------- 17 ----
1382
1790
  tool('edgegap_delete_relay_session', {
1383
1791
  title: 'Delete a relay session',
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.6.3';
6
+ export const VERSION = '0.7.0';
package/package.json CHANGED
@@ -1,14 +1,17 @@
1
1
  {
2
2
  "name": "@edgegap/mcp",
3
3
  "mcpName": "dev.edgegap/mcp",
4
- "version": "0.6.3",
4
+ "version": "0.7.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 && chmod +x dist/index.js dist/http.js",
9
9
  "typecheck": "tsc --noEmit",
10
10
  "typecheck:worker": "tsc -p worker/tsconfig.json --noEmit",
11
- "test": "node test/package.mjs && node test/skills.mjs && node test/smoke.mjs && node test/guards.mjs && node test/elicit.mjs && node test/newtools.mjs && node test/http.mjs",
11
+ "test": "node --test test/unit.test.mjs && node test/package.mjs && node test/skills.mjs && node test/smoke.mjs && node test/guards.mjs && node test/elicit.mjs && node test/newtools.mjs && node test/http.mjs && node test/spec.mjs && node test/snapshot.mjs",
12
+ "test:unit": "node --test test/unit.test.mjs",
13
+ "snapshot:update": "node test/snapshot.mjs --update",
14
+ "scan": "node scripts/scan-repo.mjs",
12
15
  "start:http": "node dist/index.js --http",
13
16
  "worker:dev": "wrangler dev --config worker/wrangler.jsonc --local --port 8787",
14
17
  "worker:check": "wrangler deploy --config worker/wrangler.jsonc --dry-run --outdir=.wrangler/dryrun",