@agledger/mcp-server 3.1.0 → 3.2.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/server.js CHANGED
@@ -1,22 +1,18 @@
1
- // `zod/v4`, not `zod`. The MCP SDK declares zod as a non-optional peer across
2
- // `^3.25 || ^4.0` and imports the version-specific subpaths, so it runs on
3
- // whichever major the host tree holds. Importing bare `zod` pinned us to v4 and
4
- // forced npm to nest a second copy whenever a host held zod 3 -- and two copies
5
- // of zod means two registries. `.describe()` and `.meta()` write into the
6
- // registry rather than onto the schema, so the SDK rendered our tools against a
7
- // registry that had never seen them: every argument description gone, and the
8
- // type of every JSON-string argument with it. Nothing threw.
9
- //
10
- // zod 3.25 ships the v4 implementation under this subpath, so one import works
11
- // on both majors and lets npm resolve a single shared copy. Matching the SDK's
12
- // dependency range is what makes the dedupe possible; see `zod-integrity.ts`
13
- // for the check that catches a tree which splits them anyway.
1
+ // `zod/v4`, the version-specific subpath, rather than bare `zod`. This package
2
+ // declares the same zod range `@modelcontextprotocol/server` does (^4.2.0), which
3
+ // is what lets npm install one shared copy. Two copies of zod mean two
4
+ // registries: `.describe()` and `.meta()` write into the registry rather than
5
+ // onto the schema, so the MCP library would render our tools against a registry
6
+ // that had never seen them, dropping every argument description and the type of
7
+ // every JSON-string argument. Nothing throws. `zod-integrity.ts` warns when a
8
+ // tree splits them anyway.
14
9
  import { z } from 'zod/v4';
15
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
10
+ import { McpServer } from '@modelcontextprotocol/server';
16
11
  import { assertNotPinnedAndDistrusted, parseDistrustedKeys, parseTrustAnchors, suggestion, verifyAuditExport, } from '@agledger/verify-core';
