@coreguard/agent-commerce 0.1.2 → 0.1.3

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/mcp.mjs CHANGED
@@ -24,6 +24,7 @@
24
24
  */
25
25
 
26
26
  import { createInterface } from "node:readline";
27
+ import { readFileSync } from "node:fs";
27
28
  import { fileURLToPath } from "node:url";
28
29
  import {
29
30
  createConsent,
@@ -32,26 +33,212 @@ import {
32
33
  assessRisk,
33
34
  AGENT_COMMERCE_VERSION,
34
35
  CONSENT_SPEC,
36
+ splitIdentity,
37
+ compareIdentities,
38
+ anchorFacts,
39
+ buildAttestation,
40
+ verifyAttestation,
41
+ outcomeForVerificationReport,
42
+ authorizationDecision,
43
+ makeProfileReference,
44
+ parseProfileReference,
45
+ createConsumptionStore,
46
+ CONSUMPTION_STORE_BOUNDARY,
47
+ CGXA_VERSION,
48
+ SOROBAN_CONSENT_BINDING_VERSION,
49
+ buildSorobanConsentBinding,
35
50
  } from "./index.mjs";
36
51
 
37
52
  const PROTOCOL_VERSION = "2025-06-18";
38
- const SERVER_INFO = { name: "coreguard-agent-commerce", version: "1.0.0" };
53
+
54
+ // Single source of truth for the version: the package manifest. The server used
55
+ // to hard-code its own string and drifted from npm (1.0.0 vs 0.1.2); the CI test
56
+ // test/integrations/agent-commerce-mcp.test.mjs now fails if they differ.
57
+ const PACKAGE = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8"));
58
+ const SERVER_INFO = Object.freeze({ name: "coreguard-agent-commerce", version: PACKAGE.version });
39
59
  const SERVER_BOUNDARY =
40
60
  "offline verification surface — binds approvals and verifies executions on committed machinery; " +
41
61
  "no contact with any commerce platform or payment network; VERIFIED ≠ SAFE; " +
42
- "single-use consumption is process-local (durable anchoring NOT_BUILT)";
62
+ "single-use consumption is process-local by default — pass storePath or set COREGUARD_CONSUMPTION_STORE for an " +
63
+ "AC-CS/1 lock-guarded file ledger (cross-process on this host); cross-host reconciliation is CG-SPEND/1 merge; " +
64
+ "on-chain anchoring NOT_BUILT";
65
+
66
+ // Optional deployment-wide AC-CS/1 ledger path. Unset keeps the documented
67
+ // process-local default; setting it makes single-use durable across processes
68
+ // on this host without changing any tool arguments.
69
+ const DEFAULT_CONSUMPTION_STORE = process.env.COREGUARD_CONSUMPTION_STORE?.trim() || null;
43
70
 
44
71
  const TOOL_NAMES = Object.freeze([
45
72
  "coreguard_authorize",
46
73
  "coreguard_verify_consent",
47
74
  "coreguard_verify_execution",
48
75
  "coreguard_assess_risk",
76
+ "coreguard_inspect_identity",
77
+ "coreguard_build_attestation",
78
+ "coreguard_verify_attestation",
79
+ "coreguard_decide_outcome",
80
+ "coreguard_profile_reference",
81
+ "coreguard_consumption_status",
49
82
  ]);
50
83
 
84
+ /**
85
+ * Stable error contract. Every failure is a tool result with `isError: true`,
86
+ * a human-readable `content[0].text` of the form "CODE: detail", and a machine
87
+ * readable `structuredContent.error = { code, detail }`. The server never exits
88
+ * or throws on bad input — the process keeps serving the next request.
89
+ */
90
+ export const ERROR_CODES = Object.freeze({
91
+ UNKNOWN_TOOL: "UNKNOWN_TOOL",
92
+ MISSING_ARGUMENT: "MISSING_ARGUMENT",
93
+ INVALID_ARGUMENT: "INVALID_ARGUMENT",
94
+ TOOL_ERROR: "TOOL_ERROR",
95
+ });
96
+
97
+ function failure(code, detail) {
98
+ return {
99
+ isError: true,
100
+ content: [{ type: "text", text: `${code}: ${detail}` }],
101
+ structuredContent: { ok: false, error: { code, detail } },
102
+ };
103
+ }
104
+
105
+ function success(value) {
106
+ const structured = value !== null && typeof value === "object" && !Array.isArray(value) ? value : { ok: true, value };
107
+ return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }], structuredContent: structured };
108
+ }
109
+
110
+ const isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
111
+
112
+ function requireObjects(args, keys) {
113
+ for (const key of keys) {
114
+ if (args[key] === undefined) return { code: ERROR_CODES.MISSING_ARGUMENT, detail: `${key} is required` };
115
+ if (!isPlainObject(args[key])) return { code: ERROR_CODES.INVALID_ARGUMENT, detail: `${key} must be a JSON object` };
116
+ }
117
+ return null;
118
+ }
119
+
120
+ function optionalObject(args, key) {
121
+ if (args[key] === undefined) return null;
122
+ if (!isPlainObject(args[key])) return { code: ERROR_CODES.INVALID_ARGUMENT, detail: `${key} must be a JSON object when supplied` };
123
+ return null;
124
+ }
125
+ function requireString(args, key) {
126
+ if (args[key] === undefined) return { code: ERROR_CODES.MISSING_ARGUMENT, detail: `${key} is required` };
127
+ if (typeof args[key] !== "string" || args[key].length === 0) {
128
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: `${key} must be a non-empty string` };
129
+ }
130
+ return null;
131
+ }
132
+
133
+ /** Per-tool input validation. Returns null when the arguments are usable. */
134
+ const VALIDATORS = Object.freeze({
135
+ coreguard_authorize(args) {
136
+ const missing = requireObjects(args, ["intent", "policy", "declaredTrace"]);
137
+ if (missing) return missing;
138
+ if (args.nowSeconds === undefined) return { code: ERROR_CODES.MISSING_ARGUMENT, detail: "nowSeconds is required" };
139
+ if (typeof args.nowSeconds !== "string" || !/^[0-9]+$/.test(args.nowSeconds)) {
140
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "nowSeconds must be a pinned unix-seconds string (digits only), not a number and never the wall clock" };
141
+ }
142
+ return optionalObject(args, "callerContext");
143
+ },
144
+ coreguard_verify_consent(args) {
145
+ const missing = requireObjects(args, ["consent"]);
146
+ if (missing) return missing;
147
+ return optionalObject(args, "callerContext");
148
+ },
149
+ coreguard_verify_execution(args) {
150
+ const missing = requireObjects(args, ["consent", "trace"]);
151
+ if (missing) return missing;
152
+ return optionalObject(args, "callerContext");
153
+ },
154
+ coreguard_assess_risk(args) {
155
+ const missing = requireObjects(args, ["intent", "policy", "trace"]);
156
+ if (missing) return missing;
157
+ if (args.consumed !== undefined && typeof args.consumed !== "boolean") {
158
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "consumed must be a boolean when supplied" };
159
+ }
160
+ return optionalObject(args, "callerContext");
161
+ },
162
+ coreguard_inspect_identity(args) {
163
+ const missing = requireString(args, "issuer") || requireString(args, "scope") || requireString(args, "subject") || requireString(args, "contentDigest");
164
+ if (missing) return missing;
165
+ if (args.anchor !== undefined && args.anchor !== null && !isPlainObject(args.anchor)) {
166
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "anchor must be a JSON object when supplied" };
167
+ }
168
+ const otherErr = optionalObject(args, "other");
169
+ if (otherErr) return otherErr;
170
+ return optionalObject(args, "callerContext");
171
+ },
172
+ coreguard_build_attestation(args) {
173
+ const missing = requireObjects(args, ["consent", "executedTrace"]);
174
+ if (missing) return missing;
175
+ const a = requireString(args, "adapterId");
176
+ if (a) return a;
177
+ if (args.nowSeconds === undefined) return { code: ERROR_CODES.MISSING_ARGUMENT, detail: "nowSeconds is required" };
178
+ const ns = args.nowSeconds;
179
+ const ok = (typeof ns === "number" && Number.isInteger(ns) && ns >= 0) || (typeof ns === "string" && /^[0-9]+$/.test(ns));
180
+ if (!ok) {
181
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "nowSeconds must be a pinned non-negative integer (or digit string)" };
182
+ }
183
+ return optionalObject(args, "callerContext");
184
+ },
185
+ coreguard_verify_attestation(args) {
186
+ const missing = requireObjects(args, ["attestation", "consent", "executedTrace"]);
187
+ if (missing) return missing;
188
+ const id = requireString(args, "attestationId");
189
+ if (id) return id;
190
+ return optionalObject(args, "callerContext");
191
+ },
192
+ coreguard_decide_outcome(args) {
193
+ const missing = requireObjects(args, ["report"]);
194
+ if (missing) return missing;
195
+ if (args.receiptId !== undefined && (typeof args.receiptId !== "string" || args.receiptId.length === 0)) {
196
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "receiptId must be a non-empty string when supplied" };
197
+ }
198
+ return optionalObject(args, "callerContext");
199
+ },
200
+ coreguard_profile_reference(args) {
201
+ const action = args.action;
202
+ if (action !== "make" && action !== "parse") {
203
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "action must be \"make\" or \"parse\"" };
204
+ }
205
+ if (action === "make") {
206
+ const r = requireString(args, "receiptId");
207
+ if (r) return r;
208
+ }
209
+ if (action === "parse") {
210
+ if (args.reference === undefined) return { code: ERROR_CODES.MISSING_ARGUMENT, detail: "reference is required for action=parse" };
211
+ if (!isPlainObject(args.reference) && typeof args.reference !== "string") {
212
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "reference must be an object or string for action=parse" };
213
+ }
214
+ }
215
+ return optionalObject(args, "callerContext");
216
+ },
217
+ coreguard_consumption_status(args) {
218
+ const r = requireString(args, "receiptId");
219
+ if (r) return r;
220
+ const action = args.action ?? "check";
221
+ if (!["check", "consume", "release"].includes(action)) {
222
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "action must be check, consume, or release" };
223
+ }
224
+ if (args.storePath !== undefined && (typeof args.storePath !== "string" || args.storePath.length === 0)) {
225
+ return { code: ERROR_CODES.INVALID_ARGUMENT, detail: "storePath must be a non-empty string when supplied" };
226
+ }
227
+ return optionalObject(args, "callerContext");
228
+ },
229
+ });
230
+
51
231
  function integerStringSchema(description) {
52
232
  return { type: "string", description, pattern: "^[0-9]+$" };
53
233
  }
