@edgegap/mcp 0.11.0 → 0.13.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,15 +9,16 @@
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';
16
16
  import { validateServerConfig, PROTOCOLS, NETCODE_NAMES, } from './serverconfig.js';
17
17
  import { generateDockerfile, DockerfileInputError } from './dockerfile.js';
18
18
  import { buildMatchmakerConfig, DASHBOARD_URL } from './matchmaker.js';
19
- import { badImage, badTag, looksSecret, TAG_FIX } from './image.js';
19
+ import { badImage, badTag, ENCRYPTED_PLACEHOLDER, isEncryptedPlaceholder, 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
@@ -462,6 +521,23 @@ function dryRunResult(requests, notes = []) {
462
521
  * Returns undefined when clean. In a dry run the token is only checked if this
463
522
  * session already holds one: a dry run must not trigger the token prompt.
464
523
  */
524
+ /**
525
+ * Refuses a registry login or env value that is the API's stand-in for a
526
+ * stored secret: it shows up when an agent copies an existing version's
527
+ * settings, and sent back it overwrites the real secret.
528
+ */
529
+ function encryptedPlaceholder(fields, keepHint) {
530
+ const hits = fields.filter(([, v]) => isEncryptedPlaceholder(v)).map(([label]) => label);
531
+ if (hits.length === 0)
532
+ return undefined;
533
+ return fail(`Refused: ${hits.join(', ')} ${hits.length > 1 ? 'are' : 'is'} "${ENCRYPTED_PLACEHOLDER}". Nothing was sent. ` +
534
+ 'That is the placeholder the Edgegap API returns instead of a stored secret, not the secret ' +
535
+ 'itself; saved, it replaces the real value and image pulls fail with "Unable to login". ' +
536
+ 'Copy only non-secret settings (image, resources, ports, non-secret env vars) from an ' +
537
+ 'existing version. The registry login comes from the dashboard\'s Container Registry page ' +
538
+ `(${DASHBOARD_URL}) for registry.edgegap.com, or from the developer for any other registry; ` +
539
+ `secret env values come from the developer. ${keepHint}`);
540
+ }
465
541
  async function tokenLeak(auth, dryRun, fields) {
466
542
  const token = dryRun ? auth.current : await auth.get();
467
543
  if (!token)
@@ -549,9 +625,51 @@ export function registerTools(server, client, config, auth, options = {}) {
549
625
  const label = hostLabel(config);
550
626
  // ...and never carries the API token, whatever the API echoed back.
551
627
  const inputs = new Map();
628
+ // The API statuses a call caused are the entries it added to client.upstream.
629
+ // Concurrent calls on one server would share entries; that only happens on
630
+ // the local server, which has no onToolCall. The list is cleared whenever no
631
+ // call is running, so it cannot grow.
632
+ const onToolCall = options.onToolCall;
633
+ let inFlight = 0;
552
634
  const tool = ((name, def, cb) => {
553
635
  inputs.set(name, (def.inputSchema) ?? {});
554
- return server.registerTool(name, def, (async (...a) => withHost(scrubToken(await cb(...a), auth.current), label)));
636
+ return server.registerTool(name, def, (async (...a) => {
637
+ const startedAt = Date.now();
638
+ const from = client.upstream.length;
639
+ inFlight++;
640
+ let result;
641
+ try {
642
+ result = withHost(scrubToken(await cb(...a), auth.current), label);
643
+ }
644
+ finally {
645
+ inFlight--;
646
+ }
647
+ const { meta, ...clean } = result;
648
+ if (onToolCall) {
649
+ const extra = a.find((x) => !!x && typeof x === 'object' && 'requestId' in x);
650
+ const args = a[0] && typeof a[0] === 'object' && a[0] !== extra ? a[0] : {};
651
+ try {
652
+ await onToolCall(finishReport({
653
+ tool: name,
654
+ requestId: extra?.requestId,
655
+ isError: clean.isError === true,
656
+ text: clean.content.map((c) => c.text).join('\n'),
657
+ token: auth.current,
658
+ args,
659
+ meta,
660
+ upstream: client.upstream.slice(from),
661
+ latencyMs: Date.now() - startedAt,
662
+ dryRun: args.dry_run === true,
663
+ }));
664
+ }
665
+ catch {
666
+ // Analytics never changes a result.
667
+ }
668
+ }
669
+ if (inFlight === 0)
670
+ client.upstream.length = 0;
671
+ return clean;
672
+ }));
555
673
  });
556
674
  // Errors the SDK raises itself (bad arguments, a handler that throws) skip
557
675
  // the wrapper above. Both SDK versions route them through createToolError,
@@ -562,7 +680,21 @@ export function registerTools(server, client, config, auth, options = {}) {
562
680
  if (sdkToolError) {
563
681
  sdk.createToolError = (message) => {
564
682
  const friendly = argumentError(message, inputs);
565
- return withHost(scrubToken(friendly ? fail(friendly) : sdkToolError(message), auth.current), label);
683
+ const result = withHost(scrubToken(friendly ? fail(friendly) : sdkToolError(message), auth.current), label);
684
+ // Rejected by the SDK before any handler ran: bad arguments or an unknown tool.
685
+ const named = message.match(/(?:Invalid arguments for tool|Tool) (\S+?):? /);
686
+ if (onToolCall && named) {
687
+ Promise.resolve(onToolCall(finishReport({
688
+ tool: named[1],
689
+ isError: true,
690
+ text: result.content.map((c) => c.text).join('\n'),
691
+ token: auth.current,
692
+ meta: { code: /not found/.test(message) ? 'NOT_FOUND' : 'VALIDATION_FAILED', stage: 'pre_flight' },
693
+ upstream: [],
694
+ latencyMs: 0,
695
+ }))).catch(() => { });
696
+ }
697
+ return result;
566
698
  };
567
699
  }
568
700
  // ---------------------------------------------------------------- 0 ----
@@ -573,14 +705,21 @@ export function registerTools(server, client, config, auth, options = {}) {
573
705
  description: 'Report which Edgegap API this server talks to, its version, whether it is the local or ' +
574
706
  'hosted server, and the guardrails in force: read-only mode, application allowlist, ' +
575
707
  '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: {},
708
+ 'dry_run. Also says whether this session has a usable token and, if not, why and how to fix it. Call it ' +
709
+ 'first when unsure what this session is allowed to do, before anything billable, or when tool calls fail ' +
710
+ 'with a token problem. Makes no API call unless check_token is true, and never shows the token.',
711
+ inputSchema: {
712
+ check_token: z
713
+ .boolean()
714
+ .optional()
715
+ .describe('Make one read-only API call (list one application) to confirm Edgegap accepts the token. Default false.'),
716
+ },
579
717
  outputSchema: OUTPUT.context,
580
718
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
581
- }, async () => {
719
+ }, async ({ check_token }) => {
582
720
  const hosted = config.transport === 'hosted';
583
- return ok({
721
+ const tokenStatus = await describeToken(client, auth, hosted, check_token === true);
722
+ return withMeta(ok({
584
723
  server: `@edgegap/mcp ${VERSION}`,
585
724
  transport: hosted ? 'hosted (Streamable HTTP)' : 'local (stdio)',
586
725
  api_host: label,
@@ -595,6 +734,7 @@ export function registerTools(server, client, config, auth, options = {}) {
595
734
  ? 'provided by the developer this session (memory only)'
596
735
  : 'not yet provided: the developer is asked on first use',
597
736
  token_scope: 'organization-wide (Edgegap cannot scope tokens)',
737
+ token_status: tokenStatus,
598
738
  read_only: config.readOnly,
599
739
  app_allowlist: config.appAllowlist.length ? config.appAllowlist : 'none (all applications)',
600
740
  max_duration_ceiling_minutes: config.maxDurationCeiling,
@@ -616,7 +756,8 @@ export function registerTools(server, client, config, auth, options = {}) {
616
756
  results: `every result starts with [${label}]`,
617
757
  },
618
758
  user_agent: `edgegap-mcp/${VERSION} (<MCP client name>)`,
619
- });
759
+ works_without_token: TOKENLESS_TOOLS,
760
+ }), { props: { token_state: String(tokenStatus.state) } });
620
761
  });
621
762
  // ---------------------------------------------------------------- 1 ----
622
763
  tool('edgegap_list_apps', {
@@ -625,19 +766,34 @@ export function registerTools(server, client, config, auth, options = {}) {
625
766
  'deploying anything, so you reuse an existing application instead of making a duplicate. ' +
626
767
  'An "application" groups versions of one game server.',
627
768
  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(),
769
+ limit: z.number().int().optional().describe('Results per page, 1-100. Default 50.'),
770
+ page: z.number().int().optional(),
630
771
  },
631
772
  outputSchema: OUTPUT.listApps,
632
773
  annotations: { readOnlyHint: true, openWorldHint: true },
633
774
  }, async ({ limit, page }) => guard(auth, async () => {
634
- const res = await client.listApps({ limit: limit ?? 50, page });
775
+ const p = clamp(page, 1, 100_000, 1);
776
+ const res = await client.listApps({ limit: clamp(limit, 1, 100, 50), page: page === undefined ? undefined : p });
635
777
  const apps = (res.applications ?? []).map((a) => ({
636
778
  name: a.name,
637
779
  active: a.is_active,
638
780
  last_updated: a.last_updated,
639
781
  }));
640
- return ok({ ...pageInfo(res.total_count, apps.length, page ?? 1), applications: apps });
782
+ if (apps.length === 0 && p === 1) {
783
+ return emptyState('empty', { total: 0, applications: [] }, 'This organization has no applications yet. Create one with edgegap_create_app (usually named after ' +
784
+ 'the game), then register the server image with edgegap_create_app_version.');
785
+ }
786
+ const info = pageInfo(res.total_count, apps.length, p);
787
+ return withMeta(ok({
788
+ ...info,
789
+ applications: apps,
790
+ ...('next_step' in info
791
+ ? {}
792
+ : {
793
+ next_step: 'Reuse the application that matches this game: edgegap_list_app_versions shows its versions. ' +
794
+ 'Only if none fits, create one with edgegap_create_app.',
795
+ }),
796
+ }), { props: { item_count: apps.length }, milestones: ['app_created'] });
641
797
  }));
642
798
  // ---------------------------------------------------------------- 2 ----
643
799
  if (mutating) {
@@ -665,11 +821,11 @@ export function registerTools(server, client, config, auth, options = {}) {
665
821
  return dryRunResult(dry.requests);
666
822
  }
667
823
  const res = await client.createApp(body);
668
- return ok({
824
+ return withMeta(ok({
669
825
  created: res.name,
670
826
  active: res.is_active,
671
827
  next_step: 'Call edgegap_create_app_version to attach a container image.',
672
- });
828
+ }), { milestones: ['app_created'] });
673
829
  }));
674
830
  }
675
831
  // --------------------------------------------------------------- 2b ----
@@ -703,8 +859,10 @@ export function registerTools(server, client, config, auth, options = {}) {
703
859
  description: 'List the versions under an application, with their container image, resources, ports ' +
704
860
  '(including whether TLS Upgrade is on, which browser/WebGL clients need for wss://) and ' +
705
861
  'whether a registry login is set for pulling the image. Use this to find the version ' +
706
- 'name to deploy, to check a version is ready before deploying, or to copy settings from ' +
707
- 'a working version when creating a new one.',
862
+ 'name to deploy, to check a version is ready before deploying, or to copy the non-secret ' +
863
+ 'settings (image, resources, ports) of a working version when creating a new one. The ' +
864
+ 'registry login and secret env values are never readable: the API returns "' + ENCRYPTED_PLACEHOLDER + '" ' +
865
+ 'for them, so get them from the dashboard\'s Container Registry page or the developer.',
708
866
  inputSchema: {
709
867
  application: z.string().describe('Application name, as returned by edgegap_list_apps.'),
710
868
  },
@@ -716,7 +874,16 @@ export function registerTools(server, client, config, auth, options = {}) {
716
874
  guarded(auth, NOT_FOUND.app, async () => {
717
875
  const res = await client.listAppVersions(application);
718
876
  const versions = (res.versions ?? []).map(compactVersion);
719
- return ok({ application, ...pageInfo(res.total_count, versions.length, 1), versions });
877
+ if (versions.length === 0) {
878
+ return emptyState('empty', { application, total: 0, versions: [] }, `Application "${application}" has no versions yet. Push the server image, confirm it with ` +
879
+ 'edgegap_list_registry_tags, then register it with edgegap_create_app_version.');
880
+ }
881
+ return withMeta(ok({
882
+ application,
883
+ ...pageInfo(res.total_count, versions.length, 1),
884
+ versions,
885
+ next_step: 'Deploy an active version with edgegap_deploy, or register a new image with edgegap_create_app_version.',
886
+ }), { props: { item_count: versions.length } });
720
887
  }));
721
888
  // --------------------------------------------------------------- 3b ----
722
889
  tool('edgegap_get_app_version', {
@@ -757,7 +924,10 @@ export function registerTools(server, client, config, auth, options = {}) {
757
924
  'Set verify_image true on the first version so a bad image fails here rather than at ' +
758
925
  'deploy time. Refused, with nothing sent, for the "latest" or an empty docker tag (use a build ID so ' +
759
926
  'deployments are reproducible) and for a docker_image that also holds a registry host or tag. ' +
760
- 'Env vars named like secrets (TOKEN, SECRET, PASSWORD, API_KEY…) are hidden in the dashboard.',
927
+ 'Env vars named like secrets (TOKEN, SECRET, PASSWORD, API_KEY…) are hidden in the dashboard. ' +
928
+ 'When copying an existing version, copy only non-secret settings: the API returns "' +
929
+ ENCRYPTED_PLACEHOLDER + '" for its registry login and secret env values, and that ' +
930
+ 'placeholder is refused here.',
761
931
  inputSchema: {
762
932
  application: z.string().describe('Existing application name.'),
763
933
  name: z
@@ -826,6 +996,14 @@ export function registerTools(server, client, config, auth, options = {}) {
826
996
  ]);
827
997
  if (leak)
828
998
  return leak;
999
+ const placeholder = encryptedPlaceholder([
1000
+ ['registry_username', args.registry_username],
1001
+ ['registry_token', args.registry_token],
1002
+ ...(args.env ?? []).map((e) => [`the value of env var "${e.key.slice(0, 40)}"`, e.value]),
1003
+ ], 'Without them, leave registry_username and registry_token out and have the developer add the ' +
1004
+ 'login to this version in the dashboard.');
1005
+ if (placeholder)
1006
+ return placeholder;
829
1007
  const tagProblem = badTag(args.docker_tag);
830
1008
  if (tagProblem)
831
1009
  return fail(`Refused: ${tagProblem}. ${TAG_FIX}`);
@@ -897,13 +1075,14 @@ export function registerTools(server, client, config, auth, options = {}) {
897
1075
  'they need wss://: create the version with tls_upgrade: true on this port.');
898
1076
  }
899
1077
  }
900
- return ok({
1078
+ return withMeta(ok({
901
1079
  created: `${args.application}/${res.version?.name ?? args.name}`,
902
1080
  max_duration_minutes: capped,
903
1081
  capped_by_server: capped < requested ? config.maxDurationCeiling : undefined,
904
1082
  notes: notes.length ? notes : undefined,
905
- next_step: 'Call edgegap_deploy to start an instance.',
906
- });
1083
+ next_step: `Call edgegap_deploy with application "${args.application}" and version ` +
1084
+ `"${res.version?.name ?? args.name}" to start a server, then edgegap_wait_for_deployment.`,
1085
+ }), { milestones: ['app_version_created'], props: { registry_login_set: hasRegistryLogin } });
907
1086
  }));
908
1087
  }