17
- import { ApiClient } from './api-client.js';
18
- import { OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './credentials.js';
12
+ import { ApiClient, QueryShapeError } from './api-client.js';
13
+ import { AgentKeysFileError, OidcCertCredential, OidcExchangeError, OidcTokenSourceError, } from './credentials.js';
19
14
  import { DelegationSource, DelegationSourceError } from './delegation.js';
15
+ import { describeError, fetchCause } from './errors.js';
20
16
  import { SERVER_VERSION } from './version.js';
21
17
  export { SERVER_VERSION };
22
18
  const QUICKSTART = {
@@ -37,10 +33,8 @@ const DOCS = {
37
33
  'Read llms.txt first if you are new to this API; read OpenAPI when you need exact routes.',
38
34
  openapi: '/openapi.json',
39
35
  openapiResource: 'agledger://openapi',
40
- // The API's agent-oriented narrative. An MCP-connected agent never learned
41
- // this existed: discover named only OpenAPI and resources/list offered only
42
- // the spec, so the one integration surface built for agents hid the API's
43
- // agent-facing documentation.
36
+ // The API's agent-oriented narrative, advertised by discover and offered
37
+ // through resources/list beside the OpenAPI spec.
44
38
  narrative: '/llms.txt',
45
39
  narrativeResource: 'agledger://llms.txt',
46
40
  };
@@ -50,9 +44,9 @@ function mirrorContent(structured) {
50
44
  return [{ type: 'text', text: JSON.stringify(structured) }];
51
45
  }
52
46
  /**
53
- * Structured error for CLI-origin failures (network, timeout, malformed input).
54
- * API-origin errors are forwarded verbatim without enrichment; if the API
55
- * returns a suggestion, agents see it; if not, that's an API concern to fix upstream.
47
+ * Structured error for failures raised by this server (network, timeout, malformed input).
48
+ * API-origin errors are forwarded verbatim without enrichment: a suggestion
49
+ * the API returns reaches the agent as sent, and none is added when it returns none.
56
50
  */
57
51
  function errorResult(message, code, suggestion, extra) {
58
52
  const structuredContent = { error: true, message };
@@ -68,12 +62,67 @@ function errorResult(message, code, suggestion, extra) {
68
62
  isError: true,
69
63
  };
70
64
  }
65
+ /** Cause codes that mean the Server's certificate was not accepted. */
66
+ const TLS_CAUSE = /^(CERT_|UNABLE_TO_|DEPTH_ZERO_|SELF_SIGNED_|ERR_TLS_|ERR_SSL_|ERR_CERT)|HOSTNAME_MISMATCH/;
67
+ /** A request that never reached the API: the connection failed, so nothing was applied. */
68
+ function networkErrorResult(err, sentKey) {
69
+ const cause = fetchCause(err);
70
+ const message = describeError(err);
71
+ if (cause === 'ENOTFOUND') {
72
+ return errorResult(message, 'NETWORK_ERROR', 'The API host does not resolve. Check the API URL for a typo, and that DNS can see it from this machine. Nothing was sent.');
73
+ }
74
+ if (cause === 'ECONNREFUSED') {
75
+ return errorResult(message, 'NETWORK_ERROR', 'The host resolved but refused the connection. Check that the Server is running and the port in the API URL is right. Nothing was sent.');
76
+ }
77
+ if (cause !== undefined && TLS_CAUSE.test(cause)) {
78
+ return errorResult(message, 'NETWORK_ERROR', 'The Server\'s TLS certificate was not accepted. Check the certificate chain, its expiry and that the host name matches the API URL. For a private certificate authority, start agledger-mcp with NODE_EXTRA_CA_CERTS=<path to the CA certificate>. Nothing was sent.');
79
+ }
80
+ return errorResult(message, 'NETWORK_ERROR', sentKey
81
+ ? `Check that the API URL is correct. Try GET /health to verify connectivity. If the connection dropped after the request went out it may have been applied: retry with idempotencyKey "${sentKey}", never a new key.`
82
+ : 'Check that the API URL is correct. Try GET /health to verify connectivity.', sentKey ? { idempotencyKey: sentKey } : undefined);
83
+ }
84
+ /** GET a discovery document for a resource read; a failure throws with the status and the API's own detail, or the connection's cause. */
85
+ async function fetchDocument(client, path) {
86
+ let response;
87
+ try {
88
+ response = await client.request('GET', path);
89
+ }
90
+ catch (err) {
91
+ throw new Error(`Failed to fetch ${path}: ${describeError(err)}`, { cause: err });
92
+ }
93
+ if (!response.ok)
94
+ throw new Error(apiFailureText(path, response));
95
+ return response.body;
96
+ }
97
+ /** What a failed fetch of a discovery document says: the status, then the API's own detail and recovery hint. */
98
+ function apiFailureText(path, response) {
99
+ const body = response.body !== null && typeof response.body === 'object' ? response.body : {};
100
+ const parts = [body.detail, body.message, body.recoveryHint].filter((v) => typeof v === 'string' && v !== '');
101
+ return `Failed to fetch ${path}: HTTP ${response.status}${parts.length > 0 ? `. ${parts.join(' ')}` : ''}`;
102
+ }
71
103
  /**
72
104
  * The credential could not produce a bearer. This is a client-side failure (the
73
105
  * request never went out), so it is reported in the server's own error shape.
74
106
  * The exchange's refusal is carried as the Server sent it, scrubbed of any
75
107
  * token, and its recoveryHint is passed through rather than rewritten.
76
108
  */
109
+ /**
110
+ * The agent keys argument in every shape the agledger-verify and agledger
111
+ * verify `--agent-keys` file takes: one JWK, a list of them, or a
112
+ * `{keys:[...]}` JWK Set (the file AGLEDGER_AGENT_KEYS_FILE collects), where an
113
+ * entry may wrap its key as `{publicKeyJwk:{...}}`. verify-core validates each
114
+ * key and refuses a bad one with a TypeError.
115
+ */
116
+ function agentKeyList(value) {
117
+ const list = Array.isArray(value)
118
+ ? value
119
+ : value !== null && typeof value === 'object' && Array.isArray(value.keys)
120
+ ? value.keys
121
+ : [value];
122
+ return list.map((entry) => entry !== null && typeof entry === 'object' && 'publicKeyJwk' in entry
123
+ ? entry.publicKeyJwk
124
+ : entry);
125
+ }
77
126
  function credentialErrorResult(err) {
78
127
  if (err instanceof OidcExchangeError) {
79
128
  return errorResult(err.message, err.code, err.recoveryHint ??
@@ -82,6 +131,9 @@ function credentialErrorResult(err) {
82
131
  if (err instanceof DelegationSourceError) {
83
132
  return errorResult(err.message, err.code, 'Fix the delegation source the server was started with (AGLEDGER_ON_BEHALF_OF_CMD or AGLEDGER_ON_BEHALF_OF_FILE); it must yield a current RFC 8693 token-exchange result token.');
84
133
  }
134
+ if (err instanceof AgentKeysFileError) {
135
+ return errorResult(err.message, err.code, `Fix or move ${err.path} (named by AGLEDGER_AGENT_KEYS_FILE), or unset it and restart the server. Nothing was signed under the new cert.`);
136
+ }
85
137
  if (err instanceof OidcTokenSourceError) {
86
138
  return errorResult(err.message, err.code, 'Fix the token source the server was started with (AGLEDGER_OIDC_TOKEN_CMD or AGLEDGER_OIDC_TOKEN_FILE); it must yield a current OIDC JWT on every call.');
87
139
  }
@@ -120,8 +172,8 @@ function unknownArgumentResult(tool, shape, args, hint) {
120
172
  // then the handler JSON.parses uniformly.
121
173
  //
122
174
  // Deliberately NOT `z.preprocess`, which published these fields as optional
123
- // even when they were required. The MCP SDK renders tool schemas with
124
- // `toJSONSchema(..., { io: 'input' })`, and that builds `required` from each
175
+ // even when they were required. Tool schemas are rendered with
176
+ // `toJSONSchema(..., { io: 'input' })`, which builds `required` from each
125
177
  // field's `_zod.optin`. `z.preprocess` types its input as `unknown`, which
126
178
  // subsumes `undefined`, so it sets `optin: 'optional'` and the field drops out
127
179
  // of `required`. `agledger_verify` published no `required` array at all, which
@@ -134,7 +186,8 @@ const jsonStringField = z
134
186
  .transform((v) => (v !== null && typeof v === 'object' ? JSON.stringify(v) : v))
135
187
  .pipe(z.string())
136
188
  .meta({ type: 'string' });
137
- function parseJsonObject(value, fieldName) {
189
+ function parseJsonObject(value, fieldName, options) {
190
+ const allowArray = options?.allowArray === true;
138
191
  let parsed;
139
192
  try {
140
193
  parsed = JSON.parse(value);
@@ -142,38 +195,19 @@ function parseJsonObject(value, fieldName) {
142
195
  catch (err) {
143
196
  return {
144
197
  ok: false,
145
- error: errorResult(`Argument \`${fieldName}\` is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}') or as a native object.`),
198
+ error: errorResult(`Argument \`${fieldName}\` is not valid JSON: ${describeError(err)}`, 'INVALID_JSON', allowArray
199
+ ? `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}' or '[{"keyId":"k1","publicKey":"..."}]') or as a native object/array.`
200
+ : `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}') or as a native object.`),
146
201
  };
147
202
  }
148
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
203
+ if (parsed === null || typeof parsed !== 'object' || (!allowArray && Array.isArray(parsed))) {
149
204
  return {
150
205
  ok: false,
151
- error: errorResult(`Argument \`${fieldName}\` must decode to a JSON object.`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON object, e.g. '{"key":"value"}'.`),
152
- };
153
- }
154
- return { ok: true, value: parsed };
155
- }
156
- /**
157
- * Parse a JSON-encoded object OR array. Used for fields that legitimately
158
- * accept either shape (e.g. `agledger_verify.publicKeys`, which accepts verify-core
159
- * `SuppliedKeyEntry[]` polymorphism). Strings,
160
- * numbers, booleans, and null still fail loudly.
161
- */
162
- function parseJsonObjectOrArray(value, fieldName) {
163
- let parsed;
164
- try {
165
- parsed = JSON.parse(value);
166
- }
167
- catch (err) {
168
- return {
169
- ok: false,
170
- error: errorResult(`Argument \`${fieldName}\` is not valid JSON: ${err instanceof Error ? err.message : String(err)}`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON-encoded string (e.g. '{"key":"value"}' or '[{"keyId":"k1","publicKey":"…"}]') or as a native object/array.`),
171
- };
172
- }
173
- if (parsed === null || typeof parsed !== 'object') {
174
- return {
175
- ok: false,
176
- error: errorResult(`Argument \`${fieldName}\` must decode to a JSON object or array.`, 'INVALID_JSON', `Pass \`${fieldName}\` as a JSON object (\`{keyId: spkiBase64, ...}\`) or array (\`[{keyId, publicKey}, ...]\`).`),
206
+ error: errorResult(allowArray
207
+ ? `Argument \`${fieldName}\` must decode to a JSON object or array.`
208
+ : `Argument \`${fieldName}\` must decode to a JSON object.`, 'INVALID_JSON', allowArray
209
+ ? `Pass \`${fieldName}\` as a JSON object (\`{keyId: spkiBase64, ...}\`) or array (\`[{keyId, publicKey}, ...]\`).`
210
+ : `Pass \`${fieldName}\` as a JSON object, e.g. '{"key":"value"}'.`),
177
211
  };
178
212
  }
179
213
  return { ok: true, value: parsed };
@@ -183,7 +217,7 @@ function parseJsonObjectOrArray(value, fieldName) {
183
217
  * returns an envelope `{ data: [{ keyId, publicKey, ... }], canonicalization, ... }`,
184
218
  * not the bare array verify-core expects. An MCP agent's natural flow gets the
185
219
  * envelope straight from `agledger_api` and has no `.data[]`-extraction step,
186
- * so unwrap `.data` here, the MCP analogue of the CLI's fix. A
220
+ * so unwrap `.data` here. A
187
221
  * bare `[{keyId, publicKey}]` list or a `{keyId: base64}` map passes through
188
222
  * untouched; verify-core then validates the shape and throws on anything else.
189
223
  */
@@ -221,17 +255,25 @@ function verifyVerdictText(result) {
221
255
  `link to a trust anchor you gave (${trust.anchors.join(', ')}). ` +
222
256
  `${result.verifiedEntries}/${result.totalEntries} entries verified.`);
223
257
  }
258
+ else if (!result.valid) {
259
+ lines.push(`Verdict: NOT ANCHORED. The trustAnchors (${trust.anchors.join(', ')}) reach none of the signing keys in this ` +
260
+ 'export, so every signed entry reads CHAIN_SIGNING_KEY_UNANCHORED, but the export verifies without them: ' +
261
+ 'nothing in it fails on its own. This is the result for an export from another Server than the one pinned, ' +
262
+ 'and equally for one re-signed wholesale under keys of its own. NOT a trusted verdict.');
263
+ lines.push('Next: check with the operator that each trustAnchors digest is a vault key of the install that wrote this ' +
264
+ 'export, and call agledger_verify again with the right one.');
265
+ }
224
266
  else if (trust.status === 'no_anchored_signature') {
225
267
  lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: the trustAnchors ' +
226
268
  `(${trust.anchors.join(', ')}) were walked, but no signature here verified under a key they anchor. ` +
227
- 'An entry that carries no signature proves nothing about who wrote it.');
269
+ 'An entry that carries no signature says nothing about who wrote it.');
228
270
  lines.push('Next: if the entries are signed, check that each trustAnchors digest is a vault key of the install that wrote ' +
229
271
  'this export (ask the operator). An export with no signed entry cannot be anchored.');
230
272
  }
231
273
  else {
232
274
  lines.push('Verdict: VERIFIED, NOT ANCHORED. Nothing failed, but this is NOT a trusted verdict: no trustAnchors were ' +
233
- 'given, so every signing key was taken on the word of the export itself, and a key written into the ' +
234
- "Server's database alone would verify.");
275
+ 'given, so every signing key was taken on the word of the export itself, and a key planted on the ' +
276
+ 'Server alone would verify.');
235
277
  lines.push('Next: call agledger_verify again with trustAnchors set to the sha256:<hex> digest of a vault key taken out of ' +
236
278
  'band (the installer prints the first vault key\'s; ask the operator). ' +
237
279
  (trust.anchoredFrom
@@ -249,10 +291,24 @@ function verifyVerdictText(result) {
249
291
  if (present > verified) {
250
292
  lines.push(`${present - verified} of ${present} agent signatures were not checked: pass agentKeys with the agents' cert public keys to re-verify them.`);
251
293
  }
294
+ lines.push(entryCountLine(result.entryCount));
252
295
  lines.push(...peerMessageLines(result.federationWire));
253
296
  lines.push(...evidenceLines(result.evidenceBinding));
254
297
  return lines.join('\n');
255
298
  }
299
+ /**
300
+ * What the export's entry count was held to. A chain cut from the end still
301
+ * verifies entry by entry, so the report names the stated count, if any, that
302
+ * stood behind the number of entries it verified.
303
+ */
304
+ export function entryCountLine(count) {
305
+ if (count.expectedEntries !== null)
306
+ return `Entry count: held to the checkpoint at position ${count.expectedEntries}.`;
307
+ if (count.statedEntries !== null) {
308
+ return `Entry count: held to the ${count.statedEntries} the export states; it names no checkpoint for this record yet.`;
309
+ }
310
+ return "Entry count: the file's own; the export states no count and names no checkpoint.";
311
+ }
256
312
  /**
257
313
  * The summary lines on the evidence bodies an `?evidence=true` export
258
314
  * inlines, each re-bound to the hash its entry signs. Silent when every one
@@ -276,7 +332,7 @@ export function evidenceLines(counts) {
276
332
  export function peerMessageLines(wire) {
277
333
  const lines = [];
278
334
  if (wire.afterRetirement > 0) {
279
- lines.push(`${wire.afterRetirement} of ${wire.present} sealed peer messages the peer signed under a key it had already retired: in order when the receiver's federation.peer_revoked audit row for the peer comes after them.`);
335
+ lines.push(`${wire.afterRetirement} of ${wire.present} sealed peer messages the peer signed under a key it had already retired: in order when the receiver's federation.peer_revoked audit entry for the peer comes after them.`);
280
336
  }
281
337
  if (wire.failed > 0) {
282
338
  lines.push(`${wire.failed} of ${wire.present} sealed peer messages failed CHAIN_FEDERATION_WIRE_INVALID.`);
@@ -289,12 +345,11 @@ export function peerMessageLines(wire) {
289
345
  }
290
346
  /**
291
347
  * Every code `agledger_verify` can report, named in its description so a model
292
- * can branch on them. The list used to be typed out by hand and fell three
293
- * codes behind verify-core (CHAIN_OIDC_ACTOR_MISMATCH, CHAIN_KEY_EXPIRED,
294
- * CHAIN_KEY_NOT_YET_ACTIVE). `ExportCodesMissing` below makes the compiler
295
- * fail when verify-core adds an export-level code this list does not carry.
296
- * CHECKPOINT_* and TENANT_* are dump-verifier codes and never come back from
297
- * an audit export. KEY_* are findings on the export's signed key statements,
348
+ * can branch on them. `ExportCodesMissing` below makes the compiler fail when
349
+ * verify-core adds an export-level code this list does not carry.
350
+ * CHECKPOINT_ROW_MISSING is the one CHECKPOINT_* code an export reports (it
351
+ * carries fewer entries than its checkpoint position); the other CHECKPOINT_*
352
+ * and the TENANT_* codes are dump-verifier codes. KEY_* are findings on the export's signed key statements,
298
353
  * reported at position 0 when trustAnchors are given.
299
354
  */
300
355
  const EXPORT_FAILURE_CODES = [
@@ -326,6 +381,7 @@ const EXPORT_FAILURE_CODES = [
326
381
  'CHAIN_KEY_WINDOW_DRIFT',
327
382
  'UNSUPPORTED_FORMAT',
328
383
  'CHAIN_EMPTY',
384
+ 'CHECKPOINT_ROW_MISSING',
329
385
  ];
330
386
  // Resolves to `true` only when nothing is missing; otherwise the assignment
331
387
  // fails and the error names the missing code.
@@ -372,7 +428,7 @@ const VERIFY_ARGS = {
372
428
  '.data array is unwrapped automatically, so the agledger_api response can be ' +
373
429
  'passed straight through, and each key\'s signed statements are walked with trustAnchors). ' +
374
430
  'Merged over any keys embedded in the export. Where a key came from is not whether it is ' +
375
- 'trusted: the Server serves these from the same database as the export. That is trustAnchors.'),
431
+ 'trusted: the Server serves these along with the export. That is trustAnchors.'),
376
432
  trustAnchors: z
377
433
  .array(z.string())
378
434
  .optional()
@@ -397,8 +453,10 @@ const VERIFY_ARGS = {
397
453
  'distrustedKeys entry to confirm with the operator.'),
398
454
  agentKeys: jsonStringField
399
455
  .optional()
400
- .describe('Optional Ed25519 public keys of agent certs, as a JSON-encoded array of JWKs ' +
401
- '\'[{"kty":"OKP","crv":"Ed25519","x":"..."}]\' (the publicKeyJwk each agent sent at cert exchange, also the cnf.jwk claim in its certJws). ' +
456
+ .describe('Optional Ed25519 public keys of agent certs, JSON-encoded: an array of JWKs ' +
457
+ '\'[{"kty":"OKP","crv":"Ed25519","x":"..."}]\', one JWK, or a {"keys":[...]} JWK Set (the file AGLEDGER_AGENT_KEYS_FILE collects), ' +
458
+ 'where an entry may wrap its key as {"publicKeyJwk":{...}}. Each is the publicKeyJwk an agent sent at cert exchange (also the cnf.jwk ' +
459
+ 'claim in its certJws; agledger_discover shows this server\'s own as agentKey). ' +
402
460
  'An entry whose sealed agent signature names one of these keys by thumbprint has that ' +
403
461
  'signature re-verified offline, and fails CHAIN_AGENT_SIGNATURE_INVALID if it does not verify. ' +
404
462
  'Without it, agent signatures are counted in result.agentSignatures but not checked.'),
@@ -409,15 +467,31 @@ const VERIFY_ARGS = {
409
467
  'operator gives it (base64 SPKI DER, or base64 of the raw 32 bytes the handshake registered). ' +
410
468
  'A receiving Server seals each peer message it accepts on the chain entry it writes (payload.wire), ' +
411
469
  'as the peer signed it. Every sealed message is held to its body hash and to its entry; one from a ' +
412
- 'hub given here also has its signature re-verified under that key, which proves what the peer ' +
470
+ 'hub given here also has its signature re-verified under that key, which checks what the peer ' +
413
471
  'asserted from this export alone, and fails CHAIN_FEDERATION_WIRE_INVALID if it does not verify. ' +
414
472
  'After a peer changes its federation key, add "history" to an array entry: the JSON the peer serves at ' +
415
473
  'GET /.well-known/agledger-federation-keys.json (no auth). Every key it links to that entry\'s publicKey ' +
416
474
  'through successions both keys signed is then trusted inside its window, so entries sealed before the ' +
417
475
  'change verify; each message is placed in its key\'s window by its signed wire.timestamp. A hub may appear ' +
418
476
  'twice, to pin a key no succession links or one the history does not list. ' +
419
- 'result.federationWire counts present, verified, failed and afterRetirement (verified, but signed by the ' +
420
- 'peer under a key it had already retired).'),
477
+ 'Federation key histories need a Server 2.2 or later on the peer. ' +
478
+ 'A message signed more than 300 seconds after its key\'s retirement fails CHAIN_FEDERATION_WIRE_INVALID unless ' +
479
+ 'allowAfterRetirement is true. result.federationWire counts present, verified, failed and afterRetirement ' +
480
+ '(accepted under allowAfterRetirement, signed by the peer under a key it had already retired).'),
481
+ allowAfterRetirement: z
482
+ .boolean()
483
+ .optional()
484
+ .describe('Accept a sealed peer message signed under a key after that key\'s retirement, and count it in ' +
485
+ 'result.federationWire.afterRetirement, for a peer that kept signing briefly after rotating because its process ' +
486
+ 'had not restarted. Without it such a message fails CHAIN_FEDERATION_WIRE_INVALID.'),
487
+ expectedEntryCount: z
488
+ .number()
489
+ .int()
490
+ .min(0)
491
+ .optional()
492
+ .describe('The number of entries the export must hold, taken out of band (the record\'s entry count from the Server or an ' +
493
+ 'earlier export). The counts an export states about itself are unsigned, so an export cut from the end with them ' +
494
+ 'deleted verifies; with this set it fails CHAIN_POSITION_GAP, and result.optionalChecks.entry_count is "applied".'),
421
495
  requireKeyId: z
422
496
  .string()
423
497
  .optional()
@@ -432,22 +506,26 @@ const VERIFY_ARGS = {
432
506
  export class AgledgerMcpServer {
433
507
  mcp;
434
508
  client;
509
+ /** The cert credential, when the server authenticates with an OIDC token source. */
510
+ oidcCredential;
511
+ agentKeysFile;
435
512
  constructor(options) {
436
513
  // No placeholder default. agledger.example.com resolves nowhere, so a
437
514
  // missing --api-url surfaced as a DNS failure against a host the operator
438
- // never configured, on every tool call. Same defect the CLI and SDK
439
- // carried; every deployment is self-hosted, so there is no default worth
440
- // having. Fail at startup, where it can be read.
515
+ // never configured, on every tool call. Every deployment is self-hosted, so
516
+ // there is no default worth having. Fail at startup, where it can be read.
441
517
  const apiUrl = options.apiUrl;
442
518
  if (!apiUrl) {
443
519
  throw new Error('No API URL configured. AGLedger is self-hosted, so the MCP server cannot guess your Server: ' +
444
520
  'pass --api-url <url> or set AGLEDGER_API_URL.');
445
521
  }
446
- if (Boolean(options.apiKey) === Boolean(options.oidc)) {
522
+ this.oidcCredential = !options.apiKey && options.oidc ? new OidcCertCredential(options.oidc) : undefined;
523
+ this.agentKeysFile = options.oidc?.agentKeysFile;
524
+ const credential = options.apiKey ? options.apiKey : this.oidcCredential;
525
+ if (Boolean(options.apiKey) === Boolean(options.oidc) || !credential) {
447
526
  throw new Error('Configure exactly one credential: an API key (--api-key or AGLEDGER_API_KEY) or an OIDC token source ' +
448
527
  '(AGLEDGER_OIDC_TOKEN_CMD or AGLEDGER_OIDC_TOKEN_FILE).');
449
528
  }
450
- const credential = options.apiKey ? options.apiKey : new OidcCertCredential(options.oidc);
451
529
  this.client = new ApiClient(apiUrl, credential, options.timeoutMs, options.onBehalfOf ? new DelegationSource(options.onBehalfOf) : undefined);
452
530
  this.mcp = new McpServer({ name: 'agledger-mcp-server', version: SERVER_VERSION }, { capabilities: { tools: {}, resources: {} } });
453
531
  this.registerTools();
@@ -485,29 +563,35 @@ export class AgledgerMcpServer {
485
563
  client.request('GET', '/v1/scope-profiles'),
486
564
  ]);
487
565
  const result = {};
488
- if (health.status === 'fulfilled') {
489
- result.health = health.value.body;
490
- }
491
- else {
492
- result.health = {
493
- error: health.reason instanceof Error ? health.reason.message : String(health.reason),
494
- };
495
- }
496
- if (identity.status === 'fulfilled') {
497
- result.identity = identity.value.body;
566
+ // One section per call. A call the API refused is marked with the
567
+ // HTTP status and the API's own body, so a failed section never reads
568
+ // as an answer, and one that never completed carries the error.
569
+ const section = (call) => {
570
+ if (call.status === 'rejected')
571
+ return { error: describeError(call.reason) };
572
+ if (call.value.ok)
573
+ return call.value.body;
574
+ const body = call.value.body !== null && typeof call.value.body === 'object' ? call.value.body : {};
575
+ return { httpStatus: call.value.status, ...body, error: true };
576
+ };
577
+ result.health = section(health);
578
+ if (identity.status === 'rejected') {
579
+ const credentialError = credentialErrorResult(identity.reason);
580
+ result.identity = credentialError ? credentialError.structuredContent : section(identity);
498
581
  }
499
582
  else {
500
- const credentialError = credentialErrorResult(identity.reason);
501
- result.identity = credentialError
502
- ? credentialError.structuredContent
503
- : {
504
- error: identity.reason instanceof Error
505
- ? identity.reason.message
506
- : String(identity.reason),
507
- };
583
+ result.identity = section(identity);
508
584
  }
509
- if (scopeProfiles.status === 'fulfilled') {
510
- result.scopeProfiles = scopeProfiles.value.body;
585
+ result.scopeProfiles = section(scopeProfiles);
586
+ // The cert key this server signs request bodies with. The cert
587
+ // carries only its thumbprint, so this is the key agledger_verify's
588
+ // agentKeys needs to re-verify what this server signed.
589
+ if (this.oidcCredential) {
590
+ result.agentKey = {
591
+ publicKeyJwk: this.oidcCredential.publicKeyJwk,
592
+ ...(this.agentKeysFile ? { recordedIn: this.agentKeysFile } : {}),
593
+ note: 'Pass this key in agledger_verify agentKeys to re-verify the agent signatures this server sealed. One key per server process.',
594
+ };
511
595
  }
512
596
  // Whether POSTs carry an AGLedger-On-Behalf-Of delegation, and from
513
597
  // where. The token itself is never shown.
@@ -524,7 +608,7 @@ export class AgledgerMcpServer {
524
608
  return { content: mirrorContent(result), structuredContent: result };
525
609
  }
526
610
  catch (err) {
527
- return errorResult(err instanceof Error ? err.message : String(err), 'DISCOVER_FAILED');
611
+ return errorResult(describeError(err), 'DISCOVER_FAILED');
528
612
  }
529
613
  });
530
614
  this.mcp.registerTool('agledger_api', {
@@ -547,6 +631,20 @@ export class AgledgerMcpServer {
547
631
  'auditor verifies offline; metadata[key]=value filters an unsigned annotation instead. ' +
548
632
  'If a call fails, the error says how to recover: recoveryHint on an error from the Server, ' +
549
633
  'suggestion on an error this tool raises itself (a bad argument, a timeout, a credential failure). ' +
634
+ 'Say what produced the work: POST /v1/records and POST /v1/records/{id}/completions take an optional ' +
635
+ 'producedBy object (modelProvider, modelId, modelVersion, agentSoftware, agentSoftwareVersion, promptDigest, ' +
636
+ 'configDigest; digests are sha256:, sha384: or sha512: hex). Search takes traceId, originRecordId, ' +
637
+ 'producedBy[key]=value and numeric bounds written as criteriaGte[amount]=500 (also criteriaGt/Lt/Lte and the ' +
638
+ 'metadata twins); pass them in params as nested objects, e.g. {"criteriaGte":{"amount":500}}. ' +
639
+ 'GET /v1/records/counts takes the same filters plus groupBy, up to two comma-joined dimensions ' +
640
+ '(type, status, performerAgentId, principalAgentId, category, gateMode, operatingMode, createdDay, createdMonth). ' +
641
+ 'A verdict (POST /v1/records/{id}/verdict) may add signatureMeaning (authorship, review, approval or responsibility): ' +
642
+ 'it is taken only on an ephemeral OIDC cert, and the Server refuses it with 422 on an API key. ' +
643
+ 'GET /v1/records/{id}/audit-export takes format=html and returns the page as text exactly as the Server sent it; ' +
644
+ 'use the default JSON export for agledger_verify. ' +
645
+ 'On a keyed write, 409 IDEMPOTENCY_KEY_IN_FLIGHT means the first attempt is still running: retry with the same key ' +
646
+ 'after Retry-After (an error result carries it as retryAfter, in seconds, beside httpStatus). 409 IDEMPOTENT_WRITE_COMMITTED means it already landed: follow its refreshUrl, do not retry. ' +
647
+ '503 SERVER_SHUTTING_DOWN is retryable. ' +
550
648
  'For the full API catalog, GET /openapi.json (or read the agledger://openapi resource); ' +
551
649
  'for prose orientation, GET /llms.txt (or read the agledger://llms.txt resource). ' +
552
650
  'For GET/DELETE, params become query parameters. For POST/PUT/PATCH, params become the JSON body. ' +
@@ -556,7 +654,8 @@ export class AgledgerMcpServer {
556
654
  annotations: {
557
655
  readOnlyHint: false,
558
656
  // This tool dispatches to any route, including DELETE/PATCH, so it can
559
- // perform destructive, non-idempotent operations. Annotate honestly.
657
+ // perform destructive, non-idempotent operations, so it is marked
658
+ // destructive and not idempotent.
560
659
  destructiveHint: true,
561
660
  idempotentHint: false,
562
661
  openWorldHint: true,
@@ -566,9 +665,9 @@ export class AgledgerMcpServer {
566
665
  // method+path to every route, each with its own scope requirement
567
666
  // (records:read, records:write, etc.). The required scope is route-
568
667
  // dependent and enforced server-side per request; it cannot be
569
- // statically declared for the dispatcher as a whole. Fabricating a
570
- // single scope here would be dishonest. Callers see the real missing
571
- // scopes in the API's 403 response (missingScopes), forwarded verbatim.
668
+ // statically declared for the dispatcher as a whole, so no scope is
669
+ // listed here. A caller sees the missing scopes in the API's 403
670
+ // response (missingScopes), forwarded verbatim.
572
671
  }, async (args) => {
573
672
  const refused = unknownArgumentResult('agledger_api', API_ARGS, args, 'The request body (POST/PUT/PATCH) and the query string (GET/DELETE) both go in `params`.');
574
673
  if (refused)
@@ -591,7 +690,7 @@ export class AgledgerMcpServer {
591
690
  // Reject control characters before building the request URL. Tool input
592
691
  // is untrusted; control chars enable request-line / header injection and
593
692
  // never appear in a legitimate API path.
594
- if (/[\x00-\x1f\x7f]/.test(path)) {
693
+ if (Array.from(path).some((ch) => ch.charCodeAt(0) <= 0x1f || ch.charCodeAt(0) === 0x7f)) {
595
694
  return errorResult('Path contains control characters.', 'PATH_INVALID', 'Remove control characters (newlines, tabs, null bytes) from the path.');
596
695
  }
597
696
  const options = {};
@@ -614,14 +713,25 @@ export class AgledgerMcpServer {
614
713
  const response = await client.request(method, path, options);
615
714
  if (response.ok) {
616
715
  const body = response.body;
716
+ // A text response (format=html|csv|ndjson on an audit export) is
717
+ // handed back as the Server sent it, not as an escaped JSON string.
718
+ // structuredContent keeps the {_raw, _contentType} wrapper.
719
+ const text = typeof body?._raw === 'string' ? [{ type: 'text', text: body._raw }] : mirrorContent(body);
617
720
  return {
618
- content: mirrorContent(body),
721
+ content: text,
619
722
  structuredContent: body,
620
723
  };
621
724
  }
622
725
  // Forward the API error body verbatim. The API owns error guidance;
623
- // the MCP does not enrich, translate, or inject suggestions.
624
- const errorBody = (response.body ?? {});
726
+ // the MCP does not enrich, translate, or inject suggestions. What it
727
+ // adds is what the body cannot say: the HTTP status, and the seconds
728
+ // of a Retry-After header, which the tool description tells the model
729
+ // to honour. The body's own fields win over both.
730
+ const errorBody = {
731
+ httpStatus: response.status,
732
+ ...(response.retryAfterSeconds !== undefined ? { retryAfter: response.retryAfterSeconds } : {}),
733
+ ...(response.body ?? {}),
734
+ };
625
735
  return {
626
736
  content: mirrorContent(errorBody),
627
737
  structuredContent: errorBody,
@@ -638,11 +748,12 @@ export class AgledgerMcpServer {
638
748
  : 'Retry the same request. This method carries no idempotency key. If your instance is slow to respond, start agledger-mcp with --timeout <seconds> (or AGLEDGER_TIMEOUT).', sentKey ? { idempotencyKey: sentKey } : undefined);
639
749
  }
640
750
  if (err instanceof TypeError && err.message.includes('fetch')) {
641
- return errorResult(err.message, 'NETWORK_ERROR', sentKey
642
- ? `Check that the API URL is correct. Try GET /health to verify connectivity. If the connection dropped after the request went out it may have been applied: retry with idempotencyKey "${sentKey}", never a new key.`
643
- : 'Check that the API URL is correct. Try GET /health to verify connectivity.', sentKey ? { idempotencyKey: sentKey } : undefined);
751
+ return networkErrorResult(err, sentKey);
752
+ }
753
+ if (err instanceof QueryShapeError) {
754
+ return errorResult(err.message, 'INVALID_ARGUMENT', 'Give each params entry a string, number or boolean, or an object of them one level deep (params: { criteriaGte: { amount: 500 } }). Nothing was sent.');
644
755
  }
645
- return errorResult(err instanceof Error ? err.message : String(err), 'UNKNOWN_ERROR');
756
+ return errorResult(describeError(err), 'UNKNOWN_ERROR');
646
757
  }
647
758
  });
648
759
  this.mcp.registerTool('agledger_verify', {
@@ -650,19 +761,23 @@ export class AgledgerMcpServer {
650
761
  description: 'Verify an AGLedger record audit export offline (format 2.0, COSE_Sign1). ' +
651
762
  'Decodes each entry\'s tagged COSE_Sign1 envelope (RFC 9052), recomputes ' +
652
763
  'sha256 over the envelope bytes, walks the hash chain, cross-checks the protected-' +
653
- 'header chain claim against the row columns, and verifies every envelope signature (Ed25519 or ES256, dispatched from the trusted key material; anything else fails closed). ' +
764
+ 'header chain claim against the entry fields the export lists beside the signed bytes, and verifies every envelope signature (Ed25519 or ES256, dispatched from the trusted key material; anything else fails closed). ' +
654
765
  'No network calls. Pass trustAnchors (the sha256:<hex> digest of a vault key the operator ' +
655
766
  'took out of band) so the export\'s signed key statements are walked from a key you trust: ' +
656
767
  'without it the keys are taken on the export\'s word and keyTrust.status is "no_anchor". ' +
657
768
  'result.verdict is "trusted" (PASS: valid, and keyTrust.status "walked"), "failed", or "unanchored" ' +
658
769
  '(VERIFIED, NOT ANCHORED: valid, but keyTrust.status "no_anchor", or "no_anchored_signature" when the ' +
659
- 'anchors were walked and no signature verified under a key they anchor); an unanchored result is not a trusted verdict. ' +
770
+ 'anchors were walked and no signature verified under a key they anchor; also NOT ANCHORED with valid false when the ' +
771
+ 'trustAnchors reach none of the export\'s keys and it verifies without them, as for another Server\'s pin); ' +
772
+ 'an unanchored result is not a trusted verdict, and isError is set only for "failed". ' +
660
773
  'result.summary states the verdict in words and the next step. ' +
661
774
  'On failure, brokenAt pinpoints the first entry that failed and its canonical code ' +
662
775
  `(${EXPORT_FAILURE_CODES.join(', ')}); CHAIN_UNSUPPORTED_ALGORITHM means this build ` +
663
776
  'could not compute the key\'s algorithm: upgrade, and never read it as a pass. Obtain the export via agledger_api with method=GET, path=/v1/records/{id}/audit-export. ' +
664
777
  'Add params \'{"evidence":true}\' to inline each completion\'s evidence and each dispute\'s filed payload: every inlined body is ' +
665
778
  're-bound to the hash its entry signs (result.evidenceBinding; an edited one fails CHAIN_EVIDENCE_BINDING_MISMATCH). ' +
779
+ 'Pass the export exactly as fetched: its length is held to the counts it states (result.entryCount), so an export with ' +
780
+ 'entries removed from the end fails CHECKPOINT_ROW_MISSING or CHAIN_POSITION_GAP. ' +
666
781
  'For the raw COSE_Sign1 stream, use path=/v1/records/{id}/attestation.',
667
782
  inputSchema: toolInput(VERIFY_ARGS),
668
783
  annotations: {
@@ -680,7 +795,7 @@ export class AgledgerMcpServer {
680
795
  if (refused)
681
796
  return refused;
682
797
  try {
683
- const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, federationKeys: federationKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, } = args;
798
+ const { export: exportRaw, publicKeys: publicKeysRaw, agentKeys: agentKeysRaw, federationKeys: federationKeysRaw, trustAnchors, distrustedKeys, requireKeyId, requireSuppliedKeys, allowAfterRetirement, expectedEntryCount, } = args;
684
799
  const decodedExport = parseJsonObject(exportRaw, 'export');
685
800
  if (!decodedExport.ok)
686
801
  return decodedExport.error;
@@ -695,13 +810,13 @@ export class AgledgerMcpServer {
695
810
  parseDistrustedKeys(distrustedKeys ?? []);
696
811
  }
697
812
  catch (err) {
698
- return errorResult(err instanceof Error ? err.message : String(err), 'INVALID_ARGUMENT', 'Pass trustAnchors as ["sha256:<64 hex>"] and distrustedKeys as ["sha256:<64 hex>" or "sha256:<64 hex>@<RFC 3339 instant>"].');
813
+ return errorResult(describeError(err), 'INVALID_ARGUMENT', 'Pass trustAnchors as ["sha256:<64 hex>"] and distrustedKeys as ["sha256:<64 hex>" or "sha256:<64 hex>@<RFC 3339 instant>"].');
699
814
  }
700
815
  try {
701
816
  assertNotPinnedAndDistrusted(trustAnchors, distrustedKeys);
702
817
  }
703
818
  catch (err) {
704
- return errorResult(err instanceof Error ? err.message : String(err), 'INVALID_ARGUMENT', 'Keep the pin and give the leaked key the instant it leaked, "sha256:<64 hex>@<RFC 3339 instant>"; or, if nothing it signed is vouched for, drop it from trustAnchors.');
819
+ return errorResult(describeError(err), 'INVALID_ARGUMENT', 'Keep the pin and give the leaked key the instant it leaked, "sha256:<64 hex>@<RFC 3339 instant>"; or, if nothing it signed is vouched for, drop it from trustAnchors.');
705
820
  }
706
821
  const anchored = trustAnchors !== undefined && trustAnchors.length > 0;
707
822
  // verify-core reads distrusted keys only during the walk, so without
@@ -711,24 +826,21 @@ export class AgledgerMcpServer {
711
826
  }
712
827
  let publicKeys;
713
828
  if (publicKeysRaw !== undefined && publicKeysRaw !== '') {
714
- const decodedKeys = parseJsonObjectOrArray(publicKeysRaw, 'publicKeys');
829
+ const decodedKeys = parseJsonObject(publicKeysRaw, 'publicKeys', { allowArray: true });
715
830
  if (!decodedKeys.ok)
716
831
  return decodedKeys.error;
717
832
  publicKeys = unwrapVerificationKeys(decodedKeys.value);
718
833
  }
719
834
  let agentKeys;
720
835
  if (agentKeysRaw !== undefined && agentKeysRaw !== '') {
721
- const decodedAgentKeys = parseJsonObjectOrArray(agentKeysRaw, 'agentKeys');
836
+ const decodedAgentKeys = parseJsonObject(agentKeysRaw, 'agentKeys', { allowArray: true });
722
837
  if (!decodedAgentKeys.ok)
723
838
  return decodedAgentKeys.error;
724
- if (!Array.isArray(decodedAgentKeys.value)) {
725
- return errorResult('Argument `agentKeys` must decode to a JSON array of Ed25519 JWKs.', 'INVALID_JSON', 'Pass `agentKeys` as \'[{"kty":"OKP","crv":"Ed25519","x":"..."}]\'.');
726
- }
727
- agentKeys = decodedAgentKeys.value;
839
+ agentKeys = agentKeyList(decodedAgentKeys.value);
728
840
  }
729
841
  let federationKeys;
730
842
  if (federationKeysRaw !== undefined && federationKeysRaw !== '') {
731
- const decodedFederationKeys = parseJsonObjectOrArray(federationKeysRaw, 'federationKeys');
843
+ const decodedFederationKeys = parseJsonObject(federationKeysRaw, 'federationKeys', { allowArray: true });
732
844
  if (!decodedFederationKeys.ok)
733
845
  return decodedFederationKeys.error;
734
846
  federationKeys = decodedFederationKeys.value;
@@ -739,6 +851,8 @@ export class AgledgerMcpServer {
739
851
  federationKeys,
740
852
  requireKeyId,
741
853
  requireSuppliedKeys,
854
+ ...(allowAfterRetirement !== undefined ? { allowAfterRetirement } : {}),
855
+ ...(expectedEntryCount !== undefined ? { expectedEntryCount } : {}),
742
856
  ...(anchored ? { trustAnchors, distrustedKeys } : {}),
743
857
  });
744
858
  // verify-core's result verbatim, verdict first (`valid` alone is true
@@ -749,22 +863,24 @@ export class AgledgerMcpServer {
749
863
  return {
750
864
  content: mirrorContent(structured),
751
865
  structuredContent: structured,
752
- isError: !result.valid,
866
+ // A pin that was not met is not a failure of the export (verdict
867
+ // "unanchored"); only a failed verdict is.
868
+ isError: verdict === 'failed',
753
869
  };
754
870
  }
755
871
  catch (err) {
756
872
  // verify-core throws TypeError only on input it refuses (a supplied
757
873
  // key's window that is not RFC 3339, a malformed key list): that is
758
874
  // the caller's argument, not a failed verification.
759
- return errorResult(err instanceof Error ? err.message : String(err), err instanceof TypeError ? 'INVALID_ARGUMENT' : 'VERIFY_FAILED');
875
+ return errorResult(describeError(err), err instanceof TypeError ? 'INVALID_ARGUMENT' : 'VERIFY_FAILED');
760
876
  }
761
877
  });
762
878
  }
763
879
  registerResources() {
764
880
  const client = this.client;
765
881
  /**
766
- * Proxies GET /openapi.json at read time. Keeps the spec fresh, with no local
767
- * cache that could go stale. Clients (Claude Desktop, etc.) surface this
882
+ * Proxies GET /openapi.json at read time. Fetches the spec on every read, with no
883
+ * local cache. Clients (Claude Desktop, etc.) surface this
768
884
  * in their resource picker, so users/agents can pull the spec into context
769
885
  * without constructing an `agledger_api` call.
770
886
  */
@@ -772,25 +888,20 @@ export class AgledgerMcpServer {
772
888
  description: 'The AGLedger API OpenAPI 3.0 specification. Fetches live from GET /openapi.json, always current with the running API instance.',
773
889
  mimeType: 'application/json',
774
890
  }, async () => {
775
- const response = await client.request('GET', '/openapi.json');
776
- if (!response.ok) {
777
- throw new Error(`Failed to fetch /openapi.json: HTTP ${response.status}`);
778
- }
891
+ const body = await fetchDocument(client, '/openapi.json');
779
892
  return {
780
893
  contents: [
781
894
  {
782
895
  uri: 'agledger://openapi',
783
896
  mimeType: 'application/json',
784
- text: typeof response.body === 'string' ? response.body : JSON.stringify(response.body),
897
+ text: typeof body === 'string' ? body : JSON.stringify(body),
785
898
  },
786
899
  ],
787
900
  };
788
901
  });
789
902
  /**
790
903
  * Proxies GET /llms.txt at read time. The API writes this narrative for
791
- * agents, and an MCP-connected agent had no way to learn it existed: the
792
- * CLI advertised it, this server did not. Same live-fetch approach as the
793
- * spec resource, so it cannot go stale.
904
+ * agents. Same live-fetch approach as the spec resource.
794
905
  */
795
906
  this.mcp.registerResource('agledger-llms-txt', 'agledger://llms.txt', {
796
907
  description: "The AGLedger API's agent-oriented documentation narrative (the llms.txt convention). " +
@@ -799,13 +910,9 @@ export class AgledgerMcpServer {
799
910
  'OpenAPI spec if you are new to the API.',
800
911
  mimeType: 'text/plain',
801
912
  }, async () => {
802
- const response = await client.request('GET', '/llms.txt');
803
- if (!response.ok) {
804
- throw new Error(`Failed to fetch /llms.txt: HTTP ${response.status}`);
805
- }
806
913
  // /llms.txt is text/plain, so the client surfaces the raw body rather
807
914
  // than a parsed object.
808
- const body = response.body;
915
+ const body = await fetchDocument(client, '/llms.txt');
809
916
  const text = typeof body === 'string'
810
917
  ? body
811
918
  : body && typeof body === 'object' && '_raw' in body