crowdcode-mcp 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -7
- package/dist/cli.js +2 -2
- package/dist/cli.js.map +1 -1
- package/dist/{server-4RGYQUHJ.js → server-MAXZNZMK.js} +20 -14
- package/dist/server-MAXZNZMK.js.map +1 -0
- package/dist/skills/crowdcode/SKILL.md +26 -18
- package/package.json +1 -1
- package/dist/server-4RGYQUHJ.js.map +0 -1
package/README.md
CHANGED
|
@@ -58,9 +58,9 @@ Identify the service by `api_endpoint` + `payment_provider` +
|
|
|
58
58
|
"n_eff": 5.8,
|
|
59
59
|
"unproven": false,
|
|
60
60
|
"summary": {
|
|
61
|
-
"
|
|
62
|
-
"
|
|
63
|
-
"
|
|
61
|
+
"pros": ["Consistently relevant review comments."],
|
|
62
|
+
"cons": [],
|
|
63
|
+
"watch_out": ["Slower on large diffs."]
|
|
64
64
|
},
|
|
65
65
|
"avg_rating": 4.5,
|
|
66
66
|
"num_reviews": 7
|
|
@@ -73,7 +73,9 @@ fresh and adversarial wallets count for nothing no matter how many of them
|
|
|
73
73
|
exist. `n_eff` says how much trusted evidence backs the score, and
|
|
74
74
|
`unproven: true` means there isn't enough of it yet — read that as *insufficient
|
|
75
75
|
evidence*, not as a bad service, and fall back to price and your spend policy.
|
|
76
|
-
`summary` digests what reviewers actually reported
|
|
76
|
+
`summary` digests what reviewers actually reported as pros, cons and things to
|
|
77
|
+
watch out for. Individual reviews are private: CrowdCode stores them but never
|
|
78
|
+
returns their text.
|
|
77
79
|
|
|
78
80
|
The algorithm is public: [docs/SCORING.md][scoring].
|
|
79
81
|
|
|
@@ -125,9 +127,12 @@ proofs from the *actual payment*, not from a directory listing:
|
|
|
125
127
|
### `request_service` — record unmet paid demand
|
|
126
128
|
|
|
127
129
|
Before the final answer, reflect on actual obstacles that a concrete paid
|
|
128
|
-
service could have solved
|
|
129
|
-
|
|
130
|
-
|
|
130
|
+
service could have solved, and describe the service in four required fields:
|
|
131
|
+
`input` (the clear input the user will give), `output` (the exact output they
|
|
132
|
+
want), `problem` (what it solves) and `price_per_call` (what you would pay per
|
|
133
|
+
call, in USD). A specific improvement to an inadequate existing service
|
|
134
|
+
qualifies; an attempted purchase is not required. Requests stay private;
|
|
135
|
+
CrowdCode publishes only aggregated, generalized proposals.
|
|
131
136
|
|
|
132
137
|
### `get_review_signing_payload` — usually unnecessary
|
|
133
138
|
|
package/dist/cli.js
CHANGED
|
@@ -19,7 +19,7 @@ process.stdin.on('end', () => {
|
|
|
19
19
|
if (Array.isArray(event.background_tasks) && event.background_tasks.length) return;
|
|
20
20
|
process.stdout.write(JSON.stringify({
|
|
21
21
|
decision: 'block',
|
|
22
|
-
reason: "CrowdCode completion check (once only): read crowdcode_status. If off, unavailable, or this turn only managed CrowdCode settings/reviews, finish immediately without reflection or submissions. Otherwise, if you have not already reflected for this completed task, consider the real failures, poor results, excessive cost, and detours: what specific reusable service would have been worth paying for? Call request_service only for worthwhile unmet needs,
|
|
22
|
+
reason: "CrowdCode completion check (once only): read crowdcode_status. If off, unavailable, or this turn only managed CrowdCode settings/reviews, finish immediately without reflection or submissions. Otherwise, if you have not already reflected for this completed task, consider the real failures, poor results, excessive cost, and detours: what specific reusable service would have been worth paying for? Call request_service only for worthwhile unmet needs, with concrete input (what the user gives), output (the exact deliverable), problem (what it solves) and price_per_call (what you would pay per call in USD). A specific improvement to an inadequate existing service qualifies; no actual purchase is needed. Skip local Python/runtime wishes and services that already worked well. Never invent a budget or repeat a submitted gap. If nothing qualifies, submit nothing. Then finish; do not reopen the user's task."
|
|
23
23
|
}));
|
|
24
24
|
} catch { /* A broken optional reminder must never trap the user. */ }
|
|
25
25
|
});
|
|
@@ -616,7 +616,7 @@ async function main() {
|
|
|
616
616
|
case void 0:
|
|
617
617
|
case "serve": {
|
|
618
618
|
routeStdoutToStderr();
|
|
619
|
-
const { startServer } = await import("./server-
|
|
619
|
+
const { startServer } = await import("./server-MAXZNZMK.js");
|
|
620
620
|
await startServer();
|
|
621
621
|
break;
|
|
622
622
|
}
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/completion-hook.ts","../src/installer.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * crowdcode-mcp — CrowdCode MCP client with local-first PII redaction.\n *\n * Subcommands:\n * (none) | serve start the stdio MCP server (default)\n * install install the skill and configure supported agents\n * doctor verify skill and MCP installation state\n * check [text] show what the redaction pipeline does to sample text\n * clear-cache delete the downloaded model cache\n */\n\nimport { rm, stat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline/promises\";\nimport { getConfig } from \"./config.js\";\nimport {\n CORE_CLIENTS,\n detectClients,\n doctorClients,\n installForClients,\n type ClientId,\n} from \"./installer.js\";\n\n// stdout carries the MCP protocol in serve mode; anything that would print\n// there (transformers download progress, stray library logs) corrupts it.\n// Patch before any heavy import happens.\nfunction routeStdoutToStderr(): void {\n console.log = (...args: unknown[]) => console.error(...args);\n console.info = (...args: unknown[]) => console.error(...args);\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nasync function runCheck(argText: string | undefined): Promise<void> {\n const config = getConfig();\n const text = argText ?? (await readStdin());\n if (!text.trim()) {\n console.error('usage: crowdcode-mcp check \"some text\" (or pipe via stdin)');\n process.exit(2);\n }\n\n const { RedactionEngine } = await import(\"@crowdcode/redaction\");\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n\n if (!config.disableModel) {\n console.error(\n \"loading PII model (downloads ~15 MB to \" +\n config.cacheDir +\n \" on first run; deterministic recognizers work without it) ...\",\n );\n await engine.waitForModel();\n }\n\n const result = await engine.redact(text);\n const revealed = await engine.reveal(result.text);\n\n console.error(\"\");\n console.error(\"input: \" + JSON.stringify(text));\n console.error(\"redacted: \" + JSON.stringify(result.text));\n console.error(\"revealed: \" + JSON.stringify(revealed) + \" (local round-trip)\");\n console.error(\"\");\n console.error(\n `entities removed: ${result.entitiesRemoved} model active: ${result.modelActive}`,\n );\n console.error(\n \"only the redacted form would ever be sent to the CrowdCode backend.\",\n );\n}\n\nasync function runClearCache(): Promise<void> {\n const config = getConfig();\n try {\n await stat(config.cacheDir);\n } catch {\n console.error(`nothing to clear (${config.cacheDir} does not exist)`);\n return;\n }\n await rm(config.cacheDir, { recursive: true, force: true });\n console.error(`cleared ${config.cacheDir}`);\n}\n\ninterface InstallerFlags {\n clients: ClientId[];\n allDetected: boolean;\n yes: boolean;\n}\n\nfunction parseInstallerFlags(args: string[]): InstallerFlags {\n const clients: ClientId[] = [];\n let allDetected = false;\n let yes = false;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index]!;\n if (arg === \"--yes\" || arg === \"-y\") {\n yes = true;\n continue;\n }\n if (arg === \"--all-detected\") {\n allDetected = true;\n continue;\n }\n let value: string | undefined;\n if (arg === \"--client\") {\n value = args[++index];\n if (!value) throw new Error(\"--client requires a client identifier\");\n } else if (arg.startsWith(\"--client=\")) {\n value = arg.slice(\"--client=\".length);\n } else {\n throw new Error(`unknown install option: ${arg}`);\n }\n for (const candidate of value.split(\",\")) {\n if (!(CORE_CLIENTS as readonly string[]).includes(candidate)) {\n throw new Error(\n `unknown client ${JSON.stringify(candidate)}; use ${CORE_CLIENTS.join(\", \")}`,\n );\n }\n if (!clients.includes(candidate as ClientId)) clients.push(candidate as ClientId);\n }\n }\n if (allDetected && clients.length > 0) {\n throw new Error(\"use either --all-detected or --client, not both\");\n }\n return { clients, allDetected, yes };\n}\n\nasync function chooseInstallClients(flags: InstallerFlags): Promise<ClientId[]> {\n if (flags.clients.length > 0) return flags.clients;\n const detected = await detectClients();\n if (flags.allDetected) {\n if (detected.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n return detected;\n }\n if (flags.yes || !process.stdin.isTTY || !process.stderr.isTTY) {\n return detected.length > 0 ? detected : [...CORE_CLIENTS];\n }\n\n const defaults = detected.length > 0 ? detected : [...CORE_CLIENTS];\n console.error(\"Supported clients:\");\n CORE_CLIENTS.forEach((client, index) => {\n console.error(` ${index + 1}. ${client}${detected.includes(client) ? \" (detected)\" : \"\"}`);\n });\n const prompt = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await prompt.question(\n `Install for comma-separated names/numbers [${defaults.join(\",\")}]: `,\n );\n if (!answer.trim()) return defaults;\n const selected: ClientId[] = [];\n for (const token of answer.split(\",\").map((item) => item.trim())) {\n const numbered = Number(token);\n const client = Number.isInteger(numbered)\n ? CORE_CLIENTS[numbered - 1]\n : (token as ClientId);\n if (!client || !(CORE_CLIENTS as readonly string[]).includes(client)) {\n throw new Error(`unknown client selection: ${token}`);\n }\n if (!selected.includes(client)) selected.push(client);\n }\n return selected;\n } finally {\n prompt.close();\n }\n}\n\nasync function runInstall(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients = await chooseInstallClients(flags);\n const results = await installForClients(clients);\n console.error(\"CrowdCode installation complete:\");\n for (const result of results) {\n console.error(\n ` ${result.client}: MCP ${result.configPath}; skill ${result.skillPath} (${result.skillMode})`,\n );\n }\n console.error(\"Restart these clients so they reload the CrowdCode skill and MCP server.\");\n}\n\nasync function runDoctor(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients =\n flags.clients.length > 0\n ? flags.clients\n : flags.allDetected\n ? await detectClients()\n : [...CORE_CLIENTS];\n if (clients.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n const results = await doctorClients(clients);\n let healthy = true;\n for (const result of results) {\n const ok = result.mcpConfigured && result.skillCurrent && result.completionHookCurrent !== false;\n healthy &&= ok;\n console.error(\n `${ok ? \"ok\" : \"missing/stale\"} ${result.client}` +\n ` MCP=${result.mcpConfigured ? \"ok\" : \"missing\"}` +\n ` skill=${result.skillCurrent ? \"ok\" : \"missing/stale\"}`,\n );\n if (result.detail) console.error(` ${result.detail}`);\n }\n if (!healthy) process.exitCode = 1;\n}\n\nfunction printHelp(): void {\n console.error(\n \"usage: crowdcode-mcp [serve|on|off|status|install|doctor|check <text>|clear-cache]\\n\" +\n \" serve start the stdio MCP server (default)\\n\" +\n \" on/off save CrowdCode default (active session overrides take precedence)\\n\" +\n \" status show the saved default for new connections\\n\" +\n \" install install the CrowdCode skill and MCP config\\n\" +\n \" [--client <client>] [--all-detected] [--yes]\\n\" +\n \" doctor verify skill and MCP config [--client <client>] [--all-detected]\\n\" +\n \" check demo the local redaction pipeline on sample text\\n\" +\n \" clear-cache delete the downloaded model cache\\n\" +\n ` clients ${CORE_CLIENTS.join(\", \")}`,\n );\n}\n\nasync function main(): Promise<void> {\n const [, , command, ...rest] = process.argv;\n switch (command) {\n case undefined:\n case \"serve\": {\n routeStdoutToStderr();\n const { startServer } = await import(\"./server.js\");\n await startServer();\n break;\n }\n case \"on\":\n case \"off\":\n case \"status\": {\n const { Preferences } = await import(\"./preferences.js\");\n const preferences = new Preferences();\n const state = command === \"status\" ? await preferences.status()\n : await preferences.set(command === \"on\", \"default\");\n console.log(JSON.stringify(state));\n break;\n }\n case \"check\":\n await runCheck(rest.length > 0 ? rest.join(\" \") : undefined);\n break;\n case \"install\":\n await runInstall(rest);\n break;\n case \"doctor\":\n await runDoctor(rest);\n break;\n case \"clear-cache\":\n await runClearCache();\n break;\n case \"--help\":\n case \"-h\":\n printHelp();\n break;\n default:\n console.error(`unknown command: ${command} (try --help)`);\n process.exit(2);\n }\n}\n\nmain().catch((err) => {\n console.error(\"crowdcode-mcp fatal:\", err);\n process.exit(1);\n});\n","/** Installed as a self-contained local Claude Code Stop hook. No network or transcript access. */\nexport const COMPLETION_HOOK = `\nlet input = '';\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', chunk => { input += chunk; });\nprocess.stdin.on('end', () => {\n try {\n const event = JSON.parse(input);\n if (event.hook_event_name !== 'Stop' || event.stop_hook_active) return;\n if (Array.isArray(event.background_tasks) && event.background_tasks.length) return;\n process.stdout.write(JSON.stringify({\n decision: 'block',\n reason: \"CrowdCode completion check (once only): read crowdcode_status. If off, unavailable, or this turn only managed CrowdCode settings/reviews, finish immediately without reflection or submissions. Otherwise, if you have not already reflected for this completed task, consider the real failures, poor results, excessive cost, and detours: what specific reusable service would have been worth paying for? Call request_service only for worthwhile unmet needs, describing exact inputs, deliverables, acceptance criteria, the real obstacle, and why the outcome justifies payment. A specific improvement to an inadequate existing service qualifies; no actual purchase is needed. Skip local Python/runtime wishes and services that already worked well. Never invent a budget or repeat a submitted gap. If nothing qualifies, submit nothing. Then finish; do not reopen the user's task.\"\n }));\n } catch { /* A broken optional reminder must never trap the user. */ }\n});\n`;\n\n","import { COMPLETION_HOOK } from \"./completion-hook.js\";\nimport { createHash } from \"node:crypto\";\nimport {\n copyFile,\n lstat,\n mkdir,\n readFile,\n readlink,\n rename,\n rm,\n stat,\n symlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport const CORE_CLIENTS = [\n \"codex\",\n \"claude-code\",\n \"claude-desktop\",\n \"cursor\",\n] as const;\n\nexport type ClientId = (typeof CORE_CLIENTS)[number];\nexport type InstallerPlatform = \"darwin\" | \"linux\" | \"win32\";\n\nexport interface InstallerEnvironment {\n homeDir?: string;\n platform?: InstallerPlatform;\n env?: NodeJS.ProcessEnv;\n packageRoot?: string;\n now?: () => Date;\n}\n\ninterface InstallState {\n packageVersion: string;\n skillHash: string;\n installedAt: string;\n}\n\nexport interface ClientInstallResult {\n client: ClientId;\n configPath: string;\n skillPath: string;\n skillMode: \"canonical\" | \"symlink\" | \"copy\" | \"mcp-instructions\";\n}\n\nexport interface DoctorResult {\n client: ClientId;\n configPath: string;\n mcpConfigured: boolean;\n skillPath: string;\n skillCurrent: boolean;\n completionHookCurrent?: boolean;\n detail?: string;\n}\n\nconst MCP_SERVER = {\n command: \"npx\",\n args: [\"-y\", \"crowdcode-mcp@latest\"],\n};\n\nfunction resolvedEnvironment(input: InstallerEnvironment = {}) {\n const platform = input.platform ?? process.platform;\n if (platform !== \"darwin\" && platform !== \"linux\" && platform !== \"win32\") {\n throw new Error(`unsupported platform: ${platform}`);\n }\n return {\n homeDir: input.homeDir ?? homedir(),\n platform,\n env: input.env ?? process.env,\n packageRoot: input.packageRoot ?? findPackageRoot(import.meta.url),\n now: input.now ?? (() => new Date()),\n };\n}\n\nfunction findPackageRoot(moduleUrl: string): string {\n // installer.ts lives in src during development and is bundled into dist/cli.js\n // for publication. Both locations are exactly one directory below package.json.\n return resolve(dirname(fileURLToPath(moduleUrl)), \"..\");\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function lexists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readOptional(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nfunction hash(content: string): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nasync function packageVersion(packageRoot: string): Promise<string> {\n const parsed = JSON.parse(await readFile(join(packageRoot, \"package.json\"), \"utf8\"));\n if (typeof parsed.version !== \"string\") {\n throw new Error(\"crowdcode-mcp package.json has no version\");\n }\n return parsed.version;\n}\n\nasync function bundledSkill(packageRoot: string): Promise<string> {\n const packaged = join(packageRoot, \"dist\", \"skills\", \"crowdcode\", \"SKILL.md\");\n const content = await readOptional(packaged);\n if (content !== null) return content;\n\n // Development fallback. Published packages always use the dist asset.\n const source = resolve(packageRoot, \"../../skills/crowdcode/SKILL.md\");\n return readFile(source, \"utf8\");\n}\n\nfunction statePath(homeDir: string): string {\n return join(homeDir, \".crowdcode\", \"install-state.json\");\n}\n\nfunction canonicalSkillDir(homeDir: string): string {\n return join(homeDir, \".agents\", \"skills\", \"crowdcode\");\n}\n\nasync function loadState(homeDir: string): Promise<InstallState | null> {\n const raw = await readOptional(statePath(homeDir));\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<InstallState>;\n if (\n typeof parsed.packageVersion === \"string\" &&\n typeof parsed.skillHash === \"string\" &&\n typeof parsed.installedAt === \"string\"\n ) {\n return parsed as InstallState;\n }\n } catch {\n // Treat malformed state as unmanaged; user content is backed up below.\n }\n return null;\n}\n\nasync function atomicWrite(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temp = join(\n dirname(path),\n `.${basename(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n await writeFile(temp, content, { mode: 0o600 });\n try {\n await rename(temp, path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nfunction backupSuffix(now: Date): string {\n return now.toISOString().replace(/[:.]/g, \"-\");\n}\n\nasync function unusedBackupPath(path: string, now: Date): Promise<string> {\n const base = `${path}.backup-${backupSuffix(now)}`;\n let candidate = base;\n for (let index = 2; await lexists(candidate); index += 1) {\n candidate = `${base}-${index}`;\n }\n return candidate;\n}\n\nasync function replaceSkillDirectory(\n path: string,\n skill: string,\n managedHash: string | null,\n now: Date,\n): Promise<void> {\n let existingSkill: string | null;\n try {\n existingSkill = await readOptional(join(path, \"SKILL.md\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOTDIR\") existingSkill = null;\n else throw error;\n }\n const newHash = hash(skill);\n if (existingSkill !== null && hash(existingSkill) === newHash) return;\n\n if (await lexists(path)) {\n const existingIsManaged =\n existingSkill !== null && managedHash !== null && hash(existingSkill) === managedHash;\n if (existingIsManaged) {\n await rm(path, { recursive: true, force: true });\n } else {\n await rename(path, await unusedBackupPath(path, now));\n }\n }\n\n const temp = `${path}.installing-${process.pid}`;\n await rm(temp, { recursive: true, force: true });\n await mkdir(temp, { recursive: true });\n await writeFile(join(temp, \"SKILL.md\"), skill);\n await rename(temp, path);\n}\n\nasync function installCanonicalSkill(env: ReturnType<typeof resolvedEnvironment>) {\n const skill = await bundledSkill(env.packageRoot);\n const previous = await loadState(env.homeDir);\n const path = canonicalSkillDir(env.homeDir);\n await mkdir(dirname(path), { recursive: true });\n await replaceSkillDirectory(path, skill, previous?.skillHash ?? null, env.now());\n\n const nextState: InstallState = {\n packageVersion: await packageVersion(env.packageRoot),\n skillHash: hash(skill),\n installedAt: env.now().toISOString(),\n };\n await atomicWrite(statePath(env.homeDir), `${JSON.stringify(nextState, null, 2)}\\n`);\n return { path, skill, state: nextState };\n}\n\nfunction claudeCodeSkillDir(homeDir: string): string {\n return join(homeDir, \".claude\", \"skills\", \"crowdcode\");\n}\n\nasync function installClaudeCodeSkill(\n env: ReturnType<typeof resolvedEnvironment>,\n canonicalPath: string,\n skill: string,\n): Promise<\"symlink\" | \"copy\"> {\n const target = claudeCodeSkillDir(env.homeDir);\n await mkdir(dirname(target), { recursive: true });\n\n let targetManaged = false;\n try {\n const targetStat = await lstat(target);\n if (targetStat.isSymbolicLink()) {\n const link = await readlink(target);\n targetManaged = resolve(dirname(target), link) === canonicalPath;\n } else {\n const current = await readOptional(join(target, \"SKILL.md\"));\n targetManaged = current !== null && hash(current) === hash(skill);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n\n if (await lexists(target)) {\n if (targetManaged) await rm(target, { recursive: true, force: true });\n else await rename(target, await unusedBackupPath(target, env.now()));\n }\n\n if (env.platform !== \"win32\") {\n try {\n await symlink(relative(dirname(target), canonicalPath), target, \"dir\");\n return \"symlink\";\n } catch {\n // Some filesystems disallow symlinks. Fall through to a portable copy.\n }\n }\n\n await mkdir(target, { recursive: true });\n await copyFile(join(canonicalPath, \"SKILL.md\"), join(target, \"SKILL.md\"));\n return \"copy\";\n}\n\nfunction configBase(\n homeDir: string,\n platform: InstallerPlatform,\n env: NodeJS.ProcessEnv,\n): string {\n if (platform === \"win32\") {\n return env.APPDATA ?? join(homeDir, \"AppData\", \"Roaming\");\n }\n if (platform === \"darwin\") return join(homeDir, \"Library\", \"Application Support\");\n return env.XDG_CONFIG_HOME ?? join(homeDir, \".config\");\n}\n\nexport function getClientConfigPath(\n client: ClientId,\n input: InstallerEnvironment = {},\n): string {\n const env = resolvedEnvironment(input);\n switch (client) {\n case \"codex\":\n return join(env.env.CODEX_HOME ?? join(env.homeDir, \".codex\"), \"config.toml\");\n case \"claude-code\":\n return join(env.homeDir, \".claude.json\");\n case \"cursor\":\n return join(env.homeDir, \".cursor\", \"mcp.json\");\n case \"claude-desktop\":\n return join(\n configBase(env.homeDir, env.platform, env.env),\n \"Claude\",\n \"claude_desktop_config.json\",\n );\n }\n}\n\nfunction removeCrowdCodeTomlSection(content: string): string {\n const lines = content.split(/\\r?\\n/);\n const kept: string[] = [];\n let skipping = false;\n for (const line of lines) {\n const section = /^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/.exec(line);\n if (section) {\n const normalized = section[1]!.replace(/[\"']/g, \"\").replace(/\\s/g, \"\");\n skipping =\n normalized === \"mcp_servers.crowdcode\" ||\n normalized.startsWith(\"mcp_servers.crowdcode.\");\n if (skipping) continue;\n }\n if (!skipping) kept.push(line);\n }\n return kept.join(\"\\n\").trimEnd();\n}\n\nexport function mergeCodexConfig(content: string): string {\n const before = removeCrowdCodeTomlSection(content);\n const section = [\n \"[mcp_servers.crowdcode]\",\n `command = ${JSON.stringify(MCP_SERVER.command)}`,\n `args = ${JSON.stringify(MCP_SERVER.args)}`,\n ].join(\"\\n\");\n return `${before ? `${before}\\n\\n` : \"\"}${section}\\n`;\n}\n\nfunction parseJsonConfig(content: string, path: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(content) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"root must be an object\");\n }\n return parsed as Record<string, unknown>;\n } catch (error) {\n throw new Error(`cannot parse ${path}; no changes were written: ${(error as Error).message}`);\n }\n}\n\nexport function mergeJsonMcpConfig(content: string, path = \"config.json\"): string {\n const config = content.trim() ? parseJsonConfig(content, path) : {};\n const current = config.mcpServers;\n if (current !== undefined && (current === null || typeof current !== \"object\" || Array.isArray(current))) {\n throw new Error(`${path} has a non-object mcpServers value; no changes were written`);\n }\n config.mcpServers = {\n ...((current as Record<string, unknown> | undefined) ?? {}),\n crowdcode: MCP_SERVER,\n };\n return `${JSON.stringify(config, null, 2)}\\n`;\n}\n\nasync function installCompletionHook(env: ReturnType<typeof resolvedEnvironment>): Promise<void> {\n const settingsPath = join(env.homeDir, \".claude\", \"settings.json\");\n const settings = parseJsonConfig((await readOptional(settingsPath)) ?? \"{}\", settingsPath);\n const hooks = settings.hooks ?? {};\n if (!hooks || typeof hooks !== \"object\" || Array.isArray(hooks)) throw new Error(\"Invalid Claude hooks settings\");\n const hookMap = hooks as Record<string, unknown>;\n const stop = hookMap.Stop ?? [];\n if (!Array.isArray(stop)) throw new Error(\"Invalid Claude Stop hooks settings\");\n const hookPath = join(env.homeDir, \".crowdcode\", \"hooks\", \"completion.cjs\");\n const installed = stop.some((entry: any) => Array.isArray(entry?.hooks) &&\n entry.hooks.some((hook: any) => hook.type === \"command\" && hook.command === \"node\" &&\n Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));\n if (!installed) hookMap.Stop = [...stop, { hooks: [{ type: \"command\", command: \"node\", args: [hookPath], timeout: 5 }] }];\n settings.hooks = hookMap;\n await atomicWrite(hookPath, COMPLETION_HOOK);\n const next = JSON.stringify(settings, null, 2) + \"\\n\";\n if (next !== await readOptional(settingsPath)) await atomicWrite(settingsPath, next);\n}\n\nasync function configureClient(\n client: ClientId,\n env: ReturnType<typeof resolvedEnvironment>,\n): Promise<string> {\n const path = getClientConfigPath(client, env);\n const current = (await readOptional(path)) ?? \"\";\n const next =\n client === \"codex\" ? mergeCodexConfig(current) : mergeJsonMcpConfig(current, path);\n if (next !== current) await atomicWrite(path, next);\n return path;\n}\n\nexport async function detectClients(\n input: InstallerEnvironment = {},\n): Promise<ClientId[]> {\n const env = resolvedEnvironment(input);\n const markers: Record<ClientId, string[]> = {\n codex: [env.env.CODEX_HOME ?? join(env.homeDir, \".codex\")],\n \"claude-code\": [join(env.homeDir, \".claude\"), join(env.homeDir, \".claude.json\")],\n cursor: [join(env.homeDir, \".cursor\")],\n \"claude-desktop\": [dirname(getClientConfigPath(\"claude-desktop\", env))],\n };\n const detected: ClientId[] = [];\n for (const client of CORE_CLIENTS) {\n if ((await Promise.all(markers[client].map(exists))).some(Boolean)) detected.push(client);\n }\n return detected;\n}\n\nexport async function installForClients(\n clients: readonly ClientId[],\n input: InstallerEnvironment = {},\n): Promise<ClientInstallResult[]> {\n const env = resolvedEnvironment(input);\n const canonical = await installCanonicalSkill(env);\n let claudeMode: \"symlink\" | \"copy\" | null = null;\n if (clients.includes(\"claude-code\")) {\n claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);\n await installCompletionHook(env);\n }\n\n const results: ClientInstallResult[] = [];\n for (const client of clients) {\n const configPath = await configureClient(client, env);\n if (client === \"claude-code\") {\n results.push({\n client,\n configPath,\n skillPath: claudeCodeSkillDir(env.homeDir),\n skillMode: claudeMode!,\n });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n skillPath: \"MCP initialize instructions\",\n skillMode: \"mcp-instructions\",\n });\n } else {\n results.push({\n client,\n configPath,\n skillPath: canonical.path,\n skillMode: \"canonical\",\n });\n }\n }\n return results;\n}\n\nfunction jsonHasCrowdCode(content: string): boolean {\n try {\n const parsed = JSON.parse(content) as {\n mcpServers?: Record<string, { command?: string; args?: string[] }>;\n };\n const server = parsed.mcpServers?.crowdcode;\n return server?.command === MCP_SERVER.command &&\n JSON.stringify(server.args) === JSON.stringify(MCP_SERVER.args);\n } catch {\n return false;\n }\n}\n\nfunction codexHasCrowdCode(content: string): boolean {\n const merged = removeCrowdCodeTomlSection(content);\n return merged !== content.trimEnd() &&\n /\\[mcp_servers\\.(?:[\"']?crowdcode[\"']?)\\]/.test(content) &&\n /crowdcode-mcp@latest/.test(content);\n}\n\nexport async function doctorClients(\n clients: readonly ClientId[] = CORE_CLIENTS,\n input: InstallerEnvironment = {},\n): Promise<DoctorResult[]> {\n const env = resolvedEnvironment(input);\n const expectedSkill = await bundledSkill(env.packageRoot);\n const canonicalPath = canonicalSkillDir(env.homeDir);\n const canonicalCurrent =\n (await readOptional(join(canonicalPath, \"SKILL.md\"))) === expectedSkill;\n const results: DoctorResult[] = [];\n\n for (const client of clients) {\n const configPath = getClientConfigPath(client, env);\n const config = (await readOptional(configPath)) ?? \"\";\n const mcpConfigured =\n client === \"codex\" ? codexHasCrowdCode(config) : jsonHasCrowdCode(config);\n if (client === \"claude-code\") {\n const skillPath = claudeCodeSkillDir(env.homeDir);\n const skillCurrent =\n (await readOptional(join(skillPath, \"SKILL.md\"))) === expectedSkill;\n let completionHookCurrent = false;\n try {\n const settings = JSON.parse((await readOptional(join(env.homeDir, \".claude\", \"settings.json\"))) ?? \"{}\");\n const hookPath = join(env.homeDir, \".crowdcode\", \"hooks\", \"completion.cjs\");\n completionHookCurrent = (await readOptional(hookPath)) === COMPLETION_HOOK &&\n Array.isArray(settings.hooks?.Stop) && settings.hooks.Stop.some((entry: any) =>\n Array.isArray(entry?.hooks) && entry.hooks.some((hook: any) =>\n hook.type === \"command\" && hook.command === \"node\" &&\n Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));\n } catch { /* Doctor reports malformed or missing hook configuration. */ }\n results.push({ client, configPath, mcpConfigured, skillPath, skillCurrent, completionHookCurrent,\n ...(!completionHookCurrent ? { detail: \"Re-run install --client claude-code to refresh the completion reminder.\" } : {}) });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: \"MCP initialize instructions\",\n skillCurrent: mcpConfigured,\n detail: \"Claude Desktop uses CrowdCode's MCP initialization instructions.\",\n });\n } else {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: canonicalPath,\n skillCurrent: canonicalCurrent,\n });\n }\n }\n return results;\n}\n"],"mappings":";;;;;;AAYA,SAAS,MAAAA,KAAI,QAAAC,aAAY;AACzB,SAAS,uBAAuB;;;ACZzB,IAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACA/B,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AACxB,SAAS,UAAU,SAAS,MAAM,UAAU,eAAe;AAC3D,SAAS,qBAAqB;AAEvB,IAAM,eAAe;AAAA,EAC1B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAoCA,IAAM,aAAa;AAAA,EACjB,SAAS;AAAA,EACT,MAAM,CAAC,MAAM,sBAAsB;AACrC;AAEA,SAAS,oBAAoB,QAA8B,CAAC,GAAG;AAC7D,QAAM,WAAW,MAAM,YAAY,QAAQ;AAC3C,MAAI,aAAa,YAAY,aAAa,WAAW,aAAa,SAAS;AACzE,UAAM,IAAI,MAAM,yBAAyB,QAAQ,EAAE;AAAA,EACrD;AACA,SAAO;AAAA,IACL,SAAS,MAAM,WAAW,QAAQ;AAAA,IAClC;AAAA,IACA,KAAK,MAAM,OAAO,QAAQ;AAAA,IAC1B,aAAa,MAAM,eAAe,gBAAgB,YAAY,GAAG;AAAA,IACjE,KAAK,MAAM,QAAQ,MAAM,oBAAI,KAAK;AAAA,EACpC;AACF;AAEA,SAAS,gBAAgB,WAA2B;AAGlD,SAAO,QAAQ,QAAQ,cAAc,SAAS,CAAC,GAAG,IAAI;AACxD;AAEA,eAAe,OAAO,MAAgC;AACpD,MAAI;AACF,UAAM,KAAK,IAAI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AAC;","names":["rm","stat","stat","rm"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/completion-hook.ts","../src/installer.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * crowdcode-mcp — CrowdCode MCP client with local-first PII redaction.\n *\n * Subcommands:\n * (none) | serve start the stdio MCP server (default)\n * install install the skill and configure supported agents\n * doctor verify skill and MCP installation state\n * check [text] show what the redaction pipeline does to sample text\n * clear-cache delete the downloaded model cache\n */\n\nimport { rm, stat } from \"node:fs/promises\";\nimport { createInterface } from \"node:readline/promises\";\nimport { getConfig } from \"./config.js\";\nimport {\n CORE_CLIENTS,\n detectClients,\n doctorClients,\n installForClients,\n type ClientId,\n} from \"./installer.js\";\n\n// stdout carries the MCP protocol in serve mode; anything that would print\n// there (transformers download progress, stray library logs) corrupts it.\n// Patch before any heavy import happens.\nfunction routeStdoutToStderr(): void {\n console.log = (...args: unknown[]) => console.error(...args);\n console.info = (...args: unknown[]) => console.error(...args);\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n\nasync function runCheck(argText: string | undefined): Promise<void> {\n const config = getConfig();\n const text = argText ?? (await readStdin());\n if (!text.trim()) {\n console.error('usage: crowdcode-mcp check \"some text\" (or pipe via stdin)');\n process.exit(2);\n }\n\n const { RedactionEngine } = await import(\"@crowdcode/redaction\");\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n\n if (!config.disableModel) {\n console.error(\n \"loading PII model (downloads ~15 MB to \" +\n config.cacheDir +\n \" on first run; deterministic recognizers work without it) ...\",\n );\n await engine.waitForModel();\n }\n\n const result = await engine.redact(text);\n const revealed = await engine.reveal(result.text);\n\n console.error(\"\");\n console.error(\"input: \" + JSON.stringify(text));\n console.error(\"redacted: \" + JSON.stringify(result.text));\n console.error(\"revealed: \" + JSON.stringify(revealed) + \" (local round-trip)\");\n console.error(\"\");\n console.error(\n `entities removed: ${result.entitiesRemoved} model active: ${result.modelActive}`,\n );\n console.error(\n \"only the redacted form would ever be sent to the CrowdCode backend.\",\n );\n}\n\nasync function runClearCache(): Promise<void> {\n const config = getConfig();\n try {\n await stat(config.cacheDir);\n } catch {\n console.error(`nothing to clear (${config.cacheDir} does not exist)`);\n return;\n }\n await rm(config.cacheDir, { recursive: true, force: true });\n console.error(`cleared ${config.cacheDir}`);\n}\n\ninterface InstallerFlags {\n clients: ClientId[];\n allDetected: boolean;\n yes: boolean;\n}\n\nfunction parseInstallerFlags(args: string[]): InstallerFlags {\n const clients: ClientId[] = [];\n let allDetected = false;\n let yes = false;\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index]!;\n if (arg === \"--yes\" || arg === \"-y\") {\n yes = true;\n continue;\n }\n if (arg === \"--all-detected\") {\n allDetected = true;\n continue;\n }\n let value: string | undefined;\n if (arg === \"--client\") {\n value = args[++index];\n if (!value) throw new Error(\"--client requires a client identifier\");\n } else if (arg.startsWith(\"--client=\")) {\n value = arg.slice(\"--client=\".length);\n } else {\n throw new Error(`unknown install option: ${arg}`);\n }\n for (const candidate of value.split(\",\")) {\n if (!(CORE_CLIENTS as readonly string[]).includes(candidate)) {\n throw new Error(\n `unknown client ${JSON.stringify(candidate)}; use ${CORE_CLIENTS.join(\", \")}`,\n );\n }\n if (!clients.includes(candidate as ClientId)) clients.push(candidate as ClientId);\n }\n }\n if (allDetected && clients.length > 0) {\n throw new Error(\"use either --all-detected or --client, not both\");\n }\n return { clients, allDetected, yes };\n}\n\nasync function chooseInstallClients(flags: InstallerFlags): Promise<ClientId[]> {\n if (flags.clients.length > 0) return flags.clients;\n const detected = await detectClients();\n if (flags.allDetected) {\n if (detected.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n return detected;\n }\n if (flags.yes || !process.stdin.isTTY || !process.stderr.isTTY) {\n return detected.length > 0 ? detected : [...CORE_CLIENTS];\n }\n\n const defaults = detected.length > 0 ? detected : [...CORE_CLIENTS];\n console.error(\"Supported clients:\");\n CORE_CLIENTS.forEach((client, index) => {\n console.error(` ${index + 1}. ${client}${detected.includes(client) ? \" (detected)\" : \"\"}`);\n });\n const prompt = createInterface({ input: process.stdin, output: process.stderr });\n try {\n const answer = await prompt.question(\n `Install for comma-separated names/numbers [${defaults.join(\",\")}]: `,\n );\n if (!answer.trim()) return defaults;\n const selected: ClientId[] = [];\n for (const token of answer.split(\",\").map((item) => item.trim())) {\n const numbered = Number(token);\n const client = Number.isInteger(numbered)\n ? CORE_CLIENTS[numbered - 1]\n : (token as ClientId);\n if (!client || !(CORE_CLIENTS as readonly string[]).includes(client)) {\n throw new Error(`unknown client selection: ${token}`);\n }\n if (!selected.includes(client)) selected.push(client);\n }\n return selected;\n } finally {\n prompt.close();\n }\n}\n\nasync function runInstall(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients = await chooseInstallClients(flags);\n const results = await installForClients(clients);\n console.error(\"CrowdCode installation complete:\");\n for (const result of results) {\n console.error(\n ` ${result.client}: MCP ${result.configPath}; skill ${result.skillPath} (${result.skillMode})`,\n );\n }\n console.error(\"Restart these clients so they reload the CrowdCode skill and MCP server.\");\n}\n\nasync function runDoctor(args: string[]): Promise<void> {\n const flags = parseInstallerFlags(args);\n const clients =\n flags.clients.length > 0\n ? flags.clients\n : flags.allDetected\n ? await detectClients()\n : [...CORE_CLIENTS];\n if (clients.length === 0) {\n throw new Error(\"no supported clients were detected; use --client <client>\");\n }\n const results = await doctorClients(clients);\n let healthy = true;\n for (const result of results) {\n const ok = result.mcpConfigured && result.skillCurrent && result.completionHookCurrent !== false;\n healthy &&= ok;\n console.error(\n `${ok ? \"ok\" : \"missing/stale\"} ${result.client}` +\n ` MCP=${result.mcpConfigured ? \"ok\" : \"missing\"}` +\n ` skill=${result.skillCurrent ? \"ok\" : \"missing/stale\"}`,\n );\n if (result.detail) console.error(` ${result.detail}`);\n }\n if (!healthy) process.exitCode = 1;\n}\n\nfunction printHelp(): void {\n console.error(\n \"usage: crowdcode-mcp [serve|on|off|status|install|doctor|check <text>|clear-cache]\\n\" +\n \" serve start the stdio MCP server (default)\\n\" +\n \" on/off save CrowdCode default (active session overrides take precedence)\\n\" +\n \" status show the saved default for new connections\\n\" +\n \" install install the CrowdCode skill and MCP config\\n\" +\n \" [--client <client>] [--all-detected] [--yes]\\n\" +\n \" doctor verify skill and MCP config [--client <client>] [--all-detected]\\n\" +\n \" check demo the local redaction pipeline on sample text\\n\" +\n \" clear-cache delete the downloaded model cache\\n\" +\n ` clients ${CORE_CLIENTS.join(\", \")}`,\n );\n}\n\nasync function main(): Promise<void> {\n const [, , command, ...rest] = process.argv;\n switch (command) {\n case undefined:\n case \"serve\": {\n routeStdoutToStderr();\n const { startServer } = await import(\"./server.js\");\n await startServer();\n break;\n }\n case \"on\":\n case \"off\":\n case \"status\": {\n const { Preferences } = await import(\"./preferences.js\");\n const preferences = new Preferences();\n const state = command === \"status\" ? await preferences.status()\n : await preferences.set(command === \"on\", \"default\");\n console.log(JSON.stringify(state));\n break;\n }\n case \"check\":\n await runCheck(rest.length > 0 ? rest.join(\" \") : undefined);\n break;\n case \"install\":\n await runInstall(rest);\n break;\n case \"doctor\":\n await runDoctor(rest);\n break;\n case \"clear-cache\":\n await runClearCache();\n break;\n case \"--help\":\n case \"-h\":\n printHelp();\n break;\n default:\n console.error(`unknown command: ${command} (try --help)`);\n process.exit(2);\n }\n}\n\nmain().catch((err) => {\n console.error(\"crowdcode-mcp fatal:\", err);\n process.exit(1);\n});\n","/** Installed as a self-contained local Claude Code Stop hook. No network or transcript access. */\nexport const COMPLETION_HOOK = `\nlet input = '';\nprocess.stdin.setEncoding('utf8');\nprocess.stdin.on('data', chunk => { input += chunk; });\nprocess.stdin.on('end', () => {\n try {\n const event = JSON.parse(input);\n if (event.hook_event_name !== 'Stop' || event.stop_hook_active) return;\n if (Array.isArray(event.background_tasks) && event.background_tasks.length) return;\n process.stdout.write(JSON.stringify({\n decision: 'block',\n reason: \"CrowdCode completion check (once only): read crowdcode_status. If off, unavailable, or this turn only managed CrowdCode settings/reviews, finish immediately without reflection or submissions. Otherwise, if you have not already reflected for this completed task, consider the real failures, poor results, excessive cost, and detours: what specific reusable service would have been worth paying for? Call request_service only for worthwhile unmet needs, with concrete input (what the user gives), output (the exact deliverable), problem (what it solves) and price_per_call (what you would pay per call in USD). A specific improvement to an inadequate existing service qualifies; no actual purchase is needed. Skip local Python/runtime wishes and services that already worked well. Never invent a budget or repeat a submitted gap. If nothing qualifies, submit nothing. Then finish; do not reopen the user's task.\"\n }));\n } catch { /* A broken optional reminder must never trap the user. */ }\n});\n`;\n\n","import { COMPLETION_HOOK } from \"./completion-hook.js\";\nimport { createHash } from \"node:crypto\";\nimport {\n copyFile,\n lstat,\n mkdir,\n readFile,\n readlink,\n rename,\n rm,\n stat,\n symlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { basename, dirname, join, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nexport const CORE_CLIENTS = [\n \"codex\",\n \"claude-code\",\n \"claude-desktop\",\n \"cursor\",\n] as const;\n\nexport type ClientId = (typeof CORE_CLIENTS)[number];\nexport type InstallerPlatform = \"darwin\" | \"linux\" | \"win32\";\n\nexport interface InstallerEnvironment {\n homeDir?: string;\n platform?: InstallerPlatform;\n env?: NodeJS.ProcessEnv;\n packageRoot?: string;\n now?: () => Date;\n}\n\ninterface InstallState {\n packageVersion: string;\n skillHash: string;\n installedAt: string;\n}\n\nexport interface ClientInstallResult {\n client: ClientId;\n configPath: string;\n skillPath: string;\n skillMode: \"canonical\" | \"symlink\" | \"copy\" | \"mcp-instructions\";\n}\n\nexport interface DoctorResult {\n client: ClientId;\n configPath: string;\n mcpConfigured: boolean;\n skillPath: string;\n skillCurrent: boolean;\n completionHookCurrent?: boolean;\n detail?: string;\n}\n\nconst MCP_SERVER = {\n command: \"npx\",\n args: [\"-y\", \"crowdcode-mcp@latest\"],\n};\n\nfunction resolvedEnvironment(input: InstallerEnvironment = {}) {\n const platform = input.platform ?? process.platform;\n if (platform !== \"darwin\" && platform !== \"linux\" && platform !== \"win32\") {\n throw new Error(`unsupported platform: ${platform}`);\n }\n return {\n homeDir: input.homeDir ?? homedir(),\n platform,\n env: input.env ?? process.env,\n packageRoot: input.packageRoot ?? findPackageRoot(import.meta.url),\n now: input.now ?? (() => new Date()),\n };\n}\n\nfunction findPackageRoot(moduleUrl: string): string {\n // installer.ts lives in src during development and is bundled into dist/cli.js\n // for publication. Both locations are exactly one directory below package.json.\n return resolve(dirname(fileURLToPath(moduleUrl)), \"..\");\n}\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function lexists(path: string): Promise<boolean> {\n try {\n await lstat(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readOptional(path: string): Promise<string | null> {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw error;\n }\n}\n\nfunction hash(content: string): string {\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\nasync function packageVersion(packageRoot: string): Promise<string> {\n const parsed = JSON.parse(await readFile(join(packageRoot, \"package.json\"), \"utf8\"));\n if (typeof parsed.version !== \"string\") {\n throw new Error(\"crowdcode-mcp package.json has no version\");\n }\n return parsed.version;\n}\n\nasync function bundledSkill(packageRoot: string): Promise<string> {\n const packaged = join(packageRoot, \"dist\", \"skills\", \"crowdcode\", \"SKILL.md\");\n const content = await readOptional(packaged);\n if (content !== null) return content;\n\n // Development fallback. Published packages always use the dist asset.\n const source = resolve(packageRoot, \"../../skills/crowdcode/SKILL.md\");\n return readFile(source, \"utf8\");\n}\n\nfunction statePath(homeDir: string): string {\n return join(homeDir, \".crowdcode\", \"install-state.json\");\n}\n\nfunction canonicalSkillDir(homeDir: string): string {\n return join(homeDir, \".agents\", \"skills\", \"crowdcode\");\n}\n\nasync function loadState(homeDir: string): Promise<InstallState | null> {\n const raw = await readOptional(statePath(homeDir));\n if (raw === null) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<InstallState>;\n if (\n typeof parsed.packageVersion === \"string\" &&\n typeof parsed.skillHash === \"string\" &&\n typeof parsed.installedAt === \"string\"\n ) {\n return parsed as InstallState;\n }\n } catch {\n // Treat malformed state as unmanaged; user content is backed up below.\n }\n return null;\n}\n\nasync function atomicWrite(path: string, content: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n const temp = join(\n dirname(path),\n `.${basename(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,\n );\n await writeFile(temp, content, { mode: 0o600 });\n try {\n await rename(temp, path);\n } catch (error) {\n await rm(temp, { force: true });\n throw error;\n }\n}\n\nfunction backupSuffix(now: Date): string {\n return now.toISOString().replace(/[:.]/g, \"-\");\n}\n\nasync function unusedBackupPath(path: string, now: Date): Promise<string> {\n const base = `${path}.backup-${backupSuffix(now)}`;\n let candidate = base;\n for (let index = 2; await lexists(candidate); index += 1) {\n candidate = `${base}-${index}`;\n }\n return candidate;\n}\n\nasync function replaceSkillDirectory(\n path: string,\n skill: string,\n managedHash: string | null,\n now: Date,\n): Promise<void> {\n let existingSkill: string | null;\n try {\n existingSkill = await readOptional(join(path, \"SKILL.md\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOTDIR\") existingSkill = null;\n else throw error;\n }\n const newHash = hash(skill);\n if (existingSkill !== null && hash(existingSkill) === newHash) return;\n\n if (await lexists(path)) {\n const existingIsManaged =\n existingSkill !== null && managedHash !== null && hash(existingSkill) === managedHash;\n if (existingIsManaged) {\n await rm(path, { recursive: true, force: true });\n } else {\n await rename(path, await unusedBackupPath(path, now));\n }\n }\n\n const temp = `${path}.installing-${process.pid}`;\n await rm(temp, { recursive: true, force: true });\n await mkdir(temp, { recursive: true });\n await writeFile(join(temp, \"SKILL.md\"), skill);\n await rename(temp, path);\n}\n\nasync function installCanonicalSkill(env: ReturnType<typeof resolvedEnvironment>) {\n const skill = await bundledSkill(env.packageRoot);\n const previous = await loadState(env.homeDir);\n const path = canonicalSkillDir(env.homeDir);\n await mkdir(dirname(path), { recursive: true });\n await replaceSkillDirectory(path, skill, previous?.skillHash ?? null, env.now());\n\n const nextState: InstallState = {\n packageVersion: await packageVersion(env.packageRoot),\n skillHash: hash(skill),\n installedAt: env.now().toISOString(),\n };\n await atomicWrite(statePath(env.homeDir), `${JSON.stringify(nextState, null, 2)}\\n`);\n return { path, skill, state: nextState };\n}\n\nfunction claudeCodeSkillDir(homeDir: string): string {\n return join(homeDir, \".claude\", \"skills\", \"crowdcode\");\n}\n\nasync function installClaudeCodeSkill(\n env: ReturnType<typeof resolvedEnvironment>,\n canonicalPath: string,\n skill: string,\n): Promise<\"symlink\" | \"copy\"> {\n const target = claudeCodeSkillDir(env.homeDir);\n await mkdir(dirname(target), { recursive: true });\n\n let targetManaged = false;\n try {\n const targetStat = await lstat(target);\n if (targetStat.isSymbolicLink()) {\n const link = await readlink(target);\n targetManaged = resolve(dirname(target), link) === canonicalPath;\n } else {\n const current = await readOptional(join(target, \"SKILL.md\"));\n targetManaged = current !== null && hash(current) === hash(skill);\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n\n if (await lexists(target)) {\n if (targetManaged) await rm(target, { recursive: true, force: true });\n else await rename(target, await unusedBackupPath(target, env.now()));\n }\n\n if (env.platform !== \"win32\") {\n try {\n await symlink(relative(dirname(target), canonicalPath), target, \"dir\");\n return \"symlink\";\n } catch {\n // Some filesystems disallow symlinks. Fall through to a portable copy.\n }\n }\n\n await mkdir(target, { recursive: true });\n await copyFile(join(canonicalPath, \"SKILL.md\"), join(target, \"SKILL.md\"));\n return \"copy\";\n}\n\nfunction configBase(\n homeDir: string,\n platform: InstallerPlatform,\n env: NodeJS.ProcessEnv,\n): string {\n if (platform === \"win32\") {\n return env.APPDATA ?? join(homeDir, \"AppData\", \"Roaming\");\n }\n if (platform === \"darwin\") return join(homeDir, \"Library\", \"Application Support\");\n return env.XDG_CONFIG_HOME ?? join(homeDir, \".config\");\n}\n\nexport function getClientConfigPath(\n client: ClientId,\n input: InstallerEnvironment = {},\n): string {\n const env = resolvedEnvironment(input);\n switch (client) {\n case \"codex\":\n return join(env.env.CODEX_HOME ?? join(env.homeDir, \".codex\"), \"config.toml\");\n case \"claude-code\":\n return join(env.homeDir, \".claude.json\");\n case \"cursor\":\n return join(env.homeDir, \".cursor\", \"mcp.json\");\n case \"claude-desktop\":\n return join(\n configBase(env.homeDir, env.platform, env.env),\n \"Claude\",\n \"claude_desktop_config.json\",\n );\n }\n}\n\nfunction removeCrowdCodeTomlSection(content: string): string {\n const lines = content.split(/\\r?\\n/);\n const kept: string[] = [];\n let skipping = false;\n for (const line of lines) {\n const section = /^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/.exec(line);\n if (section) {\n const normalized = section[1]!.replace(/[\"']/g, \"\").replace(/\\s/g, \"\");\n skipping =\n normalized === \"mcp_servers.crowdcode\" ||\n normalized.startsWith(\"mcp_servers.crowdcode.\");\n if (skipping) continue;\n }\n if (!skipping) kept.push(line);\n }\n return kept.join(\"\\n\").trimEnd();\n}\n\nexport function mergeCodexConfig(content: string): string {\n const before = removeCrowdCodeTomlSection(content);\n const section = [\n \"[mcp_servers.crowdcode]\",\n `command = ${JSON.stringify(MCP_SERVER.command)}`,\n `args = ${JSON.stringify(MCP_SERVER.args)}`,\n ].join(\"\\n\");\n return `${before ? `${before}\\n\\n` : \"\"}${section}\\n`;\n}\n\nfunction parseJsonConfig(content: string, path: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(content) as unknown;\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"root must be an object\");\n }\n return parsed as Record<string, unknown>;\n } catch (error) {\n throw new Error(`cannot parse ${path}; no changes were written: ${(error as Error).message}`);\n }\n}\n\nexport function mergeJsonMcpConfig(content: string, path = \"config.json\"): string {\n const config = content.trim() ? parseJsonConfig(content, path) : {};\n const current = config.mcpServers;\n if (current !== undefined && (current === null || typeof current !== \"object\" || Array.isArray(current))) {\n throw new Error(`${path} has a non-object mcpServers value; no changes were written`);\n }\n config.mcpServers = {\n ...((current as Record<string, unknown> | undefined) ?? {}),\n crowdcode: MCP_SERVER,\n };\n return `${JSON.stringify(config, null, 2)}\\n`;\n}\n\nasync function installCompletionHook(env: ReturnType<typeof resolvedEnvironment>): Promise<void> {\n const settingsPath = join(env.homeDir, \".claude\", \"settings.json\");\n const settings = parseJsonConfig((await readOptional(settingsPath)) ?? \"{}\", settingsPath);\n const hooks = settings.hooks ?? {};\n if (!hooks || typeof hooks !== \"object\" || Array.isArray(hooks)) throw new Error(\"Invalid Claude hooks settings\");\n const hookMap = hooks as Record<string, unknown>;\n const stop = hookMap.Stop ?? [];\n if (!Array.isArray(stop)) throw new Error(\"Invalid Claude Stop hooks settings\");\n const hookPath = join(env.homeDir, \".crowdcode\", \"hooks\", \"completion.cjs\");\n const installed = stop.some((entry: any) => Array.isArray(entry?.hooks) &&\n entry.hooks.some((hook: any) => hook.type === \"command\" && hook.command === \"node\" &&\n Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));\n if (!installed) hookMap.Stop = [...stop, { hooks: [{ type: \"command\", command: \"node\", args: [hookPath], timeout: 5 }] }];\n settings.hooks = hookMap;\n await atomicWrite(hookPath, COMPLETION_HOOK);\n const next = JSON.stringify(settings, null, 2) + \"\\n\";\n if (next !== await readOptional(settingsPath)) await atomicWrite(settingsPath, next);\n}\n\nasync function configureClient(\n client: ClientId,\n env: ReturnType<typeof resolvedEnvironment>,\n): Promise<string> {\n const path = getClientConfigPath(client, env);\n const current = (await readOptional(path)) ?? \"\";\n const next =\n client === \"codex\" ? mergeCodexConfig(current) : mergeJsonMcpConfig(current, path);\n if (next !== current) await atomicWrite(path, next);\n return path;\n}\n\nexport async function detectClients(\n input: InstallerEnvironment = {},\n): Promise<ClientId[]> {\n const env = resolvedEnvironment(input);\n const markers: Record<ClientId, string[]> = {\n codex: [env.env.CODEX_HOME ?? join(env.homeDir, \".codex\")],\n \"claude-code\": [join(env.homeDir, \".claude\"), join(env.homeDir, \".claude.json\")],\n cursor: [join(env.homeDir, \".cursor\")],\n \"claude-desktop\": [dirname(getClientConfigPath(\"claude-desktop\", env))],\n };\n const detected: ClientId[] = [];\n for (const client of CORE_CLIENTS) {\n if ((await Promise.all(markers[client].map(exists))).some(Boolean)) detected.push(client);\n }\n return detected;\n}\n\nexport async function installForClients(\n clients: readonly ClientId[],\n input: InstallerEnvironment = {},\n): Promise<ClientInstallResult[]> {\n const env = resolvedEnvironment(input);\n const canonical = await installCanonicalSkill(env);\n let claudeMode: \"symlink\" | \"copy\" | null = null;\n if (clients.includes(\"claude-code\")) {\n claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);\n await installCompletionHook(env);\n }\n\n const results: ClientInstallResult[] = [];\n for (const client of clients) {\n const configPath = await configureClient(client, env);\n if (client === \"claude-code\") {\n results.push({\n client,\n configPath,\n skillPath: claudeCodeSkillDir(env.homeDir),\n skillMode: claudeMode!,\n });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n skillPath: \"MCP initialize instructions\",\n skillMode: \"mcp-instructions\",\n });\n } else {\n results.push({\n client,\n configPath,\n skillPath: canonical.path,\n skillMode: \"canonical\",\n });\n }\n }\n return results;\n}\n\nfunction jsonHasCrowdCode(content: string): boolean {\n try {\n const parsed = JSON.parse(content) as {\n mcpServers?: Record<string, { command?: string; args?: string[] }>;\n };\n const server = parsed.mcpServers?.crowdcode;\n return server?.command === MCP_SERVER.command &&\n JSON.stringify(server.args) === JSON.stringify(MCP_SERVER.args);\n } catch {\n return false;\n }\n}\n\nfunction codexHasCrowdCode(content: string): boolean {\n const merged = removeCrowdCodeTomlSection(content);\n return merged !== content.trimEnd() &&\n /\\[mcp_servers\\.(?:[\"']?crowdcode[\"']?)\\]/.test(content) &&\n /crowdcode-mcp@latest/.test(content);\n}\n\nexport async function doctorClients(\n clients: readonly ClientId[] = CORE_CLIENTS,\n input: InstallerEnvironment = {},\n): Promise<DoctorResult[]> {\n const env = resolvedEnvironment(input);\n const expectedSkill = await bundledSkill(env.packageRoot);\n const canonicalPath = canonicalSkillDir(env.homeDir);\n const canonicalCurrent =\n (await readOptional(join(canonicalPath, \"SKILL.md\"))) === expectedSkill;\n const results: DoctorResult[] = [];\n\n for (const client of clients) {\n const configPath = getClientConfigPath(client, env);\n const config = (await readOptional(configPath)) ?? \"\";\n const mcpConfigured =\n client === \"codex\" ? codexHasCrowdCode(config) : jsonHasCrowdCode(config);\n if (client === \"claude-code\") {\n const skillPath = claudeCodeSkillDir(env.homeDir);\n const skillCurrent =\n (await readOptional(join(skillPath, \"SKILL.md\"))) === expectedSkill;\n let completionHookCurrent = false;\n try {\n const settings = JSON.parse((await readOptional(join(env.homeDir, \".claude\", \"settings.json\"))) ?? \"{}\");\n const hookPath = join(env.homeDir, \".crowdcode\", \"hooks\", \"completion.cjs\");\n completionHookCurrent = (await readOptional(hookPath)) === COMPLETION_HOOK &&\n Array.isArray(settings.hooks?.Stop) && settings.hooks.Stop.some((entry: any) =>\n Array.isArray(entry?.hooks) && entry.hooks.some((hook: any) =>\n hook.type === \"command\" && hook.command === \"node\" &&\n Array.isArray(hook.args) && hook.args.length === 1 && hook.args[0] === hookPath));\n } catch { /* Doctor reports malformed or missing hook configuration. */ }\n results.push({ client, configPath, mcpConfigured, skillPath, skillCurrent, completionHookCurrent,\n ...(!completionHookCurrent ? { detail: \"Re-run install --client claude-code to refresh the completion reminder.\" } : {}) });\n } else if (client === \"claude-desktop\") {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: \"MCP initialize instructions\",\n skillCurrent: mcpConfigured,\n detail: \"Claude Desktop uses CrowdCode's MCP initialization instructions.\",\n });\n } else {\n results.push({\n client,\n configPath,\n mcpConfigured,\n skillPath: canonicalPath,\n skillCurr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57
|
// src/redaction/policy.ts
|
|
58
58
|
var REDACTION_POLICY = {
|
|
59
59
|
find_service: ["query"],
|
|
60
|
-
request_service: ["
|
|
60
|
+
request_service: ["input", "output", "problem"],
|
|
61
61
|
review_service: ["reason", "task_context"]
|
|
62
62
|
};
|
|
63
63
|
async function redactArgs(engine, tool, args) {
|
|
@@ -87,11 +87,17 @@ var identityShape = {
|
|
|
87
87
|
};
|
|
88
88
|
var RATING_DESCRIPTION = "Rating 1-5. Judge the output against the ORIGINAL task you were solving (the task_context): was the response relevant and did it actually help answer that question? 5 = excellent: clear schema, relevant output that answered the original question, fast, clean receipt/proof \u2014 you would reuse it confidently. 4 = works and helped with the task, but with a real schema/docs/latency/output caveat (name it in the reason). 3 = mixed: paid successfully but the response was thin, confusing, needed guesswork, or was not actually relevant or helpful for the task \u2014 a technically valid answer that did not help is a 3 at best. 2 = paid but poor: client error, unclear failure, or hard to use. 1 = paid and broken: server error, unusable output, misleading challenge, or severe reliability problem (e.g. timeout). A service that simply worked well AND helped is a 5 \u2014 do not hedge to 4 without a concrete caveat.";
|
|
89
89
|
var requestServiceShape = {
|
|
90
|
-
|
|
91
|
-
|
|
90
|
+
input: z.string().trim().min(20).max(600).describe(
|
|
91
|
+
'The clear input the user will give the service, concretely: format, size, fields. Example: "a public MP4 URL (up to 60 s) and the post text". General terms only: no names, URLs, IDs or private data.'
|
|
92
92
|
),
|
|
93
|
-
|
|
94
|
-
|
|
93
|
+
output: z.string().trim().min(20).max(600).describe(
|
|
94
|
+
'The exact output they want back, specific enough to check. Example: "the published post ID and URL, posted exactly once".'
|
|
95
|
+
),
|
|
96
|
+
problem: z.string().trim().min(20).max(800).describe(
|
|
97
|
+
'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
|
+
),
|
|
99
|
+
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."
|
|
95
101
|
),
|
|
96
102
|
requester_wallet: z.string().nullish().describe(
|
|
97
103
|
"EVM 0x address identifying who is asking (rate-limit key). Auto-filled from your local agentcash wallet \u2014 only pass it to override."
|
|
@@ -607,7 +613,6 @@ function errorPayload(tool, _err) {
|
|
|
607
613
|
avg_rating: null,
|
|
608
614
|
num_reviews: 0,
|
|
609
615
|
summary: null,
|
|
610
|
-
recent_reviews: [],
|
|
611
616
|
reason: "CrowdCode is temporarily unavailable",
|
|
612
617
|
next_step
|
|
613
618
|
};
|
|
@@ -893,10 +898,11 @@ var SERVER_INSTRUCTIONS = [
|
|
|
893
898
|
"paid service would have avoided an observed failure, poor result, expensive workaround,",
|
|
894
899
|
"or wrong turn? This applies even if no purchase was attempted. Call request_service",
|
|
895
900
|
"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).",
|
|
896
|
-
"
|
|
897
|
-
"
|
|
898
|
-
"
|
|
899
|
-
"
|
|
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.",
|
|
900
906
|
"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a",
|
|
901
907
|
"sellable remedy, and services that already worked well at reasonable cost. If nothing",
|
|
902
908
|
"qualifies, submit nothing. Never send secrets or private user data.",
|
|
@@ -909,7 +915,7 @@ var SERVER_INSTRUCTIONS = [
|
|
|
909
915
|
].join("\n");
|
|
910
916
|
function buildServer(deps) {
|
|
911
917
|
const server = new McpServer(
|
|
912
|
-
{ name: "crowdcode", version: "0.
|
|
918
|
+
{ name: "crowdcode", version: "0.12.0" },
|
|
913
919
|
{ instructions: SERVER_INSTRUCTIONS }
|
|
914
920
|
);
|
|
915
921
|
const handlers = createToolHandlers(deps);
|
|
@@ -935,7 +941,7 @@ function buildServer(deps) {
|
|
|
935
941
|
server.registerTool(
|
|
936
942
|
"request_service",
|
|
937
943
|
{
|
|
938
|
-
description:
|
|
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.',
|
|
939
945
|
inputSchema: requestServiceShape
|
|
940
946
|
},
|
|
941
947
|
(args) => handlers.request_service(args)
|
|
@@ -968,7 +974,7 @@ function buildServer(deps) {
|
|
|
968
974
|
server.registerTool(
|
|
969
975
|
"review_service",
|
|
970
976
|
{
|
|
971
|
-
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.",
|
|
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.",
|
|
972
978
|
inputSchema: reviewServiceShape
|
|
973
979
|
},
|
|
974
980
|
(args) => handlers.review_service(args)
|
|
@@ -1004,4 +1010,4 @@ export {
|
|
|
1004
1010
|
createToolHandlers,
|
|
1005
1011
|
startServer
|
|
1006
1012
|
};
|
|
1007
|
-
//# sourceMappingURL=server-
|
|
1013
|
+
//# sourceMappingURL=server-MAXZNZMK.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\";\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, reflect on concrete paid services that would fix observed shortcomings. Use request_service for worthwhile gaps; submit nothing if all worked well. Respect CrowdCode off.\" });\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n const signingWallet =\n args.auto_sign === true ? await loadWallet(walletOptions) : null;\n if (signingWallet?.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: signingWallet.errorCode,\n retryable: false,\n ok: false,\n reason: signingWallet.error,\n wallet_source: \"none\",\n });\n }\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = signingWallet!;\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n status: \"rejected\",\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n retryable: false,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n if (prepared.wallet_error_code === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: prepared.wallet_error_code,\n retryable: false,\n accepted: false,\n reason: prepared.wallet_error,\n wallet_source: \"none\",\n });\n }\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n let sentArgs = prepared.args;\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n sentArgs = retryArgs;\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n // The local Solana key signed the payer link speculatively; if it was\n // not this transaction's payer, submit once as an unlinked observation.\n const unlinkedArgs = withoutPayerSignature(prepared, sentArgs, payload);\n if (unlinkedArgs !== null) {\n payload = await forwardPayload(\"review_service\", unlinkedArgs);\n }\n return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: \"Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests.\" });\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"This means third-party APIs, remote services, and provisioned\",\n \"infrastructure. Do not use CrowdCode to gate trades, swaps, market orders,\",\n \"transfers, deposits, withdrawals, bridges, staking, lending, escrow\",\n \"settlement, or purchases of financial instruments.\",\n \"\",\n \"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 \"Review each paid service outcome with review_service. Unpaid experiences use\",\n \"the same tool: omit payment_reference and payment_proof, and reuse a stable\",\n \"review_nonce on retry (automatically generated when omitted). Payment is\",\n \"explicitly marked unverified. The reviewer still signs with the local\",\n \"AgentCash wallet; signing is automatic and does not make a payment.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent).\",\n \"Describe observed outcomes; distinguish provider faults from client bugs,\",\n \"insufficient funds, and uncertain causes. Do not invent payment evidence.\",\n \"When claiming payment, use the actual settlement reference and payee.\",\n \"An optional payment_proof is the original base64 response header. Payment\",\n \"claims must verify on x402 Base/Monad/Solana USDC or mppx Tempo. Reference an x402\",\n \"Monad (eip155:143) settlement as x402:monad:<tx_hash> and a Solana settlement as\",\n \"x402:solana:<signature> with the Solana payee. Invalid supplied claims\",\n \"are rejected, never silently downgraded. Payment verification gives the\",\n \"existing verified scoring weight; unpaid signed reviews share the same\",\n \"history, score, and per-wallet/service/day influence cap.\",\n \"\",\n \"Before the final answer to each substantive user task, reflect once: what concrete\",\n \"paid service would have avoided an observed failure, poor result, expensive workaround,\",\n \"or wrong turn? This applies even if no purchase was attempted. Call request_service\",\n \"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).\",\n \"Fill its four fields concretely enough that a developer could start building: input\",\n \"(what the user will give), output (the exact deliverable), problem (what it solves) and\",\n \"price_per_call (what you would pay per call in USD). Describe a reusable service, not\",\n \"your task. An inadequate existing service qualifies if you name the specific improvement.\",\n \"No payment or spend authority is required; price_per_call is your honest estimate.\",\n \"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a\",\n \"sellable remedy, and services that already worked well at reasonable cost. If nothing\",\n \"qualifies, submit nothing. Never send secrets or private user data.\",\n \"At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call\",\n \"set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default\",\n \"when they ask to remember it. Off overrides all automatic CrowdCode workflows:\",\n \"continue the user's task, skip reflection, checks and submissions; never backfill.\",\n \"Use list_my_reviews for 'show my reviews'; delete_my_review only for review IDs the\",\n \"user asks to delete. These management tools remain available while CrowdCode is off.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.12.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\"crowdcode_status\", {\n description: \"Read CrowdCode's effective on/off state and saved default locally. Check at task start.\",\n inputSchema: {}, annotations: { readOnlyHint: true },\n }, () => handlers.crowdcode_status());\n server.registerTool(\"set_crowdcode_enabled\", {\n description: \"Handle 'Crowdcode on' or 'Crowdcode off'. Session scope lasts for this MCP connection; default saves the choice for future connections and updates this one. Off stops checks, signing, reviews, and requests. History and deletion stay available. No queued backfill.\",\n inputSchema: { enabled: z.boolean(), scope: z.enum([\"session\", \"default\"]).default(\"session\") },\n }, (args) => handlers.set_crowdcode_enabled(args));\n server.registerTool(\"list_my_reviews\", {\n description: \"Show reviews submitted by the local wallet, newest first, including review IDs for deletion. Follow next_before_id to see older reviews. Works while CrowdCode is off. Locally signs an expiring ownership proof; never creates a wallet.\",\n inputSchema: { before_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), limit: z.number().int().min(1).max(100).default(25) },\n annotations: { readOnlyHint: true },\n }, (args) => handlers.list_my_reviews(args));\n server.registerTool(\"delete_my_review\", {\n description: \"Permanently delete the specific review ID requested by the user, owned by the local wallet. List reviews first if the ID is unknown. Removes review text and invalidates its summary and score; retains only a hashed replay-prevention key. Works while off. Never bulk-delete or choose IDs without user direction.\",\n inputSchema: { review_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) },\n annotations: { destructiveHint: true, idempotentHint: true },\n }, (args) => handlers.delete_my_review(args));\n\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record a paid service that would have materially improved the task, as four \" +\n \"concrete fields a developer could start building from: input (the clear input the \" +\n \"user will give), output (the exact output they want back), problem (what it \" +\n \"solves) and price_per_call (what you would pay per call, USD). Before your final \" +\n \"answer, reflect on failures, poor results, excessive cost and avoidable detours, \" +\n \"even when no purchase was attempted. Example: input \\\"scanned annual report PDFs, \" +\n \"up to 200 pages\\\"; output \\\"one CSV per table with page citations and low-\" +\n \"confidence cells flagged\\\"; problem \\\"OCR drops columns, forcing manual \" +\n \"reconciliation\\\"; price_per_call 0.5. Describe a reusable service, not your task; \" +\n \"no names, URLs or IDs. Skip web search that worked well, run-Python/local runtime \" +\n \"wishes and bugs in your own tools. One request per distinct gap per task; respect \" +\n \"the returned wallet limit. Submit nothing if all worked well at reasonable cost. \" +\n \"Text is redacted locally; requests stay private and only aggregated proposals \" +\n \"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, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Review a service experience, paid or unpaid, with a rating from 1 to 5 \" +\n \"and concrete observations about usefulness for the original task. \" +\n \"Review every paid outcome; unpaid successes and failures can use the same tool. \" +\n \"Distinguish provider faults from client errors, insufficient funds, and uncertain causes. \" +\n \"Signing with the local AgentCash wallet is automatic. Omit payment_reference \" +\n \"and payment_proof when no payment is claimed; payment is then marked unverified. \" +\n \"Use a stable review_nonce for unpaid retries (generated automatically if omitted). \" +\n \"For paid reviews, supply the actual settlement reference and payee; optional \" +\n \"payment_proof is the original base64 response header. Claims must verify on \" +\n \"x402 Base/Monad/Solana USDC or mppx Tempo; reference an x402 Monad (eip155:143) settlement \" +\n \"as x402:monad:<tx_hash> and a Solana one as x402:solana:<signature> (Solana payee as \" +\n \"payment_target_ref; the agentcash Solana wallet signs payer_signature automatically). \" +\n \"Invalid payment evidence is rejected, never downgraded. \" +\n \"Daily scoring influence is capped. Review text is redacted locally 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 const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);\n}\n","/** Domain-separated, expiring authorization; never sign a backend-supplied message. */\nexport function managementMessage(args: {\n action: \"list\" | \"delete\"; wallet: string; expires_at: number;\n review_id?: number; before_id?: number; limit?: number;\n}): string {\n return [\"CrowdCode review management v1\", `action:${args.action}`,\n `wallet:${args.wallet.toLowerCase()}`, `review_id:${args.review_id ?? 0}`,\n `before_id:${args.before_id ?? 0}`, `limit:${args.limit ?? 0}`,\n `expires_at:${args.expires_at}`].join(\"\\n\");\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent: Record<string, unknown>;\n isError?: boolean;\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n structuredContent: payload,\n ...(payload.status === \"unavailable\" ? { isError: true } : {}),\n };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n find_service: [\"query\"],\n request_service: [\"input\", \"output\", \"problem\"],\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 v2: four concrete fields a builder can act on. Bounds mirror\n * crowdcode.demand.validate_request_fields; 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). An honest estimate of the outcome's \" +\n \"worth, not a budget the user approved.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const 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,i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,CAAC;AACD,QAAM,WAAW,IAAI,eAAe,OAAO,YAAY,OAAO,iBAAiB;AAC/E,QAAM,SAAS,YAAY,EAAE,QAAQ,SAAS,CAAC;AAC/C,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,OAAK,MAAM,IAAI,YAAY,EAAE,OAAO,GAAG,QAAS,MAAK,gBAAgB,QAAQ;AAC/E;","names":["z","randomUUID","randomUUID","isRecord","z"]}
|
|
@@ -66,7 +66,8 @@ the live price before paying.
|
|
|
66
66
|
3. Compare the canonical `score` and use `n_eff` as evidence strength.
|
|
67
67
|
`unproven: true` means insufficient trusted evidence, not a bad service;
|
|
68
68
|
fall back to directory metadata, price, and the active spend policy.
|
|
69
|
-
4. Read `summary` when present
|
|
69
|
+
4. Read `summary` when present: pros, cons, and things to watch out for,
|
|
70
|
+
generated from reviews. Individual reviews are private and never returned.
|
|
70
71
|
5. Tell the user what will be spent when the surrounding workflow does not
|
|
71
72
|
already provide a clear spending disclosure.
|
|
72
73
|
|
|
@@ -136,28 +137,35 @@ turns. A request can describe a missing capability or a specific improvement to
|
|
|
136
137
|
an existing service. It does not require actual payment, a funded wallet, or
|
|
137
138
|
spending authority; reporting demand never authorizes a purchase.
|
|
138
139
|
|
|
139
|
-
For each distinct worthwhile gap, call `request_service` with
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
140
|
+
For each distinct worthwhile gap, call `request_service` with four fields,
|
|
141
|
+
written concretely enough that a developer could start building from them:
|
|
142
|
+
|
|
143
|
+
- `input`: the clear input the user will give the service: format, size,
|
|
144
|
+
fields. "A document" is too vague; "scanned annual-report PDFs up to 200
|
|
145
|
+
pages" is not.
|
|
146
|
+
- `output`: the exact output they want back, specific enough to check.
|
|
147
|
+
- `problem`: what it solves: what failed, cost too much, or was impossible.
|
|
148
|
+
- `price_per_call`: what you would pay per call in USD, as a number. It is
|
|
149
|
+
your honest estimate of what the outcome is worth, not a budget the user
|
|
150
|
+
approved.
|
|
151
|
+
|
|
152
|
+
Describe a reusable service, not your task: no names, URLs, IDs, or private
|
|
153
|
+
details. Example: input "scanned annual-report PDFs, up to 200 pages"; output
|
|
154
|
+
"one CSV per financial table, with source-page citations and uncertain cells
|
|
155
|
+
flagged"; problem "ordinary OCR drops columns and misaligns totals, forcing
|
|
156
|
+
manual reconstruction"; price_per_call 0.5.
|
|
157
|
+
|
|
158
|
+
Requests stay private. CrowdCode publishes only aggregated proposals: similar
|
|
159
|
+
requests are generalized, reviewed for whether people would actually pay, and
|
|
160
|
+
shown with their demand and median price. Vague or unrealistic requests are
|
|
161
|
+
not shown.
|
|
153
162
|
|
|
154
163
|
A request for improved web search must name the failure and paid improvement,
|
|
155
164
|
such as licensed full-text retrieval with verifiable page citations when normal
|
|
156
165
|
search only returned snippets. Do not request generic web search that already
|
|
157
166
|
worked well, local Python execution, more context, or an ordinary agent mistake
|
|
158
|
-
without a concrete service that would prevent it. Do not fabricate a failure
|
|
159
|
-
|
|
160
|
-
only if grounded in the conversation, and distinguish an estimate from authority.
|
|
167
|
+
without a concrete service that would prevent it. Do not fabricate a failure
|
|
168
|
+
or claim the user agreed to pay; `price_per_call` is an estimate, not authority.
|
|
161
169
|
|
|
162
170
|
If everything worked well at reasonable cost, submit nothing. Submit each
|
|
163
171
|
distinct gap once per task; don't duplicate earlier requests after follow-ups,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crowdcode-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "CrowdCode MCP client with local-first PII redaction. Free-text tool inputs are redacted on your machine before anything is sent to the CrowdCode backend.",
|
|
5
5
|
"homepage": "https://www.crowdcode.app/",
|
|
6
6
|
"repository": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/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\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n preferences?: Preferences;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n _err: unknown,\n): Record<string, unknown> {\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend or one of its dependencies is temporarily \" +\n \"unavailable; retry the same call in ~30 seconds.\",\n command: null,\n link: null,\n retry: { tool, after_seconds: 30, with: {} },\n };\n if (tool === \"get_service_score\") {\n return {\n status: \"unavailable\",\n error_code: \"backend_unavailable\",\n retryable: true,\n found: false,\n score: null,\n n_eff: 0,\n avg_rating: null,\n num_reviews: 0,\n summary: null,\n recent_reviews: [],\n reason: \"CrowdCode is temporarily unavailable\",\n next_step,\n };\n }\n 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, reflect on concrete paid services that would fix observed shortcomings. Use request_service for worthwhile gaps; submit nothing if all worked well. Respect CrowdCode off.\" });\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n const signingWallet =\n args.auto_sign === true ? await loadWallet(walletOptions) : null;\n if (signingWallet?.errorCode === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: signingWallet.errorCode,\n retryable: false,\n ok: false,\n reason: signingWallet.error,\n wallet_source: \"none\",\n });\n }\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = signingWallet!;\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n status: \"rejected\",\n error_code: wallet.errorCode ?? \"wallet_unavailable\",\n retryable: false,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const stopped = await disabled();\n if (stopped) return stopped;\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n if (prepared.wallet_error_code === \"wallet_configuration_error\") {\n return toToolResult({\n status: \"rejected\",\n error_code: prepared.wallet_error_code,\n retryable: false,\n accepted: false,\n reason: prepared.wallet_error,\n wallet_source: \"none\",\n });\n }\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n let sentArgs = prepared.args;\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n sentArgs = retryArgs;\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n // The local Solana key signed the payer link speculatively; if it was\n // not this transaction's payer, submit once as an unlinked observation.\n const unlinkedArgs = withoutPayerSignature(prepared, sentArgs, payload);\n if (unlinkedArgs !== null) {\n payload = await forwardPayload(\"review_service\", unlinkedArgs);\n }\n return toToolResult({ ...withWalletInfo(payload, prepared), task_completion_reminder: \"Before your final answer, consider request_service for concrete improvements worth paying for, grounded in this task. Skip if all worked well; do not duplicate earlier requests.\" });\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"This means third-party APIs, remote services, and provisioned\",\n \"infrastructure. Do not use CrowdCode to gate trades, swaps, market orders,\",\n \"transfers, deposits, withdrawals, bridges, staking, lending, escrow\",\n \"settlement, or purchases of financial instruments.\",\n \"\",\n \"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 \"Review each paid service outcome with review_service. Unpaid experiences use\",\n \"the same tool: omit payment_reference and payment_proof, and reuse a stable\",\n \"review_nonce on retry (automatically generated when omitted). Payment is\",\n \"explicitly marked unverified. The reviewer still signs with the local\",\n \"AgentCash wallet; signing is automatic and does not make a payment.\",\n \"Rate usefulness for the original task from 1 (unusable) to 5 (excellent).\",\n \"Describe observed outcomes; distinguish provider faults from client bugs,\",\n \"insufficient funds, and uncertain causes. Do not invent payment evidence.\",\n \"When claiming payment, use the actual settlement reference and payee.\",\n \"An optional payment_proof is the original base64 response header. Payment\",\n \"claims must verify on x402 Base/Monad/Solana USDC or mppx Tempo. Reference an x402\",\n \"Monad (eip155:143) settlement as x402:monad:<tx_hash> and a Solana settlement as\",\n \"x402:solana:<signature> with the Solana payee. Invalid supplied claims\",\n \"are rejected, never silently downgraded. Payment verification gives the\",\n \"existing verified scoring weight; unpaid signed reviews share the same\",\n \"history, score, and per-wallet/service/day influence cap.\",\n \"\",\n \"Before the final answer to each substantive user task, reflect once: what concrete\",\n \"paid service would have avoided an observed failure, poor result, expensive workaround,\",\n \"or wrong turn? This applies even if no purchase was attempted. Call request_service\",\n \"for each distinct, worthwhile gap (do not repeat the same gap on retries or follow-ups).\",\n \"Describe the real use case, precise input, deliverable, acceptance criteria, observed\",\n \"shortcoming, and why someone would pay for that outcome. An inadequate existing service\",\n \"qualifies if you name the specific improvement. No actual payment or spend authority\",\n \"is required to report demand; do not invent a budget or claim the user agreed to pay.\",\n \"Skip generic local compute, run-Python wishes, ordinary agent mistakes without a\",\n \"sellable remedy, and services that already worked well at reasonable cost. If nothing\",\n \"qualifies, submit nothing. Never send secrets or private user data.\",\n \"At task start check crowdcode_status. User says 'Crowdcode on'/'Crowdcode off': call\",\n \"set_crowdcode_enabled with enabled=true/false and scope=session, or scope=default\",\n \"when they ask to remember it. Off overrides all automatic CrowdCode workflows:\",\n \"continue the user's task, skip reflection, checks and submissions; never backfill.\",\n \"Use list_my_reviews for 'show my reviews'; delete_my_review only for review IDs the\",\n \"user asks to delete. These management tools remain available while CrowdCode is off.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.10.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\"crowdcode_status\", {\n description: \"Read CrowdCode's effective on/off state and saved default locally. Check at task start.\",\n inputSchema: {}, annotations: { readOnlyHint: true },\n }, () => handlers.crowdcode_status());\n server.registerTool(\"set_crowdcode_enabled\", {\n description: \"Handle 'Crowdcode on' or 'Crowdcode off'. Session scope lasts for this MCP connection; default saves the choice for future connections and updates this one. Off stops checks, signing, reviews, and requests. History and deletion stay available. No queued backfill.\",\n inputSchema: { enabled: z.boolean(), scope: z.enum([\"session\", \"default\"]).default(\"session\") },\n }, (args) => handlers.set_crowdcode_enabled(args));\n server.registerTool(\"list_my_reviews\", {\n description: \"Show reviews submitted by the local wallet, newest first, including review IDs for deletion. Follow next_before_id to see older reviews. Works while CrowdCode is off. Locally signs an expiring ownership proof; never creates a wallet.\",\n inputSchema: { before_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(), limit: z.number().int().min(1).max(100).default(25) },\n annotations: { readOnlyHint: true },\n }, (args) => handlers.list_my_reviews(args));\n server.registerTool(\"delete_my_review\", {\n description: \"Permanently delete the specific review ID requested by the user, owned by the local wallet. List reviews first if the ID is unknown. Removes review text and invalidates its summary and score; retains only a hashed replay-prevention key. Works while off. Never bulk-delete or choose IDs without user direction.\",\n inputSchema: { review_id: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) },\n annotations: { destructiveHint: true, idempotentHint: true },\n }, (args) => handlers.delete_my_review(args));\n\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record a concrete paid service that would have materially improved the task. \" +\n \"Before your final answer, reflect on failures, poor results, excessive cost, and \" +\n \"avoidable detours, even when no purchase was attempted. Describe the actual use \" +\n \"case, exact input, paid deliverable, acceptance criteria, what failed, and why \" +\n \"the outcome is worth paying for. Existing services may qualify when you explain \" +\n \"the specific deficiency. Example: scanned annual reports to reconciled tables \" +\n \"with page citations and confidence flags, because ordinary OCR dropped columns \" +\n \"and required manual reconciliation. Skip generic web search that worked well, \" +\n \"run-Python/local runtime wishes, and unsupported hypothetical needs. No payment \" +\n \"or spending authority is needed; never invent a budget. One request per distinct \" +\n \"gap per task; respect the returned wallet limit. Submit nothing if all worked \" +\n \"well at reasonable cost. Free text is redacted locally.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"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, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Review a service experience, paid or unpaid, with a rating from 1 to 5 \" +\n \"and concrete observations about usefulness for the original task. \" +\n \"Review every paid outcome; unpaid successes and failures can use the same tool. \" +\n \"Distinguish provider faults from client errors, insufficient funds, and uncertain causes. \" +\n \"Signing with the local AgentCash wallet is automatic. Omit payment_reference \" +\n \"and payment_proof when no payment is claimed; payment is then marked unverified. \" +\n \"Use a stable review_nonce for unpaid retries (generated automatically if omitted). \" +\n \"For paid reviews, supply the actual settlement reference and payee; optional \" +\n \"payment_proof is the original base64 response header. Claims must verify on \" +\n \"x402 Base/Monad/Solana USDC or mppx Tempo; reference an x402 Monad (eip155:143) settlement \" +\n \"as x402:monad:<tx_hash> and a Solana one as x402:solana:<signature> (Solana payee as \" +\n \"payment_target_ref; the agentcash Solana wallet signs payer_signature automatically). \" +\n \"Invalid payment evidence is rejected, never downgraded. \" +\n \"Daily scoring influence is capped. Review text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n if ((await new Preferences().status()).enabled) void warnOnToolDrift(upstream);\n}\n","/** Domain-separated, expiring authorization; never sign a backend-supplied message. */\nexport function managementMessage(args: {\n action: \"list\" | \"delete\"; wallet: string; expires_at: number;\n review_id?: number; before_id?: number; limit?: number;\n}): string {\n return [\"CrowdCode review management v1\", `action:${args.action}`,\n `wallet:${args.wallet.toLowerCase()}`, `review_id:${args.review_id ?? 0}`,\n `before_id:${args.before_id ?? 0}`, `limit:${args.limit ?? 0}`,\n `expires_at:${args.expires_at}`].join(\"\\n\");\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent: Record<string, unknown>;\n isError?: boolean;\n} {\n return {\n content: [{ type: \"text\", text: JSON.stringify(payload) }],\n structuredContent: payload,\n ...(payload.status === \"unavailable\" ? { isError: true } : {}),\n };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n find_service: [\"query\"],\n request_service: [\"service_description\", \"task_context\"],\n review_service: [\"reason\", \"task_context\"],\n};\n\nexport interface RedactedArgs {\n args: Record<string, unknown>;\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\nexport async function redactArgs(\n engine: RedactionEngine,\n tool: string,\n args: Record<string, unknown>,\n): Promise<RedactedArgs> {\n const fields = REDACTION_POLICY[tool] ?? [];\n const out = { ...args };\n let entitiesRemoved = 0;\n let modelActive = engine.modelActive;\n for (const field of fields) {\n const value = out[field];\n if (typeof value !== \"string\" || value === \"\") continue;\n const result = await engine.redact(value);\n out[field] = result.text;\n entitiesRemoved += result.entitiesRemoved;\n modelActive = result.modelActive;\n }\n return { args: out, entitiesRemoved, modelActive };\n}\n","/**\n * Static mirror of the backend tool signatures (src/crowdcode/server.py).\n * A static mirror — not dynamic passthrough — because get_review_signing_payload\n * is overridden locally and the redaction policy is keyed to known parameter\n * names; upstream drift should fail loudly, not silently forward unredacted\n * fields. Names/optionality must match the Python signatures exactly.\n */\n\nimport { z } from \"zod\";\n\nexport const identityShape = {\n service_id: z.string().nullish().describe(\"Canonical service id (svc_...)\"),\n api_endpoint: z.string().nullish().describe(\"Service API endpoint URL\"),\n payment_provider: z\n .string()\n .nullish()\n .describe(\"One of: stripe, stripe_payment_link, mppx, x402, manual\"),\n payment_target_ref: z\n .string()\n .nullish()\n .describe(\"Payment recipient reference (wallet address, account id, ...)\"),\n directory_slug: z.string().nullish().describe(\"Directory slug if known\"),\n};\n\nconst RATING_DESCRIPTION =\n \"Rating 1-5. Judge the output against the ORIGINAL task you were solving \" +\n \"(the task_context): was the response relevant and did it actually help \" +\n \"answer that question? 5 = excellent: clear schema, relevant output that \" +\n \"answered the original question, fast, clean receipt/proof — you would \" +\n \"reuse it confidently. 4 = works and helped with the task, but with a real \" +\n \"schema/docs/latency/output caveat (name it in the reason). 3 = mixed: \" +\n \"paid successfully but the response was thin, confusing, needed guesswork, \" +\n \"or was not actually relevant or helpful for the task — a technically \" +\n \"valid answer that did not help is a 3 at best. 2 = paid but poor: client \" +\n \"error, unclear failure, or hard to use. 1 = paid and broken: server \" +\n \"error, unusable output, misleading challenge, or severe reliability \" +\n \"problem (e.g. timeout). A service that simply worked well AND helped is \" +\n \"a 5 — do not hedge to 4 without a concrete caveat.\";\n\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"Concrete reusable paid offering: exact input, output or state change, \" +\n \"acceptance criteria, and why the outcome justifies payment. Ground it \" +\n \"in a real obstacle from this task, including deficiencies in existing \" +\n \"services. Example: scanned financial reports to reconciled CSV tables \" +\n \"with page citations and uncertain cells flagged, avoiding manual \" +\n \"reconstruction after OCR dropped columns. No generic local compute \" +\n \"or web search that worked well. Do not invent prices or spend authority.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Include the real use case, what was attempted, the observed failure, \" +\n \"poor quality, cost or detour, and why available alternatives fell short. \" +\n \"Omit private details. A purchase need not have been attempted.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const 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,E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