909
1088
  // --------------------------------------------------------------- 4b ----
@@ -918,7 +1097,9 @@ export function registerTools(server, client, config, auth, options = {}) {
918
1097
  'edgegap_create_app_version: "latest" or empty tags, a docker_image holding a host or ' +
919
1098
  'tag, and the API token in the registry login or env vars. ports and env REPLACE the ' +
920
1099
  'version\'s whole list (per the API): read the current ones with edgegap_get_app_version ' +
921
- 'and pass every port or variable to keep. CPU and memory cannot be changed here; create a ' +
1100
+ 'and pass every port or variable to keep; secret env values are not readable, so get them ' +
1101
+ 'from the developer. Refused, with nothing sent, for a registry login or env value equal to ' +
1102
+ 'the API\'s "' + ENCRYPTED_PLACEHOLDER + '" placeholder; leave the registry login out to keep it. CPU and memory cannot be changed here; create a ' +
922
1103
  'new version, or override them per deployment in edgegap_deploy.',
923
1104
  inputSchema: {
924
1105
  application: z.string().describe('Application name.'),
@@ -973,6 +1154,14 @@ export function registerTools(server, client, config, auth, options = {}) {
973
1154
  ]);
974
1155
  if (leak)
975
1156
  return leak;
1157
+ const placeholder = encryptedPlaceholder([
1158
+ ['registry_username', args.registry_username],
1159
+ ['registry_token', args.registry_token],
1160
+ ...(args.env ?? []).map((e) => [`the value of env var "${e.key.slice(0, 40)}"`, e.value]),
1161
+ ], 'To keep the version\'s current registry login, leave registry_username and registry_token ' +
1162
+ 'out. env replaces every variable, so leave env out to keep the current ones.');
1163
+ if (placeholder)
1164
+ return placeholder;
976
1165
  const badTls = args.ports?.find((p) => p.tls_upgrade && !TLS_PROTOCOLS.has(p.protocol.toUpperCase()));
977
1166
  if (badTls) {
978
1167
  return fail(`Port ${badTls.port} is ${badTls.protocol}; tls_upgrade only works on WS and HTTP ports. ` +
@@ -1159,6 +1348,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1159
1348
  ]);
1160
1349
  if (leak)
1161
1350
  return leak;
1351
+ const placeholder = encryptedPlaceholder((args.env ?? []).map((e) => [`the value of env var "${e.key.slice(0, 40)}"`, e.value]), 'Leave the variable out: the deployment already gets the version\'s own env vars.');
1352
+ if (placeholder)
1353
+ return placeholder;
1162
1354
  const body = {
1163
1355
  application: args.application,
1164
1356
  version: args.version,
@@ -1216,14 +1408,14 @@ export function registerTools(server, client, config, auth, options = {}) {
1216
1408
  }
1217
1409
  }
1218
1410
  const res = await client.deploy(body);
1219
- return ok({
1411
+ return withMeta(ok({
1220
1412
  request_id: res.request_id,
1221
1413
  status: 'starting',
1222
1414
  tags,
1223
1415
  ...autoStop(version.max_duration),
1224
1416
  resources: body.resources,
1225
1417
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
1226
- });
1418
+ }), { hash: { request_id: res.request_id }, props: { resources_override: body.resources !== undefined } });
1227
1419
  }));
