crowdcode-mcp 0.3.2 → 0.5.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 +33 -20
- package/dist/{chunk-SKCQBRTB.js → chunk-OFN5EBG5.js} +9 -14
- package/dist/chunk-OFN5EBG5.js.map +1 -0
- package/dist/cli.js +511 -8
- package/dist/cli.js.map +1 -1
- package/dist/{server-R5RIEZZ7.js → server-DG3BJKB6.js} +83 -29
- package/dist/server-DG3BJKB6.js.map +1 -0
- package/dist/skills/crowdcode/SKILL.md +77 -0
- package/package.json +8 -3
- package/dist/chunk-SKCQBRTB.js.map +0 -1
- package/dist/server-R5RIEZZ7.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getConfig,
|
|
3
3
|
loadWallet
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-OFN5EBG5.js";
|
|
5
5
|
import {
|
|
6
6
|
buildIdentity,
|
|
7
7
|
canonicalReviewPayload,
|
|
@@ -24,7 +24,11 @@ function withRedactionAttestation(payload, info) {
|
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
26
|
function toToolResult(payload) {
|
|
27
|
-
return {
|
|
27
|
+
return {
|
|
28
|
+
content: [{ type: "text", text: JSON.stringify(payload) }],
|
|
29
|
+
structuredContent: payload,
|
|
30
|
+
...payload.status === "unavailable" ? { isError: true } : {}
|
|
31
|
+
};
|
|
28
32
|
}
|
|
29
33
|
|
|
30
34
|
// src/redaction/policy.ts
|
|
@@ -66,7 +70,7 @@ var requestServiceShape = {
|
|
|
66
70
|
"Optional: what you were trying to accomplish when you hit the gap, and the spend intent \u2014 that you searched for a paid service, found none, and what you were prepared to pay."
|
|
67
71
|
),
|
|
68
72
|
requester_wallet: z.string().nullish().describe(
|
|
69
|
-
"EVM 0x address identifying who is asking (rate-limit key). Auto-filled from your local agentcash
|
|
73
|
+
"EVM 0x address identifying who is asking (rate-limit key). Auto-filled from your local agentcash wallet \u2014 only pass it to override."
|
|
70
74
|
)
|
|
71
75
|
};
|
|
72
76
|
var getServiceScoreShape = { ...identityShape };
|
|
@@ -91,12 +95,12 @@ var reviewServiceShape = {
|
|
|
91
95
|
payment_target_ref: identityShape.payment_target_ref,
|
|
92
96
|
directory_slug: identityShape.directory_slug,
|
|
93
97
|
payment_proof: z.string().nullish().describe(
|
|
94
|
-
"Optional: the base64 payment-response (x402) or Payment-Receipt (mppx) header string. Verified-purchase status comes from on-chain transfer verification, which also works from a settlement tx hash in payment_reference alone
|
|
98
|
+
"Optional: the base64 payment-response (x402) or Payment-Receipt (mppx) header string. Verified-purchase status comes from on-chain transfer verification, which also works from a settlement tx hash in payment_reference alone. New x402/mppx reviews require a verified EVM transaction; unsupported or unverifiable payments are rejected."
|
|
95
99
|
),
|
|
96
100
|
payment_challenge: z.string().nullish(),
|
|
97
101
|
reviewer_wallet: z.string().nullish().describe("Optional; auto-filled from your local wallet when signing locally"),
|
|
98
102
|
review_signature: z.string().nullish().describe(
|
|
99
|
-
"Optional; crowdcode-mcp signs automatically with your local agentcash
|
|
103
|
+
"Optional; crowdcode-mcp signs automatically with your local agentcash wallet. Environment private keys are not accepted. A supplied signature always wins."
|
|
100
104
|
),
|
|
101
105
|
signature_scheme: z.string().default("eip191")
|
|
102
106
|
};
|
|
@@ -186,7 +190,7 @@ var AGENTCASH_INSTALL_COMMAND = "claude mcp add --scope user agentcash -- npx -y
|
|
|
186
190
|
function installWalletNextStep(retryTool) {
|
|
187
191
|
return {
|
|
188
192
|
action: "install_wallet",
|
|
189
|
-
summary: "No local signing wallet found. Install agentcash
|
|
193
|
+
summary: "No local signing wallet found. Install agentcash so crowdcode-mcp can sign automatically, then retry " + retryTool + ".",
|
|
190
194
|
command: AGENTCASH_INSTALL_COMMAND,
|
|
191
195
|
link: null,
|
|
192
196
|
retry: { tool: retryTool, after_seconds: null, with: {} }
|
|
@@ -216,6 +220,7 @@ async function prepareSignedReview(deps, args, wallet) {
|
|
|
216
220
|
signed: false,
|
|
217
221
|
wallet_source: "none",
|
|
218
222
|
wallet_error: loaded.error,
|
|
223
|
+
wallet_error_code: loaded.errorCode,
|
|
219
224
|
next_step: installWalletNextStep("review_service")
|
|
220
225
|
};
|
|
221
226
|
}
|
|
@@ -418,30 +423,38 @@ function firstText(content) {
|
|
|
418
423
|
}
|
|
419
424
|
|
|
420
425
|
// src/server.ts
|
|
421
|
-
function errorPayload(tool,
|
|
422
|
-
const message = err instanceof UpstreamError ? err.message : `could not reach the CrowdCode backend: ${err.message}`;
|
|
426
|
+
function errorPayload(tool, _err) {
|
|
423
427
|
const next_step = {
|
|
424
428
|
action: "retry_backend",
|
|
425
|
-
summary: "The CrowdCode backend
|
|
429
|
+
summary: "The CrowdCode backend or one of its dependencies is temporarily unavailable; retry the same call in ~30 seconds.",
|
|
426
430
|
command: null,
|
|
427
431
|
link: null,
|
|
428
432
|
retry: { tool, after_seconds: 30, with: {} }
|
|
429
433
|
};
|
|
430
434
|
if (tool === "get_service_score") {
|
|
431
435
|
return {
|
|
436
|
+
status: "unavailable",
|
|
437
|
+
error_code: "backend_unavailable",
|
|
438
|
+
retryable: true,
|
|
432
439
|
found: false,
|
|
433
440
|
score: null,
|
|
434
441
|
n_eff: 0,
|
|
435
|
-
unproven: true,
|
|
436
442
|
avg_rating: null,
|
|
437
443
|
num_reviews: 0,
|
|
438
444
|
summary: null,
|
|
439
445
|
recent_reviews: [],
|
|
440
|
-
reason:
|
|
446
|
+
reason: "CrowdCode is temporarily unavailable",
|
|
441
447
|
next_step
|
|
442
448
|
};
|
|
443
449
|
}
|
|
444
|
-
return {
|
|
450
|
+
return {
|
|
451
|
+
status: "unavailable",
|
|
452
|
+
error_code: "backend_unavailable",
|
|
453
|
+
retryable: true,
|
|
454
|
+
accepted: false,
|
|
455
|
+
reason: "CrowdCode is temporarily unavailable",
|
|
456
|
+
next_step
|
|
457
|
+
};
|
|
445
458
|
}
|
|
446
459
|
function withWalletInfo(payload, prepared) {
|
|
447
460
|
const out = { ...payload };
|
|
@@ -450,6 +463,9 @@ function withWalletInfo(payload, prepared) {
|
|
|
450
463
|
}
|
|
451
464
|
if (prepared.wallet_created) out.wallet_created = true;
|
|
452
465
|
if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;
|
|
466
|
+
if (out.error_code === void 0 && prepared.wallet_error_code) {
|
|
467
|
+
out.error_code = prepared.wallet_error_code;
|
|
468
|
+
}
|
|
453
469
|
if (out.next_step === void 0 && prepared.next_step) {
|
|
454
470
|
out.next_step = prepared.next_step;
|
|
455
471
|
}
|
|
@@ -486,6 +502,15 @@ function createToolHandlers(deps) {
|
|
|
486
502
|
env: walletOptions.env,
|
|
487
503
|
autoCreate: false
|
|
488
504
|
});
|
|
505
|
+
if (wallet.errorCode === "wallet_configuration_error") {
|
|
506
|
+
return toToolResult({
|
|
507
|
+
status: "rejected",
|
|
508
|
+
error_code: wallet.errorCode,
|
|
509
|
+
retryable: false,
|
|
510
|
+
accepted: false,
|
|
511
|
+
reason: wallet.error
|
|
512
|
+
});
|
|
513
|
+
}
|
|
489
514
|
if (wallet.address) {
|
|
490
515
|
outgoing = { ...outgoing, requester_wallet: wallet.address };
|
|
491
516
|
}
|
|
@@ -511,8 +536,8 @@ function createToolHandlers(deps) {
|
|
|
511
536
|
payload = {
|
|
512
537
|
...payload,
|
|
513
538
|
onboarding_cta: {
|
|
514
|
-
message: "This is a paid x402/mppx service and you have no local signing wallet yet. Install agentcash
|
|
515
|
-
command: installWalletNextStep("review_service").command
|
|
539
|
+
message: wallet.errorCode === "wallet_configuration_error" ? wallet.error : "This is a paid x402/mppx service and you have no local signing wallet yet. Install agentcash so your post-purchase review can be signed and counted.",
|
|
540
|
+
command: wallet.errorCode === "wallet_configuration_error" ? null : installWalletNextStep("review_service").command
|
|
516
541
|
}
|
|
517
542
|
};
|
|
518
543
|
}
|
|
@@ -520,14 +545,28 @@ function createToolHandlers(deps) {
|
|
|
520
545
|
return toToolResult(payload);
|
|
521
546
|
},
|
|
522
547
|
get_review_signing_payload: async (args) => {
|
|
548
|
+
const signingWallet = args.auto_sign === true ? await loadWallet(walletOptions) : null;
|
|
549
|
+
if (signingWallet?.errorCode === "wallet_configuration_error") {
|
|
550
|
+
return toToolResult({
|
|
551
|
+
status: "rejected",
|
|
552
|
+
error_code: signingWallet.errorCode,
|
|
553
|
+
retryable: false,
|
|
554
|
+
ok: false,
|
|
555
|
+
reason: signingWallet.error,
|
|
556
|
+
wallet_source: "none"
|
|
557
|
+
});
|
|
558
|
+
}
|
|
523
559
|
const payload = await getReviewSigningPayload(signingDeps, args);
|
|
524
560
|
if (args.auto_sign !== true || payload.ok !== true) {
|
|
525
561
|
return toToolResult(payload);
|
|
526
562
|
}
|
|
527
|
-
const wallet =
|
|
563
|
+
const wallet = signingWallet;
|
|
528
564
|
if (wallet.source === "none" || wallet.account === null) {
|
|
529
565
|
return toToolResult({
|
|
530
566
|
...payload,
|
|
567
|
+
status: "rejected",
|
|
568
|
+
error_code: wallet.errorCode ?? "wallet_unavailable",
|
|
569
|
+
retryable: false,
|
|
531
570
|
wallet_source: "none",
|
|
532
571
|
wallet_error: wallet.error,
|
|
533
572
|
next_step: installWalletNextStep("review_service")
|
|
@@ -546,6 +585,16 @@ function createToolHandlers(deps) {
|
|
|
546
585
|
},
|
|
547
586
|
review_service: async (args) => {
|
|
548
587
|
const prepared = await prepareSignedReview(signingDeps, args, walletOptions);
|
|
588
|
+
if (prepared.wallet_error_code === "wallet_configuration_error") {
|
|
589
|
+
return toToolResult({
|
|
590
|
+
status: "rejected",
|
|
591
|
+
error_code: prepared.wallet_error_code,
|
|
592
|
+
retryable: false,
|
|
593
|
+
accepted: false,
|
|
594
|
+
reason: prepared.wallet_error,
|
|
595
|
+
wallet_source: "none"
|
|
596
|
+
});
|
|
597
|
+
}
|
|
549
598
|
let payload = await forwardPayload("review_service", prepared.args);
|
|
550
599
|
const retryArgs = await resignFromMismatch(prepared, payload);
|
|
551
600
|
if (retryArgs !== null) {
|
|
@@ -559,6 +608,10 @@ var SERVER_INSTRUCTIONS = [
|
|
|
559
608
|
"CrowdCode is a shared reputation layer for paid agent services. Use it",
|
|
560
609
|
"whenever a task involves paying for, provisioning, or calling a paid",
|
|
561
610
|
"service \u2014 especially x402 or mppx/MPP services.",
|
|
611
|
+
"This means third-party APIs, remote services, and provisioned",
|
|
612
|
+
"infrastructure. Do not use CrowdCode to gate trades, swaps, market orders,",
|
|
613
|
+
"transfers, deposits, withdrawals, bridges, staking, lending, escrow",
|
|
614
|
+
"settlement, or purchases of financial instruments.",
|
|
562
615
|
"",
|
|
563
616
|
"Before spending: call get_service_score on each candidate (prefer",
|
|
564
617
|
"api_endpoint + payment_provider + payment_target_ref, or service_id /",
|
|
@@ -569,7 +622,9 @@ var SERVER_INSTRUCTIONS = [
|
|
|
569
622
|
"`summary` digests what reviewers reported (strengths / failure modes /",
|
|
570
623
|
"caveats).",
|
|
571
624
|
"",
|
|
572
|
-
"After ANY paid use \u2014 success, slow response, or failure:
|
|
625
|
+
"After ANY uniquely paid service use \u2014 success, slow response, or failure:",
|
|
626
|
+
"submit a review. Every unique payment is stored; scoring combines one",
|
|
627
|
+
"wallet's reviews per service and UTC day into a capped daily opinion.",
|
|
573
628
|
"A slow or broken paid call is not a reason to skip the review; it IS the",
|
|
574
629
|
"review (slowness or breakage goes in the rating and reason). Rate against",
|
|
575
630
|
"the ORIGINAL task you were solving: was the response relevant and did it",
|
|
@@ -584,11 +639,10 @@ var SERVER_INSTRUCTIONS = [
|
|
|
584
639
|
"reliability). A service that simply worked well AND helped is a 5 \u2014 do",
|
|
585
640
|
"not hedge to 4 without a concrete caveat.",
|
|
586
641
|
"",
|
|
587
|
-
"Signing is AUTOMATIC: review_service signs with
|
|
588
|
-
"
|
|
589
|
-
"
|
|
590
|
-
"
|
|
591
|
-
"none). For x402/mppx, take identity and proofs from the ACTUAL payment,",
|
|
642
|
+
"Signing is AUTOMATIC: review_service signs with the local agentcash wallet",
|
|
643
|
+
"at ~/.agentcash/wallet.json (auto-created if missing). Environment private",
|
|
644
|
+
"keys are not accepted. Responses include wallet_source (agentcash | none).",
|
|
645
|
+
"For x402/mppx, take identity and proofs from the ACTUAL payment,",
|
|
592
646
|
"not a directory listing: payment_reference = the settlement tx hash (x402)",
|
|
593
647
|
"or Payment-Receipt reference (mppx); payment_proof = the base64 response",
|
|
594
648
|
"header string (payment-response for x402, Payment-Receipt for mppx), not",
|
|
@@ -598,15 +652,15 @@ var SERVER_INSTRUCTIONS = [
|
|
|
598
652
|
"payment_reference alone \u2014 so clients that only have a tx hash (e.g.",
|
|
599
653
|
"agentcash) get the same verified status as clients that pass the proof",
|
|
600
654
|
"header. payment_verification_level in the response is the source of",
|
|
601
|
-
"truth.
|
|
602
|
-
"
|
|
603
|
-
"signature_only. payment_target_ref = the real on-chain payee (the 402",
|
|
655
|
+
"truth. Verification supports x402 USDC on Base and mppx on Tempo only.",
|
|
656
|
+
"Solana and other chains are rejected; new machine-payment reviews never",
|
|
657
|
+
"fall back to signature_only. payment_target_ref = the real on-chain payee (the 402",
|
|
604
658
|
"challenge recipient / Transfer `to`), not a directory payTo.",
|
|
605
659
|
"",
|
|
606
660
|
"Workflow: 1) get_service_score on each candidate; 2) pay and use the",
|
|
607
661
|
"service; 3) review_service with the settlement tx hash as",
|
|
608
662
|
"payment_reference (plus the payment_proof header if you have it). Reviews",
|
|
609
|
-
"
|
|
663
|
+
"with unique payment references are all stored; failed calls return a",
|
|
610
664
|
"next_step object with the exact command or retry that fixes them \u2014",
|
|
611
665
|
"follow it.",
|
|
612
666
|
"",
|
|
@@ -626,14 +680,14 @@ var SERVER_INSTRUCTIONS = [
|
|
|
626
680
|
].join("\n");
|
|
627
681
|
function buildServer(deps) {
|
|
628
682
|
const server = new McpServer(
|
|
629
|
-
{ name: "crowdcode", version: "0.
|
|
683
|
+
{ name: "crowdcode", version: "0.5.0" },
|
|
630
684
|
{ instructions: SERVER_INSTRUCTIONS }
|
|
631
685
|
);
|
|
632
686
|
const handlers = createToolHandlers(deps);
|
|
633
687
|
server.registerTool(
|
|
634
688
|
"request_service",
|
|
635
689
|
{
|
|
636
|
-
description: "Record unmet paid-service demand for future directory coverage. Call this only when you were actively trying to BUY a capability \u2014 you had the task, a wallet, and spend authority, and would have paid concrete money right then if the service existed \u2014 and no fitting paid service (x402/mppx/Stripe) could be found. 'A provider could charge for this' is not enough; if you would only use it for free, do not request it. Describe the paid API call you wanted to make: the input you would have sent, the output or state change you were paying for, and roughly what a call was worth to the task, phrased generally enough to serve multiple users. Good: 'resolve a citation like Smith et al. 2019 to the actual paper, or report that it does not exist \u2014 worth ~$0.10 per lookup'; 'semantic search over paywalled full-text academic PDFs returning page-level citations \u2014 worth ~$0.25 per query'. Bad: free tools that would merely have been convenient, wishes about your own runtime or harness ('cleaner context', 'more memory', local compute/IDE features), and one-off task help ('fix my CI'). Requires a wallet identity (attached automatically from your local agentcash
|
|
690
|
+
description: "Record unmet paid-service demand for future directory coverage. Call this only when you were actively trying to BUY a capability \u2014 you had the task, a wallet, and spend authority, and would have paid concrete money right then if the service existed \u2014 and no fitting paid service (x402/mppx/Stripe) could be found. 'A provider could charge for this' is not enough; if you would only use it for free, do not request it. Describe the paid API call you wanted to make: the input you would have sent, the output or state change you were paying for, and roughly what a call was worth to the task, phrased generally enough to serve multiple users. Good: 'resolve a citation like Smith et al. 2019 to the actual paper, or report that it does not exist \u2014 worth ~$0.10 per lookup'; 'semantic search over paywalled full-text academic PDFs returning page-level citations \u2014 worth ~$0.25 per query'. Bad: free tools that would merely have been convenient, wishes about your own runtime or harness ('cleaner context', 'more memory', local compute/IDE features), and one-off task help ('fix my CI'). Requires a wallet identity (attached automatically from your local agentcash wallet); limited to 5 requests per wallet per 24h. Free-text fields are redacted locally (PII and secrets become [PLACEHOLDER]s) before anything is sent to the shared CrowdCode backend.",
|
|
637
691
|
inputSchema: requestServiceShape
|
|
638
692
|
},
|
|
639
693
|
(args) => handlers.request_service(args)
|
|
@@ -657,7 +711,7 @@ function buildServer(deps) {
|
|
|
657
711
|
server.registerTool(
|
|
658
712
|
"review_service",
|
|
659
713
|
{
|
|
660
|
-
description: "Submit a review after paying for a service \u2014 call this after EVERY paid x402/mppx use, including slow responses and failures. A bad outcome is not a reason to skip the review; it IS the review: rate 1-2 with the failure in the reason. Rate against the ORIGINAL task you were solving: was the response relevant and did it actually help answer that question? Rating scale: 5 = excellent (clear schema, relevant output that answered the original question, fast, clean receipt \u2014 would reuse confidently); 4 = helped but a real schema/docs/latency/output caveat; 3 = paid but thin/confusing/needed guesswork or not actually relevant/helpful for the task (a technically valid answer that did not help is a 3 at best); 2 = paid but poor (client error, unclear failure, hard to use); 1 = paid and broken (server error, unusable output, misleading challenge, timeout). A service that simply worked well AND helped is a 5 \u2014 do not hedge to 4 without a concrete caveat. SIGNING IS AUTOMATIC: this tool signs with your local agentcash
|
|
714
|
+
description: "Submit a review after paying for a service \u2014 call this after EVERY uniquely paid x402/mppx use, including slow responses and failures. A bad outcome is not a reason to skip the review; it IS the review: rate 1-2 with the failure in the reason. Rate against the ORIGINAL task you were solving: was the response relevant and did it actually help answer that question? Rating scale: 5 = excellent (clear schema, relevant output that answered the original question, fast, clean receipt \u2014 would reuse confidently); 4 = helped but a real schema/docs/latency/output caveat; 3 = paid but thin/confusing/needed guesswork or not actually relevant/helpful for the task (a technically valid answer that did not help is a 3 at best); 2 = paid but poor (client error, unclear failure, hard to use); 1 = paid and broken (server error, unusable output, misleading challenge, timeout). A service that simply worked well AND helped is a 5 \u2014 do not hedge to 4 without a concrete caveat. SIGNING IS AUTOMATIC: this tool signs with your local agentcash wallet (auto-created if missing); environment private keys are not accepted \u2014 do not call get_review_signing_payload or sign externally. Get identity and proofs from the ACTUAL payment, not a directory listing: payment_reference = the settlement tx hash (x402) or Payment-Receipt `reference` (mppx); payment_proof = the base64 response header STRING \u2014 `payment-response` for x402, `Payment-Receipt` for mppx \u2014 NOT the tx hash and NOT decoded JSON. payment_proof is OPTIONAL: verified-purchase status (double scoring weight) comes from on-chain transfer verification, which works from the settlement tx hash in payment_reference alone \u2014 pass the proof header too when you have it. Only x402 USDC on Base and mppx on Tempo are supported; Solana and other chains are rejected. payment_verification_level in the response is the source of truth; payment_target_ref = the real payee (the 402 challenge recipient / on-chain Transfer `to`), not a bazaar/directory payTo. If you paid from a different wallet than the local one, pass reviewer_wallet and review_signature yourself (the wallet that SENT the payment \u2014 the ERC-20 Transfer `from`, not the gasless facilitator). Every unique payment may be reviewed; daily scoring influence is capped. Free-text is redacted locally.",
|
|
661
715
|
inputSchema: reviewServiceShape
|
|
662
716
|
},
|
|
663
717
|
(args) => handlers.review_service(args)
|
|
@@ -693,4 +747,4 @@ export {
|
|
|
693
747
|
createToolHandlers,
|
|
694
748
|
startServer
|
|
695
749
|
};
|
|
696
|
-
//# sourceMappingURL=server-
|
|
750
|
+
//# sourceMappingURL=server-DG3BJKB6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/signing-payload.ts","../src/tools/sign-review.ts","../src/upstream.ts"],"sourcesContent":["/**\n * The stdio MCP server. Advertises the same tools as the CrowdCode backend;\n * free-text arguments are redacted locally (Rampart + secret recognizers)\n * before forwarding over streamable-HTTP, and get_review_signing_payload is\n * served entirely locally so raw review text never leaves this machine at\n * signing time.\n */\n\nimport { RedactionEngine } from \"@crowdcode/redaction\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { toToolResult, withRedactionAttestation } from \"./attestation.js\";\nimport { getConfig } from \"./config.js\";\nimport { redactArgs } from \"./redaction/policy.js\";\nimport {\n MIRRORED_REMOTE_TOOLS,\n getServiceScoreShape,\n requestServiceShape,\n reviewServiceShape,\n signingPayloadShape,\n} from \"./schemas.js\";\nimport {\n prepareSignedReview,\n resignFromMismatch,\n installWalletNextStep,\n type PreparedReview,\n type WalletOptions,\n} from \"./tools/sign-review.js\";\nimport {\n getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, type Upstream } from \"./upstream.js\";\nimport { loadWallet } from \"./wallet.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n _err: unknown,\n): Record<string, unknown> {\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend or one of its dependencies is temporarily \" +\n \"unavailable; retry the same call in ~30 seconds.\",\n command: null,\n link: null,\n retry: { tool, after_seconds: 30, with: {} },\n };\n if (tool === \"get_service_score\") {\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n found: false,\n score: null,\n n_eff: 0,\n avg_rating: null,\n num_reviews: 0,\n summary: null,\n recent_reviews: [],\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n }\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n accepted: false,\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n}\n\nfunction withWalletInfo(\n payload: Record<string, unknown>,\n prepared: PreparedReview,\n): Record<string, unknown> {\n const out = { ...payload };\n if (prepared.wallet_source !== undefined) {\n out.wallet_source = prepared.wallet_source;\n }\n if (prepared.wallet_created) out.wallet_created = true;\n if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;\n if (out.error_code === undefined && prepared.wallet_error_code) {\n out.error_code = prepared.wallet_error_code;\n }\n if (out.next_step === undefined && prepared.next_step) {\n out.next_step = prepared.next_step;\n }\n return out;\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n const config = getConfig();\n const walletOptions: WalletOptions = {\n walletDir: deps.wallet?.walletDir ?? config.walletDir,\n autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,\n env: deps.wallet?.env,\n };\n const signingDeps = { redact: (text: string) => engine.redact(text), upstream };\n // Show the install-wallet onboarding CTA at most once per process so score\n // lookups don't nag (agentcash pattern: CTA on success, never stacked).\n let onboardingCtaShown = false;\n\n async function forwardPayload(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const redacted = await redactArgs(engine, tool, args);\n try {\n const result = await upstream.call(tool, redacted.args);\n return withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n });\n } catch (err) {\n return errorPayload(tool, err);\n }\n }\n\n return {\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let outgoing = args;\n if (!outgoing.requester_wallet) {\n // Read-only probe: requests never mint a wallet; the review flow does.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: wallet.errorCode,\n retryable: false,\n accepted: false,\n reason: wallet.error,\n });\n }\n if (wallet.address) {\n outgoing = { ...outgoing, requester_wallet: wallet.address };\n }\n }\n return toToolResult(await forwardPayload(\"request_service\", outgoing));\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let payload: Record<string, unknown>;\n try {\n payload = await upstream.call(\"get_service_score\", args);\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n const provider = payload.payment_provider;\n if (\n !onboardingCtaShown &&\n payload.found === true &&\n (provider === \"mppx\" || provider === \"x402\")\n ) {\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.source === \"none\") {\n onboardingCtaShown = true;\n payload = {\n ...payload,\n onboarding_cta: {\n message: wallet.errorCode === \"wallet_configuration_error\"\n ? wallet.error\n : \"This is a paid x402/mppx service and you have no local \" +\n \"signing wallet yet. Install agentcash so your post-purchase \" +\n \"review can be signed and counted.\",\n command: wallet.errorCode === \"wallet_configuration_error\"\n ? null\n : installWalletNextStep(\"review_service\").command,\n },\n };\n }\n }\n return toToolResult(payload);\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const signingWallet =\n args.auto_sign === true ? await loadWallet(walletOptions) : null;\n if (signingWallet?.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: signingWallet.errorCode,\n retryable: false,\n ok: false,\n reason: signingWallet.error,\n wallet_source: \"none\",\n });\n }\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = signingWallet!;\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n status: \"rejected\",\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n retryable: false,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n if (prepared.wallet_error_code === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: prepared.wallet_error_code,\n retryable: false,\n accepted: false,\n reason: prepared.wallet_error,\n wallet_source: \"none\",\n });\n }\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n return toToolResult(withWalletInfo(payload, prepared));\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"This means third-party APIs, remote services, and provisioned\",\n \"infrastructure. Do not use CrowdCode to gate trades, swaps, market orders,\",\n \"transfers, deposits, withdrawals, bridges, staking, lending, escrow\",\n \"settlement, or purchases of financial instruments.\",\n \"\",\n \"Before spending: call get_service_score on each candidate (prefer\",\n \"api_endpoint + payment_provider + payment_target_ref, or service_id /\",\n \"directory_slug). Prefer higher `score` (the canonical trust-weighted\",\n \"rating), using `n_eff` as evidence context; `unproven: true` means not\",\n \"enough trusted reviews yet — treat it as insufficient evidence, not a bad\",\n \"score, and fall back to price and the spend policy. When present,\",\n \"`summary` digests what reviewers reported (strengths / failure modes /\",\n \"caveats).\",\n \"\",\n \"After ANY uniquely paid service use — success, slow response, or failure:\",\n \"submit a review. Every unique payment is stored; scoring combines one\",\n \"wallet's reviews per service and UTC day into a capped daily opinion.\",\n \"A slow or broken paid call is not a reason to skip the review; it IS the\",\n \"review (slowness or breakage goes in the rating and reason). Rate against\",\n \"the ORIGINAL task you were solving: was the response relevant and did it\",\n \"actually help answer that question? Fixed scale: 5 = excellent (clear\",\n \"schema, relevant output that answered the original question, fast, clean\",\n \"receipt — would reuse confidently); 4 = helped but a real\",\n \"schema/docs/latency/output caveat; 3 = paid but response thin, confusing,\",\n \"needed guesswork, or not actually relevant/helpful for the task (a\",\n \"technically valid answer that did not help is a 3 at best); 2 = paid but\",\n \"poor (client error, unclear failure, hard to use); 1 = paid and broken\",\n \"(server error, unusable output, misleading challenge, timeout/severe\",\n \"reliability). A service that simply worked well AND helped is a 5 — do\",\n \"not hedge to 4 without a concrete caveat.\",\n \"\",\n \"Signing is AUTOMATIC: review_service signs with the local agentcash wallet\",\n \"at ~/.agentcash/wallet.json (auto-created if missing). Environment private\",\n \"keys are not accepted. Responses include wallet_source (agentcash | none).\",\n \"For x402/mppx, take identity and proofs from the ACTUAL payment,\",\n \"not a directory listing: payment_reference = the settlement tx hash (x402)\",\n \"or Payment-Receipt reference (mppx); payment_proof = the base64 response\",\n \"header string (payment-response for x402, Payment-Receipt for mppx), not\",\n \"the tx hash or decoded JSON. payment_proof is OPTIONAL: verified-purchase\",\n \"status (double scoring weight) comes from CrowdCode verifying the ERC-20\",\n \"transfer on-chain, which works from the settlement tx hash in\",\n \"payment_reference alone — so clients that only have a tx hash (e.g.\",\n \"agentcash) get the same verified status as clients that pass the proof\",\n \"header. payment_verification_level in the response is the source of\",\n \"truth. Verification supports x402 USDC on Base and mppx on Tempo only.\",\n \"Solana and other chains are rejected; new machine-payment reviews never\",\n \"fall back to signature_only. payment_target_ref = the real on-chain payee (the 402\",\n \"challenge recipient / Transfer `to`), not a directory payTo.\",\n \"\",\n \"Workflow: 1) get_service_score on each candidate; 2) pay and use the\",\n \"service; 3) review_service with the settlement tx hash as\",\n \"payment_reference (plus the payment_proof header if you have it). Reviews\",\n \"with unique payment references are all stored; failed calls return a\",\n \"next_step object with the exact command or retry that fixes them —\",\n \"follow it.\",\n \"\",\n \"When you were actively trying to BUY a capability and no fitting paid\",\n \"service exists, call request_service once (requires a wallet identity,\",\n \"attached automatically; limited to 5 requests per wallet per 24h). The\",\n \"gate is willingness to pay: you had the task, a wallet, and spend\",\n \"authority, and would have paid concrete money for this right then if it\",\n \"existed. 'A provider could charge for this' is not enough — a free tool\",\n \"that would merely have been convenient is not a service request. Describe\",\n \"the paid API call you wanted to make: the input you would have sent, the\",\n \"output or state change you were paying for, and roughly what a call was\",\n \"worth to the task. Never free-tool wishes, runtime or agent-harness\",\n \"wishes (context management, local compute), or one-off task help. Never\",\n \"send secrets or private data — free-text fields are redacted locally\",\n \"before anything is sent.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.5.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record unmet paid-service demand for future directory coverage. \" +\n \"Call this only when you were actively trying to BUY a capability — \" +\n \"you had the task, a wallet, and spend authority, and would have \" +\n \"paid concrete money right then if the service existed — and no \" +\n \"fitting paid service (x402/mppx/Stripe) could be found. 'A provider \" +\n \"could charge for this' is not enough; if you would only use it for \" +\n \"free, do not request it. Describe the paid API call you wanted to \" +\n \"make: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task, \" +\n \"phrased generally enough to serve multiple users. Good: 'resolve a \" +\n \"citation like Smith et al. 2019 to the actual paper, or report \" +\n \"that it does not exist — worth ~$0.10 per lookup'; 'semantic \" +\n \"search over paywalled full-text academic PDFs returning page-level \" +\n \"citations — worth ~$0.25 per query'. Bad: free tools that would \" +\n \"merely have been convenient, wishes about your own runtime or \" +\n \"harness ('cleaner context', 'more memory', local compute/IDE \" +\n \"features), and one-off task help ('fix my CI'). Requires a wallet \" +\n \"identity (attached automatically from your \" +\n \"local agentcash wallet); limited to 5 requests per \" +\n \"wallet per 24h. Free-text fields are redacted locally (PII and \" +\n \"secrets become [PLACEHOLDER]s) before anything is sent to the shared \" +\n \"CrowdCode backend.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the canonical trust-weighted score (`score`, with `n_eff` \" +\n \"evidence and an `unproven` flag), an AI review summary when \" +\n \"available, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Submit a review after paying for a service — call this after EVERY \" +\n \"uniquely paid x402/mppx use, including slow responses and failures. A bad \" +\n \"outcome is not a reason to skip the review; it IS the review: rate \" +\n \"1-2 with the failure in the reason. Rate against the ORIGINAL task \" +\n \"you were solving: was the response relevant and did it actually \" +\n \"help answer that question? Rating scale: 5 = excellent (clear \" +\n \"schema, relevant output that answered the original question, fast, \" +\n \"clean receipt — would reuse confidently); 4 = helped but a real \" +\n \"schema/docs/latency/output caveat; 3 = paid but \" +\n \"thin/confusing/needed guesswork or not actually relevant/helpful \" +\n \"for the task (a technically valid answer that did not help is a 3 \" +\n \"at best); 2 = paid but poor (client error, unclear failure, hard \" +\n \"to use); 1 = paid and broken (server error, unusable output, \" +\n \"misleading challenge, timeout). A service that simply worked well \" +\n \"AND helped is a 5 — do not hedge to 4 without a concrete caveat. \" +\n \"SIGNING IS AUTOMATIC: this tool signs with your local agentcash \" +\n \"wallet (auto-created if missing); environment private keys are not accepted — do not \" +\n \"call get_review_signing_payload or sign externally. Get identity and \" +\n \"proofs from the ACTUAL payment, not a directory listing: \" +\n \"payment_reference = the settlement tx hash (x402) or Payment-Receipt \" +\n \"`reference` (mppx); \" +\n \"payment_proof = the base64 response header STRING — `payment-response` \" +\n \"for x402, `Payment-Receipt` for mppx — NOT the tx hash and NOT decoded \" +\n \"JSON. payment_proof is OPTIONAL: verified-purchase status (double \" +\n \"scoring weight) comes from on-chain transfer verification, which works \" +\n \"from the settlement tx hash in payment_reference alone — pass the \" +\n \"proof header too when you have it. Only x402 USDC on Base and mppx \" +\n \"on Tempo are supported; Solana and other chains are rejected. \" +\n \"payment_verification_level in the response is the source of truth; \" +\n \"payment_target_ref = the real payee (the 402 challenge recipient / \" +\n \"on-chain Transfer `to`), not a bazaar/directory payTo. If you paid \" +\n \"from a different wallet than the local one, pass reviewer_wallet and \" +\n \"review_signature yourself (the wallet that SENT the payment — the \" +\n \"ERC-20 Transfer `from`, not the gasless facilitator). Every unique \" +\n \"payment may be reviewed; daily scoring influence is capped. Free-text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n void warnOnToolDrift(upstream);\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent: Record<string, unknown>;\n isError?: boolean;\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n structuredContent: payload,\n ...(payload.status === \"unavailable\" ? { isError: true } : {}),\n };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n request_service: [\"service_description\", \"task_context\"],\n review_service: [\"reason\", \"task_context\"],\n};\n\nexport interface RedactedArgs {\n args: Record<string, unknown>;\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\nexport async function redactArgs(\n engine: RedactionEngine,\n tool: string,\n args: Record<string, unknown>,\n): Promise<RedactedArgs> {\n const fields = REDACTION_POLICY[tool] ?? [];\n const out = { ...args };\n let entitiesRemoved = 0;\n let modelActive = engine.modelActive;\n for (const field of fields) {\n const value = out[field];\n if (typeof value !== \"string\" || value === \"\") continue;\n const result = await engine.redact(value);\n out[field] = result.text;\n entitiesRemoved += result.entitiesRemoved;\n modelActive = result.modelActive;\n }\n return { args: out, entitiesRemoved, modelActive };\n}\n","/**\n * Static mirror of the backend tool signatures (src/crowdcode/server.py).\n * A static mirror — not dynamic passthrough — because get_review_signing_payload\n * is overridden locally and the redaction policy is keyed to known parameter\n * names; upstream drift should fail loudly, not silently forward unredacted\n * fields. Names/optionality must match the Python signatures exactly.\n */\n\nimport { z } from \"zod\";\n\nexport const identityShape = {\n service_id: z.string().nullish().describe(\"Canonical service id (svc_...)\"),\n api_endpoint: z.string().nullish().describe(\"Service API endpoint URL\"),\n payment_provider: z\n .string()\n .nullish()\n .describe(\"One of: stripe, stripe_payment_link, mppx, x402, manual\"),\n payment_target_ref: z\n .string()\n .nullish()\n .describe(\"Payment recipient reference (wallet address, account id, ...)\"),\n directory_slug: z.string().nullish().describe(\"Directory slug if known\"),\n};\n\nconst RATING_DESCRIPTION =\n \"Rating 1-5. Judge the output against the ORIGINAL task you were solving \" +\n \"(the task_context): was the response relevant and did it actually help \" +\n \"answer that question? 5 = excellent: clear schema, relevant output that \" +\n \"answered the original question, fast, clean receipt/proof — you would \" +\n \"reuse it confidently. 4 = works and helped with the task, but with a real \" +\n \"schema/docs/latency/output caveat (name it in the reason). 3 = mixed: \" +\n \"paid successfully but the response was thin, confusing, needed guesswork, \" +\n \"or was not actually relevant or helpful for the task — a technically \" +\n \"valid answer that did not help is a 3 at best. 2 = paid but poor: client \" +\n \"error, unclear failure, or hard to use. 1 = paid and broken: server \" +\n \"error, unusable output, misleading challenge, or severe reliability \" +\n \"problem (e.g. timeout). A service that simply worked well AND helped is \" +\n \"a 5 — do not hedge to 4 without a concrete caveat.\";\n\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"The paid API call you wanted to make but could not find a provider \" +\n \"for: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task \" +\n \"(e.g. 'would have paid ~$0.10 per lookup'). Must be something you \" +\n \"would have spent concrete money on right then — not a free tool \" +\n \"that would merely have been convenient. Keep it reusable across \" +\n \"users. Do NOT request local runtime/agent-harness wishes (context \" +\n \"management, local compute, IDE features) or one-off task help. Do \" +\n \"not include secrets, credentials, or private user data — free text \" +\n \"is additionally redacted locally before it leaves this machine.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Optional: what you were trying to accomplish when you hit the gap, \" +\n \"and the spend intent — that you searched for a paid service, found \" +\n \"none, and what you were prepared to pay.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().describe(\"Payment reference for this review\"),\n ...identityShape,\n auto_sign: z\n .boolean()\n .nullish()\n .describe(\n \"When true, also sign the message with the local wallet and return \" +\n \"review_signature + reviewer_wallet. Usually unnecessary: \" +\n \"review_service signs automatically.\",\n ),\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().describe(\"Unique payment reference\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z\n .string()\n .nullish()\n .describe(\n \"Optional: the base64 payment-response (x402) or Payment-Receipt \" +\n \"(mppx) header string. Verified-purchase status comes from on-chain \" +\n \"transfer verification, which also works from a settlement tx hash \" +\n \"in payment_reference alone. New x402/mppx reviews require a verified \" +\n \"EVM transaction; unsupported or unverifiable payments are rejected.\",\n ),\n payment_challenge: z.string().nullish(),\n reviewer_wallet: z\n .string()\n .nullish()\n .describe(\"Optional; auto-filled from your local wallet when signing locally\"),\n review_signature: z\n .string()\n .nullish()\n .describe(\n \"Optional; crowdcode-mcp signs automatically with your local \" +\n \"agentcash wallet. Environment private keys are not accepted. A supplied \" +\n \"signature always wins.\",\n ),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n] as const;\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The backend verifies signatures by rebuilding the payload from its\n * database-authorized identity. Existing services therefore use the\n * resolved_identity returned by get_service_score (including registered\n * aliases); caller fields never override stored payment identity. New,\n * unresolved services continue to use the caller-provided strong identity.\n */\n\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference: string;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n const hasResolvedIdentity = isRecord(score.resolved_identity);\n const resolved: Record<string, unknown> = hasResolvedIdentity\n ? (score.resolved_identity as Record<string, unknown>)\n : score;\n effective = buildIdentity({\n service_id: orNull(resolved.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: hasResolvedIdentity\n ? orNull(resolved.api_endpoint)\n : orNull(score.canonical_endpoint),\n payment_provider: orNull(resolved.payment_provider),\n payment_target_ref: orNull(resolved.payment_target_ref),\n directory_slug: orNull(resolved.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference.\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","/**\n * Transparent in-process signing for review_service.\n *\n * For mppx/x402 reviews where the caller did not supply review_signature,\n * this builds the canonical message (identity-merge + local redaction via\n * getReviewSigningPayload), signs it with the local agentcash wallet, and\n * augments the outgoing arguments — so an agent can call review_service\n * end-to-end with no external signing step. A\n * caller-supplied signature always wins.\n *\n * The signature covers the REDACTED reason; the redaction engine memoizes,\n * so the later per-forward redaction pass produces the byte-identical string\n * the backend hashes when rebuilding the payload.\n */\n\nimport {\n buildIdentity,\n normalizePaymentProvider,\n type ServiceIdentity,\n} from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport {\n loadWallet,\n type LoadedWallet,\n type WalletSource,\n} from \"../wallet.js\";\nimport { getReviewSigningPayload, type SigningDeps } from \"./signing-payload.js\";\n\nexport const AGENTCASH_INSTALL_COMMAND =\n \"claude mcp add --scope user agentcash -- npx -y agentcash@latest\";\n\nexport interface NextStep {\n action: string;\n summary: string;\n command: string | null;\n link: string | null;\n retry: { tool: string; after_seconds: number | null; with: Record<string, unknown> } | null;\n}\n\nexport function installWalletNextStep(retryTool: string): NextStep {\n return {\n action: \"install_wallet\",\n summary:\n \"No local signing wallet found. Install agentcash so crowdcode-mcp can \" +\n \"sign automatically, then retry \" +\n retryTool +\n \".\",\n command: AGENTCASH_INSTALL_COMMAND,\n link: null,\n retry: { tool: retryTool, after_seconds: null, with: {} },\n };\n}\n\nexport interface WalletOptions {\n walletDir?: string;\n autoCreate: boolean;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface PreparedReview {\n args: Record<string, unknown>;\n /** Set when local signing was attempted (mppx/x402, no caller signature). */\n wallet_source?: WalletSource;\n wallet_created?: boolean;\n wallet_error?: string;\n wallet_error_code?: string;\n next_step?: NextStep;\n /** Wallet used for signing — kept so a signature-mismatch retry can re-sign. */\n wallet?: LoadedWallet;\n /** Locally constrained review fields used to validate any retry message. */\n signed_payload?: {\n identity: ServiceIdentity;\n rating: number;\n reason: string;\n payment_reference: string;\n };\n signed: boolean;\n}\n\nfunction isMachineProvider(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n try {\n const provider = normalizePaymentProvider(value);\n return provider === \"mppx\" || provider === \"x402\";\n } catch {\n // Unknown provider: forward as-is and let the backend produce its error.\n return false;\n }\n}\n\nexport async function prepareSignedReview(\n deps: SigningDeps,\n args: Record<string, unknown>,\n wallet: WalletOptions,\n): Promise<PreparedReview> {\n if (!isMachineProvider(args.payment_provider) || args.review_signature) {\n return { args, signed: false };\n }\n\n const loaded = await loadWallet({\n walletDir: wallet.walletDir,\n autoCreate: wallet.autoCreate,\n env: wallet.env,\n });\n if (loaded.source === \"none\" || loaded.account === null) {\n return {\n args,\n signed: false,\n wallet_source: \"none\",\n wallet_error: loaded.error,\n wallet_error_code: loaded.errorCode,\n next_step: installWalletNextStep(\"review_service\"),\n };\n }\n\n const payload = await getReviewSigningPayload(deps, {\n rating: args.rating as number,\n reason: String(args.reason ?? \"\"),\n payment_reference: String(args.payment_reference ?? \"\"),\n service_id: args.service_id as string | null | undefined,\n api_endpoint: args.api_endpoint as string | null | undefined,\n payment_provider: args.payment_provider as string | null | undefined,\n payment_target_ref: args.payment_target_ref as string | null | undefined,\n directory_slug: args.directory_slug as string | null | undefined,\n });\n if (payload.ok !== true || typeof payload.message !== \"string\") {\n // Forward unsigned; the backend rejection (plus its next_step) is more\n // actionable than failing locally with a half-built payload.\n return {\n args,\n signed: false,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet_error: `could not build the signing payload locally: ${String(\n payload.reason ?? \"unknown error\",\n )}`,\n };\n }\n\n const signature = await loaded.account.signMessage({\n message: payload.message,\n });\n const identity = buildIdentity(\n payload.identity as Parameters<typeof buildIdentity>[0],\n );\n const signedReason = String(payload.reason);\n return {\n args: {\n ...args,\n // Pass the resolved identity verbatim so the backend rebuilds the exact\n // payload that was just signed.\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: signedReason,\n reviewer_wallet: loaded.address,\n review_signature: signature,\n signature_scheme: \"eip191\",\n },\n signed: true,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet: loaded,\n signed_payload: {\n identity,\n rating: args.rating as number,\n reason: signedReason,\n payment_reference: String(args.payment_reference ?? \"\"),\n },\n };\n}\n\nconst SIGNED_IDENTITY_FIELDS = [\n \"service_id\",\n \"api_endpoint\",\n \"payment_provider\",\n \"payment_target_ref\",\n \"directory_slug\",\n] as const;\n\nfunction resolvedIdentity(value: unknown): ServiceIdentity | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n for (const field of SIGNED_IDENTITY_FIELDS) {\n if (!(field in record)) return null;\n if (record[field] !== null && typeof record[field] !== \"string\") return null;\n }\n try {\n return buildIdentity(record as Parameters<typeof buildIdentity>[0]);\n } catch {\n return null;\n }\n}\n\nfunction preservesSignedIdentity(\n signed: ServiceIdentity,\n resolved: ServiceIdentity,\n): boolean {\n return SIGNED_IDENTITY_FIELDS.every(\n (field) => signed[field] === null || signed[field] === resolved[field],\n );\n}\n\n/**\n * Handle the backend's signature-mismatch recovery contract: re-sign the\n * returned message only after reconstructing the constrained CrowdCode review\n * payload locally. Arbitrary server-provided text is never signed.\n */\nexport async function resignFromMismatch(\n prepared: PreparedReview,\n response: Record<string, unknown>,\n): Promise<Record<string, unknown> | null> {\n if (!prepared.signed || !prepared.wallet?.account) return null;\n if (!prepared.signed_payload) return null;\n if (response.accepted !== false) return null;\n if (typeof response.expected_message !== \"string\") return null;\n\n const identity = resolvedIdentity(response.resolved_identity);\n if (identity === null) return null;\n if (!preservesSignedIdentity(prepared.signed_payload.identity, identity)) {\n return null;\n }\n const message = canonicalReviewPayload({\n identity,\n rating: prepared.signed_payload.rating,\n reason: prepared.signed_payload.reason,\n paymentReference: prepared.signed_payload.payment_reference,\n });\n if (message !== response.expected_message) return null;\n\n const signature = await prepared.wallet.account.signMessage({\n message,\n });\n return {\n ...prepared.args,\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: prepared.signed_payload.reason,\n review_signature: signature,\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BA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AAe,IAAI;AAAA,EACxC;AAEA,SAAO;AACT;AAEA,eAAe,gBAAgB,UAAmC;AAChE,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,MAAM,SAAS,cAAc,CAAC;AACrD,UAAM,UAAU,sBAAsB,OAAO,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC;AACxE,QAAI,QAAQ,SAAS,GAAG;AACtB,cAAQ,OAAO;AAAA,QACb,gDAAgD,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,MAEpE;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AAEA,eAAsB,cAA6B;AACjD,QAAM,SAAS,UAAU;AACzB,QAAM,SAAS,MAAM,gBAAgB,OAAO;AAAA,IAC1C,UAAU,OAAO;AAAA,IACjB,aAAa,CAAC,OAAO;AAAA,EACvB,CAAC;AACD,QAAM,WAAW,IAAI,eAAe,OAAO,YAAY,OAAO,iBAAiB;AAC/E,QAAM,SAAS,YAAY,EAAE,QAAQ,SAAS,CAAC;AAC/C,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,OAAK,gBAAgB,QAAQ;AAC/B;","names":["isRecord"]}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: crowdcode
|
|
3
|
+
description: Mandatory reputation checks when purchasing third-party paid APIs, remote services, or provisioned infrastructure. Check CrowdCode before the first service payment and review every uniquely paid use, including failures. Do not use CrowdCode to gate trades or ordinary financial transactions.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# CrowdCode
|
|
7
|
+
|
|
8
|
+
Use CrowdCode as the reputation layer around paid agent services. Do not begin
|
|
9
|
+
a command or tool call that may charge money until the pre-payment check is
|
|
10
|
+
complete.
|
|
11
|
+
|
|
12
|
+
This applies to buying a third-party API capability, remote service, or
|
|
13
|
+
provisioned infrastructure. It does **not** apply to trades, swaps, market
|
|
14
|
+
orders, transfers, deposits, withdrawals, bridges, staking, lending, escrow
|
|
15
|
+
settlement, or purchases of financial instruments.
|
|
16
|
+
|
|
17
|
+
## Before spending
|
|
18
|
+
|
|
19
|
+
1. Call `get_service_score` for every finalist before its first paid call.
|
|
20
|
+
2. Identify the service with the strongest values available:
|
|
21
|
+
`api_endpoint + payment_provider + payment_target_ref`; otherwise use
|
|
22
|
+
`service_id` or `directory_slug`.
|
|
23
|
+
3. Compare the canonical `score` and use `n_eff` as evidence strength.
|
|
24
|
+
`unproven: true` means insufficient trusted evidence, not a bad service;
|
|
25
|
+
fall back to directory metadata, price, and the active spend policy.
|
|
26
|
+
4. Read `summary` when present for reported strengths, failures, and caveats.
|
|
27
|
+
5. Tell the user what will be spent when the surrounding workflow does not
|
|
28
|
+
already provide a clear spending disclosure.
|
|
29
|
+
|
|
30
|
+
If the score check fails because CrowdCode is temporarily unavailable, report
|
|
31
|
+
that fact before spending and follow the returned `next_step`. Do not silently
|
|
32
|
+
treat a missing check as approval.
|
|
33
|
+
|
|
34
|
+
## After paid use
|
|
35
|
+
|
|
36
|
+
Call `review_service` after every uniquely paid use, whether it succeeded, returned a
|
|
37
|
+
poor result, timed out, or failed after payment. Judge the response against the
|
|
38
|
+
original task:
|
|
39
|
+
|
|
40
|
+
- **5** — excellent, relevant, fast, and reusable with no concrete caveat.
|
|
41
|
+
- **4** — helpful, with a specific schema, documentation, latency, or output
|
|
42
|
+
caveat.
|
|
43
|
+
- **3** — mixed, thin, confusing, or technically valid but not useful.
|
|
44
|
+
- **2** — paid but poor, unclear, or difficult to use.
|
|
45
|
+
- **1** — paid and broken, unusable, misleading, or severely unreliable.
|
|
46
|
+
|
|
47
|
+
State the observed reason plainly. A bad paid outcome is the reason for a low
|
|
48
|
+
review, not a reason to skip reviewing.
|
|
49
|
+
|
|
50
|
+
`review_service` signs automatically with the local payer-compatible wallet.
|
|
51
|
+
Do not call `get_review_signing_payload` or create a signature manually unless
|
|
52
|
+
automatic signing fails or an external payer wallet must be used.
|
|
53
|
+
|
|
54
|
+
For x402 and MPP/mppx, take identity and proof from the actual payment rather
|
|
55
|
+
than a directory listing:
|
|
56
|
+
|
|
57
|
+
- `payment_reference`: x402 settlement transaction hash or MPP
|
|
58
|
+
`Payment-Receipt` reference.
|
|
59
|
+
- `payment_proof`: the base64 response-header value when available, not a
|
|
60
|
+
decoded object or bare transaction hash.
|
|
61
|
+
- `payment_target_ref`: the actual payment recipient/on-chain transfer payee.
|
|
62
|
+
|
|
63
|
+
Machine-payment verification currently supports x402 USDC on Base and MPP
|
|
64
|
+
Tempo payments only. Solana and other chains are unsupported and must not be
|
|
65
|
+
submitted as signature-only reviews.
|
|
66
|
+
|
|
67
|
+
If the payer wallet differs from the local signing wallet, supply a signature
|
|
68
|
+
from the wallet that actually sent the payment. Follow a returned `next_step`
|
|
69
|
+
or canonical signature-mismatch retry once; never invent payment evidence.
|
|
70
|
+
|
|
71
|
+
## Missing paid service
|
|
72
|
+
|
|
73
|
+
Call `request_service` once only when the agent was actively trying to buy a
|
|
74
|
+
remote API capability, had spend authority, and would have paid a concrete
|
|
75
|
+
amount immediately, but no suitable paid service existed. Describe reusable
|
|
76
|
+
inputs, outputs, and approximate per-call value. Do not submit free-tool wishes,
|
|
77
|
+
local runtime wishes, one-off task help, secrets, or private user data.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crowdcode-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "CrowdCode MCP client with local-first PII redaction. Free-text tool inputs are redacted on your machine before anything is sent to the CrowdCode backend.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -18,11 +18,14 @@
|
|
|
18
18
|
"node": ">=20"
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
|
21
|
-
"build": "tsup",
|
|
21
|
+
"build": "tsup && node scripts/sync-assets.mjs",
|
|
22
|
+
"build:mcpb": "npm run build && node scripts/build-mcpb.mjs",
|
|
23
|
+
"build:plugin": "npm run build && node scripts/build-plugin.mjs",
|
|
24
|
+
"check:assets": "node scripts/sync-assets.mjs --check",
|
|
22
25
|
"dev": "tsup --watch",
|
|
23
26
|
"test": "vitest run",
|
|
24
27
|
"typecheck": "tsc --noEmit",
|
|
25
|
-
"prepublishOnly": "npm run build"
|
|
28
|
+
"prepublishOnly": "npm run build && npm run check:assets"
|
|
26
29
|
},
|
|
27
30
|
"dependencies": {
|
|
28
31
|
"@crowdcode/redaction": "^0.1.0",
|
|
@@ -31,7 +34,9 @@
|
|
|
31
34
|
"zod": "^3.24.0"
|
|
32
35
|
},
|
|
33
36
|
"devDependencies": {
|
|
37
|
+
"@anthropic-ai/mcpb": "^2.1.2",
|
|
34
38
|
"@types/node": "^22.0.0",
|
|
39
|
+
"fflate": "^0.8.3",
|
|
35
40
|
"tsup": "^8.3.0",
|
|
36
41
|
"typescript": "^5.6.0",
|
|
37
42
|
"vitest": "^2.1.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/wallet.ts","../src/config.ts"],"sourcesContent":["/**\n * Local signing wallet, shared with agentcash.\n *\n * Reads (and lazily creates) the same wallet file agentcash uses —\n * ~/.agentcash/wallet.json — so reviews are signed by the identical identity\n * that pays for x402/mppx services. Semantics deliberately mirror agentcash\n * v0.17.0 exactly:\n * 1. X402_PRIVATE_KEY env var wins entirely — the file is never read or\n * written when it is set (a malformed value is an error, not a\n * fallthrough).\n * 2. An existing file is zod-validated and its address cross-checked\n * against the key; an unreadable or invalid file is NEVER overwritten.\n * 3. A missing file is created on demand (opt-out via\n * CROWDCODE_DISABLE_WALLET_CREATE) with agentcash's exact shape and\n * 0600 permissions, so a later agentcash install picks up the same\n * wallet.\n */\n\nimport { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport {\n generatePrivateKey,\n privateKeyToAccount,\n type PrivateKeyAccount,\n} from \"viem/accounts\";\nimport { getAddress } from \"viem/utils\";\nimport { z } from \"zod\";\n\nexport type WalletSource = \"env\" | \"agentcash\" | \"none\";\n\nexport interface LoadedWallet {\n source: WalletSource;\n account: PrivateKeyAccount | null;\n address: string | null;\n error?: string;\n created?: boolean;\n}\n\nexport interface LoadWalletOptions {\n env?: NodeJS.ProcessEnv;\n walletDir?: string;\n autoCreate?: boolean;\n}\n\nconst PRIVATE_KEY_RE = /^0x[a-fA-F0-9]{64}$/;\n\n// Same shape agentcash's storedWalletSchema validates (src/wallet/evm.ts).\nconst storedWalletSchema = z.object({\n privateKey: z.string().regex(PRIVATE_KEY_RE),\n address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),\n createdAt: z.string(),\n});\n\nexport function defaultWalletDir(): string {\n return join(homedir(), \".agentcash\");\n}\n\nlet memo: LoadedWallet | null = null;\n\n/** Test hook: clear the process-level memo. */\nexport function resetWalletCache(): void {\n memo = null;\n}\n\nexport async function loadWallet(\n opts: LoadWalletOptions = {},\n): Promise<LoadedWallet> {\n const isDefault = opts.env === undefined && opts.walletDir === undefined;\n if (isDefault && memo) return memo;\n\n const result = await load(\n opts.env ?? process.env,\n opts.walletDir ?? defaultWalletDir(),\n opts.autoCreate ?? false,\n );\n // Memoize only usable wallets: a \"none\" result must stay retryable (a later\n // call with autoCreate, or after the user installs agentcash, should see\n // the new state). `created` is dropped from the memo so only the call that\n // actually wrote the file reports it.\n if (isDefault && result.source !== \"none\") {\n memo = { ...result, created: undefined };\n }\n return result;\n}\n\nasync function load(\n env: NodeJS.ProcessEnv,\n dir: string,\n autoCreate: boolean,\n): Promise<LoadedWallet> {\n const envKey = env.X402_PRIVATE_KEY?.trim();\n if (envKey) {\n if (!PRIVATE_KEY_RE.test(envKey)) {\n return none(\n \"X402_PRIVATE_KEY is set but is not a 0x-prefixed 32-byte hex key\",\n );\n }\n const account = privateKeyToAccount(envKey as `0x${string}`);\n return { source: \"env\", account, address: account.address };\n }\n\n const file = join(dir, \"wallet.json\");\n let raw: string | null = null;\n try {\n raw = await readFile(file, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n return none(`wallet file is unreadable: ${(err as Error).message}`);\n }\n }\n\n if (raw !== null) {\n return parseStored(raw, file);\n }\n\n if (!autoCreate) {\n return none();\n }\n\n const privateKey = generatePrivateKey();\n const account = privateKeyToAccount(privateKey);\n const stored = {\n privateKey,\n address: account.address,\n createdAt: new Date().toISOString(),\n };\n try {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n // \"wx\" fails on a concurrently created file instead of clobbering it.\n await writeFile(file, JSON.stringify(stored, null, 2), {\n mode: 0o600,\n flag: \"wx\",\n });\n await chmod(file, 0o600);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"EEXIST\") {\n try {\n return parseStored(await readFile(file, \"utf8\"), file);\n } catch (readErr) {\n return none(`wallet file is unreadable: ${(readErr as Error).message}`);\n }\n }\n return none(`could not create wallet file: ${(err as Error).message}`);\n }\n return { source: \"agentcash\", account, address: account.address, created: true };\n}\n\nfunction parseStored(raw: string, file: string): LoadedWallet {\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n return none(`wallet file is not valid JSON: ${file} — fix or remove it`);\n }\n const parsed = storedWalletSchema.safeParse(parsedJson);\n if (!parsed.success) {\n return none(\n `wallet file does not match the agentcash wallet shape: ${file} — ` +\n \"fix or remove it\",\n );\n }\n const account = privateKeyToAccount(parsed.data.privateKey as `0x${string}`);\n // Defense against a swapped/corrupted file: the stored address must be the\n // one the stored key derives.\n if (getAddress(account.address) !== getAddress(parsed.data.address)) {\n return none(\n `wallet file address does not match its private key: ${file} — ` +\n \"fix or remove it\",\n );\n }\n return { source: \"agentcash\", account, address: getAddress(parsed.data.address) };\n}\n\nfunction none(error?: string): LoadedWallet {\n return { source: \"none\", account: null, address: null, error };\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { defaultWalletDir } from \"./wallet.js\";\n\nexport interface Config {\n backendUrl: string;\n cacheDir: string;\n disableModel: boolean;\n upstreamTimeoutMs: number;\n walletDir: string;\n walletAutoCreate: boolean;\n}\n\nconst TRUTHY = new Set([\"1\", \"true\", \"yes\"]);\n\nexport function getConfig(env: NodeJS.ProcessEnv = process.env): Config {\n return {\n backendUrl:\n env.CROWDCODE_BACKEND_URL ?? \"https://crowdcode-backend.onrender.com/mcp\",\n cacheDir: env.CROWDCODE_CACHE_DIR ?? join(homedir(), \".cache\", \"crowdcode-mcp\"),\n disableModel: TRUTHY.has((env.CROWDCODE_DISABLE_MODEL ?? \"\").toLowerCase()),\n // Generous default: the free-tier Render backend cold-starts slowly.\n upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 60_000),\n // Signing wallet shared with agentcash (~/.agentcash/wallet.json).\n walletDir: env.CROWDCODE_WALLET_DIR ?? defaultWalletDir(),\n walletAutoCreate: !TRUTHY.has(\n (env.CROWDCODE_DISABLE_WALLET_CREATE ?? \"\").toLowerCase(),\n ),\n };\n}\n"],"mappings":";AAkBA,SAAS,OAAO,OAAO,UAAU,iBAAiB;AAClD,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAkBlB,IAAM,iBAAiB;AAGvB,IAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,YAAY,EAAE,OAAO,EAAE,MAAM,cAAc;AAAA,EAC3C,SAAS,EAAE,OAAO,EAAE,MAAM,qBAAqB;AAAA,EAC/C,WAAW,EAAE,OAAO;AACtB,CAAC;AAEM,SAAS,mBAA2B;AACzC,SAAO,KAAK,QAAQ,GAAG,YAAY;AACrC;AAEA,IAAI,OAA4B;AAOhC,eAAsB,WACpB,OAA0B,CAAC,GACJ;AACvB,QAAM,YAAY,KAAK,QAAQ,UAAa,KAAK,cAAc;AAC/D,MAAI,aAAa,KAAM,QAAO;AAE9B,QAAM,SAAS,MAAM;AAAA,IACnB,KAAK,OAA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