54
234
 
235
+ const CALLER_CONTEXT_PROPERTY = {
236
+ callerContext: {
237
+ type: "object",
238
+ description: "Optional caller-provided trace/context metadata. Echoed in structuredContent.callerContext; never used as a cryptographic input.",
239
+ },
240
+ };
241
+
55
242
  const TOOLS = Object.freeze([
56
243
  {
57
244
  name: "coreguard_authorize",
@@ -64,9 +251,22 @@ const TOOLS = Object.freeze([
64
251
  policy: { type: "object", description: "CGEP/1 policy (value limit + target/recipient/selector allowlists)" },
65
252
  declaredTrace: { type: "object", description: "the exact submit-order payload the approval covers" },
66
253
  nowSeconds: integerStringSchema("pinned approval epoch (unix seconds) — never the wall clock"),
254
+ ...CALLER_CONTEXT_PROPERTY,
67
255
  },
68
256
  required: ["intent", "policy", "declaredTrace", "nowSeconds"],
69
257
  },
258
+ outputSchema: {
259
+ type: "object",
260
+ description: "CGCR/1 consent record with pinned commitments over approved bytes.",
261
+ properties: {
262
+ spec: { type: "string", description: "always CGCR/1" },
263
+ receipt: { type: "object", description: "pinned receipt commitments and timestamp" },
264
+ intent: { type: "object" },
265
+ policy: { type: "object" },
266
+ callerContext: { type: "object", description: "echoed caller context when supplied" },
267
+ },
268
+ additionalProperties: true,
269
+ },
70
270
  },
71
271
  {
72
272
  name: "coreguard_verify_consent",
@@ -74,27 +274,54 @@ const TOOLS = Object.freeze([
74
274
  "Verify a consent record's integrity and binding: recompute every commitment against the record's own approved bytes. Any tampered byte fails closed.",
75
275
  inputSchema: {
76
276
  type: "object",
77
- properties: { consent: { type: "object", description: "CGCR/1 consent record as returned by coreguard_authorize" } },
277
+ properties: {
278
+ consent: { type: "object", description: "CGCR/1 consent record as returned by coreguard_authorize" },
279
+ ...CALLER_CONTEXT_PROPERTY,
280
+ },
78
281
  required: ["consent"],
79
282
  },
283
+ outputSchema: {
284
+ type: "object",
285
+ description: "Integrity verdict for the record's own bytes; fail-closed on tamper.",
286
+ properties: {
287
+ verdict: { type: "string", description: "VERIFIED or INVALID/UNKNOWN — never SAFE" },
288
+ spec: { type: "string" },
289
+ callerContext: { type: "object" },
290
+ },
291
+ additionalProperties: true,
292
+ },
80
293
  },
81
294
  {
82
295
  name: "coreguard_verify_execution",
83
296
  description:
84
- "Verify an executed order against a consent record, fail-closed: exact execution -> VERIFIED; any drift -> INVALID with the drifted field named (AGR/1). Single-use consents are consumed by their first verified execution (process-local).",
297
+ "Verify an executed order against a consent record, fail-closed: exact execution -> VERIFIED; any drift -> INVALID with the drifted field named (AGR/1). Single-use consents are consumed by first verified execution (process-local by default; file-backed host store via AC-CS/1 when supplied by caller integration).",
85
298
  inputSchema: {
86
299
  type: "object",
87
300
  properties: {
88
301
  consent: { type: "object", description: "CGCR/1 consent record" },
89
302
  trace: { type: "object", description: "the executed order payload as observed" },
303
+ ...CALLER_CONTEXT_PROPERTY,
90
304
  },
91
305
  required: ["consent", "trace"],
92
306
  },
307
+ outputSchema: {
308
+ type: "object",
309
+ description: "Fail-closed execution verdict with AGR/1 risk report and consumption boundary.",
310
+ properties: {
311
+ spec: { type: "string", description: "AC-SDK/1" },
312
+ verdict: { type: "string", description: "VERIFIED or INVALID" },
313
+ risk: { type: "object" },
314
+ consumed: { type: "boolean" },
315
+ consumedLedger: { type: "string" },
316
+ callerContext: { type: "object" },
317
+ },
318
+ additionalProperties: true,
319
+ },
93
320
  },
94
321
  {
95
322
  name: "coreguard_assess_risk",
96
323
  description:
97
- "Classify one executed order against one approved authorization with the deterministic AGR/1 taxonomy (named classes + severities). Not a probabilistic fraud score; VERIFIED ≠ SAFE.",
324
+ "Classify one executed order against one approved authorization with the deterministic AGR/1 taxonomy. Not a probabilistic fraud score; VERIFIED ≠ SAFE.",
98
325
  inputSchema: {
99
326
  type: "object",
100
327
  properties: {
@@ -102,33 +329,254 @@ const TOOLS = Object.freeze([
102
329
  policy: { type: "object", description: "the committed policy" },
103
330
  trace: { type: "object", description: "the executed order payload" },
104
331
  consumed: { type: "boolean", description: "whether this authorization was already consumed", default: false },
332
+ ...CALLER_CONTEXT_PROPERTY,
105
333
  },
106
334
  required: ["intent", "policy", "trace"],
107
335
  },
336
+ outputSchema: {
337
+ type: "object",
338
+ description: "Deterministic AGR/1 risk report with classification, named violations, and taxonomy metadata.",
339
+ properties: {
340
+ classification: { type: "string" },
341
+ violations: { type: "array" },
342
+ callerContext: { type: "object" },
343
+ },
344
+ additionalProperties: true,
345
+ },
346
+ },
347
+ {
348
+ name: "coreguard_inspect_identity",
349
+ description:
350
+ "Inspect CG-ID/1 identity split: recordId (who) vs contentDigest (what), with optional anchor facts and optional comparison to another identity. Offline and deterministic.",
351
+ inputSchema: {
352
+ type: "object",
353
+ properties: {
354
+ issuer: { type: "string", description: "identity issuer" },
355
+ scope: { type: "string", description: "identity scope" },
356
+ subject: { type: "string", description: "identity subject" },
357
+ contentDigest: { type: "string", description: "content digest as 64-char lowercase hex (no 0x prefix)" },
358
+ anchor: { type: "object", description: "optional anchor reference" },
359
+ other: { type: "object", description: "optional other identity for comparison" },
360
+ ...CALLER_CONTEXT_PROPERTY,
361
+ },
362
+ required: ["issuer", "scope", "subject", "contentDigest"],
363
+ },
364
+ outputSchema: {
365
+ type: "object",
366
+ description: "CG-ID/1 identity view with anchor facts and optional comparison.",
367
+ properties: {
368
+ identity: { type: "object" },
369
+ anchorFacts: { type: "object" },
370
+ comparison: { type: "object" },
371
+ callerContext: { type: "object" },
372
+ },
373
+ additionalProperties: true,
374
+ },
375
+ },
376
+ {
377
+ name: "coreguard_build_attestation",
378
+ description:
379
+ "Build a CGXA/1 offline execution attestation from a consent record and executed trace. No broadcast; no chain/network contact. nowSeconds must be pinned.",
380
+ inputSchema: {
381
+ type: "object",
382
+ properties: {
383
+ consent: { type: "object", description: "CGCR/1 consent record" },
384
+ executedTrace: { type: "object", description: "executed trace observed by caller" },
385
+ adapterId: { type: "string", description: "CGXA adapter id" },
386
+ nowSeconds: { description: "pinned approval epoch (unix seconds) as non-negative integer or digit string — never wall clock", oneOf: [{ type: "integer", minimum: 0 }, { type: "string", pattern: "^[0-9]+$" }] },
387
+ ...CALLER_CONTEXT_PROPERTY,
388
+ },
389
+ required: ["consent", "executedTrace", "adapterId", "nowSeconds"],
390
+ },
391
+ outputSchema: {
392
+ type: "object",
393
+ description: "CGXA/1 offline attestation payload with attestation record and deterministic attestationId.",
394
+ properties: {
395
+ attestation: { type: "object" },
396
+ attestationId: { type: "string" },
397
+ callerContext: { type: "object" },
398
+ },
399
+ additionalProperties: true,
400
+ },
401
+ },
402
+ {
403
+ name: "coreguard_verify_attestation",
404
+ description:
405
+ "Verify a CGXA/1 attestation against its consent and executed trace. Offline, fail-closed; no chain/network contact.",
406
+ inputSchema: {
407
+ type: "object",
408
+ properties: {
409
+ attestation: { type: "object", description: "CGXA/1 attestation" },
410
+ attestationId: { type: "string", description: "attestation identifier" },
411
+ consent: { type: "object", description: "CGCR/1 consent record" },
412
+ executedTrace: { type: "object", description: "executed trace" },
413
+ ...CALLER_CONTEXT_PROPERTY,
414
+ },
415
+ required: ["attestation", "attestationId", "consent", "executedTrace"],
416
+ },
417
+ outputSchema: {
418
+ type: "object",
419
+ description: "CGXA/1 attestation verification result with deterministic verdict and boundary-aware details.",
420
+ properties: {
421
+ verdict: { type: "string" },
422
+ callerContext: { type: "object" },
423
+ },
424
+ additionalProperties: true,
425
+ },
426
+ },
427
+ {
428
+ name: "coreguard_decide_outcome",
429
+ description:
430
+ "Map a verification report to CG-OUT/1 outcome and authorization decision. ABSENT/NOT_CHECKED never render as BLOCK; VERIFIED ≠ SAFE.",
431
+ inputSchema: {
432
+ type: "object",
433
+ properties: {
434
+ report: { type: "object", description: "verification report or bridge-compatible report object" },
435
+ receiptId: { type: "string", description: "optional receipt id for profile reference" },
436
+ ...CALLER_CONTEXT_PROPERTY,
437
+ },
438
+ required: ["report"],
439
+ },
440
+ outputSchema: {
441
+ type: "object",
442
+ description: "CG-OUT/1 outcome, authorization decision, and optional profile reference.",
443
+ properties: {
444
+ outcome: { type: "object" },
445
+ decision: { type: "object" },
446
+ profileReference: { type: "object" },
447
+ callerContext: { type: "object" },
448
+ },
449
+ additionalProperties: true,
450
+ },
451
+ },
452
+ {
453
+ name: "coreguard_profile_reference",
454
+ description:
455
+ "Create or parse a CG-OUT/1 profile reference. action='make' requires receiptId; action='parse' requires reference.",
456
+ inputSchema: {
457
+ type: "object",
458
+ properties: {
459
+ action: { type: "string", enum: ["make", "parse"], description: "make or parse" },
460
+ receiptId: { type: "string", description: "receipt id for action=make" },
461
+ reference: { description: "profile reference object/string for action=parse" },
462
+ ...CALLER_CONTEXT_PROPERTY,
463
+ },
464
+ required: ["action"],
465
+ },
466
+ outputSchema: {
467
+ type: "object",
468
+ description: "CG-OUT/1 profile reference result for make or parse actions with explicit action echo.",
469
+ properties: {
470
+ action: { type: "string" },
471
+ profileReference: { type: "object" },
472
+ parsed: { type: "object" },
473
+ callerContext: { type: "object" },
474
+ },
475
+ additionalProperties: true,
476
+ },
477
+ },
478
+ {
479
+ name: "coreguard_consumption_status",
480
+ description:
481
+ "Check/consume/release a receiptId in a consumption ledger. Default is process-local (this MCP process only). If storePath is supplied (or COREGUARD_CONSUMPTION_STORE is set), uses the AC-CS/1 lock-guarded file store, which is atomic across processes on the same host. Cross-host reconciliation is CG-SPEND/1 merge; on-chain anchoring is NOT_BUILT.",
482
+ inputSchema: {
483
+ type: "object",
484
+ properties: {
485
+ receiptId: { type: "string", description: "receipt/consent identifier key" },
486
+ action: { type: "string", enum: ["check", "consume", "release"], description: "check, consume, or release", default: "check" },
487
+ storePath: { type: "string", description: "optional AC-CS/1 file-backed store path for same-host cross-process consumption (default: COREGUARD_CONSUMPTION_STORE)" },
488
+ ...CALLER_CONTEXT_PROPERTY,
489
+ },
490
+ required: ["receiptId"],
491
+ },
492
+ outputSchema: {
493
+ type: "object",
494
+ description: "Consumption status with explicit ledger boundary.",
495
+ properties: {
496
+ receiptId: { type: "string" },
497
+ action: { type: "string" },
498
+ consumed: { type: "boolean" },
499
+ ledger: { type: "string", description: "process-local or file-backed (AC-CS/1, cross-process on this host)" },
500
+ boundary: { type: "string" },
501
+ callerContext: { type: "object" },
502
+ },
503
+ additionalProperties: true,
504
+ },
108
505
  },
109
506
  ]);
110
507
 
508
+ function withCallerContext(value, args) {
509
+ if (!args?.callerContext || !isPlainObject(args.callerContext)) return value;
510
+ if (value && typeof value === "object" && !Array.isArray(value)) return { ...value, callerContext: args.callerContext };
511
+ return { value, callerContext: args.callerContext };
512
+ }
513
+
111
514
  async function callTool(name, args, { consumedSet } = {}) {
515
+ if (!TOOL_NAMES.includes(name)) return failure(ERROR_CODES.UNKNOWN_TOOL, `unknown tool: ${String(name)}`);
516
+ const a = args ?? {};
517
+ const problem = VALIDATORS[name]?.(a);
518
+ if (problem) return failure(problem.code, problem.detail);
112
519
  try {
113
- if (name === "coreguard_authorize") {
114
- const consent = await createConsent(args);
115
- return { content: [{ type: "text", text: JSON.stringify(consent, null, 2) }] };
520
+ if (name === "coreguard_authorize") return success(withCallerContext(await createConsent(a), a));
521
+ if (name === "coreguard_verify_consent") return success(withCallerContext(await verifyConsent(a.consent), a));
522
+ if (name === "coreguard_verify_execution") return success(withCallerContext(await verifyExecution(a.consent, a.trace, { consumedSet }), a));
523
+ if (name === "coreguard_assess_risk") {
524
+ return success(withCallerContext(assessRisk({ intent: a.intent, policy: a.policy, trace: a.trace, consumed: a.consumed === true }), a));
116
525
  }
117
- if (name === "coreguard_verify_consent") {
118
- const verification = await verifyConsent(args.consent);
119
- return { content: [{ type: "text", text: JSON.stringify(verification, null, 2) }] };
526
+ if (name === "coreguard_inspect_identity") {
527
+ const identity = splitIdentity({
528
+ issuer: a.issuer, scope: a.scope, subject: a.subject, contentDigest: a.contentDigest, anchor: a.anchor ?? null,
529
+ });
530
+ const facts = anchorFacts(identity);
531
+ const comparison = a.other ? compareIdentities(identity, splitIdentity(a.other)) : undefined;
532
+ return success(withCallerContext({ identity, anchorFacts: facts, ...(comparison ? { comparison } : {}) }, a));
120
533
  }
121
- if (name === "coreguard_verify_execution") {
122
- const report = await verifyExecution(args.consent, args.trace, { consumedSet });
123
- return { content: [{ type: "text", text: JSON.stringify(report, null, 2) }] };
534
+ if (name === "coreguard_build_attestation") {
535
+ const nowSeconds = typeof a.nowSeconds === "string" ? Number(a.nowSeconds) : a.nowSeconds;
536
+ const out = await buildAttestation({ consent: a.consent, executedTrace: a.executedTrace, adapterId: a.adapterId, nowSeconds });
537
+ return success(withCallerContext(out, a));
124
538
  }
125
- if (name === "coreguard_assess_risk") {
126
- const report = assessRisk({ intent: args.intent, policy: args.policy, trace: args.trace, consumed: args.consumed === true });
127
- return { content: [{ type: "text", text: JSON.stringify(report, null, 2) }] };
539
+ if (name === "coreguard_verify_attestation") {
540
+ const out = await verifyAttestation({ attestation: a.attestation, attestationId: a.attestationId, consent: a.consent, executedTrace: a.executedTrace });
541
+ return success(withCallerContext(out, a));
542
+ }
543
+ if (name === "coreguard_decide_outcome") {
544
+ const outcome = outcomeForVerificationReport(a.report);
545
+ const decision = authorizationDecision(outcome);
546
+ const profileReference = a.receiptId ? makeProfileReference({ receiptId: a.receiptId }) : undefined;
547
+ return success(withCallerContext({ outcome, decision, ...(profileReference ? { profileReference } : {}) }, a));
128
548
  }
129
- return { isError: true, content: [{ type: "text", text: `unknown tool: ${name}` }] };
549
+ if (name === "coreguard_profile_reference") {
550
+ if (a.action === "make") return success(withCallerContext({ action: "make", profileReference: makeProfileReference({ receiptId: a.receiptId }) }, a));
551
+ return success(withCallerContext({ action: "parse", parsed: parseProfileReference(a.reference) }, a));
552
+ }
553
+ if (name === "coreguard_consumption_status") {
554
+ const action = a.action ?? "check";
555
+ const key = a.receiptId;
556
+ const storePath = a.storePath ?? DEFAULT_CONSUMPTION_STORE;
557
+ if (storePath) {
558
+ const store = createConsumptionStore(storePath);
559
+ let consumed;
560
+ if (action === "consume") { consumed = store.tryAdd(key) || store.has(key); }
561
+ else if (action === "release") { store.delete(key); consumed = store.has(key); }
562
+ else consumed = store.has(key);
563
+ return success(withCallerContext({
564
+ receiptId: key, action, consumed, ledger: "file-backed (AC-CS/1, lock-guarded across processes on this host)", boundary: CONSUMPTION_STORE_BOUNDARY,
565
+ }, a));
566
+ }
567
+ const set = consumedSet ?? new Set();
568
+ let consumed;
569
+ if (action === "consume") { consumed = set.has(key); set.add(key); consumed = set.has(key); }
570
+ else if (action === "release") { set.delete(key); consumed = set.has(key); }
571
+ else consumed = set.has(key);
572
+ return success(withCallerContext({
573
+ receiptId: key, action, consumed, ledger: "process-local",
574
+ boundary: "process-local only; set storePath or COREGUARD_CONSUMPTION_STORE for the AC-CS/1 file ledger (cross-process on this host); cross-host sync is CG-SPEND/1 merge; on-chain anchoring NOT_BUILT",
575
+ }, a));
576
+ }
577
+ return failure(ERROR_CODES.UNKNOWN_TOOL, `unknown tool: ${String(name)}`);
130
578
  } catch (err) {
131
- return { isError: true, content: [{ type: "text", text: `tool error: ${err?.message ?? String(err)}` }] };
579
+ return failure(ERROR_CODES.TOOL_ERROR, err?.message ?? String(err));
132
580
  }
133
581
  }
134
582
 
@@ -179,7 +627,7 @@ export function createMcpHandler({ write } = {}) {
179
627
  if (method === "tools/call") {
180
628
  const name = params?.name;
181
629
  if (!TOOL_NAMES.includes(name)) {
182
- return respond({ result: { isError: true, content: [{ type: "text", text: `unknown tool: ${String(name)}` }] } });
630
+ return respond({ result: failure(ERROR_CODES.UNKNOWN_TOOL, `unknown tool: ${String(name)}`) });
183
631
  }
184
632
  const result = await callTool(name, params?.arguments ?? {}, { consumedSet: consumed });
185
633
  return respond({ result });
@@ -190,13 +638,20 @@ export function createMcpHandler({ write } = {}) {
190
638
 
191
639
  export function selfCheck() {
192
640
  return [
193
- ["tools exposed", TOOL_NAMES.join(",") === "coreguard_authorize,coreguard_verify_consent,coreguard_verify_execution,coreguard_assess_risk"],
641
+ ["tools exposed", TOOL_NAMES.length === 10 && TOOL_NAMES[0] === "coreguard_authorize" && TOOL_NAMES[9] === "coreguard_consumption_status"],
194
642
  ["protocol version pinned", PROTOCOL_VERSION === "2025-06-18"],
195
643
  ["spec surfaced", CONSENT_SPEC === "CGCR/1" && AGENT_COMMERCE_VERSION === "AC-SDK/1"],
196
644
  ["boundary travels", SERVER_BOUNDARY.includes("VERIFIED ≠ SAFE") && SERVER_BOUNDARY.includes("NOT_BUILT")],
645
+ ["version has one source", SERVER_INFO.version === PACKAGE.version],
646
+ ["every tool declares an output schema", TOOLS.every((t) => t.outputSchema?.type === "object")],
647
+ ["every tool declares required inputs", TOOLS.every((t) => Array.isArray(t.inputSchema?.required) && t.inputSchema.required.length > 0)],
648
+ ["error contract is exported", ERROR_CODES.MISSING_ARGUMENT === "MISSING_ARGUMENT"],
649
+ ["caller context supported", TOOLS.every((t) => t.inputSchema?.properties?.callerContext?.type === "object")],
197
650
  ];
198
651
  }
199
652
 
653
+ export { SERVER_INFO, PROTOCOL_VERSION, TOOLS };
654
+
200
655
  export async function main() {
201
656
  const handle = createMcpHandler();
202
657
  const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });