@edgegap/mcp 0.9.0 → 0.11.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,6 +8,7 @@
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 { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
11
12
  import { EdgegapApiError } from './client.js';
12
13
  import { assertAppAllowed, redact, hostLabel } from './config.js';
13
14
  import { VERSION } from './version.js';
@@ -16,6 +17,7 @@ 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';
19
21
  import { SKILLS_PACK, findSkill, findSkillFile, fileIndex, mimeType, skillUri } from './skills.js';
20
22
  import { SKILL_NAME_RE, compareVersions, latestPack, latestSkillVersions, servedPackStatus, skillsCheckFromEnv, } from './skillsversion.js';
21
23
  /**
@@ -110,8 +112,12 @@ const WS_PROTOCOLS = new Set(['WS', 'WEBSOCKET']);
110
112
  const TLS_PROTOCOLS = new Set(['WS', 'WEBSOCKET', 'HTTP']);
111
113
  const TERMINAL_OK = ['READY', 'STATUS_READY'];
112
114
  const TERMINAL_BAD = ['ERROR', 'STATUS_ERROR', 'TERMINATED', 'STATUS_TERMINATED'];
115
+ /** JSON.stringify replacer: null fields are left out, like undefined ones. The
116
+ * API sends many (fqdn before a deployment is placed, unset error_detail), and
117
+ * an absent field reads the same to an agent at fewer tokens. */
118
+ const dropNulls = (_key, value) => (value === null ? undefined : value);
113
119
  function ok(payload, notice) {
114
- const body = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);
120
+ const body = typeof payload === 'string' ? payload : JSON.stringify(payload, dropNulls, 2);
115
121
  const structured = payload !== null && typeof payload === 'object' && !Array.isArray(payload)
116
122
  ? JSON.parse(body)
117
123
  : undefined;
@@ -159,9 +165,24 @@ const NOT_FOUND = {
159
165
  'before it ran. If it is still running, check the request_id with edgegap_list_deployments.',
160
166
  relay: 'no relay session with that session_id. It may already have been deleted.',
161
167
  };
168
+ /**
169
+ * What a 403 means, per kind of resource. The API's own text is a bare "You
170
+ * are not authorized to access this resource", which reads like a bad token
171
+ * and sends agents to ask for a new one. A rejected token is a 401; a 403 is
172
+ * a token that works but may not use this feature.
173
+ */
174
+ const FORBIDDEN = {
175
+ relay: 'the token is valid, but this organization cannot use relays. Relays are not enabled on ' +
176
+ 'every plan or account; check the Relays page in the dashboard (https://app.edgegap.com) ' +
177
+ 'or ask Edgegap support. A new token will not help. Consider a dedicated server ' +
178
+ '(edgegap_deploy) instead.',
179
+ generic: 'the token is valid, but this organization may not use this feature or resource. It may ' +
180
+ 'not be enabled on the plan, or the resource belongs to another organization. A new token ' +
181
+ 'will not help; check the feature in the dashboard (https://app.edgegap.com) or ask the developer.',
182
+ };
162
183
  /** Wraps a handler so API errors come back as readable, self-correctable text
163
184
  * rather than a protocol-level exception the agent cannot act on. */
164
- function guard(auth, fn, notFound) {
185
+ function guard(auth, fn, notFound, forbidden) {
165
186
  const handled = fn().catch((err) => {
166
187
  if (err instanceof TokenUnavailableError) {
167
188
  // Not a failure to correct — a decision the human made. Say so plainly
@@ -169,7 +190,7 @@ function guard(auth, fn, notFound) {
169
190
  return fail(err.message);
170
191
  }
171
192
  if (err instanceof EdgegapApiError) {
172
- const hint = errorHint(err, notFound);
193
+ const hint = errorHint(err, notFound, forbidden);
173
194
  return fail(`${err.message}${hint ? `\n\nLikely cause: ${hint}` : ''}`);
174
195
  }
175
196
  return fail(redact(err.message ?? String(err), auth.current));
@@ -190,9 +211,9 @@ function guard(auth, fn, notFound) {
190
211
  }
191
212
  /** guard() with the 404 hint first, so it reads at the call site. */
192
213
  function guarded(auth, notFound, fn) {
193
- return guard(auth, fn, notFound);
214
+ return guard(auth, fn, notFound, notFound === NOT_FOUND.relay ? FORBIDDEN.relay : undefined);
194
215
  }
195
- function errorHint(err, notFound) {
216
+ function errorHint(err, notFound, forbidden) {
196
217
  switch (err.status) {
197
218
  case 401:
198
219
  // Deliberately does not promise a re-prompt: the local server asks again
@@ -207,6 +228,8 @@ function errorHint(err, notFound) {
207
228
  // Request ID provided", or a generic "could not understand" for logs),
208
229
  // not 404. Their only input is the request_id, so a 400 means that.
209
230
  return notFound === NOT_FOUND.deployment || notFound === NOT_FOUND.logs ? notFound : undefined;
231
+ case 403:
232
+ return forbidden ?? FORBIDDEN.generic;
210
233
  case 404:
211
234
  // Only the tool knows what was not found; no hint beats a wrong one.
212
235
  return notFound;
@@ -244,6 +267,56 @@ function pageInfo(totalCount, returned, page) {
244
267
  };
245
268
  }
246
269
  /** Trims a deployment status down to what an agent needs to act. */
270
+ /** The last `cap` characters of a deployment's container logs, or undefined
271
+ * if there are none or they cannot be read. Never throws. */
272
+ async function logTail(client, requestId, cap) {
273
+ try {
274
+ const res = await client.getDeploymentLogs(requestId);
275
+ const text = [res.logs, res.crash_logs].filter(Boolean).join('\n');
276
+ if (!text.trim())
277
+ return undefined;
278
+ return text.length > cap ? `...[truncated]...\n${text.slice(-cap)}` : text;
279
+ }
280
+ catch {
281
+ return undefined;
282
+ }
283
+ }
284
+ /**
285
+ * Stop is idempotent: stopping a deployment that has already stopped, or that
286
+ * Edgegap no longer knows, leaves nothing running, which is what was asked.
287
+ * Returns the success payload in that case, or undefined to report the error.
288
+ * An unknown request_id cannot be told apart from a cleaned-up one (both are a
289
+ * 400 or 404), so the result says so instead of claiming it was stopped.
290
+ */
291
+ async function alreadyStopped(client, requestId, err) {
292
+ if (!(err instanceof EdgegapApiError) || ![400, 404, 409, 410].includes(err.status))
293
+ return undefined;
294
+ let status;
295
+ try {
296
+ status = await client.getDeployment(requestId);
297
+ }
298
+ catch (statusErr) {
299
+ if (statusErr instanceof EdgegapApiError && [400, 404].includes(statusErr.status)) {
300
+ return {
301
+ request_id: requestId,
302
+ result: 'not_running',
303
+ note: 'Edgegap has no running deployment with this request_id: it already stopped and was ' +
304
+ 'cleaned up, or the request_id is wrong. Nothing is left to stop. If you expected it ' +
305
+ 'to be running, check edgegap_list_deployments.',
306
+ };
307
+ }
308
+ return undefined;
309
+ }
310
+ const current = (status.current_status ?? '').toUpperCase();
311
+ if (status.running && !current.includes('TERMINAT'))
312
+ return undefined;
313
+ return {
314
+ request_id: requestId,
315
+ result: 'already_stopped',
316
+ status: status.current_status,
317
+ note: 'This deployment was already stopped or stopping. Nothing more to do.',
318
+ };
319
+ }
247
320
  function compactDeployment(d) {
248
321
  const ports = Object.entries(d.ports ?? {}).map(([key, p]) => ({
249
322
  name: p.name ?? key,
@@ -430,6 +503,41 @@ function autoStop(maxDuration) {
430
503
  : {}),
431
504
  };
432
505
  }
506
+ /**
507
+ * Rewrites the SDK's "Input validation error: Invalid arguments for tool X:
508
+ * a: Invalid input: expected string, received undefined, b: ..." into one line
509
+ * per argument, plus the tool's required and optional parameters, so the agent
510
+ * can fix the call in one try. Undefined for any other message.
511
+ */
512
+ export function argumentError(message, inputs) {
513
+ const m = message.match(/Input validation error: Invalid arguments for tool (\S+?): ([\s\S]*)$/);
514
+ if (!m)
515
+ return undefined;
516
+ const [, toolName, detail] = m;
517
+ // Two wordings: SDK v1 (local) "expected string, received number at application",
518
+ // one per line; SDK v2 (hosted) "application: expected string, received number",
519
+ // comma-joined.
520
+ const problems = detail
521
+ .split('\n')
522
+ .flatMap((line) => line.split(/,\s+(?=[\w.[\]]+: )/))
523
+ .map((p) => p.trim())
524
+ .filter(Boolean)
525
+ .map((p) => {
526
+ const v2 = p.match(/^([\w.[\]]+): (?:Invalid input: )?expected (\w+), received (\w+)$/);
527
+ const v1 = p.match(/^(?:Invalid input: )?expected (\w+), received (\w+) at ([\w.[\]]+)$/);
528
+ const [field, want, got] = v2 ? [v2[1], v2[2], v2[3]] : v1 ? [v1[3], v1[1], v1[2]] : [];
529
+ if (!field)
530
+ return `- ${p}`;
531
+ return got === 'undefined' ? `- ${field}: missing (required)` : `- ${field}: must be ${want} (got ${got})`;
532
+ });
533
+ const shape = inputs.get(toolName) ?? {};
534
+ const required = Object.keys(shape).filter((k) => !shape[k].safeParse(undefined).success);
535
+ const optional = Object.keys(shape).filter((k) => !required.includes(k));
536
+ return (`Invalid arguments for ${toolName}. Nothing was sent.\n${problems.join('\n')}\n\n` +
537
+ `Required: ${required.join(', ') || 'none'}.` +
538
+ (optional.length ? ` Optional: ${optional.join(', ')}.` : '') +
539
+ ' Fix the arguments and call again.');
540
+ }
433
541
  /** Prepends "[api.edgegap.com]" (or "[custom · host]") to a tool result. */
434
542
  function withHost(result, label) {
435
543
  return { ...result, content: [{ type: 'text', text: `[${label}]` }, ...result.content] };
@@ -440,7 +548,23 @@ export function registerTools(server, client, config, auth, options = {}) {
440
548
  // at a custom EDGEGAP_BASE_URL can never be mistaken for production.
441
549
  const label = hostLabel(config);
442
550
  // ...and never carries the API token, whatever the API echoed back.
443
- const tool = ((name, def, cb) => server.registerTool(name, def, (async (...a) => withHost(scrubToken(await cb(...a), auth.current), label))));
551
+ const inputs = new Map();
552
+ const tool = ((name, def, cb) => {
553
+ inputs.set(name, (def.inputSchema) ?? {});
554
+ return server.registerTool(name, def, (async (...a) => withHost(scrubToken(await cb(...a), auth.current), label)));
555
+ });
556
+ // Errors the SDK raises itself (bad arguments, a handler that throws) skip
557
+ // the wrapper above. Both SDK versions route them through createToolError,
558
+ // so give those the same host label and token scrub, and turn argument
559
+ // errors into a list the agent can act on.
560
+ const sdk = server;
561
+ const sdkToolError = sdk.createToolError?.bind(server);
562
+ if (sdkToolError) {
563
+ sdk.createToolError = (message) => {
564
+ const friendly = argumentError(message, inputs);
565
+ return withHost(scrubToken(friendly ? fail(friendly) : sdkToolError(message), auth.current), label);
566
+ };
567
+ }
444
568
  // ---------------------------------------------------------------- 0 ----
445
569
  // No token, no network: describes this server's own configuration, so an
446
570
  // agent can check where it is pointed and what is allowed before acting.
@@ -452,6 +576,7 @@ export function registerTools(server, client, config, auth, options = {}) {
452
576
  'dry_run. Call it first when unsure what this session is allowed to do, or before ' +
453
577
  'anything billable. Makes no API call and never shows the token.',
454
578
  inputSchema: {},
579
+ outputSchema: OUTPUT.context,
455
580
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
456
581
  }, async () => {
457
582
  const hosted = config.transport === 'hosted';
@@ -503,6 +628,7 @@ export function registerTools(server, client, config, auth, options = {}) {
503
628
  limit: z.number().int().min(1).max(100).optional().describe('Results per page. Default 50.'),
504
629
  page: z.number().int().min(1).optional(),
505
630
  },
631
+ outputSchema: OUTPUT.listApps,
506
632
  annotations: { readOnlyHint: true, openWorldHint: true },
507
633
  }, async ({ limit, page }) => guard(auth, async () => {
508
634
  const res = await client.listApps({ limit: limit ?? 50, page });
@@ -582,6 +708,7 @@ export function registerTools(server, client, config, auth, options = {}) {
582
708
  inputSchema: {
583
709
  application: z.string().describe('Application name, as returned by edgegap_list_apps.'),
584
710
  },
711
+ outputSchema: OUTPUT.listAppVersions,
585
712
  annotations: { readOnlyHint: true, openWorldHint: true },
586
713
  }, async ({ application }) =>
587
714
  // Read-only, so not subject to EDGEGAP_APP_ALLOWLIST: the allowlist
@@ -602,6 +729,7 @@ export function registerTools(server, client, config, auth, options = {}) {
602
729
  application: z.string().describe('Application name.'),
603
730
  version: z.string().describe('Version name, as listed by edgegap_list_app_versions.'),
604
731
  },
732
+ outputSchema: OUTPUT.getAppVersion,
605
733
  annotations: { readOnlyHint: true, openWorldHint: true },
606
734
  }, async ({ application, version }) => guarded(auth, NOT_FOUND.app, async () => {
607
735
  const v = await client.getAppVersion(application, version);
@@ -788,8 +916,10 @@ export function registerTools(server, client, config, auth, options = {}) {
788
916
  'the shutdown grace period. Only the fields you pass change. Deployments already running ' +
789
917
  'keep their old settings; new deployments get the new ones. Same refusals as ' +
790
918
  'edgegap_create_app_version: "latest" or empty tags, a docker_image holding a host or ' +
791
- 'tag, and the API token in the registry login. Resources, ports and env vars cannot be ' +
792
- 'changed here; create a new version for those.',
919
+ 'tag, and the API token in the registry login or env vars. ports and env REPLACE the ' +
920
+ '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 ' +
922
+ 'new version, or override them per deployment in edgegap_deploy.',
793
923
  inputSchema: {
794
924
  application: z.string().describe('Application name.'),
795
925
  version: z.string().describe('Version name to change.'),
@@ -813,6 +943,21 @@ export function registerTools(server, client, config, auth, options = {}) {
813
943
  .max(3600)
814
944
  .optional()
815
945
  .describe('Seconds between SIGTERM and SIGKILL when a deployment stops.'),
946
+ ports: z
947
+ .array(z.object({
948
+ port: z.number().int().min(1).max(59999).describe('Port the server listens on.'),
949
+ protocol: z.string().describe(`One of ${PROTOCOLS.join(', ')}. Most game servers use UDP.`),
950
+ name: z.string().optional().describe('Label, e.g. "gameport".'),
951
+ to_check: z.boolean().optional().describe('Readiness check on this port. Default true.'),
952
+ tls_upgrade: z.boolean().optional().describe('wss:// / https:// for browser clients. WS and HTTP ports only.'),
953
+ }))
954
+ .min(1)
955
+ .optional()
956
+ .describe('REPLACES every port on the version. Include the ports to keep, not only new ones.'),
957
+ env: z
958
+ .array(z.object({ key: z.string(), value: z.string() }))
959
+ .optional()
960
+ .describe('REPLACES every env var on the version; [] removes them all. Values are never echoed back.'),
816
961
  dry_run: dryRunParam,
817
962
  },
818
963
  annotations: { destructiveHint: false, idempotentHint: true, openWorldHint: true },
@@ -821,9 +966,18 @@ export function registerTools(server, client, config, auth, options = {}) {
821
966
  const leak = await tokenLeak(auth, args.dry_run, [
822
967
  ['registry_username', args.registry_username],
823
968
  ['registry_token', args.registry_token],
969
+ ...(args.env ?? []).flatMap((e) => [
970
+ [`env var name "${e.key.slice(0, 40)}"`, e.key],
971
+ [`the value of env var "${e.key.slice(0, 40)}"`, e.value],
972
+ ]),
824
973
  ]);
825
974
  if (leak)
826
975
  return leak;
976
+ const badTls = args.ports?.find((p) => p.tls_upgrade && !TLS_PROTOCOLS.has(p.protocol.toUpperCase()));
977
+ if (badTls) {
978
+ return fail(`Port ${badTls.port} is ${badTls.protocol}; tls_upgrade only works on WS and HTTP ports. ` +
979
+ 'Use protocol "WS" for a WebSocket server, or drop tls_upgrade.');
980
+ }
827
981
  if (args.docker_tag !== undefined) {
828
982
  const tagProblem = badTag(args.docker_tag);
829
983
  if (tagProblem)
@@ -848,6 +1002,14 @@ export function registerTools(server, client, config, auth, options = {}) {
848
1002
  force_cache: args.force_cache,
849
1003
  verify_image: args.verify_image,
850
1004
  termination_grace_period_seconds: args.termination_grace_period_seconds,
1005
+ ports: args.ports?.map((p) => ({
1006
+ port: p.port,
1007
+ protocol: p.protocol,
1008
+ name: p.name ?? 'gameport',
1009
+ to_check: p.to_check ?? true,
1010
+ tls_upgrade: p.tls_upgrade ?? false,
1011
+ })),
1012
+ envs: args.env?.map((e) => ({ key: e.key, value: e.value, is_hidden: looksSecret(e.key) })),
851
1013
  };
852
1014
  for (const k of Object.keys(body))
853
1015
  if (body[k] === undefined)
@@ -858,6 +1020,10 @@ export function registerTools(server, client, config, auth, options = {}) {
858
1020
  const notes = capped !== undefined && capped < (args.max_duration_minutes ?? 0)
859
1021
  ? [`max_duration capped to ${capped} minutes by EDGEGAP_MAX_DURATION_MINUTES.`]
860
1022
  : [];
1023
+ if (args.ports)
1024
+ notes.push(`ports replaced: the version now has exactly these ${args.ports.length}.`);
1025
+ if (args.env)
1026
+ notes.push(`env replaced: the version now has exactly these ${args.env.length} variables.`);
861
1027
  if (args.dry_run) {
862
1028
  const dry = client.dryRun();
863
1029
  await dry.client.updateAppVersion(args.application, args.version, body);
@@ -886,6 +1052,7 @@ export function registerTools(server, client, config, auth, options = {}) {
886
1052
  page: z.number().int().min(1).optional(),
887
1053
  limit: z.number().int().min(1).max(200).optional().describe('Default 100.'),
888
1054
  },
1055
+ outputSchema: OUTPUT.listLocations,
889
1056
  annotations: { readOnlyHint: true, openWorldHint: true },
890
1057
  }, async ({ application, version, page, limit }) => guarded(auth, NOT_FOUND.app, async () => {
891
1058
  if ((application === undefined) !== (version === undefined)) {
@@ -916,6 +1083,7 @@ export function registerTools(server, client, config, auth, options = {}) {
916
1083
  page: z.number().int().min(1).optional(),
917
1084
  limit: z.number().int().min(1).max(200).optional().describe('Default 100.'),
918
1085
  },
1086
+ outputSchema: OUTPUT.listPingBeacons,
919
1087
  annotations: { readOnlyHint: true, openWorldHint: true },
920
1088
  }, async ({ page, limit }) => guard(auth, async () => {
921
1089
  const res = await client.listBeacons({ page, limit: limit ?? 100 });
@@ -961,10 +1129,16 @@ export function registerTools(server, client, config, auth, options = {}) {
961
1129
  .int()
962
1130
  .min(256)
963
1131
  .optional()
964
- .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.'),
965
- memory_mb: z.number().int().min(256).optional().describe('Override the version memory (with cpu_units). Same caveat as cpu_units.'),
1132
+ .describe('Override the version\'s CPU for this deployment only, with memory_mb. 1024 = 1 vCPU.'),
1133
+ memory_mb: z
1134
+ .number()
1135
+ .int()
1136
+ .min(256)
1137
+ .optional()
1138
+ .describe('Override the version\'s memory for this deployment only, with cpu_units. At most 2x cpu_units.'),
966
1139
  dry_run: dryRunParam,
967
1140
  },
1141
+ outputSchema: OUTPUT.deploy,
968
1142
  annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: true },
969
1143
  }, async (args) => guarded(auth, NOT_FOUND.app, async () => {
970
1144
  assertAppAllowed(config, args.application);
@@ -998,7 +1172,15 @@ export function registerTools(server, client, config, auth, options = {}) {
998
1172
  is_hidden: looksSecret(e.key),
999
1173
  }));
1000
1174
  }
1001
- if (args.cpu_units && args.memory_mb) {
1175
+ // The v2 API takes both or neither (DeploymentV2.resources).
1176
+ if ((args.cpu_units === undefined) !== (args.memory_mb === undefined)) {
1177
+ return fail('Pass both cpu_units and memory_mb to override the version\'s resources, or neither to use the version\'s.');
1178
+ }
1179
+ if (args.cpu_units !== undefined && args.memory_mb !== undefined) {
1180
+ if (args.memory_mb > args.cpu_units * 2) {
1181
+ return fail(`memory_mb (${args.memory_mb}) exceeds twice cpu_units (${args.cpu_units}). Edgegap rejects this. ` +
1182
+ `Lower memory_mb to ${args.cpu_units * 2} or raise cpu_units.`);
1183
+ }
1002
1184
  body.resources = { cpu_units: args.cpu_units, memory_mib: args.memory_mb };
1003
1185
  }
1004
1186
  if (args.dry_run) {
@@ -1039,13 +1221,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1039
1221
  status: 'starting',
1040
1222
  tags,
1041
1223
  ...autoStop(version.max_duration),
1042
- // "resources" is not in the published v2 deploy schema
1043
- // (test/spec.mjs). Say so rather than promise the override.
1044
- resources_note: body.resources
1045
- ? 'cpu_units/memory_mb were sent, but the published v2 API does not document a per-deployment ' +
1046
- 'override, so the deployment may run with the version\'s size. For a different size, create a ' +
1047
- 'version with it.'
1048
- : undefined,
1224
+ resources: body.resources,
1049
1225
  next_step: `Call edgegap_wait_for_deployment with request_id ${res.request_id}.`,
1050
1226
  });
1051
1227
  }));
@@ -1059,6 +1235,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1059
1235
  inputSchema: {
1060
1236
  request_id: z.string().describe('The request_id returned by edgegap_deploy.'),
1061
1237
  },
1238
+ outputSchema: OUTPUT.deployment,
1062
1239
  annotations: { readOnlyHint: true, openWorldHint: true },
1063
1240
  }, async ({ request_id }) => guarded(auth, NOT_FOUND.deployment, async () => {
1064
1241
  const d = await client.getDeployment(request_id);
@@ -1081,6 +1258,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1081
1258
  .optional()
1082
1259
  .describe('How long to wait before giving up. Default 180.'),
1083
1260
  },
1261
+ outputSchema: OUTPUT.waitForDeployment,
1084
1262
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
1085
1263
  }, async ({ request_id, timeout_seconds }) => guarded(auth, NOT_FOUND.deployment, async () => {
1086
1264
  const budgetMs = (timeout_seconds ?? 180) * 1000;
@@ -1091,10 +1269,16 @@ export function registerTools(server, client, config, auth, options = {}) {
1091
1269
  last = await client.getDeployment(request_id);
1092
1270
  const status = (last.current_status ?? '').toUpperCase();
1093
1271
  if (last.error || TERMINAL_BAD.some((s) => status.includes(s))) {
1272
+ // Fetched now, not left to the agent: a failed deployment is
1273
+ // cleaned up quickly and its logs go with it, so a separate
1274
+ // edgegap_get_deployment_logs call often finds nothing.
1275
+ const logs = await logTail(client, request_id, 3000);
1094
1276
  return fail(`Deployment ${request_id} failed with status ${last.current_status}.\n` +
1095
1277
  `${last.error_detail ?? 'No error detail returned.'}\n\n` +
1096
- `Call edgegap_get_deployment_logs for container output, then fix the image or ` +
1097
- `port configuration before redeploying.`);
1278
+ (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.`));
1098
1282
  }
1099
1283
  if (last.running || TERMINAL_OK.some((s) => status.includes(s))) {
1100
1284
  return ok({
@@ -1105,9 +1289,15 @@ export function registerTools(server, client, config, auth, options = {}) {
1105
1289
  await new Promise((r) => setTimeout(r, intervalMs));
1106
1290
  intervalMs = Math.min(intervalMs * 1.5, 10_000);
1107
1291
  }
1108
- return fail(`Deployment ${request_id} did not become ready within ${timeout_seconds ?? 180}s. ` +
1109
- `Last status: ${last?.current_status ?? 'unknown'}. It may still be starting — ` +
1110
- `call edgegap_get_deployment to check again, or edgegap_stop_deployment to clean up.`);
1292
+ // Not an error: the wait ran out, the deployment did not fail. It is
1293
+ // usually still starting (large images pull slowly on a cold host).
1294
+ return ok({
1295
+ ...(last ? compactDeployment(last) : { request_id }),
1296
+ ready: false,
1297
+ 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
+ });
1111
1301
  }));
1112
1302
  // ---------------------------------------------------------------- 8 ----
1113
1303
  tool('edgegap_list_deployments', {
@@ -1149,6 +1339,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1149
1339
  .describe('e.g. [{field:"created_at",order:"asc"}] for oldest first.'),
1150
1340
  limit: z.number().int().min(1).max(100).optional().describe('Default 50.'),
1151
1341
  },
1342
+ outputSchema: OUTPUT.listDeployments,
1152
1343
  annotations: { readOnlyHint: true, openWorldHint: true },
1153
1344
  }, async ({ only_agent_deployments, filters: given, order_by, limit }) => guard(auth, async () => {
1154
1345
  let filters = given;
@@ -1198,7 +1389,16 @@ export function registerTools(server, client, config, auth, options = {}) {
1198
1389
  await dry.client.stopDeployment(request_id);
1199
1390
  return dryRunResult(dry.requests);
1200
1391
  }
1201
- const res = await client.stopDeployment(request_id);
1392
+ let res;
1393
+ try {
1394
+ res = await client.stopDeployment(request_id);
1395
+ }
1396
+ catch (err) {
1397
+ const gone = await alreadyStopped(client, request_id, err);
1398
+ if (gone)
1399
+ return ok(gone);
1400
+ throw err;
1401
+ }
1202
1402
  return ok({ request_id, result: res.message ?? 'stop requested' });
1203
1403
  }));
1204
1404
  }
@@ -1247,6 +1447,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1247
1447
  end_time: z.string().optional().describe('ISO 8601. Default: now, or when it stopped.'),
1248
1448
  step: z.string().optional().describe('Averaging step, e.g. "30s" or "5m". Default: the API\'s.'),
1249
1449
  },
1450
+ outputSchema: OUTPUT.metrics,
1250
1451
  annotations: { readOnlyHint: true, openWorldHint: true },
1251
1452
  }, async ({ request_id, start_time, end_time, step }) => guarded(auth, NOT_FOUND.deployment, async () => {
1252
1453
  const bad = checkRequestId(request_id);
@@ -1399,6 +1600,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1399
1600
  docker_image: z.string().optional(),
1400
1601
  docker_tag: z.string().optional(),
1401
1602
  },
1603
+ outputSchema: OUTPUT.validateServerConfig,
1402
1604
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
1403
1605
  }, async (args) => {
1404
1606
  const { engine, errors, warnings } = validateServerConfig(args);
@@ -1465,7 +1667,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1465
1667
  // missing registry, so it must not trigger provisioning (which only
1466
1668
  // fails with a second, more confusing 403). Only a 404 — a
1467
1669
  // quick-start token whose project is not provisioned yet — does.
1468
- const unavailable = () => fail(registryCredentialsUnavailable(image_name, tag));
1670
+ const unavailable = () => manualStepsResult(registryCredentialsUnavailable(image_name, tag));
1469
1671
  let creds;
1470
1672
  try {
1471
1673
  creds = await client.getRegistryCredentials();
@@ -1533,6 +1735,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1533
1735
  page: z.number().int().min(1).optional(),
1534
1736
  limit: z.number().int().min(1).max(100).optional().describe('Default 20.'),
1535
1737
  },
1738
+ outputSchema: OUTPUT.listRegistryTags,
1536
1739
  annotations: { readOnlyHint: true, openWorldHint: true },
1537
1740
  }, async ({ image_name, page, limit }) => guard(auth, async () => {
1538
1741
  // Agents often pass the full reference they pushed. Reduce it to what
@@ -1705,7 +1908,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1705
1908
  `(status ${last.status ?? 'unknown'}). Call edgegap_get_relay_session to check again.`);
1706
1909
  }
1707
1910
  return ok({ ...compactRelay(last), waited_seconds: Math.round((Date.now() - startedAt) / 1000) });
1708
- }));
1911
+ }, undefined, FORBIDDEN.relay));
1709
1912
  }
1710
1913
  // --------------------------------------------------------------- 15 ----
1711
1914
  tool('edgegap_get_relay_session', {
@@ -1724,6 +1927,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1724
1927
  'and delete them with edgegap_delete_relay_session. Authorization tokens are not listed; ' +
1725
1928
  'read one session with edgegap_get_relay_session.',
1726
1929
  inputSchema: {},
1930
+ outputSchema: OUTPUT.listRelaySessions,
1727
1931
  annotations: { readOnlyHint: true, openWorldHint: true },
1728
1932
  }, async () => guard(auth, async () => {
1729
1933
  const res = await client.listRelaySessions();
@@ -1737,7 +1941,7 @@ export function registerTools(server, client, config, auth, options = {}) {
1737
1941
  error: r.error || undefined,
1738
1942
  }));
1739
1943
  return ok({ ...pageInfo(res.total_count, sessions.length, 1), sessions });
1740
- }));
1944
+ }, undefined, FORBIDDEN.relay));
1741
1945
  if (mutating) {
1742
1946
  // ------------------------------------------------------------- 16 ----
1743
1947
  tool('edgegap_authorize_relay_user', {
@@ -1935,14 +2139,11 @@ function registerSkills(server, tool, config, options) {
1935
2139
  title: 'List the Edgegap agent skills',
1936
2140
  description: 'List the Edgegap agent skills: tested, step-by-step workflows for getting a multiplayer ' +
1937
2141
  'game online on Edgegap, with templates (Dockerfiles, matchmaker configs, Unity C# and ' +
1938
- 'Unreal C++ drop-ins) and known pitfalls. Before working on a game project, load the ' +
1939
- 'matching skill with edgegap_get_skill: edgegap-ngo for Unity with Netcode for GameObjects, edgegap-fishnet for Unity with FishNet, ' +
1940
- '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 ' +
1941
- '(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, ' +
1942
- 'edgegap-colyseus for a Colyseus server, edgegap-nakama for a game with a Nakama backend, edgegap-playfab for a game that keeps PlayFab Matchmaking, ' +
1943
- 'edgegap-threejs for a Three.js or other browser game with its own Node.js server, ' +
1944
- 'edgegap-manus for a browser game built with Manus, edgegap for any other engine or platform questions; it routes to the rest. ' +
1945
- 'Also says whether a newer skills pack is on GitHub (reads one version number, no Edgegap API call).',
2142
+ 'Unreal C++ drop-ins) and known pitfalls. Each entry says which engine, netcode or backend ' +
2143
+ 'it is for, and the server instructions map projects to skills. Before working on a game ' +
2144
+ 'project, load the matching skill with edgegap_get_skill; "edgegap" covers any other engine ' +
2145
+ 'and routes to the rest. Also says whether a newer skills pack is on GitHub (reads one ' +
2146
+ 'version number, no Edgegap API call).',
1946
2147
  inputSchema: {},
1947
2148
  annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
1948
2149
  }, async () => {
@@ -1965,13 +2166,9 @@ function registerSkills(server, tool, config, options) {
1965
2166
  tool('edgegap_get_skill', {
1966
2167
  title: 'Load an Edgegap agent skill',
1967
2168
  description: 'Load one Edgegap agent skill: its SKILL.md (the workflow to follow) by default, or one of ' +
1968
- 'its reference documents or templates with file. Load the matching skill before acting on ' +
1969
- 'a game project — edgegap-ngo for Unity with Netcode for GameObjects, edgegap-fishnet for Unity with FishNet, ' +
1970
- '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 ' +
1971
- '(edgegap-eos-voice for voice chat), edgegap-fusion-simplefps for the Photon Simple FPS sample, edgegap-godot for Godot 4 with a Godot server, ' +
1972
- 'edgegap-colyseus for a Colyseus server, edgegap-nakama for a Nakama backend, edgegap-playfab for PlayFab Matchmaking, ' +
1973
- 'edgegap-threejs for a Three.js/browser game with a Node.js server, ' +
1974
- '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.',
2169
+ 'its reference documents or templates with file. Load the skill that matches the project ' +
2170
+ 'before acting (the server instructions and edgegap_list_skills say which; "edgegap" when ' +
2171
+ 'unsure), then fetch the references and templates it points to as you reach them. No API call.',
1975
2172
  inputSchema: {
1976
2173
  // A string, not an enum: clients cache tool schemas, and a cached enum from an older
1977
2174
  // release would refuse a skill the router already points to. The handler checks the name.
@@ -2171,22 +2368,47 @@ function registerSkills(server, tool, config, options) {
2171
2368
  ],
2172
2369
  };
2173
2370
  });
2174
- // A resource per file.
2175
- for (const f of skill.files) {
2176
- const uri = skillUri(skill.name, f.path);
2177
- server.registerResource(`${skill.name}/${f.path}`, uri, {
2178
- title: f.path === 'SKILL.md' ? `${skill.name} skill` : `${skill.name}: ${f.path}`,
2179
- description: f.path === 'SKILL.md' ? skill.description : undefined,
2180
- mimeType: mimeType(f.path),
2181
- }, async () => ({ contents: [{ uri, mimeType: mimeType(f.path), text: f.content }] }));
2182
- }
2371
+ // Only each skill's SKILL.md is listed: 21 entries instead of every file
2372
+ // (257 in pack 0.15), which crowded clients' attach menus and resource
2373
+ // lists. The other files are read through the template below.
2374
+ const main = findSkillFile(skill);
2375
+ const uri = skillUri(skill.name, main.path);
2376
+ 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 }] }));
2183
2377
  }
2378
+ // Any file in any skill, e.g. edgegap-skill://edgegap-unreal/assets/docker/Dockerfile.
2379
+ // {+path} keeps the slashes. Not listed (list: undefined): SKILL.md says
2380
+ // which files exist, and edgegap_get_skill lists them too.
2381
+ server.registerResource('edgegap-skill-file', new ResourceTemplate(`${skillUri('{skill}', '').replace(/\/$/, '')}/{+path}`, { list: undefined }), {
2382
+ title: 'Edgegap skill file',
2383
+ description: 'A reference document or template inside an Edgegap skill. SKILL.md lists the files it uses.',
2384
+ }, async (uri, vars) => {
2385
+ const skill = findSkill(String(vars.skill));
2386
+ const file = skill ? findSkillFile(skill, String(vars.path)) : undefined;
2387
+ if (!skill || !file) {
2388
+ throw new Error(skill
2389
+ ? `"${vars.path}" is not a file in the ${skill.name} skill. Its files are: ${skill.files.map((f) => f.path).join(', ')}`
2390
+ : `No skill named "${vars.skill}". The skills are: ${names.join(', ')}.`);
2391
+ }
2392
+ return { contents: [{ uri: uri.href, mimeType: mimeType(file.path), text: file.content }] };
2393
+ });
2184
2394
  }
2185
2395
  /**
2186
2396
  * What edgegap_get_registry_credentials says when Edgegap will not hand the
2187
2397
  * registry login to this token. Written as the manual path that works today,
2188
2398
  * so the agent asks the developer instead of retrying or guessing.
2189
2399
  */
2400
+ /**
2401
+ * The registry tool's answer for a regular API token. Not an error: the tool
2402
+ * did what it can for that token type, and the steps are the next action.
2403
+ * Reported as a failure it counted every regular-token developer as a broken
2404
+ * call, and some agents retried it.
2405
+ */
2406
+ function manualStepsResult(steps) {
2407
+ 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 },
2410
+ };
2411
+ }
2190
2412
  function registryCredentialsUnavailable(imageName, tag) {
2191
2413
  const image = imageName ?? '<image-name>';
2192
2414
  const buildTag = tag ?? '<unique-build-tag>';
package/dist/version.js CHANGED
@@ -3,4 +3,4 @@
3
3
  * call, and by edgegap_context. Keep in step with package.json and server.json;
4
4
  * test/package.mjs fails the build when they disagree.
5
5
  */
6
- export const VERSION = '0.9.0';
6
+ export const VERSION = '0.11.0';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@edgegap/mcp",
3
3
  "mcpName": "dev.edgegap/mcp",
4
- "version": "0.9.0",
4
+ "version": "0.11.0",
5
5
  "description": "Check, push, and deploy game servers on Edgegap from your coding agent, with relays for P2P games. Runs locally; your API token never leaves your machine.",
6
6
  "scripts": {
7
7
  "prebuild": "rm -rf dist",
@@ -34,15 +34,15 @@
34
34
  "license": "Apache-2.0",
35
35
  "repository": {
36
36
  "type": "git",
37
- "url": "git+https://github.com/edgegap/edgegap-mcp.git"
37
+ "url": "git+https://github.com/edgegap/llm-mcp-server.git"
38
38
  },
39
- "homepage": "https://github.com/edgegap/edgegap-mcp#readme",
39
+ "homepage": "https://github.com/edgegap/llm-mcp-server#readme",
40
40
  "bugs": {
41
- "url": "https://github.com/edgegap/edgegap-mcp/issues"
41
+ "url": "https://github.com/edgegap/llm-mcp-server/issues"
42
42
  },
43
43
  "dependencies": {
44
44
  "@modelcontextprotocol/sdk": "^1.32.1",
45
- "zod": "^4.6.2"
45
+ "zod": "^4.6.7"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@cloudflare/workers-types": "^5.20260911.1",