1228
1420
  }
1229
1421
  // ---------------------------------------------------------------- 6 ----
@@ -1239,7 +1431,13 @@ export function registerTools(server, client, config, auth, options = {}) {
1239
1431
  annotations: { readOnlyHint: true, openWorldHint: true },
1240
1432
  }, async ({ request_id }) => guarded(auth, NOT_FOUND.deployment, async () => {
1241
1433
  const d = await client.getDeployment(request_id);
1242
- return ok(compactDeployment(d));
1434
+ const status = (d.current_status ?? '').toUpperCase();
1435
+ const nextStep = d.error || TERMINAL_BAD.some((s) => status.includes(s))
1436
+ ? `It failed or stopped. Read why with edgegap_get_deployment_logs {request_id: "${request_id}"} before redeploying.`
1437
+ : d.running || TERMINAL_OK.some((s) => status.includes(s))
1438
+ ? `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.`
1439
+ : `Still starting. Call edgegap_wait_for_deployment {request_id: "${request_id}"} instead of polling this.`;
1440
+ return ok({ ...compactDeployment(d), next_step: nextStep });
1243
1441
  }));
1244
1442
  // ---------------------------------------------------------------- 7 ----
1245
1443
  tool('edgegap_wait_for_deployment', {
@@ -1253,51 +1451,65 @@ export function registerTools(server, client, config, auth, options = {}) {
1253
1451
  timeout_seconds: z
1254
1452
  .number()
1255
1453
  .int()
1256
- .min(5)
1257
- .max(600)
1258
1454
  .optional()
1259
- .describe('How long to wait before giving up. Default 180.'),
1455
+ .describe('How long to wait before giving up, 5-600. Default 180.'),
1260
1456
  },
1261
1457
  outputSchema: OUTPUT.waitForDeployment,
1262
1458
  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;
1459
+ }, async ({ request_id, timeout_seconds }, extra) => guarded(auth, NOT_FOUND.deployment, async () => {
1460
+ const timeoutSeconds = clamp(timeout_seconds, 5, 600, 180);
1461
+ const budgetMs = timeoutSeconds * 1000;
1265
1462
  const startedAt = Date.now();
1266
1463
  let intervalMs = 2000;
1464
+ let polls = 0;
1267
1465
  let last;
1466
+ const progress = progressReporter(extra, timeoutSeconds);
1467
+ const facts = (outcome) => ({
1468
+ props: { outcome, final_status: last?.current_status ?? 'unknown', timeout_ms_configured: budgetMs, poll_count: polls },
1469
+ hash: { request_id },
1470
+ });
1268
1471
  while (Date.now() - startedAt < budgetMs) {
1269
1472
  last = await client.getDeployment(request_id);
1473
+ polls++;
1270
1474
  const status = (last.current_status ?? '').toUpperCase();
1271
1475
  if (last.error || TERMINAL_BAD.some((s) => status.includes(s))) {
1272
1476
  // Fetched now, not left to the agent: a failed deployment is
1273
1477
  // cleaned up quickly and its logs go with it, so a separate
1274
1478
  // edgegap_get_deployment_logs call often finds nothing.
1275
1479
  const logs = await logTail(client, request_id, 3000);
1276
- return fail(`Deployment ${request_id} failed with status ${last.current_status}.\n` +
1480
+ return withMeta(fail(`Deployment ${request_id} failed with status ${last.current_status}.\n` +
1277
1481
  `${last.error_detail ?? 'No error detail returned.'}\n\n` +
1278
1482
  (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.`));
1483
+ ? `Container output (tail):\n${logs}\n\nFix the image or port configuration before redeploying. ` +
1484
+ 'Do not redeploy the same version unchanged: it will fail the same way.'
1485
+ : `No container logs could be read here (the container may never have started, or it ` +
1486
+ `was already cleaned up). Try edgegap_get_deployment_logs {request_id: "${request_id}"} once; ` +
1487
+ 'if it has nothing either, check the image, tag and ports before redeploying.'), 'DEPLOYMENT_FAILED'), { ...facts('error'), stage: 'upstream' });
1282
1488
  }
1283
1489
  if (last.running || TERMINAL_OK.some((s) => status.includes(s))) {
1284
- return ok({
1490
+ return withMeta(ok({
1285
1491
  ...compactDeployment(last),
1286
1492
  waited_seconds: Math.round((Date.now() - startedAt) / 1000),
1287
- });
1493
+ cost_reminder: 'This server bills while it runs. When testing is done, stop it with ' +
1494
+ `edgegap_stop_deployment {request_id: "${request_id}"} unless the developer wants it kept running.`,
1495
+ next_step: `Players connect to ${last.fqdn ?? 'the fqdn above'} on each port's external number. ` +
1496
+ `When finished: edgegap_stop_deployment {request_id: "${request_id}"}.`,
1497
+ }), { ...facts('ready'), milestones: ['deployment_ready'] });
1288
1498
  }
1499
+ await progress(Date.now() - startedAt, `Deployment ${request_id}: ${last.current_status ?? 'starting'}`);
1289
1500
  await new Promise((r) => setTimeout(r, intervalMs));
1290
1501
  intervalMs = Math.min(intervalMs * 1.5, 10_000);
1291
1502
  }
1292
1503
  // Not an error: the wait ran out, the deployment did not fail. It is
1293
1504
  // usually still starting (large images pull slowly on a cold host).
1294
- return ok({
1505
+ return withMeta(ok({
1295
1506
  ...(last ? compactDeployment(last) : { request_id }),
1296
1507
  ready: false,
1297
1508
  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
- });
1509
+ next_step: `Not ready within ${timeoutSeconds}s, and not failed: it is still ${last?.current_status ?? 'starting'}. ` +
1510
+ `Call edgegap_wait_for_deployment again with request_id "${request_id}" to keep waiting; do not deploy ` +
1511
+ `a second server. Stop it with edgegap_stop_deployment if it should not keep running.`,
1512
+ }), facts('timeout'));
1301
1513
  }));
1302
1514
  // ---------------------------------------------------------------- 8 ----
1303
1515
  tool('edgegap_list_deployments', {
@@ -1337,7 +1549,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1337
1549
  }))
