crowdcode-mcp 0.1.2 → 0.2.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/signing-payload.ts","../src/tools/sign-review.ts","../src/upstream.ts"],"sourcesContent":["/**\n * The stdio MCP server. Advertises the same tools as the CrowdCode backend;\n * free-text arguments are redacted locally (Rampart + secret recognizers)\n * before forwarding over streamable-HTTP, and get_review_signing_payload is\n * served entirely locally so raw review text never leaves this machine at\n * signing time.\n */\n\nimport { RedactionEngine } from \"@crowdcode/redaction\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { toToolResult, withRedactionAttestation } from \"./attestation.js\";\nimport { getConfig } from \"./config.js\";\nimport { redactArgs } from \"./redaction/policy.js\";\nimport {\n MIRRORED_REMOTE_TOOLS,\n getServiceScoreShape,\n requestServiceShape,\n reviewServiceShape,\n signingPayloadShape,\n} from \"./schemas.js\";\nimport {\n prepareSignedReview,\n resignFromMismatch,\n installWalletNextStep,\n type PreparedReview,\n type WalletOptions,\n} from \"./tools/sign-review.js\";\nimport {\n getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, UpstreamError, type Upstream } from \"./upstream.js\";\nimport { loadWallet } from \"./wallet.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n err: unknown,\n): Record<string, unknown> {\n const message =\n err instanceof UpstreamError\n ? err.message\n : `could not reach the CrowdCode backend: ${(err as Error).message}`;\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend may be cold-starting (free-tier hosting); retry \" +\n \"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 found: false,\n avg_rating: null,\n num_reviews: 0,\n recent_reviews: [],\n reason: message,\n next_step,\n };\n }\n return { accepted: false, reason: message, next_step };\n}\n\nfunction withWalletInfo(\n payload: Record<string, unknown>,\n prepared: PreparedReview,\n): Record<string, unknown> {\n const out = { ...payload };\n if (prepared.wallet_source !== undefined) {\n out.wallet_source = prepared.wallet_source;\n }\n if (prepared.wallet_created) out.wallet_created = true;\n if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;\n if (out.next_step === undefined && prepared.next_step) {\n out.next_step = prepared.next_step;\n }\n return out;\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n const config = getConfig();\n const walletOptions: WalletOptions = {\n walletDir: deps.wallet?.walletDir ?? config.walletDir,\n autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,\n env: deps.wallet?.env,\n };\n const signingDeps = { redact: (text: string) => engine.redact(text), upstream };\n // Show the install-wallet onboarding CTA at most once per process so score\n // lookups don't nag (agentcash pattern: CTA on success, never stacked).\n let onboardingCtaShown = false;\n\n async function forwardPayload(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const redacted = await redactArgs(engine, tool, args);\n try {\n const result = await upstream.call(tool, redacted.args);\n return withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n });\n } catch (err) {\n return errorPayload(tool, err);\n }\n }\n\n return {\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let outgoing = args;\n if (!outgoing.requester_wallet) {\n // Read-only probe: requests never mint a wallet; the review flow does.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.address) {\n outgoing = { ...outgoing, requester_wallet: wallet.address };\n }\n }\n return toToolResult(await forwardPayload(\"request_service\", outgoing));\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let payload: Record<string, unknown>;\n try {\n payload = await upstream.call(\"get_service_score\", args);\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n const provider = payload.payment_provider;\n if (\n !onboardingCtaShown &&\n payload.found === true &&\n (provider === \"mppx\" || provider === \"x402\")\n ) {\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.source === \"none\") {\n onboardingCtaShown = true;\n payload = {\n ...payload,\n onboarding_cta: {\n message:\n \"This is a paid x402/mppx service and you have no local \" +\n \"signing wallet yet. Install agentcash (or set \" +\n \"X402_PRIVATE_KEY) so your post-purchase review can be \" +\n \"signed and counted.\",\n command: installWalletNextStep(\"review_service\").command,\n },\n };\n }\n }\n return toToolResult(payload);\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = await loadWallet(walletOptions);\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n return toToolResult(withWalletInfo(payload, prepared));\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"\",\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 avg_rating, using num_reviews as sample-size\",\n \"context; with few or no reviews, fall back to price and the spend policy.\",\n \"\",\n \"After ANY paid use — success, slow response, or failure: submit a review.\",\n \"A slow or broken paid call is not a reason to skip the review; it IS the\",\n \"review (slowness or breakage goes in the rating and reason). Rate against\",\n \"the ORIGINAL task you were solving: was the response relevant and did it\",\n \"actually help answer that question? Fixed scale: 5 = excellent (clear\",\n \"schema, relevant output that answered the original question, fast, clean\",\n \"receipt — would reuse confidently); 4 = helped but a real\",\n \"schema/docs/latency/output caveat; 3 = paid but response thin, confusing,\",\n \"needed guesswork, or not actually relevant/helpful for the task (a\",\n \"technically valid answer that did not help is a 3 at best); 2 = paid but\",\n \"poor (client error, unclear failure, hard to use); 1 = paid and broken\",\n \"(server error, unusable output, misleading challenge, timeout/severe\",\n \"reliability). A service that simply worked well AND helped is a 5 — do\",\n \"not hedge to 4 without a concrete caveat.\",\n \"\",\n \"Signing is AUTOMATIC: review_service signs with your local wallet\",\n \"(X402_PRIVATE_KEY, or the agentcash wallet at ~/.agentcash/wallet.json,\",\n \"auto-created if missing) — you do not need get_review_signing_payload or\",\n \"an external signer. Responses include wallet_source (env | agentcash |\",\n \"none). For x402/mppx, take identity and proofs from the ACTUAL payment,\",\n \"not a directory listing: payment_reference = the settlement tx hash (x402)\",\n \"or Payment-Receipt reference (mppx); payment_proof = the base64 response\",\n \"header string (payment-response for x402, Payment-Receipt for mppx), not\",\n \"the tx hash or decoded JSON — payment_proof is OPTIONAL but strongly\",\n \"encouraged: with it the review counts as a verified purchase (double the\",\n \"scoring weight of an unverified one); payment_target_ref = the real\",\n \"on-chain payee (the 402 challenge recipient / Transfer `to`), not a\",\n \"directory payTo.\",\n \"\",\n \"Workflow: 1) get_service_score on each candidate; 2) pay and use the\",\n \"service; 3) review_service with the payment_reference and (ideally) the\",\n \"payment_proof header. Reviews are limited to 1 per service per wallet per\",\n \"24h; failed calls return a next_step object with the exact command or\",\n \"retry that fixes them — follow it.\",\n \"\",\n \"When no fitting paid service exists, call request_service once with a\",\n \"specific, reusable capability description (requires a wallet identity,\",\n \"attached automatically; limited to 5 requests per wallet per 24h). Only\",\n \"request things a provider could sell as a remote paid API — the test is:\",\n \"could you pay for it with an x402/mpp request to someone else's endpoint?\",\n \"Never runtime or agent-harness wishes (context management, local compute).\",\n \"Never send secrets or private data — free-text fields are redacted locally\",\n \"before anything is sent.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.2.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Capture an unmet, reusable service request for future directory \" +\n \"coverage. Use only when no fitting paid or external service exists. \" +\n \"Only request capabilities a provider could sell as a remote paid API \" +\n \"(x402/mppx/Stripe) — the test: could you pay for it with an x402/mpp \" +\n \"request to someone else's endpoint? Describe a specific capability \" +\n \"with clear inputs and outputs, general enough to apply to multiple \" +\n \"users. Good: 'resolve a citation like Smith et al. 2019 to the \" +\n \"actual paper, or report that it does not exist'; 'semantic search \" +\n \"over paywalled full-text academic PDFs returning page-level \" +\n \"citations'; 'live versioned registry of current API schemas'. Bad: \" +\n \"wishes about your own runtime or harness ('cleaner context', 'more \" +\n \"memory', local compute/IDE features) and one-off task help ('fix my \" +\n \"CI'). Requires a wallet identity (attached automatically from your \" +\n \"local agentcash/X402_PRIVATE_KEY wallet); limited to 5 requests per \" +\n \"wallet per 24h. Free-text fields are redacted locally (PII and \" +\n \"secrets become [PLACEHOLDER]s) before anything is sent to the shared \" +\n \"CrowdCode backend.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the average rating, review count, and recent reviews for a \" +\n \"service, identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Submit a review after paying for a service — call this after EVERY \" +\n \"paid x402/mppx use, including slow responses and failures. A bad \" +\n \"outcome is not a reason to skip the review; it IS the review: rate \" +\n \"1-2 with the failure in the reason. Rate against the ORIGINAL task \" +\n \"you were solving: was the response relevant and did it actually \" +\n \"help answer that question? Rating scale: 5 = excellent (clear \" +\n \"schema, relevant output that answered the original question, fast, \" +\n \"clean receipt — would reuse confidently); 4 = helped but a real \" +\n \"schema/docs/latency/output caveat; 3 = paid but \" +\n \"thin/confusing/needed guesswork or not actually relevant/helpful \" +\n \"for the task (a technically valid answer that did not help is a 3 \" +\n \"at best); 2 = paid but poor (client error, unclear failure, hard \" +\n \"to use); 1 = paid and broken (server error, unusable output, \" +\n \"misleading challenge, timeout). A service that simply worked well \" +\n \"AND helped is a 5 — do not hedge to 4 without a concrete caveat. \" +\n \"SIGNING IS AUTOMATIC: this tool signs with your local \" +\n \"agentcash/X402_PRIVATE_KEY wallet (auto-created if missing) — do not \" +\n \"call get_review_signing_payload or sign externally. Get identity and \" +\n \"proofs from the ACTUAL payment, not a directory listing: \" +\n \"payment_reference = the settlement tx hash (x402) or Payment-Receipt \" +\n \"`reference` (mppx); \" +\n \"payment_proof = the base64 response header STRING — `payment-response` \" +\n \"for x402, `Payment-Receipt` for mppx — NOT the tx hash and NOT decoded \" +\n \"JSON. payment_proof is OPTIONAL but strongly encouraged: with it the \" +\n \"review is a verified purchase (double scoring weight); \" +\n \"payment_target_ref = the real payee (the 402 challenge recipient / \" +\n \"on-chain Transfer `to`), not a bazaar/directory payTo. If you paid \" +\n \"from a different wallet than the local one, pass reviewer_wallet and \" +\n \"review_signature yourself (the wallet that SENT the payment — the \" +\n \"ERC-20 Transfer `from`, not the gasless facilitator). Limited to 1 \" +\n \"review per service per wallet per 24h. Free-text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n void warnOnToolDrift(upstream);\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n} {\n return { content: [{ type: \"text\", text: JSON.stringify(payload) }] };\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 \"Specific, reusable capability that a provider could sell as a remote \" +\n \"paid API (x402/mppx/Stripe) — something you could pay for with an \" +\n \"HTTP request to someone else's endpoint. Include clear inputs and \" +\n \"outputs. Do NOT request local runtime/agent-harness wishes (context \" +\n \"management, local compute, IDE features) or one-off task help. Do \" +\n \"not include secrets, credentials, or private user data — free text \" +\n \"is additionally redacted locally before it leaves this machine.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\"Optional context about the task that needed this service\"),\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/X402_PRIVATE_KEY wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().describe(\"Payment reference for this review\"),\n ...identityShape,\n auto_sign: z\n .boolean()\n .nullish()\n .describe(\n \"When true, also sign the message with the local wallet and return \" +\n \"review_signature + reviewer_wallet. Usually unnecessary: \" +\n \"review_service signs automatically.\",\n ),\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().describe(\"Unique payment reference\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z\n .string()\n .nullish()\n .describe(\n \"Strongly recommended: the base64 payment-response (x402) or \" +\n \"Payment-Receipt (mppx) header string. Omitting it stores the review \" +\n \"as UNVERIFIED, which carries half weight in scoring.\",\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/X402_PRIVATE_KEY wallet. A supplied signature always wins.\",\n ),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n] as const;\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The identity-merge logic mirrors the backend exactly\n * (src/crowdcode/server.py review_service effective_identity): the server\n * verifies signatures by REBUILDING the payload from its own resolved\n * identity, so the message signed here must match that reconstruction\n * byte-for-byte. Canonical identity comes from get_service_score when the\n * service exists; otherwise the caller-provided identity is used verbatim,\n * exactly like the old remote signing tool.\n */\n\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference: string;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n // Same merge as the backend: caller-normalized fields win, canonical\n // values fill the gaps, and the result is re-normalized.\n effective = buildIdentity({\n service_id: orNull(score.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: identity.api_endpoint ?? orNull(score.canonical_endpoint),\n payment_provider:\n identity.payment_provider ?? orNull(score.payment_provider),\n payment_target_ref:\n identity.payment_target_ref ?? orNull(score.payment_target_ref),\n directory_slug: identity.directory_slug ?? orNull(score.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference.\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","/**\n * Transparent in-process signing for review_service.\n *\n * For mppx/x402 reviews where the caller did not supply review_signature,\n * this builds the canonical message (identity-merge + local redaction via\n * getReviewSigningPayload), signs it with the local agentcash wallet (or\n * X402_PRIVATE_KEY), and augments the outgoing arguments — so an agent can\n * call review_service 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 { normalizePaymentProvider } from \"../canonical/identity.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 (or set \" +\n \"X402_PRIVATE_KEY) so crowdcode-mcp can 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 next_step?: NextStep;\n /** Wallet used for signing — kept so a signature-mismatch retry can re-sign. */\n wallet?: LoadedWallet;\n signed: boolean;\n}\n\nfunction isMachineProvider(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n try {\n const provider = normalizePaymentProvider(value);\n return provider === \"mppx\" || provider === \"x402\";\n } catch {\n // Unknown provider: forward as-is and let the backend produce its error.\n return false;\n }\n}\n\nexport async function prepareSignedReview(\n deps: SigningDeps,\n args: Record<string, unknown>,\n wallet: WalletOptions,\n): Promise<PreparedReview> {\n if (!isMachineProvider(args.payment_provider) || args.review_signature) {\n return { args, signed: false };\n }\n\n const loaded = await loadWallet({\n walletDir: wallet.walletDir,\n autoCreate: wallet.autoCreate,\n env: wallet.env,\n });\n if (loaded.source === \"none\" || loaded.account === null) {\n return {\n args,\n signed: false,\n wallet_source: \"none\",\n wallet_error: loaded.error,\n next_step: installWalletNextStep(\"review_service\"),\n };\n }\n\n const payload = await getReviewSigningPayload(deps, {\n rating: args.rating as number,\n reason: String(args.reason ?? \"\"),\n payment_reference: String(args.payment_reference ?? \"\"),\n service_id: args.service_id as string | null | undefined,\n api_endpoint: args.api_endpoint as string | null | undefined,\n payment_provider: args.payment_provider as string | null | undefined,\n payment_target_ref: args.payment_target_ref as string | null | undefined,\n directory_slug: args.directory_slug as string | null | undefined,\n });\n if (payload.ok !== true || typeof payload.message !== \"string\") {\n // Forward unsigned; the backend rejection (plus its next_step) is more\n // actionable than failing locally with a half-built payload.\n return {\n args,\n signed: false,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet_error: `could not build the signing payload locally: ${String(\n payload.reason ?? \"unknown error\",\n )}`,\n };\n }\n\n const signature = await loaded.account.signMessage({\n message: payload.message,\n });\n const identity = payload.identity as Record<string, unknown>;\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 ?? args.service_id,\n api_endpoint: identity.api_endpoint ?? args.api_endpoint,\n payment_provider: identity.payment_provider ?? args.payment_provider,\n payment_target_ref: identity.payment_target_ref ?? args.payment_target_ref,\n directory_slug: identity.directory_slug ?? args.directory_slug,\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 };\n}\n\n/**\n * Handle the backend's signature-mismatch recovery contract: re-sign the\n * returned expected_message with the same wallet and rebuild the args using\n * resolved_identity. Returns null when the response is not a recoverable\n * mismatch (or we did not sign locally in the first place).\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 (response.accepted !== false) return null;\n if (typeof response.expected_message !== \"string\") return null;\n\n const identity = (response.resolved_identity ?? {}) as Record<string, unknown>;\n const signature = await prepared.wallet.account.signMessage({\n message: response.expected_message,\n });\n return {\n ...prepared.args,\n service_id: identity.service_id ?? prepared.args.service_id,\n api_endpoint: identity.api_endpoint ?? prepared.args.api_endpoint,\n payment_provider: identity.payment_provider ?? prepared.args.payment_provider,\n payment_target_ref:\n identity.payment_target_ref ?? prepared.args.payment_target_ref,\n directory_slug: identity.directory_slug ?? prepared.args.directory_slug,\n review_signature: signature,\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACH9B,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,SAE3B;AACA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,EAAE,CAAC,EAAE;AACtE;;;ACXO,IAAM,mBAAsD;AAAA,EACjE,iBAAiB,CAAC,uBAAuB,cAAc;AAAA,EACvD,gBAAgB,CAAC,UAAU,cAAc;AAC3C;AAQA,eAAsB,WACpB,QACA,MACA,MACuB;AACvB,QAAM,SAAS,iBAAiB,IAAI,KAAK,CAAC;AAC1C,QAAM,MAAM,EAAE,GAAG,KAAK;AACtB,MAAI,kBAAkB;AACtB,MAAI,cAAc,OAAO;AACzB,aAAW,SAAS,QAAQ;AAC1B,UAAM,QAAQ,IAAI,KAAK;AACvB,QAAI,OAAO,UAAU,YAAY,UAAU,GAAI;AAC/C,UAAM,SAAS,MAAM,OAAO,OAAO,KAAK;AACxC,QAAI,KAAK,IAAI,OAAO;AACpB,uBAAmB,OAAO;AAC1B,kBAAc,OAAO;AAAA,EACvB;AACA,SAAO,EAAE,MAAM,KAAK,iBAAiB,YAAY;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"0.2.0",
4
4
  "description": "CrowdCode MCP client with local-first PII redaction. Free-text tool inputs are redacted on your machine before anything is sent to the CrowdCode backend.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -27,6 +27,7 @@
