@coreguard/agent-commerce 0.1.5 → 0.2.1
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/README.md +31 -2
- package/bin/trust-card.mjs +12 -0
- package/mcp.mjs +34 -3
- package/observations.mjs +24 -3
- package/package.json +10 -4
- package/server.json +3 -3
- package/trust-card-cli.mjs +289 -0
- package/trust-card.mjs +252 -0
- package/wave3.mjs +1173 -0
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ bytes approved, and for verifying any executed trace against that receipt.
|
|
|
12
12
|
- **Fail-closed execution verification** — a consent plus an executed trace
|
|
13
13
|
yields a verdict with named drift classes (AGR/1 taxonomy); incomplete or
|
|
14
14
|
ambiguous evidence is never treated as a pass.
|
|
15
|
-
- **stdio MCP server** (JSON-RPC 2.0, protocol `2025-06-18`) exposing
|
|
15
|
+
- **stdio MCP server** (JSON-RPC 2.0, protocol `2025-06-18`) exposing forty-six tools,
|
|
16
16
|
all offline, all deterministic, zero keys.
|
|
17
17
|
|
|
18
18
|
MIT. Node ≥ 18. No network calls, no stored credentials, no wall clock.
|
|
@@ -217,6 +217,35 @@ These 10 tools extend CoreGuard into x402/machine/delegation evidence flows. **B
|
|
|
217
217
|
| `coreguard_revoke_consent` | `decideApproval` / `revokeAgent` / `revokePolicy` |
|
|
218
218
|
| `coreguard_audit_transaction` | `auditReport` with optional filters |
|
|
219
219
|
|
|
220
|
+
### Wave 3 — reasoning, supply chain, evidence, operations (CG-W3/1)
|
|
221
|
+
|
|
222
|
+
20 deterministic tools that answer questions the receipt layer could only imply. All offline, zero keys, no wall clock in any commitment.
|
|
223
|
+
|
|
224
|
+
| Tool | Purpose |
|
|
225
|
+
|---|---|
|
|
226
|
+
| `coreguard_compile_policy` | Compile a compact spend spec into a canonical CGEP/1 policy + stable digest. |
|
|
227
|
+
| `coreguard_explain_decision` | Per-rule verdict plus the smallest single change that clears the first block. |
|
|
228
|
+
| `coreguard_simulate_spend` | Dry-run a batch against a policy; no state written. |
|
|
229
|
+
| `coreguard_diff_policies` | Rule-level diff, limit delta, tightness, re-consent flag. |
|
|
230
|
+
| `coreguard_generate_boundary_cases` | At/±1 the limit, unlisted target/recipient, closed window, wrong currency — verdicts computed by the engine. |
|
|
231
|
+
| `coreguard_audit_server_manifest` | Risk card for a third-party MCP `server.json` before install. |
|
|
232
|
+
| `coreguard_scan_tool_descriptions` | Byte-level scan for bidi/tag/zero-width characters, HTML comments, imperative payloads. |
|
|
233
|
+
| `coreguard_check_lookalike` | Homoglyph, mixed-script and punycode impersonation check. |
|
|
234
|
+
| `coreguard_diff_tool_surface` | Rug-pull detector between two `tools/list` snapshots. |
|
|
235
|
+
| `coreguard_verify_evidence_bundle` | Recompute bundle + item digests offline. |
|
|
236
|
+
| `coreguard_redact_receipt` | Share a receipt with a redaction manifest and both digests. |
|
|
237
|
+
| `coreguard_attest_batch` | Merkle root + per-item inclusion proofs over many receipts. |
|
|
238
|
+
| `coreguard_verify_batch_proof` | Offline inclusion proof verification. |
|
|
239
|
+
| `coreguard_freeze_agent` | Revoke an agent and reject its open approvals in one audited operation. |
|
|
240
|
+
| `coreguard_budget_runway` | Straight-line runway from pinned inputs; exhaustion epoch. |
|
|
241
|
+
| `coreguard_detect_spend_anomaly` | Median/MAD outlier scan with explicit threshold. |
|
|
242
|
+
| `coreguard_incident_timeline` | Sequence-ordered ledger events, gaps and chain status. |
|
|
243
|
+
| `coreguard_translate_receipt` | Structural ACP/x402/CGCR mapping with an explicit loss list. |
|
|
244
|
+
| `coreguard_emit_test_vectors` | Integration vectors with the verdicts the enforcer computes. |
|
|
245
|
+
| `coreguard_describe_surface` | Capability card/badge a directory can quote verbatim. |
|
|
246
|
+
|
|
247
|
+
**Wave 3 boundary:** every answer is arithmetic over caller-supplied JSON. A finding is evidence for a human decision, not a verdict on a third party; the manifest and description audits do not execute the server. `VERIFIED ≠ SAFE`.
|
|
248
|
+
|
|
220
249
|
## Errors
|
|
221
250
|
|
|
222
251
|
Failures are tool results, never exceptions and never a process exit:
|
|
@@ -320,7 +349,7 @@ License: MIT.
|
|
|
320
349
|
|
|
321
350
|
## Release readiness / MCPRush evidence
|
|
322
351
|
|
|
323
|
-
- **Release notes:** `docs/releases/0.1.
|
|
352
|
+
- **Release notes:** `docs/releases/0.2.1.md` (latest) · `docs/releases/0.2.0.md`
|
|
324
353
|
- **Publish readiness checklist:** `docs/releases/0.1.3-publish-readiness.md`
|
|
325
354
|
- **Security & threat model:** `docs/agent-commerce-mcp-security.md`
|
|
326
355
|
- **Client compatibility matrix + run log:** `docs/agent-commerce-mcp-compatibility.md`
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* bin wrapper — coreguard-trust-card
|
|
4
|
+
*
|
|
5
|
+
* MCP server listings get a publishable trust card from one command:
|
|
6
|
+
* npx -y @coreguard/agent-commerce trust-card --server-json server.json --stdio "npx -y @scope/server"
|
|
7
|
+
*/
|
|
8
|
+
import { runTrustCardCli } from "../trust-card-cli.mjs";
|
|
9
|
+
|
|
10
|
+
runTrustCardCli().then(({ code }) => {
|
|
11
|
+
process.exitCode = code;
|
|
12
|
+
});
|
package/mcp.mjs
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* (one JSON object per line, both directions) — the same shape MCP clients
|
|
8
8
|
* speak for stdio servers.
|
|
9
9
|
*
|
|
10
|
-
* Tools (all offline/self-hosted, deterministic, zero network keys): 10 core consent/verification tools + 10 Wave 1 Machine Economy tools + 6 Wave 2 CGCP/1 mapping tools (intent/receipt/limits/revoke/audit) =
|
|
10
|
+
* Tools (all offline/self-hosted, deterministic, zero network keys): 10 core consent/verification tools + 10 Wave 1 Machine Economy tools + 6 Wave 2 CGCP/1 mapping tools (intent/receipt/limits/revoke/audit) + 20 Wave 3 tools (policy reasoning, MCP supply-chain audit, evidence, operations, interop) = 46 total. Optional trust roots enable Ed25519 signature verification for telemetry/delegation; no custody, no broadcast, no network calls; external settlement/physical truth/device identity beyond supplied key material NOT proven.
|
|
11
11
|
*
|
|
12
12
|
* BOUNDARIES (standing): synthetic demo data is the caller's; nothing here
|
|
13
13
|
* contacts any platform or payment network (no contact/integration/endorsement
|
|
@@ -57,6 +57,7 @@ import {
|
|
|
57
57
|
MACHINE_ECONOMY_BOUNDARY,
|
|
58
58
|
} from "./machine-economy.mjs";
|
|
59
59
|
import { createIntent, issueReceipt, verifyReceipt as verifyCgcpReceipt, checkLimits, revokeConsent, auditTransaction, CGCP_MCP_BOUNDARY } from "./cgcp-mcp-tools.mjs";
|
|
60
|
+
import { WAVE3_TOOLS, WAVE3_HANDLERS, WAVE3_VALIDATORS, WAVE3_BOUNDARY } from "./wave3.mjs";
|
|
60
61
|
|
|
61
62
|
const PROTOCOL_VERSION = "2025-06-18";
|
|
62
63
|
|
|
@@ -104,6 +105,28 @@ const TOOL_NAMES = Object.freeze([
|
|
|
104
105
|
"coreguard_check_limits",
|
|
105
106
|
"coreguard_revoke_consent",
|
|
106
107
|
"coreguard_audit_transaction",
|
|
108
|
+
// Wave 3 (CG-W3/1) — deterministic policy reasoning, MCP supply-chain audit,
|
|
109
|
+
// evidence, operations and interop. Same transport, same error contract.
|
|
110
|
+
"coreguard_compile_policy",
|
|
111
|
+
"coreguard_explain_decision",
|
|
112
|
+
"coreguard_simulate_spend",
|
|
113
|
+
"coreguard_diff_policies",
|
|
114
|
+
"coreguard_generate_boundary_cases",
|
|
115
|
+
"coreguard_audit_server_manifest",
|
|
116
|
+
"coreguard_scan_tool_descriptions",
|
|
117
|
+
"coreguard_check_lookalike",
|
|
118
|
+
"coreguard_diff_tool_surface",
|
|
119
|
+
"coreguard_verify_evidence_bundle",
|
|
120
|
+
"coreguard_redact_receipt",
|
|
121
|
+
"coreguard_attest_batch",
|
|
122
|
+
"coreguard_verify_batch_proof",
|
|
123
|
+
"coreguard_freeze_agent",
|
|
124
|
+
"coreguard_budget_runway",
|
|
125
|
+
"coreguard_detect_spend_anomaly",
|
|
126
|
+
"coreguard_incident_timeline",
|
|
127
|
+
"coreguard_translate_receipt",
|
|
128
|
+
"coreguard_emit_test_vectors",
|
|
129
|
+
"coreguard_describe_surface",
|
|
107
130
|
]);
|
|
108
131
|
|
|
109
132
|
/**
|
|
@@ -157,6 +180,7 @@ function requireString(args, key) {
|
|
|
157
180
|
|
|
158
181
|
/** Per-tool input validation. Returns null when the arguments are usable. */
|
|
159
182
|
const VALIDATORS = Object.freeze({
|
|
183
|
+
...WAVE3_VALIDATORS,
|
|
160
184
|
coreguard_authorize(args) {
|
|
161
185
|
const missing = requireObjects(args, ["intent", "policy", "declaredTrace"]);
|
|
162
186
|
if (missing) return missing;
|
|
@@ -660,6 +684,7 @@ const TOOLS = Object.freeze([
|
|
|
660
684
|
inputSchema: { type: "object", properties: { storePath: { type: "string" }, txRef: { type: "string" }, approvalId: { type: "string" }, agentId: { type: "string" }, limit: { type: "integer", minimum: 1 }, ...CALLER_CONTEXT_PROPERTY }, required: ["storePath"] },
|
|
661
685
|
outputSchema: { type: "object", description: "CGCP/1 audit report with chain status and optional filters.", properties: { type: { type: "string" }, spec: { type: "string" }, report: { type: "object" }, mapping: { type: "string" }, boundary: { type: "string" }, callerContext: { type: "object" } }, additionalProperties: true },
|
|
662
686
|
},
|
|
687
|
+
...WAVE3_TOOLS,
|
|
663
688
|
]);
|
|
664
689
|
|
|
665
690
|
function withCallerContext(value, args) {
|
|
@@ -747,6 +772,10 @@ async function callTool(name, args, { consumedSet } = {}) {
|
|
|
747
772
|
if (name === "coreguard_check_limits") return success(withCallerContext(checkLimits(a), a));
|
|
748
773
|
if (name === "coreguard_revoke_consent") return success(withCallerContext(revokeConsent(a), a));
|
|
749
774
|
if (name === "coreguard_audit_transaction") return success(withCallerContext(auditTransaction(a), a));
|
|
775
|
+
if (WAVE3_HANDLERS[name]) {
|
|
776
|
+
const ctx = { toolNames: TOOL_NAMES, version: PACKAGE.version, serverName: SERVER_INFO.name, protocolVersion: PROTOCOL_VERSION };
|
|
777
|
+
return success(withCallerContext(WAVE3_HANDLERS[name](a, ctx), a));
|
|
778
|
+
}
|
|
750
779
|
return failure(ERROR_CODES.UNKNOWN_TOOL, `unknown tool: ${String(name)}`);
|
|
751
780
|
} catch (err) {
|
|
752
781
|
return failure(ERROR_CODES.TOOL_ERROR, err?.message ?? String(err));
|
|
@@ -811,7 +840,9 @@ export function createMcpHandler({ write } = {}) {
|
|
|
811
840
|
|
|
812
841
|
export function selfCheck() {
|
|
813
842
|
return [
|
|
814
|
-
["tools exposed", TOOL_NAMES.length ===
|
|
843
|
+
["tools exposed", TOOL_NAMES.length === 46 && TOOL_NAMES[0] === "coreguard_authorize" && TOOL_NAMES[9] === "coreguard_consumption_status" && TOOL_NAMES[19] === "coreguard_verify_delegation_chain" && TOOL_NAMES[25] === "coreguard_audit_transaction" && TOOL_NAMES[45] === "coreguard_describe_surface"],
|
|
844
|
+
["wave 3 declares schemas for every tool", WAVE3_TOOLS.length === 20 && WAVE3_TOOLS.every((t) => t.name.startsWith("coreguard_") && t.inputSchema?.required?.length > 0 && t.outputSchema?.type === "object" && WAVE3_HANDLERS[t.name])],
|
|
845
|
+
["wave 3 boundary travels", WAVE3_BOUNDARY.includes("VERIFIED ≠ SAFE")],
|
|
815
846
|
["protocol version pinned", PROTOCOL_VERSION === "2025-06-18"],
|
|
816
847
|
["spec surfaced", CONSENT_SPEC === "CGCR/1" && AGENT_COMMERCE_VERSION === "AC-SDK/1"],
|
|
817
848
|
["boundary travels", SERVER_BOUNDARY.includes("VERIFIED ≠ SAFE") && SERVER_BOUNDARY.includes("NOT_BUILT")],
|
|
@@ -824,7 +855,7 @@ export function selfCheck() {
|
|
|
824
855
|
];
|
|
825
856
|
}
|
|
826
857
|
|
|
827
|
-
export { SERVER_INFO, PROTOCOL_VERSION, TOOLS };
|
|
858
|
+
export { SERVER_INFO, PROTOCOL_VERSION, TOOLS, TOOL_NAMES };
|
|
828
859
|
|
|
829
860
|
export async function main() {
|
|
830
861
|
const handle = createMcpHandler();
|
package/observations.mjs
CHANGED
|
@@ -383,22 +383,32 @@ export function accrue(ledger, { action_id, subject_digest } = {}) {
|
|
|
383
383
|
|
|
384
384
|
const observers = [...byObserver.values()].map((entry) => {
|
|
385
385
|
const latest = entry.history[entry.history.length - 1];
|
|
386
|
+
const lastVerified = [...entry.history].reverse().find((e) => e.outcome === "verified") ?? null;
|
|
387
|
+
const failedAfterVerified = lastVerified
|
|
388
|
+
? entry.history.some((e) => at(e) > at(lastVerified) && e.outcome === "verification_failed")
|
|
389
|
+
: false;
|
|
386
390
|
return Object.freeze({
|
|
387
391
|
observer: entry.observer,
|
|
388
392
|
latest_outcome: latest.outcome,
|
|
389
393
|
latest_code: latest.code,
|
|
390
394
|
latest_reason: latest.reason,
|
|
391
395
|
latest_checked_at: latest.checked_at,
|
|
396
|
+
verified_at: lastVerified?.checked_at ?? null,
|
|
397
|
+
verified_observation_id: lastVerified?.observation_id ?? null,
|
|
398
|
+
confirmation_stands: lastVerified !== null && !failedAfterVerified,
|
|
392
399
|
scopes: Object.freeze([...entry.scopes]),
|
|
393
400
|
reads: entry.history.length,
|
|
394
401
|
observation_ids: Object.freeze(entry.history.map((e) => e.observation_id)),
|
|
395
402
|
});
|
|
396
403
|
});
|
|
397
404
|
|
|
398
|
-
|
|
405
|
+
// A confirmation stands unless the same observer later refused the bytes.
|
|
406
|
+
// Losing access after a verified read is not a contradiction: the observer
|
|
407
|
+
// matched the bytes earlier and cannot fetch them now — both true.
|
|
408
|
+
const verifiedBy = observers.filter((o) => o.confirmation_stands).map((o) => o.observer);
|
|
399
409
|
const notCheckedBy = observers
|
|
400
410
|
.filter((o) => o.latest_outcome === "not_checked")
|
|
401
|
-
.map((o) => Object.freeze({ observer: o.observer, reason: o.latest_reason, at: o.latest_checked_at }));
|
|
411
|
+
.map((o) => Object.freeze({ observer: o.observer, reason: o.latest_reason, at: o.latest_checked_at, confirmed_before: o.confirmation_stands }));
|
|
402
412
|
const failedBy = observers.filter((o) => o.latest_outcome === "verification_failed").map((o) => o.observer);
|
|
403
413
|
const absentBy = observers.filter((o) => o.latest_outcome === "absent").map((o) => o.observer);
|
|
404
414
|
|
|
@@ -456,10 +466,21 @@ export function describeAccrual(accrual) {
|
|
|
456
466
|
// bytes", and burying that after two observers who could not read invites the
|
|
457
467
|
// reader to scan for the refusal and stop there.
|
|
458
468
|
const ordered = [...accrual.observers].sort((a, b) => {
|
|
459
|
-
const rank = (o) => (o.
|
|
469
|
+
const rank = (o) => (o.confirmation_stands ? 0 : o.latest_outcome === "not_checked" ? 2 : 1);
|
|
460
470
|
return rank(a) - rank(b) || a.observer.localeCompare(b.observer);
|
|
461
471
|
});
|
|
462
472
|
const parts = ordered.map((o) => {
|
|
473
|
+
if (o.confirmation_stands && o.latest_outcome !== "verified") {
|
|
474
|
+
const tail =
|
|
475
|
+
o.latest_outcome === "not_checked"
|
|
476
|
+
? `later did not check (${o.latest_reason}) at ${o.latest_checked_at}`
|
|
477
|
+
: o.latest_outcome === "verification_failed"
|
|
478
|
+
? `later refused (${o.latest_code}) at ${o.latest_checked_at}`
|
|
479
|
+
: o.latest_outcome === "absent"
|
|
480
|
+
? `later found nothing to read at ${o.latest_checked_at}`
|
|
481
|
+
: `later could not resolve the record at ${o.latest_checked_at}`;
|
|
482
|
+
return `${o.observer} matched the bytes at ${o.verified_at}; ${tail}`;
|
|
483
|
+
}
|
|
463
484
|
const verb =
|
|
464
485
|
o.latest_outcome === "verified"
|
|
465
486
|
? "matched the bytes"
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coreguard/agent-commerce",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "CoreGuard Agent Commerce: consent receipts (CGCR/1) and fail-closed execution verification (AGR/1) for agentic purchases — SDK, REST surface, and a stdio MCP server (46 tools, JSON-RPC 2.0, offline, zero keys)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
|
7
7
|
"exports": {
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"./client.mjs": "./client.mjs",
|
|
12
12
|
"./firewall.mjs": "./firewall.mjs",
|
|
13
13
|
"./risk.mjs": "./risk.mjs",
|
|
14
|
+
"./trust-card.mjs": "./trust-card.mjs",
|
|
14
15
|
"./risk-cli.mjs": "./risk-cli.mjs",
|
|
15
16
|
"./outcomes.mjs": "./outcomes.mjs",
|
|
16
17
|
"./outcomes-bridge.mjs": "./outcomes-bridge.mjs",
|
|
@@ -38,7 +39,8 @@
|
|
|
38
39
|
"./cgcp-mcp-tools.mjs": "./cgcp-mcp-tools.mjs"
|
|
39
40
|
},
|
|
40
41
|
"bin": {
|
|
41
|
-
"coreguard-agent-commerce-mcp": "./bin/mcp.mjs"
|
|
42
|
+
"coreguard-agent-commerce-mcp": "./bin/mcp.mjs",
|
|
43
|
+
"coreguard-trust-card": "./bin/trust-card.mjs"
|
|
42
44
|
},
|
|
43
45
|
"files": [
|
|
44
46
|
"aer1.mjs",
|
|
@@ -77,7 +79,11 @@
|
|
|
77
79
|
"risk.mjs",
|
|
78
80
|
"server.json",
|
|
79
81
|
"spend.mjs",
|
|
80
|
-
"trust.mjs"
|
|
82
|
+
"trust.mjs",
|
|
83
|
+
"trust-card-cli.mjs",
|
|
84
|
+
"trust-card.mjs",
|
|
85
|
+
"bin/trust-card.mjs",
|
|
86
|
+
"wave3.mjs"
|
|
81
87
|
],
|
|
82
88
|
"engines": {
|
|
83
89
|
"node": ">=18"
|
package/server.json
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "io.github.EslaM-X/coreguard-agent-commerce",
|
|
4
|
-
"description": "Fail-closed consent receipts and execution verification for agentic purchases.
|
|
4
|
+
"description": "Fail-closed consent receipts and execution verification for agentic purchases. 46 MCP tools.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"url": "https://github.com/coreguard-global/CoreGuard",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "0.1
|
|
9
|
+
"version": "0.2.1",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "@coreguard/agent-commerce",
|
|
14
|
-
"version": "0.1
|
|
14
|
+
"version": "0.2.1",
|
|
15
15
|
"transport": {
|
|
16
16
|
"type": "stdio"
|
|
17
17
|
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* coreguard-trust-card — one command, one publishable trust card.
|
|
4
|
+
*
|
|
5
|
+
* coreguard-trust-card --server-json server.json --tools-list tools.json --out trust-card.md
|
|
6
|
+
* coreguard-trust-card --server-json server.json --stdio "npx -y @scope/server" --out card.md
|
|
7
|
+
*
|
|
8
|
+
* Inputs:
|
|
9
|
+
* --server-json <file> an MCP registry record (server.json)
|
|
10
|
+
* --tools-list <file> a tools/list result: array, {tools:[...]} or JSON-RPC
|
|
11
|
+
* --stdio "<command>" alternatively, run a stdio MCP server and read tools/list
|
|
12
|
+
* --name <label> override the name printed on the card
|
|
13
|
+
* --date <YYYY-MM-DD> card date; omitted by default so runs stay byte-identical
|
|
14
|
+
* --url <https://…> published card URL, embedded in the paste-ready summary
|
|
15
|
+
* --out <file|-> markdown destination (default: stdout)
|
|
16
|
+
* --json <file> also write the machine-readable sidecar
|
|
17
|
+
* --tools-out <file> also write the normalised tools/list used for the card
|
|
18
|
+
* --check do not write: fail if the existing --out/--json files differ
|
|
19
|
+
* --fail-on none|medium|high gate (default none; the GitHub Action defaults to high)
|
|
20
|
+
* --timeout <ms> stdio handshake timeout (default 45000)
|
|
21
|
+
*
|
|
22
|
+
* Exit codes:
|
|
23
|
+
* 0 card generated (and the gate, if any, passed)
|
|
24
|
+
* 1 gate tripped, or --check found drift
|
|
25
|
+
* 2 usage or input error — no card is written
|
|
26
|
+
*
|
|
27
|
+
* Offline by construction except for an explicitly requested --stdio command,
|
|
28
|
+
* which runs locally. No wall clock is read; --date is caller-supplied.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
32
|
+
import { dirname, resolve } from "node:path";
|
|
33
|
+
import { fileURLToPath } from "node:url";
|
|
34
|
+
import { spawn } from "node:child_process";
|
|
35
|
+
|
|
36
|
+
import { buildTrustCard, parseToolsList, toolsListShape, exitCodeFor, TRUST_CARD_SPEC } from "./trust-card.mjs";
|
|
37
|
+
|
|
38
|
+
const USAGE = `coreguard-trust-card (${TRUST_CARD_SPEC})
|
|
39
|
+
|
|
40
|
+
usage:
|
|
41
|
+
coreguard-trust-card --server-json <file> (--tools-list <file> | --stdio "<command>") [options]
|
|
42
|
+
|
|
43
|
+
required:
|
|
44
|
+
--server-json <file> MCP registry server record
|
|
45
|
+
one of:
|
|
46
|
+
--tools-list <file> tools/list JSON (array, {tools} or JSON-RPC response)
|
|
47
|
+
--stdio "<command>" run a stdio MCP server and request tools/list
|
|
48
|
+
|
|
49
|
+
options:
|
|
50
|
+
--name <label> override the server name on the card
|
|
51
|
+
--date <YYYY-MM-DD> card date (omitted by default: output stays deterministic)
|
|
52
|
+
--url <https://…> published card URL in the paste-ready summary
|
|
53
|
+
--out <file|-> markdown destination (default stdout)
|
|
54
|
+
--json <file> machine-readable sidecar
|
|
55
|
+
--tools-out <file> normalised tools/list used for the card
|
|
56
|
+
--check compare with existing --out/--json instead of writing
|
|
57
|
+
--fail-on none|medium|high exit 1 at this verdict (default none)
|
|
58
|
+
--timeout <ms> stdio handshake timeout (default 45000)
|
|
59
|
+
-h, --help
|
|
60
|
+
|
|
61
|
+
exit: 0 card produced · 1 gate tripped or drift · 2 usage/input error`;
|
|
62
|
+
|
|
63
|
+
function usageError(message) {
|
|
64
|
+
const err = new Error(message);
|
|
65
|
+
err.code = 2;
|
|
66
|
+
return err;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function parseArgs(argv) {
|
|
70
|
+
const opts = { out: "-", failOn: "none", timeout: 45000, check: false };
|
|
71
|
+
for (let i = 0; i < argv.length; i++) {
|
|
72
|
+
const a = argv[i];
|
|
73
|
+
const next = () => {
|
|
74
|
+
const v = argv[++i];
|
|
75
|
+
if (v === undefined) throw usageError(`${a} needs a value`);
|
|
76
|
+
return v;
|
|
77
|
+
};
|
|
78
|
+
if (a === "--server-json") opts.serverJson = next();
|
|
79
|
+
else if (a === "--tools-list") opts.toolsList = next();
|
|
80
|
+
else if (a === "--stdio") opts.stdio = next();
|
|
81
|
+
else if (a === "--name") opts.name = next();
|
|
82
|
+
else if (a === "--date") opts.date = next();
|
|
83
|
+
else if (a === "--url") opts.url = next();
|
|
84
|
+
else if (a === "--out") opts.out = next();
|
|
85
|
+
else if (a === "--json") opts.jsonOut = next();
|
|
86
|
+
else if (a === "--tools-out") opts.toolsOut = next();
|
|
87
|
+
else if (a === "--fail-on") opts.failOn = next();
|
|
88
|
+
else if (a === "--timeout") opts.timeout = Number(next());
|
|
89
|
+
else if (a === "--check") opts.check = true;
|
|
90
|
+
else if (a === "--help" || a === "-h") opts.help = true;
|
|
91
|
+
else throw usageError(`unknown argument: ${a}`);
|
|
92
|
+
}
|
|
93
|
+
return opts;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function readJson(file, label) {
|
|
97
|
+
let text;
|
|
98
|
+
try {
|
|
99
|
+
text = readFileSync(resolve(file), "utf8");
|
|
100
|
+
} catch (err) {
|
|
101
|
+
throw usageError(`${label}: cannot read ${file}: ${err?.message ?? err}`);
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
return { text, value: JSON.parse(text) };
|
|
105
|
+
} catch (err) {
|
|
106
|
+
throw usageError(`${label}: ${file} is not valid JSON: ${err?.message ?? err}`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Minimal stdio MCP handshake: initialize, initialized, tools/list.
|
|
112
|
+
* Anything the server writes on stderr is kept for the failure message.
|
|
113
|
+
*/
|
|
114
|
+
export function captureToolsList(command, { timeoutMs = 45000, spawnImpl = spawn } = {}) {
|
|
115
|
+
return new Promise((resolvePromise, reject) => {
|
|
116
|
+
const child = spawnImpl(command, { shell: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
117
|
+
let stdout = "";
|
|
118
|
+
let stderr = "";
|
|
119
|
+
let done = false;
|
|
120
|
+
let initialized = false;
|
|
121
|
+
const timer = setTimeout(() => finish(new Error(`stdio handshake timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
122
|
+
|
|
123
|
+
const send = (message) => {
|
|
124
|
+
child.stdin.write(JSON.stringify(message) + "\n");
|
|
125
|
+
};
|
|
126
|
+
function finish(err, value) {
|
|
127
|
+
if (done) return;
|
|
128
|
+
done = true;
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
try {
|
|
131
|
+
child.stdin.end();
|
|
132
|
+
child.kill("SIGTERM");
|
|
133
|
+
} catch {
|
|
134
|
+
/* already gone */
|
|
135
|
+
}
|
|
136
|
+
if (err) reject(err);
|
|
137
|
+
else resolvePromise(value);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
child.on("error", (err) => finish(new Error(`cannot start stdio command: ${err?.message ?? err}`)));
|
|
141
|
+
child.on("exit", (code) => {
|
|
142
|
+
if (!done) finish(new Error(`stdio server exited (code ${code}) before returning tools/list${stderr ? `: ${stderr.trim().slice(-400)}` : ""}`));
|
|
143
|
+
});
|
|
144
|
+
child.stderr.on("data", (chunk) => {
|
|
145
|
+
stderr += chunk;
|
|
146
|
+
});
|
|
147
|
+
child.stdout.on("data", (chunk) => {
|
|
148
|
+
stdout += chunk;
|
|
149
|
+
let newline;
|
|
150
|
+
while ((newline = stdout.indexOf("\n")) !== -1) {
|
|
151
|
+
const line = stdout.slice(0, newline).trim();
|
|
152
|
+
stdout = stdout.slice(newline + 1);
|
|
153
|
+
if (!line) continue;
|
|
154
|
+
let msg;
|
|
155
|
+
try {
|
|
156
|
+
msg = JSON.parse(line);
|
|
157
|
+
} catch {
|
|
158
|
+
continue; // servers may log on stdout; only JSON-RPC lines matter
|
|
159
|
+
}
|
|
160
|
+
if (msg.id === 1 && msg.result && !initialized) {
|
|
161
|
+
initialized = true;
|
|
162
|
+
send({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
163
|
+
send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} });
|
|
164
|
+
} else if (msg.id === 2) {
|
|
165
|
+
if (msg.error) return finish(new Error(`tools/list failed: ${JSON.stringify(msg.error)}`));
|
|
166
|
+
if (!Array.isArray(msg.result?.tools)) return finish(new Error("tools/list result has no tools array"));
|
|
167
|
+
finish(null, msg.result.tools);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
send({
|
|
173
|
+
jsonrpc: "2.0",
|
|
174
|
+
id: 1,
|
|
175
|
+
method: "initialize",
|
|
176
|
+
params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "coreguard-trust-card", version: "1.0.0" } },
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function ensureDir(file) {
|
|
182
|
+
mkdirSync(dirname(resolve(file)), { recursive: true });
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function compare(file, expected, label) {
|
|
186
|
+
let actual;
|
|
187
|
+
try {
|
|
188
|
+
actual = readFileSync(resolve(file), "utf8");
|
|
189
|
+
} catch {
|
|
190
|
+
throw usageError(`${label}: ${file} does not exist yet — run the command without --check`);
|
|
191
|
+
}
|
|
192
|
+
if (actual !== expected) {
|
|
193
|
+
const err = new Error(`${label}: ${file} is stale — regenerate it with this command`);
|
|
194
|
+
err.code = 1;
|
|
195
|
+
throw err;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
export async function runTrustCardCli(argv = process.argv.slice(2), io = {}) {
|
|
200
|
+
const log = io.log ?? ((s) => process.stdout.write(String(s) + "\n"));
|
|
201
|
+
const err = io.err ?? ((s) => process.stderr.write(String(s) + "\n"));
|
|
202
|
+
let opts;
|
|
203
|
+
try {
|
|
204
|
+
opts = parseArgs(argv);
|
|
205
|
+
} catch (error) {
|
|
206
|
+
err(`trust-card: ${error.message}`);
|
|
207
|
+
err(USAGE);
|
|
208
|
+
return { code: 2 };
|
|
209
|
+
}
|
|
210
|
+
if (opts.help) {
|
|
211
|
+
log(USAGE);
|
|
212
|
+
return { code: 0 };
|
|
213
|
+
}
|
|
214
|
+
if (!opts.serverJson) {
|
|
215
|
+
err("trust-card: --server-json <file> is required");
|
|
216
|
+
return { code: 2 };
|
|
217
|
+
}
|
|
218
|
+
if (Boolean(opts.toolsList) === Boolean(opts.stdio)) {
|
|
219
|
+
err("trust-card: pass exactly one of --tools-list <file> or --stdio \"<command>\" — a card without a scanned tool surface is not issued");
|
|
220
|
+
return { code: 2 };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
const { value: manifest } = readJson(opts.serverJson, "server.json");
|
|
225
|
+
let tools;
|
|
226
|
+
let toolsShape;
|
|
227
|
+
let toolsLabel;
|
|
228
|
+
if (opts.toolsList) {
|
|
229
|
+
const { value } = readJson(opts.toolsList, "tools/list");
|
|
230
|
+
tools = parseToolsList(value);
|
|
231
|
+
toolsShape = toolsListShape(value);
|
|
232
|
+
toolsLabel = opts.toolsList;
|
|
233
|
+
} else {
|
|
234
|
+
tools = await captureToolsList(opts.stdio, { timeoutMs: opts.timeout });
|
|
235
|
+
toolsShape = "json-rpc";
|
|
236
|
+
toolsLabel = `stdio: ${opts.stdio}`;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const card = buildTrustCard({
|
|
240
|
+
manifest,
|
|
241
|
+
tools,
|
|
242
|
+
name: opts.name,
|
|
243
|
+
date: opts.date,
|
|
244
|
+
url: opts.url,
|
|
245
|
+
toolsShape,
|
|
246
|
+
sources: { manifest: opts.serverJson, tools: toolsLabel },
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
const jsonText = JSON.stringify(card.json, null, 2) + "\n";
|
|
250
|
+
if (opts.check) {
|
|
251
|
+
if (opts.out === "-") throw usageError("--check needs --out <file>");
|
|
252
|
+
compare(opts.out, card.markdown, "trust card");
|
|
253
|
+
if (opts.jsonOut) compare(opts.jsonOut, jsonText, "trust card JSON");
|
|
254
|
+
log(`trust-card: up to date (${card.verdict}, ${card.json.tools.count} tools, ${card.cardDigest.slice(0, 23)}…)`);
|
|
255
|
+
return { code: exitCodeFor(card.verdict, opts.failOn), result: card };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (opts.out === "-") {
|
|
259
|
+
log(card.markdown.replace(/\n$/, ""));
|
|
260
|
+
} else {
|
|
261
|
+
ensureDir(opts.out);
|
|
262
|
+
writeFileSync(resolve(opts.out), card.markdown);
|
|
263
|
+
log(`trust-card: wrote ${opts.out} (${card.verdict}, ${card.json.tools.count} tools, ${card.cardDigest})`);
|
|
264
|
+
}
|
|
265
|
+
if (opts.jsonOut) {
|
|
266
|
+
ensureDir(opts.jsonOut);
|
|
267
|
+
writeFileSync(resolve(opts.jsonOut), jsonText);
|
|
268
|
+
if (opts.out !== "-") log(`trust-card: wrote ${opts.jsonOut}`);
|
|
269
|
+
}
|
|
270
|
+
if (opts.toolsOut) {
|
|
271
|
+
ensureDir(opts.toolsOut);
|
|
272
|
+
writeFileSync(resolve(opts.toolsOut), JSON.stringify(tools, null, 2) + "\n");
|
|
273
|
+
log(`trust-card: wrote ${opts.toolsOut} (${tools.length} tools)`);
|
|
274
|
+
}
|
|
275
|
+
const code = exitCodeFor(card.verdict, opts.failOn);
|
|
276
|
+
if (code !== 0) err(`trust-card: gate --fail-on ${opts.failOn} tripped by verdict ${card.verdict}`);
|
|
277
|
+
return { code, result: card };
|
|
278
|
+
} catch (error) {
|
|
279
|
+
err(`trust-card: ${error.message}`);
|
|
280
|
+
return { code: error.code === 1 ? 1 : 2 };
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const invokedDirectly = process.argv[1] && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
|
|
285
|
+
if (invokedDirectly) {
|
|
286
|
+
runTrustCardCli().then(({ code }) => {
|
|
287
|
+
process.exitCode = code;
|
|
288
|
+
});
|
|
289
|
+
}
|