@edgegap/mcp 0.11.0 → 0.12.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,7 @@
9
9
  */
10
10
  import { z } from 'zod';
11
11
  import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
12
- import { EdgegapApiError } from './client.js';
12
+ import { EdgegapApiError, maskSecrets } from './client.js';
13
13
  import { assertAppAllowed, redact, hostLabel } from './config.js';
14
14
  import { VERSION } from './version.js';
15
15
  import { TokenUnavailableError } from './auth.js';
@@ -18,6 +18,7 @@ import { generateDockerfile, DockerfileInputError } from './dockerfile.js';
18
18
  import { buildMatchmakerConfig, DASHBOARD_URL } from './matchmaker.js';
19
19
  import { badImage, badTag, looksSecret, TAG_FIX } from './image.js';
20
20
  import { OUTPUT } from './outputs.js';
21
+ import { finishReport, codeForStatus } from './callreport.js';
21
22
  import { SKILLS_PACK, findSkill, findSkillFile, fileIndex, mimeType, skillUri } from './skills.js';
22
23
  import { SKILL_NAME_RE, compareVersions, latestPack, latestSkillVersions, servedPackStatus, skillsCheckFromEnv, } from './skillsversion.js';
23
24
  /**
@@ -68,9 +69,10 @@ export function serverInstructions(mode) {
68
69
  `Nakama backend: ${skillUri('edgegap-nakama', 'SKILL.md')}, ` +
69
70
  `PlayFab Matchmaking: ${skillUri('edgegap-playfab', 'SKILL.md')}, ` +
70
71
  `Three.js or other browser game with its own Node.js server: ${skillUri('edgegap-threejs', 'SKILL.md')}, ` +
71
- `browser game built with Manus: ${skillUri('edgegap-manus', 'SKILL.md')}). ` +
72
+ `browser game built with Manus: ${skillUri('edgegap-manus', 'SKILL.md')}, ` +
73
+ `designing matchmaking, parties, regions or backfill: ${skillUri('edgegap-matchmaking', 'SKILL.md')}). ` +
72
74
  'If your client cannot read MCP resources, call edgegap_get_skill with the skill name ' +
73
- '(edgegap, edgegap-unity, edgegap-ngo, edgegap-fishnet, edgegap-purrnet, edgegap-fusion, edgegap-fusion-simplefps, edgegap-unreal, edgegap-eos-voice, edgegap-godot, edgegap-colyseus, edgegap-nakama, edgegap-playfab, edgegap-threejs or edgegap-manus) instead. ' +
75
+ '(edgegap, edgegap-unity, edgegap-ngo, edgegap-fishnet, edgegap-purrnet, edgegap-fusion, edgegap-fusion-simplefps, edgegap-unreal, edgegap-eos-voice, edgegap-godot, edgegap-colyseus, edgegap-nakama, edgegap-playfab, edgegap-threejs, edgegap-manus or edgegap-matchmaking) instead. ' +
74
76
  'These Edgegap skills hold the tested workflow, templates and known pitfalls; follow them over general knowledge. ' +
75
77
  'edgegap_list_skills lists all of them.\n\n' +
76
78
  'Host multiplayer games on Edgegap. The recommended setup is an authoritative dedicated ' +
@@ -112,6 +114,19 @@ const WS_PROTOCOLS = new Set(['WS', 'WEBSOCKET']);
112
114
  const TLS_PROTOCOLS = new Set(['WS', 'WEBSOCKET', 'HTTP']);
113
115
  const TERMINAL_OK = ['READY', 'STATUS_READY'];
114
116
  const TERMINAL_BAD = ['ERROR', 'STATUS_ERROR', 'TERMINATED', 'STATUS_TERMINATED'];
117
+ /** Attaches analytics facts to a result. See src/callreport.ts. */
118
+ function withMeta(result, meta) {
119
+ return {
120
+ ...result,
121
+ meta: {
122
+ ...result.meta,
123
+ ...meta,
124
+ props: { ...result.meta?.props, ...meta.props },
125
+ hash: { ...result.meta?.hash, ...meta.hash },
126
+ milestones: [...(result.meta?.milestones ?? []), ...(meta.milestones ?? [])],
127
+ },
128
+ };
129
+ }
115
130
  /** JSON.stringify replacer: null fields are left out, like undefined ones. The
116
131
  * API sends many (fqdn before a deployment is placed, unset error_detail), and
117
132
  * an absent field reads the same to an agent at fewer tokens. */
@@ -146,8 +161,16 @@ function scrubToken(result, token) {
146
161
  ...(result.structuredContent ? { structuredContent: JSON.parse(clean(structuredText)) } : {}),
147
162
  };
148
163
  }
