@edgegap/mcp 0.10.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
@@ -8,7 +8,8 @@
8
8
  * failure mode in agent flows is not a bad call, it is a call made out of order.
9
9
  */
10
10
  import { z } from 'zod';
11
- import { EdgegapApiError } from './client.js';
11
+ import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
12
+ import { EdgegapApiError, maskSecrets } from './client.js';
12
13
  import { assertAppAllowed, redact, hostLabel } from './config.js';
13
14
  import { VERSION } from './version.js';
14
15
  import { TokenUnavailableError } from './auth.js';
@@ -16,6 +17,8 @@ import { validateServerConfig, PROTOCOLS, NETCODE_NAMES, } from './serverconfig.
16
17
  import { generateDockerfile, DockerfileInputError } from './dockerfile.js';
17
18
  import { buildMatchmakerConfig, DASHBOARD_URL } from './matchmaker.js';
18
19
  import { badImage, badTag, looksSecret, TAG_FIX } from './image.js';
20
+ import { OUTPUT } from './outputs.js';
21
+ import { finishReport, codeForStatus } from './callreport.js';
19
22
  import { SKILLS_PACK, findSkill, findSkillFile, fileIndex, mimeType, skillUri } from './skills.js';
20
23
  import { SKILL_NAME_RE, compareVersions, latestPack, latestSkillVersions, servedPackStatus, skillsCheckFromEnv, } from './skillsversion.js';
21
24
  /**
@@ -66,9 +69,10 @@ export function serverInstructions(mode) {
66
69
  `Nakama backend: ${skillUri('edgegap-nakama', 'SKILL.md')}, ` +
67
70
  `PlayFab Matchmaking: ${skillUri('edgegap-playfab', 'SKILL.md')}, ` +
68
71
  `Three.js or other browser game with its own Node.js server: ${skillUri('edgegap-threejs', 'SKILL.md')}, ` +
69
- `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')}). ` +
70
74
  'If your client cannot read MCP resources, call edgegap_get_skill with the skill name ' +
71
- '(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. ' +
72
76
  'These Edgegap skills hold the tested workflow, templates and known pitfalls; follow them over general knowledge. ' +
73
77
  'edgegap_list_skills lists all of them.\n\n' +
74
78
  'Host multiplayer games on Edgegap. The recommended setup is an authoritative dedicated ' +
@@ -110,8 +114,25 @@ const WS_PROTOCOLS = new Set(['WS', 'WEBSOCKET']);
110
114
  const TLS_PROTOCOLS = new Set(['WS', 'WEBSOCKET', 'HTTP']);
111
115
  const TERMINAL_OK = ['READY', 'STATUS_READY'];
112
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
+ }
130
+ /** JSON.stringify replacer: null fields are left out, like undefined ones. The
131
+ * API sends many (fqdn before a deployment is placed, unset error_detail), and
132
+ * an absent field reads the same to an agent at fewer tokens. */
133
+ const dropNulls = (_key, value) => (value === null ? undefined : value);
113
134
  function ok(payload, notice) {
114
- const body = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);
135
+ const body = typeof payload === 'string' ? payload : JSON.stringify(payload, dropNulls, 2);
115
136
  const structured = payload !== null && typeof payload === 'object' && !Array.isArray(payload)
116
137
  ? JSON.parse(body)
117
138
  : undefined;
@@ -140,8 +161,16 @@ function scrubToken(result, token) {
140
161
  ...(result.structuredContent ? { structuredContent: JSON.parse(clean(structuredText)) } : {}),
141
162
  };
142
163
  }
143
- function fail(message) {
144
- 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 } });
145
174
  }
146
175
  /**
147
176
  * What a 404 means, per kind of resource. A 404 from Edgegap only says "not
@@ -181,13 +210,19 @@ function guard(auth, fn, notFound, forbidden) {
181
210
  if (err instanceof TokenUnavailableError) {
182
211
  // Not a failure to correct — a decision the human made. Say so plainly
183
212
  // so the agent stops rather than looping on the same tool.
184
- 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);
185
215
  }
186
216
  if (err instanceof EdgegapApiError) {
187
217
  const hint = errorHint(err, notFound, forbidden);
188
- 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
+ });
189
223
  }
190
- 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');
191
226
  });
192
227
  // The org-wide-scope reminder is attached to whichever call first used a
193
228
  // freshly supplied token, success or failure. A developer who just handed
@@ -207,7 +242,37 @@ function guard(auth, fn, notFound, forbidden) {
207
242
  function guarded(auth, notFound, fn) {
208
243
  return guard(auth, fn, notFound, notFound === NOT_FOUND.relay ? FORBIDDEN.relay : undefined);
209
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;
210
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
+ }
211
276
  switch (err.status) {
212
277
  case 401:
213
278
  // Deliberately does not promise a re-prompt: the local server asks again
@@ -497,6 +562,41 @@ function autoStop(maxDuration) {
497
562
  : {}),
498
563
  };
499
564
  }
565
+ /**
566
+ * Rewrites the SDK's "Input validation error: Invalid arguments for tool X:
567
+ * a: Invalid input: expected string, received undefined, b: ..." into one line
568
+ * per argument, plus the tool's required and optional parameters, so the agent
569
+ * can fix the call in one try. Undefined for any other message.
570
+ */
571
+ export function argumentError(message, inputs) {
572
+ const m = message.match(/Input validation error: Invalid arguments for tool (\S+?): ([\s\S]*)$/);
573
+ if (!m)
574
+ return undefined;
575
+ const [, toolName, detail] = m;
576
+ // Two wordings: SDK v1 (local) "expected string, received number at application",
577
+ // one per line; SDK v2 (hosted) "application: expected string, received number",
578
+ // comma-joined.
579
+ const problems = detail
580
+ .split('\n')
581
+ .flatMap((line) => line.split(/,\s+(?=[\w.[\]]+: )/))
582
+ .map((p) => p.trim())
583
+ .filter(Boolean)
584
+ .map((p) => {
585
+ const v2 = p.match(/^([\w.[\]]+): (?:Invalid input: )?expected (\w+), received (\w+)$/);
586
+ const v1 = p.match(/^(?:Invalid input: )?expected (\w+), received (\w+) at ([\w.[\]]+)$/);
587
+ const [field, want, got] = v2 ? [v2[1], v2[2], v2[3]] : v1 ? [v1[3], v1[1], v1[2]] : [];
588
+ if (!field)
589
+ return `- ${p}`;
590
+ return got === 'undefined' ? `- ${field}: missing (required)` : `- ${field}: must be ${want} (got ${got})`;
591
+ });
592
+ const shape = inputs.get(toolName) ?? {};
593
+ const required = Object.keys(shape).filter((k) => !shape[k].safeParse(undefined).success);
594
+ const optional = Object.keys(shape).filter((k) => !required.includes(k));
595
+ return (`Invalid arguments for ${toolName}. Nothing was sent.\n${problems.join('\n')}\n\n` +
596
+ `Required: ${required.join(', ') || 'none'}.` +
597
+ (optional.length ? ` Optional: ${optional.join(', ')}.` : '') +
598
+ ' Fix the arguments and call again.');
599
+ }
500
600
  /** Prepends "[api.edgegap.com]" (or "[custom · host]") to a tool result. */
