crowdcode-mcp 0.3.1 → 0.4.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
CHANGED
|
@@ -11,22 +11,38 @@ sent**.
|
|
|
11
11
|
## Install
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
|
-
|
|
14
|
+
npx -y crowdcode-mcp@latest install
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
The installer detects Codex, Claude Code, Cursor, and Claude Desktop; installs
|
|
18
|
+
the eager CrowdCode skill; and configures the local MCP server. Restart the
|
|
19
|
+
configured clients afterward. Useful non-interactive forms:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
npx -y crowdcode-mcp@latest install --all-detected --yes
|
|
23
|
+
npx -y crowdcode-mcp@latest install --client codex --client claude-code --yes
|
|
24
|
+
npx -y crowdcode-mcp@latest doctor
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
For another MCP client, use the generic configuration and install the
|
|
28
|
+
CrowdCode `SKILL.md` in that client's global skill directory:
|
|
19
29
|
|
|
20
30
|
```json
|
|
21
31
|
{
|
|
22
32
|
"mcpServers": {
|
|
23
|
-
"crowdcode": {
|
|
33
|
+
"crowdcode": {
|
|
34
|
+
"command": "npx",
|
|
35
|
+
"args": ["-y", "crowdcode-mcp@latest"]
|
|
36
|
+
}
|
|
24
37
|
}
|
|
25
38
|
}
|
|
26
39
|
```
|
|
27
40
|
|
|
28
41
|
No API key or configuration required. Node 20+.
|
|
29
42
|
|
|
43
|
+
Codex plugin source is distributed in `plugins/crowdcode`. Claude Desktop
|
|
44
|
+
release artifacts use the platform-specific `.mcpb` format.
|
|
45
|
+
|
|
30
46
|
## Tools
|
|
31
47
|
|
|
32
48
|
### `get_service_score` — call this before paying
|
package/dist/cli.js
CHANGED
|
@@ -4,7 +4,390 @@ import {
|
|
|
4
4
|
} from "./chunk-SKCQBRTB.js";
|
|
5
5
|
|
|
6
6
|
// src/cli.ts
|
|
7
|
-
import { rm, stat } from "fs/promises";
|
|
7
|
+
import { rm as rm2, stat as stat2 } from "fs/promises";
|
|
8
|
+
import { createInterface } from "readline/promises";
|
|
9
|
+
|
|
10
|
+
// src/installer.ts
|
|
11
|
+
import { createHash } from "crypto";
|
|
12
|
+
import {
|
|
13
|
+
copyFile,
|
|
14
|
+
lstat,
|
|
15
|
+
mkdir,
|
|
16
|
+
readFile,
|
|
17
|
+
readlink,
|
|
18
|
+
rename,
|
|
19
|
+
rm,
|
|
20
|
+
stat,
|
|
21
|
+
symlink,
|
|
22
|
+
writeFile
|
|
23
|
+
} from "fs/promises";
|
|
24
|
+
import { homedir } from "os";
|
|
25
|
+
import { basename, dirname, join, relative, resolve } from "path";
|
|
26
|
+
import { fileURLToPath } from "url";
|
|
27
|
+
var CORE_CLIENTS = [
|
|
28
|
+
"codex",
|
|
29
|
+
"claude-code",
|
|
30
|
+
"claude-desktop",
|
|
31
|
+
"cursor"
|
|
32
|
+
];
|
|
33
|
+
var MCP_SERVER = {
|
|
34
|
+
command: "npx",
|
|
35
|
+
args: ["-y", "crowdcode-mcp@latest"]
|
|
36
|
+
};
|
|
37
|
+
function resolvedEnvironment(input = {}) {
|
|
38
|
+
const platform = input.platform ?? process.platform;
|
|
39
|
+
if (platform !== "darwin" && platform !== "linux" && platform !== "win32") {
|
|
40
|
+
throw new Error(`unsupported platform: ${platform}`);
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
homeDir: input.homeDir ?? homedir(),
|
|
44
|
+
platform,
|
|
45
|
+
env: input.env ?? process.env,
|
|
46
|
+
packageRoot: input.packageRoot ?? findPackageRoot(import.meta.url),
|
|
47
|
+
now: input.now ?? (() => /* @__PURE__ */ new Date())
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function findPackageRoot(moduleUrl) {
|
|
51
|
+
return resolve(dirname(fileURLToPath(moduleUrl)), "..");
|
|
52
|
+
}
|
|
53
|
+
async function exists(path) {
|
|
54
|
+
try {
|
|
55
|
+
await stat(path);
|
|
56
|
+
return true;
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function lexists(path) {
|
|
62
|
+
try {
|
|
63
|
+
await lstat(path);
|
|
64
|
+
return true;
|
|
65
|
+
} catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function readOptional(path) {
|
|
70
|
+
try {
|
|
71
|
+
return await readFile(path, "utf8");
|
|
72
|
+
} catch (error) {
|
|
73
|
+
if (error.code === "ENOENT") return null;
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function hash(content) {
|
|
78
|
+
return createHash("sha256").update(content).digest("hex");
|
|
79
|
+
}
|
|
80
|
+
async function packageVersion(packageRoot) {
|
|
81
|
+
const parsed = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
|
|
82
|
+
if (typeof parsed.version !== "string") {
|
|
83
|
+
throw new Error("crowdcode-mcp package.json has no version");
|
|
84
|
+
}
|
|
85
|
+
return parsed.version;
|
|
86
|
+
}
|
|
87
|
+
async function bundledSkill(packageRoot) {
|
|
88
|
+
const packaged = join(packageRoot, "dist", "skills", "crowdcode", "SKILL.md");
|
|
89
|
+
const content = await readOptional(packaged);
|
|
90
|
+
if (content !== null) return content;
|
|
91
|
+
const source = resolve(packageRoot, "../../skills/crowdcode/SKILL.md");
|
|
92
|
+
return readFile(source, "utf8");
|
|
93
|
+
}
|
|
94
|
+
function statePath(homeDir) {
|
|
95
|
+
return join(homeDir, ".crowdcode", "install-state.json");
|
|
96
|
+
}
|
|
97
|
+
function canonicalSkillDir(homeDir) {
|
|
98
|
+
return join(homeDir, ".agents", "skills", "crowdcode");
|
|
99
|
+
}
|
|
100
|
+
async function loadState(homeDir) {
|
|
101
|
+
const raw = await readOptional(statePath(homeDir));
|
|
102
|
+
if (raw === null) return null;
|
|
103
|
+
try {
|
|
104
|
+
const parsed = JSON.parse(raw);
|
|
105
|
+
if (typeof parsed.packageVersion === "string" && typeof parsed.skillHash === "string" && typeof parsed.installedAt === "string") {
|
|
106
|
+
return parsed;
|
|
107
|
+
}
|
|
108
|
+
} catch {
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
async function atomicWrite(path, content) {
|
|
113
|
+
await mkdir(dirname(path), { recursive: true });
|
|
114
|
+
const temp = join(
|
|
115
|
+
dirname(path),
|
|
116
|
+
`.${basename(path)}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`
|
|
117
|
+
);
|
|
118
|
+
await writeFile(temp, content, { mode: 384 });
|
|
119
|
+
try {
|
|
120
|
+
await rename(temp, path);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
await rm(temp, { force: true });
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
function backupSuffix(now) {
|
|
127
|
+
return now.toISOString().replace(/[:.]/g, "-");
|
|
128
|
+
}
|
|
129
|
+
async function unusedBackupPath(path, now) {
|
|
130
|
+
const base = `${path}.backup-${backupSuffix(now)}`;
|
|
131
|
+
let candidate = base;
|
|
132
|
+
for (let index = 2; await lexists(candidate); index += 1) {
|
|
133
|
+
candidate = `${base}-${index}`;
|
|
134
|
+
}
|
|
135
|
+
return candidate;
|
|
136
|
+
}
|
|
137
|
+
async function replaceSkillDirectory(path, skill, managedHash, now) {
|
|
138
|
+
let existingSkill;
|
|
139
|
+
try {
|
|
140
|
+
existingSkill = await readOptional(join(path, "SKILL.md"));
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error.code === "ENOTDIR") existingSkill = null;
|
|
143
|
+
else throw error;
|
|
144
|
+
}
|
|
145
|
+
const newHash = hash(skill);
|
|
146
|
+
if (existingSkill !== null && hash(existingSkill) === newHash) return;
|
|
147
|
+
if (await lexists(path)) {
|
|
148
|
+
const existingIsManaged = existingSkill !== null && managedHash !== null && hash(existingSkill) === managedHash;
|
|
149
|
+
if (existingIsManaged) {
|
|
150
|
+
await rm(path, { recursive: true, force: true });
|
|
151
|
+
} else {
|
|
152
|
+
await rename(path, await unusedBackupPath(path, now));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const temp = `${path}.installing-${process.pid}`;
|
|
156
|
+
await rm(temp, { recursive: true, force: true });
|
|
157
|
+
await mkdir(temp, { recursive: true });
|
|
158
|
+
await writeFile(join(temp, "SKILL.md"), skill);
|
|
159
|
+
await rename(temp, path);
|
|
160
|
+
}
|
|
161
|
+
async function installCanonicalSkill(env) {
|
|
162
|
+
const skill = await bundledSkill(env.packageRoot);
|
|
163
|
+
const previous = await loadState(env.homeDir);
|
|
164
|
+
const path = canonicalSkillDir(env.homeDir);
|
|
165
|
+
await mkdir(dirname(path), { recursive: true });
|
|
166
|
+
await replaceSkillDirectory(path, skill, previous?.skillHash ?? null, env.now());
|
|
167
|
+
const nextState = {
|
|
168
|
+
packageVersion: await packageVersion(env.packageRoot),
|
|
169
|
+
skillHash: hash(skill),
|
|
170
|
+
installedAt: env.now().toISOString()
|
|
171
|
+
};
|
|
172
|
+
await atomicWrite(statePath(env.homeDir), `${JSON.stringify(nextState, null, 2)}
|
|
173
|
+
`);
|
|
174
|
+
return { path, skill, state: nextState };
|
|
175
|
+
}
|
|
176
|
+
function claudeCodeSkillDir(homeDir) {
|
|
177
|
+
return join(homeDir, ".claude", "skills", "crowdcode");
|
|
178
|
+
}
|
|
179
|
+
async function installClaudeCodeSkill(env, canonicalPath, skill) {
|
|
180
|
+
const target = claudeCodeSkillDir(env.homeDir);
|
|
181
|
+
await mkdir(dirname(target), { recursive: true });
|
|
182
|
+
let targetManaged = false;
|
|
183
|
+
try {
|
|
184
|
+
const targetStat = await lstat(target);
|
|
185
|
+
if (targetStat.isSymbolicLink()) {
|
|
186
|
+
const link = await readlink(target);
|
|
187
|
+
targetManaged = resolve(dirname(target), link) === canonicalPath;
|
|
188
|
+
} else {
|
|
189
|
+
const current = await readOptional(join(target, "SKILL.md"));
|
|
190
|
+
targetManaged = current !== null && hash(current) === hash(skill);
|
|
191
|
+
}
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (error.code !== "ENOENT") throw error;
|
|
194
|
+
}
|
|
195
|
+
if (await lexists(target)) {
|
|
196
|
+
if (targetManaged) await rm(target, { recursive: true, force: true });
|
|
197
|
+
else await rename(target, await unusedBackupPath(target, env.now()));
|
|
198
|
+
}
|
|
199
|
+
if (env.platform !== "win32") {
|
|
200
|
+
try {
|
|
201
|
+
await symlink(relative(dirname(target), canonicalPath), target, "dir");
|
|
202
|
+
return "symlink";
|
|
203
|
+
} catch {
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
await mkdir(target, { recursive: true });
|
|
207
|
+
await copyFile(join(canonicalPath, "SKILL.md"), join(target, "SKILL.md"));
|
|
208
|
+
return "copy";
|
|
209
|
+
}
|
|
210
|
+
function configBase(homeDir, platform, env) {
|
|
211
|
+
if (platform === "win32") {
|
|
212
|
+
return env.APPDATA ?? join(homeDir, "AppData", "Roaming");
|
|
213
|
+
}
|
|
214
|
+
if (platform === "darwin") return join(homeDir, "Library", "Application Support");
|
|
215
|
+
return env.XDG_CONFIG_HOME ?? join(homeDir, ".config");
|
|
216
|
+
}
|
|
217
|
+
function getClientConfigPath(client, input = {}) {
|
|
218
|
+
const env = resolvedEnvironment(input);
|
|
219
|
+
switch (client) {
|
|
220
|
+
case "codex":
|
|
221
|
+
return join(env.env.CODEX_HOME ?? join(env.homeDir, ".codex"), "config.toml");
|
|
222
|
+
case "claude-code":
|
|
223
|
+
return join(env.homeDir, ".claude.json");
|
|
224
|
+
case "cursor":
|
|
225
|
+
return join(env.homeDir, ".cursor", "mcp.json");
|
|
226
|
+
case "claude-desktop":
|
|
227
|
+
return join(
|
|
228
|
+
configBase(env.homeDir, env.platform, env.env),
|
|
229
|
+
"Claude",
|
|
230
|
+
"claude_desktop_config.json"
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
function removeCrowdCodeTomlSection(content) {
|
|
235
|
+
const lines = content.split(/\r?\n/);
|
|
236
|
+
const kept = [];
|
|
237
|
+
let skipping = false;
|
|
238
|
+
for (const line of lines) {
|
|
239
|
+
const section = /^\s*\[([^\]]+)\]\s*(?:#.*)?$/.exec(line);
|
|
240
|
+
if (section) {
|
|
241
|
+
const normalized = section[1].replace(/["']/g, "").replace(/\s/g, "");
|
|
242
|
+
skipping = normalized === "mcp_servers.crowdcode" || normalized.startsWith("mcp_servers.crowdcode.");
|
|
243
|
+
if (skipping) continue;
|
|
244
|
+
}
|
|
245
|
+
if (!skipping) kept.push(line);
|
|
246
|
+
}
|
|
247
|
+
return kept.join("\n").trimEnd();
|
|
248
|
+
}
|
|
249
|
+
function mergeCodexConfig(content) {
|
|
250
|
+
const before = removeCrowdCodeTomlSection(content);
|
|
251
|
+
const section = [
|
|
252
|
+
"[mcp_servers.crowdcode]",
|
|
253
|
+
`command = ${JSON.stringify(MCP_SERVER.command)}`,
|
|
254
|
+
`args = ${JSON.stringify(MCP_SERVER.args)}`
|
|
255
|
+
].join("\n");
|
|
256
|
+
return `${before ? `${before}
|
|
257
|
+
|
|
258
|
+
` : ""}${section}
|
|
259
|
+
`;
|
|
260
|
+
}
|
|
261
|
+
function parseJsonConfig(content, path) {
|
|
262
|
+
try {
|
|
263
|
+
const parsed = JSON.parse(content);
|
|
264
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
265
|
+
throw new Error("root must be an object");
|
|
266
|
+
}
|
|
267
|
+
return parsed;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
throw new Error(`cannot parse ${path}; no changes were written: ${error.message}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function mergeJsonMcpConfig(content, path = "config.json") {
|
|
273
|
+
const config = content.trim() ? parseJsonConfig(content, path) : {};
|
|
274
|
+
const current = config.mcpServers;
|
|
275
|
+
if (current !== void 0 && (current === null || typeof current !== "object" || Array.isArray(current))) {
|
|
276
|
+
throw new Error(`${path} has a non-object mcpServers value; no changes were written`);
|
|
277
|
+
}
|
|
278
|
+
config.mcpServers = {
|
|
279
|
+
...current ?? {},
|
|
280
|
+
crowdcode: MCP_SERVER
|
|
281
|
+
};
|
|
282
|
+
return `${JSON.stringify(config, null, 2)}
|
|
283
|
+
`;
|
|
284
|
+
}
|
|
285
|
+
async function configureClient(client, env) {
|
|
286
|
+
const path = getClientConfigPath(client, env);
|
|
287
|
+
const current = await readOptional(path) ?? "";
|
|
288
|
+
const next = client === "codex" ? mergeCodexConfig(current) : mergeJsonMcpConfig(current, path);
|
|
289
|
+
if (next !== current) await atomicWrite(path, next);
|
|
290
|
+
return path;
|
|
291
|
+
}
|
|
292
|
+
async function detectClients(input = {}) {
|
|
293
|
+
const env = resolvedEnvironment(input);
|
|
294
|
+
const markers = {
|
|
295
|
+
codex: [env.env.CODEX_HOME ?? join(env.homeDir, ".codex")],
|
|
296
|
+
"claude-code": [join(env.homeDir, ".claude"), join(env.homeDir, ".claude.json")],
|
|
297
|
+
cursor: [join(env.homeDir, ".cursor")],
|
|
298
|
+
"claude-desktop": [dirname(getClientConfigPath("claude-desktop", env))]
|
|
299
|
+
};
|
|
300
|
+
const detected = [];
|
|
301
|
+
for (const client of CORE_CLIENTS) {
|
|
302
|
+
if ((await Promise.all(markers[client].map(exists))).some(Boolean)) detected.push(client);
|
|
303
|
+
}
|
|
304
|
+
return detected;
|
|
305
|
+
}
|
|
306
|
+
async function installForClients(clients, input = {}) {
|
|
307
|
+
const env = resolvedEnvironment(input);
|
|
308
|
+
const canonical = await installCanonicalSkill(env);
|
|
309
|
+
let claudeMode = null;
|
|
310
|
+
if (clients.includes("claude-code")) {
|
|
311
|
+
claudeMode = await installClaudeCodeSkill(env, canonical.path, canonical.skill);
|
|
312
|
+
}
|
|
313
|
+
const results = [];
|
|
314
|
+
for (const client of clients) {
|
|
315
|
+
const configPath = await configureClient(client, env);
|
|
316
|
+
if (client === "claude-code") {
|
|
317
|
+
results.push({
|
|
318
|
+
client,
|
|
319
|
+
configPath,
|
|
320
|
+
skillPath: claudeCodeSkillDir(env.homeDir),
|
|
321
|
+
skillMode: claudeMode
|
|
322
|
+
});
|
|
323
|
+
} else if (client === "claude-desktop") {
|
|
324
|
+
results.push({
|
|
325
|
+
client,
|
|
326
|
+
configPath,
|
|
327
|
+
skillPath: "MCP initialize instructions",
|
|
328
|
+
skillMode: "mcp-instructions"
|
|
329
|
+
});
|
|
330
|
+
} else {
|
|
331
|
+
results.push({
|
|
332
|
+
client,
|
|
333
|
+
configPath,
|
|
334
|
+
skillPath: canonical.path,
|
|
335
|
+
skillMode: "canonical"
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return results;
|
|
340
|
+
}
|
|
341
|
+
function jsonHasCrowdCode(content) {
|
|
342
|
+
try {
|
|
343
|
+
const parsed = JSON.parse(content);
|
|
344
|
+
const server = parsed.mcpServers?.crowdcode;
|
|
345
|
+
return server?.command === MCP_SERVER.command && JSON.stringify(server.args) === JSON.stringify(MCP_SERVER.args);
|
|
346
|
+
} catch {
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
function codexHasCrowdCode(content) {
|
|
351
|
+
const merged = removeCrowdCodeTomlSection(content);
|
|
352
|
+
return merged !== content.trimEnd() && /\[mcp_servers\.(?:["']?crowdcode["']?)\]/.test(content) && /crowdcode-mcp@latest/.test(content);
|
|
353
|
+
}
|
|
354
|
+
async function doctorClients(clients = CORE_CLIENTS, input = {}) {
|
|
355
|
+
const env = resolvedEnvironment(input);
|
|
356
|
+
const expectedSkill = await bundledSkill(env.packageRoot);
|
|
357
|
+
const canonicalPath = canonicalSkillDir(env.homeDir);
|
|
358
|
+
const canonicalCurrent = await readOptional(join(canonicalPath, "SKILL.md")) === expectedSkill;
|
|
359
|
+
const results = [];
|
|
360
|
+
for (const client of clients) {
|
|
361
|
+
const configPath = getClientConfigPath(client, env);
|
|
362
|
+
const config = await readOptional(configPath) ?? "";
|
|
363
|
+
const mcpConfigured = client === "codex" ? codexHasCrowdCode(config) : jsonHasCrowdCode(config);
|
|
364
|
+
if (client === "claude-code") {
|
|
365
|
+
const skillPath = claudeCodeSkillDir(env.homeDir);
|
|
366
|
+
const skillCurrent = await readOptional(join(skillPath, "SKILL.md")) === expectedSkill;
|
|
367
|
+
results.push({ client, configPath, mcpConfigured, skillPath, skillCurrent });
|
|
368
|
+
} else if (client === "claude-desktop") {
|
|
369
|
+
results.push({
|
|
370
|
+
client,
|
|
371
|
+
configPath,
|
|
372
|
+
mcpConfigured,
|
|
373
|
+
skillPath: "MCP initialize instructions",
|
|
374
|
+
skillCurrent: mcpConfigured,
|
|
375
|
+
detail: "Claude Desktop uses CrowdCode's MCP initialization instructions."
|
|
376
|
+
});
|
|
377
|
+
} else {
|
|
378
|
+
results.push({
|
|
379
|
+
client,
|
|
380
|
+
configPath,
|
|
381
|
+
mcpConfigured,
|
|
382
|
+
skillPath: canonicalPath,
|
|
383
|
+
skillCurrent: canonicalCurrent
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return results;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// src/cli.ts
|
|
8
391
|
function routeStdoutToStderr() {
|
|
9
392
|
console.log = (...args) => console.error(...args);
|
|
10
393
|
console.info = (...args) => console.error(...args);
|
|
@@ -51,35 +434,155 @@ async function runCheck(argText) {
|
|
|
51
434
|
async function runClearCache() {
|
|
52
435
|
const config = getConfig();
|
|
53
436
|
try {
|
|
54
|
-
await
|
|
437
|
+
await stat2(config.cacheDir);
|
|
55
438
|
} catch {
|
|
56
439
|
console.error(`nothing to clear (${config.cacheDir} does not exist)`);
|
|
57
440
|
return;
|
|
58
441
|
}
|
|
59
|
-
await
|
|
442
|
+
await rm2(config.cacheDir, { recursive: true, force: true });
|
|
60
443
|
console.error(`cleared ${config.cacheDir}`);
|
|
61
444
|
}
|
|
445
|
+
function parseInstallerFlags(args) {
|
|
446
|
+
const clients = [];
|
|
447
|
+
let allDetected = false;
|
|
448
|
+
let yes = false;
|
|
449
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
450
|
+
const arg = args[index];
|
|
451
|
+
if (arg === "--yes" || arg === "-y") {
|
|
452
|
+
yes = true;
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (arg === "--all-detected") {
|
|
456
|
+
allDetected = true;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
let value;
|
|
460
|
+
if (arg === "--client") {
|
|
461
|
+
value = args[++index];
|
|
462
|
+
if (!value) throw new Error("--client requires a client identifier");
|
|
463
|
+
} else if (arg.startsWith("--client=")) {
|
|
464
|
+
value = arg.slice("--client=".length);
|
|
465
|
+
} else {
|
|
466
|
+
throw new Error(`unknown install option: ${arg}`);
|
|
467
|
+
}
|
|
468
|
+
for (const candidate of value.split(",")) {
|
|
469
|
+
if (!CORE_CLIENTS.includes(candidate)) {
|
|
470
|
+
throw new Error(
|
|
471
|
+
`unknown client ${JSON.stringify(candidate)}; use ${CORE_CLIENTS.join(", ")}`
|
|
472
|
+
);
|
|
473
|
+
}
|
|
474
|
+
if (!clients.includes(candidate)) clients.push(candidate);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
if (allDetected && clients.length > 0) {
|
|
478
|
+
throw new Error("use either --all-detected or --client, not both");
|
|
479
|
+
}
|
|
480
|
+
return { clients, allDetected, yes };
|
|
481
|
+
}
|
|
482
|
+
async function chooseInstallClients(flags) {
|
|
483
|
+
if (flags.clients.length > 0) return flags.clients;
|
|
484
|
+
const detected = await detectClients();
|
|
485
|
+
if (flags.allDetected) {
|
|
486
|
+
if (detected.length === 0) {
|
|
487
|
+
throw new Error("no supported clients were detected; use --client <client>");
|
|
488
|
+
}
|
|
489
|
+
return detected;
|
|
490
|
+
}
|
|
491
|
+
if (flags.yes || !process.stdin.isTTY || !process.stderr.isTTY) {
|
|
492
|
+
return detected.length > 0 ? detected : [...CORE_CLIENTS];
|
|
493
|
+
}
|
|
494
|
+
const defaults = detected.length > 0 ? detected : [...CORE_CLIENTS];
|
|
495
|
+
console.error("Supported clients:");
|
|
496
|
+
CORE_CLIENTS.forEach((client, index) => {
|
|
497
|
+
console.error(` ${index + 1}. ${client}${detected.includes(client) ? " (detected)" : ""}`);
|
|
498
|
+
});
|
|
499
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
500
|
+
try {
|
|
501
|
+
const answer = await prompt.question(
|
|
502
|
+
`Install for comma-separated names/numbers [${defaults.join(",")}]: `
|
|
503
|
+
);
|
|
504
|
+
if (!answer.trim()) return defaults;
|
|
505
|
+
const selected = [];
|
|
506
|
+
for (const token of answer.split(",").map((item) => item.trim())) {
|
|
507
|
+
const numbered = Number(token);
|
|
508
|
+
const client = Number.isInteger(numbered) ? CORE_CLIENTS[numbered - 1] : token;
|
|
509
|
+
if (!client || !CORE_CLIENTS.includes(client)) {
|
|
510
|
+
throw new Error(`unknown client selection: ${token}`);
|
|
511
|
+
}
|
|
512
|
+
if (!selected.includes(client)) selected.push(client);
|
|
513
|
+
}
|
|
514
|
+
return selected;
|
|
515
|
+
} finally {
|
|
516
|
+
prompt.close();
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
async function runInstall(args) {
|
|
520
|
+
const flags = parseInstallerFlags(args);
|
|
521
|
+
const clients = await chooseInstallClients(flags);
|
|
522
|
+
const results = await installForClients(clients);
|
|
523
|
+
console.error("CrowdCode installation complete:");
|
|
524
|
+
for (const result of results) {
|
|
525
|
+
console.error(
|
|
526
|
+
` ${result.client}: MCP ${result.configPath}; skill ${result.skillPath} (${result.skillMode})`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
console.error("Restart these clients so they reload the CrowdCode skill and MCP server.");
|
|
530
|
+
}
|
|
531
|
+
async function runDoctor(args) {
|
|
532
|
+
const flags = parseInstallerFlags(args);
|
|
533
|
+
const clients = flags.clients.length > 0 ? flags.clients : flags.allDetected ? await detectClients() : [...CORE_CLIENTS];
|
|
534
|
+
if (clients.length === 0) {
|
|
535
|
+
throw new Error("no supported clients were detected; use --client <client>");
|
|
536
|
+
}
|
|
537
|
+
const results = await doctorClients(clients);
|
|
538
|
+
let healthy = true;
|
|
539
|
+
for (const result of results) {
|
|
540
|
+
const ok = result.mcpConfigured && result.skillCurrent;
|
|
541
|
+
healthy &&= ok;
|
|
542
|
+
console.error(
|
|
543
|
+
`${ok ? "ok" : "missing/stale"} ${result.client} MCP=${result.mcpConfigured ? "ok" : "missing"} skill=${result.skillCurrent ? "ok" : "missing/stale"}`
|
|
544
|
+
);
|
|
545
|
+
if (result.detail) console.error(` ${result.detail}`);
|
|
546
|
+
}
|
|
547
|
+
if (!healthy) process.exitCode = 1;
|
|
548
|
+
}
|
|
549
|
+
function printHelp() {
|
|
550
|
+
console.error(
|
|
551
|
+
`usage: crowdcode-mcp [serve|install|doctor|check <text>|clear-cache]
|
|
552
|
+
serve start the stdio MCP server (default)
|
|
553
|
+
install install the CrowdCode skill and MCP config
|
|
554
|
+
[--client <client>] [--all-detected] [--yes]
|
|
555
|
+
doctor verify skill and MCP config [--client <client>] [--all-detected]
|
|
556
|
+
check demo the local redaction pipeline on sample text
|
|
557
|
+
clear-cache delete the downloaded model cache
|
|
558
|
+
clients ${CORE_CLIENTS.join(", ")}`
|
|
559
|
+
);
|
|
560
|
+
}
|
|
62
561
|
async function main() {
|
|
63
562
|
const [, , command, ...rest] = process.argv;
|
|
64
563
|
switch (command) {
|
|
65
564
|
case void 0:
|
|
66
565
|
case "serve": {
|
|
67
566
|
routeStdoutToStderr();
|
|
68
|
-
const { startServer } = await import("./server-
|
|
567
|
+
const { startServer } = await import("./server-WNVGTJQI.js");
|
|
69
568
|
await startServer();
|
|
70
569
|
break;
|
|
71
570
|
}
|
|
72
571
|
case "check":
|
|
73
572
|
await runCheck(rest.length > 0 ? rest.join(" ") : void 0);
|
|
74
573
|
break;
|
|
574
|
+
case "install":
|
|
575
|
+
await runInstall(rest);
|
|
576
|
+
break;
|
|
577
|
+
case "doctor":
|
|
578
|
+
await runDoctor(rest);
|
|
579
|
+
break;
|
|
75
580
|
case "clear-cache":
|
|
76
581
|
await runClearCache();
|
|
77
582
|
break;
|
|
78
583
|
case "--help":
|
|
79
584
|
case "-h":
|
|
80
|
-
|
|
81
|
-
"usage: crowdcode-mcp [serve|check <text>|clear-cache]\n serve start the stdio MCP server (default)\n check demo the local redaction pipeline on sample text\n clear-cache delete the downloaded model cache"
|
|
82
|
-
);
|
|
585
|
+
printHelp();
|
|
83
586
|
break;
|
|
84
587
|
default:
|
|
85
588
|
console.error(`unknown command: ${command} (try --help)`);
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.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 * 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 { getConfig } from \"./config.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\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 \"check\":\n await runCheck(rest.length > 0 ? rest.join(\" \") : undefined);\n break;\n case \"clear-cache\":\n await runClearCache();\n break;\n case \"--help\":\n case \"-h\":\n console.error(\n \"usage: crowdcode-mcp [serve|check <text>|clear-cache]\\n\" +\n \" serve start the stdio MCP server (default)\\n\" +\n \" check demo the local redaction pipeline on sample text\\n\" +\n \" clear-cache delete the downloaded model cache\",\n );\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"],"mappings":";;;;;;AAUA,SAAS,IAAI,YAAY;AAMzB,SAAS,sBAA4B;AACnC,UAAQ,MAAM,IAAI,SAAoB,QAAQ,MAAM,GAAG,IAAI;AAC3D,UAAQ,OAAO,IAAI,SAAoB,QAAQ,MAAM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O,QAAQ,kBAAkB;AACpE;AAAA,EACF;AACA,QAAM,GAAG,OAAO,UAAU,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAC1D,UAAQ,MAAM,WAAW,OAAO,QAAQ,EAAE;AAC5C;AAEA,eAAe,OAAsB;AACnC,QAAM,CAAC,EAAE,EAAE,SAAS,GAAG,IAAI,IAAI,QAAQ;AACvC,UAAQ,SAAS;AAAA,IACf,KAAK;AAAA,IACL,KAAK,SAAS;AACZ,0BAAoB;AACpB,YAAM,EAAE,YAAY,IAAI,MAAM,OAAO,sBAAa;AAClD,YAAM,YAAY;AAClB;AAAA,IACF;AAAA,IACA,KAAK;AACH,YAAM,SAAS,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,MAAS;AAC3D;AAAA,IACF,KAAK;AACH,YAAM,cAAc;AACpB;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AACH,cAAQ;AAAA,QACN;AAAA,MAIF;AACA;AAAA,IACF;AACE,cAAQ,MAAM,oBAAoB,OAAO,eAAe;AACxD,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,wBAAwB,GAAG;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.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;\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|install|doctor|check <text>|clear-cache]\\n\" +\n \" serve start the stdio MCP server (default)\\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 \"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","import { 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 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 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 }\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 results.push({ client, configPath, mcpConfigured, skillPath, skillCurrent });\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;;;ACbhC,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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AACpB,UAAQ,MAAM,wBAAwB,GAAG;AACzC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["rm","stat","stat","rm"]}
|
|
@@ -110,6 +110,9 @@ var MIRRORED_REMOTE_TOOLS = [
|
|
|
110
110
|
function orNull(value) {
|
|
111
111
|
return typeof value === "string" && value !== "" ? value : null;
|
|
112
112
|
}
|
|
113
|
+
function isRecord(value) {
|
|
114
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
115
|
+
}
|
|
113
116
|
async function getReviewSigningPayload(deps, args) {
|
|
114
117
|
let identity;
|
|
115
118
|
try {
|
|
@@ -136,13 +139,15 @@ async function getReviewSigningPayload(deps, args) {
|
|
|
136
139
|
let effective = identity;
|
|
137
140
|
if (score.found === true) {
|
|
138
141
|
try {
|
|
142
|
+
const hasResolvedIdentity = isRecord(score.resolved_identity);
|
|
143
|
+
const resolved = hasResolvedIdentity ? score.resolved_identity : score;
|
|
139
144
|
effective = buildIdentity({
|
|
140
|
-
service_id: orNull(
|
|
145
|
+
service_id: orNull(resolved.service_id),
|
|
141
146
|
service_name: orNull(score.service_name),
|
|
142
|
-
api_endpoint:
|
|
143
|
-
payment_provider:
|
|
144
|
-
payment_target_ref:
|
|
145
|
-
directory_slug:
|
|
147
|
+
api_endpoint: hasResolvedIdentity ? orNull(resolved.api_endpoint) : orNull(score.canonical_endpoint),
|
|
148
|
+
payment_provider: orNull(resolved.payment_provider),
|
|
149
|
+
payment_target_ref: orNull(resolved.payment_target_ref),
|
|
150
|
+
directory_slug: orNull(resolved.directory_slug)
|
|
146
151
|
});
|
|
147
152
|
} catch (err) {
|
|
148
153
|
return { ok: false, reason: err.message };
|
|
@@ -238,17 +243,21 @@ async function prepareSignedReview(deps, args, wallet) {
|
|
|
238
243
|
const signature = await loaded.account.signMessage({
|
|
239
244
|
message: payload.message
|
|
240
245
|
});
|
|
241
|
-
const identity =
|
|
246
|
+
const identity = buildIdentity(
|
|
247
|
+
payload.identity
|
|
248
|
+
);
|
|
249
|
+
const signedReason = String(payload.reason);
|
|
242
250
|
return {
|
|
243
251
|
args: {
|
|
244
252
|
...args,
|
|
245
253
|
// Pass the resolved identity verbatim so the backend rebuilds the exact
|
|
246
254
|
// payload that was just signed.
|
|
247
|
-
service_id: identity.service_id
|
|
248
|
-
api_endpoint: identity.api_endpoint
|
|
249
|
-
payment_provider: identity.payment_provider
|
|
250
|
-
payment_target_ref: identity.payment_target_ref
|
|
251
|
-
directory_slug: identity.directory_slug
|
|
255
|
+
service_id: identity.service_id,
|
|
256
|
+
api_endpoint: identity.api_endpoint,
|
|
257
|
+
payment_provider: identity.payment_provider,
|
|
258
|
+
payment_target_ref: identity.payment_target_ref,
|
|
259
|
+
directory_slug: identity.directory_slug,
|
|
260
|
+
reason: signedReason,
|
|
252
261
|
reviewer_wallet: loaded.address,
|
|
253
262
|
review_signature: signature,
|
|
254
263
|
signature_scheme: "eip191"
|
|
@@ -256,24 +265,70 @@ async function prepareSignedReview(deps, args, wallet) {
|
|
|
256
265
|
signed: true,
|
|
257
266
|
wallet_source: loaded.source,
|
|
258
267
|
wallet_created: loaded.created,
|
|
259
|
-
wallet: loaded
|
|
268
|
+
wallet: loaded,
|
|
269
|
+
signed_payload: {
|
|
270
|
+
identity,
|
|
271
|
+
rating: args.rating,
|
|
272
|
+
reason: signedReason,
|
|
273
|
+
payment_reference: String(args.payment_reference ?? "")
|
|
274
|
+
}
|
|
260
275
|
};
|
|
261
276
|
}
|
|
277
|
+
var SIGNED_IDENTITY_FIELDS = [
|
|
278
|
+
"service_id",
|
|
279
|
+
"api_endpoint",
|
|
280
|
+
"payment_provider",
|
|
281
|
+
"payment_target_ref",
|
|
282
|
+
"directory_slug"
|
|
283
|
+
];
|
|
284
|
+
function resolvedIdentity(value) {
|
|
285
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
const record = value;
|
|
289
|
+
for (const field of SIGNED_IDENTITY_FIELDS) {
|
|
290
|
+
if (!(field in record)) return null;
|
|
291
|
+
if (record[field] !== null && typeof record[field] !== "string") return null;
|
|
292
|
+
}
|
|
293
|
+
try {
|
|
294
|
+
return buildIdentity(record);
|
|
295
|
+
} catch {
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function preservesSignedIdentity(signed, resolved) {
|
|
300
|
+
return SIGNED_IDENTITY_FIELDS.every(
|
|
301
|
+
(field) => signed[field] === null || signed[field] === resolved[field]
|
|
302
|
+
);
|
|
303
|
+
}
|
|
262
304
|
async function resignFromMismatch(prepared, response) {
|
|
263
305
|
if (!prepared.signed || !prepared.wallet?.account) return null;
|
|
306
|
+
if (!prepared.signed_payload) return null;
|
|
264
307
|
if (response.accepted !== false) return null;
|
|
265
308
|
if (typeof response.expected_message !== "string") return null;
|
|
266
|
-
const identity = response.resolved_identity
|
|
309
|
+
const identity = resolvedIdentity(response.resolved_identity);
|
|
310
|
+
if (identity === null) return null;
|
|
311
|
+
if (!preservesSignedIdentity(prepared.signed_payload.identity, identity)) {
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
const message = canonicalReviewPayload({
|
|
315
|
+
identity,
|
|
316
|
+
rating: prepared.signed_payload.rating,
|
|
317
|
+
reason: prepared.signed_payload.reason,
|
|
318
|
+
paymentReference: prepared.signed_payload.payment_reference
|
|
319
|
+
});
|
|
320
|
+
if (message !== response.expected_message) return null;
|
|
267
321
|
const signature = await prepared.wallet.account.signMessage({
|
|
268
|
-
message
|
|
322
|
+
message
|
|
269
323
|
});
|
|
270
324
|
return {
|
|
271
325
|
...prepared.args,
|
|
272
|
-
service_id: identity.service_id
|
|
273
|
-
api_endpoint: identity.api_endpoint
|
|
274
|
-
payment_provider: identity.payment_provider
|
|
275
|
-
payment_target_ref: identity.payment_target_ref
|
|
276
|
-
directory_slug: identity.directory_slug
|
|
326
|
+
service_id: identity.service_id,
|
|
327
|
+
api_endpoint: identity.api_endpoint,
|
|
328
|
+
payment_provider: identity.payment_provider,
|
|
329
|
+
payment_target_ref: identity.payment_target_ref,
|
|
330
|
+
directory_slug: identity.directory_slug,
|
|
331
|
+
reason: prepared.signed_payload.reason,
|
|
277
332
|
review_signature: signature
|
|
278
333
|
};
|
|
279
334
|
}
|
|
@@ -329,13 +384,13 @@ var UpstreamClient = class {
|
|
|
329
384
|
);
|
|
330
385
|
}
|
|
331
386
|
const structured = result.structuredContent;
|
|
332
|
-
if (structured !== void 0 &&
|
|
387
|
+
if (structured !== void 0 && isRecord2(structured)) {
|
|
333
388
|
return structured;
|
|
334
389
|
}
|
|
335
390
|
const text = firstText(result.content);
|
|
336
391
|
try {
|
|
337
392
|
const parsed = JSON.parse(text);
|
|
338
|
-
if (
|
|
393
|
+
if (isRecord2(parsed)) return parsed;
|
|
339
394
|
} catch {
|
|
340
395
|
}
|
|
341
396
|
throw new UpstreamError(
|
|
@@ -348,13 +403,13 @@ var UpstreamClient = class {
|
|
|
348
403
|
return tools.map((tool) => tool.name);
|
|
349
404
|
}
|
|
350
405
|
};
|
|
351
|
-
function
|
|
406
|
+
function isRecord2(value) {
|
|
352
407
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
353
408
|
}
|
|
354
409
|
function firstText(content) {
|
|
355
410
|
if (Array.isArray(content)) {
|
|
356
411
|
for (const item of content) {
|
|
357
|
-
if (
|
|
412
|
+
if (isRecord2(item) && item.type === "text" && typeof item.text === "string") {
|
|
358
413
|
return item.text;
|
|
359
414
|
}
|
|
360
415
|
}
|
|
@@ -571,7 +626,7 @@ var SERVER_INSTRUCTIONS = [
|
|
|
571
626
|
].join("\n");
|
|
572
627
|
function buildServer(deps) {
|
|
573
628
|
const server = new McpServer(
|
|
574
|
-
{ name: "crowdcode", version: "0.
|
|
629
|
+
{ name: "crowdcode", version: "0.4.0" },
|
|
575
630
|
{ instructions: SERVER_INSTRUCTIONS }
|
|
576
631
|
);
|
|
577
632
|
const handlers = createToolHandlers(deps);
|
|
@@ -638,4 +693,4 @@ export {
|
|
|
638
693
|
createToolHandlers,
|
|
639
694
|
startServer
|
|
640
695
|
};
|
|
641
|
-
//# sourceMappingURL=server-
|
|
696
|
+
//# sourceMappingURL=server-WNVGTJQI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/signing-payload.ts","../src/tools/sign-review.ts","../src/upstream.ts"],"sourcesContent":["/**\n * The stdio MCP server. Advertises the same tools as the CrowdCode backend;\n * free-text arguments are redacted locally (Rampart + secret recognizers)\n * before forwarding over streamable-HTTP, and get_review_signing_payload is\n * served entirely locally so raw review text never leaves this machine at\n * signing time.\n */\n\nimport { RedactionEngine } from \"@crowdcode/redaction\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { toToolResult, withRedactionAttestation } from \"./attestation.js\";\nimport { getConfig } from \"./config.js\";\nimport { redactArgs } from \"./redaction/policy.js\";\nimport {\n MIRRORED_REMOTE_TOOLS,\n getServiceScoreShape,\n requestServiceShape,\n reviewServiceShape,\n signingPayloadShape,\n} from \"./schemas.js\";\nimport {\n prepareSignedReview,\n resignFromMismatch,\n installWalletNextStep,\n type PreparedReview,\n type WalletOptions,\n} from \"./tools/sign-review.js\";\nimport {\n getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, UpstreamError, type Upstream } from \"./upstream.js\";\nimport { loadWallet } from \"./wallet.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n err: unknown,\n): Record<string, unknown> {\n const message =\n err instanceof UpstreamError\n ? err.message\n : `could not reach the CrowdCode backend: ${(err as Error).message}`;\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend may be cold-starting (free-tier hosting); retry \" +\n \"the same call in ~30 seconds.\",\n command: null,\n link: null,\n retry: { tool, after_seconds: 30, with: {} },\n };\n if (tool === \"get_service_score\") {\n return {\n found: false,\n score: null,\n n_eff: 0,\n unproven: true,\n avg_rating: null,\n num_reviews: 0,\n summary: null,\n recent_reviews: [],\n reason: message,\n next_step,\n };\n }\n return { accepted: false, reason: message, next_step };\n}\n\nfunction withWalletInfo(\n payload: Record<string, unknown>,\n prepared: PreparedReview,\n): Record<string, unknown> {\n const out = { ...payload };\n if (prepared.wallet_source !== undefined) {\n out.wallet_source = prepared.wallet_source;\n }\n if (prepared.wallet_created) out.wallet_created = true;\n if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;\n if (out.next_step === undefined && prepared.next_step) {\n out.next_step = prepared.next_step;\n }\n return out;\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n const config = getConfig();\n const walletOptions: WalletOptions = {\n walletDir: deps.wallet?.walletDir ?? config.walletDir,\n autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,\n env: deps.wallet?.env,\n };\n const signingDeps = { redact: (text: string) => engine.redact(text), upstream };\n // Show the install-wallet onboarding CTA at most once per process so score\n // lookups don't nag (agentcash pattern: CTA on success, never stacked).\n let onboardingCtaShown = false;\n\n async function forwardPayload(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const redacted = await redactArgs(engine, tool, args);\n try {\n const result = await upstream.call(tool, redacted.args);\n return withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n });\n } catch (err) {\n return errorPayload(tool, err);\n }\n }\n\n return {\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let outgoing = args;\n if (!outgoing.requester_wallet) {\n // Read-only probe: requests never mint a wallet; the review flow does.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.address) {\n outgoing = { ...outgoing, requester_wallet: wallet.address };\n }\n }\n return toToolResult(await forwardPayload(\"request_service\", outgoing));\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let payload: Record<string, unknown>;\n try {\n payload = await upstream.call(\"get_service_score\", args);\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n const provider = payload.payment_provider;\n if (\n !onboardingCtaShown &&\n payload.found === true &&\n (provider === \"mppx\" || provider === \"x402\")\n ) {\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.source === \"none\") {\n onboardingCtaShown = true;\n payload = {\n ...payload,\n onboarding_cta: {\n message:\n \"This is a paid x402/mppx service and you have no local \" +\n \"signing wallet yet. Install agentcash (or set \" +\n \"X402_PRIVATE_KEY) so your post-purchase review can be \" +\n \"signed and counted.\",\n command: installWalletNextStep(\"review_service\").command,\n },\n };\n }\n }\n return toToolResult(payload);\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = await loadWallet(walletOptions);\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n return toToolResult(withWalletInfo(payload, prepared));\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"\",\n \"Before spending: call get_service_score on each candidate (prefer\",\n \"api_endpoint + payment_provider + payment_target_ref, or service_id /\",\n \"directory_slug). Prefer higher `score` (the canonical trust-weighted\",\n \"rating), using `n_eff` as evidence context; `unproven: true` means not\",\n \"enough trusted reviews yet — treat it as insufficient evidence, not a bad\",\n \"score, and fall back to price and the spend policy. When present,\",\n \"`summary` digests what reviewers reported (strengths / failure modes /\",\n \"caveats).\",\n \"\",\n \"After ANY paid use — success, slow response, or failure: submit a review.\",\n \"A slow or broken paid call is not a reason to skip the review; it IS the\",\n \"review (slowness or breakage goes in the rating and reason). Rate against\",\n \"the ORIGINAL task you were solving: was the response relevant and did it\",\n \"actually help answer that question? Fixed scale: 5 = excellent (clear\",\n \"schema, relevant output that answered the original question, fast, clean\",\n \"receipt — would reuse confidently); 4 = helped but a real\",\n \"schema/docs/latency/output caveat; 3 = paid but response thin, confusing,\",\n \"needed guesswork, or not actually relevant/helpful for the task (a\",\n \"technically valid answer that did not help is a 3 at best); 2 = paid but\",\n \"poor (client error, unclear failure, hard to use); 1 = paid and broken\",\n \"(server error, unusable output, misleading challenge, timeout/severe\",\n \"reliability). A service that simply worked well AND helped is a 5 — do\",\n \"not hedge to 4 without a concrete caveat.\",\n \"\",\n \"Signing is AUTOMATIC: review_service signs with your local wallet\",\n \"(X402_PRIVATE_KEY, or the agentcash wallet at ~/.agentcash/wallet.json,\",\n \"auto-created if missing) — you do not need get_review_signing_payload or\",\n \"an external signer. Responses include wallet_source (env | agentcash |\",\n \"none). For x402/mppx, take identity and proofs from the ACTUAL payment,\",\n \"not a directory listing: payment_reference = the settlement tx hash (x402)\",\n \"or Payment-Receipt reference (mppx); payment_proof = the base64 response\",\n \"header string (payment-response for x402, Payment-Receipt for mppx), not\",\n \"the tx hash or decoded JSON. payment_proof is OPTIONAL: verified-purchase\",\n \"status (double scoring weight) comes from CrowdCode verifying the ERC-20\",\n \"transfer on-chain, which works from the settlement tx hash in\",\n \"payment_reference alone — so clients that only have a tx hash (e.g.\",\n \"agentcash) get the same verified status as clients that pass the proof\",\n \"header. payment_verification_level in the response is the source of\",\n \"truth. On-chain verification covers x402 on Base and mppx on Tempo;\",\n \"payments settled elsewhere (e.g. Solana) are accepted but stay\",\n \"signature_only. payment_target_ref = the real on-chain payee (the 402\",\n \"challenge recipient / Transfer `to`), not a directory payTo.\",\n \"\",\n \"Workflow: 1) get_service_score on each candidate; 2) pay and use the\",\n \"service; 3) review_service with the settlement tx hash as\",\n \"payment_reference (plus the payment_proof header if you have it). Reviews\",\n \"are limited to 1 per service per wallet per 24h; failed calls return a\",\n \"next_step object with the exact command or retry that fixes them —\",\n \"follow it.\",\n \"\",\n \"When you were actively trying to BUY a capability and no fitting paid\",\n \"service exists, call request_service once (requires a wallet identity,\",\n \"attached automatically; limited to 5 requests per wallet per 24h). The\",\n \"gate is willingness to pay: you had the task, a wallet, and spend\",\n \"authority, and would have paid concrete money for this right then if it\",\n \"existed. 'A provider could charge for this' is not enough — a free tool\",\n \"that would merely have been convenient is not a service request. Describe\",\n \"the paid API call you wanted to make: the input you would have sent, the\",\n \"output or state change you were paying for, and roughly what a call was\",\n \"worth to the task. Never free-tool wishes, runtime or agent-harness\",\n \"wishes (context management, local compute), or one-off task help. Never\",\n \"send secrets or private data — free-text fields are redacted locally\",\n \"before anything is sent.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.3.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record unmet paid-service demand for future directory coverage. \" +\n \"Call this only when you were actively trying to BUY a capability — \" +\n \"you had the task, a wallet, and spend authority, and would have \" +\n \"paid concrete money right then if the service existed — and no \" +\n \"fitting paid service (x402/mppx/Stripe) could be found. 'A provider \" +\n \"could charge for this' is not enough; if you would only use it for \" +\n \"free, do not request it. Describe the paid API call you wanted to \" +\n \"make: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task, \" +\n \"phrased generally enough to serve multiple users. Good: 'resolve a \" +\n \"citation like Smith et al. 2019 to the actual paper, or report \" +\n \"that it does not exist — worth ~$0.10 per lookup'; 'semantic \" +\n \"search over paywalled full-text academic PDFs returning page-level \" +\n \"citations — worth ~$0.25 per query'. Bad: free tools that would \" +\n \"merely have been convenient, wishes about your own runtime or \" +\n \"harness ('cleaner context', 'more memory', local compute/IDE \" +\n \"features), and one-off task help ('fix my CI'). Requires a wallet \" +\n \"identity (attached automatically from your \" +\n \"local agentcash/X402_PRIVATE_KEY wallet); limited to 5 requests per \" +\n \"wallet per 24h. Free-text fields are redacted locally (PII and \" +\n \"secrets become [PLACEHOLDER]s) before anything is sent to the shared \" +\n \"CrowdCode backend.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the canonical trust-weighted score (`score`, with `n_eff` \" +\n \"evidence and an `unproven` flag), an AI review summary when \" +\n \"available, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Submit a review after paying for a service — call this after EVERY \" +\n \"paid x402/mppx use, including slow responses and failures. A bad \" +\n \"outcome is not a reason to skip the review; it IS the review: rate \" +\n \"1-2 with the failure in the reason. Rate against the ORIGINAL task \" +\n \"you were solving: was the response relevant and did it actually \" +\n \"help answer that question? Rating scale: 5 = excellent (clear \" +\n \"schema, relevant output that answered the original question, fast, \" +\n \"clean receipt — would reuse confidently); 4 = helped but a real \" +\n \"schema/docs/latency/output caveat; 3 = paid but \" +\n \"thin/confusing/needed guesswork or not actually relevant/helpful \" +\n \"for the task (a technically valid answer that did not help is a 3 \" +\n \"at best); 2 = paid but poor (client error, unclear failure, hard \" +\n \"to use); 1 = paid and broken (server error, unusable output, \" +\n \"misleading challenge, timeout). A service that simply worked well \" +\n \"AND helped is a 5 — do not hedge to 4 without a concrete caveat. \" +\n \"SIGNING IS AUTOMATIC: this tool signs with your local \" +\n \"agentcash/X402_PRIVATE_KEY wallet (auto-created if missing) — do not \" +\n \"call get_review_signing_payload or sign externally. Get identity and \" +\n \"proofs from the ACTUAL payment, not a directory listing: \" +\n \"payment_reference = the settlement tx hash (x402) or Payment-Receipt \" +\n \"`reference` (mppx); \" +\n \"payment_proof = the base64 response header STRING — `payment-response` \" +\n \"for x402, `Payment-Receipt` for mppx — NOT the tx hash and NOT decoded \" +\n \"JSON. payment_proof is OPTIONAL: verified-purchase status (double \" +\n \"scoring weight) comes from on-chain transfer verification, which works \" +\n \"from the settlement tx hash in payment_reference alone — pass the \" +\n \"proof header too when you have it. payment_verification_level in the \" +\n \"response is the source of truth; \" +\n \"payment_target_ref = the real payee (the 402 challenge recipient / \" +\n \"on-chain Transfer `to`), not a bazaar/directory payTo. If you paid \" +\n \"from a different wallet than the local one, pass reviewer_wallet and \" +\n \"review_signature yourself (the wallet that SENT the payment — the \" +\n \"ERC-20 Transfer `from`, not the gasless facilitator). Limited to 1 \" +\n \"review per service per wallet per 24h. Free-text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n void warnOnToolDrift(upstream);\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n} {\n return { content: [{ type: \"text\", text: JSON.stringify(payload) }] };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n request_service: [\"service_description\", \"task_context\"],\n review_service: [\"reason\", \"task_context\"],\n};\n\nexport interface RedactedArgs {\n args: Record<string, unknown>;\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\nexport async function redactArgs(\n engine: RedactionEngine,\n tool: string,\n args: Record<string, unknown>,\n): Promise<RedactedArgs> {\n const fields = REDACTION_POLICY[tool] ?? [];\n const out = { ...args };\n let entitiesRemoved = 0;\n let modelActive = engine.modelActive;\n for (const field of fields) {\n const value = out[field];\n if (typeof value !== \"string\" || value === \"\") continue;\n const result = await engine.redact(value);\n out[field] = result.text;\n entitiesRemoved += result.entitiesRemoved;\n modelActive = result.modelActive;\n }\n return { args: out, entitiesRemoved, modelActive };\n}\n","/**\n * Static mirror of the backend tool signatures (src/crowdcode/server.py).\n * A static mirror — not dynamic passthrough — because get_review_signing_payload\n * is overridden locally and the redaction policy is keyed to known parameter\n * names; upstream drift should fail loudly, not silently forward unredacted\n * fields. Names/optionality must match the Python signatures exactly.\n */\n\nimport { z } from \"zod\";\n\nexport const identityShape = {\n service_id: z.string().nullish().describe(\"Canonical service id (svc_...)\"),\n api_endpoint: z.string().nullish().describe(\"Service API endpoint URL\"),\n payment_provider: z\n .string()\n .nullish()\n .describe(\"One of: stripe, stripe_payment_link, mppx, x402, manual\"),\n payment_target_ref: z\n .string()\n .nullish()\n .describe(\"Payment recipient reference (wallet address, account id, ...)\"),\n directory_slug: z.string().nullish().describe(\"Directory slug if known\"),\n};\n\nconst RATING_DESCRIPTION =\n \"Rating 1-5. Judge the output against the ORIGINAL task you were solving \" +\n \"(the task_context): was the response relevant and did it actually help \" +\n \"answer that question? 5 = excellent: clear schema, relevant output that \" +\n \"answered the original question, fast, clean receipt/proof — you would \" +\n \"reuse it confidently. 4 = works and helped with the task, but with a real \" +\n \"schema/docs/latency/output caveat (name it in the reason). 3 = mixed: \" +\n \"paid successfully but the response was thin, confusing, needed guesswork, \" +\n \"or was not actually relevant or helpful for the task — a technically \" +\n \"valid answer that did not help is a 3 at best. 2 = paid but poor: client \" +\n \"error, unclear failure, or hard to use. 1 = paid and broken: server \" +\n \"error, unusable output, misleading challenge, or severe reliability \" +\n \"problem (e.g. timeout). A service that simply worked well AND helped is \" +\n \"a 5 — do not hedge to 4 without a concrete caveat.\";\n\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"The paid API call you wanted to make but could not find a provider \" +\n \"for: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task \" +\n \"(e.g. 'would have paid ~$0.10 per lookup'). Must be something you \" +\n \"would have spent concrete money on right then — not a free tool \" +\n \"that would merely have been convenient. Keep it reusable across \" +\n \"users. Do NOT request local runtime/agent-harness wishes (context \" +\n \"management, local compute, IDE features) or one-off task help. Do \" +\n \"not include secrets, credentials, or private user data — free text \" +\n \"is additionally redacted locally before it leaves this machine.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Optional: what you were trying to accomplish when you hit the gap, \" +\n \"and the spend intent — that you searched for a paid service, found \" +\n \"none, and what you were prepared to pay.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash/X402_PRIVATE_KEY wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().describe(\"Payment reference for this review\"),\n ...identityShape,\n auto_sign: z\n .boolean()\n .nullish()\n .describe(\n \"When true, also sign the message with the local wallet and return \" +\n \"review_signature + reviewer_wallet. Usually unnecessary: \" +\n \"review_service signs automatically.\",\n ),\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().describe(\"Unique payment reference\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z\n .string()\n .nullish()\n .describe(\n \"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 — without either, the review is stored \" +\n \"as UNVERIFIED and carries half weight in scoring.\",\n ),\n payment_challenge: z.string().nullish(),\n reviewer_wallet: z\n .string()\n .nullish()\n .describe(\"Optional; auto-filled from your local wallet when signing locally\"),\n review_signature: z\n .string()\n .nullish()\n .describe(\n \"Optional; crowdcode-mcp signs automatically with your local \" +\n \"agentcash/X402_PRIVATE_KEY wallet. A supplied signature always wins.\",\n ),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n] as const;\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The identity-merge logic mirrors the backend exactly\n * (src/crowdcode/server.py review_service effective_identity): the server\n * verifies signatures by REBUILDING the payload from its own resolved\n * identity, so the message signed here must match that reconstruction\n * byte-for-byte. Canonical identity comes from get_service_score when the\n * service exists; otherwise the caller-provided identity is used verbatim,\n * exactly like the old remote signing tool.\n */\n\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference: string;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n // Same merge as the backend: caller-normalized fields win, canonical\n // values fill the gaps, and the result is re-normalized.\n effective = buildIdentity({\n service_id: orNull(score.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: identity.api_endpoint ?? orNull(score.canonical_endpoint),\n payment_provider:\n identity.payment_provider ?? orNull(score.payment_provider),\n payment_target_ref:\n identity.payment_target_ref ?? orNull(score.payment_target_ref),\n directory_slug: identity.directory_slug ?? orNull(score.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference.\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","/**\n * Transparent in-process signing for review_service.\n *\n * For mppx/x402 reviews where the caller did not supply review_signature,\n * this builds the canonical message (identity-merge + local redaction via\n * getReviewSigningPayload), signs it with the local agentcash wallet (or\n * X402_PRIVATE_KEY), and augments the outgoing arguments — so an agent can\n * call review_service end-to-end with no external signing step. A\n * caller-supplied signature always wins.\n *\n * The signature covers the REDACTED reason; the redaction engine memoizes,\n * so the later per-forward redaction pass produces the byte-identical string\n * the backend hashes when rebuilding the payload.\n */\n\nimport { normalizePaymentProvider } from \"../canonical/identity.js\";\nimport {\n loadWallet,\n type LoadedWallet,\n type WalletSource,\n} from \"../wallet.js\";\nimport { getReviewSigningPayload, type SigningDeps } from \"./signing-payload.js\";\n\nexport const AGENTCASH_INSTALL_COMMAND =\n \"claude mcp add --scope user agentcash -- npx -y agentcash@latest\";\n\nexport interface NextStep {\n action: string;\n summary: string;\n command: string | null;\n link: string | null;\n retry: { tool: string; after_seconds: number | null; with: Record<string, unknown> } | null;\n}\n\nexport function installWalletNextStep(retryTool: string): NextStep {\n return {\n action: \"install_wallet\",\n summary:\n \"No local signing wallet found. Install agentcash (or set \" +\n \"X402_PRIVATE_KEY) so crowdcode-mcp can sign automatically, then retry \" +\n retryTool +\n \".\",\n command: AGENTCASH_INSTALL_COMMAND,\n link: null,\n retry: { tool: retryTool, after_seconds: null, with: {} },\n };\n}\n\nexport interface WalletOptions {\n walletDir?: string;\n autoCreate: boolean;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface PreparedReview {\n args: Record<string, unknown>;\n /** Set when local signing was attempted (mppx/x402, no caller signature). */\n wallet_source?: WalletSource;\n wallet_created?: boolean;\n wallet_error?: string;\n next_step?: NextStep;\n /** Wallet used for signing — kept so a signature-mismatch retry can re-sign. */\n wallet?: LoadedWallet;\n signed: boolean;\n}\n\nfunction isMachineProvider(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n try {\n const provider = normalizePaymentProvider(value);\n return provider === \"mppx\" || provider === \"x402\";\n } catch {\n // Unknown provider: forward as-is and let the backend produce its error.\n return false;\n }\n}\n\nexport async function prepareSignedReview(\n deps: SigningDeps,\n args: Record<string, unknown>,\n wallet: WalletOptions,\n): Promise<PreparedReview> {\n if (!isMachineProvider(args.payment_provider) || args.review_signature) {\n return { args, signed: false };\n }\n\n const loaded = await loadWallet({\n walletDir: wallet.walletDir,\n autoCreate: wallet.autoCreate,\n env: wallet.env,\n });\n if (loaded.source === \"none\" || loaded.account === null) {\n return {\n args,\n signed: false,\n wallet_source: \"none\",\n wallet_error: loaded.error,\n next_step: installWalletNextStep(\"review_service\"),\n };\n }\n\n const payload = await getReviewSigningPayload(deps, {\n rating: args.rating as number,\n reason: String(args.reason ?? \"\"),\n payment_reference: String(args.payment_reference ?? \"\"),\n service_id: args.service_id as string | null | undefined,\n api_endpoint: args.api_endpoint as string | null | undefined,\n payment_provider: args.payment_provider as string | null | undefined,\n payment_target_ref: args.payment_target_ref as string | null | undefined,\n directory_slug: args.directory_slug as string | null | undefined,\n });\n if (payload.ok !== true || typeof payload.message !== \"string\") {\n // Forward unsigned; the backend rejection (plus its next_step) is more\n // actionable than failing locally with a half-built payload.\n return {\n args,\n signed: false,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet_error: `could not build the signing payload locally: ${String(\n payload.reason ?? \"unknown error\",\n )}`,\n };\n }\n\n const signature = await loaded.account.signMessage({\n message: payload.message,\n });\n const identity = payload.identity as Record<string, unknown>;\n return {\n args: {\n ...args,\n // Pass the resolved identity verbatim so the backend rebuilds the exact\n // payload that was just signed.\n service_id: identity.service_id ?? args.service_id,\n api_endpoint: identity.api_endpoint ?? args.api_endpoint,\n payment_provider: identity.payment_provider ?? args.payment_provider,\n payment_target_ref: identity.payment_target_ref ?? args.payment_target_ref,\n directory_slug: identity.directory_slug ?? args.directory_slug,\n reviewer_wallet: loaded.address,\n review_signature: signature,\n signature_scheme: \"eip191\",\n },\n signed: true,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet: loaded,\n };\n}\n\n/**\n * Handle the backend's signature-mismatch recovery contract: re-sign the\n * returned expected_message with the same wallet and rebuild the args using\n * resolved_identity. Returns null when the response is not a recoverable\n * mismatch (or we did not sign locally in the first place).\n */\nexport async function resignFromMismatch(\n prepared: PreparedReview,\n response: Record<string, unknown>,\n): Promise<Record<string, unknown> | null> {\n if (!prepared.signed || !prepared.wallet?.account) return null;\n if (response.accepted !== false) return null;\n if (typeof response.expected_message !== \"string\") return null;\n\n const identity = (response.resolved_identity ?? {}) as Record<string, unknown>;\n const signature = await prepared.wallet.account.signMessage({\n message: response.expected_message,\n });\n return {\n ...prepared.args,\n service_id: identity.service_id ?? prepared.args.service_id,\n api_endpoint: identity.api_endpoint ?? prepared.args.api_endpoint,\n payment_provider: identity.payment_provider ?? prepared.args.payment_provider,\n payment_target_ref:\n identity.payment_target_ref ?? prepared.args.payment_target_ref,\n directory_slug: identity.directory_slug ?? prepared.args.directory_slug,\n review_signature: signature,\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACH9B,SAAS,yBACd,SACA,MACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY;AAAA,MACV,kBAAkB,KAAK;AAAA,MACvB,cAAc,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aAAa,SAE3B;AACA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,EAAE,CAAC,EAAE;AACtE;;;ACXO,IAAM,mBAAsD;AAAA,EACjE,iBAAiB,CAAC,uBAAuB,cAAc;AAAA,EACvD,gBAAgB,CAAC,UAAU,cAAc;AAC3C;AAQA,eAAsB,WACpB,QACA,MACA,MACuB;AACvB,QAAM,SAAS,iBAAiB,IAAI,KAAK,CAAC;AAC1C,QAAM,MAAM,EAAE,GAAG,KAAK;AACtB,MAAI,kBAAkB;AACtB,MAAI,cAAc,OAAO;AACzB,aAAW,SAAS,QAAQ;AAC1B,UAAM,QAAQ,IAAI,KAAK;AACvB,QAAI,OAAO,UAAU,YAAY,UAAU,GAAI;AAC/C,UAAM,SAAS,MAAM,OAAO,OAAO,KAAK;AACxC,QAAI,KAAK,IAAI,OAAO;AACpB,uBAAmB,OAAO;AAC1B,kBAAc,OAAO;AAAA,EACvB;AACA,SAAO,EAAE,MAAM,KAAK,iBAAiB,YAAY;AACnD;;;AClCA,SAAS,SAAS;AAEX,IAAM,gBAAgB;AAAA,EAC3B,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,gCAAgC;AAAA,EAC1E,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,0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":["../src/server.ts","../src/attestation.ts","../src/redaction/policy.ts","../src/schemas.ts","../src/tools/signing-payload.ts","../src/tools/sign-review.ts","../src/upstream.ts"],"sourcesContent":["/**\n * The stdio MCP server. Advertises the same tools as the CrowdCode backend;\n * free-text arguments are redacted locally (Rampart + secret recognizers)\n * before forwarding over streamable-HTTP, and get_review_signing_payload is\n * served entirely locally so raw review text never leaves this machine at\n * signing time.\n */\n\nimport { RedactionEngine } from \"@crowdcode/redaction\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { toToolResult, withRedactionAttestation } from \"./attestation.js\";\nimport { getConfig } from \"./config.js\";\nimport { redactArgs } from \"./redaction/policy.js\";\nimport {\n MIRRORED_REMOTE_TOOLS,\n getServiceScoreShape,\n requestServiceShape,\n reviewServiceShape,\n signingPayloadShape,\n} from \"./schemas.js\";\nimport {\n prepareSignedReview,\n resignFromMismatch,\n installWalletNextStep,\n type PreparedReview,\n type WalletOptions,\n} from \"./tools/sign-review.js\";\nimport {\n getReviewSigningPayload,\n type SigningPayloadArgs,\n} from \"./tools/signing-payload.js\";\nimport { UpstreamClient, UpstreamError, type Upstream } from \"./upstream.js\";\nimport { loadWallet } from \"./wallet.js\";\n\nexport interface ServerDeps {\n engine: RedactionEngine;\n upstream: Upstream;\n /** Wallet loading knobs; defaults come from getConfig(). Injectable in tests. */\n wallet?: Partial<WalletOptions>;\n}\n\ntype ToolResult = ReturnType<typeof toToolResult>;\n\nfunction errorPayload(\n tool: string,\n err: unknown,\n): Record<string, unknown> {\n const message =\n err instanceof UpstreamError\n ? err.message\n : `could not reach the CrowdCode backend: ${(err as Error).message}`;\n const next_step = {\n action: \"retry_backend\",\n summary:\n \"The CrowdCode backend may be cold-starting (free-tier hosting); retry \" +\n \"the same call in ~30 seconds.\",\n command: null,\n link: null,\n retry: { tool, after_seconds: 30, with: {} },\n };\n if (tool === \"get_service_score\") {\n return {\n found: false,\n score: null,\n n_eff: 0,\n unproven: true,\n avg_rating: null,\n num_reviews: 0,\n summary: null,\n recent_reviews: [],\n reason: message,\n next_step,\n };\n }\n return { accepted: false, reason: message, next_step };\n}\n\nfunction withWalletInfo(\n payload: Record<string, unknown>,\n prepared: PreparedReview,\n): Record<string, unknown> {\n const out = { ...payload };\n if (prepared.wallet_source !== undefined) {\n out.wallet_source = prepared.wallet_source;\n }\n if (prepared.wallet_created) out.wallet_created = true;\n if (prepared.wallet_error) out.wallet_error = prepared.wallet_error;\n if (out.next_step === undefined && prepared.next_step) {\n out.next_step = prepared.next_step;\n }\n return out;\n}\n\nexport function createToolHandlers(deps: ServerDeps) {\n const { engine, upstream } = deps;\n const config = getConfig();\n const walletOptions: WalletOptions = {\n walletDir: deps.wallet?.walletDir ?? config.walletDir,\n autoCreate: deps.wallet?.autoCreate ?? config.walletAutoCreate,\n env: deps.wallet?.env,\n };\n const signingDeps = { redact: (text: string) => engine.redact(text), upstream };\n // Show the install-wallet onboarding CTA at most once per process so score\n // lookups don't nag (agentcash pattern: CTA on success, never stacked).\n let onboardingCtaShown = false;\n\n async function forwardPayload(\n tool: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const redacted = await redactArgs(engine, tool, args);\n try {\n const result = await upstream.call(tool, redacted.args);\n return withRedactionAttestation(result, {\n entitiesRemoved: redacted.entitiesRemoved,\n modelActive: redacted.modelActive,\n });\n } catch (err) {\n return errorPayload(tool, err);\n }\n }\n\n return {\n request_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let outgoing = args;\n if (!outgoing.requester_wallet) {\n // Read-only probe: requests never mint a wallet; the review flow does.\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.address) {\n outgoing = { ...outgoing, requester_wallet: wallet.address };\n }\n }\n return toToolResult(await forwardPayload(\"request_service\", outgoing));\n },\n\n get_service_score: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n let payload: Record<string, unknown>;\n try {\n payload = await upstream.call(\"get_service_score\", args);\n } catch (err) {\n return toToolResult(errorPayload(\"get_service_score\", err));\n }\n const provider = payload.payment_provider;\n if (\n !onboardingCtaShown &&\n payload.found === true &&\n (provider === \"mppx\" || provider === \"x402\")\n ) {\n const wallet = await loadWallet({\n walletDir: walletOptions.walletDir,\n env: walletOptions.env,\n autoCreate: false,\n });\n if (wallet.source === \"none\") {\n onboardingCtaShown = true;\n payload = {\n ...payload,\n onboarding_cta: {\n message:\n \"This is a paid x402/mppx service and you have no local \" +\n \"signing wallet yet. Install agentcash (or set \" +\n \"X402_PRIVATE_KEY) so your post-purchase review can be \" +\n \"signed and counted.\",\n command: installWalletNextStep(\"review_service\").command,\n },\n };\n }\n }\n return toToolResult(payload);\n },\n\n get_review_signing_payload: async (\n args: SigningPayloadArgs & { auto_sign?: boolean | null },\n ): Promise<ToolResult> => {\n const payload = await getReviewSigningPayload(signingDeps, args);\n if (args.auto_sign !== true || payload.ok !== true) {\n return toToolResult(payload);\n }\n const wallet = await loadWallet(walletOptions);\n if (wallet.source === \"none\" || wallet.account === null) {\n return toToolResult({\n ...payload,\n wallet_source: \"none\",\n wallet_error: wallet.error,\n next_step: installWalletNextStep(\"review_service\"),\n });\n }\n const signature = await wallet.account.signMessage({\n message: payload.message as string,\n });\n return toToolResult({\n ...payload,\n review_signature: signature,\n reviewer_wallet: wallet.address,\n wallet_source: wallet.source,\n ...(wallet.created ? { wallet_created: true } : {}),\n });\n },\n\n review_service: async (\n args: Record<string, unknown>,\n ): Promise<ToolResult> => {\n const prepared = await prepareSignedReview(signingDeps, args, walletOptions);\n let payload = await forwardPayload(\"review_service\", prepared.args);\n // Signature-mismatch recovery (identity resolution race): re-sign the\n // backend's expected_message once with the same wallet and retry. A\n // second mismatch is surfaced to the caller.\n const retryArgs = await resignFromMismatch(prepared, payload);\n if (retryArgs !== null) {\n payload = await forwardPayload(\"review_service\", retryArgs);\n }\n return toToolResult(withWalletInfo(payload, prepared));\n },\n };\n}\n\nconst SERVER_INSTRUCTIONS = [\n \"CrowdCode is a shared reputation layer for paid agent services. Use it\",\n \"whenever a task involves paying for, provisioning, or calling a paid\",\n \"service — especially x402 or mppx/MPP services.\",\n \"\",\n \"Before spending: call get_service_score on each candidate (prefer\",\n \"api_endpoint + payment_provider + payment_target_ref, or service_id /\",\n \"directory_slug). Prefer higher `score` (the canonical trust-weighted\",\n \"rating), using `n_eff` as evidence context; `unproven: true` means not\",\n \"enough trusted reviews yet — treat it as insufficient evidence, not a bad\",\n \"score, and fall back to price and the spend policy. When present,\",\n \"`summary` digests what reviewers reported (strengths / failure modes /\",\n \"caveats).\",\n \"\",\n \"After ANY paid use — success, slow response, or failure: submit a review.\",\n \"A slow or broken paid call is not a reason to skip the review; it IS the\",\n \"review (slowness or breakage goes in the rating and reason). Rate against\",\n \"the ORIGINAL task you were solving: was the response relevant and did it\",\n \"actually help answer that question? Fixed scale: 5 = excellent (clear\",\n \"schema, relevant output that answered the original question, fast, clean\",\n \"receipt — would reuse confidently); 4 = helped but a real\",\n \"schema/docs/latency/output caveat; 3 = paid but response thin, confusing,\",\n \"needed guesswork, or not actually relevant/helpful for the task (a\",\n \"technically valid answer that did not help is a 3 at best); 2 = paid but\",\n \"poor (client error, unclear failure, hard to use); 1 = paid and broken\",\n \"(server error, unusable output, misleading challenge, timeout/severe\",\n \"reliability). A service that simply worked well AND helped is a 5 — do\",\n \"not hedge to 4 without a concrete caveat.\",\n \"\",\n \"Signing is AUTOMATIC: review_service signs with your local wallet\",\n \"(X402_PRIVATE_KEY, or the agentcash wallet at ~/.agentcash/wallet.json,\",\n \"auto-created if missing) — you do not need get_review_signing_payload or\",\n \"an external signer. Responses include wallet_source (env | agentcash |\",\n \"none). For x402/mppx, take identity and proofs from the ACTUAL payment,\",\n \"not a directory listing: payment_reference = the settlement tx hash (x402)\",\n \"or Payment-Receipt reference (mppx); payment_proof = the base64 response\",\n \"header string (payment-response for x402, Payment-Receipt for mppx), not\",\n \"the tx hash or decoded JSON. payment_proof is OPTIONAL: verified-purchase\",\n \"status (double scoring weight) comes from CrowdCode verifying the ERC-20\",\n \"transfer on-chain, which works from the settlement tx hash in\",\n \"payment_reference alone — so clients that only have a tx hash (e.g.\",\n \"agentcash) get the same verified status as clients that pass the proof\",\n \"header. payment_verification_level in the response is the source of\",\n \"truth. On-chain verification covers x402 on Base and mppx on Tempo;\",\n \"payments settled elsewhere (e.g. Solana) are accepted but stay\",\n \"signature_only. payment_target_ref = the real on-chain payee (the 402\",\n \"challenge recipient / Transfer `to`), not a directory payTo.\",\n \"\",\n \"Workflow: 1) get_service_score on each candidate; 2) pay and use the\",\n \"service; 3) review_service with the settlement tx hash as\",\n \"payment_reference (plus the payment_proof header if you have it). Reviews\",\n \"are limited to 1 per service per wallet per 24h; failed calls return a\",\n \"next_step object with the exact command or retry that fixes them —\",\n \"follow it.\",\n \"\",\n \"When you were actively trying to BUY a capability and no fitting paid\",\n \"service exists, call request_service once (requires a wallet identity,\",\n \"attached automatically; limited to 5 requests per wallet per 24h). The\",\n \"gate is willingness to pay: you had the task, a wallet, and spend\",\n \"authority, and would have paid concrete money for this right then if it\",\n \"existed. 'A provider could charge for this' is not enough — a free tool\",\n \"that would merely have been convenient is not a service request. Describe\",\n \"the paid API call you wanted to make: the input you would have sent, the\",\n \"output or state change you were paying for, and roughly what a call was\",\n \"worth to the task. Never free-tool wishes, runtime or agent-harness\",\n \"wishes (context management, local compute), or one-off task help. Never\",\n \"send secrets or private data — free-text fields are redacted locally\",\n \"before anything is sent.\",\n].join(\"\\n\");\n\nexport function buildServer(deps: ServerDeps): McpServer {\n const server = new McpServer(\n { name: \"crowdcode\", version: \"0.4.0\" },\n { instructions: SERVER_INSTRUCTIONS },\n );\n const handlers = createToolHandlers(deps);\n\n server.registerTool(\n \"request_service\",\n {\n description:\n \"Record unmet paid-service demand for future directory coverage. \" +\n \"Call this only when you were actively trying to BUY a capability — \" +\n \"you had the task, a wallet, and spend authority, and would have \" +\n \"paid concrete money right then if the service existed — and no \" +\n \"fitting paid service (x402/mppx/Stripe) could be found. 'A provider \" +\n \"could charge for this' is not enough; if you would only use it for \" +\n \"free, do not request it. Describe the paid API call you wanted to \" +\n \"make: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task, \" +\n \"phrased generally enough to serve multiple users. Good: 'resolve a \" +\n \"citation like Smith et al. 2019 to the actual paper, or report \" +\n \"that it does not exist — worth ~$0.10 per lookup'; 'semantic \" +\n \"search over paywalled full-text academic PDFs returning page-level \" +\n \"citations — worth ~$0.25 per query'. Bad: free tools that would \" +\n \"merely have been convenient, wishes about your own runtime or \" +\n \"harness ('cleaner context', 'more memory', local compute/IDE \" +\n \"features), and one-off task help ('fix my CI'). Requires a wallet \" +\n \"identity (attached automatically from your \" +\n \"local agentcash/X402_PRIVATE_KEY wallet); limited to 5 requests per \" +\n \"wallet per 24h. Free-text fields are redacted locally (PII and \" +\n \"secrets become [PLACEHOLDER]s) before anything is sent to the shared \" +\n \"CrowdCode backend.\",\n inputSchema: requestServiceShape,\n },\n (args) => handlers.request_service(args),\n );\n\n server.registerTool(\n \"get_service_score\",\n {\n description:\n \"Return the canonical trust-weighted score (`score`, with `n_eff` \" +\n \"evidence and an `unproven` flag), an AI review summary when \" +\n \"available, plus raw rating stats and recent reviews for a service, \" +\n \"identified by service_id, api_endpoint, payment target, or \" +\n \"directory_slug. Check this before paying for, provisioning, or calling \" +\n \"any paid agent service — especially x402 and mppx/MPP services.\",\n inputSchema: getServiceScoreShape,\n },\n (args) => handlers.get_service_score(args),\n );\n\n server.registerTool(\n \"get_review_signing_payload\",\n {\n description:\n \"Build the exact EIP-191 message for an mppx/x402 review — usually \" +\n \"UNNECESSARY: review_service signs automatically with your local \" +\n \"wallet. Use this only for transparency/debugging or when signing \" +\n \"with an external wallet. Runs entirely locally: the review reason is \" +\n \"redacted on this machine and only its hash enters the payload. Pass \" +\n \"auto_sign=true to also sign with the local wallet and get \" +\n \"review_signature + reviewer_wallet back. If signing externally, sign \" +\n \"`message` VERBATIM (byte-for-byte) with the payer wallet, then call \" +\n \"review_service with the returned `reason` and `identity` fields \" +\n \"verbatim, in this same session.\",\n inputSchema: signingPayloadShape,\n },\n (args) => handlers.get_review_signing_payload(args as SigningPayloadArgs),\n );\n\n server.registerTool(\n \"review_service\",\n {\n description:\n \"Submit a review after paying for a service — call this after EVERY \" +\n \"paid x402/mppx use, including slow responses and failures. A bad \" +\n \"outcome is not a reason to skip the review; it IS the review: rate \" +\n \"1-2 with the failure in the reason. Rate against the ORIGINAL task \" +\n \"you were solving: was the response relevant and did it actually \" +\n \"help answer that question? Rating scale: 5 = excellent (clear \" +\n \"schema, relevant output that answered the original question, fast, \" +\n \"clean receipt — would reuse confidently); 4 = helped but a real \" +\n \"schema/docs/latency/output caveat; 3 = paid but \" +\n \"thin/confusing/needed guesswork or not actually relevant/helpful \" +\n \"for the task (a technically valid answer that did not help is a 3 \" +\n \"at best); 2 = paid but poor (client error, unclear failure, hard \" +\n \"to use); 1 = paid and broken (server error, unusable output, \" +\n \"misleading challenge, timeout). A service that simply worked well \" +\n \"AND helped is a 5 — do not hedge to 4 without a concrete caveat. \" +\n \"SIGNING IS AUTOMATIC: this tool signs with your local \" +\n \"agentcash/X402_PRIVATE_KEY wallet (auto-created if missing) — do not \" +\n \"call get_review_signing_payload or sign externally. Get identity and \" +\n \"proofs from the ACTUAL payment, not a directory listing: \" +\n \"payment_reference = the settlement tx hash (x402) or Payment-Receipt \" +\n \"`reference` (mppx); \" +\n \"payment_proof = the base64 response header STRING — `payment-response` \" +\n \"for x402, `Payment-Receipt` for mppx — NOT the tx hash and NOT decoded \" +\n \"JSON. payment_proof is OPTIONAL: verified-purchase status (double \" +\n \"scoring weight) comes from on-chain transfer verification, which works \" +\n \"from the settlement tx hash in payment_reference alone — pass the \" +\n \"proof header too when you have it. payment_verification_level in the \" +\n \"response is the source of truth; \" +\n \"payment_target_ref = the real payee (the 402 challenge recipient / \" +\n \"on-chain Transfer `to`), not a bazaar/directory payTo. If you paid \" +\n \"from a different wallet than the local one, pass reviewer_wallet and \" +\n \"review_signature yourself (the wallet that SENT the payment — the \" +\n \"ERC-20 Transfer `from`, not the gasless facilitator). Limited to 1 \" +\n \"review per service per wallet per 24h. Free-text is redacted locally.\",\n inputSchema: reviewServiceShape,\n },\n (args) => handlers.review_service(args),\n );\n\n return server;\n}\n\nasync function warnOnToolDrift(upstream: Upstream): Promise<void> {\n try {\n const remote = new Set(await upstream.listToolNames());\n const missing = MIRRORED_REMOTE_TOOLS.filter((name) => !remote.has(name));\n if (missing.length > 0) {\n process.stderr.write(\n `crowdcode-mcp: backend no longer advertises: ${missing.join(\", \")} — ` +\n \"update the crowdcode-mcp package.\\n\",\n );\n }\n } catch {\n // Backend unreachable at startup (cold start); tool calls will retry.\n }\n}\n\nexport async function startServer(): Promise<void> {\n const config = getConfig();\n const engine = await RedactionEngine.create({\n cacheDir: config.cacheDir,\n enableModel: !config.disableModel,\n });\n const upstream = new UpstreamClient(config.backendUrl, config.upstreamTimeoutMs);\n const server = buildServer({ engine, upstream });\n await server.connect(new StdioServerTransport());\n void warnOnToolDrift(upstream);\n}\n","export interface RedactionInfo {\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\n/** Attach the local-redaction attestation so agents (and users reading\n * transcripts) can see that redaction ran and at what coverage level. */\nexport function withRedactionAttestation(\n payload: Record<string, unknown>,\n info: RedactionInfo,\n): Record<string, unknown> {\n return {\n ...payload,\n _redaction: {\n entities_removed: info.entitiesRemoved,\n model_active: info.modelActive,\n },\n };\n}\n\nexport function toToolResult(payload: Record<string, unknown>): {\n content: Array<{ type: \"text\"; text: string }>;\n} {\n return { content: [{ type: \"text\", text: JSON.stringify(payload) }] };\n}\n","/**\n * Which tool arguments get redacted before leaving the machine.\n *\n * Only free-text fields are listed. Identity fields (api_endpoint,\n * payment_target_ref, directory_slug, service_id, service_name) and payment\n * material (payment_reference, payment_proof, reviewer_wallet,\n * review_signature) pass through untouched — redacting them would break\n * service resolution and payment verification, and they are minimized\n * server-side instead.\n */\n\nimport type { RedactionEngine } from \"@crowdcode/redaction\";\n\nexport const REDACTION_POLICY: Record<string, readonly string[]> = {\n request_service: [\"service_description\", \"task_context\"],\n review_service: [\"reason\", \"task_context\"],\n};\n\nexport interface RedactedArgs {\n args: Record<string, unknown>;\n entitiesRemoved: number;\n modelActive: boolean;\n}\n\nexport async function redactArgs(\n engine: RedactionEngine,\n tool: string,\n args: Record<string, unknown>,\n): Promise<RedactedArgs> {\n const fields = REDACTION_POLICY[tool] ?? [];\n const out = { ...args };\n let entitiesRemoved = 0;\n let modelActive = engine.modelActive;\n for (const field of fields) {\n const value = out[field];\n if (typeof value !== \"string\" || value === \"\") continue;\n const result = await engine.redact(value);\n out[field] = result.text;\n entitiesRemoved += result.entitiesRemoved;\n modelActive = result.modelActive;\n }\n return { args: out, entitiesRemoved, modelActive };\n}\n","/**\n * Static mirror of the backend tool signatures (src/crowdcode/server.py).\n * A static mirror — not dynamic passthrough — because get_review_signing_payload\n * is overridden locally and the redaction policy is keyed to known parameter\n * names; upstream drift should fail loudly, not silently forward unredacted\n * fields. Names/optionality must match the Python signatures exactly.\n */\n\nimport { z } from \"zod\";\n\nexport const identityShape = {\n service_id: z.string().nullish().describe(\"Canonical service id (svc_...)\"),\n api_endpoint: z.string().nullish().describe(\"Service API endpoint URL\"),\n payment_provider: z\n .string()\n .nullish()\n .describe(\"One of: stripe, stripe_payment_link, mppx, x402, manual\"),\n payment_target_ref: z\n .string()\n .nullish()\n .describe(\"Payment recipient reference (wallet address, account id, ...)\"),\n directory_slug: z.string().nullish().describe(\"Directory slug if known\"),\n};\n\nconst RATING_DESCRIPTION =\n \"Rating 1-5. Judge the output against the ORIGINAL task you were solving \" +\n \"(the task_context): was the response relevant and did it actually help \" +\n \"answer that question? 5 = excellent: clear schema, relevant output that \" +\n \"answered the original question, fast, clean receipt/proof — you would \" +\n \"reuse it confidently. 4 = works and helped with the task, but with a real \" +\n \"schema/docs/latency/output caveat (name it in the reason). 3 = mixed: \" +\n \"paid successfully but the response was thin, confusing, needed guesswork, \" +\n \"or was not actually relevant or helpful for the task — a technically \" +\n \"valid answer that did not help is a 3 at best. 2 = paid but poor: client \" +\n \"error, unclear failure, or hard to use. 1 = paid and broken: server \" +\n \"error, unusable output, misleading challenge, or severe reliability \" +\n \"problem (e.g. timeout). A service that simply worked well AND helped is \" +\n \"a 5 — do not hedge to 4 without a concrete caveat.\";\n\nexport const requestServiceShape = {\n service_description: z\n .string()\n .describe(\n \"The paid API call you wanted to make but could not find a provider \" +\n \"for: the input you would have sent, the output or state change you \" +\n \"were paying for, and roughly what a call was worth to the task \" +\n \"(e.g. 'would have paid ~$0.10 per lookup'). Must be something you \" +\n \"would have spent concrete money on right then — not a free tool \" +\n \"that would merely have been convenient. Keep it reusable across \" +\n \"users. Do NOT request local runtime/agent-harness wishes (context \" +\n \"management, local compute, IDE features) or one-off task help. Do \" +\n \"not include secrets, credentials, or private user data — free text \" +\n \"is additionally redacted locally before it leaves this machine.\",\n ),\n task_context: z\n .string()\n .nullish()\n .describe(\n \"Optional: what you were trying to accomplish when you hit the gap, \" +\n \"and the spend intent — that you searched for a paid service, found \" +\n \"none, and what you were prepared to pay.\",\n ),\n requester_wallet: z\n .string()\n .nullish()\n .describe(\n \"EVM 0x address identifying who is asking (rate-limit key). \" +\n \"Auto-filled from your local agentcash/X402_PRIVATE_KEY wallet — \" +\n \"only pass it to override.\",\n ),\n};\n\nexport const getServiceScoreShape = { ...identityShape };\n\nexport const signingPayloadShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before hashing)\"),\n payment_reference: z.string().describe(\"Payment reference for this review\"),\n ...identityShape,\n auto_sign: z\n .boolean()\n .nullish()\n .describe(\n \"When true, also sign the message with the local wallet and return \" +\n \"review_signature + reviewer_wallet. Usually unnecessary: \" +\n \"review_service signs automatically.\",\n ),\n};\n\nexport const reviewServiceShape = {\n rating: z.number().int().describe(RATING_DESCRIPTION),\n reason: z.string().describe(\"Review text (redacted locally before sending)\"),\n payment_reference: z.string().describe(\"Unique payment reference\"),\n service_id: identityShape.service_id,\n task_context: z.string().nullish(),\n service_name: z.string().nullish(),\n api_endpoint: identityShape.api_endpoint,\n payment_provider: identityShape.payment_provider,\n payment_target_ref: identityShape.payment_target_ref,\n directory_slug: identityShape.directory_slug,\n payment_proof: z\n .string()\n .nullish()\n .describe(\n \"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 — without either, the review is stored \" +\n \"as UNVERIFIED and carries half weight in scoring.\",\n ),\n payment_challenge: z.string().nullish(),\n reviewer_wallet: z\n .string()\n .nullish()\n .describe(\"Optional; auto-filled from your local wallet when signing locally\"),\n review_signature: z\n .string()\n .nullish()\n .describe(\n \"Optional; crowdcode-mcp signs automatically with your local \" +\n \"agentcash/X402_PRIVATE_KEY wallet. A supplied signature always wins.\",\n ),\n signature_scheme: z.string().default(\"eip191\"),\n};\n\nexport const MIRRORED_REMOTE_TOOLS = [\n \"request_service\",\n \"get_service_score\",\n \"review_service\",\n] as const;\n","/**\n * Local implementation of get_review_signing_payload.\n *\n * This replaces the remote tool so raw review text is never sent at signing\n * time: the reason is redacted locally, hashed locally, and the canonical\n * EIP-191 message is constructed locally (spec/CANONICAL_PAYLOAD.md).\n *\n * The backend verifies signatures by rebuilding the payload from its\n * database-authorized identity. Existing services therefore use the\n * resolved_identity returned by get_service_score (including registered\n * aliases); caller fields never override stored payment identity. New,\n * unresolved services continue to use the caller-provided strong identity.\n */\n\nimport type { RedactionResult } from \"@crowdcode/redaction\";\nimport { buildIdentity, type ServiceIdentity } from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport type { Upstream } from \"../upstream.js\";\n\nexport interface SigningPayloadArgs {\n rating: number;\n reason: string;\n payment_reference: string;\n service_id?: string | null;\n api_endpoint?: string | null;\n payment_provider?: string | null;\n payment_target_ref?: string | null;\n directory_slug?: string | null;\n}\n\nexport interface SigningDeps {\n redact(text: string): Promise<RedactionResult>;\n upstream: Pick<Upstream, \"call\">;\n}\n\nfunction orNull(value: unknown): string | null {\n return typeof value === \"string\" && value !== \"\" ? value : null;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport async function getReviewSigningPayload(\n deps: SigningDeps,\n args: SigningPayloadArgs,\n): Promise<Record<string, unknown>> {\n let identity: ServiceIdentity;\n try {\n identity = buildIdentity(args);\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n\n const redacted = await deps.redact(args.reason);\n\n let score: Record<string, unknown>;\n try {\n score = await deps.upstream.call(\"get_service_score\", {\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n });\n } catch (err) {\n return {\n ok: false,\n reason: `could not reach the CrowdCode backend to resolve the service: ${\n (err as Error).message\n }`,\n };\n }\n\n let effective = identity;\n if (score.found === true) {\n try {\n const hasResolvedIdentity = isRecord(score.resolved_identity);\n const resolved: Record<string, unknown> = hasResolvedIdentity\n ? (score.resolved_identity as Record<string, unknown>)\n : score;\n effective = buildIdentity({\n service_id: orNull(resolved.service_id),\n service_name: orNull(score.service_name),\n api_endpoint: hasResolvedIdentity\n ? orNull(resolved.api_endpoint)\n : orNull(score.canonical_endpoint),\n payment_provider: orNull(resolved.payment_provider),\n payment_target_ref: orNull(resolved.payment_target_ref),\n directory_slug: orNull(resolved.directory_slug),\n });\n } catch (err) {\n return { ok: false, reason: (err as Error).message };\n }\n } else if (\n typeof score.reason === \"string\" &&\n score.reason !== \"service not found\"\n ) {\n // e.g. \"service identity conflict\" — same failure the remote tool returned.\n return { ok: false, reason: score.reason };\n }\n\n const message = canonicalReviewPayload({\n identity: effective,\n rating: args.rating,\n reason: redacted.text,\n paymentReference: args.payment_reference,\n });\n\n return {\n ok: true,\n signature_scheme: \"eip191\",\n message,\n reason: redacted.text,\n identity: {\n service_id: effective.service_id,\n api_endpoint: effective.api_endpoint,\n payment_provider: effective.payment_provider,\n payment_target_ref: effective.payment_target_ref,\n directory_slug: effective.directory_slug,\n },\n instructions:\n \"Sign `message` with the reviewer wallet (EIP-191 personal_sign). Then \" +\n \"call review_service in this same session, passing this exact `reason` \" +\n \"string and every field of `identity` verbatim, plus the same rating \" +\n \"and payment_reference.\",\n _redaction: {\n entities_removed: redacted.entitiesRemoved,\n model_active: redacted.modelActive,\n },\n };\n}\n","/**\n * Transparent in-process signing for review_service.\n *\n * For mppx/x402 reviews where the caller did not supply review_signature,\n * this builds the canonical message (identity-merge + local redaction via\n * getReviewSigningPayload), signs it with the local agentcash wallet (or\n * X402_PRIVATE_KEY), and augments the outgoing arguments — so an agent can\n * call review_service end-to-end with no external signing step. A\n * caller-supplied signature always wins.\n *\n * The signature covers the REDACTED reason; the redaction engine memoizes,\n * so the later per-forward redaction pass produces the byte-identical string\n * the backend hashes when rebuilding the payload.\n */\n\nimport {\n buildIdentity,\n normalizePaymentProvider,\n type ServiceIdentity,\n} from \"../canonical/identity.js\";\nimport { canonicalReviewPayload } from \"../canonical/payload.js\";\nimport {\n loadWallet,\n type LoadedWallet,\n type WalletSource,\n} from \"../wallet.js\";\nimport { getReviewSigningPayload, type SigningDeps } from \"./signing-payload.js\";\n\nexport const AGENTCASH_INSTALL_COMMAND =\n \"claude mcp add --scope user agentcash -- npx -y agentcash@latest\";\n\nexport interface NextStep {\n action: string;\n summary: string;\n command: string | null;\n link: string | null;\n retry: { tool: string; after_seconds: number | null; with: Record<string, unknown> } | null;\n}\n\nexport function installWalletNextStep(retryTool: string): NextStep {\n return {\n action: \"install_wallet\",\n summary:\n \"No local signing wallet found. Install agentcash (or set \" +\n \"X402_PRIVATE_KEY) so crowdcode-mcp can sign automatically, then retry \" +\n retryTool +\n \".\",\n command: AGENTCASH_INSTALL_COMMAND,\n link: null,\n retry: { tool: retryTool, after_seconds: null, with: {} },\n };\n}\n\nexport interface WalletOptions {\n walletDir?: string;\n autoCreate: boolean;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface PreparedReview {\n args: Record<string, unknown>;\n /** Set when local signing was attempted (mppx/x402, no caller signature). */\n wallet_source?: WalletSource;\n wallet_created?: boolean;\n wallet_error?: string;\n next_step?: NextStep;\n /** Wallet used for signing — kept so a signature-mismatch retry can re-sign. */\n wallet?: LoadedWallet;\n /** Locally constrained review fields used to validate any retry message. */\n signed_payload?: {\n identity: ServiceIdentity;\n rating: number;\n reason: string;\n payment_reference: string;\n };\n signed: boolean;\n}\n\nfunction isMachineProvider(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n try {\n const provider = normalizePaymentProvider(value);\n return provider === \"mppx\" || provider === \"x402\";\n } catch {\n // Unknown provider: forward as-is and let the backend produce its error.\n return false;\n }\n}\n\nexport async function prepareSignedReview(\n deps: SigningDeps,\n args: Record<string, unknown>,\n wallet: WalletOptions,\n): Promise<PreparedReview> {\n if (!isMachineProvider(args.payment_provider) || args.review_signature) {\n return { args, signed: false };\n }\n\n const loaded = await loadWallet({\n walletDir: wallet.walletDir,\n autoCreate: wallet.autoCreate,\n env: wallet.env,\n });\n if (loaded.source === \"none\" || loaded.account === null) {\n return {\n args,\n signed: false,\n wallet_source: \"none\",\n wallet_error: loaded.error,\n next_step: installWalletNextStep(\"review_service\"),\n };\n }\n\n const payload = await getReviewSigningPayload(deps, {\n rating: args.rating as number,\n reason: String(args.reason ?? \"\"),\n payment_reference: String(args.payment_reference ?? \"\"),\n service_id: args.service_id as string | null | undefined,\n api_endpoint: args.api_endpoint as string | null | undefined,\n payment_provider: args.payment_provider as string | null | undefined,\n payment_target_ref: args.payment_target_ref as string | null | undefined,\n directory_slug: args.directory_slug as string | null | undefined,\n });\n if (payload.ok !== true || typeof payload.message !== \"string\") {\n // Forward unsigned; the backend rejection (plus its next_step) is more\n // actionable than failing locally with a half-built payload.\n return {\n args,\n signed: false,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet_error: `could not build the signing payload locally: ${String(\n payload.reason ?? \"unknown error\",\n )}`,\n };\n }\n\n const signature = await loaded.account.signMessage({\n message: payload.message,\n });\n const identity = buildIdentity(\n payload.identity as Parameters<typeof buildIdentity>[0],\n );\n const signedReason = String(payload.reason);\n return {\n args: {\n ...args,\n // Pass the resolved identity verbatim so the backend rebuilds the exact\n // payload that was just signed.\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: signedReason,\n reviewer_wallet: loaded.address,\n review_signature: signature,\n signature_scheme: \"eip191\",\n },\n signed: true,\n wallet_source: loaded.source,\n wallet_created: loaded.created,\n wallet: loaded,\n signed_payload: {\n identity,\n rating: args.rating as number,\n reason: signedReason,\n payment_reference: String(args.payment_reference ?? \"\"),\n },\n };\n}\n\nconst SIGNED_IDENTITY_FIELDS = [\n \"service_id\",\n \"api_endpoint\",\n \"payment_provider\",\n \"payment_target_ref\",\n \"directory_slug\",\n] as const;\n\nfunction resolvedIdentity(value: unknown): ServiceIdentity | null {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n for (const field of SIGNED_IDENTITY_FIELDS) {\n if (!(field in record)) return null;\n if (record[field] !== null && typeof record[field] !== \"string\") return null;\n }\n try {\n return buildIdentity(record as Parameters<typeof buildIdentity>[0]);\n } catch {\n return null;\n }\n}\n\nfunction preservesSignedIdentity(\n signed: ServiceIdentity,\n resolved: ServiceIdentity,\n): boolean {\n return SIGNED_IDENTITY_FIELDS.every(\n (field) => signed[field] === null || signed[field] === resolved[field],\n );\n}\n\n/**\n * Handle the backend's signature-mismatch recovery contract: re-sign the\n * returned message only after reconstructing the constrained CrowdCode review\n * payload locally. Arbitrary server-provided text is never signed.\n */\nexport async function resignFromMismatch(\n prepared: PreparedReview,\n response: Record<string, unknown>,\n): Promise<Record<string, unknown> | null> {\n if (!prepared.signed || !prepared.wallet?.account) return null;\n if (!prepared.signed_payload) return null;\n if (response.accepted !== false) return null;\n if (typeof response.expected_message !== \"string\") return null;\n\n const identity = resolvedIdentity(response.resolved_identity);\n if (identity === null) return null;\n if (!preservesSignedIdentity(prepared.signed_payload.identity, identity)) {\n return null;\n }\n const message = canonicalReviewPayload({\n identity,\n rating: prepared.signed_payload.rating,\n reason: prepared.signed_payload.reason,\n paymentReference: prepared.signed_payload.payment_reference,\n });\n if (message !== response.expected_message) return null;\n\n const signature = await prepared.wallet.account.signMessage({\n message,\n });\n return {\n ...prepared.args,\n service_id: identity.service_id,\n api_endpoint: identity.api_endpoint,\n payment_provider: identity.payment_provider,\n payment_target_ref: identity.payment_target_ref,\n directory_slug: identity.directory_slug,\n reason: prepared.signed_payload.reason,\n review_signature: signature,\n };\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\n\n/** A tool-level failure reported by the backend (not a transport problem). */\nexport class UpstreamError extends Error {}\n\nexport interface Upstream {\n call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n listToolNames(): Promise<string[]>;\n}\n\nexport class UpstreamClient implements Upstream {\n private client: Client | null = null;\n\n constructor(\n private readonly baseUrl: string,\n private readonly timeoutMs: number,\n ) {}\n\n private async connect(): Promise<Client> {\n if (this.client !== null) return this.client;\n const client = new Client({ name: \"crowdcode-mcp-local\", version: \"0.1.0\" });\n const transport = new StreamableHTTPClientTransport(new URL(this.baseUrl));\n await client.connect(transport);\n this.client = client;\n return client;\n }\n\n private async reset(): Promise<void> {\n const client = this.client;\n this.client = null;\n if (client !== null) {\n try {\n await client.close();\n } catch {\n // already broken\n }\n }\n }\n\n async call(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n try {\n return await this.callOnce(name, args);\n } catch (err) {\n if (err instanceof UpstreamError) throw err;\n // Transport-level failure: reconnect once (absorbs dropped sessions and\n // Render cold starts).\n await this.reset();\n return this.callOnce(name, args);\n }\n }\n\n private async callOnce(\n name: string,\n args: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n const client = await this.connect();\n const result = await client.callTool({ name, arguments: args }, undefined, {\n timeout: this.timeoutMs,\n });\n\n if (result.isError) {\n throw new UpstreamError(\n `backend tool ${name} failed: ${firstText(result.content)}`,\n );\n }\n const structured = result.structuredContent;\n if (structured !== undefined && isRecord(structured)) {\n return structured;\n }\n const text = firstText(result.content);\n try {\n const parsed: unknown = JSON.parse(text);\n if (isRecord(parsed)) return parsed;\n } catch {\n // fall through\n }\n throw new UpstreamError(\n `backend tool ${name} returned an unparseable result: ${text.slice(0, 200)}`,\n );\n }\n\n async listToolNames(): Promise<string[]> {\n const client = await this.connect();\n const { tools } = await client.listTools();\n return tools.map((tool) => tool.name);\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction firstText(content: unknown): string {\n if (Array.isArray(content)) {\n for (const item of content) {\n if (\n isRecord(item) &&\n item.type === \"text\" &&\n typeof item.text === \"string\"\n ) {\n return item.text;\n }\n }\n }\n return \"\";\n}\n"],"mappings":";;;;;;;;;;;AAQA,SAAS,uBAAuB;AAChC,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACH9B,SAAS,yBACd,SACA,MACyB;AACzB,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY;AAAA,MACV,kBAAkB,KAAK;AAAA,MACvB,cAAc,KAAK;AAAA,IACrB;AAAA,EACF;AACF;AAEO,SAAS,aAAa,SAE3B;AACA,SAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,OAAO,EAAE,CAAC,EAAE;AACtE;;;ACXO,IAAM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Ac,CAAC;AACrD,UAAM,UAAU,sBAAsB,OAAO,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC;AACxE,QAAI,QAAQ,SAAS,GAAG;AACtB,cAAQ,OAAO;AAAA,QACb,gDAAgD,QAAQ,KAAK,IAAI,CAAC;AAAA;AAAA,MAEpE;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACF;AAEA,eAAsB,cAA6B;AACjD,QAAM,SAAS,UAAU;AACzB,QAAM,SAAS,MAAM,gBAAgB,OAAO;AAAA,IAC1C,UAAU,OAAO;AAAA,IACjB,aAAa,CAAC,OAAO;AAAA,EACvB,CAAC;AACD,QAAM,WAAW,IAAI,eAAe,OAAO,YAAY,OAAO,iBAAiB;AAC/E,QAAM,SAAS,YAAY,EAAE,QAAQ,SAAS,CAAC;AAC/C,QAAM,OAAO,QAAQ,IAAI,qBAAqB,CAAC;AAC/C,OAAK,gBAAgB,QAAQ;AAC/B;","names":["isRecord"]}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: crowdcode
|
|
3
|
+
description: Mandatory reputation checks for paid agent services. Use whenever an agent may spend money, call or provision a paid API, make an x402 or MPP/mppx request, use AgentCash or Stripe for a service, or purchase any external capability. Check CrowdCode before the first payment and review the service after every paid use, including failures.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# CrowdCode
|
|
7
|
+
|
|
8
|
+
Use CrowdCode as the reputation layer around paid agent services. Do not begin
|
|
9
|
+
a command or tool call that may charge money until the pre-payment check is
|
|
10
|
+
complete.
|
|
11
|
+
|
|
12
|
+
## Before spending
|
|
13
|
+
|
|
14
|
+
1. Call `get_service_score` for every finalist before its first paid call.
|
|
15
|
+
2. Identify the service with the strongest values available:
|
|
16
|
+
`api_endpoint + payment_provider + payment_target_ref`; otherwise use
|
|
17
|
+
`service_id` or `directory_slug`.
|
|
18
|
+
3. Compare the canonical `score` and use `n_eff` as evidence strength.
|
|
19
|
+
`unproven: true` means insufficient trusted evidence, not a bad service;
|
|
20
|
+
fall back to directory metadata, price, and the active spend policy.
|
|
21
|
+
4. Read `summary` when present for reported strengths, failures, and caveats.
|
|
22
|
+
5. Tell the user what will be spent when the surrounding workflow does not
|
|
23
|
+
already provide a clear spending disclosure.
|
|
24
|
+
|
|
25
|
+
If the score check fails because CrowdCode is temporarily unavailable, report
|
|
26
|
+
that fact before spending and follow the returned `next_step`. Do not silently
|
|
27
|
+
treat a missing check as approval.
|
|
28
|
+
|
|
29
|
+
## After paid use
|
|
30
|
+
|
|
31
|
+
Call `review_service` after every paid use, whether it succeeded, returned a
|
|
32
|
+
poor result, timed out, or failed after payment. Judge the response against the
|
|
33
|
+
original task:
|
|
34
|
+
|
|
35
|
+
- **5** — excellent, relevant, fast, and reusable with no concrete caveat.
|
|
36
|
+
- **4** — helpful, with a specific schema, documentation, latency, or output
|
|
37
|
+
caveat.
|
|
38
|
+
- **3** — mixed, thin, confusing, or technically valid but not useful.
|
|
39
|
+
- **2** — paid but poor, unclear, or difficult to use.
|
|
40
|
+
- **1** — paid and broken, unusable, misleading, or severely unreliable.
|
|
41
|
+
|
|
42
|
+
State the observed reason plainly. A bad paid outcome is the reason for a low
|
|
43
|
+
review, not a reason to skip reviewing.
|
|
44
|
+
|
|
45
|
+
`review_service` signs automatically with the local payer-compatible wallet.
|
|
46
|
+
Do not call `get_review_signing_payload` or create a signature manually unless
|
|
47
|
+
automatic signing fails or an external payer wallet must be used.
|
|
48
|
+
|
|
49
|
+
For x402 and MPP/mppx, take identity and proof from the actual payment rather
|
|
50
|
+
than a directory listing:
|
|
51
|
+
|
|
52
|
+
- `payment_reference`: x402 settlement transaction hash or MPP
|
|
53
|
+
`Payment-Receipt` reference.
|
|
54
|
+
- `payment_proof`: the base64 response-header value when available, not a
|
|
55
|
+
decoded object or bare transaction hash.
|
|
56
|
+
- `payment_target_ref`: the actual payment recipient/on-chain transfer payee.
|
|
57
|
+
|
|
58
|
+
If the payer wallet differs from the local signing wallet, supply a signature
|
|
59
|
+
from the wallet that actually sent the payment. Follow a returned `next_step`
|
|
60
|
+
or canonical signature-mismatch retry once; never invent payment evidence.
|
|
61
|
+
|
|
62
|
+
## Missing paid service
|
|
63
|
+
|
|
64
|
+
Call `request_service` once only when the agent was actively trying to buy a
|
|
65
|
+
remote API capability, had spend authority, and would have paid a concrete
|
|
66
|
+
amount immediately, but no suitable paid service existed. Describe reusable
|
|
67
|
+
inputs, outputs, and approximate per-call value. Do not submit free-tool wishes,
|
|
68
|
+
local runtime wishes, one-off task help, secrets, or private user data.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "crowdcode-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "CrowdCode MCP client with local-first PII redaction. Free-text tool inputs are redacted on your machine before anything is sent to the CrowdCode backend.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -18,11 +18,14 @@
|
|
|
18
18
|
"node": ">=20"
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
|
21
|
-
"build": "tsup",
|
|
21
|
+
"build": "tsup && node scripts/sync-assets.mjs",
|
|
22
|
+
"build:mcpb": "npm run build && node scripts/build-mcpb.mjs",
|
|
23
|
+
"build:plugin": "npm run build && node scripts/build-plugin.mjs",
|
|
24
|
+
"check:assets": "node scripts/sync-assets.mjs --check",
|
|
22
25
|
"dev": "tsup --watch",
|
|
23
26
|
"test": "vitest run",
|
|
24
27
|
"typecheck": "tsc --noEmit",
|
|
25
|
-
"prepublishOnly": "npm run build"
|
|
28
|
+
"prepublishOnly": "npm run build && npm run check:assets"
|
|
26
29
|
},
|
|
27
30
|
"dependencies": {
|
|
28
31
|
"@crowdcode/redaction": "^0.1.0",
|
|
@@ -31,7 +34,9 @@
|
|
|
31
34
|
"zod": "^3.24.0"
|
|
32
35
|
},
|
|
33
36
|
"devDependencies": {
|
|
37
|
+
"@anthropic-ai/mcpb": "^2.1.2",
|
|
34
38
|
"@types/node": "^22.0.0",
|
|
39
|
+
"fflate": "^0.8.3",
|
|
35
40
|
"tsup": "^8.3.0",
|
|
36
41
|
"typescript": "^5.6.0",
|
|
37
42
|
"vitest": "^2.1.0"
|