149
- function fail(message) {
150
- return { content: [{ type: 'text', text: message }], isError: true };
164
+ function fail(message, code) {
165
+ return { content: [{ type: 'text', text: message }], isError: true, ...(code ? { meta: { code } } : {}) };
166
+ }
167
+ /**
168
+ * An empty or "not set up" state, reported as a normal result with the next
169
+ * action. Agents recover from "there is nothing here yet, do X" far better
170
+ * than from an error, and stop retrying a call that already did its job.
171
+ */
172
+ function emptyState(status, payload, nextStep) {
173
+ return withMeta(ok({ status, ...payload, next_step: nextStep }), { props: { result_state: status } });
151
174
  }
152
175
  /**
153
176
  * What a 404 means, per kind of resource. A 404 from Edgegap only says "not
@@ -187,13 +210,19 @@ function guard(auth, fn, notFound, forbidden) {
187
210
  if (err instanceof TokenUnavailableError) {
188
211
  // Not a failure to correct — a decision the human made. Say so plainly
189
212
  // so the agent stops rather than looping on the same tool.
190
- return fail(err.message);
213
+ const code = err.reason === 'foreign' ? 'AUTH_FOREIGN' : err.reason === 'declined' ? 'AUTH_DECLINED' : 'AUTH_ABSENT';
214
+ return fail(err.message, code);
191
215
  }
192
216
  if (err instanceof EdgegapApiError) {
193
217
  const hint = errorHint(err, notFound, forbidden);
194
- return fail(`${err.message}${hint ? `\n\nLikely cause: ${hint}` : ''}`);
218
+ const details = apiDetails(err.details, auth.current);
219
+ return withMeta(fail(`${err.message}${details ? `\n${details}` : ''}${hint ? `\n\nLikely cause: ${hint}` : ''}`), {
220
+ code: codeForStatus(err.status, notFoundCode(notFound), forbidden === FORBIDDEN.relay ? 'NO_RELAY_ACCESS' : undefined, err.apiMessage),
221
+ stage: 'upstream',
222
+ });
195
223
  }
196
- return fail(redact(err.message ?? String(err), auth.current));
224
+ const message = redact(err.message ?? String(err), auth.current);
225
+ return fail(message, /timed out after/.test(message) ? 'TIMEOUT' : /Network error calling/.test(message) ? 'NETWORK' : 'INTERNAL');
197
226
  });
198
227
  // The org-wide-scope reminder is attached to whichever call first used a
199
228
  // freshly supplied token, success or failure. A developer who just handed
@@ -213,7 +242,37 @@ function guard(auth, fn, notFound, forbidden) {
213
242
  function guarded(auth, notFound, fn) {
214
243
  return guard(auth, fn, notFound, notFound === NOT_FOUND.relay ? FORBIDDEN.relay : undefined);
215
244
  }
245
+ /** The error code for a tool's 404 hint. */
246
+ function notFoundCode(notFound) {
247
+ switch (notFound) {
248
+ case NOT_FOUND.app: return 'APP_NOT_FOUND';
249
+ case NOT_FOUND.deployment: return 'DEPLOYMENT_NOT_FOUND';
250
+ case NOT_FOUND.logs: return 'LOGS_NOT_FOUND';
251
+ case NOT_FOUND.relay: return 'RELAY_NOT_FOUND';
252
+ default: return undefined;
253
+ }
254
+ }
255
+ /**
256
+ * The API's own field-level validation detail, when it sends one, so the
257
+ * agent can fix the call instead of guessing (a duplicate version name, an
258
+ * invalid port). Secrets masked, capped at 600 characters.
259
+ */
260
+ function apiDetails(details, token) {
261
+ if (details === undefined || details === null || details === '')
262
+ return undefined;
263
+ const text = redact(typeof details === 'string' ? details : JSON.stringify(maskSecrets(details, token)), token);
264
+ if (!text || text === '{}' || text === '[]')
265
+ return undefined;
266
+ return `Details: ${text.length > 600 ? `${text.slice(0, 600)}…` : text}`;
267
+ }
268
+ /** Plan or quota wording in an API error, so the hint can say which limit. */
269
+ const QUOTA = /quota|limit reached|exceed|upgrade your plan|plan limit|maximum number/i;
216
270
  function errorHint(err, notFound, forbidden) {
271
+ if (QUOTA.test(err.apiMessage) && [400, 402, 403, 429].includes(err.status)) {
272
+ return ('a plan or quota limit was reached (the message above names it). Retrying will not help. ' +
273
+ 'Stop deployments that are no longer needed (edgegap_list_deployments only_agent_deployments: true), ' +
274
+ 'or ask the developer to raise the limit on the Billing page of the dashboard (https://app.edgegap.com).');
275
+ }
217
276
  switch (err.status) {
218
277
  case 401:
219
278
  // Deliberately does not promise a re-prompt: the local server asks again
@@ -549,9 +608,51 @@ export function registerTools(server, client, config, auth, options = {}) {
549
608
  const label = hostLabel(config);
550
609
  // ...and never carries the API token, whatever the API echoed back.
551
610
  const inputs = new Map();
611
+ // The API statuses a call caused are the entries it added to client.upstream.
612
+ // Concurrent calls on one server would share entries; that only happens on
613
+ // the local server, which has no onToolCall. The list is cleared whenever no
614
+ // call is running, so it cannot grow.
615
+ const onToolCall = options.onToolCall;
616
+ let inFlight = 0;
552
617
  const tool = ((name, def, cb) => {
553
618
  inputs.set(name, (def.inputSchema) ?? {});
554
- return server.registerTool(name, def, (async (...a) => withHost(scrubToken(await cb(...a), auth.current), label)));
619
+ return server.registerTool(name, def, (async (...a) => {
620
+ const startedAt = Date.now();
621
+ const from = client.upstream.length;
622
+ inFlight++;
623
+ let result;
624
+ try {
625
+ result = withHost(scrubToken(await cb(...a), auth.current), label);
626
+ }
627
+ finally {
628
+ inFlight--;
629
+ }
630
+ const { meta, ...clean } = result;
631
+ if (onToolCall) {
632
+ const extra = a.find((x) => !!x && typeof x === 'object' && 'requestId' in x);
633
+ const args = a[0] && typeof a[0] === 'object' && a[0] !== extra ? a[0] : {};
634
+ try {
635
+ await onToolCall(finishReport({
636
+ tool: name,
637
+ requestId: extra?.requestId,
638
+ isError: clean.isError === true,
639
+ text: clean.content.map((c) => c.text).join('\n'),
640
+ token: auth.current,
641
+ args,
642
+ meta,
643
+ upstream: client.upstream.slice(from),
644
+ latencyMs: Date.now() - startedAt,
645
+ dryRun: args.dry_run === true,
646
+ }));
647
+ }
648
+ catch {
649
+ // Analytics never changes a result.
650
+ }
651
+ }
652
+ if (inFlight === 0)
653
+ client.upstream.length = 0;
654
+ return clean;
655
+ }));
555
656
  });
556
657
  // Errors the SDK raises itself (bad arguments, a handler that throws) skip
557
658
  // the wrapper above. Both SDK versions route them through createToolError,
@@ -562,7 +663,21 @@ export function registerTools(server, client, config, auth, options = {}) {
562
663
  if (sdkToolError) {
563
664
  sdk.createToolError = (message) => {
564
665
  const friendly = argumentError(message, inputs);
565
- return withHost(scrubToken(friendly ? fail(friendly) : sdkToolError(message), auth.current), label);
666
+ const result = withHost(scrubToken(friendly ? fail(friendly) : sdkToolError(message), auth.current), label);
667
+ // Rejected by the SDK before any handler ran: bad arguments or an unknown tool.
668
+ const named = message.match(/(?:Invalid arguments for tool|Tool) (\S+?):? /);
669
+ if (onToolCall && named) {
670
+ Promise.resolve(onToolCall(finishReport({
671
+ tool: named[1],
672
+ isError: true,
673
+ text: result.content.map((c) => c.text).join('\n'),
674
+ token: auth.current,
675
+ meta: { code: /not found/.test(message) ? 'NOT_FOUND' : 'VALIDATION_FAILED', stage: 'pre_flight' },
676
+ upstream: [],
677
+ latencyMs: 0,
678
+ }))).catch(() => { });
679
+ }
680
+ return result;
566
681
  };
567
682
  }
568
683
  // ---------------------------------------------------------------- 0 ----
@@ -573,14 +688,21 @@ export function registerTools(server, client, config, auth, options = {}) {
573
688
  description: 'Report which Edgegap API this server talks to, its version, whether it is the local or ' +
574
689
  'hosted server, and the guardrails in force: read-only mode, application allowlist, ' +
575
690
  'max_duration ceiling, the agent deployment cap, the tag forced onto every deployment, and which tools support ' +
576
- 'dry_run. Call it first when unsure what this session is allowed to do, or before ' +
577
- 'anything billable. Makes no API call and never shows the token.',
578
- inputSchema: {},
691
+ 'dry_run. Also says whether this session has a usable token and, if not, why and how to fix it. Call it ' +
692
+ 'first when unsure what this session is allowed to do, before anything billable, or when tool calls fail ' +
693
+ 'with a token problem. Makes no API call unless check_token is true, and never shows the token.',
694
+ inputSchema: {
695
+ check_token: z
696
+ .boolean()
697
+ .optional()
698
+ .describe('Make one read-only API call (list one application) to confirm Edgegap accepts the token. Default false.'),
699
+ },
579
700
  outputSchema: OUTPUT.context,
580
701
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
581
- }, async () => {
702
+ }, async ({ check_token }) => {
582
703
  const hosted = config.transport === 'hosted';
583
- return ok({
704
+ const tokenStatus = await describeToken(client, auth, hosted, check_token === true);
705
+ return withMeta(ok({
584
706
  server: `@edgegap/mcp ${VERSION}`,
585
707
  transport: hosted ? 'hosted (Streamable HTTP)' : 'local (stdio)',
586
708
  api_host: label,
@@ -595,6 +717,7 @@ export function registerTools(server, client, config, auth, options = {}) {
595
717
  ? 'provided by the developer this session (memory only)'
596
718
  : 'not yet provided: the developer is asked on first use',
597
719
  token_scope: 'organization-wide (Edgegap cannot scope tokens)',
720
+ token_status: tokenStatus,
598
721
  read_only: config.readOnly,
599
722
  app_allowlist: config.appAllowlist.length ? config.appAllowlist : 'none (all applications)',
600
723
  max_duration_ceiling_minutes: config.maxDurationCeiling,
@@ -616,7 +739,8 @@ export function registerTools(server, client, config, auth, options = {}) {
616
739
  results: `every result starts with [${label}]`,
617
740
  },
618
741
  user_agent: `edgegap-mcp/${VERSION} (<MCP client name>)`,
619
- });
742
+ works_without_token: TOKENLESS_TOOLS,
743
+ }), { props: { token_state: String(tokenStatus.state) } });
620
744
  });
621
745
  // ---------------------------------------------------------------- 1 ----
622
746
  tool('edgegap_list_apps', {
@@ -625,19 +749,34 @@ export function registerTools(server, client, config, auth, options = {}) {
625
749
  'deploying anything, so you reuse an existing application instead of making a duplicate. ' +
626
750
  'An "application" groups versions of one game server.',
627
751
  inputSchema: {
628
- limit: z.number().int().min(1).max(100).optional().describe('Results per page. Default 50.'),
629
- page: z.number().int().min(1).optional(),
752
+ limit: z.number().int().optional().describe('Results per page, 1-100. Default 50.'),
753
+ page: z.number().int().optional(),
630
754
  },
631
755
  outputSchema: OUTPUT.listApps,
632
756
  annotations: { readOnlyHint: true, openWorldHint: true },
633
757
  }, async ({ limit, page }) => guard(auth, async () => {
634
- const res = await client.listApps({ limit: limit ?? 50, page });
758
+ const p = clamp(page, 1, 100_000, 1);
759
+ const res = await client.listApps({ limit: clamp(limit, 1, 100, 50), page: page === undefined ? undefined : p });
635
760
  const apps = (res.applications ?? []).map((a) => ({
636
761
  name: a.name,
637
762
  active: a.is_active,
638
763
  last_updated: a.last_updated,
639
764
  }));
640
- return ok({ ...pageInfo(res.total_count, apps.length, page ?? 1), applications: apps });
765
+ if (apps.length === 0 && p === 1) {
766
+ return emptyState('empty', { total: 0, applications: [] }, 'This organization has no applications yet. Create one with edgegap_create_app (usually named after ' +
767
+ 'the game), then register the server image with edgegap_create_app_version.');
768
+ }
769
+ const info = pageInfo(res.total_count, apps.length, p);
770
+ return withMeta(ok({
771
+ ...info,
772
+ applications: apps,
773
+ ...('next_step' in info
774
+ ? {}
775
+ : {
776
+ next_step: 'Reuse the application that matches this game: edgegap_list_app_versions shows its versions. ' +
777
+ 'Only if none fits, create one with edgegap_create_app.',
778
+ }),
779
+ }), { props: { item_count: apps.length }, milestones: ['app_created'] });
641
780
  }));
642
781
  // ---------------------------------------------------------------- 2 ----
643
782
  if (mutating) {
@@ -665,11 +804,11 @@ export function registerTools(server, client, config, auth, options = {}) {
665
804
  return dryRunResult(dry.requests);
666
805
  }
667
806
  const res = await client.createApp(body);
668
- return ok({
807
+ return withMeta(ok({
669
808
  created: res.name,
670
809
  active: res.is_active,
671
810
  next_step: 'Call edgegap_create_app_version to attach a container image.',
672
- });
811
+ }), { milestones: ['app_created'] });
673
812
  }));
674
813
  }
675
814
  // --------------------------------------------------------------- 2b ----
@@ -716,7 +855,16 @@ export function registerTools(server, client, config, auth, options = {}) {
716
855
  guarded(auth, NOT_FOUND.app, async () => {
717
856
  const res = await client.listAppVersions(application);
718
857
  const versions = (res.versions ?? []).map(compactVersion);
719
- return ok({ application, ...pageInfo(res.total_count, versions.length, 1), versions });
858
+ if (versions.length === 0) {
859
+ return emptyState('empty', { application, total: 0, versions: [] }, `Application "${application}" has no versions yet. Push the server image, confirm it with ` +
860
+ 'edgegap_list_registry_tags, then register it with edgegap_create_app_version.');
861
+ }
862
+ return withMeta(ok({
863
+ application,
864
+ ...pageInfo(res.total_count, versions.length, 1),
865
+ versions,
866
+ next_step: 'Deploy an active version with edgegap_deploy, or register a new image with edgegap_create_app_version.',
867
+ }), { props: { item_count: versions.length } });
720
868
  }));
721
869
  // --------------------------------------------------------------- 3b ----
722
870
  tool('edgegap_get_app_version', {
@@ -897,13 +1045,14 @@ export function registerTools(server, client, config, auth, options = {}) {
897
1045
  'they need wss://: create the version with tls_upgrade: true on this port.');
898
1046
  }
899
1047
  }
900
- return ok({
1048
+ return withMeta(ok({
901
1049
  created: `${args.application}/${res.version?.name ?? args.name}`,
902
1050
  max_duration_minutes: capped,
903
1051
  capped_by_server: capped < requested ? config.maxDurationCeiling : undefined,
904
1052
  notes: notes.length ? notes : undefined,
905
- next_step: 'Call edgegap_deploy to start an instance.',
906
- });
1053
+ next_step: `Call edgegap_deploy with application "${args.application}" and version ` +
1054
+ `"${res.version?.name ?? args.name}" to start a server, then edgegap_wait_for_deployment.`,
1055
+ }), { milestones: ['app_version_created'], props: { registry_login_set: hasRegistryLogin } });
907
1056
  }));