1338
1550
  .optional()
1339
1551
  .describe('e.g. [{field:"created_at",order:"asc"}] for oldest first.'),
1340
- limit: z.number().int().min(1).max(100).optional().describe('Default 50.'),
1552
+ limit: z.number().int().optional().describe('1-100. Default 50.'),
1341
1553
  },
1342
1554
  outputSchema: OUTPUT.listDeployments,
1343
1555
  annotations: { readOnlyHint: true, openWorldHint: true },
@@ -1357,7 +1569,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1357
1569
  const query = filters?.length || order_by?.length
1358
1570
  ? JSON.stringify({ filters: filters ?? [], ...(order_by?.length ? { order_by } : {}) })
1359
1571
  : undefined;
1360
- const res = await client.listDeployments({ query, limit: limit ?? 50 });
1572
+ const res = await client.listDeployments({ query, limit: clamp(limit, 1, 100, 50) });
1361
1573
  const rows = (res.data ?? []).map((d) => ({
1362
1574
  request_id: d.request_id,
1363
1575
  ready: d.ready,
@@ -1365,7 +1577,23 @@ export function registerTools(server, client, config, auth, options = {}) {
1365
1577
  started: d.start_time,
1366
1578
  tags: d.tags,
1367
1579
  }));
1368
- return ok({ ...pageInfo(res.total_count, rows.length, 1), deployments: rows });
1580
+ if (rows.length === 0) {
1581
+ return emptyState('empty', { total: 0, deployments: [] }, only_agent_deployments
1582
+ ? 'No deployment started through this server is running: nothing is left to stop.'
1583
+ : filters?.length
1584
+ ? 'No running deployment matches these filters.'
1585
+ : 'No deployments are running. Start one with edgegap_deploy.');
1586
+ }
1587
+ const info = pageInfo(res.total_count, rows.length, 1);
1588
+ return withMeta(ok({
1589
+ ...info,
1590
+ deployments: rows,
1591
+ ...('next_step' in info
1592
+ ? {}
1593
+ : {
1594
+ next_step: 'Stop the ones you started and no longer need with edgegap_stop_deployment, one request_id per call.',
1595
+ }),
1596
+ }), { props: { item_count: rows.length, only_agent_deployments: only_agent_deployments === true } });
1369
1597
  }));
1370
1598
  // ---------------------------------------------------------------- 9 ----