501
601
  function withHost(result, label) {
502
602
  return { ...result, content: [{ type: 'text', text: `[${label}]` }, ...result.content] };
@@ -507,7 +607,79 @@ export function registerTools(server, client, config, auth, options = {}) {
507
607
  // at a custom EDGEGAP_BASE_URL can never be mistaken for production.
508
608
  const label = hostLabel(config);
509
609
  // ...and never carries the API token, whatever the API echoed back.
510
- const tool = ((name, def, cb) => server.registerTool(name, def, (async (...a) => withHost(scrubToken(await cb(...a), auth.current), label))));
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;
617
+ const tool = ((name, def, cb) => {
618
+ inputs.set(name, (def.inputSchema) ?? {});
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
+ }));
656
+ });
657
+ // Errors the SDK raises itself (bad arguments, a handler that throws) skip
658
+ // the wrapper above. Both SDK versions route them through createToolError,
659
+ // so give those the same host label and token scrub, and turn argument
660
+ // errors into a list the agent can act on.
661
+ const sdk = server;
662
+ const sdkToolError = sdk.createToolError?.bind(server);
663
+ if (sdkToolError) {
664
+ sdk.createToolError = (message) => {
665
+ const friendly = argumentError(message, inputs);
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;
681
+ };
682
+ }
511
683
  // ---------------------------------------------------------------- 0 ----
512
684
  // No token, no network: describes this server's own configuration, so an
513
685
  // agent can check where it is pointed and what is allowed before acting.
@@ -516,13 +688,21 @@ export function registerTools(server, client, config, auth, options = {}) {
516
688
  description: 'Report which Edgegap API this server talks to, its version, whether it is the local or ' +
517
689
  'hosted server, and the guardrails in force: read-only mode, application allowlist, ' +
518
690
  'max_duration ceiling, the agent deployment cap, the tag forced onto every deployment, and which tools support ' +
519
- 'dry_run. Call it first when unsure what this session is allowed to do, or before ' +
520
- 'anything billable. Makes no API call and never shows the token.',
521
- 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
+ },
700
+ outputSchema: OUTPUT.context,
522
701
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
523
- }, async () => {
702
+ }, async ({ check_token }) => {
524
703
  const hosted = config.transport === 'hosted';
525
- return ok({
704
+ const tokenStatus = await describeToken(client, auth, hosted, check_token === true);
705
+ return withMeta(ok({
526
706
  server: `@edgegap/mcp ${VERSION}`,
527
707
  transport: hosted ? 'hosted (Streamable HTTP)' : 'local (stdio)',
528
708
  api_host: label,
@@ -537,6 +717,7 @@ export function registerTools(server, client, config, auth, options = {}) {
537
717
  ? 'provided by the developer this session (memory only)'
538
718
  : 'not yet provided: the developer is asked on first use',
539
719
  token_scope: 'organization-wide (Edgegap cannot scope tokens)',
720
+ token_status: tokenStatus,
540
721
  read_only: config.readOnly,
541
722
  app_allowlist: config.appAllowlist.length ? config.appAllowlist : 'none (all applications)',
542
723
  max_duration_ceiling_minutes: config.maxDurationCeiling,
@@ -558,7 +739,8 @@ export function registerTools(server, client, config, auth, options = {}) {
558
739
  results: `every result starts with [${label}]`,
559
740
  },
560
741
  user_agent: `edgegap-mcp/${VERSION} (<MCP client name>)`,
561
- });
742
+ works_without_token: TOKENLESS_TOOLS,
743
+ }), { props: { token_state: String(tokenStatus.state) } });
562
744
  });
563
745
  // ---------------------------------------------------------------- 1 ----
564
746
  tool('edgegap_list_apps', {
@@ -567,18 +749,34 @@ export function registerTools(server, client, config, auth, options = {}) {
567
749
  'deploying anything, so you reuse an existing application instead of making a duplicate. ' +
568
750
  'An "application" groups versions of one game server.',
569
751
  inputSchema: {
570
- limit: z.number().int().min(1).max(100).optional().describe('Results per page. Default 50.'),
571
- 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(),
572
754
  },
755
+ outputSchema: OUTPUT.listApps,
573
756
  annotations: { readOnlyHint: true, openWorldHint: true },
574
757
  }, async ({ limit, page }) => guard(auth, async () => {
575
- 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 });
576
760
  const apps = (res.applications ?? []).map((a) => ({
577
761
  name: a.name,
578
762
  active: a.is_active,
579
763
  last_updated: a.last_updated,
580
764
  }));
581
- 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'] });
582
780
  }));
583
781
  // ---------------------------------------------------------------- 2 ----
584
782
  if (mutating) {
@@ -606,11 +804,11 @@ export function registerTools(server, client, config, auth, options = {}) {
606
804
  return dryRunResult(dry.requests);
607
805
  }
608
806
  const res = await client.createApp(body);
609
- return ok({
807
+ return withMeta(ok({
610
808
  created: res.name,
611
809
  active: res.is_active,
612
810
  next_step: 'Call edgegap_create_app_version to attach a container image.',
613
- });
811
+ }), { milestones: ['app_created'] });
614
812
  }));
615
813
  }
616
814
  // --------------------------------------------------------------- 2b ----