908
1057
  }
909
1058
  // --------------------------------------------------------------- 4b ----
@@ -1216,14 +1365,14 @@ export function registerTools(server, client, config, auth, options = {}) {
1216
1365
  }
1217
1366
  }
1218
1367
  const res = await client.deploy(body);
1219
- return ok({
1368
+ return withMeta(ok({
1220
1369
  request_id: res.request_id,
1221
1370
  status: 'starting',
1222
1371
  tags,
1223
1372
  ...autoStop(version.max_duration),
1224
1373
  resources: body.resources,
1225
1374
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
1226
- });
1375
+ }), { hash: { request_id: res.request_id }, props: { resources_override: body.resources !== undefined } });
1227
1376
  }));
1228
1377
  }
1229
1378
  // ---------------------------------------------------------------- 6 ----
@@ -1239,7 +1388,13 @@ export function registerTools(server, client, config, auth, options = {}) {
1239
1388
  annotations: { readOnlyHint: true, openWorldHint: true },
1240
1389
  }, async ({ request_id }) => guarded(auth, NOT_FOUND.deployment, async () => {
1241
1390
  const d = await client.getDeployment(request_id);
1242
- return ok(compactDeployment(d));
1391
+ const status = (d.current_status ?? '').toUpperCase();
1392
+ const nextStep = d.error || TERMINAL_BAD.some((s) => status.includes(s))
1393
+ ? `It failed or stopped. Read why with edgegap_get_deployment_logs {request_id: "${request_id}"} before redeploying.`
1394
+ : d.running || TERMINAL_OK.some((s) => status.includes(s))
1395
+ ? `Players connect to fqdn on each port's external number. Stop it with edgegap_stop_deployment {request_id: "${request_id}"} when done: it bills while running.`
1396
+ : `Still starting. Call edgegap_wait_for_deployment {request_id: "${request_id}"} instead of polling this.`;
1397
+ return ok({ ...compactDeployment(d), next_step: nextStep });
1243
1398
  }));
1244
1399
  // ---------------------------------------------------------------- 7 ----
