@coreguard/agent-commerce 0.2.0 → 0.3.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/README.md +1 -1
- package/bin/trust-card.mjs +12 -0
- package/mcp.mjs +35 -1
- package/observations.mjs +24 -3
- package/package.json +13 -6
- package/server.json +3 -3
- package/trust-card-cli.mjs +289 -0
- package/trust-card.mjs +252 -0
- package/wave3.mjs +97 -11
- package/wave4.mjs +593 -0
package/README.md
CHANGED
|
@@ -349,7 +349,7 @@ License: MIT.
|
|
|
349
349
|
|
|
350
350
|
## Release readiness / MCPRush evidence
|
|
351
351
|
|
|
352
|
-
- **Release notes:** `docs/releases/0.1.
|
|
352
|
+
- **Release notes:** `docs/releases/0.2.1.md` (latest) · `docs/releases/0.2.0.md`
|
|
353
353
|
- **Publish readiness checklist:** `docs/releases/0.1.3-publish-readiness.md`
|
|
354
354
|
- **Security & threat model:** `docs/agent-commerce-mcp-security.md`
|
|
355
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
|
@@ -58,6 +58,7 @@ import {
|
|
|
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
60
|
import { WAVE3_TOOLS, WAVE3_HANDLERS, WAVE3_VALIDATORS, WAVE3_BOUNDARY } from "./wave3.mjs";
|
|
61
|
+
import { WAVE4_TOOLS, WAVE4_HANDLERS, WAVE4_VALIDATORS, WAVE4_BOUNDARY } from "./wave4.mjs";
|
|
61
62
|
|
|
62
63
|
const PROTOCOL_VERSION = "2025-06-18";
|
|
63
64
|
|
|
@@ -127,6 +128,31 @@ const TOOL_NAMES = Object.freeze([
|
|
|
127
128
|
"coreguard_translate_receipt",
|
|
128
129
|
"coreguard_emit_test_vectors",
|
|
129
130
|
"coreguard_describe_surface",
|
|
131
|
+
// Wave 4 (CG-W4/1) — cross-border/bank/chain/machine/loan evidence tools. Offline, caller-supplied evidence only.
|
|
132
|
+
"coreguard_parse_iso20022_payment",
|
|
133
|
+
"coreguard_verify_cross_border_instruction",
|
|
134
|
+
"coreguard_assess_fx_quote_risk",
|
|
135
|
+
"coreguard_verify_swift_remittance_evidence",
|
|
136
|
+
"coreguard_verify_bank_transfer_evidence",
|
|
137
|
+
"coreguard_assess_sanctions_screening_evidence",
|
|
138
|
+
"coreguard_verify_invoice_match",
|
|
139
|
+
"coreguard_generate_payment_compliance_packet",
|
|
140
|
+
"coreguard_verify_stellar_settlement_evidence",
|
|
141
|
+
"coreguard_verify_evm_settlement_evidence",
|
|
142
|
+
"coreguard_verify_coredao_settlement_evidence",
|
|
143
|
+
"coreguard_verify_pi_payment_evidence",
|
|
144
|
+
"coreguard_assess_bridge_risk",
|
|
145
|
+
"coreguard_assess_defi_position_risk",
|
|
146
|
+
"coreguard_verify_web3_signature_evidence",
|
|
147
|
+
"coreguard_verify_stablecoin_reserve_evidence",
|
|
148
|
+
"coreguard_create_robot_mission_receipt",
|
|
149
|
+
"coreguard_verify_robot_mission_evidence",
|
|
150
|
+
"coreguard_assess_machine_sla",
|
|
151
|
+
"coreguard_assess_loan_application",
|
|
152
|
+
"coreguard_verify_collateral_packet",
|
|
153
|
+
"coreguard_assess_credit_line_utilization",
|
|
154
|
+
"coreguard_verify_escrow_milestone",
|
|
155
|
+
"coreguard_create_incident_war_room",
|
|
130
156
|
]);
|
|
131
157
|
|
|
132
158
|
/**
|
|
@@ -181,6 +207,7 @@ function requireString(args, key) {
|
|
|
181
207
|
/** Per-tool input validation. Returns null when the arguments are usable. */
|
|
182
208
|
const VALIDATORS = Object.freeze({
|
|
183
209
|
...WAVE3_VALIDATORS,
|
|
210
|
+
...WAVE4_VALIDATORS,
|
|
184
211
|
coreguard_authorize(args) {
|
|
185
212
|
const missing = requireObjects(args, ["intent", "policy", "declaredTrace"]);
|
|
186
213
|
if (missing) return missing;
|
|
@@ -685,6 +712,7 @@ const TOOLS = Object.freeze([
|
|
|
685
712
|
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 },
|
|
686
713
|
},
|
|
687
714
|
...WAVE3_TOOLS,
|
|
715
|
+
...WAVE4_TOOLS,
|
|
688
716
|
]);
|
|
689
717
|
|
|
690
718
|
function withCallerContext(value, args) {
|
|
@@ -776,6 +804,10 @@ async function callTool(name, args, { consumedSet } = {}) {
|
|
|
776
804
|
const ctx = { toolNames: TOOL_NAMES, version: PACKAGE.version, serverName: SERVER_INFO.name, protocolVersion: PROTOCOL_VERSION };
|
|
777
805
|
return success(withCallerContext(WAVE3_HANDLERS[name](a, ctx), a));
|
|
778
806
|
}
|
|
807
|
+
if (WAVE4_HANDLERS[name]) {
|
|
808
|
+
const ctx = { toolNames: TOOL_NAMES, version: PACKAGE.version, serverName: SERVER_INFO.name, protocolVersion: PROTOCOL_VERSION };
|
|
809
|
+
return success(withCallerContext(WAVE4_HANDLERS[name](a, ctx), a));
|
|
810
|
+
}
|
|
779
811
|
return failure(ERROR_CODES.UNKNOWN_TOOL, `unknown tool: ${String(name)}`);
|
|
780
812
|
} catch (err) {
|
|
781
813
|
return failure(ERROR_CODES.TOOL_ERROR, err?.message ?? String(err));
|
|
@@ -840,8 +872,10 @@ export function createMcpHandler({ write } = {}) {
|
|
|
840
872
|
|
|
841
873
|
export function selfCheck() {
|
|
842
874
|
return [
|
|
843
|
-
["tools exposed", TOOL_NAMES.length ===
|
|
875
|
+
["tools exposed", TOOL_NAMES.length === 70 && 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" && TOOL_NAMES[69] === "coreguard_create_incident_war_room"],
|
|
844
876
|
["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])],
|
|
877
|
+
["wave 4 declares schemas for every tool", WAVE4_TOOLS.length === 24 && WAVE4_TOOLS.every((t) => t.name.startsWith("coreguard_") && t.inputSchema && t.outputSchema?.type === "object" && WAVE4_HANDLERS[t.name])],
|
|
878
|
+
["wave 4 boundary travels", WAVE4_BOUNDARY.includes("VERIFIED ≠ SAFE")],
|
|
845
879
|
["wave 3 boundary travels", WAVE3_BOUNDARY.includes("VERIFIED ≠ SAFE")],
|
|
846
880
|
["protocol version pinned", PROTOCOL_VERSION === "2025-06-18"],
|
|
847
881
|
["spec surfaced", CONSENT_SPEC === "CGCR/1" && AGENT_COMMERCE_VERSION === "AC-SDK/1"],
|
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.
|
|
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.3.0",
|
|
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 (70 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",
|
|
@@ -35,16 +36,20 @@
|
|
|
35
36
|
"./prod/observability.mjs": "./prod/observability.mjs",
|
|
36
37
|
"./prod/kms-anchor.mjs": "./prod/kms-anchor.mjs",
|
|
37
38
|
"./machine-economy.mjs": "./machine-economy.mjs",
|
|
38
|
-
"./cgcp-mcp-tools.mjs": "./cgcp-mcp-tools.mjs"
|
|
39
|
+
"./cgcp-mcp-tools.mjs": "./cgcp-mcp-tools.mjs",
|
|
40
|
+
"./wave4.mjs": "./wave4.mjs"
|
|
39
41
|
},
|
|
40
42
|
"bin": {
|
|
41
|
-
"coreguard-agent-commerce-mcp": "./bin/mcp.mjs"
|
|
43
|
+
"coreguard-agent-commerce-mcp": "./bin/mcp.mjs",
|
|
44
|
+
"coreguard-trust-card": "./bin/trust-card.mjs"
|
|
42
45
|
},
|
|
43
46
|
"files": [
|
|
47
|
+
"README.md",
|
|
44
48
|
"aer1.mjs",
|
|
45
49
|
"anchor.mjs",
|
|
46
50
|
"attest.mjs",
|
|
47
51
|
"bin/mcp.mjs",
|
|
52
|
+
"bin/trust-card.mjs",
|
|
48
53
|
"cgcp-mcp-tools.mjs",
|
|
49
54
|
"client.mjs",
|
|
50
55
|
"composition.mjs",
|
|
@@ -71,14 +76,16 @@
|
|
|
71
76
|
"prod/schema.mjs",
|
|
72
77
|
"prod/sqlite-storage.mjs",
|
|
73
78
|
"profile-ref.mjs",
|
|
74
|
-
"README.md",
|
|
75
79
|
"reference.mjs",
|
|
76
80
|
"risk-cli.mjs",
|
|
77
81
|
"risk.mjs",
|
|
78
82
|
"server.json",
|
|
79
83
|
"spend.mjs",
|
|
84
|
+
"trust-card-cli.mjs",
|
|
85
|
+
"trust-card.mjs",
|
|
80
86
|
"trust.mjs",
|
|
81
|
-
"wave3.mjs"
|
|
87
|
+
"wave3.mjs",
|
|
88
|
+
"wave4.mjs"
|
|
82
89
|
],
|
|
83
90
|
"engines": {
|
|
84
91
|
"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. 70 MCP tools.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"url": "https://github.com/coreguard-global/CoreGuard",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "0.
|
|
9
|
+
"version": "0.3.0",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "@coreguard/agent-commerce",
|
|
14
|
-
"version": "0.
|
|
14
|
+
"version": "0.3.0",
|
|
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
|
+
}
|