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