crowdcode-mcp 0.6.0 → 0.8.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 +17 -3
- package/dist/{chunk-OFN5EBG5.js → chunk-M37QDGMY.js} +91 -1
- package/dist/chunk-M37QDGMY.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/{server-Q6FUDOBY.js → server-NAVVZUD4.js} +118 -8
- package/dist/server-NAVVZUD4.js.map +1 -0
- package/dist/skills/crowdcode/SKILL.md +12 -5
- package/package.json +1 -1
- package/dist/chunk-OFN5EBG5.js.map +0 -1
- package/dist/server-Q6FUDOBY.js.map +0 -1
package/README.md
CHANGED
|
@@ -102,9 +102,23 @@ proofs from the *actual payment*, not from a directory listing:
|
|
|
102
102
|
x402, `Payment-Receipt` for mppx). Optional: pass it when you have it, but
|
|
103
103
|
verified status comes from the on-chain transfer either way. The response's
|
|
104
104
|
`payment_verification_level` is the source of truth. On-chain verification
|
|
105
|
-
supports x402 USDC on Base
|
|
106
|
-
|
|
107
|
-
`
|
|
105
|
+
supports x402 USDC on Base, Monad (`eip155:143`) and Solana, and mppx on
|
|
106
|
+
Tempo. For Monad, pass `payment_reference: "x402:monad:<tx_hash>"` (or the
|
|
107
|
+
bare hash with a `payment_proof` whose `network` is `eip155:143`;
|
|
108
|
+
crowdcode-mcp rewrites it to the prefixed form before signing). For Solana,
|
|
109
|
+
pass `x402:solana:<base58 signature>` (or a `payment_proof` whose `network`
|
|
110
|
+
is `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`) with the Solana payee as
|
|
111
|
+
`payment_target_ref`. Other chains are rejected as unsupported; invalid
|
|
112
|
+
supplied payment claims never fall back to `signature_only`.
|
|
113
|
+
- `payer_signature` — x402 Solana only. The reviewer wallet is EVM, but a
|
|
114
|
+
Solana payer is a base58 key, so a Solana payment is a verified purchase only
|
|
115
|
+
when the payer also signs the payer link message (`spec/CANONICAL_PAYLOAD.md`
|
|
116
|
+
in the GitHub repository). crowdcode-mcp signs
|
|
117
|
+
it automatically with agentcash's Solana wallet
|
|
118
|
+
(`~/.agentcash/solana-wallet.json`) unless the proof names another payer, and
|
|
119
|
+
retries once without it if the backend reports `payer_signature_invalid`.
|
|
120
|
+
Without it the transfer is recorded as observed and the review is weighted
|
|
121
|
+
as `signature_only`.
|
|
108
122
|
- `payment_target_ref` — the real payee (the 402 challenge recipient / on-chain
|
|
109
123
|
`Transfer` `to`), not a bazaar-advertised `payTo`.
|
|
110
124
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// src/wallet.ts
|
|
2
|
+
import { createPrivateKey, createPublicKey, sign as cryptoSign } from "crypto";
|
|
2
3
|
import { chmod, mkdir, readFile, writeFile } from "fs/promises";
|
|
3
4
|
import { homedir } from "os";
|
|
4
5
|
import { join } from "path";
|
|
@@ -8,6 +9,56 @@ import {
|
|
|
8
9
|
} from "viem/accounts";
|
|
9
10
|
import { getAddress } from "viem/utils";
|
|
10
11
|
import { z } from "zod";
|
|
12
|
+
|
|
13
|
+
// src/canonical/solana.ts
|
|
14
|
+
import { createHash } from "crypto";
|
|
15
|
+
var ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
16
|
+
var BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;
|
|
17
|
+
function base58Decode(value) {
|
|
18
|
+
if (typeof value !== "string" || !BASE58_RE.test(value)) return null;
|
|
19
|
+
let n = 0n;
|
|
20
|
+
for (const char of value) n = n * 58n + BigInt(ALPHABET.indexOf(char));
|
|
21
|
+
const body = [];
|
|
22
|
+
while (n > 0n) {
|
|
23
|
+
body.unshift(Number(n & 0xffn));
|
|
24
|
+
n >>= 8n;
|
|
25
|
+
}
|
|
26
|
+
const zeros = value.length - value.replace(/^1+/, "").length;
|
|
27
|
+
return Uint8Array.from([...new Array(zeros).fill(0), ...body]);
|
|
28
|
+
}
|
|
29
|
+
function base58Encode(bytes) {
|
|
30
|
+
let n = 0n;
|
|
31
|
+
for (const byte of bytes) n = n << 8n | BigInt(byte);
|
|
32
|
+
let out = "";
|
|
33
|
+
while (n > 0n) {
|
|
34
|
+
out = ALPHABET[Number(n % 58n)] + out;
|
|
35
|
+
n /= 58n;
|
|
36
|
+
}
|
|
37
|
+
let zeros = 0;
|
|
38
|
+
while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
|
|
39
|
+
return "1".repeat(zeros) + out;
|
|
40
|
+
}
|
|
41
|
+
function decodesTo(value, size) {
|
|
42
|
+
if (typeof value !== "string") return false;
|
|
43
|
+
return base58Decode(value.trim())?.length === size;
|
|
44
|
+
}
|
|
45
|
+
var isSolanaSignature = (value) => decodesTo(value, 64);
|
|
46
|
+
function solanaReferenceSignature(reference) {
|
|
47
|
+
if (typeof reference !== "string") return null;
|
|
48
|
+
let cleaned = reference.trim();
|
|
49
|
+
if (cleaned.slice(0, 12).toLowerCase() === "x402:solana:") cleaned = cleaned.slice(12);
|
|
50
|
+
return isSolanaSignature(cleaned) ? cleaned : null;
|
|
51
|
+
}
|
|
52
|
+
var PAYER_LINK_MESSAGE_HEADER = "CrowdCode review payer link v1";
|
|
53
|
+
function payerLinkMessage(reviewerWallet, payload) {
|
|
54
|
+
return [
|
|
55
|
+
PAYER_LINK_MESSAGE_HEADER,
|
|
56
|
+
`reviewer_wallet:${reviewerWallet.trim().toLowerCase()}`,
|
|
57
|
+
`payload_sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`
|
|
58
|
+
].join("\n");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// src/wallet.ts
|
|
11
62
|
var PRIVATE_KEY_RE = /^0x[a-fA-F0-9]{64}$/;
|
|
12
63
|
var storedWalletSchema = z.object({
|
|
13
64
|
privateKey: z.string().regex(PRIVATE_KEY_RE),
|
|
@@ -103,6 +154,41 @@ function parseStored(raw, file) {
|
|
|
103
154
|
function none(error, errorCode) {
|
|
104
155
|
return { source: "none", account: null, address: null, error, errorCode };
|
|
105
156
|
}
|
|
157
|
+
var solanaWalletSchema = z.object({
|
|
158
|
+
privateKey: z.string().regex(/^[1-9A-HJ-NP-Za-km-z]+$/),
|
|
159
|
+
address: z.string(),
|
|
160
|
+
createdAt: z.string().optional()
|
|
161
|
+
});
|
|
162
|
+
var ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
|
|
163
|
+
async function loadSolanaWallet(walletDir) {
|
|
164
|
+
let raw;
|
|
165
|
+
try {
|
|
166
|
+
raw = await readFile(join(walletDir ?? defaultWalletDir(), "solana-wallet.json"), "utf8");
|
|
167
|
+
} catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
let parsed;
|
|
171
|
+
try {
|
|
172
|
+
parsed = solanaWalletSchema.parse(JSON.parse(raw));
|
|
173
|
+
} catch {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
const secret = base58Decode(parsed.privateKey);
|
|
177
|
+
if (secret === null || secret.length !== 32 && secret.length !== 64) return null;
|
|
178
|
+
const key = createPrivateKey({
|
|
179
|
+
key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(secret.subarray(0, 32))]),
|
|
180
|
+
format: "der",
|
|
181
|
+
type: "pkcs8"
|
|
182
|
+
});
|
|
183
|
+
const jwk = createPublicKey(key).export({ format: "jwk" });
|
|
184
|
+
const address = base58Encode(Buffer.from(String(jwk.x), "base64url"));
|
|
185
|
+
if (address !== parsed.address.trim()) return null;
|
|
186
|
+
if (secret.length === 64 && base58Encode(secret.subarray(32)) !== address) return null;
|
|
187
|
+
return {
|
|
188
|
+
address,
|
|
189
|
+
sign: (message) => base58Encode(cryptoSign(null, Buffer.from(message, "utf8"), key))
|
|
190
|
+
};
|
|
191
|
+
}
|
|
106
192
|
|
|
107
193
|
// src/config.ts
|
|
108
194
|
import { homedir as homedir2 } from "os";
|
|
@@ -123,7 +209,11 @@ function getConfig(env = process.env) {
|
|
|
123
209
|
}
|
|
124
210
|
|
|
125
211
|
export {
|
|
212
|
+
isSolanaSignature,
|
|
213
|
+
solanaReferenceSignature,
|
|
214
|
+
payerLinkMessage,
|
|
126
215
|
loadWallet,
|
|
216
|
+
loadSolanaWallet,
|
|
127
217
|
getConfig
|
|
128
218
|
};
|
|
129
|
-
//# sourceMappingURL=chunk-
|
|
219
|
+
//# sourceMappingURL=chunk-M37QDGMY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/wallet.ts","../src/canonical/solana.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. Private keys supplied through environment\n * variables are deliberately unsupported: the agent gets addresses and\n * canonical review signatures, never a key-ingestion API.\n * 1. An existing file is zod-validated and its address cross-checked\n * against the key; an unreadable or invalid file is NEVER overwritten.\n * 2. 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 { createPrivateKey, createPublicKey, sign as cryptoSign } from \"node:crypto\";\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\";\nimport { base58Decode, base58Encode } from \"./canonical/solana.js\";\n\nexport type WalletSource = \"agentcash\" | \"none\";\n\nexport interface LoadedWallet {\n source: WalletSource;\n account: PrivateKeyAccount | null;\n address: string | null;\n error?: string;\n errorCode?: 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 if (Object.prototype.hasOwnProperty.call(env, \"X402_PRIVATE_KEY\")) {\n return none(\n \"X402_PRIVATE_KEY is no longer supported; remove it from the CrowdCode \" +\n \"process and use the local agentcash wallet file instead\",\n \"wallet_configuration_error\",\n );\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, errorCode?: string): LoadedWallet {\n return { source: \"none\", account: null, address: null, error, errorCode };\n}\n\n/**\n * agentcash's Solana wallet, ~/.agentcash/solana-wallet.json (agentcash\n * src/wallet/svm.ts): `{ privateKey: base58(32-byte ed25519 seed), address,\n * createdAt }`. agentcash pays x402 Solana with this key, so it can sign the\n * payer link that makes a Solana review verified. Read-only: CrowdCode never\n * creates a Solana key, and a missing or invalid file just means reviews go\n * out without payer_signature.\n */\nexport interface SolanaWallet {\n address: string;\n /** ed25519 over the UTF-8 bytes of `message`; base58 signature. */\n sign(message: string): string;\n}\n\nconst solanaWalletSchema = z.object({\n privateKey: z.string().regex(/^[1-9A-HJ-NP-Za-km-z]+$/),\n address: z.string(),\n createdAt: z.string().optional(),\n});\n\n// PKCS#8 DER prefix for a raw 32-byte Ed25519 seed (RFC 8410).\nconst ED25519_PKCS8_PREFIX = Buffer.from(\"302e020100300506032b657004220420\", \"hex\");\n\nexport async function loadSolanaWallet(walletDir?: string): Promise<SolanaWallet | null> {\n let raw: string;\n try {\n raw = await readFile(join(walletDir ?? defaultWalletDir(), \"solana-wallet.json\"), \"utf8\");\n } catch {\n return null;\n }\n let parsed: z.infer<typeof solanaWalletSchema>;\n try {\n parsed = solanaWalletSchema.parse(JSON.parse(raw));\n } catch {\n return null;\n }\n const secret = base58Decode(parsed.privateKey);\n // agentcash stores the 32-byte seed; Solana CLI keypairs are seed + pubkey.\n if (secret === null || (secret.length !== 32 && secret.length !== 64)) return null;\n const key = createPrivateKey({\n key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(secret.subarray(0, 32))]),\n format: \"der\",\n type: \"pkcs8\",\n });\n const jwk = createPublicKey(key).export({ format: \"jwk\" });\n const address = base58Encode(Buffer.from(String(jwk.x), \"base64url\"));\n // Same defense as the EVM file: the stored address must derive from the key.\n if (address !== parsed.address.trim()) return null;\n if (secret.length === 64 && base58Encode(secret.subarray(32)) !== address) return null;\n return {\n address,\n sign: (message) => base58Encode(cryptoSign(null, Buffer.from(message, \"utf8\"), key)),\n };\n}\n","/**\n * Solana pieces of the review contract (mirrors src/crowdcode/solana.py and\n * payer_link_message in src/crowdcode/payments.py; spec/CANONICAL_PAYLOAD.md).\n *\n * Solana identifiers are case-sensitive base58 and are never lowercased.\n */\n\nimport { createHash } from \"node:crypto\";\n\nconst ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nconst BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;\n\nexport function base58Decode(value: string): Uint8Array | null {\n if (typeof value !== \"string\" || !BASE58_RE.test(value)) return null;\n let n = 0n;\n for (const char of value) n = n * 58n + BigInt(ALPHABET.indexOf(char));\n const body: number[] = [];\n while (n > 0n) {\n body.unshift(Number(n & 0xffn));\n n >>= 8n;\n }\n const zeros = value.length - value.replace(/^1+/, \"\").length;\n return Uint8Array.from([...new Array<number>(zeros).fill(0), ...body]);\n}\n\nexport function base58Encode(bytes: Uint8Array): string {\n let n = 0n;\n for (const byte of bytes) n = (n << 8n) | BigInt(byte);\n let out = \"\";\n while (n > 0n) {\n out = ALPHABET[Number(n % 58n)] + out;\n n /= 58n;\n }\n let zeros = 0;\n while (zeros < bytes.length && bytes[zeros] === 0) zeros++;\n return \"1\".repeat(zeros) + out;\n}\n\nfunction decodesTo(value: unknown, size: number): boolean {\n if (typeof value !== \"string\") return false;\n return base58Decode(value.trim())?.length === size;\n}\n\n/** A base58 32-byte public key. */\nexport const isSolanaAddress = (value: unknown): boolean => decodesTo(value, 32);\n/** A base58 64-byte ed25519 signature (also a Solana transaction id). */\nexport const isSolanaSignature = (value: unknown): boolean => decodesTo(value, 64);\n\n/**\n * The transaction signature named by `x402:solana:<sig>` (prefix\n * case-insensitive) or a bare base58 signature; null otherwise.\n */\nexport function solanaReferenceSignature(reference: unknown): string | null {\n if (typeof reference !== \"string\") return null;\n let cleaned = reference.trim();\n if (cleaned.slice(0, 12).toLowerCase() === \"x402:solana:\") cleaned = cleaned.slice(12);\n return isSolanaSignature(cleaned) ? cleaned : null;\n}\n\nexport const PAYER_LINK_MESSAGE_HEADER = \"CrowdCode review payer link v1\";\n\n/**\n * The text a Solana payer signs (ed25519 over its raw UTF-8 bytes; the\n * signature is sent base58 as `payer_signature`) to link its payment to a\n * review. It commits to the exact canonical review payload the reviewer\n * signed and to the reviewer's EVM wallet.\n */\nexport function payerLinkMessage(reviewerWallet: string, payload: string): string {\n return [\n PAYER_LINK_MESSAGE_HEADER,\n `reviewer_wallet:${reviewerWallet.trim().toLowerCase()}`,\n `payload_sha256:${createHash(\"sha256\").update(payload, \"utf8\").digest(\"hex\")}`,\n ].join(\"\\n\");\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 upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 15_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":";AAgBA,SAAS,kBAAkB,iBAAiB,QAAQ,kBAAkB;AACtE,SAAS,OAAO,OAAO,UAAU,iBAAiB;AAClD,SAAS,eAAe;AACxB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,kBAAkB;AAC3B,SAAS,SAAS;;;ACnBlB,SAAS,kBAAkB;AAE3B,IAAM,WAAW;AACjB,IAAM,YAAY;AAEX,SAAS,aAAa,OAAkC;AAC7D,MAAI,OAAO,UAAU,YAAY,CAAC,UAAU,KAAK,KAAK,EAAG,QAAO;AAChE,MAAI,IAAI;AACR,aAAW,QAAQ,MAAO,KAAI,IAAI,MAAM,OAAO,SAAS,QAAQ,IAAI,CAAC;AACrE,QAAM,OAAiB,CAAC;AACxB,SAAO,IAAI,IAAI;AACb,SAAK,QAAQ,OAAO,IAAI,KAAK,CAAC;AAC9B,UAAM;AAAA,EACR;AACA,QAAM,QAAQ,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AAS,UAAU,MAAyB,QAAQ,KAAa;AACtE,SAAO;AAAA,IACL,YACE,IAAI,yBAAyB;AAAA,IAC/B,UAAU,IAAI,uBAAuBC,MAAKC,SAAQ,GAAG,UAAU,eAAe;AAAA,IAC9E,cAAc,OAAO,KAAK,IAAI,2BAA2B,IAAI,YAAY,CAAC;AAAA,IAC1E,mBAAmB,OAAO,IAAI,iCAAiC,IAAM;AAAA;AAAA,IAErE,WAAW,IAAI,wBAAwB,iBAAiB;AAAA,IACxD,kBAAkB,CAAC,OAAO;AAAA,OACvB,IAAI,mCAAmC,IAAI,YAAY;AAAA,IAC1D;AAAA,EACF;AACF;","names":["homedir","join","join","homedir"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
getConfig
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-M37QDGMY.js";
|
|
5
5
|
|
|
6
6
|
// src/cli.ts
|
|
7
7
|
import { rm as rm2, stat as stat2 } from "fs/promises";
|
|
@@ -616,7 +616,7 @@ async function main() {
|
|
|
616
616
|
case void 0:
|
|
617
617
|
case "serve": {
|
|
618
618
|
routeStdoutToStderr();
|
|
619
|
-
const { startServer } = await import("./server-
|
|
619
|
+
const { startServer } = await import("./server-NAVVZUD4.js");
|
|
620
620
|
await startServer();
|
|
621
621
|
break;
|
|
622
622
|
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getConfig,
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
isSolanaSignature,
|
|
4
|
+
loadSolanaWallet,
|
|
5
|
+
loadWallet,
|
|
6
|
+
payerLinkMessage,
|
|
7
|
+
solanaReferenceSignature
|
|
8
|
+
} from "./chunk-M37QDGMY.js";
|
|
5
9
|
import {
|
|
6
10
|
buildIdentity,
|
|
7
11
|
canonicalReviewPayload,
|
|
@@ -106,7 +110,9 @@ var signingPayloadShape = {
|
|
|
106
110
|
var reviewServiceShape = {
|
|
107
111
|
rating: z.number().int().describe(RATING_DESCRIPTION),
|
|
108
112
|
reason: z.string().describe("Review text (redacted locally before sending)"),
|
|
109
|
-
payment_reference: z.string().min(1).nullish().describe(
|
|
113
|
+
payment_reference: z.string().min(1).nullish().describe(
|
|
114
|
+
"Optional unique settlement reference; omit when no payment is claimed. x402: the settlement tx hash (Base), x402:monad:<tx_hash> for Monad (eip155:143), or x402:solana:<base58 signature> for Solana (case-sensitive)"
|
|
115
|
+
),
|
|
110
116
|
review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe("Unpaid review retry identifier; generated automatically when omitted"),
|
|
111
117
|
service_id: identityShape.service_id,
|
|
112
118
|
task_context: z.string().nullish(),
|
|
@@ -123,7 +129,11 @@ var reviewServiceShape = {
|
|
|
123
129
|
review_signature: z.string().nullish().describe(
|
|
124
130
|
"Optional; crowdcode-mcp signs automatically with your local agentcash wallet. Environment private keys are not accepted. A supplied signature always wins."
|
|
125
131
|
),
|
|
126
|
-
signature_scheme: z.string().default("eip191")
|
|
132
|
+
signature_scheme: z.string().default("eip191"),
|
|
133
|
+
payer_signature: z.string().nullish().describe(
|
|
134
|
+
"x402 Solana only: base58 ed25519 signature by the Solana payer over the payer link message, which makes the review a verified purchase. crowdcode-mcp signs automatically with the agentcash Solana wallet."
|
|
135
|
+
),
|
|
136
|
+
payer_wallet: z.string().nullish().describe("x402 Solana only, optional: the base58 payer address that signed payer_signature")
|
|
127
137
|
};
|
|
128
138
|
var MIRRORED_REMOTE_TOOLS = [
|
|
129
139
|
"request_service",
|
|
@@ -136,6 +146,67 @@ var MIRRORED_REMOTE_TOOLS = [
|
|
|
136
146
|
// src/tools/sign-review.ts
|
|
137
147
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
138
148
|
|
|
149
|
+
// src/canonical/x402.ts
|
|
150
|
+
var X402_NETWORKS = {
|
|
151
|
+
base: "base",
|
|
152
|
+
"eip155:8453": "base",
|
|
153
|
+
"8453": "base",
|
|
154
|
+
monad: "monad",
|
|
155
|
+
"eip155:143": "monad",
|
|
156
|
+
"143": "monad",
|
|
157
|
+
solana: "solana",
|
|
158
|
+
// Lowercased, like every lookup key here.
|
|
159
|
+
"solana:5eykt4usfv8p8njdtrepy1vzqkqzkvdp": "solana"
|
|
160
|
+
};
|
|
161
|
+
var DEFAULT_X402_NETWORK = "base";
|
|
162
|
+
var TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;
|
|
163
|
+
function x402Network(value) {
|
|
164
|
+
if (typeof value !== "string" && typeof value !== "number") return null;
|
|
165
|
+
return X402_NETWORKS[String(value).trim().toLowerCase()] ?? null;
|
|
166
|
+
}
|
|
167
|
+
function parseProof(proof) {
|
|
168
|
+
if (typeof proof === "object" && proof !== null && !Array.isArray(proof)) {
|
|
169
|
+
return proof;
|
|
170
|
+
}
|
|
171
|
+
if (typeof proof !== "string" || proof.trim() === "") return null;
|
|
172
|
+
const cleaned = proof.trim();
|
|
173
|
+
for (const text of [cleaned, Buffer.from(cleaned, "base64").toString("utf8")]) {
|
|
174
|
+
try {
|
|
175
|
+
const parsed = JSON.parse(text);
|
|
176
|
+
if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
|
|
177
|
+
return parsed;
|
|
178
|
+
}
|
|
179
|
+
} catch {
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
function x402Settlement(proof) {
|
|
185
|
+
const parsed = parseProof(proof);
|
|
186
|
+
if (parsed === null) return null;
|
|
187
|
+
const transaction = parsed.transaction ?? parsed.transactionHash ?? parsed.txHash ?? parsed.reference;
|
|
188
|
+
const rawNetwork = parsed.network ?? parsed.chain;
|
|
189
|
+
const network = rawNetwork === void 0 || rawNetwork === null ? DEFAULT_X402_NETWORK : x402Network(rawNetwork);
|
|
190
|
+
if (typeof transaction !== "string" || network === null) return null;
|
|
191
|
+
const valid = network === "solana" ? isSolanaSignature(transaction) : TX_HASH_RE.test(transaction);
|
|
192
|
+
return valid ? { transaction, network } : null;
|
|
193
|
+
}
|
|
194
|
+
function x402PaymentReference(reference, proof) {
|
|
195
|
+
const settlement = x402Settlement(proof);
|
|
196
|
+
if (settlement === null) return reference;
|
|
197
|
+
const { transaction, network } = settlement;
|
|
198
|
+
const prefix = network === DEFAULT_X402_NETWORK ? "" : `x402:${network}:`;
|
|
199
|
+
if (reference === null || reference === void 0) return prefix + transaction;
|
|
200
|
+
const bare = reference.trim();
|
|
201
|
+
const same = network === "solana" ? bare === transaction : bare.toLowerCase() === transaction.toLowerCase();
|
|
202
|
+
if (prefix !== "" && same) return prefix + bare;
|
|
203
|
+
return reference;
|
|
204
|
+
}
|
|
205
|
+
function x402ProofPayer(proof) {
|
|
206
|
+
const payer = parseProof(proof)?.payer;
|
|
207
|
+
return typeof payer === "string" && payer.trim() !== "" ? payer.trim() : null;
|
|
208
|
+
}
|
|
209
|
+
|
|
139
210
|
// src/tools/signing-payload.ts
|
|
140
211
|
import { randomUUID } from "crypto";
|
|
141
212
|
function orNull(value) {
|
|
@@ -235,10 +306,26 @@ function isMachineProvider(value) {
|
|
|
235
306
|
return false;
|
|
236
307
|
}
|
|
237
308
|
}
|
|
309
|
+
function mayBeX402(value) {
|
|
310
|
+
if (value === null || value === void 0) return true;
|
|
311
|
+
try {
|
|
312
|
+
const provider = normalizePaymentProvider(String(value));
|
|
313
|
+
return provider === null || provider === "x402";
|
|
314
|
+
} catch {
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
238
318
|
async function prepareSignedReview(deps, args, wallet) {
|
|
239
319
|
if (args.review_signature || args.payment_reference != null && args.payment_provider && !isMachineProvider(args.payment_provider)) {
|
|
240
320
|
return { args, signed: false };
|
|
241
321
|
}
|
|
322
|
+
if (args.payment_proof != null && mayBeX402(args.payment_provider)) {
|
|
323
|
+
const reference = x402PaymentReference(
|
|
324
|
+
args.payment_reference,
|
|
325
|
+
args.payment_proof
|
|
326
|
+
);
|
|
327
|
+
if (reference !== args.payment_reference) args = { ...args, payment_reference: reference };
|
|
328
|
+
}
|
|
242
329
|
if (args.payment_reference == null) {
|
|
243
330
|
args = { ...args, review_nonce: args.review_nonce ?? randomUUID2() };
|
|
244
331
|
}
|
|
@@ -286,9 +373,11 @@ async function prepareSignedReview(deps, args, wallet) {
|
|
|
286
373
|
payload.identity
|
|
287
374
|
);
|
|
288
375
|
const signedReason = String(payload.reason);
|
|
376
|
+
const payer = args.payer_signature == null && identity.payment_provider === "x402" && solanaReferenceSignature(args.payment_reference) !== null ? await solanaPayer(wallet.walletDir, args.payment_proof) : null;
|
|
289
377
|
return {
|
|
290
378
|
args: {
|
|
291
379
|
...args,
|
|
380
|
+
...payer && loaded.address ? { payer_signature: payer.sign(payerLinkMessage(loaded.address, payload.message)) } : {},
|
|
292
381
|
// Pass the resolved identity verbatim so the backend rebuilds the exact
|
|
293
382
|
// payload that was just signed.
|
|
294
383
|
service_id: identity.service_id,
|
|
@@ -305,6 +394,7 @@ async function prepareSignedReview(deps, args, wallet) {
|
|
|
305
394
|
wallet_source: loaded.source,
|
|
306
395
|
wallet_created: loaded.created,
|
|
307
396
|
wallet: loaded,
|
|
397
|
+
...payer ? { payer_wallet: payer } : {},
|
|
308
398
|
signed_payload: {
|
|
309
399
|
identity,
|
|
310
400
|
rating: args.rating,
|
|
@@ -314,6 +404,16 @@ async function prepareSignedReview(deps, args, wallet) {
|
|
|
314
404
|
}
|
|
315
405
|
};
|
|
316
406
|
}
|
|
407
|
+
async function solanaPayer(walletDir, proof) {
|
|
408
|
+
const wallet = await loadSolanaWallet(walletDir);
|
|
409
|
+
const named = x402ProofPayer(proof);
|
|
410
|
+
return wallet && (named === null || named === wallet.address) ? wallet : null;
|
|
411
|
+
}
|
|
412
|
+
function withoutPayerSignature(prepared, args, response) {
|
|
413
|
+
if (!prepared.payer_wallet || response.error_code !== "payer_signature_invalid") return null;
|
|
414
|
+
const { payer_signature: _dropped, ...rest } = args;
|
|
415
|
+
return rest;
|
|
416
|
+
}
|
|
317
417
|
var SIGNED_IDENTITY_FIELDS = [
|
|
318
418
|
"service_id",
|
|
319
419
|
"api_endpoint",
|
|
@@ -362,8 +462,10 @@ async function resignFromMismatch(prepared, response) {
|
|
|
362
462
|
const signature = await prepared.wallet.account.signMessage({
|
|
363
463
|
message
|
|
364
464
|
});
|
|
465
|
+
const address = prepared.wallet.address;
|
|
365
466
|
return {
|
|
366
467
|
...prepared.args,
|
|
468
|
+
...prepared.payer_wallet && address ? { payer_signature: prepared.payer_wallet.sign(payerLinkMessage(address, message)) } : {},
|
|
367
469
|
service_id: identity.service_id,
|
|
368
470
|
api_endpoint: identity.api_endpoint,
|
|
369
471
|
payment_provider: identity.payment_provider,
|
|
@@ -693,10 +795,16 @@ function createToolHandlers(deps) {
|
|
|
693
795
|
});
|
|
694
796
|
}
|
|
695
797
|
let payload = await forwardPayload("review_service", prepared.args);
|
|
798
|
+
let sentArgs = prepared.args;
|
|
696
799
|
const retryArgs = await resignFromMismatch(prepared, payload);
|
|
697
800
|
if (retryArgs !== null) {
|
|
801
|
+
sentArgs = retryArgs;
|
|
698
802
|
payload = await forwardPayload("review_service", retryArgs);
|
|
699
803
|
}
|
|
804
|
+
const unlinkedArgs = withoutPayerSignature(prepared, sentArgs, payload);
|
|
805
|
+
if (unlinkedArgs !== null) {
|
|
806
|
+
payload = await forwardPayload("review_service", unlinkedArgs);
|
|
807
|
+
}
|
|
700
808
|
return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: "Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests." });
|
|
701
809
|
}
|
|
702
810
|
};
|
|
@@ -729,7 +837,9 @@ var SERVER_INSTRUCTIONS = [
|
|
|
729
837
|
"insufficient funds, and uncertain causes. Do not invent payment evidence.",
|
|
730
838
|
"When claiming payment, use the actual settlement reference and payee.",
|
|
731
839
|
"An optional payment_proof is the original base64 response header. Payment",
|
|
732
|
-
"claims must verify on x402 Base USDC or mppx Tempo.
|
|
840
|
+
"claims must verify on x402 Base/Monad/Solana USDC or mppx Tempo. Reference an x402",
|
|
841
|
+
"Monad (eip155:143) settlement as x402:monad:<tx_hash> and a Solana settlement as",
|
|
842
|
+
"x402:solana:<signature> with the Solana payee. Invalid supplied claims",
|
|
733
843
|
"are rejected, never silently downgraded. Payment verification gives the",
|
|
734
844
|
"existing verified scoring weight; unpaid signed reviews share the same",
|
|
735
845
|
"history, score, and per-wallet/service/day influence cap.",
|
|
@@ -754,7 +864,7 @@ var SERVER_INSTRUCTIONS = [
|
|
|
754
864
|
].join("\n");
|
|
755
865
|
function buildServer(deps) {
|
|
756
866
|
const server = new McpServer(
|
|
757
|
-
{ name: "crowdcode", version: "0.
|
|
867
|
+
{ name: "crowdcode", version: "0.8.0" },
|
|
758
868
|
{ instructions: SERVER_INSTRUCTIONS }
|
|
759
869
|
);
|
|
760
870
|
const handlers = createToolHandlers(deps);
|
|
@@ -804,7 +914,7 @@ function buildServer(deps) {
|
|
|
804
914
|
server.registerTool(
|
|
805
915
|
"review_service",
|
|
806
916
|
{
|
|
807
|
-
description: "Review a service experience, paid or unpaid, with a rating from 1 to 5 and concrete observations about usefulness for the original task. Review every paid outcome; unpaid successes and failures can use the same tool. Distinguish provider faults from client errors, insufficient funds, and uncertain causes. Signing with the local AgentCash wallet is automatic. Omit payment_reference and payment_proof when no payment is claimed; payment is then marked unverified. Use a stable review_nonce for unpaid retries (generated automatically if omitted). For paid reviews, supply the actual settlement reference and payee; optional payment_proof is the original base64 response header. Claims must verify on x402 Base USDC or mppx Tempo;
|
|
917
|
+
description: "Review a service experience, paid or unpaid, with a rating from 1 to 5 and concrete observations about usefulness for the original task. Review every paid outcome; unpaid successes and failures can use the same tool. Distinguish provider faults from client errors, insufficient funds, and uncertain causes. Signing with the local AgentCash wallet is automatic. Omit payment_reference and payment_proof when no payment is claimed; payment is then marked unverified. Use a stable review_nonce for unpaid retries (generated automatically if omitted). For paid reviews, supply the actual settlement reference and payee; optional payment_proof is the original base64 response header. Claims must verify on x402 Base/Monad/Solana USDC or mppx Tempo; reference an x402 Monad (eip155:143) settlement as x402:monad:<tx_hash> and a Solana one as x402:solana:<signature> (Solana payee as payment_target_ref; the agentcash Solana wallet signs payer_signature automatically). Invalid payment evidence is rejected, never downgraded. Daily scoring influence is capped. Review text is redacted locally.",
|
|
808
918
|
inputSchema: reviewServiceShape
|
|
809
919
|
},
|
|
810
920
|
(args) => handlers.review_service(args)
|
|
@@ -840,4 +950,4 @@ export {
|
|
|
840
950
|
createToolHandlers,
|
|
841
951
|
startServer
|
|
842
952
|
};
|
|
843
|
-
//# sourceMappingURL=server-
|
|
953
|
+
//# sourceMappingURL=server-NAVVZUD4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/tools/manage-reviews.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/sign-review.ts","../src/canonical/x402.ts","../src/tools/signing-payload.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 { z } from \"zod\";\nimport { Preferences } from \"./preferences.js\";\nimport { managementMessage } from \"./tools/manage-reviews.js\";\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 withoutPayerSignature,\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 preferences?: Preferences;\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.args.review_nonce != null) out.review_nonce = prepared.args.review_nonce;\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 preferences = deps.preferences ?? new Preferences();\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 const stopped = await disabled();\n if (stopped) return stopped.structuredContent;\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 async function disabled(): Promise<ToolResult | null> {\n try {\n if ((await preferences.status()).enabled) return null;\n return toToolResult({ status: \"disabled\", accepted: false, enabled: false,\n reason: \"CrowdCode is off. Continue the user's task without CrowdCode. Do not retry or queue submissions. History, deletion, and settings remain available.\" });\n } catch {\n return toToolResult({ status: \"unavailable\", accepted: false,\n error_code: \"preferences_unavailable\", reason: \"Cannot read CrowdCode preferences; no data was sent.\" });\n }\n }\n\n async function manageReviews(action: \"list\" | \"delete\", args: { review_id?: number; before_id?: number; limit?: number }) {\n const wallet = await loadWallet({ ...walletOptions, autoCreate: false });\n if (!wallet.account || !wallet.address) return toToolResult({ accepted: false,\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n reason: \"Use the original reviewing wallet to access or delete its reviews. No wallet was created.\" });\n const expires_at = Math.floor(Date.now() / 1000) + 300;\n const message = managementMessage({ action, wallet: wallet.address, expires_at, ...args });\n const authorization = await wallet.account.signMessage({ message });\n const tool = action === \"list\" ? \"list_my_reviews\" : \"delete_my_review\";\n try {\n return toToolResult(await upstream.call(tool, { ...args, reviewer_wallet: wallet.address,\n expires_at, authorization }));\n } catch (error) {\n return toToolResult(errorPayload(tool, error));\n }\n }\n\n return {\n crowdcode_status: async () => toToolResult(await preferences.status()),\n set_crowdcode_enabled: async (args: { enabled: boolean; scope?: \"session\" | \"default\" }) =>\n toToolResult(await preferences.set(args.enabled, args.scope)),\n list_my_reviews: async (args: { before_id?: number; limit?: number }) =>\n manageReviews(\"list\", { ...args, limit: args.limit ?? 25 }),\n delete_my_review: async (args: { review_id: number }) => manageReviews(\"delete\", args),\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n let outgoing = args;\n let walletCreated = false;\n if (!outgoing.requester_wallet) {\n // Demand needs an identity, not funds or permission to make a payment.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: walletOptions.autoCreate,\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 walletCreated = wallet.created === true;\n }\n }\n return toToolResult({ ...await forwardPayload(\"request_service\", outgoing),\n ...(walletCreated ? { wallet_created: true, wallet_source: \"agentcash\" } : {}) });\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\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, task_completion_reminder:\n \"Before your final answer, reflect on concrete paid services that would fix observed shortcomings. Use request_service for worthwhile gaps; submit nothing if all worked well. Respect CrowdCode off.\" });\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\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 stopped = await disabled();\n if (stopped) return stopped;\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 let sentArgs = prepared.args;\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n sentArgs = retryArgs;\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n // The local Solana key signed the payer link speculatively; if it was\n // not this transaction's payer, submit once as an unlinked observation.\n const unlinkedArgs = withoutPayerSignature(prepared, sentArgs, payload);\n if (unlinkedArgs !== null) {\n payload = await forwardPayload(\"review_service\", unlinkedArgs);\n }\n return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: \"Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests.\" });\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 \"Review each paid service outcome with review_service. Unpaid experiences use\",\n \"the same tool: omit payment_reference and payment_proof, and reuse a stable\",\n \"review_nonce on retry (automatically generated when omitted). Payment is\",\n \"explicitly marked unverified. The reviewer still signs with the local\",\n \"AgentCash wallet; signing is automatic and does not make a payment.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent).\",\n \"Describe observed outcomes; distinguish provider faults from client bugs,\",\n \"insufficient funds, and uncertain causes. Do not invent payment evidence.\",\n \"When claiming payment, use the actual settlement reference and payee.\",\n \"An optional payment_proof is the original base64 response header. Payment\",\n \"claims must verify on x402 Base/Monad/Solana USDC or mppx Tempo. Reference an x402\",\n \"Monad (eip155:143) settlement as x402:monad:<tx_hash> and a Solana settlement as\",\n \"x402:solana:<signature> with the Solana payee. Invalid supplied claims\",\n \"are rejected, never silently downgraded. Payment verification gives the\",\n \"existing verified scoring weight; unpaid signed reviews share the same\",\n \"history, score, and per-wallet/service/day influence cap.\",\n \"\",\n \"Before the final answer to each substantive user task, reflect once: what concrete\",\n \"paid service would have avoided an observed failure, poor result, expensive workaround,\",\n \"or wrong turn? This applies even if no purchase was attempted. Call request_service\",\n \"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).\",\n \"Describe the real use case, precise input, deliverable, acceptance criteria, observed\",\n \"shortcoming, and why someone would pay for that outcome. An inadequate existing service\",\n \"qualifies if you name the specific improvement. No actual payment or spend authority\",\n \"is required to report demand; do not invent a budget or claim the user agreed to pay.\",\n \"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a\",\n \"sellable remedy, and services that already worked well at reasonable cost. If nothing\",\n \"qualifies, submit nothing. Never send secrets or private user data.\",\n \"At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call\",\n \"set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default\",\n \"when they ask to remember it. Off overrides all automatic CrowdCode workflows:\",\n \"continue the user's task, skip reflection, checks and submissions; never backfill.\",\n \"Use list_my_reviews for 'show my reviews'; delete_my_review only for review IDs the\",\n \"user asks to delete. These management tools remain available while CrowdCode is off.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.8.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\"crowdcode_status\", {\n description: \"Read CrowdCode's effective on/off state and saved default locally. Check at task start.\",\n inputSchema: {}, annotations: { readOnlyHint: true },\n }, () => handlers.crowdcode_status());\n server.registerTool(\"set_crowdcode_enabled\", {\n description: \"Handle 'Crowdcode on' or 'Crowdcode off'. Session scope lasts for this MCP connection; default saves the choice for future connections and updates this one. Off stops checks, signing, reviews, and requests. History and deletion stay available. No queued backfill.\",\n inputSchema: { enabled: z.boolean(), scope: z.enum([\"session\", \"default\"]).default(\"session\") },\n }, (args) => handlers.set_crowdcode_enabled(args));\n server.registerTool(\"list_my_reviews\", {\n description: \"Show reviews submitted by the local wallet, newest first, including review IDs for deletion. Follow next_before_id to see older reviews. Works while CrowdCode is off. Locally signs an expiring ownership proof; never creates a wallet.\",\n inputSchema: { before_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), limit: z.number().int().min(1).max(100).default(25) },\n annotations: { readOnlyHint: true },\n }, (args) => handlers.list_my_reviews(args));\n server.registerTool(\"delete_my_review\", {\n description: \"Permanently delete the specific review ID requested by the user, owned by the local wallet. List reviews first if the ID is unknown. Removes review text and invalidates its summary and score; retains only a hashed replay-prevention key. Works while off. Never bulk-delete or choose IDs without user direction.\",\n inputSchema: { review_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) },\n annotations: { destructiveHint: true, idempotentHint: true },\n }, (args) => handlers.delete_my_review(args));\n\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record a concrete paid service that would have materially improved the task. \" +\n \"Before your final answer, reflect on failures, poor results, excessive cost, and \" +\n \"avoidable detours, even when no purchase was attempted. Describe the actual use \" +\n \"case, exact input, paid deliverable, acceptance criteria, what failed, and why \" +\n \"the outcome is worth paying for. Existing services may qualify when you explain \" +\n \"the specific deficiency. Example: scanned annual reports to reconciled tables \" +\n \"with page citations and confidence flags, because ordinary OCR dropped columns \" +\n \"and required manual reconciliation. Skip generic web search that worked well, \" +\n \"run-Python/local runtime wishes, and unsupported hypothetical needs. No payment \" +\n \"or spending authority is needed; never invent a budget. One request per distinct \" +\n \"gap per task; respect the returned wallet limit. Submit nothing if all worked \" +\n \"well at reasonable cost. Free text is redacted locally.\",\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 \"Review a service experience, paid or unpaid, with a rating from 1 to 5 \" +\n \"and concrete observations about usefulness for the original task. \" +\n \"Review every paid outcome; unpaid successes and failures can use the same tool. \" +\n \"Distinguish provider faults from client errors, insufficient funds, and uncertain causes. \" +\n \"Signing with the local AgentCash wallet is automatic. Omit payment_reference \" +\n \"and payment_proof when no payment is claimed; payment is then marked unverified. \" +\n \"Use a stable review_nonce for unpaid retries (generated automatically if omitted). \" +\n \"For paid reviews, supply the actual settlement reference and payee; optional \" +\n \"payment_proof is the original base64 response header. Claims must verify on \" +\n \"x402 Base/Monad/Solana USDC or mppx Tempo; reference an x402 Monad (eip155:143) settlement \" +\n \"as x402:monad:<tx_hash> and a Solana one as x402:solana:<signature> (Solana payee as \" +\n \"payment_target_ref; the agentcash Solana wallet signs payer_signature automatically). \" +\n \"Invalid payment evidence is rejected, never downgraded. \" +\n \"Daily scoring influence is capped. Review 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 if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);\n}\n","/** Domain-separated, expiring authorization; never sign a backend-supplied message. */\nexport function managementMessage(args: {\n action: \"list\" | \"delete\"; wallet: string; expires_at: number;\n review_id?: number; before_id?: number; limit?: number;\n}): string {\n return [\"CrowdCode review management v1\", `action:${args.action}`,\n `wallet:${args.wallet.toLowerCase()}`, `review_id:${args.review_id ?? 0}`,\n `before_id:${args.before_id ?? 0}`, `limit:${args.limit ?? 0}`,\n `expires_at:${args.expires_at}`].join(\"\\n\");\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 \"Concrete reusable paid offering: exact input, output or state change, \" +\n \"acceptance criteria, and why the outcome justifies payment. Ground it \" +\n \"in a real obstacle from this task, including deficiencies in existing \" +\n \"services. Example: scanned financial reports to reconciled CSV tables \" +\n \"with page citations and uncertain cells flagged, avoiding manual \" +\n \"reconstruction after OCR dropped columns. No generic local compute \" +\n \"or web search that worked well. Do not invent prices or spend authority.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Include the real use case, what was attempted, the observed failure, \" +\n \"poor quality, cost or detour, and why available alternatives fell short. \" +\n \"Omit private details. A purchase need not have been attempted.\",\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().min(1).nullish().describe(\"Optional settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Stable unique identifier for an unpaid review; reuse on retry\"),\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().min(1).nullish().describe(\n \"Optional unique settlement reference; omit when no payment is claimed. \" +\n \"x402: the settlement tx hash (Base), x402:monad:<tx_hash> for Monad (eip155:143), \" +\n \"or x402:solana:<base58 signature> for Solana (case-sensitive)\",\n ),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Unpaid review retry identifier; generated automatically when omitted\"),\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. If supplied, a payment claim must verify; \" +\n \"omit payment evidence to submit a signed review without verified payment.\",\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 payer_signature: z\n .string()\n .nullish()\n .describe(\n \"x402 Solana only: base58 ed25519 signature by the Solana payer over the \" +\n \"payer link message, which makes the review a verified purchase. \" +\n \"crowdcode-mcp signs automatically with the agentcash Solana wallet.\",\n ),\n payer_wallet: z\n .string()\n .nullish()\n .describe(\"x402 Solana only, optional: the base58 payer address that signed payer_signature\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n \"list_my_reviews\",\n \"delete_my_review\",\n] as const;\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 { randomUUID } from \"node:crypto\";\nimport {\n buildIdentity,\n normalizePaymentProvider,\n type ServiceIdentity,\n} from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport { payerLinkMessage, solanaReferenceSignature } from \"../canonical/solana.js\";\nimport { x402PaymentReference, x402ProofPayer } from \"../canonical/x402.js\";\nimport {\n loadSolanaWallet,\n loadWallet,\n type LoadedWallet,\n type SolanaWallet,\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 | null;\n review_nonce?: string | null;\n };\n signed: boolean;\n /**\n * Local agentcash Solana wallet that signed payer_signature for an x402\n * Solana review. Signing is speculative (the backend, not the client,\n * reads the transaction's payer), so a payer_signature_invalid rejection\n * is retried once without it, as an unlinked observation.\n */\n payer_wallet?: SolanaWallet;\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\nfunction mayBeX402(value: unknown): boolean {\n if (value === null || value === undefined) return true;\n try {\n const provider = normalizePaymentProvider(String(value));\n return provider === null || provider === \"x402\";\n } catch {\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 (args.review_signature || (args.payment_reference != null && args.payment_provider && !isMachineProvider(args.payment_provider))) {\n return { args, signed: false };\n }\n\n // Sign the chain-qualified reference (x402:monad:<tx>) for x402 receipts\n // settled off Base, so the reference alone tells the backend which chain\n // to verify on.\n if (args.payment_proof != null && mayBeX402(args.payment_provider)) {\n const reference = x402PaymentReference(\n args.payment_reference as string | null | undefined,\n args.payment_proof,\n );\n if (reference !== args.payment_reference) args = { ...args, payment_reference: reference };\n }\n\n if (args.payment_reference == null) {\n args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\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: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\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 const payer =\n args.payer_signature == null && identity.payment_provider === \"x402\" &&\n solanaReferenceSignature(args.payment_reference) !== null\n ? await solanaPayer(wallet.walletDir, args.payment_proof)\n : null;\n return {\n args: {\n ...args,\n ...(payer && loaded.address\n ? { payer_signature: payer.sign(payerLinkMessage(loaded.address, payload.message)) }\n : {}),\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 ...(payer ? { payer_wallet: payer } : {}),\n signed_payload: {\n identity,\n rating: args.rating as number,\n reason: signedReason,\n payment_reference: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\n },\n };\n}\n\n/**\n * The local Solana wallet, unless the proof names a different payer (then the\n * local key did not pay and its signature could only be rejected).\n */\nasync function solanaPayer(walletDir: string | undefined, proof: unknown): Promise<SolanaWallet | null> {\n const wallet = await loadSolanaWallet(walletDir);\n const named = x402ProofPayer(proof);\n return wallet && (named === null || named === wallet.address) ? wallet : null;\n}\n\n/** Retry args for an unlinked Solana observation after a payer_signature rejection. */\nexport function withoutPayerSignature(\n prepared: PreparedReview,\n args: Record<string, unknown>,\n response: Record<string, unknown>,\n): Record<string, unknown> | null {\n if (!prepared.payer_wallet || response.error_code !== \"payer_signature_invalid\") return null;\n const { payer_signature: _dropped, ...rest } = args;\n return rest;\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 reviewNonce: prepared.signed_payload.review_nonce,\n });\n if (message !== response.expected_message) return null;\n\n const signature = await prepared.wallet.account.signMessage({\n message,\n });\n const address = prepared.wallet.address;\n return {\n ...prepared.args,\n ...(prepared.payer_wallet && address\n ? { payer_signature: prepared.payer_wallet.sign(payerLinkMessage(address, message)) }\n : {}),\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","/**\n * x402 settlement references (mirrors X402_CHAINS in\n * src/crowdcode/payments.py). The backend checks a bare transaction hash on\n * Base; a settlement on another chain is referenced as\n * `x402:<network>:<tx>`, e.g. `x402:monad:0x…` for Monad (eip155:143) or\n * `x402:solana:<base58 signature>` for Solana (case-sensitive).\n */\n\nimport { isSolanaSignature } from \"./solana.js\";\n\nconst X402_NETWORKS: Record<string, string> = {\n base: \"base\",\n \"eip155:8453\": \"base\",\n \"8453\": \"base\",\n monad: \"monad\",\n \"eip155:143\": \"monad\",\n \"143\": \"monad\",\n solana: \"solana\",\n // Lowercased, like every lookup key here.\n \"solana:5eykt4usfv8p8njdtrepy1vzqkqzkvdp\": \"solana\",\n};\n\nconst DEFAULT_X402_NETWORK = \"base\";\nconst TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;\n\n/** Short x402 network name for a name, CAIP-2 id, or chain id; else null. */\nexport function x402Network(value: unknown): string | null {\n if (typeof value !== \"string\" && typeof value !== \"number\") return null;\n return X402_NETWORKS[String(value).trim().toLowerCase()] ?? null;\n}\n\nfunction parseProof(proof: unknown): Record<string, unknown> | null {\n if (typeof proof === \"object\" && proof !== null && !Array.isArray(proof)) {\n return proof as Record<string, unknown>;\n }\n if (typeof proof !== \"string\" || proof.trim() === \"\") return null;\n const cleaned = proof.trim();\n for (const text of [cleaned, Buffer.from(cleaned, \"base64\").toString(\"utf8\")]) {\n try {\n const parsed: unknown = JSON.parse(text);\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Try the next encoding.\n }\n }\n return null;\n}\n\n/**\n * The settlement named by an x402 payment-response proof (raw JSON, base64\n * header value, or object): its transaction hash and short network name.\n * A proof without a network is Base, as on the backend.\n */\nexport function x402Settlement(\n proof: unknown,\n): { transaction: string; network: string } | null {\n const parsed = parseProof(proof);\n if (parsed === null) return null;\n const transaction =\n parsed.transaction ?? parsed.transactionHash ?? parsed.txHash ?? parsed.reference;\n const rawNetwork = parsed.network ?? parsed.chain;\n const network =\n rawNetwork === undefined || rawNetwork === null\n ? DEFAULT_X402_NETWORK\n : x402Network(rawNetwork);\n if (typeof transaction !== \"string\" || network === null) return null;\n const valid = network === \"solana\" ? isSolanaSignature(transaction) : TX_HASH_RE.test(transaction);\n return valid ? { transaction, network } : null;\n}\n\n/**\n * The payment_reference to sign for an x402 review. A non-Base settlement\n * gets its `x402:<network>:` prefix so the reference alone names the chain;\n * a missing reference is taken from the proof. Anything else (Base, a\n * mismatched hash, an unparseable proof) is returned unchanged for the\n * backend to judge.\n */\nexport function x402PaymentReference(\n reference: string | null | undefined,\n proof: unknown,\n): string | null | undefined {\n const settlement = x402Settlement(proof);\n if (settlement === null) return reference;\n const { transaction, network } = settlement;\n const prefix = network === DEFAULT_X402_NETWORK ? \"\" : `x402:${network}:`;\n if (reference === null || reference === undefined) return prefix + transaction;\n const bare = reference.trim();\n // Base58 signatures are case-sensitive; EVM hashes are not.\n const same = network === \"solana\" ? bare === transaction : bare.toLowerCase() === transaction.toLowerCase();\n if (prefix !== \"\" && same) return prefix + bare;\n return reference;\n}\n\n/** The `payer` an x402 payment-response proof names, if any (unverified hint). */\nexport function x402ProofPayer(proof: unknown): string | null {\n const payer = parseProof(proof)?.payer;\n return typeof payer === \"string\" && payer.trim() !== \"\" ? payer.trim() : null;\n}\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 { randomUUID } from \"node:crypto\";\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 | null;\n review_nonce?: string | null;\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 if (args.payment_reference == null) args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\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 reviewNonce: args.review_nonce,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n ...(args.payment_reference == null ? { review_nonce: args.review_nonce } : {}),\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 (or review_nonce when payment is omitted).\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\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,KAAAA,UAAS;;;ACPX,SAAS,kBAAkB,MAGvB;AACT,SAAO;AAAA,IAAC;AAAA,IAAkC,UAAU,KAAK,MAAM;AAAA,IAC7D,UAAU,KAAK,OAAO,YAAY,CAAC;AAAA,IAAI,aAAa,KAAK,aAAa,CAAC;AAAA,IACvE,aAAa,KAAK,aAAa,CAAC;AAAA,IAAI,SAAS,KAAK,SAAS,CAAC;AAAA,IAC5D,cAAc,KAAK,UAAU;AAAA,EAAE,EAAE,KAAK,IAAI;AAC9C;;;ADEA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;AEN9B,SAAS,yBACd,SACA,MACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY;AAAA,MACV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E;","names":["z","randomUUID","randomUUID","isRecord","z"]}
|
|
@@ -88,13 +88,20 @@ For x402 and MPP/mppx, take identity and proof from the actual payment rather
|
|
|
88
88
|
than a directory listing:
|
|
89
89
|
|
|
90
90
|
- `payment_reference`: x402 settlement transaction hash or MPP
|
|
91
|
-
`Payment-Receipt` reference.
|
|
91
|
+
`Payment-Receipt` reference. For x402 on Monad (`eip155:143`) use
|
|
92
|
+
`x402:monad:<tx_hash>`; for x402 on Solana use `x402:solana:<signature>`
|
|
93
|
+
(base58, case-sensitive). A bare hash means Base unless `payment_proof` names
|
|
94
|
+
the chain.
|
|
92
95
|
- `payment_proof`: the base64 response-header value when available, not a
|
|
93
96
|
decoded object or bare transaction hash.
|
|
94
|
-
- `payment_target_ref`: the actual payment recipient/on-chain transfer payee
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
97
|
+
- `payment_target_ref`: the actual payment recipient/on-chain transfer payee
|
|
98
|
+
(the Solana payee address for x402 Solana).
|
|
99
|
+
|
|
100
|
+
Machine-payment verification currently supports x402 USDC on Base, Monad and
|
|
101
|
+
Solana, and MPP Tempo payments only. A Solana payment counts as verified only
|
|
102
|
+
when the Solana payer also signs (`payer_signature`, automatic with the
|
|
103
|
+
agentcash Solana wallet); otherwise it is recorded as observed and weighted as
|
|
104
|
+
unverified. Unsupported or invalid payment claims are rejected, never
|
|
98
105
|
silently downgraded. An experience can instead be reviewed with payment evidence
|
|
99
106
|
omitted and payment explicitly marked unverified.
|
|
100
107
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crowdcode-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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
|
"homepage": "https://www.crowdcode.app/",
|
|
6
6
|
"repository": {
|
|
@@ -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. Private keys supplied through environment\n * variables are deliberately unsupported: the agent gets addresses and\n * canonical review signatures, never a key-ingestion API.\n * 1. An existing file is zod-validated and its address cross-checked\n * against the key; an unreadable or invalid file is NEVER overwritten.\n * 2. 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 = \"agentcash\" | \"none\";\n\nexport interface LoadedWallet {\n source: WalletSource;\n account: PrivateKeyAccount | null;\n address: string | null;\n error?: string;\n errorCode?: 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 if (Object.prototype.hasOwnProperty.call(env, \"X402_PRIVATE_KEY\")) {\n return none(\n \"X402_PRIVATE_KEY is no longer supported; remove it from the CrowdCode \" +\n \"process and use the local agentcash wallet file instead\",\n \"wallet_configuration_error\",\n );\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, errorCode?: string): LoadedWallet {\n return { source: \"none\", account: null, address: null, error, errorCode };\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 upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 15_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":";AAgBA,SAAS,OAAO,OAAO,UAAU,iBAAiB;AAClD,SAAS,eAAe;AACxB,SAAS,YAAY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AAClF;AAEA,SAAS,KAAK,OAAgB,WAAkC;AAC9D,SAAO,EAAE,QAAQ,QAAQ,SAAS,MAAM,SAAS,MAAM,OAAO,UAAU;AAC1E;;;AC5KA,SAAS,WAAAA,gBAAe;AACxB,SAAS,QAAAC,aAAY;AAYrB,IAAM,SAAS,oBAAI,IAAI,CAAC,KAAK,QAAQ,KAAK,CAAC;AAEpC,SAAS,UAAU,MAAyB,QAAQ,KAAa;AACtE,SAAO;AAAA,IACL,YACE,IAAI,yBAAyB;AAAA,IAC/B,UAAU,IAAI,uBAAuBC,MAAKC,SAAQ,GAAG,UAAU,eAAe;AAAA,IAC9E,cAAc,OAAO,KAAK,IAAI,2BAA2B,IAAI,YAAY,CAAC;AAAA,IAC1E,mBAAmB,OAAO,IAAI,iCAAiC,IAAM;AAAA;AAAA,IAErE,WAAW,IAAI,wBAAwB,iBAAiB;AAAA,IACxD,kBAAkB,CAAC,OAAO;AAAA,OACvB,IAAI,mCAAmC,IAAI,YAAY;AAAA,IAC1D;AAAA,EACF;AACF;","names":["homedir","join","join","homedir"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/tools/manage-reviews.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/sign-review.ts","../src/tools/signing-payload.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 { z } from \"zod\";\nimport { Preferences } from \"./preferences.js\";\nimport { managementMessage } from \"./tools/manage-reviews.js\";\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 preferences?: Preferences;\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.args.review_nonce != null) out.review_nonce = prepared.args.review_nonce;\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 preferences = deps.preferences ?? new Preferences();\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 const stopped = await disabled();\n if (stopped) return stopped.structuredContent;\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 async function disabled(): Promise<ToolResult | null> {\n try {\n if ((await preferences.status()).enabled) return null;\n return toToolResult({ status: \"disabled\", accepted: false, enabled: false,\n reason: \"CrowdCode is off. Continue the user's task without CrowdCode. Do not retry or queue submissions. History, deletion, and settings remain available.\" });\n } catch {\n return toToolResult({ status: \"unavailable\", accepted: false,\n error_code: \"preferences_unavailable\", reason: \"Cannot read CrowdCode preferences; no data was sent.\" });\n }\n }\n\n async function manageReviews(action: \"list\" | \"delete\", args: { review_id?: number; before_id?: number; limit?: number }) {\n const wallet = await loadWallet({ ...walletOptions, autoCreate: false });\n if (!wallet.account || !wallet.address) return toToolResult({ accepted: false,\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n reason: \"Use the original reviewing wallet to access or delete its reviews. No wallet was created.\" });\n const expires_at = Math.floor(Date.now() / 1000) + 300;\n const message = managementMessage({ action, wallet: wallet.address, expires_at, ...args });\n const authorization = await wallet.account.signMessage({ message });\n const tool = action === \"list\" ? \"list_my_reviews\" : \"delete_my_review\";\n try {\n return toToolResult(await upstream.call(tool, { ...args, reviewer_wallet: wallet.address,\n expires_at, authorization }));\n } catch (error) {\n return toToolResult(errorPayload(tool, error));\n }\n }\n\n return {\n crowdcode_status: async () => toToolResult(await preferences.status()),\n set_crowdcode_enabled: async (args: { enabled: boolean; scope?: \"session\" | \"default\" }) =>\n toToolResult(await preferences.set(args.enabled, args.scope)),\n list_my_reviews: async (args: { before_id?: number; limit?: number }) =>\n manageReviews(\"list\", { ...args, limit: args.limit ?? 25 }),\n delete_my_review: async (args: { review_id: number }) => manageReviews(\"delete\", args),\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n let outgoing = args;\n let walletCreated = false;\n if (!outgoing.requester_wallet) {\n // Demand needs an identity, not funds or permission to make a payment.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: walletOptions.autoCreate,\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 walletCreated = wallet.created === true;\n }\n }\n return toToolResult({ ...await forwardPayload(\"request_service\", outgoing),\n ...(walletCreated ? { wallet_created: true, wallet_source: \"agentcash\" } : {}) });\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\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, task_completion_reminder:\n \"Before your final answer, reflect on concrete paid services that would fix observed shortcomings. Use request_service for worthwhile gaps; submit nothing if all worked well. Respect CrowdCode off.\" });\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\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 stopped = await disabled();\n if (stopped) return stopped;\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), task_completion_reminder: \"Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests.\" });\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 \"Review each paid service outcome with review_service. Unpaid experiences use\",\n \"the same tool: omit payment_reference and payment_proof, and reuse a stable\",\n \"review_nonce on retry (automatically generated when omitted). Payment is\",\n \"explicitly marked unverified. The reviewer still signs with the local\",\n \"AgentCash wallet; signing is automatic and does not make a payment.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent).\",\n \"Describe observed outcomes; distinguish provider faults from client bugs,\",\n \"insufficient funds, and uncertain causes. Do not invent payment evidence.\",\n \"When claiming payment, use the actual settlement reference and payee.\",\n \"An optional payment_proof is the original base64 response header. Payment\",\n \"claims must verify on x402 Base USDC or mppx Tempo. Invalid supplied claims\",\n \"are rejected, never silently downgraded. Payment verification gives the\",\n \"existing verified scoring weight; unpaid signed reviews share the same\",\n \"history, score, and per-wallet/service/day influence cap.\",\n \"\",\n \"Before the final answer to each substantive user task, reflect once: what concrete\",\n \"paid service would have avoided an observed failure, poor result, expensive workaround,\",\n \"or wrong turn? This applies even if no purchase was attempted. Call request_service\",\n \"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).\",\n \"Describe the real use case, precise input, deliverable, acceptance criteria, observed\",\n \"shortcoming, and why someone would pay for that outcome. An inadequate existing service\",\n \"qualifies if you name the specific improvement. No actual payment or spend authority\",\n \"is required to report demand; do not invent a budget or claim the user agreed to pay.\",\n \"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a\",\n \"sellable remedy, and services that already worked well at reasonable cost. If nothing\",\n \"qualifies, submit nothing. Never send secrets or private user data.\",\n \"At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call\",\n \"set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default\",\n \"when they ask to remember it. Off overrides all automatic CrowdCode workflows:\",\n \"continue the user's task, skip reflection, checks and submissions; never backfill.\",\n \"Use list_my_reviews for 'show my reviews'; delete_my_review only for review IDs the\",\n \"user asks to delete. These management tools remain available while CrowdCode is off.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.6.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\"crowdcode_status\", {\n description: \"Read CrowdCode's effective on/off state and saved default locally. Check at task start.\",\n inputSchema: {}, annotations: { readOnlyHint: true },\n }, () => handlers.crowdcode_status());\n server.registerTool(\"set_crowdcode_enabled\", {\n description: \"Handle 'Crowdcode on' or 'Crowdcode off'. Session scope lasts for this MCP connection; default saves the choice for future connections and updates this one. Off stops checks, signing, reviews, and requests. History and deletion stay available. No queued backfill.\",\n inputSchema: { enabled: z.boolean(), scope: z.enum([\"session\", \"default\"]).default(\"session\") },\n }, (args) => handlers.set_crowdcode_enabled(args));\n server.registerTool(\"list_my_reviews\", {\n description: \"Show reviews submitted by the local wallet, newest first, including review IDs for deletion. Follow next_before_id to see older reviews. Works while CrowdCode is off. Locally signs an expiring ownership proof; never creates a wallet.\",\n inputSchema: { before_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), limit: z.number().int().min(1).max(100).default(25) },\n annotations: { readOnlyHint: true },\n }, (args) => handlers.list_my_reviews(args));\n server.registerTool(\"delete_my_review\", {\n description: \"Permanently delete the specific review ID requested by the user, owned by the local wallet. List reviews first if the ID is unknown. Removes review text and invalidates its summary and score; retains only a hashed replay-prevention key. Works while off. Never bulk-delete or choose IDs without user direction.\",\n inputSchema: { review_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) },\n annotations: { destructiveHint: true, idempotentHint: true },\n }, (args) => handlers.delete_my_review(args));\n\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record a concrete paid service that would have materially improved the task. \" +\n \"Before your final answer, reflect on failures, poor results, excessive cost, and \" +\n \"avoidable detours, even when no purchase was attempted. Describe the actual use \" +\n \"case, exact input, paid deliverable, acceptance criteria, what failed, and why \" +\n \"the outcome is worth paying for. Existing services may qualify when you explain \" +\n \"the specific deficiency. Example: scanned annual reports to reconciled tables \" +\n \"with page citations and confidence flags, because ordinary OCR dropped columns \" +\n \"and required manual reconciliation. Skip generic web search that worked well, \" +\n \"run-Python/local runtime wishes, and unsupported hypothetical needs. No payment \" +\n \"or spending authority is needed; never invent a budget. One request per distinct \" +\n \"gap per task; respect the returned wallet limit. Submit nothing if all worked \" +\n \"well at reasonable cost. Free text is redacted locally.\",\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 \"Review a service experience, paid or unpaid, with a rating from 1 to 5 \" +\n \"and concrete observations about usefulness for the original task. \" +\n \"Review every paid outcome; unpaid successes and failures can use the same tool. \" +\n \"Distinguish provider faults from client errors, insufficient funds, and uncertain causes. \" +\n \"Signing with the local AgentCash wallet is automatic. Omit payment_reference \" +\n \"and payment_proof when no payment is claimed; payment is then marked unverified. \" +\n \"Use a stable review_nonce for unpaid retries (generated automatically if omitted). \" +\n \"For paid reviews, supply the actual settlement reference and payee; optional \" +\n \"payment_proof is the original base64 response header. Claims must verify on \" +\n \"x402 Base USDC or mppx Tempo; invalid payment evidence is rejected, never downgraded. \" +\n \"Daily scoring influence is capped. Review 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 if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);\n}\n","/** Domain-separated, expiring authorization; never sign a backend-supplied message. */\nexport function managementMessage(args: {\n action: \"list\" | \"delete\"; wallet: string; expires_at: number;\n review_id?: number; before_id?: number; limit?: number;\n}): string {\n return [\"CrowdCode review management v1\", `action:${args.action}`,\n `wallet:${args.wallet.toLowerCase()}`, `review_id:${args.review_id ?? 0}`,\n `before_id:${args.before_id ?? 0}`, `limit:${args.limit ?? 0}`,\n `expires_at:${args.expires_at}`].join(\"\\n\");\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 \"Concrete reusable paid offering: exact input, output or state change, \" +\n \"acceptance criteria, and why the outcome justifies payment. Ground it \" +\n \"in a real obstacle from this task, including deficiencies in existing \" +\n \"services. Example: scanned financial reports to reconciled CSV tables \" +\n \"with page citations and uncertain cells flagged, avoiding manual \" +\n \"reconstruction after OCR dropped columns. No generic local compute \" +\n \"or web search that worked well. Do not invent prices or spend authority.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Include the real use case, what was attempted, the observed failure, \" +\n \"poor quality, cost or detour, and why available alternatives fell short. \" +\n \"Omit private details. A purchase need not have been attempted.\",\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().min(1).nullish().describe(\"Optional settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Stable unique identifier for an unpaid review; reuse on retry\"),\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().min(1).nullish().describe(\"Optional unique settlement reference; omit when no payment is claimed\"),\n review_nonce: z.string().regex(/^[A-Za-z0-9_-]{8,128}$/).nullish().describe(\"Unpaid review retry identifier; generated automatically when omitted\"),\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. If supplied, a payment claim must verify; \" +\n \"omit payment evidence to submit a signed review without verified payment.\",\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 \"list_my_reviews\",\n \"delete_my_review\",\n] as const;\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 { randomUUID } from \"node:crypto\";\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 | null;\n review_nonce?: string | null;\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 (args.review_signature || (args.payment_reference != null && args.payment_provider && !isMachineProvider(args.payment_provider))) {\n return { args, signed: false };\n }\n\n if (args.payment_reference == null) {\n args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\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: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\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: args.payment_reference as string | null | undefined,\n review_nonce: args.review_nonce as string | null | undefined,\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 reviewNonce: prepared.signed_payload.review_nonce,\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","/**\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 { randomUUID } from \"node:crypto\";\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 | null;\n review_nonce?: string | null;\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 if (args.payment_reference == null) args = { ...args, review_nonce: args.review_nonce ?? randomUUID() };\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 reviewNonce: args.review_nonce,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n ...(args.payment_reference == null ? { review_nonce: args.review_nonce } : {}),\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 (or review_nonce when payment is omitted).\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\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,KAAAA,UAAS;;;ACPX,SAAS,kBAAkB,MAGvB;AACT,SAAO;AAAA,IAAC;AAAA,IAAkC,UAAU,KAAK,MAAM;AAAA,IAC7D,UAAU,KAAK,OAAO,YAAY,CAAC;AAAA,IAAI,aAAa,KAAK,aAAa,CAAC;AAAA,IACvE,aAAa,KAAK,aAAa,CAAC;AAAA,IAAI,SAAS,KAAK,SAAS,CAAC;AAAA,IAC5D,cAAc,KAAK,UAAU;AAAA,EAAE,EAAE,KAAK,IAAI;AAC9C;;;ADEA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;AEN9B,SAAS,yBACd,SACA,MACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY;AAAA,MACV,kBAAkB,KAAK;AAAA,MACvB,cAAc,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aAAa,SAI3B;AACA,SAAO;AAAA,IACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,EAAE,CAAC;AAAA,IACzD,mBAAmB;AAAA,IACnB,GAAI,QAAQ,WAAW,gBAAgB,EAAE,SAAS,KAAK,IA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