@@ -649,6 +847,7 @@ export function registerTools(server, client, config, auth, options = {}) {
649
847
  inputSchema: {
650
848
  application: z.string().describe('Application name, as returned by edgegap_list_apps.'),
651
849
  },
850
+ outputSchema: OUTPUT.listAppVersions,
652
851
  annotations: { readOnlyHint: true, openWorldHint: true },
653
852
  }, async ({ application }) =>
654
853
  // Read-only, so not subject to EDGEGAP_APP_ALLOWLIST: the allowlist
@@ -656,7 +855,16 @@ export function registerTools(server, client, config, auth, options = {}) {
656
855
  guarded(auth, NOT_FOUND.app, async () => {
657
856
  const res = await client.listAppVersions(application);
658
857
  const versions = (res.versions ?? []).map(compactVersion);
659
- 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 } });
660
868
  }));
661
869
  // --------------------------------------------------------------- 3b ----
662
870
  tool('edgegap_get_app_version', {
@@ -669,6 +877,7 @@ export function registerTools(server, client, config, auth, options = {}) {
669
877
  application: z.string().describe('Application name.'),
670
878
  version: z.string().describe('Version name, as listed by edgegap_list_app_versions.'),
671
879
  },
880
+ outputSchema: OUTPUT.getAppVersion,
672
881
  annotations: { readOnlyHint: true, openWorldHint: true },
673
882
  }, async ({ application, version }) => guarded(auth, NOT_FOUND.app, async () => {
674
883
  const v = await client.getAppVersion(application, version);
@@ -836,13 +1045,14 @@ export function registerTools(server, client, config, auth, options = {}) {
836
1045
  'they need wss://: create the version with tls_upgrade: true on this port.');
837
1046
  }
838
1047
  }
839
- return ok({
1048
+ return withMeta(ok({
840
1049
  created: `${args.application}/${res.version?.name ?? args.name}`,
841
1050
  max_duration_minutes: capped,
842
1051
  capped_by_server: capped < requested ? config.maxDurationCeiling : undefined,
843
1052
  notes: notes.length ? notes : undefined,
844
- next_step: 'Call edgegap_deploy to start an instance.',
845
- });
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 } });
846
1056
  }));
847
1057
  }
848
1058
  // --------------------------------------------------------------- 4b ----
