init-xmcp 0.0.18

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.
Files changed (39) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/README.md +44 -0
  3. package/build-and-link.sh +73 -0
  4. package/dist/helpers/create-handler.d.ts +7 -0
  5. package/dist/helpers/create-handler.js +29 -0
  6. package/dist/helpers/create-tool.d.ts +6 -0
  7. package/dist/helpers/create-tool.js +53 -0
  8. package/dist/helpers/detect-framework.d.ts +3 -0
  9. package/dist/helpers/detect-framework.js +33 -0
  10. package/dist/helpers/generate-config.d.ts +7 -0
  11. package/dist/helpers/generate-config.js +29 -0
  12. package/dist/helpers/init.d.ts +10 -0
  13. package/dist/helpers/init.js +21 -0
  14. package/dist/helpers/install.d.ts +11 -0
  15. package/dist/helpers/install.js +44 -0
  16. package/dist/helpers/update-gitignore.d.ts +6 -0
  17. package/dist/helpers/update-gitignore.js +18 -0
  18. package/dist/helpers/update-package.d.ts +6 -0
  19. package/dist/helpers/update-package.js +28 -0
  20. package/dist/helpers/update-tsconfig.d.ts +6 -0
  21. package/dist/helpers/update-tsconfig.js +35 -0
  22. package/dist/index.d.ts +2 -0
  23. package/dist/index.js +239 -0
  24. package/dist/utils/check-node.d.ts +4 -0
  25. package/dist/utils/check-node.js +15 -0
  26. package/index.js +23 -0
  27. package/package.json +57 -0
  28. package/src/helpers/create-handler.ts +35 -0
  29. package/src/helpers/create-tool.ts +57 -0
  30. package/src/helpers/detect-framework.ts +62 -0
  31. package/src/helpers/generate-config.ts +37 -0
  32. package/src/helpers/init.ts +40 -0
  33. package/src/helpers/install.ts +59 -0
  34. package/src/helpers/update-gitignore.ts +23 -0
  35. package/src/helpers/update-package.ts +31 -0
  36. package/src/helpers/update-tsconfig.ts +45 -0
  37. package/src/index.ts +312 -0
  38. package/src/utils/check-node.ts +23 -0
  39. package/tsconfig.json +15 -0
