@hellocrossman/mcp-sdk 0.2.0 → 0.3.2

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/dist/cli.js CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from "fs";
3
3
  import path from "path";
4
+ import readline from "readline";
5
+ import { scanAllRoutes } from "./route-scan.js";
4
6
  const IMPORT_LINE_ESM = `import { createMcpServer } from '@hellocrossman/mcp-sdk';`;
5
7
  const IMPORT_LINE_CJS = `const { createMcpServer } = require('@hellocrossman/mcp-sdk');`;
6
- const SETUP_LINE = `createMcpServer({ app });`;
7
8
  const COMMON_ENTRY_FILES = [
8
9
  "server/index.ts",
9
10
  "server/index.js",
@@ -28,12 +29,49 @@ const EXPRESS_PATTERNS = [
28
29
  ];
29
30
  const APP_VAR_PATTERN = /(?:const|let|var)\s+(\w+)\s*=\s*express\(\)/;
30
31
  const LISTEN_PATTERN = /(?:app|server|httpServer)\s*\.listen\s*\(/;
32
+ const COLORS = {
33
+ reset: "\x1b[0m",
34
+ bold: "\x1b[1m",
35
+ dim: "\x1b[2m",
36
+ green: "\x1b[32m",
37
+ yellow: "\x1b[33m",
38
+ blue: "\x1b[34m",
39
+ magenta: "\x1b[35m",
40
+ cyan: "\x1b[36m",
41
+ white: "\x1b[37m",
42
+ gray: "\x1b[90m",
43
+ bgGreen: "\x1b[42m",
44
+ bgYellow: "\x1b[43m",
45
+ };
46
+ function c(color, text) {
47
+ return `${COLORS[color]}${text}${COLORS.reset}`;
48
+ }
49
+ function createPrompt() {
50
+ const rl = readline.createInterface({
51
+ input: process.stdin,
52
+ output: process.stdout,
53
+ });
54
+ return {
55
+ ask: (question) => new Promise((resolve) => {
56
+ rl.question(question, (answer) => resolve(answer.trim()));
57
+ }),
58
+ confirm: async (question, defaultYes = true) => {
59
+ const hint = defaultYes ? "Y/n" : "y/N";
60
+ const answer = await new Promise((resolve) => {
61
+ rl.question(`${question} ${c("dim", `(${hint})`)} `, (a) => resolve(a.trim().toLowerCase()));
62
+ });
63
+ if (answer === "")
64
+ return defaultYes;
65
+ return answer === "y" || answer === "yes";
66
+ },
67
+ close: () => rl.close(),
68
+ };
69
+ }
31
70
  function findProjectRoot() {
32
71
  let dir = process.cwd();
33
72
  while (dir !== path.dirname(dir)) {
34
- if (fs.existsSync(path.join(dir, "package.json"))) {
73
+ if (fs.existsSync(path.join(dir, "package.json")))
35
74
  return dir;
36
- }
37
75
  dir = path.dirname(dir);
38
76
  }
39
77
  return process.cwd();
@@ -43,9 +81,8 @@ function findExpressEntryFile(root) {
43
81
  const fullPath = path.join(root, file);
44
82
  if (fs.existsSync(fullPath)) {
45
83
  const content = fs.readFileSync(fullPath, "utf-8");
46
- if (EXPRESS_PATTERNS.some((p) => p.test(content))) {
84
+ if (EXPRESS_PATTERNS.some((p) => p.test(content)))
47
85
  return fullPath;
48
- }
49
86
  }
50
87
  }
51
88
  const srcDirs = ["server", "src", "."];
@@ -57,14 +94,13 @@ function findExpressEntryFile(root) {
57
94
  for (const file of files) {
58
95
  const fullPath = path.join(dirPath, file);
59
96
  const content = fs.readFileSync(fullPath, "utf-8");
60
- if (EXPRESS_PATTERNS.some((p) => p.test(content))) {
97
+ if (EXPRESS_PATTERNS.some((p) => p.test(content)))
61
98
  return fullPath;
62
- }
63
99
  }
64
100
  }
65
101
  return null;
66
102
  }
67
- function isESM(filePath, root) {
103
+ function checkIsESM(filePath, root) {
68
104
  if (filePath.endsWith(".ts") || filePath.endsWith(".mjs"))
69
105
  return true;
70
106
  try {
@@ -76,20 +112,336 @@ function isESM(filePath, root) {
76
112
  }
77
113
  }
78
114
  function alreadySetup(content) {
79
- return (content.includes("createMcpServer") ||
80
- content.includes("@hellocrossman/mcp-sdk") ||
81
- content.includes("hellocrossman/mcp-sdk"));
115
+ return content.includes("createMcpServer") || content.includes("@hellocrossman/mcp-sdk");
82
116
  }
83
- function injectMcpSetup(filePath, root) {
84
- const content = fs.readFileSync(filePath, "utf-8");
117
+ function checkPgInstalled(root) {
118
+ return fs.existsSync(path.join(root, "node_modules", "pg"));
119
+ }
120
+ function detectPackageManager(root) {
121
+ if (fs.existsSync(path.join(root, "pnpm-lock.yaml")))
122
+ return "pnpm";
123
+ if (fs.existsSync(path.join(root, "yarn.lock")))
124
+ return "yarn";
125
+ return "npm";
126
+ }
127
+ function printHeader() {
128
+ console.log();
129
+ console.log(c("cyan", ` __ __ _____ ____`));
130
+ console.log(c("cyan", ` | \\/ |/ ____| _ \\`));
131
+ console.log(c("cyan", ` | \\ / | | | |_) |`));
132
+ console.log(c("cyan", ` | |\\/| | | | __/`));
133
+ console.log(c("cyan", ` | | | | |____| |`));
134
+ console.log(c("cyan", ` |_| |_|\\_____|_|`) + c("dim", ` SDK`));
135
+ console.log();
136
+ console.log(` ${c("bold", "@hellocrossman/mcp-sdk")}`);
137
+ console.log(` ${c("dim", "Turn your Express API into an MCP server")}`);
138
+ console.log();
139
+ console.log(` ${c("dim", "This wizard will walk you through setup.")}`);
140
+ console.log(` ${c("dim", "Press Ctrl+C at any time to cancel.")}`);
141
+ console.log();
142
+ console.log(c("dim", ` ${"~".repeat(46)}`));
143
+ console.log();
144
+ }
145
+ function printStep(step, total, title) {
146
+ console.log();
147
+ const bar = Array.from({ length: total }, (_, i) => i < step ? c("cyan", "\u2501") : c("dim", "\u2501")).join("");
148
+ console.log(` ${bar} ${c("dim", `${step}/${total}`)}`);
149
+ console.log(` ${c("bold", title)}`);
150
+ console.log();
151
+ }
152
+ function printToolTable(tools) {
153
+ const routeTools = tools.filter((t) => t.source === "route");
154
+ const dbTools = tools.filter((t) => t.source === "database");
155
+ if (routeTools.length > 0) {
156
+ console.log(`\n ${c("dim", "API Routes:")}`);
157
+ for (const t of routeTools) {
158
+ const status = t.enabled ? c("green", "ON ") : c("dim", "OFF");
159
+ const method = t.method.padEnd(6);
160
+ console.log(` ${status} ${c("yellow", method)} ${t.name} ${c("dim", `- ${t.description}`)}`);
161
+ }
162
+ }
163
+ if (dbTools.length > 0) {
164
+ console.log(`\n ${c("dim", "Database Tables:")}`);
165
+ for (const t of dbTools) {
166
+ const status = t.enabled ? c("green", "ON ") : c("dim", "OFF");
167
+ const method = t.method.padEnd(6);
168
+ console.log(` ${status} ${c("magenta", method)} ${t.name} ${c("dim", `- ${t.description}`)}`);
169
+ }
170
+ }
171
+ }
172
+ async function stepDetectApp(state, prompt, specifiedFile) {
173
+ printStep(1, 5, "Detecting Express app");
174
+ let entryFile = null;
175
+ if (specifiedFile) {
176
+ const resolved = path.resolve(state.root, specifiedFile);
177
+ if (fs.existsSync(resolved)) {
178
+ entryFile = resolved;
179
+ }
180
+ else {
181
+ console.log(` ${c("yellow", "!")} File not found: ${specifiedFile}`);
182
+ return false;
183
+ }
184
+ }
185
+ else {
186
+ entryFile = findExpressEntryFile(state.root);
187
+ }
188
+ if (!entryFile) {
189
+ console.log(` ${c("yellow", "!")} Could not find an Express app file.`);
190
+ const custom = await prompt.ask(` Enter the path to your Express app file: `);
191
+ if (custom) {
192
+ const resolved = path.resolve(state.root, custom);
193
+ if (fs.existsSync(resolved)) {
194
+ entryFile = resolved;
195
+ }
196
+ else {
197
+ console.log(` ${c("yellow", "!")} File not found: ${custom}`);
198
+ return false;
199
+ }
200
+ }
201
+ else {
202
+ return false;
203
+ }
204
+ }
205
+ const content = fs.readFileSync(entryFile, "utf-8");
85
206
  if (alreadySetup(content)) {
86
- return { success: true, message: "MCP SDK is already set up in this file." };
207
+ console.log(` ${c("green", "+")} MCP SDK is already set up in ${path.relative(state.root, entryFile)}`);
208
+ console.log(` ${c("dim", " Remove the existing createMcpServer() call to reconfigure.")}`);
209
+ return false;
87
210
  }
88
- const esm = isESM(filePath, root);
89
- const importLine = esm ? IMPORT_LINE_ESM : IMPORT_LINE_CJS;
90
211
  const appMatch = content.match(APP_VAR_PATTERN);
91
- const appVarName = appMatch ? appMatch[1] : "app";
92
- const setupCode = `createMcpServer({ app: ${appVarName} });`;
212
+ state.entryFile = entryFile;
213
+ state.appVarName = appMatch ? appMatch[1] : "app";
214
+ state.isESM = checkIsESM(entryFile, state.root);
215
+ console.log(` ${c("green", "+")} Found Express app: ${c("bold", path.relative(state.root, entryFile))}`);
216
+ console.log(` ${c("dim", ` Variable: ${state.appVarName}, Module: ${state.isESM ? "ESM" : "CommonJS"}`)}`);
217
+ return true;
218
+ }
219
+ async function stepScanRoutes(state) {
220
+ printStep(2, 5, "Scanning API routes");
221
+ state.routes = scanAllRoutes(state.entryFile, state.routePrefix);
222
+ if (state.routes.length === 0) {
223
+ console.log(` ${c("dim", " No routes found under")} ${state.routePrefix}`);
224
+ console.log(` ${c("dim", " Routes will be discovered at runtime when your app starts.")}`);
225
+ return;
226
+ }
227
+ console.log(` ${c("green", "+")} Found ${c("bold", String(state.routes.length))} API routes:\n`);
228
+ for (const route of state.routes) {
229
+ const method = route.method.padEnd(6);
230
+ console.log(` ${c("yellow", method)} ${route.path}`);
231
+ }
232
+ for (const route of state.routes) {
233
+ const name = generateToolName(route.method, route.path);
234
+ const description = generateToolDescription(route.method, route.path);
235
+ state.tools.push({
236
+ name,
237
+ description,
238
+ method: route.method,
239
+ path: route.path,
240
+ source: "route",
241
+ enabled: true,
242
+ });
243
+ }
244
+ }
245
+ async function stepScanDatabase(state, prompt) {
246
+ printStep(3, 5, "Database discovery");
247
+ const wantDb = await prompt.confirm(` Scan your database for tables to expose as tools?`);
248
+ if (!wantDb) {
249
+ state.databaseEnabled = false;
250
+ console.log(` ${c("dim", " Skipping database discovery.")}`);
251
+ return;
252
+ }
253
+ let dbUrl = process.env.DATABASE_URL || process.env.POSTGRES_URL || process.env.PG_CONNECTION_STRING;
254
+ if (!dbUrl) {
255
+ console.log(` ${c("yellow", "!")} No DATABASE_URL found in environment.`);
256
+ dbUrl = (await prompt.ask(` Enter your PostgreSQL connection string (or press Enter to skip): `)) || undefined;
257
+ if (!dbUrl) {
258
+ state.databaseEnabled = false;
259
+ console.log(` ${c("dim", " Skipping database discovery.")}`);
260
+ return;
261
+ }
262
+ }
263
+ if (!checkPgInstalled(state.root)) {
264
+ console.log(` ${c("yellow", "!")} The 'pg' package is required for database features.`);
265
+ const pm = detectPackageManager(state.root);
266
+ const installCmd = pm === "yarn" ? "yarn add pg" : pm === "pnpm" ? "pnpm add pg" : "npm install pg";
267
+ const installPg = await prompt.confirm(` Install pg now? (${c("dim", installCmd)})`);
268
+ if (installPg) {
269
+ console.log(` ${c("dim", ` Running ${installCmd}...`)}`);
270
+ const { execSync } = await import("child_process");
271
+ try {
272
+ execSync(installCmd, { cwd: state.root, stdio: "pipe" });
273
+ console.log(` ${c("green", "+")} pg installed successfully.`);
274
+ }
275
+ catch {
276
+ console.log(` ${c("yellow", "!")} Failed to install pg. Run '${installCmd}' manually.`);
277
+ state.databaseEnabled = false;
278
+ return;
279
+ }
280
+ }
281
+ else {
282
+ console.log(` ${c("dim", ` Run '${installCmd}' to enable database features later.`)}`);
283
+ state.databaseEnabled = false;
284
+ return;
285
+ }
286
+ }
287
+ try {
288
+ const { introspectDatabase } = await import("./db-introspect.js");
289
+ const { isSensitiveTable } = await import("./db-tool-generator.js");
290
+ console.log(` ${c("dim", " Connecting to database...")}`);
291
+ const result = await introspectDatabase(dbUrl);
292
+ const safeTables = result.tables.filter((t) => !isSensitiveTable(t.name));
293
+ const hiddenTables = result.tables.filter((t) => isSensitiveTable(t.name));
294
+ state.dbTables = safeTables;
295
+ state.databaseEnabled = true;
296
+ console.log(` ${c("green", "+")} Found ${c("bold", String(result.tables.length))} tables (${safeTables.length} safe, ${hiddenTables.length} hidden)\n`);
297
+ if (hiddenTables.length > 0) {
298
+ console.log(` ${c("dim", " Auto-hidden (sensitive):")} ${hiddenTables.map((t) => t.name).join(", ")}`);
299
+ }
300
+ console.log(`\n ${c("dim", " Available tables:")}`);
301
+ for (const table of safeTables) {
302
+ const colCount = table.columns.length;
303
+ const pk = table.columns.find((col) => col.isPrimary);
304
+ console.log(` ${c("magenta", table.name)} ${c("dim", `(${colCount} columns${pk ? `, pk: ${pk.name}` : ""})`)}`);
305
+ state.tools.push({
306
+ name: `list_${table.name}`,
307
+ description: `List all ${formatTableName(table.name)} records with filtering and pagination`,
308
+ method: "QUERY",
309
+ path: `db://${table.name}`,
310
+ source: "database",
311
+ enabled: true,
312
+ tableName: table.name,
313
+ });
314
+ if (pk) {
315
+ state.tools.push({
316
+ name: `get_${table.name}_by_${pk.name}`,
317
+ description: `Get a specific ${formatTableName(table.name)} record by ${pk.name}`,
318
+ method: "QUERY",
319
+ path: `db://${table.name}/${pk.name}`,
320
+ source: "database",
321
+ enabled: true,
322
+ tableName: table.name,
323
+ });
324
+ }
325
+ }
326
+ }
327
+ catch (err) {
328
+ const msg = err instanceof Error ? err.message : String(err);
329
+ console.log(` ${c("yellow", "!")} Database scan failed: ${msg}`);
330
+ state.databaseEnabled = false;
331
+ }
332
+ }
333
+ async function stepEnrichAndReview(state, prompt) {
334
+ printStep(4, 5, "AI enrichment & tool review");
335
+ if (state.tools.length === 0) {
336
+ console.log(` ${c("dim", " No tools discovered. Routes will be discovered at runtime.")}`);
337
+ state.enrichmentEnabled = true;
338
+ return;
339
+ }
340
+ const wantEnrich = await prompt.confirm(` Use AI to improve tool names and descriptions?`);
341
+ if (wantEnrich) {
342
+ console.log(` ${c("dim", " Contacting enrichment service...")}`);
343
+ try {
344
+ const { enrichTools } = await import("./enrichment.js");
345
+ const toolSummaries = state.tools.map((t) => ({
346
+ name: t.name,
347
+ description: t.description,
348
+ method: t.method === "QUERY" ? "DB_QUERY" : t.method,
349
+ path: t.path,
350
+ inputSchema: {},
351
+ params: [],
352
+ }));
353
+ const enriched = await enrichTools(toolSummaries);
354
+ let enrichCount = 0;
355
+ for (let i = 0; i < state.tools.length; i++) {
356
+ if (enriched[i]) {
357
+ if (enriched[i].name)
358
+ state.tools[i].name = enriched[i].name;
359
+ if (enriched[i].description)
360
+ state.tools[i].description = enriched[i].description;
361
+ enrichCount++;
362
+ }
363
+ }
364
+ console.log(` ${c("green", "+")} Enhanced ${enrichCount} tool descriptions.`);
365
+ state.enrichmentEnabled = true;
366
+ }
367
+ catch {
368
+ console.log(` ${c("yellow", "!")} Enrichment service unavailable. Using auto-generated names.`);
369
+ state.enrichmentEnabled = false;
370
+ }
371
+ }
372
+ else {
373
+ state.enrichmentEnabled = false;
374
+ }
375
+ console.log(`\n ${c("bold", "Discovered tools:")}`);
376
+ printToolTable(state.tools);
377
+ console.log();
378
+ const reviewMode = await prompt.ask(` Enable all tools, or review individually? ${c("dim", "(all/review)")} `);
379
+ if (reviewMode.toLowerCase() === "review" || reviewMode.toLowerCase() === "r") {
380
+ console.log();
381
+ for (let i = 0; i < state.tools.length; i++) {
382
+ const t = state.tools[i];
383
+ const source = t.source === "route" ? c("yellow", t.method) : c("magenta", "DB");
384
+ const enabled = await prompt.confirm(` ${source} ${c("bold", t.name)} ${c("dim", `- ${t.description}`)}\n Enable this tool?`);
385
+ state.tools[i].enabled = enabled;
386
+ }
387
+ const enabledCount = state.tools.filter((t) => t.enabled).length;
388
+ console.log(`\n ${c("green", "+")} ${enabledCount} of ${state.tools.length} tools enabled.`);
389
+ }
390
+ else {
391
+ console.log(` ${c("green", "+")} All ${state.tools.length} tools enabled.`);
392
+ }
393
+ if (state.databaseEnabled) {
394
+ const wantWrites = await prompt.confirm(`\n Enable write operations (create/insert) for database tables?`, false);
395
+ state.includeWrites = wantWrites;
396
+ }
397
+ }
398
+ async function stepGenerate(state) {
399
+ printStep(5, 5, "Generating MCP server");
400
+ const content = fs.readFileSync(state.entryFile, "utf-8");
401
+ const importLine = state.isESM ? IMPORT_LINE_ESM : IMPORT_LINE_CJS;
402
+ const disabledRoutePaths = state.tools
403
+ .filter((t) => t.source === "route" && !t.enabled)
404
+ .map((t) => t.path);
405
+ const enabledRoutePaths = new Set(state.tools
406
+ .filter((t) => t.source === "route" && t.enabled)
407
+ .map((t) => t.path));
408
+ const disabledRoutes = disabledRoutePaths.filter((p) => !enabledRoutePaths.has(p));
409
+ const disabledTables = new Set();
410
+ const dbTools = state.tools.filter((t) => t.source === "database");
411
+ const tableNames = [...new Set(dbTools.map((t) => t.tableName))];
412
+ for (const tableName of tableNames) {
413
+ const tableTools = dbTools.filter((t) => t.tableName === tableName);
414
+ const allDisabled = tableTools.every((t) => !t.enabled);
415
+ if (allDisabled)
416
+ disabledTables.add(tableName);
417
+ }
418
+ const configParts = [];
419
+ configParts.push(`app: ${state.appVarName}`);
420
+ if (disabledRoutes.length > 0) {
421
+ configParts.push(`excludeRoutes: ${JSON.stringify(disabledRoutes)}`);
422
+ }
423
+ if (!state.databaseEnabled) {
424
+ configParts.push(`database: false`);
425
+ }
426
+ else {
427
+ if (disabledTables.size > 0) {
428
+ configParts.push(`excludeTables: ${JSON.stringify([...disabledTables])}`);
429
+ }
430
+ if (state.includeWrites) {
431
+ configParts.push(`includeWrites: true`);
432
+ }
433
+ }
434
+ if (!state.enrichmentEnabled) {
435
+ configParts.push(`enrichment: false`);
436
+ }
437
+ let setupCode;
438
+ if (configParts.length <= 2) {
439
+ setupCode = `createMcpServer({ ${configParts.join(", ")} });`;
440
+ }
441
+ else {
442
+ const indent = " ";
443
+ setupCode = `createMcpServer({\n${configParts.map((p) => `${indent}${p},`).join("\n")}\n});`;
444
+ }
93
445
  const lines = content.split("\n");
94
446
  let lastImportIndex = -1;
95
447
  for (let i = 0; i < lines.length; i++) {
@@ -97,8 +449,7 @@ function injectMcpSetup(filePath, root) {
97
449
  lastImportIndex = i;
98
450
  }
99
451
  }
100
- const insertImportAt = lastImportIndex + 1;
101
- lines.splice(insertImportAt, 0, importLine);
452
+ lines.splice(lastImportIndex + 1, 0, importLine);
102
453
  let listenIndex = -1;
103
454
  for (let i = lines.length - 1; i >= 0; i--) {
104
455
  if (LISTEN_PATTERN.test(lines[i])) {
@@ -106,72 +457,153 @@ function injectMcpSetup(filePath, root) {
106
457
  break;
107
458
  }
108
459
  }
460
+ const commentLine = `// MCP server - exposes your API to AI assistants (Claude, ChatGPT, Cursor)`;
109
461
  if (listenIndex >= 0) {
110
- lines.splice(listenIndex, 0, "", `// MCP server - auto-discovered from your Express routes and database`, setupCode);
462
+ lines.splice(listenIndex, 0, "", commentLine, setupCode);
111
463
  }
112
464
  else {
113
- lines.push("");
114
- lines.push(`// MCP server - auto-discovered from your Express routes and database`);
115
- lines.push(setupCode);
465
+ lines.push("", commentLine, setupCode);
116
466
  }
117
- fs.writeFileSync(filePath, lines.join("\n"));
118
- return {
119
- success: true,
120
- message: `Added MCP setup to ${path.relative(root, filePath)}`,
121
- };
467
+ fs.writeFileSync(state.entryFile, lines.join("\n"));
468
+ const relPath = path.relative(state.root, state.entryFile);
469
+ const enabledCount = state.tools.filter((t) => t.enabled).length;
470
+ console.log();
471
+ console.log(c("green", ` +------------------------------+`));
472
+ console.log(c("green", ` | |`));
473
+ console.log(c("green", ` | `) + c("bold", `MCP server configured!`) + c("green", ` |`));
474
+ console.log(c("green", ` | |`));
475
+ console.log(c("green", ` +------------------------------+`));
476
+ console.log();
477
+ console.log(` ${c("green", "\u2713")} Updated ${c("bold", relPath)}`);
478
+ console.log();
479
+ console.log(` ${c("dim", "Configuration")}`);
480
+ console.log(` ${c("dim", "\u2502")} Tools enabled ${c("bold", String(enabledCount))}`);
481
+ console.log(` ${c("dim", "\u2502")} Database ${state.databaseEnabled ? c("green", "enabled") : c("dim", "disabled")}`);
482
+ console.log(` ${c("dim", "\u2502")} AI enrichment ${state.enrichmentEnabled ? c("green", "enabled") : c("dim", "disabled")}`);
483
+ console.log(` ${c("dim", "\u2502")} Write operations ${state.includeWrites ? c("green", "enabled") : c("dim", "disabled")}`);
484
+ console.log();
485
+ console.log(` ${c("bold", "What's next?")}`);
486
+ console.log();
487
+ console.log(` ${c("cyan", "1.")} Restart your app`);
488
+ console.log(` ${c("cyan", "2.")} Visit ${c("cyan", "http://localhost:3000/mcp")} to see your tools`);
489
+ console.log(` ${c("cyan", "3.")} Connect Claude, ChatGPT, or Cursor to your /mcp endpoint`);
490
+ console.log();
491
+ console.log(` ${c("dim", "Full guide:")} ${c("cyan", "https://mcp-skill-scanner.replit.app/guide")}`);
492
+ console.log();
122
493
  }
123
- function main() {
124
- const args = process.argv.slice(2);
125
- if (args[0] !== "init") {
126
- console.log(`
127
- @hellocrossman/mcp-sdk CLI
128
-
129
- Usage:
130
- npx @hellocrossman/mcp-sdk init Auto-detect Express app and add MCP server
131
-
132
- Options:
133
- --file <path> Specify the Express app file manually
134
- `);
135
- return;
494
+ function generateToolName(method, routePath) {
495
+ const segments = routePath
496
+ .replace(/^\/api\/?/, "")
497
+ .split("/")
498
+ .filter((s) => s && !s.startsWith(":"));
499
+ const resource = segments.join("_") || "root";
500
+ const paramSegments = routePath.split("/").filter((s) => s.startsWith(":"));
501
+ switch (method.toUpperCase()) {
502
+ case "GET":
503
+ return paramSegments.length > 0
504
+ ? `get_${resource}_by_${paramSegments[0].slice(1)}`
505
+ : `list_${resource}`;
506
+ case "POST":
507
+ return `create_${resource}`;
508
+ case "PUT":
509
+ case "PATCH":
510
+ return `update_${resource}`;
511
+ case "DELETE":
512
+ return `delete_${resource}`;
513
+ default:
514
+ return `${method.toLowerCase()}_${resource}`;
136
515
  }
137
- console.log("\n @hellocrossman/mcp-sdk\n");
138
- console.log(" Setting up MCP server...\n");
139
- const root = findProjectRoot();
140
- const fileArgIndex = args.indexOf("--file");
141
- let entryFile = null;
142
- if (fileArgIndex >= 0 && args[fileArgIndex + 1]) {
143
- const specified = path.resolve(root, args[fileArgIndex + 1]);
144
- if (fs.existsSync(specified)) {
145
- entryFile = specified;
516
+ }
517
+ function generateToolDescription(method, routePath) {
518
+ const segments = routePath
519
+ .replace(/^\/api\/?/, "")
520
+ .split("/")
521
+ .filter((s) => s && !s.startsWith(":"));
522
+ const resource = segments.map((s) => s.replace(/[-_]/g, " ")).join(" ") || "resource";
523
+ const paramSegments = routePath.split("/").filter((s) => s.startsWith(":"));
524
+ switch (method.toUpperCase()) {
525
+ case "GET":
526
+ return paramSegments.length > 0
527
+ ? `Get ${resource} by ${paramSegments[0].slice(1)}`
528
+ : `List all ${resource}`;
529
+ case "POST":
530
+ return `Create a new ${resource}`;
531
+ case "PUT":
532
+ case "PATCH":
533
+ return `Update ${resource}`;
534
+ case "DELETE":
535
+ return `Delete ${resource}`;
536
+ default:
537
+ return `${method} ${resource}`;
538
+ }
539
+ }
540
+ function formatTableName(name) {
541
+ return name.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());
542
+ }
543
+ async function runWizard(specifiedFile) {
544
+ printHeader();
545
+ const prompt = createPrompt();
546
+ const state = {
547
+ root: findProjectRoot(),
548
+ entryFile: "",
549
+ appVarName: "app",
550
+ isESM: false,
551
+ routePrefix: "/api",
552
+ routes: [],
553
+ dbTables: [],
554
+ tools: [],
555
+ databaseEnabled: true,
556
+ enrichmentEnabled: true,
557
+ includeWrites: false,
558
+ };
559
+ try {
560
+ const found = await stepDetectApp(state, prompt, specifiedFile);
561
+ if (!found) {
562
+ prompt.close();
563
+ return;
564
+ }
565
+ await stepScanRoutes(state);
566
+ await stepScanDatabase(state, prompt);
567
+ await stepEnrichAndReview(state, prompt);
568
+ await stepGenerate(state);
569
+ }
570
+ catch (err) {
571
+ if (err instanceof Error && err.message.includes("readline was closed")) {
572
+ console.log(`\n ${c("dim", "Setup cancelled.")}\n`);
146
573
  }
147
574
  else {
148
- console.error(` Error: File not found: ${args[fileArgIndex + 1]}`);
149
- process.exit(1);
575
+ throw err;
150
576
  }
151
577
  }
152
- else {
153
- entryFile = findExpressEntryFile(root);
578
+ finally {
579
+ prompt.close();
154
580
  }
155
- if (!entryFile) {
156
- console.error(" Could not find an Express app file.");
157
- console.error(" Try: npx @hellocrossman/mcp-sdk init --file server/index.ts\n");
158
- process.exit(1);
159
- }
160
- console.log(` Found Express app: ${path.relative(root, entryFile)}`);
161
- const result = injectMcpSetup(entryFile, root);
162
- if (result.success) {
163
- console.log(` ${result.message}`);
164
- console.log("");
165
- console.log(" Your MCP server will be available at /mcp when you start your app.");
166
- console.log(" It auto-discovers Express routes and database tables.");
167
- console.log(" Sensitive tables (users, sessions, etc.) are hidden by default.");
168
- console.log("");
169
- console.log(" Restart your app to see it in action.\n");
581
+ }
582
+ function main() {
583
+ const args = process.argv.slice(2);
584
+ if (args[0] !== "init") {
585
+ console.log();
586
+ console.log(c("cyan", ` __ __ _____ ____`));
587
+ console.log(c("cyan", ` | \\/ |/ ____| _ \\`));
588
+ console.log(c("cyan", ` | \\ / | | | |_) |`));
589
+ console.log(c("cyan", ` | |\\/| | | | __/`));
590
+ console.log(c("cyan", ` | | | | |____| |`));
591
+ console.log(c("cyan", ` |_| |_|\\_____|_|`) + c("dim", ` SDK`));
592
+ console.log();
593
+ console.log(` ${c("bold", "Usage")}`);
594
+ console.log(` ${c("dim", "$")} npx @hellocrossman/mcp-sdk init`);
595
+ console.log();
596
+ console.log(` ${c("bold", "Options")}`);
597
+ console.log(` --file <path> Specify the Express app file`);
598
+ console.log();
599
+ return;
170
600
  }
171
- else {
172
- console.error(` Error: ${result.message}\n`);
601
+ const fileArgIndex = args.indexOf("--file");
602
+ const specifiedFile = fileArgIndex >= 0 ? args[fileArgIndex + 1] : undefined;
603
+ runWizard(specifiedFile).catch((err) => {
604
+ console.error(`\n Error: ${err instanceof Error ? err.message : String(err)}\n`);
173
605
  process.exit(1);
174
- }
606
+ });
175
607
  }
176
608
  main();
177
609
  //# sourceMappingURL=cli.js.map