1245
1400
  tool('edgegap_wait_for_deployment', {
@@ -1253,51 +1408,65 @@ export function registerTools(server, client, config, auth, options = {}) {
1253
1408
  timeout_seconds: z
1254
1409
  .number()
1255
1410
  .int()
1256
- .min(5)
1257
- .max(600)
1258
1411
  .optional()
1259
- .describe('How long to wait before giving up. Default 180.'),
1412
+ .describe('How long to wait before giving up, 5-600. Default 180.'),
1260
1413
  },
1261
1414
  outputSchema: OUTPUT.waitForDeployment,
1262
1415
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
1263
- }, async ({ request_id, timeout_seconds }) => guarded(auth, NOT_FOUND.deployment, async () => {
1264
- const budgetMs = (timeout_seconds ?? 180) * 1000;
1416
+ }, async ({ request_id, timeout_seconds }, extra) => guarded(auth, NOT_FOUND.deployment, async () => {
1417
+ const timeoutSeconds = clamp(timeout_seconds, 5, 600, 180);
1418
+ const budgetMs = timeoutSeconds * 1000;
1265
1419
  const startedAt = Date.now();
1266
1420
  let intervalMs = 2000;
1421
+ let polls = 0;
1267
1422
  let last;
1423
+ const progress = progressReporter(extra, timeoutSeconds);
1424
+ const facts = (outcome) => ({
1425
+ props: { outcome, final_status: last?.current_status ?? 'unknown', timeout_ms_configured: budgetMs, poll_count: polls },
1426
+ hash: { request_id },
1427
+ });
1268
1428
  while (Date.now() - startedAt < budgetMs) {
1269
1429
  last = await client.getDeployment(request_id);
1430
+ polls++;
1270
1431
  const status = (last.current_status ?? '').toUpperCase();
1271
1432
  if (last.error || TERMINAL_BAD.some((s) => status.includes(s))) {
1272
1433
  // Fetched now, not left to the agent: a failed deployment is
1273
1434
  // cleaned up quickly and its logs go with it, so a separate
1274
1435
  // edgegap_get_deployment_logs call often finds nothing.
1275
1436
  const logs = await logTail(client, request_id, 3000);
1276
- return fail(`Deployment ${request_id} failed with status ${last.current_status}.\n` +
1437
+ return withMeta(fail(`Deployment ${request_id} failed with status ${last.current_status}.\n` +
1277
1438
  `${last.error_detail ?? 'No error detail returned.'}\n\n` +
1278
1439
  (logs
1279
- ? `Container output (tail):\n${logs}\n\nFix the image or port configuration before redeploying.`
1280
- : `No container logs could be read (the container may never have started, or it ` +
1281
- `was already cleaned up). Check the image, tag and ports before redeploying.`));
1440
+ ? `Container output (tail):\n${logs}\n\nFix the image or port configuration before redeploying. ` +
1441
+ 'Do not redeploy the same version unchanged: it will fail the same way.'
1442
+ : `No container logs could be read here (the container may never have started, or it ` +
1443
+ `was already cleaned up). Try edgegap_get_deployment_logs {request_id: "${request_id}"} once; ` +
1444
+ 'if it has nothing either, check the image, tag and ports before redeploying.'), 'DEPLOYMENT_FAILED'), { ...facts('error'), stage: 'upstream' });
1282
1445
  }
1283
1446
  if (last.running || TERMINAL_OK.some((s) => status.includes(s))) {
1284
- return ok({
1447
+ return withMeta(ok({
1285
1448
  ...compactDeployment(last),
1286
1449
  waited_seconds: Math.round((Date.now() - startedAt) / 1000),
1287
- });
1450
+ cost_reminder: 'This server bills while it runs. When testing is done, stop it with ' +
1451
+ `edgegap_stop_deployment {request_id: "${request_id}"} unless the developer wants it kept running.`,
1452
+ next_step: `Players connect to ${last.fqdn ?? 'the fqdn above'} on each port's external number. ` +
1453
+ `When finished: edgegap_stop_deployment {request_id: "${request_id}"}.`,
1454
+ }), { ...facts('ready'), milestones: ['deployment_ready'] });
1288
1455
  }
1456
+ await progress(Date.now() - startedAt, `Deployment ${request_id}: ${last.current_status ?? 'starting'}`);
1289
1457
  await new Promise((r) => setTimeout(r, intervalMs));
1290
1458
  intervalMs = Math.min(intervalMs * 1.5, 10_000);
1291
1459
  }
1292
1460
  // Not an error: the wait ran out, the deployment did not fail. It is
1293
1461
  // usually still starting (large images pull slowly on a cold host).
1294
- return ok({
1462
+ return withMeta(ok({
1295
1463
  ...(last ? compactDeployment(last) : { request_id }),
1296
1464
  ready: false,
1297
1465
  waited_seconds: Math.round((Date.now() - startedAt) / 1000),
1298
- next_step: `Not ready within ${timeout_seconds ?? 180}s, and not failed: it may still be starting. ` +
1299
- `Call edgegap_wait_for_deployment again, or edgegap_stop_deployment if it should not keep running.`,
1300
- });
1466
+ next_step: `Not ready within ${timeoutSeconds}s, and not failed: it is still ${last?.current_status ?? 'starting'}. ` +
1467
+ `Call edgegap_wait_for_deployment again with request_id "${request_id}" to keep waiting; do not deploy ` +
1468
+ `a second server. Stop it with edgegap_stop_deployment if it should not keep running.`,
1469
+ }), facts('timeout'));
1301
1470
  }));
1302
1471
  // ---------------------------------------------------------------- 8 ----
1303
1472
  tool('edgegap_list_deployments', {
@@ -1337,7 +1506,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1337
1506
  }))
1338
1507
  .optional()
1339
1508
  .describe('e.g. [{field:"created_at",order:"asc"}] for oldest first.'),
1340
- limit: z.number().int().min(1).max(100).optional().describe('Default 50.'),
1509
+ limit: z.number().int().optional().describe('1-100. Default 50.'),
1341
1510
  },
1342
1511
  outputSchema: OUTPUT.listDeployments,
1343
1512
  annotations: { readOnlyHint: true, openWorldHint: true },
@@ -1357,7 +1526,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1357
1526
  const query = filters?.length || order_by?.length
1358
1527
  ? JSON.stringify({ filters: filters ?? [], ...(order_by?.length ? { order_by } : {}) })
1359
1528
  : undefined;
1360
- const res = await client.listDeployments({ query, limit: limit ?? 50 });
1529
+ const res = await client.listDeployments({ query, limit: clamp(limit, 1, 100, 50) });
1361
1530
  const rows = (res.data ?? []).map((d) => ({
1362
1531
  request_id: d.request_id,
1363
1532
  ready: d.ready,
@@ -1365,7 +1534,23 @@ export function registerTools(server, client, config, auth, options = {}) {
1365
1534
  started: d.start_time,
1366
1535
  tags: d.tags,
1367
1536
  }));
1368
- return ok({ ...pageInfo(res.total_count, rows.length, 1), deployments: rows });
1537
+ if (rows.length === 0) {
1538
+ return emptyState('empty', { total: 0, deployments: [] }, only_agent_deployments
1539
+ ? 'No deployment started through this server is running: nothing is left to stop.'
1540
+ : filters?.length
1541
+ ? 'No running deployment matches these filters.'
1542
+ : 'No deployments are running. Start one with edgegap_deploy.');
1543
+ }
1544
+ const info = pageInfo(res.total_count, rows.length, 1);
1545
+ return withMeta(ok({
1546
+ ...info,
1547
+ deployments: rows,
1548
+ ...('next_step' in info
1549
+ ? {}
1550
+ : {
1551
+ next_step: 'Stop the ones you started and no longer need with edgegap_stop_deployment, one request_id per call.',
1552
+ }),
1553
+ }), { props: { item_count: rows.length, only_agent_deployments: only_agent_deployments === true } });
1369
1554
  }));