@@ -855,8 +1065,10 @@ export function registerTools(server, client, config, auth, options = {}) {
855
1065
  'the shutdown grace period. Only the fields you pass change. Deployments already running ' +
856
1066
  'keep their old settings; new deployments get the new ones. Same refusals as ' +
857
1067
  'edgegap_create_app_version: "latest" or empty tags, a docker_image holding a host or ' +
858
- 'tag, and the API token in the registry login. Resources, ports and env vars cannot be ' +
859
- 'changed here; create a new version for those.',
1068
+ 'tag, and the API token in the registry login or env vars. ports and env REPLACE the ' +
1069
+ 'version\'s whole list (per the API): read the current ones with edgegap_get_app_version ' +
1070
+ 'and pass every port or variable to keep. CPU and memory cannot be changed here; create a ' +
1071
+ 'new version, or override them per deployment in edgegap_deploy.',
860
1072
  inputSchema: {
861
1073
  application: z.string().describe('Application name.'),
862
1074
  version: z.string().describe('Version name to change.'),
@@ -880,6 +1092,21 @@ export function registerTools(server, client, config, auth, options = {}) {
880
1092
  .max(3600)
881
1093
  .optional()
882
1094
  .describe('Seconds between SIGTERM and SIGKILL when a deployment stops.'),
1095
+ ports: z
1096
+ .array(z.object({
1097
+ port: z.number().int().min(1).max(59999).describe('Port the server listens on.'),
1098
+ protocol: z.string().describe(`One of ${PROTOCOLS.join(', ')}. Most game servers use UDP.`),
1099
+ name: z.string().optional().describe('Label, e.g. "gameport".'),
1100
+ to_check: z.boolean().optional().describe('Readiness check on this port. Default true.'),
1101
+ tls_upgrade: z.boolean().optional().describe('wss:// / https:// for browser clients. WS and HTTP ports only.'),
1102
+ }))
1103
+ .min(1)
1104
+ .optional()
1105
+ .describe('REPLACES every port on the version. Include the ports to keep, not only new ones.'),
1106
+ env: z
1107
+ .array(z.object({ key: z.string(), value: z.string() }))
1108
+ .optional()
1109
+ .describe('REPLACES every env var on the version; [] removes them all. Values are never echoed back.'),
883
1110
  dry_run: dryRunParam,
884
1111
  },
885
1112
  annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
@@ -888,9 +1115,18 @@ export function registerTools(server, client, config, auth, options = {}) {
888
1115
  const leak = await tokenLeak(auth, args.dry_run, [
889
1116
  ['registry_username', args.registry_username],
890
1117
  ['registry_token', args.registry_token],
1118
+ ...(args.env ?? []).flatMap((e) => [
1119
+ [`env var name "${e.key.slice(0, 40)}"`, e.key],
1120
+ [`the value of env var "${e.key.slice(0, 40)}"`, e.value],
1121
+ ]),
891
1122
  ]);
892
1123
  if (leak)
893
1124
  return leak;
1125
+ const badTls = args.ports?.find((p) => p.tls_upgrade && !TLS_PROTOCOLS.has(p.protocol.toUpperCase()));
1126
+ if (badTls) {
1127
+ return fail(`Port ${badTls.port} is ${badTls.protocol}; tls_upgrade only works on WS and HTTP ports. ` +
1128
+ 'Use protocol "WS" for a WebSocket server, or drop tls_upgrade.');
1129
+ }
894
1130
  if (args.docker_tag !== undefined) {
895
1131
  const tagProblem = badTag(args.docker_tag);
896
1132
  if (tagProblem)
@@ -915,6 +1151,14 @@ export function registerTools(server, client, config, auth, options = {}) {
915
1151
  force_cache: args.force_cache,
916
1152
  verify_image: args.verify_image,
917
1153
  termination_grace_period_seconds: args.termination_grace_period_seconds,
1154
+ ports: args.ports?.map((p) => ({
1155
+ port: p.port,
1156
+ protocol: p.protocol,
1157
+ name: p.name ?? 'gameport',
1158
+ to_check: p.to_check ?? true,
1159
+ tls_upgrade: p.tls_upgrade ?? false,
1160
+ })),
1161
+ envs: args.env?.map((e) => ({ key: e.key, value: e.value, is_hidden: looksSecret(e.key) })),
918
1162
  };
919
1163
  for (const k of Object.keys(body))
920
1164
  if (body[k] === undefined)
@@ -925,6 +1169,10 @@ export function registerTools(server, client, config, auth, options = {}) {
925
1169
  const notes = capped !== undefined && capped < (args.max_duration_minutes ?? 0)
926
1170
  ? [`max_duration capped to ${capped} minutes by EDGEGAP_MAX_DURATION_MINUTES.`]
927
1171
  : [];
1172
+ if (args.ports)
1173
+ notes.push(`ports replaced: the version now has exactly these ${args.ports.length}.`);
1174
+ if (args.env)
1175
+ notes.push(`env replaced: the version now has exactly these ${args.env.length} variables.`);
928
1176
  if (args.dry_run) {
929
1177
  const dry = client.dryRun();
930
1178
  await dry.client.updateAppVersion(args.application, args.version, body);
@@ -953,6 +1201,7 @@ export function registerTools(server, client, config, auth, options = {}) {
953
1201
  page: z.number().int().min(1).optional(),
954
1202
  limit: z.number().int().min(1).max(200).optional().describe('Default 100.'),
955
1203
  },
1204
+ outputSchema: OUTPUT.listLocations,
956
1205
  annotations: { readOnlyHint: true, openWorldHint: true },
957
1206
  }, async ({ application, version, page, limit }) => guarded(auth, NOT_FOUND.app, async () => {
958
1207
  if ((application === undefined) !== (version === undefined)) {
@@ -983,6 +1232,7 @@ export function registerTools(server, client, config, auth, options = {}) {
983
1232
  page: z.number().int().min(1).optional(),
984
1233
  limit: z.number().int().min(1).max(200).optional().describe('Default 100.'),
985
1234
  },
1235
+ outputSchema: OUTPUT.listPingBeacons,
986
1236
  annotations: { readOnlyHint: true, openWorldHint: true },
987
1237
  }, async ({ page, limit }) => guard(auth, async () => {
988
1238
  const res = await client.listBeacons({ page, limit: limit ?? 100 });
@@ -1028,10 +1278,16 @@ export function registerTools(server, client, config, auth, options = {}) {
1028
1278
  .int()
1029
1279
  .min(256)
1030
1280
  .optional()
1031
- .describe('Override the version CPU (with memory_mb). Not in the published v2 spec, so the API may ignore it; a version with the size you need is the reliable way.'),
1032
- memory_mb: z.number().int().min(256).optional().describe('Override the version memory (with cpu_units). Same caveat as cpu_units.'),
1281
+ .describe('Override the version\'s CPU for this deployment only, with memory_mb. 1024 = 1 vCPU.'),
1282
+ memory_mb: z
1283
+ .number()
1284
+ .int()
1285
+ .min(256)
1286
+ .optional()
1287
+ .describe('Override the version\'s memory for this deployment only, with cpu_units. At most 2x cpu_units.'),
1033
1288
  dry_run: dryRunParam,
1034
1289
  },
1290
+ outputSchema: OUTPUT.deploy,
1035
1291
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
1036
1292
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
1037
1293
  assertAppAllowed(config, args.application);
@@ -1065,7 +1321,15 @@ export function registerTools(server, client, config, auth, options = {}) {
1065
1321
  is_hidden: looksSecret(e.key),
1066
1322
  }));
1067
1323
  }
1068
- if (args.cpu_units && args.memory_mb) {
1324
+ // The v2 API takes both or neither (DeploymentV2.resources).
1325
+ if ((args.cpu_units === undefined) !== (args.memory_mb === undefined)) {
1326
+ return fail('Pass both cpu_units and memory_mb to override the version\'s resources, or neither to use the version\'s.');
1327
+ }
1328
+ if (args.cpu_units !== undefined && args.memory_mb !== undefined) {
1329
+ if (args.memory_mb > args.cpu_units * 2) {
1330
+ return fail(`memory_mb (${args.memory_mb}) exceeds twice cpu_units (${args.cpu_units}). Edgegap rejects this. ` +
1331
+ `Lower memory_mb to ${args.cpu_units * 2} or raise cpu_units.`);
1332
+ }
1069
1333
  body.resources = { cpu_units: args.cpu_units, memory_mib: args.memory_mb };
1070
1334
  }
1071
1335
  if (args.dry_run) {
@@ -1101,20 +1365,14 @@ export function registerTools(server, client, config, auth, options = {}) {
1101
1365
  }
1102
1366
  }
1103
1367
  const res = await client.deploy(body);
1104
- return ok({
1368
+ return withMeta(ok({
1105
1369
  request_id: res.request_id,
1106
1370
  status: 'starting',
1107
1371
  tags,
1108
1372
  ...autoStop(version.max_duration),
1109
- // "resources" is not in the published v2 deploy schema
1110
- // (test/spec.mjs). Say so rather than promise the override.
1111
- resources_note: body.resources
1112
- ? 'cpu_units/memory_mb were sent, but the published v2 API does not document a per-deployment ' +
1113
- 'override, so the deployment may run with the version\'s size. For a different size, create a ' +
1114
- 'version with it.'
1115
- : undefined,
1373
+ resources: body.resources,
1116
1374
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
1117
- });
1375
+ }), { hash: { request_id: res.request_id }, props: { resources_override: body.resources !== undefined } });
1118
1376
  }));
1119
1377
  }
1120
1378
  // ---------------------------------------------------------------- 6 ----
@@ -1126,10 +1384,17 @@ export function registerTools(server, client, config, auth, options = {}) {
1126
1384
  inputSchema: {
1127
1385
  request_id: z.string().describe('The request_id returned by edgegap_deploy.'),
1128
1386
  },
1387
+ outputSchema: OUTPUT.deployment,
1129
1388
  annotations: { readOnlyHint: true, openWorldHint: true },
1130
1389
  }, async ({ request_id }) => guarded(auth, NOT_FOUND.deployment, async () => {
1131
1390
  const d = await client.getDeployment(request_id);
1132
- 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 });
1133
1398
  }));
1134
1399
  // ---------------------------------------------------------------- 7 ----
