@edgegap/mcp 0.3.2 → 0.4.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/dist/tools.js CHANGED
@@ -9,7 +9,8 @@
9
9
  */
10
10
  import { z } from 'zod';
11
11
  import { EdgegapApiError } from './client.js';
12
- import { assertAppAllowed, redact } from './config.js';
12
+ import { assertAppAllowed, redact, hostLabel } from './config.js';
13
+ import { VERSION } from './version.js';
13
14
  import { TokenUnavailableError } from './auth.js';
14
15
  import { validateServerConfig, PROTOCOLS, NETCODE_NAMES, } from './serverconfig.js';
15
16
  import { generateDockerfile, DockerfileInputError } from './dockerfile.js';
@@ -61,9 +62,13 @@ export function serverInstructions(mode) {
61
62
  '8. edgegap_stop_deployment when finished\n' +
62
63
  'To match players into those servers, edgegap_build_matchmaker_config produces the ' +
63
64
  'config the developer uploads in the dashboard.\n\n' +
64
- 'Deployments and relay sessions cost money while running. Tag test deployments, and ' +
65
- 'stop deployments and delete relay sessions you created before ending the task. If a ' +
65
+ 'Deployments and relay sessions cost money while running. Stop deployments and delete ' +
66
+ 'relay sessions you created before ending the task; edgegap_list_deployments with ' +
67
+ `only_agent_deployments: true lists every deployment tagged "${AGENT_TAG}". If a ` +
66
68
  'deployment errors, read the container logs before redeploying.\n\n' +
69
+ 'Guardrails: edgegap_context shows which API and limits this session has. Every tool that ' +
70
+ 'changes something takes dry_run: true to show the exact request and send nothing; use it ' +
71
+ 'when unsure. Never put the API token in env vars, tags or URLs: such calls are refused.\n\n' +
67
72
  credentials +
68
73
  'That token is org-wide and cannot be scoped by Edgegap, so it authorises far more than ' +
69
74
  'any single task needs. Treat it as a supervised credential: do not use it for work the ' +
@@ -74,6 +79,10 @@ export function serverInstructions(mode) {
74
79
  /** 1x1 transparent PNG. The create-app endpoint requires an image and agents
75
80
  * have no sensible one to supply; a placeholder beats a blocked flow. */
76
81
  const PLACEHOLDER_IMAGE = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
82
+ /** Port protocols, uppercased. The API accepts "WS" but returns "Websocket". */
83
+ const WS_PROTOCOLS = new Set(['WS', 'WEBSOCKET']);
84
+ /** tls_upgrade is only valid on WebSocket and HTTP ports (per the API spec). */
85
+ const TLS_PROTOCOLS = new Set(['WS', 'WEBSOCKET', 'HTTP']);
77
86
  const TERMINAL_OK = ['READY', 'STATUS_READY'];
78
87
  const TERMINAL_BAD = ['ERROR', 'STATUS_ERROR', 'TERMINATED', 'STATUS_TERMINATED'];
79
88
  function ok(payload, notice) {
@@ -85,9 +94,25 @@ function ok(payload, notice) {
85
94
  function fail(message) {
86
95
  return { content: [{ type: 'text', text: message }], isError: true };
87
96
  }
97
+ /**
98
+ * What a 404 means, per kind of resource. A 404 from Edgegap only says "not
99
+ * found"; which thing is missing, and what to do next, depends on the tool.
100
+ * One generic hint used to be attached to every 404, which sent agents to
101
+ * edgegap_list_apps for stopped deployments and missing registry images.
102
+ */
103
+ const NOT_FOUND = {
104
+ app: 'the application or version name does not exist. Call edgegap_list_apps, then ' +
105
+ 'edgegap_list_app_versions, to find the right names.',
106
+ deployment: 'no deployment with that request_id. It may have stopped and been cleaned up, or the ' +
107
+ 'request_id is wrong. Running deployments are listed by edgegap_list_deployments.',
108
+ logs: 'no logs for this deployment. Container logs only exist while a deployment is running; ' +
109
+ 'once it has stopped they are gone, unless Endpoint Storage was configured on the version ' +
110
+ 'before it ran. If it is still running, check the request_id with edgegap_list_deployments.',
111
+ relay: 'no relay session with that session_id. It may already have been deleted.',
112
+ };
88
113
  /** Wraps a handler so API errors come back as readable, self-correctable text
89
114
  * rather than a protocol-level exception the agent cannot act on. */
90
- function guard(auth, fn) {
115
+ function guard(auth, fn, notFound) {
91
116
  const handled = fn().catch((err) => {
92
117
  if (err instanceof TokenUnavailableError) {
93
118
  // Not a failure to correct — a decision the human made. Say so plainly
@@ -95,7 +120,7 @@ function guard(auth, fn) {
95
120
  return fail(err.message);
96
121
  }
97
122
  if (err instanceof EdgegapApiError) {
98
- const hint = errorHint(err);
123
+ const hint = errorHint(err, notFound);
99
124
  return fail(`${err.message}${hint ? `\n\nLikely cause: ${hint}` : ''}`);
100
125
  }
101
126
  return fail(redact(err.message ?? String(err), auth.current));
@@ -114,7 +139,11 @@ function guard(auth, fn) {
114
139
  };
115
140
  });
116
141
  }
117
- function errorHint(err) {
142
+ /** guard() with the 404 hint first, so it reads at the call site. */
143
+ function guarded(auth, notFound, fn) {
144
+ return guard(auth, fn, notFound);
145
+ }
146
+ function errorHint(err, notFound) {
118
147
  switch (err.status) {
119
148
  case 401:
120
149
  // Deliberately does not promise a re-prompt: the local server asks again
@@ -124,8 +153,16 @@ function errorHint(err) {
124
153
  'different organization. Check it at ' +
125
154
  'https://app.edgegap.com/user-settings?tab=tokens. The token has been ' +
126
155
  'discarded from this session.');
156
+ case 400:
157
+ // The deployment endpoints answer an unknown request_id with 400 ("Bad
158
+ // Request ID provided", or a generic "could not understand" for logs),
159
+ // not 404. Their only input is the request_id, so a 400 means that.
160
+ return notFound === NOT_FOUND.deployment || notFound === NOT_FOUND.logs ? notFound : undefined;
127
161
  case 404:
128
- return 'the application or version name does not exist. Call edgegap_list_apps first.';
162
+ // Only the tool knows what was not found; no hint beats a wrong one.
163
+ return notFound;
164
+ case 429:
165
+ return 'Edgegap rate-limited this token. Wait a few seconds before the next call, and do not retry in a loop.';
129
166
  case 409:
130
167
  return 'a resource with that name already exists. Pick a different name or reuse the existing one.';
131
168
  case 422:
@@ -208,10 +245,153 @@ function buildUsers(input) {
208
245
  }
209
246
  return users;
210
247
  }
248
+ // ================================================================ guardrails ====
249
+ /**
250
+ * Added to every deployment this server starts, whatever tags the caller
251
+ * passes, so agent deployments can always be found and cleaned up:
252
+ * edgegap_list_deployments with only_agent_deployments: true.
253
+ */
254
+ export const AGENT_TAG = 'edgegap-mcp';
255
+ /**
256
+ * A single Edgegap request_id ("61b1be8f54d9"). Anything else — empty, a
257
+ * wildcard, a list, whitespace — is refused before a stop is sent, so a stop
258
+ * can only ever hit the one deployment it names.
259
+ */
260
+ const REQUEST_ID = /^[A-Za-z0-9]{6,64}$/;
261
+ /** A single relay session_id, e.g. "0724828881e2-S". */
262
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-]{4,63}$/;
263
+ function checkRequestId(id) {
264
+ if (REQUEST_ID.test(id))
265
+ return undefined;
266
+ return fail(`"${id.slice(0, 80)}" is not a single request_id. Pass exactly one request_id, e.g. "61b1be8f54d9", ` +
267
+ 'as returned by edgegap_deploy or edgegap_list_deployments. Wildcards, lists and empty IDs ' +
268
+ 'are refused, and there is no bulk stop.');
269
+ }
270
+ /** The dry_run parameter every write tool takes. */
271
+ const dryRunParam = z
272
+ .boolean()
273
+ .optional()
274
+ .describe('Show the exact request (method, host, path, body) with secrets masked, and send nothing. ' +
275
+ 'Local checks still run. Use it to confirm a billable or destructive call before making it.');
276
+ function dryRunResult(requests, notes = []) {
277
+ return ok({
278
+ dry_run: true,
279
+ sent: false,
280
+ requests,
281
+ notes: notes.length ? notes : undefined,
282
+ next_step: 'Nothing was sent. Call again without dry_run to do it.',
283
+ });
284
+ }
285
+ /**
286
+ * Refuses to put the server's own API token into a container or a URL.
287
+ *
288
+ * Env vars, tags and webhook URLs end up in places the agent and other people
289
+ * can read — container environments, the dashboard, third-party endpoints. An
290
+ * agent that "helpfully" passes the token along (say, so the game server can
291
+ * call the API) would hand an org-wide credential to all of them. Nothing is
292
+ * sent when this fires, and the matching value is never echoed.
293
+ *
294
+ * Returns undefined when clean. In a dry run the token is only checked if this
295
+ * session already holds one: a dry run must not trigger the token prompt.
296
+ */
297
+ async function tokenLeak(auth, dryRun, fields) {
298
+ const token = dryRun ? auth.current : await auth.get();
299
+ if (!token)
300
+ return undefined;
301
+ const needles = [token, token.replace(/-/g, '')].filter((n) => n.length >= 16);
302
+ const hit = fields.find(([, v]) => v && needles.some((n) => v.toLowerCase().includes(n.toLowerCase())));
303
+ if (!hit)
304
+ return undefined;
305
+ return fail(`Refused: ${hit[0]} contains this server's Edgegap API token. Nothing was sent. ` +
306
+ 'The token is organization-wide; putting it in a container, tag or URL exposes it to ' +
307
+ 'everything that can read those. If the game server needs to call Edgegap, give it a ' +
308
+ 'separate, purpose-made credential, and never this one.');
309
+ }
310
+ /**
311
+ * How long a new deployment can run before Edgegap stops it, from the
312
+ * version's max_duration. The API takes no per-deployment limit, so this is
313
+ * the only bound there is, and the agent should hear it on every deploy.
314
+ */
315
+ function autoStop(maxDuration) {
316
+ if (maxDuration === undefined || maxDuration === null) {
317
+ return { auto_stop: 'unknown: the version did not report max_duration. Stop this deployment when done.' };
318
+ }
319
+ if (maxDuration <= 0) {
320
+ return {
321
+ auto_stop: 'none',
322
+ warning: 'This version has no max_duration, so the deployment runs and bills until it is stopped. ' +
323
+ 'Stop it with edgegap_stop_deployment when done, or give the version a max_duration.',
324
+ };
325
+ }
326
+ const hours = maxDuration >= 120 ? ` (${Math.round(maxDuration / 60)} hours)` : '';
327
+ return {
328
+ auto_stop_after_minutes: maxDuration,
329
+ ...(maxDuration > 60
330
+ ? {
331
+ warning: `Edgegap stops this deployment after ${maxDuration} minutes${hours}, the version's ` +
332
+ 'max_duration. Stop it yourself when done testing; versions created with ' +
333
+ 'edgegap_create_app_version are capped by EDGEGAP_MAX_DURATION_MINUTES instead.',
334
+ }
335
+ : {}),
336
+ };
337
+ }
338
+ /** Prepends "[api.edgegap.com]" (or "[custom · host]") to a tool result. */
339
+ function withHost(result, label) {
340
+ return { ...result, content: [{ type: 'text', text: `[${label}]` }, ...result.content] };
341
+ }
211
342
  export function registerTools(server, client, config, auth) {
212
343
  const mutating = !config.readOnly;
344
+ // Every result names the API host it came from, first, so a session pointed
345
+ // at a custom EDGEGAP_BASE_URL can never be mistaken for production.
346
+ const label = hostLabel(config);
347
+ const tool = ((name, def, cb) => server.registerTool(name, def, (async (...a) => withHost(await cb(...a), label))));
348
+ // ---------------------------------------------------------------- 0 ----
349
+ // No token, no network: describes this server's own configuration, so an
350
+ // agent can check where it is pointed and what is allowed before acting.
351
+ tool('edgegap_context', {
352
+ title: 'Show this Edgegap MCP server\'s configuration',
353
+ description: 'Report which Edgegap API this server talks to, its version, whether it is the local or ' +
354
+ 'hosted server, and the guardrails in force: read-only mode, application allowlist, ' +
355
+ 'max_duration ceiling, the tag forced onto every deployment, and which tools support ' +
356
+ 'dry_run. Call it first when unsure what this session is allowed to do, or before ' +
357
+ 'anything billable. Makes no API call and never shows the token.',
358
+ inputSchema: {},
359
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
360
+ }, async () => {
361
+ const hosted = config.transport === 'hosted';
362
+ return ok({
363
+ server: `@edgegap/mcp ${VERSION}`,
364
+ transport: hosted ? 'hosted (Streamable HTTP)' : 'local (stdio)',
365
+ api_host: label,
366
+ api_base_url: config.baseUrlV1,
367
+ token: hosted
368
+ ? auth.current
369
+ ? 'received on this request\'s Authorization header'
370
+ : 'none on this request: send it as an Authorization header'
371
+ : config.envToken
372
+ ? 'from EDGEGAP_API_TOKEN'
373
+ : auth.current
374
+ ? 'provided by the developer this session (memory only)'
375
+ : 'not yet provided: the developer is asked on first use',
376
+ token_scope: 'organization-wide (Edgegap cannot scope tokens)',
377
+ read_only: config.readOnly,
378
+ app_allowlist: config.appAllowlist.length ? config.appAllowlist : 'none (all applications)',
379
+ max_duration_ceiling_minutes: config.maxDurationCeiling,
380
+ forced_deploy_tag: AGENT_TAG,
381
+ guardrails: {
382
+ dry_run: mutating
383
+ ? 'deploy, stop_deployment, create_app, create_app_version, create/authorize/delete relay'
384
+ : 'n/a: read-only, no write tools are registered',
385
+ token_in_container: 'deploys and versions are refused if the API token appears in an env var, tag or webhook URL',
386
+ stop: 'one exact request_id per call; no bulk stop',
387
+ auto_stop: 'each deploy reports its version\'s max_duration; Edgegap has no per-deployment time limit',
388
+ results: `every result starts with [${label}]`,
389
+ },
390
+ user_agent: `edgegap-mcp/${VERSION} (<MCP client name>)`,
391
+ });
392
+ });
213
393
  // ---------------------------------------------------------------- 1 ----
214
- server.registerTool('edgegap_list_apps', {
394
+ tool('edgegap_list_apps', {
215
395
  title: 'List Edgegap applications',
216
396
  description: 'List the applications in the Edgegap organization. Start here before creating or ' +
217
397
  'deploying anything, so you reuse an existing application instead of making a duplicate. ' +
@@ -232,7 +412,7 @@ export function registerTools(server, client, config, auth) {
232
412
  }));
233
413
  // ---------------------------------------------------------------- 2 ----
234
414
  if (mutating) {
235
- server.registerTool('edgegap_create_app', {
415
+ tool('edgegap_create_app', {
236
416
  title: 'Create an Edgegap application',
237
417
  description: 'Create a new application to hold game server versions. Only call this after ' +
238
418
  'edgegap_list_apps confirms no suitable application exists. Creating an application ' +
@@ -244,15 +424,18 @@ export function registerTools(server, client, config, auth) {
244
424
  .max(64)
245
425
  .describe('Application name, 3-64 chars. Usually the game or project name.'),
246
426
  is_active: z.boolean().optional().describe('Whether deployments are allowed. Default true.'),
427
+ dry_run: dryRunParam,
247
428
  },
248
429
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
249
- }, async ({ name, is_active }) => guard(auth, async () => {
430
+ }, async ({ name, is_active, dry_run }) => guard(auth, async () => {
250
431
  assertAppAllowed(config, name);
251
- const res = await client.createApp({
252
- name,
253
- is_active: is_active ?? true,
254
- image: PLACEHOLDER_IMAGE,
255
- });
432
+ const body = { name, is_active: is_active ?? true, image: PLACEHOLDER_IMAGE };
433
+ if (dry_run) {
434
+ const dry = client.dryRun();
435
+ await dry.client.createApp(body);
436
+ return dryRunResult(dry.requests);
437
+ }
438
+ const res = await client.createApp(body);
256
439
  return ok({
257
440
  created: res.name,
258
441
  active: res.is_active,
@@ -261,32 +444,44 @@ export function registerTools(server, client, config, auth) {
261
444
  }));
262
445
  }
263
446
  // ---------------------------------------------------------------- 3 ----
264
- server.registerTool('edgegap_list_app_versions', {
447
+ tool('edgegap_list_app_versions', {
265
448
  title: 'List versions of an application',
266
- description: 'List the versions under an application, with their container image and resource ' +
267
- 'settings. Use this to find the version name to deploy, or to copy settings from a ' +
268
- 'working version when creating a new one.',
449
+ description: 'List the versions under an application, with their container image, resources, ports ' +
450
+ '(including whether TLS Upgrade is on, which browser/WebGL clients need for wss://) and ' +
451
+ 'whether a registry login is set for pulling the image. Use this to find the version ' +
452
+ 'name to deploy, to check a version is ready before deploying, or to copy settings from ' +
453
+ 'a working version when creating a new one.',
269
454
  inputSchema: {
270
455
  application: z.string().describe('Application name, as returned by edgegap_list_apps.'),
271
456
  },
272
457
  annotations: { readOnlyHint: true, openWorldHint: true },
273
- }, async ({ application }) => guard(auth, async () => {
274
- assertAppAllowed(config, application);
458
+ }, async ({ application }) =>
459
+ // Read-only, so not subject to EDGEGAP_APP_ALLOWLIST: the allowlist
460
+ // limits what the agent can create and deploy into, as documented.
461
+ guarded(auth, NOT_FOUND.app, async () => {
275
462
  const res = await client.listAppVersions(application);
276
463
  const versions = (res.versions ?? []).map((v) => ({
277
464
  name: v.name,
278
465
  active: v.is_active,
279
466
  image: [v.docker_repository, v.docker_image, v.docker_tag].filter(Boolean).join('/'),
467
+ // Whether a login is set, never the login itself: the API returns
468
+ // the registry token in this response.
469
+ registry_credentials_set: Boolean(v.private_username && v.private_token),
280
470
  cpu_units: v.req_cpu,
281
471
  memory_mb: v.req_memory,
282
472
  max_duration_minutes: v.max_duration,
283
- ports: v.ports?.map((p) => `${p.name ?? 'port'}:${p.port}/${p.protocol}`),
473
+ ports: v.ports?.map((p) => ({
474
+ name: p.name,
475
+ port: p.port,
476
+ protocol: p.protocol,
477
+ tls_upgrade: p.tls_upgrade ?? false,
478
+ })),
284
479
  }));
285
480
  return ok({ application, ...pageInfo(res.total_count, versions.length, 1), versions });
286
481
  }));
287
482
  // ---------------------------------------------------------------- 4 ----
288
483
  if (mutating) {
289
- server.registerTool('edgegap_create_app_version', {
484
+ tool('edgegap_create_app_version', {
290
485
  title: 'Create an application version',
291
486
  description: 'Register a container image as a deployable version of an application. The image must ' +
292
487
  'already be pushed to a registry that Edgegap can pull from (see ' +
@@ -319,10 +514,20 @@ export function registerTools(server, client, config, auth) {
319
514
  .boolean()
320
515
  .optional()
321
516
  .describe('Readiness check on this port. Default true.'),
517
+ tls_upgrade: z
518
+ .boolean()
519
+ .optional()
520
+ .describe('Edgegap terminates TLS on this port, so clients connect with wss:// or https://. ' +
521
+ 'Required for browser (WebGL) clients, which cannot use plain ws:// from an https page. ' +
522
+ 'WS and HTTP ports only. Default false.'),
322
523
  }))
323
524
  .min(1)
324
525
  .describe('Ports to expose. At least one is required for players to connect.'),
325
- registry_username: z.string().optional().describe('Registry username, for private images.'),
526
+ registry_username: z
527
+ .string()
528
+ .optional()
529
+ .describe('Registry username. Needed for private images, including images in your own ' +
530
+ 'registry.edgegap.com project: Edgegap pulls with this login, not your API token.'),
326
531
  registry_token: z.string().optional().describe('Registry password or token.'),
327
532
  max_duration_minutes: z
328
533
  .number()
@@ -336,18 +541,36 @@ export function registerTools(server, client, config, auth) {
336
541
  env: z
337
542
  .array(z.object({ key: z.string(), value: z.string() }))
338
543
  .optional()
339
- .describe('Environment variables injected into the container.'),
544
+ .describe('Environment variables injected into the container. Values are never echoed back.'),
545
+ dry_run: dryRunParam,
340
546
  },
341
547
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
342
- }, async (args) => guard(auth, async () => {
548
+ }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
343
549
  assertAppAllowed(config, args.application);
550
+ const leak = await tokenLeak(auth, args.dry_run, [
551
+ ...(args.env ?? []).flatMap((e) => [
552
+ [`env var name "${e.key.slice(0, 40)}"`, e.key],
553
+ [`the value of env var "${e.key.slice(0, 40)}"`, e.value],
554
+ ]),
555
+ ['registry_username', args.registry_username],
556
+ ['registry_token', args.registry_token],
557
+ ]);
558
+ if (leak)
559
+ return leak;
344
560
  if (args.memory_mb > args.cpu_units * 2) {
345
561
  return fail(`memory_mb (${args.memory_mb}) exceeds twice cpu_units (${args.cpu_units}). ` +
346
562
  `Edgegap rejects this. Either lower memory_mb to ${args.cpu_units * 2} or raise cpu_units.`);
347
563
  }
564
+ const badTls = args.ports.find((p) => p.tls_upgrade && !TLS_PROTOCOLS.has(p.protocol.toUpperCase()));
565
+ if (badTls) {
566
+ return fail(`Port ${badTls.port} is ${badTls.protocol}; tls_upgrade only works on WS and HTTP ports. ` +
567
+ 'Use protocol "WS" for a WebSocket server, or drop tls_upgrade.');
568
+ }
348
569
  const requested = args.max_duration_minutes ?? config.maxDurationCeiling;
349
570
  const capped = Math.min(requested, config.maxDurationCeiling);
350
- const res = await client.createAppVersion(args.application, {
571
+ const hasRegistryLogin = Boolean(args.registry_username && args.registry_token);
572
+ const edgegapRegistry = /(^|\/\/)registry\.edgegap\.com\/?$/.test(args.docker_repository.trim());
573
+ const body = {
351
574
  name: args.name,
352
575
  is_active: true,
353
576
  req_cpu: args.cpu_units,
@@ -364,26 +587,63 @@ export function registerTools(server, client, config, auth) {
364
587
  protocol: p.protocol,
365
588
  name: p.name ?? 'gameport',
366
589
  to_check: p.to_check ?? true,
590
+ tls_upgrade: p.tls_upgrade ?? false,
367
591
  })),
368
592
  envs: args.env?.map((e) => ({ key: e.key, value: e.value, is_hidden: false })),
369
- });
593
+ };
594
+ if (args.dry_run) {
595
+ const dry = client.dryRun();
596
+ await dry.client.createAppVersion(args.application, body);
597
+ return dryRunResult(dry.requests, capped < requested ? [`max_duration capped to ${capped} minutes by EDGEGAP_MAX_DURATION_MINUTES.`] : []);
598
+ }
599
+ let res;
600
+ try {
601
+ res = await client.createAppVersion(args.application, body);
602
+ }
603
+ catch (err) {
604
+ // verify_image pulls with the version's registry login. Without one
605
+ // — even for the org's own registry.edgegap.com project — Edgegap
606
+ // answers a bare 400 "Unable to login with the given credentials".
607
+ if (err instanceof EdgegapApiError && err.status === 400 && /login|credential/i.test(err.apiMessage)) {
608
+ return fail(registryLoginNeeded(args.docker_repository, hasRegistryLogin));
609
+ }
610
+ throw err;
611
+ }
612
+ const notes = [];
613
+ if (edgegapRegistry && !hasRegistryLogin) {
614
+ notes.push('No registry login was set. Edgegap pulls images from registry.edgegap.com with the ' +
615
+ 'version\'s registry login, not your API token, so deployments of this version will ' +
616
+ 'likely fail to pull (424) until the developer adds the Container Registry username ' +
617
+ 'and token to this version in the dashboard.');
618
+ }
619
+ for (const p of args.ports) {
620
+ if (WS_PROTOCOLS.has(p.protocol.toUpperCase()) && !p.tls_upgrade) {
621
+ notes.push(`Port ${p.port} is WebSocket without tls_upgrade. If clients run in a browser (WebGL), ` +
622
+ 'they need wss://: create the version with tls_upgrade: true on this port.');
623
+ }
624
+ }
370
625
  return ok({
371
626
  created: `${args.application}/${res.version?.name ?? args.name}`,
372
627
  max_duration_minutes: capped,
373
628
  capped_by_server: capped < requested ? config.maxDurationCeiling : undefined,
629
+ notes: notes.length ? notes : undefined,
374
630
  next_step: 'Call edgegap_deploy to start an instance.',
375
631
  });
376
632
  }));
377
633
  }
378
634
  // ---------------------------------------------------------------- 5 ----
379
635
  if (mutating) {
380
- server.registerTool('edgegap_deploy', {
636
+ tool('edgegap_deploy', {
381
637
  title: 'Deploy a game server',
382
638
  description: 'Start one authoritative dedicated game server from an application version, placed near ' +
383
639
  'the players you specify. This is the recommended way to host a multiplayer match: the ' +
384
640
  'server owns the game state, so no player hosts it. Returns immediately with a request_id; the server is still starting and ' +
385
641
  'has no connection details yet. Follow this call with edgegap_wait_for_deployment to ' +
386
- 'get the address players connect to. Always stop deployments you started for testing.',
642
+ 'get the address players connect to. Always stop deployments you started for testing. ' +
643
+ `Every deployment is tagged "${AGENT_TAG}" in addition to any tags you pass, so ` +
644
+ 'edgegap_list_deployments with only_agent_deployments: true finds them all. Runs until ' +
645
+ 'stopped or until the version\'s max_duration, which the result reports. Refused, with ' +
646
+ 'nothing sent, if the API token appears in an env var or tag.',
387
647
  inputSchema: {
388
648
  application: z.string().describe('Application name.'),
389
649
  version: z.string().describe('Version name within the application.'),
@@ -391,27 +651,40 @@ export function registerTools(server, client, config, auth) {
391
651
  env: z
392
652
  .array(z.object({ key: z.string(), value: z.string() }))
393
653
  .optional()
394
- .describe('Environment variables for this deployment only.'),
654
+ .describe('Environment variables for this deployment only. Values are never echoed back.'),
395
655
  tags: z
396
- .array(z.string())
656
+ .array(z.string().min(1).max(40))
397
657
  .optional()
398
- .describe('Tags for filtering later, e.g. ["agent-test"]. Recommended.'),
658
+ .describe(`Extra tags for filtering later, e.g. ["agent-test"]. "${AGENT_TAG}" is always added.`),
399
659
  cpu_units: z.number().int().min(256).optional().describe('Override the version CPU.'),
400
660
  memory_mb: z.number().int().min(256).optional().describe('Override the version memory.'),
661
+ dry_run: dryRunParam,
401
662
  },
402
663
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
403
- }, async (args) => guard(auth, async () => {
664
+ }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
404
665
  assertAppAllowed(config, args.application);
405
666
  const users = buildUsers(args.users);
406
667
  if (users.length === 0) {
407
668
  return fail('No player locations given. Supply users.ip_addresses (e.g. the developer\'s own ' +
408
669
  'public IP) or users.geo_coordinates. Edgegap needs at least one to choose a region.');
409
670
  }
671
+ // Forced, whatever the caller passed: the tag is how agent
672
+ // deployments are found and cleaned up, so it cannot be optional.
673
+ const tags = [...new Set([...(args.tags ?? []), AGENT_TAG])];
674
+ const leak = await tokenLeak(auth, args.dry_run, [
675
+ ...(args.env ?? []).flatMap((e) => [
676
+ [`env var name "${e.key.slice(0, 40)}"`, e.key],
677
+ [`the value of env var "${e.key.slice(0, 40)}"`, e.value],
678
+ ]),
679
+ ...tags.map((t) => [`tag "${t.slice(0, 8)}…"`, t]),
680
+ ]);
681
+ if (leak)
682
+ return leak;
410
683
  const body = {
411
684
  application: args.application,
412
685
  version: args.version,
413
686
  users,
414
- tags: args.tags ?? ['mcp'],
687
+ tags,
415
688
  };
416
689
  if (args.env) {
417
690
  body.environment_variables = args.env.map((e) => ({
@@ -423,16 +696,31 @@ export function registerTools(server, client, config, auth) {
423
696
  if (args.cpu_units && args.memory_mb) {
424
697
  body.resources = { cpu_units: args.cpu_units, memory_mib: args.memory_mb };
425
698
  }
699
+ if (args.dry_run) {
700
+ const dry = client.dryRun();
701
+ await dry.client.deploy(body);
702
+ return dryRunResult(dry.requests, [
703
+ `Tagged "${AGENT_TAG}" automatically.`,
704
+ 'Auto-stop comes from the version\'s max_duration; a real deploy reports it.',
705
+ ]);
706
+ }
707
+ // Edgegap has no per-deployment time limit: a deployment runs until
708
+ // stopped or until its version's max_duration (default 1440 minutes,
709
+ // a full day). Read it first so the agent knows how long an
710
+ // unstopped test server will keep billing.
711
+ const version = await client.getAppVersion(args.application, args.version);
426
712
  const res = await client.deploy(body);
427
713
  return ok({
428
714
  request_id: res.request_id,
429
715
  status: 'starting',
716
+ tags,
717
+ ...autoStop(version.max_duration),
430
718
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
431
719
  });
432
720
  }));
433
721
  }
434
722
  // ---------------------------------------------------------------- 6 ----
435
- server.registerTool('edgegap_get_deployment', {
723
+ tool('edgegap_get_deployment', {
436
724
  title: 'Get deployment status',
437
725
  description: 'Read the current status of one deployment, including connection address and ports once ' +
438
726
  'it is ready. For a deployment you just created, prefer edgegap_wait_for_deployment — it ' +
@@ -441,12 +729,12 @@ export function registerTools(server, client, config, auth) {
441
729
  request_id: z.string().describe('The request_id returned by edgegap_deploy.'),
442
730
  },
443
731
  annotations: { readOnlyHint: true, openWorldHint: true },
444
- }, async ({ request_id }) => guard(auth, async () => {
732
+ }, async ({ request_id }) => guarded(auth, NOT_FOUND.deployment, async () => {
445
733
  const d = await client.getDeployment(request_id);
446
734
  return ok(compactDeployment(d));
447
735
  }));
448
736
  // ---------------------------------------------------------------- 7 ----
449
- server.registerTool('edgegap_wait_for_deployment', {
737
+ tool('edgegap_wait_for_deployment', {
450
738
  title: 'Wait for a deployment to become ready',
451
739
  description: 'Poll a deployment until it is ready, errors, or the timeout expires, then return the ' +
452
740
  'connection details. This is the tool to call right after edgegap_deploy. Do not build ' +
@@ -463,7 +751,7 @@ export function registerTools(server, client, config, auth) {
463
751
  .describe('How long to wait before giving up. Default 180.'),
464
752
  },
465
753
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
466
- }, async ({ request_id, timeout_seconds }) => guard(auth, async () => {
754
+ }, async ({ request_id, timeout_seconds }) => guarded(auth, NOT_FOUND.deployment, async () => {
467
755
  const budgetMs = (timeout_seconds ?? 180) * 1000;
468
756
  const startedAt = Date.now();
469
757
  let intervalMs = 2000;
@@ -491,7 +779,7 @@ export function registerTools(server, client, config, auth) {
491
779
  `call edgegap_get_deployment to check again, or edgegap_stop_deployment to clean up.`);
492
780
  }));
493
781
  // ---------------------------------------------------------------- 8 ----
494
- server.registerTool('edgegap_list_deployments', {
782
+ tool('edgegap_list_deployments', {
495
783
  title: 'List running deployments',
496
784
  description: 'List active deployments, optionally filtered and sorted. Use this to find deployments left running ' +
497
785
  'from earlier sessions before starting new ones — orphaned servers cost money. ' +
@@ -499,8 +787,15 @@ export function registerTools(server, client, config, auth) {
499
787
  'e.g. [{field:"application",operator:"eq",value:"my-game"},{field:"status",operator:"eq",value:"ready"}]. ' +
500
788
  'Operators: eq and neq on every field except created_at (eq, gte, lte); in and nin with an array value ' +
501
789
  'on request_id, tags, application, version, fleet_name, host_name; ilike with % wildcards on fleet_name ' +
502
- 'and host_name. At most one filter per field. Sort by created_at or available_session_sockets.',
790
+ 'and host_name. At most one filter per field. Sort by created_at or available_session_sockets. ' +
791
+ `To find every deployment an agent started through this server, pass only_agent_deployments: true ` +
792
+ `(the same as filtering tags in ["${AGENT_TAG}", "mcp"]).`,
503
793
  inputSchema: {
794
+ only_agent_deployments: z
795
+ .boolean()
796
+ .optional()
797
+ .describe(`Only deployments started through this server: tagged "${AGENT_TAG}", or "mcp" by versions ` +
798
+ 'up to 0.3.3. Cannot be combined with a tags filter.'),
504
799
  filters: z
505
800
  .array(z.object({
506
801
  field: z.enum([
@@ -524,7 +819,14 @@ export function registerTools(server, client, config, auth) {
524
819
  limit: z.number().int().min(1).max(100).optional().describe('Default 50.'),
525
820
  },
526
821
  annotations: { readOnlyHint: true, openWorldHint: true },
527
- }, async ({ filters, order_by, limit }) => guard(auth, async () => {
822
+ }, async ({ only_agent_deployments, filters: given, order_by, limit }) => guard(auth, async () => {
823
+ let filters = given;
824
+ if (only_agent_deployments) {
825
+ if (given?.some((f) => f.field === 'tags')) {
826
+ return fail('only_agent_deployments already filters on tags. Drop the tags filter, or drop only_agent_deployments.');
827
+ }
828
+ filters = [...(given ?? []), { field: 'tags', operator: 'in', value: [AGENT_TAG, 'mcp'] }];
829
+ }
528
830
  const fields = (filters ?? []).map((f) => f.field);
529
831
  const repeated = fields.find((f, i) => fields.indexOf(f) !== i);
530
832
  if (repeated) {
@@ -545,22 +847,32 @@ export function registerTools(server, client, config, auth) {
545
847
  }));
546
848
  // ---------------------------------------------------------------- 9 ----
547
849
  if (mutating) {
548
- server.registerTool('edgegap_stop_deployment', {
850
+ tool('edgegap_stop_deployment', {
549
851
  title: 'Stop a deployment',
550
852
  description: 'Gracefully stop one deployment by request_id, sending SIGTERM to the container. ' +
551
853
  'Stop every deployment you started for testing before ending your task. This tool ' +
552
- 'stops exactly one deployment; bulk stop is deliberately not exposed.',
854
+ 'stops exactly one deployment, named by its exact request_id: empty IDs, wildcards ' +
855
+ 'and lists are refused, and bulk stop is deliberately not exposed.',
553
856
  inputSchema: {
554
- request_id: z.string().describe('The request_id of the deployment to stop.'),
857
+ request_id: z.string().describe('The exact request_id of the one deployment to stop, e.g. "61b1be8f54d9".'),
858
+ dry_run: dryRunParam,
555
859
  },
556
860
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
557
- }, async ({ request_id }) => guard(auth, async () => {
861
+ }, async ({ request_id, dry_run }) => guarded(auth, NOT_FOUND.deployment, async () => {
862
+ const bad = checkRequestId(request_id);
863
+ if (bad)
864
+ return bad;
865
+ if (dry_run) {
866
+ const dry = client.dryRun();
867
+ await dry.client.stopDeployment(request_id);
868
+ return dryRunResult(dry.requests);
869
+ }
558
870
  const res = await client.stopDeployment(request_id);
559
871
  return ok({ request_id, result: res.message ?? 'stop requested' });
560
872
  }));
561
873
  }
562
874
  // --------------------------------------------------------------- 10 ----
563
- server.registerTool('edgegap_get_deployment_logs', {
875
+ tool('edgegap_get_deployment_logs', {
564
876
  title: 'Get container logs for a deployment',
565
877
  description: 'Retrieve stdout/stderr and crash output for a deployment. Call this whenever a ' +
566
878
  'deployment errors or a server exits unexpectedly — the crash exit code usually ' +
@@ -577,7 +889,7 @@ export function registerTools(server, client, config, auth) {
577
889
  .describe('Truncate logs to this length, keeping the tail. Default 8000.'),
578
890
  },
579
891
  annotations: { readOnlyHint: true, openWorldHint: true },
580
- }, async ({ request_id, max_characters }) => guard(auth, async () => {
892
+ }, async ({ request_id, max_characters }) => guarded(auth, NOT_FOUND.logs, async () => {
581
893
  const res = await client.getDeploymentLogs(request_id);
582
894
  const cap = max_characters ?? 8000;
583
895
  const tail = (s) => !s ? undefined : s.length > cap ? `...[truncated]...\n${s.slice(-cap)}` : s;
@@ -595,7 +907,7 @@ export function registerTools(server, client, config, auth) {
595
907
  // -------------------------------------------------------------- 11a ----
596
908
  // Pure text generation: no token, no network, so it is always registered and
597
909
  // never goes through guard().
598
- server.registerTool('edgegap_generate_dockerfile', {
910
+ tool('edgegap_generate_dockerfile', {
599
911
  title: 'Generate a game server Dockerfile',
600
912
  description: 'Write a Dockerfile for this project\'s headless game server build, ready for Edgegap: ' +
601
913
  'linux/amd64 base, the build folder copied in, the binary made executable, the right ' +
@@ -624,6 +936,7 @@ export function registerTools(server, client, config, auth) {
624
936
  port: z.number().int().min(1).max(59999),
625
937
  protocol: z.enum(PROTOCOLS),
626
938
  name: z.string().optional(),
939
+ tls_upgrade: z.boolean().optional().describe('TLS Upgrade (wss/https) on a WS or HTTP port, for browser clients.'),
627
940
  }))
628
941
  .optional()
629
942
  .describe('Ports the server listens on. Default: 7777, with the protocol the netcode uses (UDP if unknown).'),
@@ -683,7 +996,7 @@ export function registerTools(server, client, config, auth) {
683
996
  // --------------------------------------------------------------- 11 ----
684
997
  // Pure text analysis: no token, no network, so it is always registered and
685
998
  // never goes through guard().
686
- server.registerTool('edgegap_validate_server_config', {
999
+ tool('edgegap_validate_server_config', {
687
1000
  title: 'Validate a game server Dockerfile and port config',
688
1001
  description: 'Check a game server Dockerfile and the ports/resources you intend to register against ' +
689
1002
  'what Edgegap requires, BEFORE building and pushing. Catches the failures that otherwise ' +
@@ -708,6 +1021,7 @@ export function registerTools(server, client, config, auth) {
708
1021
  port: z.number().int(),
709
1022
  protocol: z.string(),
710
1023
  name: z.string().optional(),
1024
+ tls_upgrade: z.boolean().optional().describe('TLS Upgrade (wss/https) on a WS or HTTP port, for browser clients.'),
711
1025
  }))
712
1026
  .optional()
713
1027
  .describe('Ports you plan to pass to edgegap_create_app_version.'),
@@ -750,7 +1064,7 @@ export function registerTools(server, client, config, auth) {
750
1064
  // Mutating-only: it can provision the registry project, and it hands a
751
1065
  // secret to the agent. A read-only session has no business receiving one.
752
1066
  if (mutating) {
753
- server.registerTool('edgegap_get_registry_credentials', {
1067
+ tool('edgegap_get_registry_credentials', {
754
1068
  title: 'Get Edgegap container registry push credentials',
755
1069
  description: 'Get the push login for this organization\'s private Edgegap container registry ' +
756
1070
  '(registry.edgegap.com) and the exact docker login, build and push commands for your ' +
@@ -837,7 +1151,7 @@ export function registerTools(server, client, config, auth) {
837
1151
  }));
838
1152
  }
839
1153
  // --------------------------------------------------------------- 13 ----
840
- server.registerTool('edgegap_list_registry_tags', {
1154
+ tool('edgegap_list_registry_tags', {
841
1155
  title: 'List image tags in the Edgegap registry',
842
1156
  description: 'List the tags pushed for one image in this organization\'s Edgegap container registry, ' +
843
1157
  'with push time and size. Call it after docker push to confirm the tag landed before ' +
@@ -908,7 +1222,7 @@ export function registerTools(server, client, config, auth) {
908
1222
  // ================================================== peer-to-peer relays ====
909
1223
  // --------------------------------------------------------------- 14 ----
910
1224
  if (mutating) {
911
- server.registerTool('edgegap_create_relay_session', {
1225
+ tool('edgegap_create_relay_session', {
912
1226
  title: 'Create a relay session (host-client games only)',
913
1227
  description: 'A relay is NOT a game server and is not the recommended default — for a multiplayer ' +
914
1228
  'match, deploy an authoritative dedicated server with edgegap_deploy instead. A relay ' +
@@ -930,13 +1244,20 @@ export function registerTools(server, client, config, auth) {
930
1244
  webhook_url: z.string().url().optional().describe('Called when the session is ready.'),
931
1245
  wait_until_ready: z.boolean().optional().describe('Poll until the relay is assigned. Default true.'),
932
1246
  timeout_seconds: z.number().int().min(5).max(120).optional().describe('Default 30.'),
1247
+ dry_run: dryRunParam,
933
1248
  },
934
1249
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
935
- }, async ({ user_ips, webhook_url, wait_until_ready, timeout_seconds }) => guard(auth, async () => {
936
- const created = await client.createRelaySession({
937
- users: user_ips.map((ip) => ({ ip })),
938
- ...(webhook_url ? { webhook_url } : {}),
939
- });
1250
+ }, async ({ user_ips, webhook_url, wait_until_ready, timeout_seconds, dry_run }) => guard(auth, async () => {
1251
+ const leak = await tokenLeak(auth, dry_run, [['webhook_url', webhook_url]]);
1252
+ if (leak)
1253
+ return leak;
1254
+ const body = { users: user_ips.map((ip) => ({ ip })), ...(webhook_url ? { webhook_url } : {}) };
1255
+ if (dry_run) {
1256
+ const dry = client.dryRun();
1257
+ await dry.client.createRelaySession(body);
1258
+ return dryRunResult(dry.requests);
1259
+ }
1260
+ const created = await client.createRelaySession(body);
940
1261
  if (wait_until_ready === false) {
941
1262
  return ok({
942
1263
  ...compactRelay(created),
@@ -965,26 +1286,32 @@ export function registerTools(server, client, config, auth) {
965
1286
  }));
966
1287
  }
967
1288
  // --------------------------------------------------------------- 15 ----
968
- server.registerTool('edgegap_get_relay_session', {
1289
+ tool('edgegap_get_relay_session', {
969
1290
  title: 'Get a relay session',
970
1291
  description: 'Read one relay session: whether it is ready, the relay address and ports, and each ' +
971
1292
  'authorized player with their authorization token. edgegap_create_relay_session already ' +
972
1293
  'waits for readiness; use this to re-read a session or one created with wait_until_ready false.',
973
1294
  inputSchema: { session_id: z.string().describe('Returned by edgegap_create_relay_session.') },
974
1295
  annotations: { readOnlyHint: true, openWorldHint: true },
975
- }, async ({ session_id }) => guard(auth, async () => ok(compactRelay(await client.getRelaySession(session_id)))));
1296
+ }, async ({ session_id }) => guarded(auth, NOT_FOUND.relay, async () => ok(compactRelay(await client.getRelaySession(session_id)))));
976
1297
  if (mutating) {
977
1298
  // ------------------------------------------------------------- 16 ----
978
- server.registerTool('edgegap_authorize_relay_user', {
1299
+ tool('edgegap_authorize_relay_user', {
979
1300
  title: 'Add a player to a relay session',
980
1301
  description: 'Authorize one more player (by public IP) on an existing relay session, for a player ' +
981
1302
  'joining after the session was created. Returns that player\'s authorization token.',
982
1303
  inputSchema: {
983
1304
  session_id: z.string(),
984
1305
  user_ip: z.string().min(3).describe('Public IP of the joining player.'),
1306
+ dry_run: dryRunParam,
985
1307
  },
986
1308
  annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
987
- }, async ({ session_id, user_ip }) => guard(auth, async () => {
1309
+ }, async ({ session_id, user_ip, dry_run }) => guarded(auth, NOT_FOUND.relay, async () => {
1310
+ if (dry_run) {
1311
+ const dry = client.dryRun();
1312
+ await dry.client.authorizeRelayUser({ session_id, user_ip });
1313
+ return dryRunResult(dry.requests);
1314
+ }
988
1315
  const res = await client.authorizeRelayUser({ session_id, user_ip });
989
1316
  return ok({
990
1317
  session_id: res.session_id,
@@ -994,13 +1321,25 @@ export function registerTools(server, client, config, auth) {
994
1321
  });
995
1322
  }));
996
1323
  // ------------------------------------------------------------- 17 ----
997
- server.registerTool('edgegap_delete_relay_session', {
1324
+ tool('edgegap_delete_relay_session', {
998
1325
  title: 'Delete a relay session',
999
1326
  description: 'Close one relay session. Connected players lose their relay connection. Delete every ' +
1000
- 'session you created for testing before ending your task.',
1001
- inputSchema: { session_id: z.string() },
1327
+ 'session you created for testing before ending your task. Takes exactly one session_id; ' +
1328
+ 'empty IDs, wildcards and lists are refused.',
1329
+ inputSchema: {
1330
+ session_id: z.string().describe('The exact session_id of the one session to delete, e.g. "0724828881e2-S".'),
1331
+ dry_run: dryRunParam,
1332
+ },
1002
1333
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
1003
- }, async ({ session_id }) => guard(auth, async () => {
1334
+ }, async ({ session_id, dry_run }) => guarded(auth, NOT_FOUND.relay, async () => {
1335
+ if (!SESSION_ID.test(session_id)) {
1336
+ return fail(`"${session_id.slice(0, 80)}" is not a single relay session_id. Pass exactly one, e.g. "0724828881e2-S".`);
1337
+ }
1338
+ if (dry_run) {
1339
+ const dry = client.dryRun();
1340
+ await dry.client.deleteRelaySession(session_id);
1341
+ return dryRunResult(dry.requests);
1342
+ }
1004
1343
  await client.deleteRelaySession(session_id);
1005
1344
  return ok({ session_id, result: 'deleted' });
1006
1345
  }));
@@ -1010,7 +1349,7 @@ export function registerTools(server, client, config, auth) {
1010
1349
  // Edgegap has no public API to create a matchmaker, so this does not create
1011
1350
  // one. It produces the configuration the dashboard asks for, checked against
1012
1351
  // the application version it points at.
1013
- server.registerTool('edgegap_build_matchmaker_config', {
1352
+ tool('edgegap_build_matchmaker_config', {
1014
1353
  title: 'Build a basic matchmaker configuration',
1015
1354
  description: 'Generate a ready-to-upload Edgegap matchmaker JSON configuration with one profile: team ' +
1016
1355
  'count and size, optional latency rule, and optional expansions that relax the rules the ' +
@@ -1044,9 +1383,15 @@ export function registerTools(server, client, config, auth) {
1044
1383
  ticket_expiration: z.string().optional().describe('Default "5m".'),
1045
1384
  inspect: z.boolean().optional().describe('Expose the inspection API for debugging. Default true; turn off for production.'),
1046
1385
  verify_version: z.boolean().optional().describe('Look up the application version first. Default true.'),
1386
+ allowed_cors_origins: z
1387
+ .array(z.string())
1388
+ .optional()
1389
+ .describe('Origins of web pages allowed to call the matchmaker, e.g. ["https://mygame.example.com", ' +
1390
+ '"http://localhost:8080"]. Required when game clients run in a browser (WebGL): browsers ' +
1391
+ 'block matchmaker calls from any origin not listed. Scheme and host only, no path.'),
1047
1392
  },
1048
1393
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
1049
- }, async (args) => guard(auth, async () => {
1394
+ }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
1050
1395
  assertAppAllowed(config, args.application);
1051
1396
  const { config: mmConfig, problems, cautions } = buildMatchmakerConfig(args);
1052
1397
  if (args.verify_version !== false) {
@@ -1087,6 +1432,9 @@ export function registerTools(server, client, config, auth) {
1087
1432
  'The dashboard then shows the matchmaker API URL and auth token. Game clients call POST {api_url}/tickets ' +
1088
1433
  `with header "Authorization: <auth token>" and profile "${args.profile_name}", then poll GET {api_url}/memberships/{id} until it returns the server address.`,
1089
1434
  'That auth token is safe to ship in game clients: it grants no access to the Edgegap API.',
1435
+ args.allowed_cors_origins?.length
1436
+ ? `Browser clients are allowed from: ${args.allowed_cors_origins.join(', ')}. Add any other origin the game is served from (each staging or production URL) before uploading.`
1437
+ : 'If game clients run in a browser (WebGL), set allowed_cors_origins to the origin of every page that serves the game, including http://localhost:<port> for local testing, or browsers will block the matchmaker calls.',
1090
1438
  ],
1091
1439
  });
1092
1440
  }));
@@ -1117,6 +1465,26 @@ function registryCredentialsUnavailable(imageName, tag) {
1117
1465
  'Or push to any other registry Edgegap can pull from (Docker Hub, GHCR, ECR, GCR, GitLab) ' +
1118
1466
  'and pass its registry_username/registry_token to edgegap_create_app_version.');
1119
1467
  }
1468
+ /**
1469
+ * What edgegap_create_app_version says when Edgegap could not log in to the
1470
+ * registry to verify the image. The agent should not be handed the registry
1471
+ * login just to get past this, so the dashboard route comes first.
1472
+ */
1473
+ function registryLoginNeeded(repository, hadLogin) {
1474
+ return (`Edgegap could not log in to ${repository} to verify the image, so the version was not ` +
1475
+ 'created. ' +
1476
+ (hadLogin
1477
+ ? 'The registry_username/registry_token given were rejected: check them.'
1478
+ : 'Edgegap pulls images with a registry login set on the version, not your API token — ' +
1479
+ 'this applies to your own registry.edgegap.com project too.') +
1480
+ '\n\nOptions:\n' +
1481
+ '1. Create the version again with verify_image false, then have the developer open it in ' +
1482
+ `the dashboard (${DASHBOARD_URL}) and add the registry username and token (for ` +
1483
+ 'registry.edgegap.com, the ones on the Container Registry page). Deployments fail to pull ' +
1484
+ 'until they do.\n' +
1485
+ '2. If the developer chooses to give them to you, pass registry_username and registry_token. ' +
1486
+ 'They are registry-scoped, not the org API token. Do not write them into files.');
1487
+ }
1120
1488
  /** Trims a relay session down to what a game client integration needs. */
1121
1489
  function compactRelay(s) {
1122
1490
  return {