1371
1599
  if (mutating) {
@@ -1396,10 +1624,14 @@ export function registerTools(server, client, config, auth, options = {}) {
1396
1624
  catch (err) {
1397
1625
  const gone = await alreadyStopped(client, request_id, err);
1398
1626
  if (gone)
1399
- return ok(gone);
1627
+ return withMeta(ok(gone), { hash: { request_id }, props: { stop_result: gone.result } });
1400
1628
  throw err;
1401
1629
  }
1402
- return ok({ request_id, result: res.message ?? 'stop requested' });
1630
+ return withMeta(ok({
1631
+ request_id,
1632
+ result: res.message ?? 'stop requested',
1633
+ next_step: 'Before ending the task, confirm nothing else is left with edgegap_list_deployments only_agent_deployments: true.',
1634
+ }), { hash: { request_id }, milestones: ['deployment_stopped'], props: { stop_result: 'stopped' } });
1403
1635
  }));
1404
1636
  }
1405
1637
  // --------------------------------------------------------------- 10 ----
@@ -1414,19 +1646,30 @@ export function registerTools(server, client, config, auth, options = {}) {
1414
1646
  max_characters: z
1415
1647
  .number()
1416
1648
  .int()
1417
- .min(500)
1418
- .max(50_000)
1419
1649
  .optional()
1420
- .describe('Truncate logs to this length, keeping the tail. Default 8000.'),
1650
+ .describe('Truncate logs to this length (500-50000), keeping the tail. Default 8000.'),
1421
1651
  },
1422
1652
  annotations: { readOnlyHint: true, openWorldHint: true },
1423
1653
  }, 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;
1654
+ let res;
1655
+ try {
1656
+ res = await client.getDeploymentLogs(request_id);
1657
+ }
1658
+ catch (err) {
1659
+ // The logs endpoint answers 400 for every "no logs" case alike. Ask
1660
+ // the status endpoint which one this is.
1661
+ if (!(err instanceof EdgegapApiError) || ![400, 404].includes(err.status))
1662
+ throw err;
1663
+ const why = await whyNoLogs(client, request_id);
1664
+ if (!why)
1665
+ throw err;
1666
+ return why;
1667
+ }
1668
+ const cap = clamp(max_characters, 500, 50_000, 8000);
1426
1669
  const tail = (s) => !s ? undefined : s.length > cap ? `...[truncated]...\n${s.slice(-cap)}` : s;
1427
1670
  return ok({
1428
1671
  request_id,
1429
- logs: tail(res.logs) ?? '(no logs returned)',
1672
+ logs: tail(res.logs) ?? '(no logs returned yet: the server has printed nothing)',
1430
1673
  crash_logs: tail(res.crash_logs),
1431
1674
  exit_code: res.crash_data?.exit_code,
1432
1675
  crash_message: res.crash_data?.message,
@@ -1610,7 +1853,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1610
1853
  ? generateDockerfile({ engine, ports: args.ports, netcode: args.netcode }).dockerfile
1611
1854
  : undefined;
1612
1855
  const verdict = errors.length > 0 ? 'fail' : warnings.length > 0 ? 'pass_with_warnings' : 'pass';
1613
- return ok({
1856
+ return withMeta(ok({
1614
1857
  verdict,
1615
1858
  engine,
1616
1859
  errors,
@@ -1628,6 +1871,15 @@ export function registerTools(server, client, config, auth, options = {}) {
1628
1871
  : 'Build with "docker build --platform linux/amd64 -t <image>:<unique-tag> ." and run it ' +
1629
1872
  'locally with the same port mapping to confirm it starts. Then push it; ' +
1630
1873
  'edgegap_get_registry_credentials gives you a registry and the exact commands.',
1874
+ }), {
1875
+ props: {
1876
+ validation_result: errors.length > 0 ? 'fail' : 'pass',
1877
+ issue_count: errors.length + warnings.length,
1878
+ error_count: errors.length,
1879
+ warning_count: warnings.length,
1880
+ engine,
1881
+ checked_dockerfile: args.dockerfile !== undefined,
1882
+ },
1631
1883
  });
1632
1884
  });
1633
1885
  // --------------------------------------------------------------- 12 ----
@@ -1645,7 +1897,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1645
1897
  'do not retry. When it does return a token, it is registry-scoped (push/pull images in ' +
1646
1898
  'this project), not the org API token: pass it to docker login via --password-stdin, ' +
1647
1899
  'never as a command-line argument, and do not write it into files. Call ' +
1648
- 'edgegap_validate_server_config before building.',
1900
+ 'edgegap_validate_server_config before building. Any other registry Edgegap can pull from ' +
1901
+ '(Docker Hub, GHCR, ECR, GitLab) works too: then skip this tool and pass that registry and its ' +
1902
+ 'pull login to edgegap_create_app_version.',
1649
1903
  inputSchema: {
1650
1904
  image_name: z
1651
1905
  .string()
@@ -1695,7 +1949,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1695
1949
  const image = image_name ?? '<image-name>';
1696
1950
  const buildTag = tag ?? '<unique-build-tag>';
1697
1951
  const ref = `${host}/${creds.project}/${image}:${buildTag}`;
1698
- return ok({
1952
+ return withMeta(ok({
1699
1953
  registry_url: host,
1700
1954
  project: creds.project,
1701
1955
  username: creds.username,
@@ -1717,7 +1971,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1717
1971
  '(it never needs to appear in a command line or file), then build and push. ' +
1718
1972
  `Confirm the push with edgegap_list_registry_tags (image_name "${image}", without the project), ` +
1719
1973
  'then call edgegap_create_app_version with the values in for_create_app_version.',
1720
- });
1974
+ }), { milestones: ['registry_credentials_ok'], props: { registry_status: 'credentials_returned' } });
1721
1975
  }));
1722
1976
  }
1723
1977
  // --------------------------------------------------------------- 13 ----
@@ -1725,7 +1979,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1725
1979
  title: 'List image tags in the Edgegap registry',
1726
1980
  description: 'List the tags pushed for one image in this organization\'s Edgegap container registry, ' +
1727
1981
  '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.',
1982
+ 'edgegap_create_app_version, which otherwise fails later with an image-pull error. An image ' +
1983
+ 'that was never pushed comes back as status "not_found" with no tags, not as an error. Only ' +
1984
+ 'for registry.edgegap.com: images in Docker Hub, GHCR or another registry are not listed here.',
1729
1985
  inputSchema: {
1730
1986
  image_name: z
1731
1987
  .string()
@@ -1733,7 +1989,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1733
1989
  .describe('The image name only, without the project, registry host or tag, e.g. "my-game-server". ' +
1734
1990
  'The API reads the project from your token; "<project>/my-game-server" is not found.'),
1735
1991
  page: z.number().int().min(1).optional(),
1736
- limit: z.number().int().min(1).max(100).optional().describe('Default 20.'),
1992
+ limit: z.number().int().optional().describe('1-100. Default 20.'),
1737
1993
  },