@@ -0,0 +1,31 @@
1
+ import path from "path";
2
+ import fs from "fs-extra";
3
+
4
+ /**
5
+ * update package.json scripts to include xmcp build and dev commands
6
+ * @param projectPath - The root directory of the project
7
+ * @returns void
8
+ */
9
+ export function updatePackageJson(projectPath: string): void {
10
+ const packageJsonPath = path.join(projectPath, "package.json");
11
+ const packageJson = fs.readJsonSync(packageJsonPath);
12
+
13
+ if (!packageJson.scripts) {
14
+ packageJson.scripts = {};
15
+ }
16
+
17
+ // prepend commands to existing scripts - prevent overwriting
18
+ if (packageJson.scripts.build) {
19
+ packageJson.scripts.build = `xmcp build && ${packageJson.scripts.build}`;
20
+ } else {
21
+ packageJson.scripts.build = "xmcp build";
22
+ }
23
+
24
+ if (packageJson.scripts.dev) {
25
+ packageJson.scripts.dev = `xmcp dev & ${packageJson.scripts.dev}`;
26
+ } else {
27
+ packageJson.scripts.dev = "xmcp dev";
28
+ }
29
+
30
+ fs.writeJsonSync(packageJsonPath, packageJson, { spaces: 2 });
31
+ }
@@ -0,0 +1,45 @@
1
+ import path from "path";
2
+ import fs from "fs-extra";
3
+ import chalk from "chalk";
4
+
5
+ /**
6
+ * updates the tsconfig.json file to include the @xmcp/* alias for accessing the handler
7
+ * @param projectRoot - The root directory of the project
8
+ * @returns void
9
+ */
10
+ export function updateTsConfig(projectRoot: string) {
11
+ const tsconfigPath = path.join(projectRoot, "tsconfig.json");
12
+ const tsconfig = fs.readJsonSync(tsconfigPath);
13
+
14
+ if (!tsconfig) {
15
+ console.log(
16
+ chalk.yellow("No tsconfig.json file found - skipping alias configuration")
17
+ );
18
+ return;
19
+ }
20
+
21
+ // there's a file, but it's empty - we can add the compiler options and paths
22
+ if (!tsconfig.compilerOptions) {
23
+ tsconfig.compilerOptions = {};
24
+ }
25
+
26
+ if (!tsconfig.compilerOptions.paths) {
27
+ tsconfig.compilerOptions.paths = {};
28
+ }
29
+
30
+ // alias for accessing the handler, otherwise should be pointing to .xmcp/adapter when importing it
31
+ if (!tsconfig.compilerOptions.paths["@xmcp/*"]) {
32
+ tsconfig.compilerOptions.paths["@xmcp/*"] = ["./.xmcp/*"];
33
+ }
34
+
35
+ if (!tsconfig.include) {
36
+ tsconfig.include = [];
37
+ }
38
+
39
+ if (!tsconfig.include.includes("xmcp.d.ts")) {
40
+ // include xmcp.d.ts in the build
41
+ tsconfig.include.push("xmcp.d.ts");
42
+ }
43
+
44
+ fs.writeJsonSync(tsconfigPath, tsconfig, { spaces: 2 });
45
+ }
package/src/index.ts ADDED
@@ -0,0 +1,312 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Command } from "commander";
4
+ import chalk from "chalk";
5
+ import inquirer from "inquirer";
6
+ import { init } from "./helpers/init.js";
7
+ import {
8
+ detectFramework,
9
+ detectTypeScript,
10
+ } from "./helpers/detect-framework.js";
11
+ import { detectPackageManager } from "./helpers/install.js";
12
+ import fs from "fs-extra";
13
+ import path from "path";
14
+ import { checkNodeVersion } from "./utils/check-node.js";
15
+ import { fileURLToPath } from "url";
16
+
17
+ checkNodeVersion();
18
+
19
+ const __filename = fileURLToPath(import.meta.url);
20
+ const __dirname = path.dirname(__filename);
21
+
22
+ const packageJson = JSON.parse(
23
+ fs.readFileSync(path.join(__dirname, "../package.json"), "utf8")
24
+ );
25
+
26
+ const program = new Command()
27
+ .name("init-xmcp")
28
+ .description("Initialize xmcp in an existing project")
29
+ .version(
30
+ packageJson.version,
31
+ "-v, --version",
32
+ "Output the current version of init-xmcp."
33
+ )
34
+ .helpOption("-h, --help", "Display help message.")
35
+ .option("-y, --yes", "Skip confirmation prompts", false)
36
+ .option(
37
+ "--package-manager <manager>",
38
+ "Specify package manager (npm, yarn, pnpm)",
39
+ ""
40
+ )
41
+ .option("--tools-path <path>", "Specify custom tools path", "")
42
+ .option("--route-path <path>", "Specify custom route path", "")
43
+ .option("--skip-tools", "Skip tool creation", false)
44
+ .option("--skip-route", "Skip route creation", false)
45
+ .action(async (options) => {
46
+ console.log(chalk.bold(`\ninit-xmcp@${packageJson.version}`));
47
+
48
+ const projectRoot = process.cwd();
49
+
50
+ // check if it's a node js project
51
+ if (!fs.existsSync(path.join(projectRoot, "package.json"))) {
52
+ console.error(
53
+ chalk.red(
54
+ "Error: No package.json found. Please run this command in a Node.js project."
55
+ )
56
+ );
57
+ process.exit(1);
58
+ }
59
+
60
+ // check if xmcp is already initialized
61
+ if (
62
+ fs.existsSync(path.join(projectRoot, "xmcp.config.ts")) ||
63
+ fs.existsSync(path.join(projectRoot, "xmcp.config.json"))
64
+ ) {
65
+ console.error(
66
+ chalk.red("Error: xmcp is already initialized in this project.")
67
+ );
68
+ process.exit(1);
69
+ }
70
+
71
+ // detect framework package manager and language
72
+ const detectedFramework = detectFramework(projectRoot);
73
+ const detectedPackageManager = detectPackageManager(projectRoot);
74
+ const detectedTypeScript = detectTypeScript(projectRoot);
75
+
76
+ if (!detectedTypeScript) {
77
+ process.exit(1);
78
+ }
79
+
80
+ // determine tools path
81
+ let toolsPath: string | undefined;
82
+ if (!options.skipTools) {
83
+ if (options.toolsPath) {
84
+ toolsPath = options.toolsPath;
85
+ } else {
86
+ // check if src folder exists and default to src/tools if it does, otherwise tools
87
+ const hasSrcFolder = fs.existsSync(path.join(projectRoot, "src"));
88
+ toolsPath = hasSrcFolder ? "src/tools" : "tools";
89
+ }
90
+ }
91
+
92
+ // determine route path
93
+ let routePath: string | undefined;
94
+ if (detectedFramework === "nextjs" && !options.skipRoute) {
95
+ if (options.routePath) {
96
+ routePath = options.routePath;
97
+ } else {
98
+ // check if src folder exists and default to src/mcp if it does, otherwise mcp
99
+ const hasSrcFolder = fs.existsSync(path.join(projectRoot, "src"));
100
+ routePath = hasSrcFolder ? "src/app/mcp" : "app/mcp";
101
+ }
102
+ }
103
+
104
+ // determine package manager
105
+ let packageManager: "npm" | "yarn" | "pnpm";
106
+ if (detectedPackageManager) {
107
+ packageManager = detectedPackageManager;
108
+ } else if (options.packageManager) {
109
+ packageManager = options.packageManager as "npm" | "yarn" | "pnpm";
110
+ } else {
111
+ // no package manager detected, will prompt user
112
+ packageManager = "npm"; // default fallback
113
+ }
114
+
115
+ // interactive prompts if not --yes
116
+ if (!options.yes) {
117
+ console.log(chalk.blue("\n📋 xmcp Initialization Settings:"));
118
+ console.log(` Framework: ${chalk.cyan(detectedFramework)}`);
119
+
120
+ const prompts = [];
121
+
122
+ if (!options.skipTools) {
123
+ prompts.push({
124
+ type: "input",
125
+ name: "toolsPath",
126
+ message: "Tools directory path:",
127
+ default: toolsPath,
128
+ });
129
+ }
130
+
131
+ if (detectedFramework === "nextjs" && !options.skipRoute) {
132
+ prompts.push({
133
+ type: "input",
134
+ name: "routePath",
135
+ message: "Route directory path:",
136
+ default: routePath, // will not be undefined if detectedFramework is nextjs
137
+ });
138
+ }
139
+
140
+ if (!detectedPackageManager) {
141
+ prompts.push({
142
+ type: "list",
143
+ name: "packageManager",
144
+ message: "Package manager:",
145
+ choices: [
146
+ { name: "npm", value: "npm" },
147
+ { name: "yarn", value: "yarn" },
148
+ { name: "pnpm", value: "pnpm" },
149
+ ],
150
+ default: packageManager,
151
+ });
152
+ } else {
153
+ console.log(
154
+ chalk.green(` Package manager detected: ${packageManager}`)
155
+ );
156
+ }
157
+
158
+ prompts.push({
159
+ type: "confirm",
160
+ name: "confirmed",
161
+ message: "Continue with initialization?",
162
+ default: true,
163
+ });
164
+
165
+ const answers = await inquirer.prompt(prompts);
166
+
167
+ if (!answers.confirmed) {
168
+ console.log(chalk.yellow("❌ Aborting initialization."));
169
+ process.exit(0);
170
+ }
171
+
172
+ if (!options.skipTools) {
173
+ toolsPath = answers.toolsPath;
174
+ }
175
+ if (
176
+ detectedFramework === "nextjs" &&
177
+ !options.skipRoute &&
178
+ answers.routePath
179
+ ) {
180
+ routePath = answers.routePath;
181
+ }
182
+ if (!detectedPackageManager) {
183
+ packageManager = answers.packageManager;
184
+ }
185
+ }
186
+
187
+ // check if tools directory already exists and has content
188
+ if (toolsPath) {
189
+ const toolsDirPath = path.join(projectRoot, toolsPath);
190
+ if (fs.existsSync(toolsDirPath)) {
191
+ const toolsDirContent = fs.readdirSync(toolsDirPath);
192
+ if (toolsDirContent.length > 0) {
193
+ console.warn(
194
+ chalk.yellow(
195
+ `Warning: Tools directory "${toolsPath}" already exists and is not empty.`
196
+ )
197
+ );
198
+
199
+ if (!options.yes) {
200
+ const { overwrite } = await inquirer.prompt([
201
+ {
202
+ type: "confirm",
203
+ name: "overwrite",
204
+ message:
205
+ "Do you want to continue? Existing files will be preserved.",
206
+ default: true,
207
+ },
208
+ ]);
209
+
210
+ if (!overwrite) {
211
+ console.log(chalk.yellow("❌ Aborting initialization."));
212
+ process.exit(0);
213
+ }
214
+ }
215
+ }
216
+ }
217
+ }
218
+
219
+ // check if route directory already exists and has content
220
+ if (routePath) {
221
+ // means detectedFramework is nextjs
222
+ const routeDirPath = path.join(projectRoot, routePath);
223
+ if (fs.existsSync(routeDirPath)) {
224
+ const routeDirContent = fs.readdirSync(routeDirPath);
225
+ if (routeDirContent.length > 0) {
226
+ console.warn(
227
+ chalk.yellow(
228
+ `Warning: Route directory "${routePath}" already exists and is not empty.`
229
+ )
230
+ );
231
+
232
+ if (!options.yes) {
233
+ const { overwrite } = await inquirer.prompt([
234
+ {
235
+ type: "confirm",
236
+ name: "overwrite",
237
+ message:
238
+ "Do you want to continue? Existing files will be preserved.",
239
+ default: true,
240
+ },
241
+ ]);
242
+
243
+ if (!overwrite) {
244
+ console.log(chalk.yellow("❌ Aborting initialization."));
245
+ process.exit(0);
246
+ }
247
+ }
248
+ }
249
+ }
250
+ }
251
+
252
+ try {
253
+ console.log(chalk.blue("\n Initializing xmcp..."));
254
+
255
+ await init({
256
+ projectRoot,
257
+ framework: detectedFramework,
258
+ toolsPath,
259
+ routePath,
260
+ packageManager,
261
+ });
262
+
263
+ console.log(chalk.green("\n✔ xmcp initialized successfully!"));
264
+ console.log(chalk.blue("\n❯ Files created:"));
265
+ console.log(` • xmcp.config.ts`);
266
+
267
+ if (toolsPath) {
268
+ console.log(` • ${toolsPath}/greet.ts`);
269
+ }
270
+
271
+ if (routePath) {
272
+ console.log(` • ${routePath}/route.ts`);
273
+ }
274
+
275
+ console.log(chalk.blue("\n❯ Files updated:"));
276
+ console.log(` • package.json`);
277
+ console.log(` • tsconfig.json`);
278
+
279
+ console.log(chalk.blue("\nNext steps:"));
280
+
281
+ // code integration for express projects (default)
282
+ if (detectedFramework !== "nextjs") {
283
+ const integrationCode = `import { xmcpHandler } from '@xmcp/adapter';
284
+
285
+ myApp.post("/mcp", xmcpHandler);
286
+ myApp.get("/mcp", xmcpHandler);`;
287
+
288
+ const lines = integrationCode.split("\n");
289
+ const maxLength = Math.max(...lines.map((line) => line.length)) + 2;
290
+
291
+ console.log(
292
+ "\nTo get started with the xmcpHandler in your Express application, add this code to your server:\n"
293
+ );
294
+ console.log(chalk.green(chalk.bgBlack(` ${" ".repeat(maxLength)}`)));
295
+ lines.forEach((line) => {
296
+ const padding = " ".repeat(maxLength - line.length);
297
+ console.log(chalk.green(chalk.bgBlack(` ${line}${padding}`)));
298
+ });
299
+ console.log(chalk.green(chalk.bgBlack(` ${" ".repeat(maxLength)}`)));
300
+ }
301
+
302
+ console.log(
303
+ ` \nRun "${packageManager} run dev" to start the development server\n`
304
+ );
305
+ } catch (error) {
306
+ console.error(chalk.red("\nFailed to initialize xmcp:"));
307
+ console.error(error);
308
+ process.exit(1);
309
+ }
310
+ });
311
+
312
+ program.parse();
@@ -0,0 +1,23 @@
1
+ import chalk from "chalk";
2
+
3
+ /**
4
+ * Check if the Node.js version is supported
5
+ */
6
+ export function checkNodeVersion(): void {
7
+ const nodeVersion = process.version;
8
+ const majorVersion = parseInt(nodeVersion.slice(1).split(".")[0]);
9
+
10
+ if (majorVersion < 20) {
11
+ console.error(
12
+ chalk.red(`❌ Node.js version ${nodeVersion} is not supported.`)
13
+ );
14
+ console.error(chalk.red(`xmcp requires Node.js 20 or higher.`));
15
+ console.error(
16
+ chalk.yellow(`Please upgrade your Node.js version and try again.`)
17
+ );
18
+ console.error(
19
+ chalk.blue(`Visit https://nodejs.org/ to download the latest version.`)
20
+ );
21
+ process.exit(1);
22
+ }
23
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "esModuleInterop": true,
7
+ "outDir": "./dist",
8
+ "strict": true,
9
+ "declaration": true,
10
+ "skipLibCheck": true,
11
+ "rootDir": "./src"
12
+ },
13
+ "include": ["src/**/*"],
14
+ "exclude": ["node_modules", "dist", "templates"]
15
+ }