crowdcode-mcp 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ import {
2
+ MESSAGE_HEADER,
3
+ OBSERVATION_DISCLOSURE,
4
+ OBSERVATION_FIELDS,
5
+ buildSubmission,
6
+ crowdcodeDir,
7
+ flushPending,
8
+ observationMessage,
9
+ observationsUrl,
10
+ toRecord
11
+ } from "./chunk-QKICGYZG.js";
12
+ import "./chunk-2Y65AAP3.js";
13
+ export {
14
+ MESSAGE_HEADER,
15
+ OBSERVATION_DISCLOSURE,
16
+ OBSERVATION_FIELDS,
17
+ buildSubmission,
18
+ crowdcodeDir,
19
+ flushPending,
20
+ observationMessage,
21
+ observationsUrl,
22
+ toRecord
23
+ };
24
+ //# sourceMappingURL=observations-HIXF7KW5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,16 +1,22 @@
1
1
  import {
2
- getConfig,
3
- isSolanaSignature,
4
- loadSolanaWallet,
5
- loadWallet,
6
- payerLinkMessage,
7
- solanaReferenceSignature
8
- } from "./chunk-M37QDGMY.js";
2
+ getConfig
3
+ } from "./chunk-CF6JGOQF.js";
9
4
  import {
10
5
  buildIdentity,
11
6
  canonicalReviewPayload,
12
7
  normalizePaymentProvider
13
8
  } from "./chunk-C2ZDQIG7.js";
9
+ import {
10
+ flushPending,
11
+ observationsUrl
12
+ } from "./chunk-QKICGYZG.js";
13
+ import {
14
+ isSolanaSignature,
15
+ loadSolanaWallet,
16
+ loadWallet,
17
+ payerLinkMessage,
18
+ solanaReferenceSignature
19
+ } from "./chunk-2Y65AAP3.js";
14
20
  import {
15
21
  Preferences
16
22
  } from "./chunk-ZPDTU2RK.js";
@@ -57,7 +63,7 @@ function toToolResult(payload) {
57
63
  // src/redaction/policy.ts
58
64
  var REDACTION_POLICY = {
59
65
  find_service: ["query"],
60
- request_service: ["input", "output", "problem"],
66
+ request_service: ["input", "output", "problem", "builds_on", "unlocks"],
61
67
  review_service: ["reason", "task_context"]
62
68
  };
63
69
  async function redactArgs(engine, tool, args) {
@@ -97,8 +103,19 @@ var requestServiceShape = {
97
103
  'The problem it solves: what failed, cost too much or was impossible without it. Example: "agents publishing video to X fail on chunked uploads and cannot tell whether it posted".'
98
104
  ),
99
105
  price_per_call: z.number().positive().max(100).describe(
100
- "What you would pay per call, in USD (e.g. 0.05). An honest estimate of the outcome's worth, not a budget the user approved."
106
+ "What you would pay per call, in USD (e.g. 0.05). Price the outcome's value (a booked trip can be worth $2): an honest estimate, not a budget the user approved."
107
+ ),
108
+ kind: z.enum(["gap", "leverage"]).describe(
109
+ "gap: a step that failed, was poor, slow or costly. leverage: a service that would have let you act (book, call, buy, file, send), reach data you could not (licensed, real-time, behind the user's own login with consent), persist (monitor, alert, retry over days) or verify (an authoritative or human check)."
110
+ ),
111
+ builds_on: z.string().trim().min(20).max(400).describe(
112
+ `What it could be built from today: an official API, a licensed dataset, existing paid services combined, or a human-ops team. Example: "the airline's NDC booking API plus a card-issuing API". "Nothing exists" is rejected.`
113
+ ),
114
+ unlocks: z.string().trim().min(20).max(400).describe(
115
+ 'What you could then have done for the user, in one sentence. Example: "book the cheapest refundable fare instead of only listing options".'
101
116
  ),
117
+ frequency: z.enum(["one_off", "per_task_like_this", "recurring"]).describe("How often it would be called: one_off, per_task_like_this, or recurring (daily or weekly)."),
118
+ capability: z.string().max(80).nullish().describe("Optional capability tree node id; CrowdCode maps one when omitted."),
102
119
  requester_wallet: z.string().nullish().describe(
103
120
  "EVM 0x address identifying who is asking (rate-limit key). Auto-filled from your local agentcash wallet \u2014 only pass it to override."
104
121
  )
@@ -781,7 +798,7 @@ function createToolHandlers(deps) {
781
798
  };
782
799
  }
783
800
  }