1370
1555
  // ---------------------------------------------------------------- 9 ----
1371
1556
  if (mutating) {
@@ -1396,10 +1581,14 @@ export function registerTools(server, client, config, auth, options = {}) {
1396
1581
  catch (err) {
1397
1582
  const gone = await alreadyStopped(client, request_id, err);
1398
1583
  if (gone)
1399
- return ok(gone);
1584
+ return withMeta(ok(gone), { hash: { request_id }, props: { stop_result: gone.result } });
1400
1585
  throw err;
1401
1586
  }
1402
- return ok({ request_id, result: res.message ?? 'stop requested' });
1587
+ return withMeta(ok({
1588
+ request_id,
1589
+ result: res.message ?? 'stop requested',
1590
+ next_step: 'Before ending the task, confirm nothing else is left with edgegap_list_deployments only_agent_deployments: true.',
1591
+ }), { hash: { request_id }, milestones: ['deployment_stopped'], props: { stop_result: 'stopped' } });
1403
1592
  }));
1404
1593
  }
1405
1594
  // --------------------------------------------------------------- 10 ----
@@ -1414,19 +1603,30 @@ export function registerTools(server, client, config, auth, options = {}) {
1414
1603
  max_characters: z
1415
1604
  .number()
1416
1605
  .int()
1417
- .min(500)
1418
- .max(50_000)
1419
1606
  .optional()
1420
- .describe('Truncate logs to this length, keeping the tail. Default 8000.'),
1607
+ .describe('Truncate logs to this length (500-50000), keeping the tail. Default 8000.'),
1421
1608
  },
1422
1609
  annotations: { readOnlyHint: true, openWorldHint: true },
1423
1610
  }, async ({ request_id, max_characters }) => guarded(auth, NOT_FOUND.logs, async () => {
1424
- const res = await client.getDeploymentLogs(request_id);
1425
- const cap = max_characters ?? 8000;
1611
+ let res;
1612
+ try {
1613
+ res = await client.getDeploymentLogs(request_id);
1614
+ }
1615
+ catch (err) {
1616
+ // The logs endpoint answers 400 for every "no logs" case alike. Ask
1617
+ // the status endpoint which one this is.
1618
+ if (!(err instanceof EdgegapApiError) || ![400, 404].includes(err.status))
1619
+ throw err;
1620
+ const why = await whyNoLogs(client, request_id);
1621
+ if (!why)
1622
+ throw err;
1623
+ return why;
1624
+ }
1625
+ const cap = clamp(max_characters, 500, 50_000, 8000);
1426
1626
  const tail = (s) => !s ? undefined : s.length > cap ? `...[truncated]...\n${s.slice(-cap)}` : s;
1427
1627
  return ok({
1428
1628
  request_id,
1429
- logs: tail(res.logs) ?? '(no logs returned)',
1629
+ logs: tail(res.logs) ?? '(no logs returned yet: the server has printed nothing)',
1430
1630
  crash_logs: tail(res.crash_logs),
1431
1631
  exit_code: res.crash_data?.exit_code,
1432
1632
  crash_message: res.crash_data?.message,
@@ -1610,7 +1810,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1610
1810
  ? generateDockerfile({ engine, ports: args.ports, netcode: args.netcode }).dockerfile
1611
1811
  : undefined;
1612
1812
  const verdict = errors.length > 0 ? 'fail' : warnings.length > 0 ? 'pass_with_warnings' : 'pass';
1613
- return ok({
1813
+ return withMeta(ok({
1614
1814
  verdict,
1615
1815
  engine,
1616
1816
  errors,
@@ -1628,6 +1828,15 @@ export function registerTools(server, client, config, auth, options = {}) {
1628
1828
  : 'Build with "docker build --platform linux/amd64 -t <image>:<unique-tag> ." and run it ' +
1629
1829
  'locally with the same port mapping to confirm it starts. Then push it; ' +
1630
1830
  'edgegap_get_registry_credentials gives you a registry and the exact commands.',
1831
+ }), {
1832
+ props: {
1833
+ validation_result: errors.length > 0 ? 'fail' : 'pass',
1834
+ issue_count: errors.length + warnings.length,
1835
+ error_count: errors.length,
1836
+ warning_count: warnings.length,
1837
+ engine,
1838
+ checked_dockerfile: args.dockerfile !== undefined,
1839
+ },
1631
1840
  });
1632
1841
  });
1633
1842
  // --------------------------------------------------------------- 12 ----
@@ -1645,7 +1854,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1645
1854
  'do not retry. When it does return a token, it is registry-scoped (push/pull images in ' +
1646
1855
  'this project), not the org API token: pass it to docker login via --password-stdin, ' +
1647
1856
  'never as a command-line argument, and do not write it into files. Call ' +
1648
- 'edgegap_validate_server_config before building.',
1857
+ 'edgegap_validate_server_config before building. Any other registry Edgegap can pull from ' +
1858
+ '(Docker Hub, GHCR, ECR, GitLab) works too: then skip this tool and pass that registry and its ' +
1859
+ 'pull login to edgegap_create_app_version.',
1649
1860
  inputSchema: {
1650
1861
  image_name: z
1651
1862
  .string()
@@ -1695,7 +1906,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1695
1906
  const image = image_name ?? '<image-name>';
1696
1907
  const buildTag = tag ?? '<unique-build-tag>';
1697
1908
  const ref = `${host}/${creds.project}/${image}:${buildTag}`;
1698
- return ok({
1909
+ return withMeta(ok({
1699
1910
  registry_url: host,
1700
1911
  project: creds.project,
1701
1912
  username: creds.username,
@@ -1717,7 +1928,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1717
1928
  '(it never needs to appear in a command line or file), then build and push. ' +
1718
1929
  `Confirm the push with edgegap_list_registry_tags (image_name "${image}", without the project), ` +
1719
1930
  'then call edgegap_create_app_version with the values in for_create_app_version.',
1720
- });
1931
+ }), { milestones: ['registry_credentials_ok'], props: { registry_status: 'credentials_returned' } });
1721
1932
  }));
1722
1933
  }
1723
1934
  // --------------------------------------------------------------- 13 ----
@@ -1725,7 +1936,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1725
1936
  title: 'List image tags in the Edgegap registry',
1726
1937
  description: 'List the tags pushed for one image in this organization\'s Edgegap container registry, ' +
1727
1938
  'with push time and size. Call it after docker push to confirm the tag landed before ' +
1728
- 'edgegap_create_app_version, which otherwise fails later with an image-pull error.',
1939
+ 'edgegap_create_app_version, which otherwise fails later with an image-pull error. An image ' +
1940
+ 'that was never pushed comes back as status "not_found" with no tags, not as an error. Only ' +
1941
+ 'for registry.edgegap.com: images in Docker Hub, GHCR or another registry are not listed here.',
1729
1942
  inputSchema: {
1730
1943
  image_name: z
1731
1944
  .string()
@@ -1733,7 +1946,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1733
1946
  .describe('The image name only, without the project, registry host or tag, e.g. "my-game-server". ' +
1734
1947
  'The API reads the project from your token; "<project>/my-game-server" is not found.'),
1735
1948
  page: z.number().int().min(1).optional(),
1736
- limit: z.number().int().min(1).max(100).optional().describe('Default 20.'),
1949
+ limit: z.number().int().optional().describe('1-100. Default 20.'),
1737
1950
  },
1738
1951
  outputSchema: OUTPUT.listRegistryTags,
1739
1952
  annotations: { readOnlyHint: true, openWorldHint: true },
@@ -1741,7 +1954,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1741
1954
  // Agents often pass the full reference they pushed. Reduce it to what
1742
1955
  // the API wants: no "registry.edgegap.com/" host, no ":tag".
1743
1956
  let name = imageNameOnly(image_name);
1744
- const query = { page, limit: limit ?? 20 };
1957
+ const query = { page, limit: clamp(limit, 1, 100, 20) };
1745
1958
  const notFound = (err) => err instanceof EdgegapApiError && err.status === 404;
1746
1959
  let res;
1747
1960
  try {
@@ -1758,12 +1971,20 @@ export function registerTools(server, client, config, auth, options = {}) {
1758
1971
  }
1759
1972
  }
1760
1973
  catch (err) {
1761
- // The generic 404 hint points at applications, which is wrong here.
1762
- if (!notFound(err))
1763
- throw err;
1764
- return fail(`No image named "${name}" in this organization's Edgegap registry, so nothing has been ` +
1765
- 'pushed under that name. Check the name (image name only, as used after ' +
1766
- '"registry.edgegap.com/<project>/" in docker push), or push the image first.');
1974
+ // Nothing pushed under that name is a state, not a failure: the
1975
+ // answer to "did my push land?" is "no, push it".
1976
+ if (notFound(err)) {
1977
+ return emptyState('not_found', { image_name: name, total: 0, tags: [] }, `Nothing has been pushed as "${name}" to this organization's Edgegap registry. Check the name (image ` +
1978
+ 'name only, as used after "registry.edgegap.com/<project>/" in docker push), or push the image ' +
1979
+ 'first (edgegap_get_registry_credentials has the commands). If the image lives in Docker Hub, GHCR ' +
1980
+ 'or another registry, skip this check and pass that registry to edgegap_create_app_version.');
1981
+ }
1982
+ if (err instanceof EdgegapApiError && err.status === 403) {
1983
+ return emptyState('not_configured', { image_name: name, total: 0, tags: [] }, 'This token cannot read an Edgegap container registry for this organization (403). Ask the developer ' +
1984
+ 'to open the Container Registry page of the dashboard (https://app.edgegap.com), or push the image to ' +
1985
+ 'Docker Hub, GHCR or another registry and pass it to edgegap_create_app_version with its pull login.');
1986
+ }
1987
+ throw err;
1767
1988
  }
1768
1989
  const tags = (res.data ?? []).map((t) => ({
1769
1990
  tag: t.tag,
@@ -1772,7 +1993,10 @@ export function registerTools(server, client, config, auth, options = {}) {
1772
1993
  digest: t.artifact?.image_hash,
1773
1994
  }));
1774
1995
  const hasNext = res.pagination?.has_next === true;
1775
- return ok({
1996
+ if (tags.length === 0 && !hasNext && (page ?? 1) === 1) {
1997
+ return emptyState('empty', { image_name: name, total: 0, tags: [] }, `The image "${name}" exists but has no tags. Push a build with a unique tag (never "latest"), then check again.`);
1998
+ }
1999
+ return withMeta(ok({
1776
2000
  image_name: name,
1777
2001
  note: name !== image_name ? `Looked up "${name}". Pass the image name only next time.` : undefined,
1778
2002
  total: res.count ?? tags.length,
@@ -1782,9 +2006,12 @@ export function registerTools(server, client, config, auth, options = {}) {
1782
2006
  truncated: true,
1783
2007
  next_step: `Only page ${page ?? 1} is shown. Call again with page: ${(page ?? 1) + 1} before concluding a tag is missing.`,
1784
2008
  }
1785
- : {}),
2009
+ : {
2010
+ next_step: 'If the tag you pushed is listed, register it with edgegap_create_app_version (docker_repository ' +
2011
+ `"registry.edgegap.com", docker_image "<project>/${name}", and that tag).`,
2012
+ }),
1786
2013
  tags,
1787
- });
2014
+ }), { props: { item_count: tags.length }, milestones: tags.length ? ['image_pushed'] : [] });
1788
2015
  }));