1738
1994
  outputSchema: OUTPUT.listRegistryTags,
1739
1995
  annotations: { readOnlyHint: true, openWorldHint: true },
@@ -1741,7 +1997,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1741
1997
  // Agents often pass the full reference they pushed. Reduce it to what
1742
1998
  // the API wants: no "registry.edgegap.com/" host, no ":tag".
1743
1999
  let name = imageNameOnly(image_name);
1744
- const query = { page, limit: limit ?? 20 };
2000
+ const query = { page, limit: clamp(limit, 1, 100, 20) };
1745
2001
  const notFound = (err) => err instanceof EdgegapApiError && err.status === 404;
1746
2002
  let res;
1747
2003
  try {
@@ -1758,12 +2014,20 @@ export function registerTools(server, client, config, auth, options = {}) {
1758
2014
  }
1759
2015
  }
1760
2016
  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.');
2017
+ // Nothing pushed under that name is a state, not a failure: the
2018
+ // answer to "did my push land?" is "no, push it".
2019
+ if (notFound(err)) {
2020
+ 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 ` +
2021
+ 'name only, as used after "registry.edgegap.com/<project>/" in docker push), or push the image ' +
2022
+ 'first (edgegap_get_registry_credentials has the commands). If the image lives in Docker Hub, GHCR ' +
2023
+ 'or another registry, skip this check and pass that registry to edgegap_create_app_version.');
2024
+ }
2025
+ if (err instanceof EdgegapApiError && err.status === 403) {
2026
+ 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 ' +
2027
+ 'to open the Container Registry page of the dashboard (https://app.edgegap.com), or push the image to ' +
2028
+ 'Docker Hub, GHCR or another registry and pass it to edgegap_create_app_version with its pull login.');
2029
+ }
2030
+ throw err;
1767
2031
  }
1768
2032
  const tags = (res.data ?? []).map((t) => ({
1769
2033
  tag: t.tag,
@@ -1772,7 +2036,10 @@ export function registerTools(server, client, config, auth, options = {}) {
1772
2036
  digest: t.artifact?.image_hash,
1773
2037
  }));
1774
2038
  const hasNext = res.pagination?.has_next === true;
1775
- return ok({
2039
+ if (tags.length === 0 && !hasNext && (page ?? 1) === 1) {
2040
+ 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.`);
2041
+ }
2042
+ return withMeta(ok({
1776
2043
  image_name: name,
1777
2044
  note: name !== image_name ? `Looked up "${name}". Pass the image name only next time.` : undefined,
1778
2045
  total: res.count ?? tags.length,
@@ -1782,9 +2049,12 @@ export function registerTools(server, client, config, auth, options = {}) {
1782
2049
  truncated: true,
1783
2050
  next_step: `Only page ${page ?? 1} is shown. Call again with page: ${(page ?? 1) + 1} before concluding a tag is missing.`,
1784
2051
  }
1785
- : {}),
2052
+ : {
2053
+ next_step: 'If the tag you pushed is listed, register it with edgegap_create_app_version (docker_repository ' +
2054
+ `"registry.edgegap.com", docker_image "<project>/${name}", and that tag).`,
2055
+ }),
1786
2056
  tags,
1787
- });
2057
+ }), { props: { item_count: tags.length }, milestones: tags.length ? ['image_pushed'] : [] });
1788
2058
  }));
1789
2059
  // --------------------------------------------------------------- 13b ----