1135
1400
  tool('edgegap_wait_for_deployment', {
@@ -1143,50 +1408,65 @@ export function registerTools(server, client, config, auth, options = {}) {
1143
1408
  timeout_seconds: z
1144
1409
  .number()
1145
1410
  .int()
1146
- .min(5)
1147
- .max(600)
1148
1411
  .optional()
1149
- .describe('How long to wait before giving up. Default 180.'),
1412
+ .describe('How long to wait before giving up, 5-600. Default 180.'),
1150
1413
  },
1414
+ outputSchema: OUTPUT.waitForDeployment,
1151
1415
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
1152
- }, async ({ request_id, timeout_seconds }) => guarded(auth, NOT_FOUND.deployment, async () => {
1153
- 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;
1154
1419
  const startedAt = Date.now();
1155
1420
  let intervalMs = 2000;
1421
+ let polls = 0;
1156
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
+ });
1157
1428
  while (Date.now() - startedAt < budgetMs) {
1158
1429
  last = await client.getDeployment(request_id);
1430
+ polls++;
1159
1431
  const status = (last.current_status ?? '').toUpperCase();
1160
1432
  if (last.error || TERMINAL_BAD.some((s) => status.includes(s))) {
1161
1433
  // Fetched now, not left to the agent: a failed deployment is
1162
1434
  // cleaned up quickly and its logs go with it, so a separate
1163
1435
  // edgegap_get_deployment_logs call often finds nothing.
1164
1436
  const logs = await logTail(client, request_id, 3000);
1165
- 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` +
1166
1438
  `${last.error_detail ?? 'No error detail returned.'}\n\n` +
1167
1439
  (logs
1168
- ? `Container output (tail):\n${logs}\n\nFix the image or port configuration before redeploying.`
1169
- : `No container logs could be read (the container may never have started, or it ` +
1170
- `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' });
1171
1445
  }
1172
1446
  if (last.running || TERMINAL_OK.some((s) => status.includes(s))) {
1173
- return ok({
1447
+ return withMeta(ok({
1174
1448
  ...compactDeployment(last),
1175
1449
  waited_seconds: Math.round((Date.now() - startedAt) / 1000),
1176
- });
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'] });
1177
1455
  }
1456
+ await progress(Date.now() - startedAt, `Deployment ${request_id}: ${last.current_status ?? 'starting'}`);
1178
1457
  await new Promise((r) => setTimeout(r, intervalMs));
1179
1458
  intervalMs = Math.min(intervalMs * 1.5, 10_000);
1180
1459
  }
1181
1460
  // Not an error: the wait ran out, the deployment did not fail. It is
1182
1461
  // usually still starting (large images pull slowly on a cold host).
1183
- return ok({
1462
+ return withMeta(ok({
1184
1463
  ...(last ? compactDeployment(last) : { request_id }),
1185
1464
  ready: false,
1186
1465
  waited_seconds: Math.round((Date.now() - startedAt) / 1000),
1187
- next_step: `Not ready within ${timeout_seconds ?? 180}s, and not failed: it may still be starting. ` +
1188
- `Call edgegap_wait_for_deployment again, or edgegap_stop_deployment if it should not keep running.`,
1189
- });
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'));
1190
1470
  }));
1191
1471
  // ---------------------------------------------------------------- 8 ----
1192
1472
  tool('edgegap_list_deployments', {
@@ -1226,8 +1506,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1226
1506
  }))
1227
1507
  .optional()
1228
1508
  .describe('e.g. [{field:"created_at",order:"asc"}] for oldest first.'),
1229
- limit: z.number().int().min(1).max(100).optional().describe('Default 50.'),
1509
+ limit: z.number().int().optional().describe('1-100. Default 50.'),
1230
1510
  },
1511
+ outputSchema: OUTPUT.listDeployments,
1231
1512
  annotations: { readOnlyHint: true, openWorldHint: true },
1232
1513
  }, async ({ only_agent_deployments, filters: given, order_by, limit }) => guard(auth, async () => {
1233
1514
  let filters = given;
@@ -1245,7 +1526,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1245
1526
  const query = filters?.length || order_by?.length
1246
1527
  ? JSON.stringify({ filters: filters ?? [], ...(order_by?.length ? { order_by } : {}) })
1247
1528
  : undefined;
1248
- const res = await client.listDeployments({ query, limit: limit ?? 50 });
1529
+ const res = await client.listDeployments({ query, limit: clamp(limit, 1, 100, 50) });
1249
1530
  const rows = (res.data ?? []).map((d) => ({
1250
1531
  request_id: d.request_id,
1251
1532
  ready: d.ready,
@@ -1253,7 +1534,23 @@ export function registerTools(server, client, config, auth, options = {}) {
1253
1534
  started: d.start_time,
1254
1535
  tags: d.tags,
1255
1536
  }));
1256
- 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 } });
1257
1554
  }));
1258
1555
  // ---------------------------------------------------------------- 9 ----
1259
1556
  if (mutating) {
@@ -1284,10 +1581,14 @@ export function registerTools(server, client, config, auth, options = {}) {
1284
1581
  catch (err) {
1285
1582
  const gone = await alreadyStopped(client, request_id, err);
1286
1583
  if (gone)
1287
- return ok(gone);
1584
+ return withMeta(ok(gone), { hash: { request_id }, props: { stop_result: gone.result } });
1288
1585
  throw err;
1289
1586
  }
1290
- 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' } });
1291
1592
  }));
1292
1593
  }
1293
1594
  // --------------------------------------------------------------- 10 ----
@@ -1302,19 +1603,30 @@ export function registerTools(server, client, config, auth, options = {}) {
1302
1603
  max_characters: z
1303
1604
  .number()
1304
1605
  .int()
1305
- .min(500)
1306
- .max(50_000)
1307
1606
  .optional()
1308
- .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.'),
1309
1608
  },
1310
1609
  annotations: { readOnlyHint: true, openWorldHint: true },
