@edgegap/mcp 0.3.3 → 0.5.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,11 +9,13 @@
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';
16
17
  import { buildMatchmakerConfig, DASHBOARD_URL } from './matchmaker.js';
18
+ import { SKILLS_PACK, findSkill, findSkillFile, fileIndex, mimeType, skillUri } from './skills.js';
17
19
  /**
18
20
  * The one definition of "dedicated server vs relay" this server gives agents.
19
21
  * Used in the server instructions, the relay tool description, and every relay
@@ -49,6 +51,10 @@ export function serverInstructions(mode) {
49
51
  'server per match; relays exist for games built host-client.\n\n' +
50
52
  ARCHITECTURE_GUIDANCE +
51
53
  '\n\n' +
54
+ 'Skills: before working on a game project, load the matching Edgegap skill with ' +
55
+ 'edgegap_get_skill (edgegap-unity for Unity, edgegap-unreal for Unreal Engine, edgegap for ' +
56
+ 'any other engine or platform questions). They hold the tested workflow, templates and known ' +
57
+ 'pitfalls; follow them over general knowledge. edgegap_list_skills lists them all.\n\n' +
52
58
  'Golden path for a first dedicated-server deployment:\n' +
53
59
  '1. edgegap_generate_dockerfile if the project has no Dockerfile, or ' +
54
60
  'edgegap_validate_server_config on the one it has, before building\n' +
@@ -61,9 +67,13 @@ export function serverInstructions(mode) {
61
67
  '8. edgegap_stop_deployment when finished\n' +
62
68
  'To match players into those servers, edgegap_build_matchmaker_config produces the ' +
63
69
  '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 ' +
70
+ 'Deployments and relay sessions cost money while running. Stop deployments and delete ' +
71
+ 'relay sessions you created before ending the task; edgegap_list_deployments with ' +
72
+ `only_agent_deployments: true lists every deployment tagged "${AGENT_TAG}". If a ` +
66
73
  'deployment errors, read the container logs before redeploying.\n\n' +
74
+ 'Guardrails: edgegap_context shows which API and limits this session has. Every tool that ' +
75
+ 'changes something takes dry_run: true to show the exact request and send nothing; use it ' +
76
+ 'when unsure. Never put the API token in env vars, tags or URLs: such calls are refused.\n\n' +
67
77
  credentials +
68
78
  'That token is org-wide and cannot be scoped by Edgegap, so it authorises far more than ' +
69
79
  'any single task needs. Treat it as a supervised credential: do not use it for work the ' +
@@ -240,10 +250,186 @@ function buildUsers(input) {
240
250
  }
241
251
  return users;
242
252
  }
243
- export function registerTools(server, client, config, auth) {
253
+ // ================================================================ guardrails ====
254
+ /**
255
+ * Added to every deployment this server starts, whatever tags the caller
256
+ * passes, so agent deployments can always be found and cleaned up:
257
+ * edgegap_list_deployments with only_agent_deployments: true.
258
+ */
259
+ export const AGENT_TAG = 'edgegap-mcp';
260
+ /**
261
+ * A single Edgegap request_id ("61b1be8f54d9"). Anything else — empty, a
262
+ * wildcard, a list, whitespace — is refused before a stop is sent, so a stop
263
+ * can only ever hit the one deployment it names.
264
+ */
265
+ const REQUEST_ID = /^[A-Za-z0-9]{6,64}$/;
266
+ /** A single relay session_id, e.g. "0724828881e2-S". */
267
+ const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9-]{4,63}$/;
268
+ function checkRequestId(id) {
269
+ if (REQUEST_ID.test(id))
270
+ return undefined;
271
+ return fail(`"${id.slice(0, 80)}" is not a single request_id. Pass exactly one request_id, e.g. "61b1be8f54d9", ` +
272
+ 'as returned by edgegap_deploy or edgegap_list_deployments. Wildcards, lists and empty IDs ' +
273
+ 'are refused, and there is no bulk stop.');
274
+ }
275
+ /** The dry_run parameter every write tool takes. */
276
+ const dryRunParam = z
277
+ .boolean()
278
+ .optional()
279
+ .describe('Show the exact request (method, host, path, body) with secrets masked, and send nothing. ' +
280
+ 'Local checks still run. Use it to confirm a billable or destructive call before making it.');
281
+ function dryRunResult(requests, notes = []) {
282
+ return ok({
283
+ dry_run: true,
284
+ sent: false,
285
+ requests,
286
+ notes: notes.length ? notes : undefined,
287
+ next_step: 'Nothing was sent. Call again without dry_run to do it.',
288
+ });
289
+ }
290
+ /**
291
+ * Refuses to put the server's own API token into a container or a URL.
292
+ *
293
+ * Env vars, tags and webhook URLs end up in places the agent and other people
294
+ * can read — container environments, the dashboard, third-party endpoints. An
295
+ * agent that "helpfully" passes the token along (say, so the game server can
296
+ * call the API) would hand an org-wide credential to all of them. Nothing is
297
+ * sent when this fires, and the matching value is never echoed.
298
+ *
299
+ * Returns undefined when clean. In a dry run the token is only checked if this
300
+ * session already holds one: a dry run must not trigger the token prompt.
301
+ */
302
+ async function tokenLeak(auth, dryRun, fields) {
303
+ const token = dryRun ? auth.current : await auth.get();
304
+ if (!token)
305
+ return undefined;
306
+ const needles = [token, token.replace(/-/g, '')].filter((n) => n.length >= 16);
307
+ const hit = fields.find(([, v]) => v && needles.some((n) => v.toLowerCase().includes(n.toLowerCase())));
308
+ if (!hit)
309
+ return undefined;
310
+ return fail(`Refused: ${hit[0]} contains this server's Edgegap API token. Nothing was sent. ` +
311
+ 'The token is organization-wide; putting it in a container, tag or URL exposes it to ' +
312
+ 'everything that can read those. If the game server needs to call Edgegap, give it a ' +
313
+ 'separate, purpose-made credential, and never this one.');
314
+ }
315
+ /**
316
+ * How long a new deployment can run before Edgegap stops it, from the
317
+ * version's max_duration. The API takes no per-deployment limit, so this is
318
+ * the only bound there is, and the agent should hear it on every deploy.
319
+ */
320
+ function autoStop(maxDuration) {
321
+ if (maxDuration === undefined || maxDuration === null) {
322
+ return { auto_stop: 'unknown: the version did not report max_duration. Stop this deployment when done.' };
323
+ }
324
+ if (maxDuration <= 0) {
325
+ return {
326
+ auto_stop: 'none',
327
+ warning: 'This version has no max_duration, so the deployment runs and bills until it is stopped. ' +
328
+ 'Stop it with edgegap_stop_deployment when done, or give the version a max_duration.',
329
+ };
330
+ }
331
+ const hours = maxDuration >= 120 ? ` (${Math.round(maxDuration / 60)} hours)` : '';
332
+ return {
333
+ auto_stop_after_minutes: maxDuration,
334
+ ...(maxDuration > 60
335
+ ? {
336
+ warning: `Edgegap stops this deployment after ${maxDuration} minutes${hours}, the version's ` +
337
+ 'max_duration. Stop it yourself when done testing; versions created with ' +
338
+ 'edgegap_create_app_version are capped by EDGEGAP_MAX_DURATION_MINUTES instead.',
339
+ }
340
+ : {}),
341
+ };
342
+ }
343
+ function toolCallEvent(name, input, result, started) {
344
+ const args = (input && typeof input === 'object' ? input : {});
345
+ const text = result.content.map((c) => c.text).join('\n');
346
+ const status = text.match(/Edgegap API (\d{3})\b/)?.[1];
347
+ const event = {
348
+ tool: name,
349
+ success: !result.isError,
350
+ duration_ms: Date.now() - started,
351
+ dry_run: args.dry_run === true,
352
+ };
353
+ if (result.isError) {
354
+ event.error_kind = status ? 'api' : /^Refused|is not a single|not in EDGEGAP_APP_ALLOWLIST/m.test(text) ? 'refused' : 'other';
355
+ if (status)
356
+ event.error_status = Number(status);
357
+ }
358
+ if (name === 'edgegap_get_skill' && typeof args.skill === 'string')
359
+ event.skill = args.skill.slice(0, 80);
360
+ return event;
361
+ }
362
+ /** Prepends "[api.edgegap.com]" (or "[custom · host]") to a tool result. */
363
+ function withHost(result, label) {
364
+ return { ...result, content: [{ type: 'text', text: `[${label}]` }, ...result.content] };
365
+ }
366
+ export function registerTools(server, client, config, auth, hooks = {}) {
244
367
  const mutating = !config.readOnly;
368
+ // Every result names the API host it came from, first, so a session pointed
369
+ // at a custom EDGEGAP_BASE_URL can never be mistaken for production.
370
+ // The optional hook (the hosted Worker's analytics) sees each call's outcome.
371
+ const label = hostLabel(config);
372
+ const tool = ((name, def, cb) => server.registerTool(name, def, (async (...a) => {
373
+ const started = Date.now();
374
+ const result = await cb(...a);
375
+ if (hooks.onToolCall) {
376
+ try {
377
+ hooks.onToolCall(toolCallEvent(name, a[0], result, started));
378
+ }
379
+ catch {
380
+ // Analytics must never affect a tool result.
381
+ }
382
+ }
383
+ return withHost(result, label);
384
+ })));
385
+ // ---------------------------------------------------------------- 0 ----
386
+ // No token, no network: describes this server's own configuration, so an
387
+ // agent can check where it is pointed and what is allowed before acting.
388
+ tool('edgegap_context', {
389
+ title: 'Show this Edgegap MCP server\'s configuration',
390
+ description: 'Report which Edgegap API this server talks to, its version, whether it is the local or ' +
391
+ 'hosted server, and the guardrails in force: read-only mode, application allowlist, ' +
392
+ 'max_duration ceiling, the tag forced onto every deployment, and which tools support ' +
393
+ 'dry_run. Call it first when unsure what this session is allowed to do, or before ' +
394
+ 'anything billable. Makes no API call and never shows the token.',
395
+ inputSchema: {},
396
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
397
+ }, async () => {
398
+ const hosted = config.transport === 'hosted';
399
+ return ok({
400
+ server: `@edgegap/mcp ${VERSION}`,
401
+ transport: hosted ? 'hosted (Streamable HTTP)' : 'local (stdio)',
402
+ api_host: label,
403
+ api_base_url: config.baseUrlV1,
404
+ token: hosted
405
+ ? auth.current
406
+ ? 'received on this request\'s Authorization header'
407
+ : 'none on this request: send it as an Authorization header'
408
+ : config.envToken
409
+ ? 'from EDGEGAP_API_TOKEN'
410
+ : auth.current
411
+ ? 'provided by the developer this session (memory only)'
412
+ : 'not yet provided: the developer is asked on first use',
413
+ token_scope: 'organization-wide (Edgegap cannot scope tokens)',
414
+ read_only: config.readOnly,
415
+ app_allowlist: config.appAllowlist.length ? config.appAllowlist : 'none (all applications)',
416
+ max_duration_ceiling_minutes: config.maxDurationCeiling,
417
+ skills_pack: `${SKILLS_PACK.version} (${SKILLS_PACK.commit.slice(0, 7)}), ${SKILLS_PACK.skills.length} skills`,
418
+ forced_deploy_tag: AGENT_TAG,
419
+ guardrails: {
420
+ dry_run: mutating
421
+ ? 'deploy, stop_deployment, create_app, create_app_version, create/authorize/delete relay'
422
+ : 'n/a: read-only, no write tools are registered',
423
+ token_in_container: 'deploys and versions are refused if the API token appears in an env var, tag or webhook URL',
424
+ stop: 'one exact request_id per call; no bulk stop',
425
+ auto_stop: 'each deploy reports its version\'s max_duration; Edgegap has no per-deployment time limit',
426
+ results: `every result starts with [${label}]`,
427
+ },
428
+ user_agent: `edgegap-mcp/${VERSION} (<MCP client name>)`,
429
+ });
430
+ });
245
431
  // ---------------------------------------------------------------- 1 ----
246
- server.registerTool('edgegap_list_apps', {
432
+ tool('edgegap_list_apps', {
247
433
  title: 'List Edgegap applications',
248
434
  description: 'List the applications in the Edgegap organization. Start here before creating or ' +
249
435
  'deploying anything, so you reuse an existing application instead of making a duplicate. ' +
@@ -264,7 +450,7 @@ export function registerTools(server, client, config, auth) {
264
450
  }));
265
451
  // ---------------------------------------------------------------- 2 ----
266
452
  if (mutating) {
267
- server.registerTool('edgegap_create_app', {
453
+ tool('edgegap_create_app', {
268
454
  title: 'Create an Edgegap application',
269
455
  description: 'Create a new application to hold game server versions. Only call this after ' +
270
456
  'edgegap_list_apps confirms no suitable application exists. Creating an application ' +
@@ -276,15 +462,18 @@ export function registerTools(server, client, config, auth) {
276
462
  .max(64)
277
463
  .describe('Application name, 3-64 chars. Usually the game or project name.'),
278
464
  is_active: z.boolean().optional().describe('Whether deployments are allowed. Default true.'),
465
+ dry_run: dryRunParam,
279
466
  },
280
467
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
281
- }, async ({ name, is_active }) => guard(auth, async () => {
468
+ }, async ({ name, is_active, dry_run }) => guard(auth, async () => {
282
469
  assertAppAllowed(config, name);
283
- const res = await client.createApp({
284
- name,
285
- is_active: is_active ?? true,
286
- image: PLACEHOLDER_IMAGE,
287
- });
470
+ const body = { name, is_active: is_active ?? true, image: PLACEHOLDER_IMAGE };
471
+ if (dry_run) {
472
+ const dry = client.dryRun();
473
+ await dry.client.createApp(body);
474
+ return dryRunResult(dry.requests);
475
+ }
476
+ const res = await client.createApp(body);
288
477
  return ok({
289
478
  created: res.name,
290
479
  active: res.is_active,
@@ -293,7 +482,7 @@ export function registerTools(server, client, config, auth) {
293
482
  }));
294
483
  }
295
484
  // ---------------------------------------------------------------- 3 ----
296
- server.registerTool('edgegap_list_app_versions', {
485
+ tool('edgegap_list_app_versions', {
297
486
  title: 'List versions of an application',
298
487
  description: 'List the versions under an application, with their container image, resources, ports ' +
299
488
  '(including whether TLS Upgrade is on, which browser/WebGL clients need for wss://) and ' +
@@ -330,7 +519,7 @@ export function registerTools(server, client, config, auth) {
330
519
  }));
331
520
  // ---------------------------------------------------------------- 4 ----
332
521
  if (mutating) {
333
- server.registerTool('edgegap_create_app_version', {
522
+ tool('edgegap_create_app_version', {
334
523
  title: 'Create an application version',
335
524
  description: 'Register a container image as a deployable version of an application. The image must ' +
336
525
  'already be pushed to a registry that Edgegap can pull from (see ' +
@@ -390,11 +579,22 @@ export function registerTools(server, client, config, auth) {
390
579
  env: z
391
580
  .array(z.object({ key: z.string(), value: z.string() }))
392
581
  .optional()
393
- .describe('Environment variables injected into the container.'),
582
+ .describe('Environment variables injected into the container. Values are never echoed back.'),
583
+ dry_run: dryRunParam,
394
584
  },
395
585
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
396
586
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
397
587
  assertAppAllowed(config, args.application);
588
+ const leak = await tokenLeak(auth, args.dry_run, [
589
+ ...(args.env ?? []).flatMap((e) => [
590
+ [`env var name "${e.key.slice(0, 40)}"`, e.key],
591
+ [`the value of env var "${e.key.slice(0, 40)}"`, e.value],
592
+ ]),
593
+ ['registry_username', args.registry_username],
594
+ ['registry_token', args.registry_token],
595
+ ]);
596
+ if (leak)
597
+ return leak;
398
598
  if (args.memory_mb > args.cpu_units * 2) {
399
599
  return fail(`memory_mb (${args.memory_mb}) exceeds twice cpu_units (${args.cpu_units}). ` +
400
600
  `Edgegap rejects this. Either lower memory_mb to ${args.cpu_units * 2} or raise cpu_units.`);
@@ -408,29 +608,35 @@ export function registerTools(server, client, config, auth) {
408
608
  const capped = Math.min(requested, config.maxDurationCeiling);
409
609
  const hasRegistryLogin = Boolean(args.registry_username && args.registry_token);
410
610
  const edgegapRegistry = /(^|\/\/)registry\.edgegap\.com\/?$/.test(args.docker_repository.trim());
611
+ const body = {
612
+ name: args.name,
613
+ is_active: true,
614
+ req_cpu: args.cpu_units,
615
+ req_memory: args.memory_mb,
616
+ docker_repository: args.docker_repository,
617
+ docker_image: args.docker_image,
618
+ docker_tag: args.docker_tag,
619
+ private_username: args.registry_username,
620
+ private_token: args.registry_token,
621
+ verify_image: args.verify_image ?? false,
622
+ max_duration: capped,
623
+ ports: args.ports.map((p) => ({
624
+ port: p.port,
625
+ protocol: p.protocol,
626
+ name: p.name ?? 'gameport',
627
+ to_check: p.to_check ?? true,
628
+ tls_upgrade: p.tls_upgrade ?? false,
629
+ })),
630
+ envs: args.env?.map((e) => ({ key: e.key, value: e.value, is_hidden: false })),
631
+ };
632
+ if (args.dry_run) {
633
+ const dry = client.dryRun();
634
+ await dry.client.createAppVersion(args.application, body);
635
+ return dryRunResult(dry.requests, capped < requested ? [`max_duration capped to ${capped} minutes by EDGEGAP_MAX_DURATION_MINUTES.`] : []);
636
+ }
411
637
  let res;
412
638
  try {
413
- res = await client.createAppVersion(args.application, {
414
- name: args.name,
415
- is_active: true,
416
- req_cpu: args.cpu_units,
417
- req_memory: args.memory_mb,
418
- docker_repository: args.docker_repository,
419
- docker_image: args.docker_image,
420
- docker_tag: args.docker_tag,
421
- private_username: args.registry_username,
422
- private_token: args.registry_token,
423
- verify_image: args.verify_image ?? false,
424
- max_duration: capped,
425
- ports: args.ports.map((p) => ({
426
- port: p.port,
427
- protocol: p.protocol,
428
- name: p.name ?? 'gameport',
429
- to_check: p.to_check ?? true,
430
- tls_upgrade: p.tls_upgrade ?? false,
431
- })),
432
- envs: args.env?.map((e) => ({ key: e.key, value: e.value, is_hidden: false })),
433
- });
639
+ res = await client.createAppVersion(args.application, body);
434
640
  }
435
641
  catch (err) {
436
642
  // verify_image pulls with the version's registry login. Without one
@@ -465,13 +671,17 @@ export function registerTools(server, client, config, auth) {
465
671
  }
466
672
  // ---------------------------------------------------------------- 5 ----
467
673
  if (mutating) {
468
- server.registerTool('edgegap_deploy', {
674
+ tool('edgegap_deploy', {
469
675
  title: 'Deploy a game server',
470
676
  description: 'Start one authoritative dedicated game server from an application version, placed near ' +
471
677
  'the players you specify. This is the recommended way to host a multiplayer match: the ' +
472
678
  'server owns the game state, so no player hosts it. Returns immediately with a request_id; the server is still starting and ' +
473
679
  'has no connection details yet. Follow this call with edgegap_wait_for_deployment to ' +
474
- 'get the address players connect to. Always stop deployments you started for testing.',
680
+ 'get the address players connect to. Always stop deployments you started for testing. ' +
681
+ `Every deployment is tagged "${AGENT_TAG}" in addition to any tags you pass, so ` +
682
+ 'edgegap_list_deployments with only_agent_deployments: true finds them all. Runs until ' +
683
+ 'stopped or until the version\'s max_duration, which the result reports. Refused, with ' +
684
+ 'nothing sent, if the API token appears in an env var or tag.',
475
685
  inputSchema: {
476
686
  application: z.string().describe('Application name.'),
477
687
  version: z.string().describe('Version name within the application.'),
@@ -479,13 +689,14 @@ export function registerTools(server, client, config, auth) {
479
689
  env: z
480
690
  .array(z.object({ key: z.string(), value: z.string() }))
481
691
  .optional()
482
- .describe('Environment variables for this deployment only.'),
692
+ .describe('Environment variables for this deployment only. Values are never echoed back.'),
483
693
  tags: z
484
- .array(z.string())
694
+ .array(z.string().min(1).max(40))
485
695
  .optional()
486
- .describe('Tags for filtering later, e.g. ["agent-test"]. Recommended.'),
696
+ .describe(`Extra tags for filtering later, e.g. ["agent-test"]. "${AGENT_TAG}" is always added.`),
487
697
  cpu_units: z.number().int().min(256).optional().describe('Override the version CPU.'),
488
698
  memory_mb: z.number().int().min(256).optional().describe('Override the version memory.'),
699
+ dry_run: dryRunParam,
489
700
  },
490
701
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
491
702
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
@@ -495,11 +706,23 @@ export function registerTools(server, client, config, auth) {
495
706
  return fail('No player locations given. Supply users.ip_addresses (e.g. the developer\'s own ' +
496
707
  'public IP) or users.geo_coordinates. Edgegap needs at least one to choose a region.');
497
708
  }
709
+ // Forced, whatever the caller passed: the tag is how agent
710
+ // deployments are found and cleaned up, so it cannot be optional.
711
+ const tags = [...new Set([...(args.tags ?? []), AGENT_TAG])];
712
+ const leak = await tokenLeak(auth, args.dry_run, [
713
+ ...(args.env ?? []).flatMap((e) => [
714
+ [`env var name "${e.key.slice(0, 40)}"`, e.key],
715
+ [`the value of env var "${e.key.slice(0, 40)}"`, e.value],
716
+ ]),
717
+ ...tags.map((t) => [`tag "${t.slice(0, 8)}…"`, t]),
718
+ ]);
719
+ if (leak)
720
+ return leak;
498
721
  const body = {
499
722
  application: args.application,
500
723
  version: args.version,
501
724
  users,
502
- tags: args.tags ?? ['mcp'],
725
+ tags,
503
726
  };
504
727
  if (args.env) {
505
728
  body.environment_variables = args.env.map((e) => ({
@@ -511,16 +734,31 @@ export function registerTools(server, client, config, auth) {
511
734
  if (args.cpu_units && args.memory_mb) {
512
735
  body.resources = { cpu_units: args.cpu_units, memory_mib: args.memory_mb };
513
736
  }
737
+ if (args.dry_run) {
738
+ const dry = client.dryRun();
739
+ await dry.client.deploy(body);
740
+ return dryRunResult(dry.requests, [
741
+ `Tagged "${AGENT_TAG}" automatically.`,
742
+ 'Auto-stop comes from the version\'s max_duration; a real deploy reports it.',
743
+ ]);
744
+ }
745
+ // Edgegap has no per-deployment time limit: a deployment runs until
746
+ // stopped or until its version's max_duration (default 1440 minutes,
747
+ // a full day). Read it first so the agent knows how long an
748
+ // unstopped test server will keep billing.
749
+ const version = await client.getAppVersion(args.application, args.version);
514
750
  const res = await client.deploy(body);
515
751
  return ok({
516
752
  request_id: res.request_id,
517
753
  status: 'starting',
754
+ tags,
755
+ ...autoStop(version.max_duration),
518
756
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
519
757
  });
520
758
  }));
521
759
  }
522
760
  // ---------------------------------------------------------------- 6 ----
523
- server.registerTool('edgegap_get_deployment', {
761
+ tool('edgegap_get_deployment', {
524
762
  title: 'Get deployment status',
525
763
  description: 'Read the current status of one deployment, including connection address and ports once ' +
526
764
  'it is ready. For a deployment you just created, prefer edgegap_wait_for_deployment — it ' +
@@ -534,7 +772,7 @@ export function registerTools(server, client, config, auth) {
534
772
  return ok(compactDeployment(d));
535
773
  }));
536
774
  // ---------------------------------------------------------------- 7 ----
537
- server.registerTool('edgegap_wait_for_deployment', {
775
+ tool('edgegap_wait_for_deployment', {
538
776
  title: 'Wait for a deployment to become ready',
539
777
  description: 'Poll a deployment until it is ready, errors, or the timeout expires, then return the ' +
540
778
  'connection details. This is the tool to call right after edgegap_deploy. Do not build ' +
@@ -579,7 +817,7 @@ export function registerTools(server, client, config, auth) {
579
817
  `call edgegap_get_deployment to check again, or edgegap_stop_deployment to clean up.`);
580
818
  }));
581
819
  // ---------------------------------------------------------------- 8 ----
582
- server.registerTool('edgegap_list_deployments', {
820
+ tool('edgegap_list_deployments', {
583
821
  title: 'List running deployments',
584
822
  description: 'List active deployments, optionally filtered and sorted. Use this to find deployments left running ' +
585
823
  'from earlier sessions before starting new ones — orphaned servers cost money. ' +
@@ -587,8 +825,15 @@ export function registerTools(server, client, config, auth) {
587
825
  'e.g. [{field:"application",operator:"eq",value:"my-game"},{field:"status",operator:"eq",value:"ready"}]. ' +
588
826
  'Operators: eq and neq on every field except created_at (eq, gte, lte); in and nin with an array value ' +
589
827
  'on request_id, tags, application, version, fleet_name, host_name; ilike with % wildcards on fleet_name ' +
590
- 'and host_name. At most one filter per field. Sort by created_at or available_session_sockets.',
828
+ 'and host_name. At most one filter per field. Sort by created_at or available_session_sockets. ' +
829
+ `To find every deployment an agent started through this server, pass only_agent_deployments: true ` +
830
+ `(the same as filtering tags in ["${AGENT_TAG}", "mcp"]).`,
591
831
  inputSchema: {
832
+ only_agent_deployments: z
833
+ .boolean()
834
+ .optional()
835
+ .describe(`Only deployments started through this server: tagged "${AGENT_TAG}", or "mcp" by versions ` +
836
+ 'up to 0.3.3. Cannot be combined with a tags filter.'),
592
837
  filters: z
593
838
  .array(z.object({
594
839
  field: z.enum([
@@ -612,7 +857,14 @@ export function registerTools(server, client, config, auth) {
612
857
  limit: z.number().int().min(1).max(100).optional().describe('Default 50.'),
613
858
  },
614
859
  annotations: { readOnlyHint: true, openWorldHint: true },
615
- }, async ({ filters, order_by, limit }) => guard(auth, async () => {
860
+ }, async ({ only_agent_deployments, filters: given, order_by, limit }) => guard(auth, async () => {
861
+ let filters = given;
862
+ if (only_agent_deployments) {
863
+ if (given?.some((f) => f.field === 'tags')) {
864
+ return fail('only_agent_deployments already filters on tags. Drop the tags filter, or drop only_agent_deployments.');
865
+ }
866
+ filters = [...(given ?? []), { field: 'tags', operator: 'in', value: [AGENT_TAG, 'mcp'] }];
867
+ }
616
868
  const fields = (filters ?? []).map((f) => f.field);
617
869
  const repeated = fields.find((f, i) => fields.indexOf(f) !== i);
618
870
  if (repeated) {
@@ -633,22 +885,32 @@ export function registerTools(server, client, config, auth) {
633
885
  }));
634
886
  // ---------------------------------------------------------------- 9 ----
635
887
  if (mutating) {
636
- server.registerTool('edgegap_stop_deployment', {
888
+ tool('edgegap_stop_deployment', {
637
889
  title: 'Stop a deployment',
638
890
  description: 'Gracefully stop one deployment by request_id, sending SIGTERM to the container. ' +
639
891
  'Stop every deployment you started for testing before ending your task. This tool ' +
640
- 'stops exactly one deployment; bulk stop is deliberately not exposed.',
892
+ 'stops exactly one deployment, named by its exact request_id: empty IDs, wildcards ' +
893
+ 'and lists are refused, and bulk stop is deliberately not exposed.',
641
894
  inputSchema: {
642
- request_id: z.string().describe('The request_id of the deployment to stop.'),
895
+ request_id: z.string().describe('The exact request_id of the one deployment to stop, e.g. "61b1be8f54d9".'),
896
+ dry_run: dryRunParam,
643
897
  },
644
898
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
645
- }, async ({ request_id }) => guarded(auth, NOT_FOUND.deployment, async () => {
899
+ }, async ({ request_id, dry_run }) => guarded(auth, NOT_FOUND.deployment, async () => {
900
+ const bad = checkRequestId(request_id);
901
+ if (bad)
902
+ return bad;
903
+ if (dry_run) {
904
+ const dry = client.dryRun();
905
+ await dry.client.stopDeployment(request_id);
906
+ return dryRunResult(dry.requests);
907
+ }
646
908
  const res = await client.stopDeployment(request_id);
647
909
  return ok({ request_id, result: res.message ?? 'stop requested' });
648
910
  }));
649
911
  }
650
912
  // --------------------------------------------------------------- 10 ----
651
- server.registerTool('edgegap_get_deployment_logs', {
913
+ tool('edgegap_get_deployment_logs', {
652
914
  title: 'Get container logs for a deployment',
653
915
  description: 'Retrieve stdout/stderr and crash output for a deployment. Call this whenever a ' +
654
916
  'deployment errors or a server exits unexpectedly — the crash exit code usually ' +
@@ -683,7 +945,7 @@ export function registerTools(server, client, config, auth) {
683
945
  // -------------------------------------------------------------- 11a ----
684
946
  // Pure text generation: no token, no network, so it is always registered and
685
947
  // never goes through guard().
686
- server.registerTool('edgegap_generate_dockerfile', {
948
+ tool('edgegap_generate_dockerfile', {
687
949
  title: 'Generate a game server Dockerfile',
688
950
  description: 'Write a Dockerfile for this project\'s headless game server build, ready for Edgegap: ' +
689
951
  'linux/amd64 base, the build folder copied in, the binary made executable, the right ' +
@@ -772,7 +1034,7 @@ export function registerTools(server, client, config, auth) {
772
1034
  // --------------------------------------------------------------- 11 ----
773
1035
  // Pure text analysis: no token, no network, so it is always registered and
774
1036
  // never goes through guard().
775
- server.registerTool('edgegap_validate_server_config', {
1037
+ tool('edgegap_validate_server_config', {
776
1038
  title: 'Validate a game server Dockerfile and port config',
777
1039
  description: 'Check a game server Dockerfile and the ports/resources you intend to register against ' +
778
1040
  'what Edgegap requires, BEFORE building and pushing. Catches the failures that otherwise ' +
@@ -840,7 +1102,7 @@ export function registerTools(server, client, config, auth) {
840
1102
  // Mutating-only: it can provision the registry project, and it hands a
841
1103
  // secret to the agent. A read-only session has no business receiving one.
842
1104
  if (mutating) {
843
- server.registerTool('edgegap_get_registry_credentials', {
1105
+ tool('edgegap_get_registry_credentials', {
844
1106
  title: 'Get Edgegap container registry push credentials',
845
1107
  description: 'Get the push login for this organization\'s private Edgegap container registry ' +
846
1108
  '(registry.edgegap.com) and the exact docker login, build and push commands for your ' +
@@ -927,7 +1189,7 @@ export function registerTools(server, client, config, auth) {
927
1189
  }));
928
1190
  }
929
1191
  // --------------------------------------------------------------- 13 ----
930
- server.registerTool('edgegap_list_registry_tags', {
1192
+ tool('edgegap_list_registry_tags', {
931
1193
  title: 'List image tags in the Edgegap registry',
932
1194
  description: 'List the tags pushed for one image in this organization\'s Edgegap container registry, ' +
933
1195
  'with push time and size. Call it after docker push to confirm the tag landed before ' +
@@ -998,7 +1260,7 @@ export function registerTools(server, client, config, auth) {
998
1260
  // ================================================== peer-to-peer relays ====
999
1261
  // --------------------------------------------------------------- 14 ----
1000
1262
  if (mutating) {
1001
- server.registerTool('edgegap_create_relay_session', {
1263
+ tool('edgegap_create_relay_session', {
1002
1264
  title: 'Create a relay session (host-client games only)',
1003
1265
  description: 'A relay is NOT a game server and is not the recommended default — for a multiplayer ' +
1004
1266
  'match, deploy an authoritative dedicated server with edgegap_deploy instead. A relay ' +
@@ -1020,13 +1282,20 @@ export function registerTools(server, client, config, auth) {
1020
1282
  webhook_url: z.string().url().optional().describe('Called when the session is ready.'),
1021
1283
  wait_until_ready: z.boolean().optional().describe('Poll until the relay is assigned. Default true.'),
1022
1284
  timeout_seconds: z.number().int().min(5).max(120).optional().describe('Default 30.'),
1285
+ dry_run: dryRunParam,
1023
1286
  },
1024
1287
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
1025
- }, async ({ user_ips, webhook_url, wait_until_ready, timeout_seconds }) => guard(auth, async () => {
1026
- const created = await client.createRelaySession({
1027
- users: user_ips.map((ip) => ({ ip })),
1028
- ...(webhook_url ? { webhook_url } : {}),
1029
- });
1288
+ }, async ({ user_ips, webhook_url, wait_until_ready, timeout_seconds, dry_run }) => guard(auth, async () => {
1289
+ const leak = await tokenLeak(auth, dry_run, [['webhook_url', webhook_url]]);
1290
+ if (leak)
1291
+ return leak;
1292
+ const body = { users: user_ips.map((ip) => ({ ip })), ...(webhook_url ? { webhook_url } : {}) };
1293
+ if (dry_run) {
1294
+ const dry = client.dryRun();
1295
+ await dry.client.createRelaySession(body);
1296
+ return dryRunResult(dry.requests);
1297
+ }
1298
+ const created = await client.createRelaySession(body);
1030
1299
  if (wait_until_ready === false) {
1031
1300
  return ok({
1032
1301
  ...compactRelay(created),
@@ -1055,7 +1324,7 @@ export function registerTools(server, client, config, auth) {
1055
1324
  }));
1056
1325
  }
1057
1326
  // --------------------------------------------------------------- 15 ----
1058
- server.registerTool('edgegap_get_relay_session', {
1327
+ tool('edgegap_get_relay_session', {
1059
1328
  title: 'Get a relay session',
1060
1329
  description: 'Read one relay session: whether it is ready, the relay address and ports, and each ' +
1061
1330
  'authorized player with their authorization token. edgegap_create_relay_session already ' +
@@ -1065,16 +1334,22 @@ export function registerTools(server, client, config, auth) {
1065
1334
  }, async ({ session_id }) => guarded(auth, NOT_FOUND.relay, async () => ok(compactRelay(await client.getRelaySession(session_id)))));
1066
1335
  if (mutating) {
1067
1336
  // ------------------------------------------------------------- 16 ----
1068
- server.registerTool('edgegap_authorize_relay_user', {
1337
+ tool('edgegap_authorize_relay_user', {
1069
1338
  title: 'Add a player to a relay session',
1070
1339
  description: 'Authorize one more player (by public IP) on an existing relay session, for a player ' +
1071
1340
  'joining after the session was created. Returns that player\'s authorization token.',
1072
1341
  inputSchema: {
1073
1342
  session_id: z.string(),
1074
1343
  user_ip: z.string().min(3).describe('Public IP of the joining player.'),
1344
+ dry_run: dryRunParam,
1075
1345
  },
1076
1346
  annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
1077
- }, async ({ session_id, user_ip }) => guarded(auth, NOT_FOUND.relay, async () => {
1347
+ }, async ({ session_id, user_ip, dry_run }) => guarded(auth, NOT_FOUND.relay, async () => {
1348
+ if (dry_run) {
1349
+ const dry = client.dryRun();
1350
+ await dry.client.authorizeRelayUser({ session_id, user_ip });
1351
+ return dryRunResult(dry.requests);
1352
+ }
1078
1353
  const res = await client.authorizeRelayUser({ session_id, user_ip });
1079
1354
  return ok({
1080
1355
  session_id: res.session_id,
@@ -1084,13 +1359,25 @@ export function registerTools(server, client, config, auth) {
1084
1359
  });
1085
1360
  }));
1086
1361
  // ------------------------------------------------------------- 17 ----
1087
- server.registerTool('edgegap_delete_relay_session', {
1362
+ tool('edgegap_delete_relay_session', {
1088
1363
  title: 'Delete a relay session',
1089
1364
  description: 'Close one relay session. Connected players lose their relay connection. Delete every ' +
1090
- 'session you created for testing before ending your task.',
1091
- inputSchema: { session_id: z.string() },
1365
+ 'session you created for testing before ending your task. Takes exactly one session_id; ' +
1366
+ 'empty IDs, wildcards and lists are refused.',
1367
+ inputSchema: {
1368
+ session_id: z.string().describe('The exact session_id of the one session to delete, e.g. "0724828881e2-S".'),
1369
+ dry_run: dryRunParam,
1370
+ },
1092
1371
  annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: true },
1093
- }, async ({ session_id }) => guarded(auth, NOT_FOUND.relay, async () => {
1372
+ }, async ({ session_id, dry_run }) => guarded(auth, NOT_FOUND.relay, async () => {
1373
+ if (!SESSION_ID.test(session_id)) {
1374
+ return fail(`"${session_id.slice(0, 80)}" is not a single relay session_id. Pass exactly one, e.g. "0724828881e2-S".`);
1375
+ }
1376
+ if (dry_run) {
1377
+ const dry = client.dryRun();
1378
+ await dry.client.deleteRelaySession(session_id);
1379
+ return dryRunResult(dry.requests);
1380
+ }
1094
1381
  await client.deleteRelaySession(session_id);
1095
1382
  return ok({ session_id, result: 'deleted' });
1096
1383
  }));
@@ -1100,7 +1387,7 @@ export function registerTools(server, client, config, auth) {
1100
1387
  // Edgegap has no public API to create a matchmaker, so this does not create
1101
1388
  // one. It produces the configuration the dashboard asks for, checked against
1102
1389
  // the application version it points at.
1103
- server.registerTool('edgegap_build_matchmaker_config', {
1390
+ tool('edgegap_build_matchmaker_config', {
1104
1391
  title: 'Build a basic matchmaker configuration',
1105
1392
  description: 'Generate a ready-to-upload Edgegap matchmaker JSON configuration with one profile: team ' +
1106
1393
  'count and size, optional latency rule, and optional expansions that relax the rules the ' +
@@ -1189,6 +1476,108 @@ export function registerTools(server, client, config, auth) {
1189
1476
  ],
1190
1477
  });
1191
1478
  }));
1479
+ registerSkills(server, tool);
1480
+ }
1481
+ // ==================================================================== skills ====
1482
+ /**
1483
+ * Serves the bundled Edgegap agent skills three ways, because MCP clients
1484
+ * differ in what they surface:
1485
+ * - tools (edgegap_list_skills, edgegap_get_skill): every agent can call these;
1486
+ * - prompts, one per skill: slash commands in clients that show prompts;
1487
+ * - resources, one per file: for clients that browse or @-mention resources.
1488
+ * All three read the same bundle (src/skills.generated.ts). No token, no network.
1489
+ */
1490
+ function registerSkills(server, tool) {
1491
+ const names = SKILLS_PACK.skills.map((s) => s.name);
1492
+ const pack = `${SKILLS_PACK.version} (${SKILLS_PACK.commit.slice(0, 7)})`;
1493
+ const howToFetch = (skill) => `Fetch any of these with edgegap_get_skill {skill: "${skill}", file: "<path>"}, or read the ` +
1494
+ `resource ${skillUri(skill, '<path>')}. Template files are meant to be copied into the project ` +
1495
+ 'where the skill says.';
1496
+ tool('edgegap_list_skills', {
1497
+ title: 'List the Edgegap agent skills',
1498
+ description: 'List the Edgegap agent skills: tested, step-by-step workflows for getting a multiplayer ' +
1499
+ 'game online on Edgegap, with templates (Dockerfiles, matchmaker configs, Unity C# and ' +
1500
+ 'Unreal C++ drop-ins) and known pitfalls. Before working on a game project, load the ' +
1501
+ 'matching skill with edgegap_get_skill: edgegap-unity for Unity, edgegap-unreal for Unreal ' +
1502
+ 'Engine, edgegap for any other engine or platform questions; it routes to the rest. No ' +
1503
+ 'API call.',
1504
+ inputSchema: {},
1505
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
1506
+ }, async () => ok({
1507
+ pack,
1508
+ source: SKILLS_PACK.source,
1509
+ skills: SKILLS_PACK.skills.map((s) => ({
1510
+ name: s.name,
1511
+ version: s.version,
1512
+ description: s.description,
1513
+ files: s.files.length,
1514
+ })),
1515
+ next_step: 'Load the skill that matches the project with edgegap_get_skill, then follow it.',
1516
+ }));
1517
+ tool('edgegap_get_skill', {
1518
+ title: 'Load an Edgegap agent skill',
1519
+ description: 'Load one Edgegap agent skill: its SKILL.md (the workflow to follow) by default, or one of ' +
1520
+ 'its reference documents or templates with file. Load the matching skill before acting on ' +
1521
+ 'a game project — edgegap-unity for Unity, edgegap-unreal for Unreal Engine, edgegap ' +
1522
+ 'otherwise — and fetch the references and templates it points to as you reach them. No API call.',
1523
+ inputSchema: {
1524
+ skill: z.enum(names).describe('Skill name, from edgegap_list_skills.'),
1525
+ file: z
1526
+ .string()
1527
+ .optional()
1528
+ .describe('A file inside the skill, e.g. "references/deploy.md" or "assets/docker/Dockerfile". Default SKILL.md.'),
1529
+ },
1530
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
1531
+ }, async ({ skill: name, file }) => {
1532
+ const skill = findSkill(name);
1533
+ if (!skill)
1534
+ return fail(`No skill named "${name}". Call edgegap_list_skills.`);
1535
+ const found = findSkillFile(skill, file);
1536
+ if (!found) {
1537
+ return fail(`"${file}" is not a file in the ${skill.name} skill. Its files are:\n` +
1538
+ skill.files.map((f) => `- ${f.path}`).join('\n'));
1539
+ }
1540
+ const header = `${skill.name} ${skill.version} · ${found.path} · pack ${pack}`;
1541
+ const others = found.path === 'SKILL.md' ? fileIndex(skill) : [];
1542
+ const footer = others.length
1543
+ ? `\n\n---\nOther files in this skill:\n${others.map((p) => `- ${p}`).join('\n')}\n\n${howToFetch(skill.name)}`
1544
+ : '';
1545
+ return { content: [{ type: 'text', text: `${header}\n\n${found.content}${footer}` }] };
1546
+ });
1547
+ for (const skill of SKILLS_PACK.skills) {
1548
+ // A prompt per skill: in Claude Code these show up as slash commands.
1549
+ server.registerPrompt(skill.name, {
1550
+ title: `Edgegap skill: ${skill.name}`,
1551
+ description: skill.description,
1552
+ }, () => {
1553
+ const main = findSkillFile(skill);
1554
+ const others = fileIndex(skill);
1555
+ return {
1556
+ description: skill.description,
1557
+ messages: [
1558
+ {
1559
+ role: 'user',
1560
+ content: {
1561
+ type: 'text',
1562
+ text: `Follow this Edgegap skill (${skill.name} ${skill.version}, pack ${pack}).\n\n${main.content}` +
1563
+ (others.length
1564
+ ? `\n\n---\nOther files in this skill:\n${others.map((p) => `- ${p}`).join('\n')}\n\n${howToFetch(skill.name)}`
1565
+ : ''),
1566
+ },
1567
+ },
1568
+ ],
1569
+ };
1570
+ });
1571
+ // A resource per file.
1572
+ for (const f of skill.files) {
1573
+ const uri = skillUri(skill.name, f.path);
1574
+ server.registerResource(`${skill.name}/${f.path}`, uri, {
1575
+ title: f.path === 'SKILL.md' ? `${skill.name} skill` : `${skill.name}: ${f.path}`,
1576
+ description: f.path === 'SKILL.md' ? skill.description : undefined,
1577
+ mimeType: mimeType(f.path),
1578
+ }, async () => ({ contents: [{ uri, mimeType: mimeType(f.path), text: f.content }] }));
1579
+ }
1580
+ }
1192
1581
  }
1193
1582
  /**
1194
1583
  * What edgegap_get_registry_credentials says when Edgegap will not hand the