1790
2060
  if (mutating) {
@@ -1930,7 +2200,22 @@ export function registerTools(server, client, config, auth, options = {}) {
1930
2200
  outputSchema: OUTPUT.listRelaySessions,
1931
2201
  annotations: { readOnlyHint: true, openWorldHint: true },
1932
2202
  }, async () => guard(auth, async () => {
1933
- const res = await client.listRelaySessions();
2203
+ let res;
2204
+ try {
2205
+ res = await client.listRelaySessions();
2206
+ }
2207
+ catch (err) {
2208
+ // An organization without relays gets 403 here. Listing has nothing
2209
+ // to correct: there are no sessions, and none can be billing.
2210
+ if (!(err instanceof EdgegapApiError) || err.status !== 403)
2211
+ throw err;
2212
+ return emptyState('not_configured', { total: 0, sessions: [] }, 'This organization cannot use relays (the API answered 403), so no relay sessions exist or bill. ' +
2213
+ 'Relays are not enabled on every plan; check the Relays page of the dashboard or ask Edgegap support. ' +
2214
+ 'For a multiplayer match, a dedicated server (edgegap_deploy) needs no relay.');
2215
+ }
2216
+ if ((res.sessions ?? []).length === 0) {
2217
+ return emptyState('empty', { total: 0, sessions: [] }, 'No relay sessions are open, so none are billing.');
2218
+ }
1934
2219
  const sessions = (res.sessions ?? []).map((r) => ({
1935
2220
  session_id: r.session_id,
1936
2221
  status: r.status,
@@ -2067,6 +2352,7 @@ export function registerTools(server, client, config, auth, options = {}) {
2067
2352
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
2068
2353
  assertAppAllowed(config, args.application);
2069
2354
  const { config: mmConfig, problems, cautions } = buildMatchmakerConfig(args);
2355
+ let verified = false;
2070
2356
  if (args.verify_version !== false) {
2071
2357
  try {
2072
2358
  const res = await client.listAppVersions(args.application);
@@ -2081,22 +2367,39 @@ export function registerTools(server, client, config, auth, options = {}) {
2081
2367
  if (!v.ports?.length)
2082
2368
  problems.push(`Version "${args.version}" has no ports, so matched players have nothing to connect to.`);
2083
2369
  }
2370
+ verified = true;
2084
2371
  }
2085
2372
  catch (err) {
2086
2373
  if (err instanceof EdgegapApiError && err.status === 404) {
2087
2374
  problems.push(`Application "${args.application}" does not exist. Call edgegap_list_apps.`);
2088
2375
  }
2376
+ else if (err instanceof TokenUnavailableError && err.reason !== 'declined') {
2377
+ // Building the config needs no token; only the version check
2378
+ // does. Without one, hand back the config and say what was skipped.
2379
+ cautions.push(`Not checked against Edgegap: this session has no API token, so whether "${args.application}/${args.version}" ` +
2380
+ 'exists, is active and has ports was not verified. Check it in the dashboard before uploading.');
2381
+ }
2089
2382
  else {
2090
2383
  throw err;
2091
2384
  }
2092
2385
  }
2093
2386
  }
2387
+ const facts = {
2388
+ props: {
2389
+ matchmaker_template: 'single_profile',
2390
+ team_count: args.team_count,
2391
+ has_latency_rule: args.max_latency_ms !== undefined,
2392
+ expansion_count: args.expansions?.length ?? 0,
2393
+ problem_count: problems.length,
2394
+ version_verified: verified,
2395
+ },
2396
+ };
2094
2397
  if (problems.length > 0) {
2095
- return fail('The matchmaker configuration has problems; fix them before uploading:\n- ' +
2398
+ return withMeta(fail(`The matchmaker configuration has ${problems.length} problem${problems.length === 1 ? '' : 's'}; fix all of them before uploading:\n- ` +
2096
2399
  problems.join('\n- ') +
2097
- `\n\nDraft config:\n${JSON.stringify(mmConfig, null, 2)}`);
2400
+ `\n\nDraft config:\n${JSON.stringify(mmConfig, null, 2)}`, 'VALIDATION_FAILED'), facts);
2098
2401
  }
2099
- return ok({
2402
+ return withMeta(ok({
2100
2403
  config: mmConfig,
2101
2404
  cautions: cautions.length ? cautions : undefined,
2102
2405
  next_steps: [
@@ -2113,7 +2416,7 @@ export function registerTools(server, client, config, auth, options = {}) {
2113
2416
  ? `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
2417
  : '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
2418
  ],
2116
- });
2419
+ }), facts);
2117
2420
  }));
2118
2421
  registerSkills(server, tool, config, options);
2119
2422
  }
@@ -2183,12 +2486,14 @@ function registerSkills(server, tool, config, options) {
2183
2486
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
2184
2487
  }, async ({ skill: name, file }) => {
2185
2488
  const skill = findSkill(name);
2186
- if (!skill)
2187
- return fail(`No skill named "${name}". The skills are: ${names.join(', ')}.`);
2489
+ if (!skill) {
2490
+ const guess = closestSkill(name, names);
2491
+ 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) } });
2492
+ }
2188
2493
  const found = findSkillFile(skill, file);
2189
2494
  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'));
2495
+ return withMeta(fail(`"${file}" is not a file in the ${skill.name} skill. Its files are:\n` +
2496
+ ['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
2497
  }
2193
2498
  const status = found.path === 'SKILL.md' ? servedPackStatus(await latestPack(check), hosted) : undefined;
2194
2499
  const header = `${skill.name} ${skill.version} · ${found.path} · pack ${pack}` +
@@ -2197,7 +2502,10 @@ function registerSkills(server, tool, config, options) {
2197
2502
  const footer = others.length
2198
2503
  ? `\n\n---\nOther files in this skill:\n${others.map((p) => `- ${p}`).join('\n')}\n\n${howToFetch(skill.name)}`
2199
2504
  : '';
2200
- return { content: [{ type: 'text', text: `${header}\n\n${found.content}${footer}` }] };
2505
+ return {
2506
+ content: [{ type: 'text', text: `${header}\n\n${found.content}${footer}` }],
2507
+ meta: { props: { skill_name: skill.name, skill_file: found.path, resource_uri: skillUri(skill.name, found.path) } },
2508
+ };
2201
2509
  });
2202
2510
  tool('edgegap_update_skills', {
2203
2511
  title: 'Check and update the installed Edgegap skills',
@@ -2344,6 +2652,37 @@ function registerSkills(server, tool, config, options) {
2344
2652
  '(in Claude Code, /reload-plugins also works for the plugin) to use the update.';
2345
2653
  return failed ? { ...ok(result), isError: true } : ok(result);
2346
2654
  });
2655
+ // The one obvious place to start: a prompt that runs the golden path for
2656
+ // whatever engine and netcode the project uses.
2657
+ server.registerPrompt('deploy-game-server', {
2658
+ title: 'Deploy my game server to Edgegap',
2659
+ description: 'Start here. Detects the project\'s engine and netcode, loads the matching Edgegap skill, and walks the golden ' +
2660
+ 'path to a running dedicated server: Dockerfile, registry, app version, deploy, wait, then stop.',
2661
+ }, () => ({
2662
+ description: 'Deploy this project\'s game server to Edgegap',
2663
+ messages: [
2664
+ {
2665
+ role: 'user',
2666
+ content: {
2667
+ type: 'text',
2668
+ text: 'Deploy this project\'s game server to Edgegap as an authoritative dedicated server.\n\n' +
2669
+ '1. Look at the project files to find the engine (Unity, Unreal, Godot, or a Node.js/other server) and ' +
2670
+ 'the netcode (NGO, FishNet, PurrNet, Mirror, Photon Fusion, Colyseus, Nakama, PlayFab...).\n' +
2671
+ '2. Load the matching skill with edgegap_get_skill (edgegap_list_skills says which; "edgegap" if unsure) ' +
2672
+ 'and follow it over anything below.\n' +
2673
+ '3. Golden path: edgegap_generate_dockerfile (or edgegap_validate_server_config on an existing ' +
2674
+ 'Dockerfile) → edgegap_get_registry_credentials, build and push → edgegap_list_registry_tags → ' +
2675
+ 'edgegap_list_apps / edgegap_create_app → edgegap_create_app_version → edgegap_deploy → ' +
2676
+ 'edgegap_wait_for_deployment → edgegap_stop_deployment when done.\n' +
2677
+ '4. Results with a status such as "empty" or "not_configured" are normal states: do what their ' +
2678
+ 'next_step says instead of retrying.\n' +
2679
+ '5. Before finishing, stop every deployment you started unless I ask to keep it, and confirm with ' +
2680
+ 'edgegap_list_deployments only_agent_deployments: true.\n\n' +
2681
+ 'Ask me before anything you are unsure of, and use dry_run: true on a write you want to check first.',
2682
+ },
2683
+ },
2684
+ ],
2685
+ }));
2347
2686
  for (const skill of SKILLS_PACK.skills) {
2348
2687
  // A prompt per skill: in Claude Code these show up as slash commands.
2349
2688
  server.registerPrompt(skill.name, {
@@ -2368,7 +2707,7 @@ function registerSkills(server, tool, config, options) {
2368
2707
  ],
2369
2708
  };
2370
2709
  });
2371
- // Only each skill's SKILL.md is listed: 21 entries instead of every file
2710
+ // Only each skill's SKILL.md is listed: one entry per skill instead of every file
2372
2711
  // (257 in pack 0.15), which crowded clients' attach menus and resource
2373
2712
  // lists. The other files are read through the template below.
2374
2713
  const main = findSkillFile(skill);
@@ -2404,10 +2743,141 @@ function registerSkills(server, tool, config, options) {
2404
2743
  * call, and some agents retried it.
2405
2744
  */
2406
2745
  function manualStepsResult(steps) {
2746
+ const nextStep = 'Ask the developer for the registry Project, Username and Token from the Container Registry page, or ' +
2747
+ 'whether to use Docker Hub, GHCR or another registry instead. Do not call this tool again.';
2407
2748
  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 },
2749
+ content: [{ type: 'text', text: `status: manual_steps_required (no credentials returned)\n\n${steps}\n\nnext_step: ${nextStep}` }],
2750
+ structuredContent: { status: 'manual_steps_required', credentials_returned: false, steps, next_step: nextStep },
2751
+ meta: { props: { registry_status: 'manual_steps_required' } },
2752
+ };
2753
+ }
2754
+ /** A number argument pulled into range, so an agent's limit: 500 is served
2755
+ * as 100 instead of refused before the API is even called. */
2756
+ function clamp(value, min, max, fallback) {
2757
+ if (value === undefined || !Number.isFinite(value))
2758
+ return fallback;
2759
+ return Math.min(max, Math.max(min, Math.trunc(value)));
2760
+ }
2761
+ /** Tools that need no Edgegap token, for onboarding and the token messages. */
2762
+ const TOKENLESS_TOOLS = [
2763
+ 'edgegap_context',
2764
+ 'edgegap_list_skills',
2765
+ 'edgegap_get_skill',
2766
+ 'edgegap_generate_dockerfile',
2767
+ 'edgegap_validate_server_config',
2768
+ 'edgegap_build_matchmaker_config (without the version check)',
2769
+ ];
2770
+ /**
2771
+ * Whether this session can call the Edgegap API, and if not, why and how to
2772
+ * fix it. Never shows the token: only its last four characters, which is
2773
+ * what the developer needs to find it on the tokens page. Edgegap has no
2774
+ * endpoint that names the organization a token belongs to, so this cannot.
2775
+ */
2776
+ async function describeToken(client, auth, hosted, check) {
2777
+ const fix = `Create a token at ${TOKENS_URL} (no account yet? sign up free at ${SIGNUP_URL}).`;
2778
+ if (!auth.current) {
2779
+ if (!hosted) {
2780
+ return { state: 'not_provided', note: 'The developer is asked for a token on the first call that needs one.', fix };
2781
+ }
2782
+ try {
2783
+ await auth.get();
2784
+ }
2785
+ catch (err) {
2786
+ const reason = err instanceof TokenUnavailableError ? err.reason : 'absent';
2787
+ return {
2788
+ state: reason,
2789
+ note: reason === 'foreign'
2790
+ ? 'The Authorization header holds a credential the MCP client issued itself, not an Edgegap token. ' +
2791
+ 'This client cannot pass an Edgegap token to the hosted server: use the local server ' +
2792
+ '(npx -y @edgegap/mcp) with EDGEGAP_API_TOKEN instead.'
2793
+ : 'No Authorization header on this connection. Add "Authorization: token <your Edgegap token>" to the MCP client config.',
2794
+ fix,
2795
+ works_without_token: TOKENLESS_TOOLS,
2796
+ };
2797
+ }
2798
+ }
2799
+ const token = auth.current;
2800
+ const base = {
2801
+ token_ends_with: token ? `…${token.slice(-4)}` : undefined,
2802
+ 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
2803
  };
2804
+ if (!check)
2805
+ return { state: 'present (not checked)', ...base, note: 'Pass check_token: true to confirm Edgegap accepts it.' };
2806
+ try {
2807
+ await client.listApps({ limit: 1 });
2808
+ return { state: 'accepted', ...base };
2809
+ }
2810
+ catch (err) {
2811
+ if (err instanceof EdgegapApiError && err.status === 401) {
2812
+ return { state: 'rejected', ...base, note: 'Edgegap rejected this token: it was revoked, expired or mistyped.', fix };
2813
+ }
2814
+ return { state: 'unknown', ...base, note: `The check call failed: ${err.message.slice(0, 200)}` };
2815
+ }
2816
+ }
2817
+ const TOKENS_URL = 'https://app.edgegap.com/user-settings?tab=tokens';
2818
+ const SIGNUP_URL = 'https://app.edgegap.com';
2819
+ /**
2820
+ * Sends MCP progress notifications while a tool waits, when the client asked
2821
+ * for them (a progressToken in the request). Silently does nothing otherwise,
2822
+ * and a client that cannot take them never breaks the call.
2823
+ */
2824
+ function progressReporter(extra, totalSeconds) {
2825
+ const e = extra;
2826
+ const progressToken = e?._meta?.progressToken;
2827
+ const send = e?.sendNotification;
2828
+ if (progressToken === undefined || !send)
2829
+ return async (_elapsedMs, _message) => { };
2830
+ return async (elapsedMs, message) => {
2831
+ try {
2832
+ await send({
2833
+ method: 'notifications/progress',
2834
+ params: { progressToken, progress: Math.round(elapsedMs / 1000), total: totalSeconds, message },
2835
+ });
2836
+ }
2837
+ catch {
2838
+ // Progress is a courtesy; the wait goes on without it.
2839
+ }
2840
+ };
2841
+ }
2842
+ /**
2843
+ * Why a deployment has no logs, from its status: it does not exist (or is
2844
+ * another organization's), it has not started, or it has stopped and its logs
2845
+ * went with it. Undefined when the status does not explain it, so the caller
2846
+ * reports the original API error.
2847
+ */
2848
+ async function whyNoLogs(client, requestId) {
2849
+ let d;
2850
+ try {
2851
+ d = await client.getDeployment(requestId);
2852
+ }
2853
+ catch (err) {
2854
+ if (err instanceof EdgegapApiError && [400, 404].includes(err.status)) {
2855
+ return withMeta(fail(`No deployment with request_id "${requestId}" in this organization: it was never created here, belongs ` +
2856
+ 'to another organization, or stopped long enough ago to be cleaned up. Check the request_id with ' +
2857
+ 'edgegap_list_deployments.', 'DEPLOYMENT_NOT_FOUND'), { stage: 'upstream' });
2858
+ }
2859
+ return undefined;
2860
+ }
2861
+ const status = (d.current_status ?? '').toUpperCase();
2862
+ if (d.error || TERMINAL_BAD.some((s) => status.includes(s))) {
2863
+ 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 ' +
2864
+ 'Storage was set on the version). error_detail is what Edgegap kept. Fix the cause and redeploy; ' +
2865
+ 'edgegap_wait_for_deployment returns the log tail itself when a start fails.');
2866
+ }
2867
+ if (!d.running && !TERMINAL_OK.some((s) => status.includes(s))) {
2868
+ 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}"}, ` +
2869
+ 'then read the logs if it fails or misbehaves.');
2870
+ }
2871
+ return undefined;
2872
+ }
2873
+ /** The skill name an agent most likely meant: "unity" → "edgegap-unity". */
2874
+ function closestSkill(input, names) {
2875
+ const wanted = input.trim().toLowerCase().replace(/^edgegap[-_ ]?/, '').replace(/[_ ]/g, '-');
2876
+ if (!wanted)
2877
+ return 'edgegap';
2878
+ return (names.find((n) => n === `edgegap-${wanted}`) ??
2879
+ names.find((n) => n.replace(/^edgegap-?/, '').startsWith(wanted)) ??
2880
+ names.find((n) => wanted.includes(n.replace(/^edgegap-/, '')) && n !== 'edgegap'));
2411
2881
  }
2412
2882
  function registryCredentialsUnavailable(imageName, tag) {
2413
2883
  const image = imageName ?? '<image-name>';