27
27
  "dependencies": {
28
28
  "@crowdcode/redaction": "^0.1.0",
29
29
  "@modelcontextprotocol/sdk": "^1.29.0",
30
+ "viem": "^2.55.8",
30
31
  "zod": "^3.24.0"
31
32
  },
32
33
  "devDependencies": {
@@ -1,18 +0,0 @@
1
- // src/config.ts
2
- import { homedir } from "os";
3
- import { join } from "path";
4
- var TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes"]);
5
- function getConfig(env = process.env) {
6
- return {
7
- backendUrl: env.CROWDCODE_BACKEND_URL ?? "https://crowdcode-backend.onrender.com/mcp",
8
- cacheDir: env.CROWDCODE_CACHE_DIR ?? join(homedir(), ".cache", "crowdcode-mcp"),
9
- disableModel: TRUTHY.has((env.CROWDCODE_DISABLE_MODEL ?? "").toLowerCase()),
10
- // Generous default: the free-tier Render backend cold-starts slowly.
11
- upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 6e4)
12
- };
13
- }
14
-
15
- export {
16
- getConfig
17
- };
18
- //# sourceMappingURL=chunk-ZOKWC7AU.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config.ts"],"sourcesContent":["import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport interface Config {\n backendUrl: string;\n cacheDir: string;\n disableModel: boolean;\n upstreamTimeoutMs: number;\n}\n\nconst TRUTHY = new Set([\"1\", \"true\", \"yes\"]);\n\nexport function getConfig(env: NodeJS.ProcessEnv = process.env): Config {\n return {\n backendUrl:\n env.CROWDCODE_BACKEND_URL ?? \"https://crowdcode-backend.onrender.com/mcp\",\n cacheDir: env.CROWDCODE_CACHE_DIR ?? join(homedir(), \".cache\", \"crowdcode-mcp\"),\n disableModel: TRUTHY.has((env.CROWDCODE_DISABLE_MODEL ?? \"\").toLowerCase()),\n // Generous default: the free-tier Render backend cold-starts slowly.\n upstreamTimeoutMs: Number(env.CROWDCODE_UPSTREAM_TIMEOUT_MS ?? 60_000),\n };\n}\n"],"mappings":";AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AASrB,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,uBAAuB,KAAK,QAAQ,GAAG,UAAU,eAAe;AAAA,IAC9E,cAAc,OAAO,KAAK,IAAI,2BAA2B,IAAI,YAAY,CAAC;AAAA;AAAA,IAE1E,mBAAmB,OAAO,IAAI,iCAAiC,GAAM;AAAA,EACvE;AACF;","names":[]}
@@ -1,391 +0,0 @@
1
- import {
2
- getConfig
3
- } from "./chunk-ZOKWC7AU.js";
4
- import {
5
- buildIdentity,
6
- canonicalReviewPayload
7
- } from "./chunk-URCCBSON.js";
8
-
9
- // src/server.ts
10
- import { RedactionEngine } from "@crowdcode/redaction";
11
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
13
-
14
- // src/attestation.ts
15
- function withRedactionAttestation(payload, info) {
16
- return {
17
- ...payload,
18
- _redaction: {
19
- entities_removed: info.entitiesRemoved,
20
- model_active: info.modelActive
21
- }
22
- };
23
- }
24
- function toToolResult(payload) {
25
- return { content: [{ type: "text", text: JSON.stringify(payload) }] };
26
- }
27
-
28
- // src/redaction/policy.ts
29
- var REDACTION_POLICY = {
30
- request_service: ["service_description", "task_context"],
31
- review_service: ["reason", "task_context"]
32
- };
33
- async function redactArgs(engine, tool, args) {
34
- const fields = REDACTION_POLICY[tool] ?? [];
35
- const out = { ...args };
36
- let entitiesRemoved = 0;
37
- let modelActive = engine.modelActive;
38
- for (const field of fields) {
39
- const value = out[field];
40
- if (typeof value !== "string" || value === "") continue;
41
- const result = await engine.redact(value);
42
- out[field] = result.text;
43
- entitiesRemoved += result.entitiesRemoved;
44
- modelActive = result.modelActive;
45
- }
46
- return { args: out, entitiesRemoved, modelActive };
47
- }
48
-
49
- // src/schemas.ts
50
- import { z } from "zod";
51
- var identityShape = {
52
- service_id: z.string().nullish().describe("Canonical service id (svc_...)"),
53
- api_endpoint: z.string().nullish().describe("Service API endpoint URL"),
54
- payment_provider: z.string().nullish().describe("One of: stripe, stripe_payment_link, mppx, x402, manual"),
55
- payment_target_ref: z.string().nullish().describe("Payment recipient reference (wallet address, account id, ...)"),
56
- directory_slug: z.string().nullish().describe("Directory slug if known")
57
- };
58
- var requestServiceShape = {
59
- service_description: z.string().describe(
60
- "Specific, reusable service capability with clear inputs and outputs. Do not include secrets, credentials, or private user data \u2014 free text is additionally redacted locally before it leaves this machine."
61
- ),
62
- task_context: z.string().nullish().describe("Optional context about the task that needed this service")
63
- };
64
- var getServiceScoreShape = { ...identityShape };
65
- var signingPayloadShape = {
66
- rating: z.number().int().describe("Rating 1-5"),
67
- reason: z.string().describe("Review text (redacted locally before hashing)"),
68
- payment_reference: z.string().describe("Payment reference for this review"),
69
- ...identityShape
70
- };
71
- var reviewServiceShape = {
72
- rating: z.number().int().describe("Rating 1-5"),
73
- reason: z.string().describe("Review text (redacted locally before sending)"),
74
- payment_reference: z.string().describe("Unique payment reference"),
75
- service_id: identityShape.service_id,
76
- task_context: z.string().nullish(),
77
- service_name: z.string().nullish(),
78
- api_endpoint: identityShape.api_endpoint,
79
- payment_provider: identityShape.payment_provider,
80
- payment_target_ref: identityShape.payment_target_ref,
81
- directory_slug: identityShape.directory_slug,
82
- payment_proof: z.string().nullish(),
83
- payment_challenge: z.string().nullish(),
84
- reviewer_wallet: z.string().nullish(),
85
- review_signature: z.string().nullish(),
86
- signature_scheme: z.string().default("eip191")
87
- };
88
- var MIRRORED_REMOTE_TOOLS = [
89
- "request_service",
90
- "get_service_score",
91
- "review_service"
92
- ];
93
-
94
- // src/tools/signing-payload.ts
95
- function orNull(value) {
96
- return typeof value === "string" && value !== "" ? value : null;
97
- }
98
- async function getReviewSigningPayload(deps, args) {
99
- let identity;
100
- try {
101
- identity = buildIdentity(args);
102
- } catch (err) {
103
- return { ok: false, reason: err.message };
104
- }
105
- const redacted = await deps.redact(args.reason);
106
- let score;
107
- try {
108
- score = await deps.upstream.call("get_service_score", {
109
- service_id: identity.service_id,
110
- api_endpoint: identity.api_endpoint,
111
- payment_provider: identity.payment_provider,
112
- payment_target_ref: identity.payment_target_ref,
113
- directory_slug: identity.directory_slug
114
- });
115
- } catch (err) {
116
- return {
117
- ok: false,
118
- reason: `could not reach the CrowdCode backend to resolve the service: ${err.message}`
119
- };
120
- }
121
- let effective = identity;
122
- if (score.found === true) {
123
- try {
124
- effective = buildIdentity({
125
- service_id: orNull(score.service_id),
126
- service_name: orNull(score.service_name),
127
- api_endpoint: identity.api_endpoint ?? orNull(score.canonical_endpoint),
128
- payment_provider: identity.payment_provider ?? orNull(score.payment_provider),
129
- payment_target_ref: identity.payment_target_ref ?? orNull(score.payment_target_ref),
130
- directory_slug: identity.directory_slug ?? orNull(score.directory_slug)
131
- });
132
- } catch (err) {
133
- return { ok: false, reason: err.message };
134
- }
135
- } else if (typeof score.reason === "string" && score.reason !== "service not found") {
136
- return { ok: false, reason: score.reason };
137
- }
138
- const message = canonicalReviewPayload({
139
- identity: effective,
140
- rating: args.rating,
141
- reason: redacted.text,
142
- paymentReference: args.payment_reference
143
- });
144
- return {
145
- ok: true,
146
- signature_scheme: "eip191",
147
- message,
148
- reason: redacted.text,
149
- identity: {
150
- service_id: effective.service_id,
151
- api_endpoint: effective.api_endpoint,
152
- payment_provider: effective.payment_provider,
153
- payment_target_ref: effective.payment_target_ref,
154
- directory_slug: effective.directory_slug
155
- },
156
- instructions: "Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then call review_service in this same session, passing this exact `reason` string and every field of `identity` verbatim, plus the same rating and payment_reference.",
157
- _redaction: {
158
- entities_removed: redacted.entitiesRemoved,
159
- model_active: redacted.modelActive
160
- }
161
- };
162
- }
163
-
164
- // src/upstream.ts
165
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
166
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
167
- var UpstreamError = class extends Error {
168
- };
169
- var UpstreamClient = class {
170
- constructor(baseUrl, timeoutMs) {
171
- this.baseUrl = baseUrl;
172
- this.timeoutMs = timeoutMs;
173
- }
174
- baseUrl;
175
- timeoutMs;
176
- client = null;
177
- async connect() {
178
- if (this.client !== null) return this.client;
179
- const client = new Client({ name: "crowdcode-mcp-local", version: "0.1.0" });
180
- const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));
181
- await client.connect(transport);
182
- this.client = client;
183
- return client;
184
- }
185
- async reset() {
186
- const client = this.client;
187
- this.client = null;
188
- if (client !== null) {
189
- try {
190
- await client.close();
191
- } catch {
192
- }
193
- }
194
- }
195
- async call(name, args) {
196
- try {
197
- return await this.callOnce(name, args);
198
- } catch (err) {
199
- if (err instanceof UpstreamError) throw err;
200
- await this.reset();
201
- return this.callOnce(name, args);
202
- }
203
- }
204
- async callOnce(name, args) {
205
- const client = await this.connect();
206
- const result = await client.callTool({ name, arguments: args }, void 0, {
207
- timeout: this.timeoutMs
208
- });
209
- if (result.isError) {
210
- throw new UpstreamError(
211
- `backend tool ${name} failed: ${firstText(result.content)}`
212
- );
213
- }
214
- const structured = result.structuredContent;
215
- if (structured !== void 0 && isRecord(structured)) {
216
- return structured;
217
- }
218
- const text = firstText(result.content);
219
- try {
220
- const parsed = JSON.parse(text);
221
- if (isRecord(parsed)) return parsed;
222
- } catch {
223
- }
224
- throw new UpstreamError(
225
- `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`
226
- );
227
- }
228
- async listToolNames() {
229
- const client = await this.connect();
230
- const { tools } = await client.listTools();
231
- return tools.map((tool) => tool.name);
232
- }
233
- };
234
- function isRecord(value) {
235
- return typeof value === "object" && value !== null && !Array.isArray(value);
236
- }
237
- function firstText(content) {
238
- if (Array.isArray(content)) {
239
- for (const item of content) {
240
- if (isRecord(item) && item.type === "text" && typeof item.text === "string") {
241
- return item.text;
242
- }
243
- }
244
- }
245
- return "";
246
- }
247
-
248
- // src/server.ts
249
- function errorPayload(tool, err) {
250
- const message = err instanceof UpstreamError ? err.message : `could not reach the CrowdCode backend: ${err.message}`;
251
- if (tool === "get_service_score") {
252
- return {
253
- found: false,
254
- avg_rating: null,
255
- num_reviews: 0,
256
- recent_reviews: [],
257
- reason: message
258
- };
259
- }
260
- return { accepted: false, reason: message };
261
- }
262
- function createToolHandlers(deps) {
263
- const { engine, upstream } = deps;
264
- async function forwardWithRedaction(tool, args) {
265
- const redacted = await redactArgs(engine, tool, args);
266
- try {
267
- const result = await upstream.call(tool, redacted.args);
268
- return toToolResult(
269
- withRedactionAttestation(result, {
270
- entitiesRemoved: redacted.entitiesRemoved,
271
- modelActive: redacted.modelActive
272
- })
273
- );
274
- } catch (err) {
275
- return toToolResult(errorPayload(tool, err));
276
- }
277
- }
278
- return {
279
- request_service: (args) => forwardWithRedaction("request_service", args),
280
- get_service_score: async (args) => {
281
- try {
282
- return toToolResult(await upstream.call("get_service_score", args));
283
- } catch (err) {
284
- return toToolResult(errorPayload("get_service_score", err));
285
- }
286
- },
287
- get_review_signing_payload: async (args) => toToolResult(
288
- await getReviewSigningPayload(
289
- { redact: (text) => engine.redact(text), upstream },
290
- args
291
- )
292
- ),
293
- review_service: (args) => forwardWithRedaction("review_service", args)
294
- };
295
- }
296
- var SERVER_INSTRUCTIONS = [
297
- "CrowdCode is a shared reputation layer for paid agent services. Use it",
298
- "whenever a task involves paying for, provisioning, or calling a paid",
299
- "service \u2014 especially x402 or mppx/MPP services.",
300
- "",
301
- "Before spending: call get_service_score on each candidate (prefer",
302
- "api_endpoint + payment_provider + payment_target_ref, or service_id /",
303
- "directory_slug). Prefer higher avg_rating, using num_reviews as sample-size",
304
- "context; with few or no reviews, fall back to price and the spend policy.",
305
- "",
306
- "After a successful paid use: submit a review. For x402/mppx, take the",
307
- "identity and proofs from the ACTUAL payment, not a directory listing:",
308
- "payment_reference = the settlement tx hash (x402) or Payment-Receipt",
309
- "reference (mppx); payment_proof = the base64 response header string",
310
- "(payment-response for x402, Payment-Receipt for mppx), not the tx hash or",
311
- "decoded JSON; payment_target_ref = the real on-chain payee (the 402",
312
- "challenge recipient / Transfer `to`), not a directory payTo; reviewer_wallet",
313
- "= the wallet that SENT the payment (the Transfer `from`, not the gasless",
314
- "facilitator), which must be a self-custody wallet you can EIP-191 sign with.",
315
- "Call get_review_signing_payload, sign the returned message verbatim, then",
316
- "call review_service in the same session.",
317
- "",
318
- "When no fitting paid service exists, call request_service once with a",
319
- "specific, reusable capability description. Never send secrets or private",
320
- "data \u2014 free-text fields are redacted locally before anything is sent."
321
- ].join("\n");
322
- function buildServer(deps) {
323
- const server = new McpServer(
324
- { name: "crowdcode", version: "0.1.2" },
325
- { instructions: SERVER_INSTRUCTIONS }
326
- );
327
- const handlers = createToolHandlers(deps);
328
- server.registerTool(
329
- "request_service",
330
- {
331
- description: "Capture an unmet, reusable service request for future directory coverage. Use only when no fitting paid or external service exists. Describe a specific capability with clear inputs and outputs, general enough to apply to multiple users. Free-text fields are redacted locally (PII and secrets become [PLACEHOLDER]s) before anything is sent to the shared CrowdCode backend.",
332
- inputSchema: requestServiceShape
333
- },
334
- (args) => handlers.request_service(args)
335
- );
336
- server.registerTool(
337
- "get_service_score",
338
- {
339
- description: "Return the average rating, review count, and recent reviews for a service, identified by service_id, api_endpoint, payment target, or directory_slug. Check this before paying for, provisioning, or calling any paid agent service \u2014 especially x402 and mppx/MPP services.",
340
- inputSchema: getServiceScoreShape
341
- },
342
- (args) => handlers.get_service_score(args)
343
- );
344
- server.registerTool(
345
- "get_review_signing_payload",
346
- {
347
- description: "Build the exact EIP-191 message to sign before submitting an mppx or x402 review. Runs entirely locally: the review reason is redacted on this machine and only its hash enters the payload. Sign the returned `message` VERBATIM (byte-for-byte) with the payer wallet \u2014 the same self-custody wallet that sent the payment, whose key you hold (custodial or login-only wallets cannot sign an arbitrary message). Then call review_service with the returned `reason` and `identity` fields passed through verbatim, in this same session.",
348
- inputSchema: signingPayloadShape
349
- },
350
- (args) => handlers.get_review_signing_payload(args)
351
- );
352
- server.registerTool(
353
- "review_service",
354
- {
355
- description: "Submit a review after paying for a service (call this after any paid x402/mppx use). Requires the payment reference; mppx/x402 reviews also require payment_proof, reviewer_wallet, and review_signature over the message from get_review_signing_payload. Get these from the ACTUAL payment, not a directory listing: payment_reference = the settlement tx hash (x402) or Payment-Receipt `reference` (mppx); payment_proof = the base64 response header STRING \u2014 `payment-response` for x402, `Payment-Receipt` for mppx \u2014 NOT the tx hash and NOT decoded JSON; payment_target_ref = the real payee (the 402 challenge recipient / on-chain Transfer `to`), not a bazaar/directory payTo; reviewer_wallet = the wallet that SENT the payment (the ERC-20 Transfer `from`) \u2014 for gasless x402/mppx the tx sender is a facilitator, not the payer. Free-text is redacted locally; pass the exact `reason` returned by get_review_signing_payload.",
356
- inputSchema: reviewServiceShape
357
- },
358
- (args) => handlers.review_service(args)
359
- );
360
- return server;
361
- }
362
- async function warnOnToolDrift(upstream) {
363
- try {
364
- const remote = new Set(await upstream.listToolNames());
365
- const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));
366
- if (missing.length > 0) {
367
- process.stderr.write(
368
- `crowdcode-mcp: backend no longer advertises: ${missing.join(", ")} \u2014 update the crowdcode-mcp package.
369
- `
370
- );
371
- }
372
- } catch {
373
- }
374
- }
375
- async function startServer() {
376
- const config = getConfig();
377
- const engine = await RedactionEngine.create({
378
- cacheDir: config.cacheDir,
379
- enableModel: !config.disableModel
380
- });
381
- const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);
382
- const server = buildServer({ engine, upstream });
383
- await server.connect(new StdioServerTransport());
384
- void warnOnToolDrift(upstream);
385
- }
386
- export {
387
- buildServer,
388
- createToolHandlers,
389
- startServer
390
- };
391
- //# sourceMappingURL=server-6AVZDCL4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.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 { 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 getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, UpstreamError, type Upstream } from \"./upstream.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n err: unknown,\n): Record<string, unknown> {\n const message =\n err instanceof UpstreamError\n ? err.message\n : `could not reach the CrowdCode backend: ${(err as Error).message}`;\n if (tool === \"get_service_score\") {\n return {\n found: false,\n avg_rating: null,\n num_reviews: 0,\n recent_reviews: [],\n reason: message,\n };\n }\n return { accepted: false, reason: message };\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n\n async function forwardWithRedaction(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n const redacted = await redactArgs(engine, tool, args);\n try {\n const result = await upstream.call(tool, redacted.args);\n return toToolResult(\n withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n }),\n );\n } catch (err) {\n return toToolResult(errorPayload(tool, err));\n }\n }\n\n return {\n request_service: (args: Record<string, unknown>) =>\n forwardWithRedaction(\"request_service\", args),\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n try {\n return toToolResult(await upstream.call(\"get_service_score\", args));\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs,\n ): Promise<ToolResult> =>\n toToolResult(\n await getReviewSigningPayload(\n { redact: (text) => engine.redact(text), upstream },\n args,\n ),\n ),\n\n review_service: (args: Record<string, unknown>) =>\n forwardWithRedaction(\"review_service\", args),\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 \"\",\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 avg_rating, using num_reviews as sample-size\",\n \"context; with few or no reviews, fall back to price and the spend policy.\",\n \"\",\n \"After a successful paid use: submit a review. For x402/mppx, take the\",\n \"identity and proofs from the ACTUAL payment, not a directory listing:\",\n \"payment_reference = the settlement tx hash (x402) or Payment-Receipt\",\n \"reference (mppx); payment_proof = the base64 response header string\",\n \"(payment-response for x402, Payment-Receipt for mppx), not the tx hash or\",\n \"decoded JSON; payment_target_ref = the real on-chain payee (the 402\",\n \"challenge recipient / Transfer `to`), not a directory payTo; reviewer_wallet\",\n \"= the wallet that SENT the payment (the Transfer `from`, not the gasless\",\n \"facilitator), which must be a self-custody wallet you can EIP-191 sign with.\",\n \"Call get_review_signing_payload, sign the returned message verbatim, then\",\n \"call review_service in the same session.\",\n \"\",\n \"When no fitting paid service exists, call request_service once with a\",\n \"specific, reusable capability description. Never send secrets or private\",\n \"data — free-text fields are redacted locally before anything is sent.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.1.2\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Capture an unmet, reusable service request for future directory \" +\n \"coverage. Use only when no fitting paid or external service exists. \" +\n \"Describe a specific capability with clear inputs and outputs, general \" +\n \"enough to apply to multiple users. Free-text fields are redacted \" +\n \"locally (PII and secrets become [PLACEHOLDER]s) before anything is \" +\n \"sent to the shared CrowdCode backend.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the average rating, review count, and recent reviews for a \" +\n \"service, 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 to sign before submitting an mppx or \" +\n \"x402 review. Runs entirely locally: the review reason is redacted on \" +\n \"this machine and only its hash enters the payload. Sign the returned \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet — the same \" +\n \"self-custody wallet that sent the payment, whose key you hold \" +\n \"(custodial or login-only wallets cannot sign an arbitrary message). \" +\n \"Then call review_service with the returned `reason` and `identity` \" +\n \"fields passed through verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Submit a review after paying for a service (call this after any paid \" +\n \"x402/mppx use). Requires the payment reference; mppx/x402 reviews also \" +\n \"require payment_proof, reviewer_wallet, and review_signature over the \" +\n \"message from get_review_signing_payload. Get these from the ACTUAL \" +\n \"payment, not a directory listing: \" +\n \"payment_reference = the settlement tx hash (x402) or Payment-Receipt \" +\n \"`reference` (mppx); \" +\n \"payment_proof = the base64 response header STRING — `payment-response` \" +\n \"for x402, `Payment-Receipt` for mppx — NOT the tx hash and NOT decoded \" +\n \"JSON; \" +\n \"payment_target_ref = the real payee (the 402 challenge recipient / \" +\n \"on-chain Transfer `to`), not a bazaar/directory payTo; \" +\n \"reviewer_wallet = the wallet that SENT the payment (the ERC-20 \" +\n \"Transfer `from`) — for gasless x402/mppx the tx sender is a \" +\n \"facilitator, not the payer. Free-text is redacted locally; pass the \" +\n \"exact `reason` returned by get_review_signing_payload.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n void warnOnToolDrift(upstream);\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n} {\n return { content: [{ type: \"text\", text: JSON.stringify(payload) }] };\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\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"Specific, reusable service capability with clear inputs and outputs. \" +\n \"Do not include secrets, credentials, or private user data — free text \" +\n \"is additionally redacted locally before it leaves this machine.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\"Optional context about the task that needed this service\"),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(\"Rating 1-5\"),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().describe(\"Payment reference for this review\"),\n ...identityShape,\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(\"Rating 1-5\"),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().describe(\"Unique payment reference\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z.string().nullish(),\n payment_challenge: z.string().nullish(),\n reviewer_wallet: z.string().nullish(),\n review_signature: z.string().nullish(),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n] as const;\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The identity-merge logic mirrors the backend exactly\n * (src/crowdcode/server.py review_service effective_identity): the server\n * verifies signatures by REBUILDING the payload from its own resolved\n * identity, so the message signed here must match that reconstruction\n * byte-for-byte. Canonical identity comes from get_service_score when the\n * service exists; otherwise the caller-provided identity is used verbatim,\n * exactly like the old remote signing tool.\n */\n\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference: string;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n // Same merge as the backend: caller-normalized fields win, canonical\n // values fill the gaps, and the result is re-normalized.\n effective = buildIdentity({\n service_id: orNull(score.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: identity.api_endpoint ?? orNull(score.canonical_endpoint),\n payment_provider:\n identity.payment_provider ?? orNull(score.payment_provider),\n payment_target_ref:\n identity.payment_target_ref ?? orNull(score.payment_target_ref),\n directory_slug: identity.directory_slug ?? orNull(score.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference.\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;AAQA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACH9B,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,SAE3B;AACA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,EAAE,CAAC,EAAE;AACtE;;;ACXO,IAAM,mBAAsD;AAAA,EACjE,iBAAiB,CAAC,uBAAuB,cAAc;AAAA,EACvD,gBAAgB,CAAC,UAAU,cAAc;AAC3C;AAQA,eAAsB,WACpB,QACA,MACA,MACuB;AACvB,QAA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