1311
1610
  }, async ({ request_id, max_characters }) => guarded(auth, NOT_FOUND.logs, async () => {
1312
- const res = await client.getDeploymentLogs(request_id);
1313
- 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);
1314
1626
  const tail = (s) => !s ? undefined : s.length > cap ? `...[truncated]...\n${s.slice(-cap)}` : s;
1315
1627
  return ok({
1316
1628
  request_id,
1317
- logs: tail(res.logs) ?? '(no logs returned)',
1629
+ logs: tail(res.logs) ?? '(no logs returned yet: the server has printed nothing)',
1318
1630
  crash_logs: tail(res.crash_logs),
1319
1631
  exit_code: res.crash_data?.exit_code,
1320
1632
  crash_message: res.crash_data?.message,
@@ -1335,6 +1647,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1335
1647
  end_time: z.string().optional().describe('ISO 8601. Default: now, or when it stopped.'),
1336
1648
  step: z.string().optional().describe('Averaging step, e.g. "30s" or "5m". Default: the API\'s.'),
1337
1649
  },
1650
+ outputSchema: OUTPUT.metrics,
1338
1651
  annotations: { readOnlyHint: true, openWorldHint: true },
1339
1652
  }, async ({ request_id, start_time, end_time, step }) => guarded(auth, NOT_FOUND.deployment, async () => {
1340
1653
  const bad = checkRequestId(request_id);
@@ -1487,6 +1800,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1487
1800
  docker_image: z.string().optional(),
1488
1801
  docker_tag: z.string().optional(),
1489
1802
  },
1803
+ outputSchema: OUTPUT.validateServerConfig,
1490
1804
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
1491
1805
  }, async (args) => {
1492
1806
  const { engine, errors, warnings } = validateServerConfig(args);
@@ -1496,7 +1810,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1496
1810
  ? generateDockerfile({ engine, ports: args.ports, netcode: args.netcode }).dockerfile
1497
1811
  : undefined;
1498
1812
  const verdict = errors.length > 0 ? 'fail' : warnings.length > 0 ? 'pass_with_warnings' : 'pass';
1499
- return ok({
1813
+ return withMeta(ok({
1500
1814
  verdict,
1501
1815
  engine,
1502
1816
  errors,
@@ -1514,6 +1828,15 @@ export function registerTools(server, client, config, auth, options = {}) {
1514
1828
  : 'Build with "docker build --platform linux/amd64 -t <image>:<unique-tag> ." and run it ' +
1515
1829
  'locally with the same port mapping to confirm it starts. Then push it; ' +
1516
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
+ },
1517
1840
  });
1518
1841
  });
1519
1842
  // --------------------------------------------------------------- 12 ----
@@ -1531,7 +1854,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1531
1854
  'do not retry. When it does return a token, it is registry-scoped (push/pull images in ' +
1532
1855
  'this project), not the org API token: pass it to docker login via --password-stdin, ' +
1533
1856
  'never as a command-line argument, and do not write it into files. Call ' +
1534
- '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.',
1535
1860
  inputSchema: {
1536
1861
  image_name: z
1537
1862
  .string()
@@ -1581,7 +1906,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1581
1906
  const image = image_name ?? '<image-name>';
1582
1907
  const buildTag = tag ?? '<unique-build-tag>';
1583
1908
  const ref = `${host}/${creds.project}/${image}:${buildTag}`;
1584
- return ok({
1909
+ return withMeta(ok({
1585
1910
  registry_url: host,
1586
1911
  project: creds.project,
1587
1912
  username: creds.username,
@@ -1603,7 +1928,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1603
1928
  '(it never needs to appear in a command line or file), then build and push. ' +
1604
1929
  `Confirm the push with edgegap_list_registry_tags (image_name "${image}", without the project), ` +
1605
1930
  'then call edgegap_create_app_version with the values in for_create_app_version.',
1606
- });
1931
+ }), { milestones: ['registry_credentials_ok'], props: { registry_status: 'credentials_returned' } });
1607
1932
  }));
1608
1933
  }
1609
1934
  // --------------------------------------------------------------- 13 ----
@@ -1611,7 +1936,9 @@ export function registerTools(server, client, config, auth, options = {}) {
1611
1936
  title: 'List image tags in the Edgegap registry',
1612
1937
  description: 'List the tags pushed for one image in this organization\'s Edgegap container registry, ' +
1613
1938
  'with push time and size. Call it after docker push to confirm the tag landed before ' +
1614
- '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.',
1615
1942
  inputSchema: {
1616
1943
  image_name: z
1617
1944
  .string()
@@ -1619,14 +1946,15 @@ export function registerTools(server, client, config, auth, options = {}) {
1619
1946
  .describe('The image name only, without the project, registry host or tag, e.g. "my-game-server". ' +
1620
1947
  'The API reads the project from your token; "<project>/my-game-server" is not found.'),
1621
1948
  page: z.number().int().min(1).optional(),
1622
- limit: z.number().int().min(1).max(100).optional().describe('Default 20.'),
1949
+ limit: z.number().int().optional().describe('1-100. Default 20.'),
1623
1950
  },
1951
+ outputSchema: OUTPUT.listRegistryTags,
1624
1952
  annotations: { readOnlyHint: true, openWorldHint: true },
1625
1953
  }, async ({ image_name, page, limit }) => guard(auth, async () => {
1626
1954
  // Agents often pass the full reference they pushed. Reduce it to what
1627
1955
  // the API wants: no "registry.edgegap.com/" host, no ":tag".
1628
1956
  let name = imageNameOnly(image_name);
1629
- const query = { page, limit: limit ?? 20 };
1957
+ const query = { page, limit: clamp(limit, 1, 100, 20) };
1630
1958
  const notFound = (err) => err instanceof EdgegapApiError && err.status === 404;
1631
1959
  let res;
1632
1960
  try {
@@ -1643,12 +1971,20 @@ export function registerTools(server, client, config, auth, options = {}) {
1643
1971
  }
1644
1972
  }
1645
1973
  catch (err) {
1646
- // The generic 404 hint points at applications, which is wrong here.
1647
- if (!notFound(err))
1648
- throw err;
1649
- return fail(`No image named "${name}" in this organization's Edgegap registry, so nothing has been ` +
1650
- 'pushed under that name. Check the name (image name only, as used after ' +
1651
- '"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;
1652
1988
  }
1653
1989
  const tags = (res.data ?? []).map((t) => ({
1654
1990
  tag: t.tag,
@@ -1657,7 +1993,10 @@ export function registerTools(server, client, config, auth, options = {}) {
1657
1993
  digest: t.artifact?.image_hash,
1658
1994
  }));
1659
1995
  const hasNext = res.pagination?.has_next === true;
1660
- 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({
1661
2000
  image_name: name,
1662
2001
  note: name !== image_name ? `Looked up "${name}". Pass the image name only next time.` : undefined,
1663
2002
  total: res.count ?? tags.length,
@@ -1667,9 +2006,12 @@ export function registerTools(server, client, config, auth, options = {}) {
1667
2006
  truncated: true,
1668
2007
  next_step: `Only page ${page ?? 1} is shown. Call again with page: ${(page ?? 1) + 1} before concluding a tag is missing.`,
1669
2008
  }
1670
- : {}),
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
+ }),
1671
2013
  tags,
1672
- });
2014
+ }), { props: { item_count: tags.length }, milestones: tags.length ? ['image_pushed'] : [] });
1673
2015
  }));