1789
2016
  // --------------------------------------------------------------- 13b ----
1790
2017
  if (mutating) {
@@ -1930,7 +2157,22 @@ export function registerTools(server, client, config, auth, options = {}) {
1930
2157
  outputSchema: OUTPUT.listRelaySessions,
1931
2158
  annotations: { readOnlyHint: true, openWorldHint: true },
1932
2159
  }, async () => guard(auth, async () => {
1933
- const res = await client.listRelaySessions();
2160
+ let res;
2161
+ try {
2162
+ res = await client.listRelaySessions();
2163
+ }
2164
+ catch (err) {
2165
+ // An organization without relays gets 403 here. Listing has nothing
2166
+ // to correct: there are no sessions, and none can be billing.
2167
+ if (!(err instanceof EdgegapApiError) || err.status !== 403)
2168
+ throw err;
2169
+ return emptyState('not_configured', { total: 0, sessions: [] }, 'This organization cannot use relays (the API answered 403), so no relay sessions exist or bill. ' +
2170
+ 'Relays are not enabled on every plan; check the Relays page of the dashboard or ask Edgegap support. ' +
2171
+ 'For a multiplayer match, a dedicated server (edgegap_deploy) needs no relay.');
2172
+ }
2173
+ if ((res.sessions ?? []).length === 0) {
2174
+ return emptyState('empty', { total: 0, sessions: [] }, 'No relay sessions are open, so none are billing.');
2175
+ }
1934
2176
  const sessions = (res.sessions ?? []).map((r) => ({
1935
2177
  session_id: r.session_id,
1936
2178
  status: r.status,
@@ -2067,6 +2309,7 @@ export function registerTools(server, client, config, auth, options = {}) {
2067
2309
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
2068
2310
  assertAppAllowed(config, args.application);
2069
2311
  const { config: mmConfig, problems, cautions } = buildMatchmakerConfig(args);
2312
+ let verified = false;
2070
2313
  if (args.verify_version !== false) {
2071
2314
  try {
2072
2315
  const res = await client.listAppVersions(args.application);
@@ -2081,22 +2324,39 @@ export function registerTools(server, client, config, auth, options = {}) {
2081
2324
  if (!v.ports?.length)
2082
2325
  problems.push(`Version "${args.version}" has no ports, so matched players have nothing to connect to.`);
2083
2326
  }
2327
+ verified = true;
2084
2328
  }
2085
2329
  catch (err) {
2086
2330
  if (err instanceof EdgegapApiError && err.status === 404) {
2087
2331
  problems.push(`Application "${args.application}" does not exist. Call edgegap_list_apps.`);
2088
2332
  }
2333
+ else if (err instanceof TokenUnavailableError && err.reason !== 'declined') {
2334
+ // Building the config needs no token; only the version check
2335
+ // does. Without one, hand back the config and say what was skipped.
2336
+ cautions.push(`Not checked against Edgegap: this session has no API token, so whether "${args.application}/${args.version}" ` +
2337
+ 'exists, is active and has ports was not verified. Check it in the dashboard before uploading.');
2338
+ }
2089
2339
  else {
2090
2340
  throw err;
2091
2341
  }
2092
2342
  }
2093
2343
  }
2344
+ const facts = {
2345
+ props: {
2346
+ matchmaker_template: 'single_profile',
2347
+ team_count: args.team_count,
2348
+ has_latency_rule: args.max_latency_ms !== undefined,
2349
+ expansion_count: args.expansions?.length ?? 0,
2350
+ problem_count: problems.length,
2351
+ version_verified: verified,
2352
+ },
2353
+ };
2094
2354
  if (problems.length > 0) {
2095
- return fail('The matchmaker configuration has problems; fix them before uploading:\n- ' +
2355
+ return withMeta(fail(`The matchmaker configuration has ${problems.length} problem${problems.length === 1 ? '' : 's'}; fix all of them before uploading:\n- ` +
2096
2356
  problems.join('\n- ') +
2097
- `\n\nDraft config:\n${JSON.stringify(mmConfig, null, 2)}`);
2357
+ `\n\nDraft config:\n${JSON.stringify(mmConfig, null, 2)}`, 'VALIDATION_FAILED'), facts);
2098
2358
  }
2099
- return ok({
2359
+ return withMeta(ok({
2100
2360
  config: mmConfig,
2101
2361
  cautions: cautions.length ? cautions : undefined,
2102
2362
  next_steps: [
@@ -2113,7 +2373,7 @@ export function registerTools(server, client, config, auth, options = {}) {
2113
2373
  ? `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.`
2114
2374
  : '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.',
2115
2375
  ],
2116
- });
2376
+ }), facts);
2117
2377
  }));
2118
2378
  registerSkills(server, tool, config, options);
2119
2379
  }
@@ -2183,12 +2443,14 @@ function registerSkills(server, tool, config, options) {
2183
2443
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
2184
2444
  }, async ({ skill: name, file }) => {
2185
2445
  const skill = findSkill(name);
2186
- if (!skill)
2187
- return fail(`No skill named "${name}". The skills are: ${names.join(', ')}.`);
2446
+ if (!skill) {
2447
+ const guess = closestSkill(name, names);
2448
+ return withMeta(fail(`No skill named "${name}".${guess ? ` Did you mean "${guess}"?` : ''} The skills are: ${names.join(', ')}.`, 'SKILL_NOT_FOUND'), { props: { skill_name: name.slice(0, 60) } });
2449
+ }
2188
2450
  const found = findSkillFile(skill, file);
2189
2451
  if (!found) {
2190
- return fail(`"${file}" is not a file in the ${skill.name} skill. Its files are:\n` +
2191
- skill.files.map((f) => `- ${f.path}`).join('\n'));
2452
+ return withMeta(fail(`"${file}" is not a file in the ${skill.name} skill. Its files are:\n` +
2453
+ ['SKILL.md', ...fileIndex(skill)].map((p) => `- ${p}`).join('\n'), 'SKILL_NOT_FOUND'), { props: { skill_name: skill.name, skill_file: String(file).slice(0, 120) } });
2192
2454
  }
2193
2455
  const status = found.path === 'SKILL.md' ? servedPackStatus(await latestPack(check), hosted) : undefined;
2194
2456
  const header = `${skill.name} ${skill.version} · ${found.path} · pack ${pack}` +
@@ -2197,7 +2459,10 @@ function registerSkills(server, tool, config, options) {
2197
2459
  const footer = others.length
2198
2460
  ? `\n\n---\nOther files in this skill:\n${others.map((p) => `- ${p}`).join('\n')}\n\n${howToFetch(skill.name)}`
2199
2461
  : '';
2200
- return { content: [{ type: 'text', text: `${header}\n\n${found.content}${footer}` }] };
2462
+ return {
2463
+ content: [{ type: 'text', text: `${header}\n\n${found.content}${footer}` }],
2464
+ meta: { props: { skill_name: skill.name, skill_file: found.path, resource_uri: skillUri(skill.name, found.path) } },
2465
+ };
2201
2466
  });
2202
2467
  tool('edgegap_update_skills', {
2203
2468
  title: 'Check and update the installed Edgegap skills',
@@ -2344,6 +2609,37 @@ function registerSkills(server, tool, config, options) {
2344
2609
  '(in Claude Code, /reload-plugins also works for the plugin) to use the update.';
2345
2610
  return failed ? { ...ok(result), isError: true } : ok(result);
2346
2611
  });
2612
+ // The one obvious place to start: a prompt that runs the golden path for
2613
+ // whatever engine and netcode the project uses.
2614
+ server.registerPrompt('deploy-game-server', {
2615
+ title: 'Deploy my game server to Edgegap',
2616
+ description: 'Start here. Detects the project\'s engine and netcode, loads the matching Edgegap skill, and walks the golden ' +
2617
+ 'path to a running dedicated server: Dockerfile, registry, app version, deploy, wait, then stop.',
2618
+ }, () => ({
2619
+ description: 'Deploy this project\'s game server to Edgegap',
2620
+ messages: [
2621
+ {
2622
+ role: 'user',
2623
+ content: {
2624
+ type: 'text',
2625
+ text: 'Deploy this project\'s game server to Edgegap as an authoritative dedicated server.\n\n' +
2626
+ '1. Look at the project files to find the engine (Unity, Unreal, Godot, or a Node.js/other server) and ' +
2627
+ 'the netcode (NGO, FishNet, PurrNet, Mirror, Photon Fusion, Colyseus, Nakama, PlayFab...).\n' +
2628
+ '2. Load the matching skill with edgegap_get_skill (edgegap_list_skills says which; "edgegap" if unsure) ' +
2629
+ 'and follow it over anything below.\n' +
2630
+ '3. Golden path: edgegap_generate_dockerfile (or edgegap_validate_server_config on an existing ' +
2631
+ 'Dockerfile) → edgegap_get_registry_credentials, build and push → edgegap_list_registry_tags → ' +
2632
+ 'edgegap_list_apps / edgegap_create_app → edgegap_create_app_version → edgegap_deploy → ' +
2633
+ 'edgegap_wait_for_deployment → edgegap_stop_deployment when done.\n' +
2634
+ '4. Results with a status such as "empty" or "not_configured" are normal states: do what their ' +
2635
+ 'next_step says instead of retrying.\n' +
2636
+ '5. Before finishing, stop every deployment you started unless I ask to keep it, and confirm with ' +
2637
+ 'edgegap_list_deployments only_agent_deployments: true.\n\n' +
2638
+ 'Ask me before anything you are unsure of, and use dry_run: true on a write you want to check first.',
2639
+ },
2640
+ },
2641
+ ],
2642
+ }));
2347
2643
  for (const skill of SKILLS_PACK.skills) {
2348
2644
  // A prompt per skill: in Claude Code these show up as slash commands.
2349
2645
  server.registerPrompt(skill.name, {
@@ -2368,7 +2664,7 @@ function registerSkills(server, tool, config, options) {
2368
2664
  ],
2369
2665
  };
2370
2666
  });
2371
- // Only each skill's SKILL.md is listed: 21 entries instead of every file
2667
+ // Only each skill's SKILL.md is listed: one entry per skill instead of every file
2372
2668
  // (257 in pack 0.15), which crowded clients' attach menus and resource
2373
2669
  // lists. The other files are read through the template below.
2374
2670
  const main = findSkillFile(skill);
@@ -2404,10 +2700,141 @@ function registerSkills(server, tool, config, options) {
2404
2700
  * call, and some agents retried it.
2405
2701
  */
2406
2702
  function manualStepsResult(steps) {
2703
+ const nextStep = 'Ask the developer for the registry Project, Username and Token from the Container Registry page, or ' +
2704
+ 'whether to use Docker Hub, GHCR or another registry instead. Do not call this tool again.';
2407
2705
  return {
2408
- content: [{ type: 'text', text: `status: manual_steps_required (no credentials returned)\n\n${steps}` }],
2409
- structuredContent: { status: 'manual_steps_required', credentials_returned: false, steps },
2706
+ content: [{ type: 'text', text: `status: manual_steps_required (no credentials returned)\n\n${steps}\n\nnext_step: ${nextStep}` }],
2707
+ structuredContent: { status: 'manual_steps_required', credentials_returned: false, steps, next_step: nextStep },
2708
+ meta: { props: { registry_status: 'manual_steps_required' } },
2709
+ };
2710
+ }
2711
+ /** A number argument pulled into range, so an agent's limit: 500 is served
2712
+ * as 100 instead of refused before the API is even called. */
2713
+ function clamp(value, min, max, fallback) {
2714
+ if (value === undefined || !Number.isFinite(value))
2715
+ return fallback;
2716
+ return Math.min(max, Math.max(min, Math.trunc(value)));
2717
+ }
2718
+ /** Tools that need no Edgegap token, for onboarding and the token messages. */
2719
+ const TOKENLESS_TOOLS = [
2720
+ 'edgegap_context',
2721
+ 'edgegap_list_skills',
2722
+ 'edgegap_get_skill',
2723
+ 'edgegap_generate_dockerfile',
2724
+ 'edgegap_validate_server_config',
2725
+ 'edgegap_build_matchmaker_config (without the version check)',
2726
+ ];
2727
+ /**
2728
+ * Whether this session can call the Edgegap API, and if not, why and how to
2729
+ * fix it. Never shows the token: only its last four characters, which is
2730
+ * what the developer needs to find it on the tokens page. Edgegap has no
2731
+ * endpoint that names the organization a token belongs to, so this cannot.
2732
+ */
2733
+ async function describeToken(client, auth, hosted, check) {
2734
+ const fix = `Create a token at ${TOKENS_URL} (no account yet? sign up free at ${SIGNUP_URL}).`;
2735
+ if (!auth.current) {
2736
+ if (!hosted) {
2737
+ return { state: 'not_provided', note: 'The developer is asked for a token on the first call that needs one.', fix };
2738
+ }
2739
+ try {
2740
+ await auth.get();
2741
+ }
2742
+ catch (err) {
2743
+ const reason = err instanceof TokenUnavailableError ? err.reason : 'absent';
2744
+ return {
2745
+ state: reason,
2746
+ note: reason === 'foreign'
2747
+ ? 'The Authorization header holds a credential the MCP client issued itself, not an Edgegap token. ' +
2748
+ 'This client cannot pass an Edgegap token to the hosted server: use the local server ' +
2749
+ '(npx -y @edgegap/mcp) with EDGEGAP_API_TOKEN instead.'
2750
+ : 'No Authorization header on this connection. Add "Authorization: token <your Edgegap token>" to the MCP client config.',
2751
+ fix,
2752
+ works_without_token: TOKENLESS_TOOLS,
2753
+ };
2754
+ }
2755
+ }
2756
+ const token = auth.current;
2757
+ const base = {
2758
+ token_ends_with: token ? `…${token.slice(-4)}` : undefined,
2759
+ organization: 'not reported: the Edgegap API has no endpoint that names a token\'s organization. Match the token by its last characters on the tokens page.',
2410
2760
  };
2761
+ if (!check)
2762
+ return { state: 'present (not checked)', ...base, note: 'Pass check_token: true to confirm Edgegap accepts it.' };
2763
+ try {
2764
+ await client.listApps({ limit: 1 });
2765
+ return { state: 'accepted', ...base };
2766
+ }
2767
+ catch (err) {
2768
+ if (err instanceof EdgegapApiError && err.status === 401) {
2769
+ return { state: 'rejected', ...base, note: 'Edgegap rejected this token: it was revoked, expired or mistyped.', fix };
2770
+ }
2771
+ return { state: 'unknown', ...base, note: `The check call failed: ${err.message.slice(0, 200)}` };
2772
+ }
2773
+ }
2774
+ const TOKENS_URL = 'https://app.edgegap.com/user-settings?tab=tokens';
2775
+ const SIGNUP_URL = 'https://app.edgegap.com';
2776
+ /**
2777
+ * Sends MCP progress notifications while a tool waits, when the client asked
2778
+ * for them (a progressToken in the request). Silently does nothing otherwise,
2779
+ * and a client that cannot take them never breaks the call.
2780
+ */
2781
+ function progressReporter(extra, totalSeconds) {
2782
+ const e = extra;
2783
+ const progressToken = e?._meta?.progressToken;
2784
+ const send = e?.sendNotification;
2785
+ if (progressToken === undefined || !send)
2786
+ return async (_elapsedMs, _message) => { };
2787
+ return async (elapsedMs, message) => {
2788
+ try {
2789
+ await send({
2790
+ method: 'notifications/progress',
2791
+ params: { progressToken, progress: Math.round(elapsedMs / 1000), total: totalSeconds, message },
2792
+ });
2793
+ }
2794
+ catch {
2795
+ // Progress is a courtesy; the wait goes on without it.
2796
+ }
2797
+ };
2798
+ }
2799
+ /**
2800
+ * Why a deployment has no logs, from its status: it does not exist (or is
2801
+ * another organization's), it has not started, or it has stopped and its logs
2802
+ * went with it. Undefined when the status does not explain it, so the caller
2803
+ * reports the original API error.
2804
+ */
2805
+ async function whyNoLogs(client, requestId) {
2806
+ let d;
2807
+ try {
2808
+ d = await client.getDeployment(requestId);
2809
+ }
2810
+ catch (err) {
2811
+ if (err instanceof EdgegapApiError && [400, 404].includes(err.status)) {
2812
+ return withMeta(fail(`No deployment with request_id "${requestId}" in this organization: it was never created here, belongs ` +
2813
+ 'to another organization, or stopped long enough ago to be cleaned up. Check the request_id with ' +
2814
+ 'edgegap_list_deployments.', 'DEPLOYMENT_NOT_FOUND'), { stage: 'upstream' });
2815
+ }
2816
+ return undefined;
2817
+ }
2818
+ const status = (d.current_status ?? '').toUpperCase();
2819
+ if (d.error || TERMINAL_BAD.some((s) => status.includes(s))) {
2820
+ return emptyState('expired', { request_id: requestId, deployment_status: d.current_status, error_detail: d.error_detail || undefined, logs: '' }, 'This deployment has stopped, and its container logs went with it (they are only kept when Endpoint ' +
2821
+ 'Storage was set on the version). error_detail is what Edgegap kept. Fix the cause and redeploy; ' +
2822
+ 'edgegap_wait_for_deployment returns the log tail itself when a start fails.');
2823
+ }
2824
+ if (!d.running && !TERMINAL_OK.some((s) => status.includes(s))) {
2825
+ return emptyState('not_ready', { request_id: requestId, deployment_status: d.current_status, logs: '' }, `The container has not started yet, so it has no logs. Call edgegap_wait_for_deployment {request_id: "${requestId}"}, ` +
2826
+ 'then read the logs if it fails or misbehaves.');
2827
+ }
2828
+ return undefined;
2829
+ }
2830
+ /** The skill name an agent most likely meant: "unity" → "edgegap-unity". */
2831
+ function closestSkill(input, names) {
2832
+ const wanted = input.trim().toLowerCase().replace(/^edgegap[-_ ]?/, '').replace(/[_ ]/g, '-');
2833
+ if (!wanted)
2834
+ return 'edgegap';
2835
+ return (names.find((n) => n === `edgegap-${wanted}`) ??
2836
+ names.find((n) => n.replace(/^edgegap-?/, '').startsWith(wanted)) ??
2837
+ names.find((n) => wanted.includes(n.replace(/^edgegap-/, '')) && n !== 'edgegap'));
2411
2838
  }
2412
2839
  function registryCredentialsUnavailable(imageName, tag) {
2413
2840
  const image = imageName ?? '<image-name>';