784
- return toToolResult({ ...payload, task_completion_reminder: "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." });
801
+ return toToolResult({ ...payload, task_completion_reminder: "Before your final answer, consider one gap (a step that failed or cost too much) or one leverage service (one that would have let you act, reach data, persist or verify) worth paying for, and file it with request_service including builds_on. Submit nothing if none qualifies. Respect CrowdCode off." });
785
802
  },
786
803
  get_review_signing_payload: async (args) => {
787
804
  const stopped = await disabled();
@@ -849,7 +866,7 @@ function createToolHandlers(deps) {
849
866
  if (unlinkedArgs !== null) {
850
867
  payload = await forwardPayload("review_service", unlinkedArgs);
851
868
  }
852
- 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." });
869
+ return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: "Before your final answer, consider request_service for a gap or leverage service grounded in this task, with builds_on. Skip if nothing qualifies; do not duplicate earlier requests." });
853
870
  }
854
871
  };
855
872
  }
@@ -877,35 +894,34 @@ var SERVER_INSTRUCTIONS = [
877
894
  "`summary` digests what reviewers reported (strengths / failure modes /",
878
895
  "caveats).",
879
896
  "",
880
- "Review each paid service outcome with review_service. Unpaid experiences use",
881
- "the same tool: omit payment_reference and payment_proof, and reuse a stable",
882
- "review_nonce on retry (automatically generated when omitted). Payment is",
883
- "explicitly marked unverified. The reviewer still signs with the local",
884
- "AgentCash wallet; signing is automatic and does not make a payment.",
885
- "Rate usefulness for the original task from 1 (unusable) to 5 (excellent).",
886
- "Describe observed outcomes; distinguish provider faults from client bugs,",
887
- "insufficient funds, and uncertain causes. Do not invent payment evidence.",
888
- "When claiming payment, use the actual settlement reference and payee.",
889
- "An optional payment_proof is the original base64 response header. Payment",
890
- "claims must verify on x402 Base/Monad/Solana USDC or mppx Tempo. Reference an x402",
891
- "Monad (eip155:143) settlement as x402:monad:<tx_hash> and a Solana settlement as",
892
- "x402:solana:<signature> with the Solana payee. Invalid supplied claims",
893
- "are rejected, never silently downgraded. Payment verification gives the",
894
- "existing verified scoring weight; unpaid signed reviews share the same",
895
- "history, score, and per-wallet/service/day influence cap.",
897
+ "Reviews are optional for you: use review_service when a paid result was poor or",
898
+ "failed, or when the user asks. Only reviews from hosted CrowdCode agents carry ranking",
899
+ "weight; yours are published as unweighted community evidence and are still useful.",
900
+ "Unpaid experiences use the same tool: omit payment_reference and payment_proof. The",
901
+ "reviewer signs with the local AgentCash wallet; signing is automatic and pays nothing.",
902
+ "Rate usefulness for the original task from 1 (unusable) to 5 (excellent), describe",
903
+ "observed outcomes, and distinguish provider faults from client bugs, insufficient funds",
904
+ "and uncertain causes. Never invent payment evidence; when claiming payment use the actual",
905
+ "settlement reference and payee (proof formats are in review_service's description).",
896
906
  "",
897
- "Before the final answer to each substantive user task, reflect once: what concrete",
898
- "paid service would have avoided an observed failure, poor result, expensive workaround,",
899
- "or wrong turn? This applies even if no purchase was attempted. Call request_service",
900
- "for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).",
901
- "Fill its four fields concretely enough that a developer could start building: input",
902
- "(what the user will give), output (the exact deliverable), problem (what it solves) and",
903
- "price_per_call (what you would pay per call in USD). Describe a reusable service, not",
904
- "your task. An inadequate existing service qualifies if you name the specific improvement.",
905
- "No payment or spend authority is required; price_per_call is your honest estimate.",
906
- "Skip generic local compute, run-Python wishes, ordinary agent mistakes without a",
907
- "sellable remedy, and services that already worked well at reasonable cost. If nothing",
908
- "qualifies, submit nothing. Never send secrets or private user data.",
907
+ "Paid-call records: in Claude Code and Codex, a local hook notes each paid x402/MPP call",
908
+ "any MCP tool makes (endpoint without query, method, network, settlement reference,",
909
+ "amount, HTTP status, response size, time) and crowdcode-mcp submits it signed, never the",
910
+ "request or response. CrowdCode counts it as a payer and liveness signal, not a rating.",
911
+ "`crowdcode-mcp off` stops it.",
912
+ "",
913
+ "Before the final answer to a substantive task that bought something, hit a failure or",
914
+ "took many steps, reflect once on two kinds of service. gap: a step that failed, was poor,",
915
+ "slow or costly. leverage: a service that, at a fair price, would have let you deliver a",
916
+ "much better result or something you could not do at all: act (book, call, buy, file,",
917
+ "send), reach data you could not (licensed, real-time, behind the user's own login with",
918
+ "consent), persist (monitor, alert, retry over days) or verify (an authoritative or human",
919
+ "check). For each worthwhile one call request_service with kind, input, output, problem,",
920
+ "builds_on (what it could be built from today), unlocks (what you could then have done),",
921
+ "frequency and price_per_call (price the outcome's value). Describe a reusable service,",
922
+ "never the task's answer restated; requests that restate the task, say N/A or lack",
923
+ "builds_on are rejected. If nothing qualifies, submit nothing. Never send secrets or",
924
+ "private user data.",
909
925
  "At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call",
910
926
  "set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default",
911
927
  "when they ask to remember it. Off overrides all automatic CrowdCode workflows:",
@@ -915,7 +931,7 @@ var SERVER_INSTRUCTIONS = [
915
931
  ].join("\n");
916
932
  function buildServer(deps) {
917
933
  const server = new McpServer(
918
- { name: "crowdcode", version: "0.12.0" },
934
+ { name: "crowdcode", version: "0.12.1" },
919
935
  { instructions: SERVER_INSTRUCTIONS }
920
936
  );
921
937
  const handlers = createToolHandlers(deps);
@@ -941,7 +957,7 @@ function buildServer(deps) {
941
957
  server.registerTool(
942
958
  "request_service",
943
959
  {
944
- description: 'Record a paid service that would have materially improved the task, as four concrete fields a developer could start building from: input (the clear input the user will give), output (the exact output they want back), problem (what it solves) and price_per_call (what you would pay per call, USD). Before your final answer, reflect on failures, poor results, excessive cost and avoidable detours, even when no purchase was attempted. Example: input "scanned annual report PDFs, up to 200 pages"; output "one CSV per table with page citations and low-confidence cells flagged"; problem "OCR drops columns, forcing manual reconciliation"; price_per_call 0.5. Describe a reusable service, not your task; no names, URLs or IDs. Skip web search that worked well, run-Python/local runtime wishes and bugs in your own tools. One request per distinct gap per task; respect the returned wallet limit. Submit nothing if all worked well at reasonable cost. Text is redacted locally; requests stay private and only aggregated proposals are published.',
960
+ description: `Record a reusable paid service that would have changed this task's outcome. kind is gap (a step failed, was poor, slow or costly) or leverage (a service that would have let you act: book, call, buy, file, send; reach data you could not: licensed, real-time, behind the user's own login with consent; persist: monitor, alert, retry over days; or verify: an authoritative or human check). Fill input (what the user gives), output (the exact deliverable), problem (what it solves), builds_on (what it could be built from today: an official API, licensed data, existing paid services, a human-ops team), unlocks (what you could then have done for the user), frequency (one_off, per_task_like_this, recurring) and price_per_call (USD; price the outcome's value, a booked trip can be worth $2). Example leverage: input "a held itinerary and traveller profile"; output "a booked, refundable fare with confirmation code"; builds_on "airline NDC booking APIs plus a card-issuing API"; unlocks "book the trip instead of listing options"; frequency per_task_like_this; price_per_call 2. Requests that restate the task's answer, say N/A or lack builds_on are rejected. No names, URLs or IDs. Submit nothing if nothing qualifies. Text is redacted locally; requests stay private and only aggregated proposals are published.`,
945
961
  inputSchema: requestServiceShape
946
962
  },
947
963
  (args) => handlers.request_service(args)
@@ -958,7 +974,7 @@ function buildServer(deps) {
958
974
  server.registerTool(
959
975
  "get_service_score",
960
976
  {
961
- description: "Return the canonical trust-weighted score (`score`, with `n_eff` evidence and an `unproven` flag), an AI review summary when available, plus raw rating stats 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.",
977
+ description: "Return the canonical trust-weighted score (`score`, with `n_eff` evidence and an `unproven` flag), an AI review summary when available, and raw rating stats 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.",
962
978
  inputSchema: getServiceScoreShape
963
979
  },
964
980
  (args) => handlers.get_service_score(args)
@@ -974,7 +990,7 @@ function buildServer(deps) {
974
990
  server.registerTool(
975
991
  "review_service",
976
992
  {
977
- 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 and stays private: CrowdCode publishes only counts, scores and a generated summary.",
993
+ description: "Review a service experience, paid or unpaid, with a rating from 1 to 5 and concrete observations about usefulness for the original task. Optional for local agents: review a poor or failed paid result, or when the user asks. Only hosted CrowdCode agents' reviews carry ranking weight; yours are published as unweighted community evidence. 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 and stays private: CrowdCode publishes only counts, scores and a generated summary.",
978
994
  inputSchema: reviewServiceShape
979
995
  },
980
996
  (args) => handlers.review_service(args)
@@ -1001,13 +1017,29 @@ async function startServer() {
1001
1017
  enableModel: !config.disableModel
1002
1018
  });
1003
1019
  const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);
1004
- const server = buildServer({ engine, upstream });
1020
+ const preferences = new Preferences();
1021
+ const server = buildServer({ engine, upstream, preferences });
1005
1022
  await server.connect(new StdioServerTransport());
1006
1023
  if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);
1024
+ startObservationLoop(config.backendUrl, () => preferences.status().then((s) => s.enabled));
1025
+ }
1026
+ var OBSERVATION_INTERVAL_MS = 15e3;
1027
+ function startObservationLoop(backendUrl, enabled) {
1028
+ const tick = () => {
1029
+ void flushPending({
1030
+ url: observationsUrl(backendUrl),
1031
+ enabled,
1032
+ log: (message) => process.stderr.write(message + "\n")
1033
+ }).catch(() => {
1034
+ });
1035
+ };
1036
+ setTimeout(tick, 2e3).unref();
1037
+ setInterval(tick, OBSERVATION_INTERVAL_MS).unref();
1007
1038
  }
1008
1039
  export {
1009
1040
  buildServer,
1010
1041
  createToolHandlers,
1042
+ startObservationLoop,
1011
1043
  startServer
1012
1044
  };
1013
- //# sourceMappingURL=server-MAXZNZMK.js.map
1045
+ //# sourceMappingURL=server-AMGZRDBF.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 findServiceShape,\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\";\nimport { flushPending, observationsUrl } from \"./observations.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 reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n }\n if (tool === \"find_service\") {\n return { status: \"unavailable\", error_code: \"backend_unavailable\", retryable: true, ok: false,\n services: [], reason: \"CrowdCode is temporarily unavailable\", next_step };\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 find_service: async (args: Record<string, unknown>): Promise<ToolResult> =>\n toToolResult(await forwardPayload(\"find_service\", args)),\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, consider one gap (a step that failed or cost too much) or one leverage service (one that would have let you act, reach data, persist or verify) worth paying for, and file it with request_service including builds_on. Submit nothing if none qualifies. 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 a gap or leverage service grounded in this task, with builds_on. Skip if nothing qualifies; 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 \"Choosing a service: call find_service with the capability and, when known, your\",\n \"USDC balance per network. It searches every catalog across Base, Solana and Tempo\",\n \"and ranks by CrowdCode quality, then effective price (including a transfer between\",\n \"your own networks when one is short), then balance. Prefer the top result that fits\",\n \"the task, whatever its network.\",\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 \"Reviews are optional for you: use review_service when a paid result was poor or\",\n \"failed, or when the user asks. Only reviews from hosted CrowdCode agents carry ranking\",\n \"weight; yours are published as unweighted community evidence and are still useful.\",\n \"Unpaid experiences use the same tool: omit payment_reference and payment_proof. The\",\n \"reviewer signs with the local AgentCash wallet; signing is automatic and pays nothing.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent), describe\",\n \"observed outcomes, and distinguish provider faults from client bugs, insufficient funds\",\n \"and uncertain causes. Never invent payment evidence; when claiming payment use the actual\",\n \"settlement reference and payee (proof formats are in review_service's description).\",\n \"\",\n \"Paid-call records: in Claude Code and Codex, a local hook notes each paid x402/MPP call\",\n \"any MCP tool makes (endpoint without query, method, network, settlement reference,\",\n \"amount, HTTP status, response size, time) and crowdcode-mcp submits it signed, never the\",\n \"request or response. CrowdCode counts it as a payer and liveness signal, not a rating.\",\n \"`crowdcode-mcp off` stops it.\",\n \"\",\n \"Before the final answer to a substantive task that bought something, hit a failure or\",\n \"took many steps, reflect once on two kinds of service. gap: a step that failed, was poor,\",\n \"slow or costly. leverage: a service that, at a fair price, would have let you deliver a\",\n \"much better result or something you could not do at all: act (book, call, buy, file,\",\n \"send), reach data you could not (licensed, real-time, behind the user's own login with\",\n \"consent), persist (monitor, alert, retry over days) or verify (an authoritative or human\",\n \"check). For each worthwhile one call request_service with kind, input, output, problem,\",\n \"builds_on (what it could be built from today), unlocks (what you could then have done),\",\n \"frequency and price_per_call (price the outcome's value). Describe a reusable service,\",\n \"never the task's answer restated; requests that restate the task, say N/A or lack\",\n \"builds_on are rejected. If nothing qualifies, submit nothing. Never send secrets or\",\n \"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.12.1\" },\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 reusable paid service that would have changed this task's outcome. kind \" +\n \"is gap (a step failed, was poor, slow or costly) or leverage (a service that would \" +\n \"have let you act: book, call, buy, file, send; reach data you could not: licensed, \" +\n \"real-time, behind the user's own login with consent; persist: monitor, alert, retry \" +\n \"over days; or verify: an authoritative or human check). Fill input (what the user \" +\n \"gives), output (the exact deliverable), problem (what it solves), builds_on (what it \" +\n \"could be built from today: an official API, licensed data, existing paid services, a \" +\n \"human-ops team), unlocks (what you could then have done for the user), frequency \" +\n \"(one_off, per_task_like_this, recurring) and price_per_call (USD; price the outcome's \" +\n \"value, a booked trip can be worth $2). Example leverage: input \\\"a held itinerary and \" +\n \"traveller profile\\\"; output \\\"a booked, refundable fare with confirmation code\\\"; \" +\n \"builds_on \\\"airline NDC booking APIs plus a card-issuing API\\\"; unlocks \\\"book the \" +\n \"trip instead of listing options\\\"; frequency per_task_like_this; price_per_call 2. \" +\n \"Requests that restate the task's answer, say N/A or lack builds_on are rejected. No \" +\n \"names, URLs or IDs. Submit nothing if nothing qualifies. Text is redacted locally; \" +\n \"requests stay private and only aggregated proposals are published.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"find_service\",\n {\n description:\n \"Find the best paid service for a capability across Base, Solana and Tempo. \" +\n \"Searches Coinbase's x402 Bazaar, the mpp.dev MPP catalog and CrowdCode's reviewed \" +\n \"services, merges them by endpoint, and ranks them: CrowdCode quality first, then the \" +\n \"effective price on your best network (plus one transfer between your own networks when \" +\n \"that network's balance is short), then your balance there. Pass your per-network \" +\n \"`balances` when known, and endpoints found elsewhere (for example AgentCash search) as \" +\n \"`candidates`. Each result names its best network, offers, quality evidence and sources. \" +\n \"Catalog prices can be dynamic: inspect the chosen endpoint for its live quote before paying. \" +\n \"The query is redacted locally.\",\n inputSchema: findServiceShape,\n annotations: { readOnlyHint: true },\n },\n (args) => handlers.find_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, and raw rating stats 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 \"Optional for local agents: review a poor or failed paid result, or when the user asks. \" +\n \"Only hosted CrowdCode agents' reviews carry ranking weight; yours are published as \" +\n \"unweighted community evidence. 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 and stays \" +\n \"private: CrowdCode publishes only counts, scores and a generated summary.\",\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 // One preferences object for the tools and the observation loop, so a\n // session-scoped \"CrowdCode off\" stops submissions too.\n const preferences = new Preferences();\n const server = buildServer({ engine, upstream, preferences });\n await server.connect(new StdioServerTransport());\n if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);\n startObservationLoop(config.backendUrl, () => preferences.status().then((s) => s.enabled));\n}\n\nconst OBSERVATION_INTERVAL_MS = 15_000;\n\n/** Submit the PostToolUse hook's paid-call records while this server runs. */\nexport function startObservationLoop(backendUrl: string, enabled: () => Promise<boolean>): void {\n const tick = () => {\n void flushPending({ url: observationsUrl(backendUrl), enabled,\n log: (message) => process.stderr.write(message + \"\\n\") }).catch(() => {});\n };\n setTimeout(tick, 2_000).unref();\n setInterval(tick, OBSERVATION_INTERVAL_MS).unref();\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 find_service: [\"query\"],\n request_service: [\"input\", \"output\", \"problem\", \"builds_on\", \"unlocks\"],\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\n/**\n * request_service: concrete fields a builder can act on, and whether it is a gap\n * or leverage (C6). Bounds mirror crowdcode.demand.validate_request_fields and\n * validate_request_extras; the backend stays authoritative.\n */\nexport const requestServiceShape = {\n input: z\n .string()\n .trim()\n .min(20)\n .max(600)\n .describe(\n \"The clear input the user will give the service, concretely: format, size, fields. \" +\n \"Example: \\\"a public MP4 URL (up to 60 s) and the post text\\\". \" +\n \"General terms only: no names, URLs, IDs or private data.\",\n ),\n output: z\n .string()\n .trim()\n .min(20)\n .max(600)\n .describe(\n \"The exact output they want back, specific enough to check. \" +\n \"Example: \\\"the published post ID and URL, posted exactly once\\\".\",\n ),\n problem: z\n .string()\n .trim()\n .min(20)\n .max(800)\n .describe(\n \"The problem it solves: what failed, cost too much or was impossible without it. \" +\n \"Example: \\\"agents publishing video to X fail on chunked uploads and cannot tell whether it posted\\\".\",\n ),\n price_per_call: z\n .number()\n .positive()\n .max(100)\n .describe(\n \"What you would pay per call, in USD (e.g. 0.05). Price the outcome's value (a booked \" +\n \"trip can be worth $2): an honest estimate, not a budget the user approved.\",\n ),\n kind: z\n .enum([\"gap\", \"leverage\"])\n .describe(\n \"gap: a step that failed, was poor, slow or costly. leverage: a service that would have \" +\n \"let you act (book, call, buy, file, send), reach data you could not (licensed, \" +\n \"real-time, behind the user's own login with consent), persist (monitor, alert, retry \" +\n \"over days) or verify (an authoritative or human check).\",\n ),\n builds_on: z\n .string()\n .trim()\n .min(20)\n .max(400)\n .describe(\n \"What it could be built from today: an official API, a licensed dataset, existing paid \" +\n \"services combined, or a human-ops team. Example: \\\"the airline's NDC booking API plus \" +\n \"a card-issuing API\\\". \\\"Nothing exists\\\" is rejected.\",\n ),\n unlocks: z\n .string()\n .trim()\n .min(20)\n .max(400)\n .describe(\n \"What you could then have done for the user, in one sentence. Example: \\\"book the \" +\n \"cheapest refundable fare instead of only listing options\\\".\",\n ),\n frequency: z\n .enum([\"one_off\", \"per_task_like_this\", \"recurring\"])\n .describe(\"How often it would be called: one_off, per_task_like_this, or recurring (daily or weekly).\"),\n capability: z\n .string()\n .max(80)\n .nullish()\n .describe(\"Optional capability tree node id; CrowdCode maps one when omitted.\"),\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 findServiceShape = {\n query: z.string().min(1).max(500).describe(\n \"The capability in a few words, for example \\\"web search\\\", \\\"object storage\\\" or \\\"solana token risk\\\"; \" +\n \"not the task's subject (redacted locally before sending)\",\n ),\n networks: z\n .array(z.string())\n .nullish()\n .describe(\"Networks you can pay on: base, solana, tempo (default all three)\"),\n balances: z\n .record(z.string(), z.number())\n .nullish()\n .describe(\n \"Available USDC per network, e.g. {\\\"base\\\": 1.2, \\\"solana\\\": 0.4, \\\"tempo\\\": 0}. \" +\n \"Lets the ranking add a transfer cost where a network's balance is short.\",\n ),\n candidates: z\n .array(\n z.object({\n endpoint: z.string(),\n method: z.string().nullish(),\n name: z.string().nullish(),\n description: z.string().nullish(),\n price_usd: z.number().nullish(),\n network: z.string().nullish(),\n networks: z.array(z.string()).nullish(),\n protocol: z.string().nullish(),\n protocols: z.array(z.string()).nullish(),\n unique_payers: z.number().nullish(),\n source: z.string().nullish(),\n }).passthrough(),\n )\n .max(50)\n .nullish()\n .describe(\"Endpoints you found elsewhere (for example AgentCash search) to rank together with the catalogs\"),\n limit: z.number().int().min(1).max(25).nullish(),\n};\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 \"find_service\",\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,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,IAAI,CAAC;AAAA,EAC9D;AACF;;;ACjBO,IAAM,mBAAsD;AAAA,EACjE,cAAc,CAAC,OAAO;AAAA,EACtB,iBAAiB,CAAC,SAAS,UAAU,WAAW,aAAa,SAAS;AAAA,EACtE,gBAAgB,CAAC,UAAU,cAAc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