1674
2016
  // --------------------------------------------------------------- 13b ----
1675
2017
  if (mutating) {
@@ -1812,9 +2154,25 @@ export function registerTools(server, client, config, auth, options = {}) {
1812
2154
  'and delete them with edgegap_delete_relay_session. Authorization tokens are not listed; ' +
1813
2155
  'read one session with edgegap_get_relay_session.',
1814
2156
  inputSchema: {},
2157
+ outputSchema: OUTPUT.listRelaySessions,
1815
2158
  annotations: { readOnlyHint: true, openWorldHint: true },
1816
2159
  }, async () => guard(auth, async () => {
1817
- 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
+ }
1818
2176
  const sessions = (res.sessions ?? []).map((r) => ({
1819
2177
  session_id: r.session_id,
1820
2178
  status: r.status,
@@ -1951,6 +2309,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1951
2309
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
1952
2310
  assertAppAllowed(config, args.application);
1953
2311
  const { config: mmConfig, problems, cautions } = buildMatchmakerConfig(args);
2312
+ let verified = false;
1954
2313
  if (args.verify_version !== false) {
1955
2314
  try {
1956
2315
  const res = await client.listAppVersions(args.application);
@@ -1965,22 +2324,39 @@ export function registerTools(server, client, config, auth, options = {}) {
1965
2324
  if (!v.ports?.length)
1966
2325
  problems.push(`Version "${args.version}" has no ports, so matched players have nothing to connect to.`);
1967
2326
  }
2327
+ verified = true;
1968
2328
  }
1969
2329
  catch (err) {
1970
2330
  if (err instanceof EdgegapApiError && err.status === 404) {
1971
2331
  problems.push(`Application "${args.application}" does not exist. Call edgegap_list_apps.`);
1972
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
+ }
1973
2339
  else {
1974
2340
  throw err;
1975
2341
  }
1976
2342
  }
1977
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
+ };
1978
2354
  if (problems.length > 0) {
1979
- 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- ` +
1980
2356
  problems.join('\n- ') +
1981
- `\n\nDraft config:\n${JSON.stringify(mmConfig, null, 2)}`);
2357
+ `\n\nDraft config:\n${JSON.stringify(mmConfig, null, 2)}`, 'VALIDATION_FAILED'), facts);
1982
2358
  }
1983
- return ok({
2359
+ return withMeta(ok({
1984
2360
  config: mmConfig,
1985
2361
  cautions: cautions.length ? cautions : undefined,
1986
2362
  next_steps: [
@@ -1997,7 +2373,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1997
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.`
1998
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.',
1999
2375
  ],
2000
- });
2376
+ }), facts);
2001
2377
  }));
2002
2378
  registerSkills(server, tool, config, options);
2003
2379
  }
@@ -2023,14 +2399,11 @@ function registerSkills(server, tool, config, options) {
2023
2399
  title: 'List the Edgegap agent skills',
2024
2400
  description: 'List the Edgegap agent skills: tested, step-by-step workflows for getting a multiplayer ' +
2025
2401
  'game online on Edgegap, with templates (Dockerfiles, matchmaker configs, Unity C# and ' +
2026
- 'Unreal C++ drop-ins) and known pitfalls. Before working on a game project, load the ' +
2027
- 'matching skill with edgegap_get_skill: edgegap-ngo for Unity with Netcode for GameObjects, edgegap-fishnet for Unity with FishNet, ' +
2028
- 'edgegap-purrnet for Unity with PurrNet, edgegap-fusion for Unity with Photon Fusion 2, edgegap-unity for other Unity projects, edgegap-unreal for Unreal Engine ' +
2029
- '(edgegap-eos-voice to add voice chat to it), edgegap-fusion-simplefps for the Photon Simple FPS sample, edgegap-godot for Godot 4 with a Godot server, ' +
2030
- 'edgegap-colyseus for a Colyseus server, edgegap-nakama for a game with a Nakama backend, edgegap-playfab for a game that keeps PlayFab Matchmaking, ' +
2031
- 'edgegap-threejs for a Three.js or other browser game with its own Node.js server, ' +
2032
- 'edgegap-manus for a browser game built with Manus, edgegap for any other engine or platform questions; it routes to the rest. ' +
2033
- 'Also says whether a newer skills pack is on GitHub (reads one version number, no Edgegap API call).',
2402
+ 'Unreal C++ drop-ins) and known pitfalls. Each entry says which engine, netcode or backend ' +
2403
+ 'it is for, and the server instructions map projects to skills. Before working on a game ' +
2404
+ 'project, load the matching skill with edgegap_get_skill; "edgegap" covers any other engine ' +
2405
+ 'and routes to the rest. Also says whether a newer skills pack is on GitHub (reads one ' +
2406
+ 'version number, no Edgegap API call).',
2034
2407
  inputSchema: {},
2035
2408
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
2036
2409
  }, async () => {
@@ -2053,13 +2426,9 @@ function registerSkills(server, tool, config, options) {
2053
2426
  tool('edgegap_get_skill', {
2054
2427
  title: 'Load an Edgegap agent skill',
2055
2428
  description: 'Load one Edgegap agent skill: its SKILL.md (the workflow to follow) by default, or one of ' +
2056
- 'its reference documents or templates with file. Load the matching skill before acting on ' +
2057
- 'a game project — edgegap-ngo for Unity with Netcode for GameObjects, edgegap-fishnet for Unity with FishNet, ' +
2058
- 'edgegap-purrnet for Unity with PurrNet, edgegap-fusion for Unity with Photon Fusion 2, edgegap-unity for other Unity projects, edgegap-unreal for Unreal Engine ' +
2059
- '(edgegap-eos-voice for voice chat), edgegap-fusion-simplefps for the Photon Simple FPS sample, edgegap-godot for Godot 4 with a Godot server, ' +
2060
- 'edgegap-colyseus for a Colyseus server, edgegap-nakama for a Nakama backend, edgegap-playfab for PlayFab Matchmaking, ' +
2061
- 'edgegap-threejs for a Three.js/browser game with a Node.js server, ' +
2062
- 'edgegap-manus for a browser game built with Manus, edgegap otherwise — and fetch the references and templates it points to as you reach them. No API call.',
2429
+ 'its reference documents or templates with file. Load the skill that matches the project ' +
2430
+ 'before acting (the server instructions and edgegap_list_skills say which; "edgegap" when ' +
2431
+ 'unsure), then fetch the references and templates it points to as you reach them. No API call.',
2063
2432
  inputSchema: {
2064
2433
  // A string, not an enum: clients cache tool schemas, and a cached enum from an older
2065
2434
  // release would refuse a skill the router already points to. The handler checks the name.
@@ -2074,12 +2443,14 @@ function registerSkills(server, tool, config, options) {
2074
2443
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
2075
2444
  }, async ({ skill: name, file }) => {
2076
2445
  const skill = findSkill(name);
2077
- if (!skill)
2078
- 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
+ }
2079
2450
  const found = findSkillFile(skill, file);
2080
2451
  if (!found) {
2081
- return fail(`"${file}" is not a file in the ${skill.name} skill. Its files are:\n` +
2082
- 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) } });
2083
2454
  }
2084
2455
  const status = found.path === 'SKILL.md' ? servedPackStatus(await latestPack(check), hosted) : undefined;
2085
2456
  const header = `${skill.name} ${skill.version} · ${found.path} · pack ${pack}` +
@@ -2088,7 +2459,10 @@ function registerSkills(server, tool, config, options) {
2088
2459
  const footer = others.length
2089
2460
  ? `\n\n---\nOther files in this skill:\n${others.map((p) => `- ${p}`).join('\n')}\n\n${howToFetch(skill.name)}`
2090
2461
  : '';
2091
- 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
+ };
2092
2466
  });
2093
2467
  tool('edgegap_update_skills', {
2094
2468
  title: 'Check and update the installed Edgegap skills',
@@ -2235,6 +2609,37 @@ function registerSkills(server, tool, config, options) {
2235
2609
  '(in Claude Code, /reload-plugins also works for the plugin) to use the update.';
2236
2610
  return failed ? { ...ok(result), isError: true } : ok(result);
2237
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
+ }));
2238
2643
  for (const skill of SKILLS_PACK.skills) {
2239
2644
  // A prompt per skill: in Claude Code these show up as slash commands.
2240
2645
  server.registerPrompt(skill.name, {
@@ -2259,16 +2664,29 @@ function registerSkills(server, tool, config, options) {
2259
2664
  ],
2260
2665
  };
2261
2666
  });
2262
- // A resource per file.
2263
- for (const f of skill.files) {
2264
- const uri = skillUri(skill.name, f.path);
2265
- server.registerResource(`${skill.name}/${f.path}`, uri, {
2266
- title: f.path === 'SKILL.md' ? `${skill.name} skill` : `${skill.name}: ${f.path}`,
2267
- description: f.path === 'SKILL.md' ? skill.description : undefined,
2268
- mimeType: mimeType(f.path),
2269
- }, async () => ({ contents: [{ uri, mimeType: mimeType(f.path), text: f.content }] }));
2270
- }
2667
+ // Only each skill's SKILL.md is listed: one entry per skill instead of every file
2668
+ // (257 in pack 0.15), which crowded clients' attach menus and resource
2669
+ // lists. The other files are read through the template below.
2670
+ const main = findSkillFile(skill);
2671
+ const uri = skillUri(skill.name, main.path);
2672
+ server.registerResource(`${skill.name}/${main.path}`, uri, { title: `${skill.name} skill`, description: skill.description, mimeType: mimeType(main.path) }, async () => ({ contents: [{ uri, mimeType: mimeType(main.path), text: main.content }] }));
2271
2673
  }
2674
+ // Any file in any skill, e.g. edgegap-skill://edgegap-unreal/assets/docker/Dockerfile.
2675
+ // {+path} keeps the slashes. Not listed (list: undefined): SKILL.md says
2676
+ // which files exist, and edgegap_get_skill lists them too.
2677
+ server.registerResource('edgegap-skill-file', new ResourceTemplate(`${skillUri('{skill}', '').replace(/\/$/, '')}/{+path}`, { list: undefined }), {
2678
+ title: 'Edgegap skill file',
2679
+ description: 'A reference document or template inside an Edgegap skill. SKILL.md lists the files it uses.',
2680
+ }, async (uri, vars) => {
2681
+ const skill = findSkill(String(vars.skill));
2682
+ const file = skill ? findSkillFile(skill, String(vars.path)) : undefined;
2683
+ if (!skill || !file) {
2684
+ throw new Error(skill
2685
+ ? `"${vars.path}" is not a file in the ${skill.name} skill. Its files are: ${skill.files.map((f) => f.path).join(', ')}`
2686
+ : `No skill named "${vars.skill}". The skills are: ${names.join(', ')}.`);
2687
+ }
2688
+ return { contents: [{ uri: uri.href, mimeType: mimeType(file.path), text: file.content }] };
2689
+ });
2272
2690
  }
2273
2691
  /**
2274
2692
  * What edgegap_get_registry_credentials says when Edgegap will not hand the
@@ -2282,11 +2700,142 @@ function registerSkills(server, tool, config, options) {
2282
2700
  * call, and some agents retried it.
2283
2701
  */
2284
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.';
2285
2705
  return {
2286
- content: [{ type: 'text', text: `status: manual_steps_required (no credentials returned)\n\n${steps}` }],
2287
- 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' } },
2288
2709
  };
2289
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.',
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'));
2838
+ }
2290
2839
  function registryCredentialsUnavailable(imageName, tag) {
2291
2840
  const image = imageName ?? '<image-name>';
2292
2841
  const buildTag = tag ?? '<unique-build-tag>';