init-xmcp 1.2.0 → 1.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > init-xmcp@1.2.0 build /home/runner/work/xmcp/xmcp/packages/init-xmcp
2
+ > init-xmcp@1.4.0 build /home/runner/work/xmcp/xmcp/packages/init-xmcp
3
3
  > tsc
4
4
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # init-xmcp
2
2
 
3
+ ## 1.4.0
4
+
5
+ ## 1.3.0
6
+
7
+ ### Minor Changes
8
+
9
+ - a1f4d67: Add a TanStack Start adapter for React applications on Node.js and Cloudflare Workers, with ESM output, stateless request handling, and automatic setup through init-xmcp.
10
+
3
11
  ## 1.2.0
4
12
 
5
13
  ## 1.1.3
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  # init-xmcp
17
17
 
18
- Initialize `xmcp` applications with one command on top of Next.js and Express projects. Unlock the power of `xmcp` discovery and integration with your existing codebase.
18
+ Initialize `xmcp` applications with one command on top of Next.js, TanStack Start, NestJS, Express, and Fastify projects. Unlock the power of `xmcp` discovery and integration with your existing codebase.
19
19
 
20
20
  ## Usage
21
21
 
@@ -31,9 +31,24 @@ npx init-xmcp@latest
31
31
  - `--tools-path <path>`: Specify custom tools path (default: "")
32
32
  - `--route-path <path>`: Specify custom route path (default: "")
33
33
  - `--skip-tools`: Skip tool creation (default: false)
34
+ - `--cf`: Build the TanStack Start adapter for Cloudflare Workers (also inferred from `@cloudflare/vite-plugin`).
34
35
  - `--skip-route`: Skip route creation (default: false)
35
36
  - `-h, --help`: Display help message.
36
37
 
38
+ ## TanStack Start
39
+
40
+ React Start projects are detected through `@tanstack/react-start`. Initialization
41
+ creates `src/routes/mcp.ts`, discovers handlers in the configured directories, and
42
+ builds the adapter before Vite starts. `--route-path src/routes/api` creates an
43
+ `/api/mcp` endpoint. Existing route files are preserved; use `--skip-route` to
44
+ integrate manually. All options work with `--yes`.
45
+
46
+ Use `--cf` for Workers builds if the Cloudflare Vite plugin is not installed yet.
47
+ Your application owns its hosting setup, including Vite and Wrangler configuration;
48
+ Workers require `nodejs_compat`. See the
49
+ [TanStack Start guide](https://xmcp.dev/docs/adapters/tanstack) for Node and Workers
50
+ examples, manual setup, authentication, and CORS.
51
+
37
52
  ## Getting Started
38
53
 
39
54
  - Visit [xmcp.dev](https://xmcp.dev) to learn more about the project.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,114 @@
1
+ import { afterEach, beforeEach, describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "fs-extra";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { spawnSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import { detectFramework } from "../helpers/detect-framework.js";
9
+ import { createTanstackRoute, detectTanstackCloudflare, getTanstackRoute, } from "../helpers/create-tanstack-route.js";
10
+ import { updatePackageJson } from "../helpers/update-package.js";
11
+ import { generateConfig } from "../helpers/generate-config.js";
12
+ describe("TanStack initialization", () => {
13
+ let root;
14
+ beforeEach(() => {
15
+ root = fs.mkdtempSync(path.join(os.tmpdir(), "xmcp-tanstack-"));
16
+ });
17
+ afterEach(() => fs.removeSync(root));
18
+ it("detects React Start in either dependency section before Fastify", () => {
19
+ for (const section of ["dependencies", "devDependencies"]) {
20
+ fs.writeJsonSync(path.join(root, "package.json"), {
21
+ [section]: { "@tanstack/react-start": "1", fastify: "5" },
22
+ });
23
+ assert.equal(detectFramework(root), "tanstack");
24
+ assert.equal(detectTanstackCloudflare(root), false);
25
+ }
26
+ fs.writeJsonSync(path.join(root, "package.json"), {
27
+ devDependencies: { "@cloudflare/vite-plugin": "1" },
28
+ });
29
+ assert.equal(detectTanstackCloudflare(root), true);
30
+ });
31
+ it("generates default and nested routes with resolvable relative imports", () => {
32
+ for (const [directory, endpoint] of [
33
+ ["src/routes", "/mcp"],
34
+ ["src/routes/api", "/api/mcp"],
35
+ ["app/routes", "/mcp"],
36
+ ]) {
37
+ createTanstackRoute(root, directory);
38
+ const route = getTanstackRoute(root, directory);
39
+ assert.equal(route.endpoint, endpoint);
40
+ assert.equal(path.resolve(path.dirname(route.file), route.adapterImport), path.join(root, ".xmcp/adapter/index.js"));
41
+ const content = fs.readFileSync(route.file, "utf8");
42
+ assert.ok(content.includes(`createFileRoute("${endpoint}")`));
43
+ for (const method of ["GET", "POST", "DELETE"])
44
+ assert.ok(content.includes(`${method}: ({ request })`));
45
+ }
46
+ });
47
+ it("preserves an existing route", () => {
48
+ const file = path.join(root, "src/routes/mcp.ts");
49
+ fs.outputFileSync(file, "existing route");
50
+ assert.throws(() => createTanstackRoute(root, "src/routes"), /--skip-route/);
51
+ assert.equal(fs.readFileSync(file, "utf8"), "existing route");
52
+ });
53
+ it("builds the adapter before Vite and retains host commands for both platforms", () => {
54
+ for (const cloudflare of [false, true]) {
55
+ fs.writeJsonSync(path.join(root, "package.json"), {
56
+ scripts: {
57
+ dev: "vite dev --port 4321",
58
+ build: "vite build",
59
+ deploy: "wrangler deploy",
60
+ },
61
+ });
62
+ updatePackageJson(root, { framework: "tanstack", cloudflare });
63
+ const { scripts } = fs.readJsonSync(path.join(root, "package.json"));
64
+ const flag = cloudflare ? " --cf" : "";
65
+ assert.equal(scripts.dev, `xmcp build${flag} && (xmcp dev${flag} & vite dev --port 4321)`);
66
+ assert.equal(scripts.build, `xmcp build${flag} && vite build`);
67
+ assert.equal(scripts.deploy, "wrangler deploy");
68
+ }
69
+ });
70
+ it("runs noninteractively with skip flags and an explicit Workers target", () => {
71
+ fs.writeJsonSync(path.join(root, "package.json"), {
72
+ dependencies: { "@tanstack/react-start": "1" },
73
+ devDependencies: { typescript: "5" },
74
+ scripts: { dev: "vite dev", build: "vite build" },
75
+ });
76
+ fs.writeJsonSync(path.join(root, "tsconfig.json"), { include: ["src"] });
77
+ // Stub dependency installation; this test exercises the real CLI's scaffolding.
78
+ const bin = path.join(root, "bin");
79
+ fs.ensureDirSync(bin);
80
+ fs.writeFileSync(path.join(bin, "npm"), "#!/bin/sh\nexit 0\n", {
81
+ mode: 0o755,
82
+ });
83
+ const result = spawnSync(process.execPath, [
84
+ fileURLToPath(new URL("../index.js", import.meta.url)),
85
+ "--yes",
86
+ "--package-manager",
87
+ "npm",
88
+ "--cf",
89
+ "--skip-route",
90
+ "--skip-tools",
91
+ "--skip-prompts",
92
+ "--skip-resources",
93
+ ], {
94
+ cwd: root,
95
+ encoding: "utf8",
96
+ env: {
97
+ ...process.env,
98
+ PATH: `${bin}${path.delimiter}${process.env.PATH}`,
99
+ },
100
+ });
101
+ assert.equal(result.status, 0, result.stdout + result.stderr);
102
+ assert.equal(fs.existsSync(path.join(root, "src/routes/mcp.ts")), false);
103
+ assert.match(fs.readFileSync(path.join(root, "xmcp.config.ts"), "utf8"), /adapter: "tanstack"/);
104
+ assert.equal(fs.readJsonSync(path.join(root, "package.json")).scripts.build, "xmcp build --cf && vite build");
105
+ });
106
+ it("configures TanStack with a custom endpoint and deferred host typechecking", () => {
107
+ generateConfig(root, "tanstack", "src/tools", undefined, undefined, "/api/mcp");
108
+ const config = fs.readFileSync(path.join(root, "xmcp.config.ts"), "utf8");
109
+ assert.match(config, /adapter: "tanstack"/);
110
+ assert.match(config, /endpoint: "\/api\/mcp"/);
111
+ assert.match(config, /skipTypeCheck: true/);
112
+ assert.match(config, /prompts: false/);
113
+ });
114
+ });
@@ -0,0 +1,9 @@
1
+ /** --route-path is a directory; the MCP endpoint is its mcp.ts child. */
2
+ export declare function getTanstackRoute(projectRoot: string, routeDirectory: string): {
3
+ file: string;
4
+ endpoint: string;
5
+ adapterImport: string;
6
+ };
7
+ export declare function assertTanstackRouteAvailable(projectRoot: string, routeDirectory: string): void;
8
+ export declare function createTanstackRoute(projectRoot: string, routeDirectory: string): void;
9
+ export declare function detectTanstackCloudflare(projectRoot: string): boolean;
@@ -0,0 +1,46 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+ /** --route-path is a directory; the MCP endpoint is its mcp.ts child. */
4
+ export function getTanstackRoute(projectRoot, routeDirectory) {
5
+ const file = path.resolve(projectRoot, routeDirectory, "mcp.ts");
6
+ const directory = routeDirectory.replace(/\\/g, "/").replace(/\/$/, "");
7
+ const routesIndex = directory.split("/").lastIndexOf("routes");
8
+ const segments = routesIndex < 0 ? [] : directory.split("/").slice(routesIndex + 1);
9
+ const endpoint = `/${[...segments, "mcp"].join("/")}`;
10
+ let adapterImport = path
11
+ .relative(path.dirname(file), path.join(projectRoot, ".xmcp/adapter/index.js"))
12
+ .split(path.sep)
13
+ .join("/");
14
+ if (!adapterImport.startsWith("."))
15
+ adapterImport = `./${adapterImport}`;
16
+ return { file, endpoint, adapterImport };
17
+ }
18
+ export function assertTanstackRouteAvailable(projectRoot, routeDirectory) {
19
+ const { file } = getTanstackRoute(projectRoot, routeDirectory);
20
+ if (fs.existsSync(file)) {
21
+ throw new Error(`MCP route already exists: ${file}. Use --skip-route to keep it, or choose another --route-path.`);
22
+ }
23
+ }
24
+ export function createTanstackRoute(projectRoot, routeDirectory) {
25
+ assertTanstackRouteAvailable(projectRoot, routeDirectory);
26
+ const { file, endpoint, adapterImport } = getTanstackRoute(projectRoot, routeDirectory);
27
+ fs.ensureDirSync(path.dirname(file));
28
+ fs.writeFileSync(file, `import { createFileRoute } from "@tanstack/react-router";
29
+ import { xmcpHandler } from ${JSON.stringify(adapterImport)};
30
+
31
+ export const Route = createFileRoute(${JSON.stringify(endpoint)})({
32
+ server: {
33
+ handlers: {
34
+ GET: ({ request }) => xmcpHandler(request),
35
+ POST: ({ request }) => xmcpHandler(request),
36
+ DELETE: ({ request }) => xmcpHandler(request),
37
+ },
38
+ },
39
+ });
40
+ `, { flag: "wx" });
41
+ }
42
+ export function detectTanstackCloudflare(projectRoot) {
43
+ const pkg = fs.readJsonSync(path.join(projectRoot, "package.json"));
44
+ return !!(pkg.dependencies?.["@cloudflare/vite-plugin"] ||
45
+ pkg.devDependencies?.["@cloudflare/vite-plugin"]);
46
+ }
@@ -1,3 +1,3 @@
1
- export type Framework = "nextjs" | "nestjs" | "express" | "fastify";
1
+ export type Framework = "nextjs" | "nestjs" | "express" | "fastify" | "tanstack";
2
2
  export declare function detectFramework(projectRoot: string): Framework;
3
3
  export declare function detectTypeScript(projectRoot: string): boolean;
@@ -13,6 +13,10 @@ export function detectFramework(projectRoot) {
13
13
  if (packageJson.dependencies?.next || packageJson.devDependencies?.next) {
14
14
  return "nextjs";
15
15
  }
16
+ if (packageJson.dependencies?.["@tanstack/react-start"] ||
17
+ packageJson.devDependencies?.["@tanstack/react-start"]) {
18
+ return "tanstack";
19
+ }
16
20
  // Check for Fastify
17
21
  if (packageJson.dependencies?.fastify ||
18
22
  packageJson.devDependencies?.fastify) {
@@ -4,4 +4,4 @@
4
4
  * @param frameworkAdapter - Selected framework adapter
5
5
  * @param toolsPath - Optional path for tools directory
6
6
  */
7
- export declare function generateConfig(projectPath: string, frameworkAdapter: string, toolsPath?: string, promptsPath?: string, resourcesPath?: string): void;
7
+ export declare function generateConfig(projectPath: string, frameworkAdapter: string, toolsPath?: string, promptsPath?: string, resourcesPath?: string, endpoint?: string): void;
@@ -6,11 +6,11 @@ import fs from "fs-extra";
6
6
  * @param frameworkAdapter - Selected framework adapter
7
7
  * @param toolsPath - Optional path for tools directory
8
8
  */
9
- export function generateConfig(projectPath, frameworkAdapter, toolsPath, promptsPath, resourcesPath) {
9
+ export function generateConfig(projectPath, frameworkAdapter, toolsPath, promptsPath, resourcesPath, endpoint) {
10
10
  let configContent = `import { type XmcpConfig } from "xmcp";
11
11
 
12
12
  const config: XmcpConfig = {
13
- http: true,
13
+ http: ${endpoint ? `{ endpoint: ${JSON.stringify(endpoint)} }` : "true"},
14
14
  experimental: {
15
15
  adapter: "${frameworkAdapter}",
16
16
  },`;
@@ -20,7 +20,7 @@ const config: XmcpConfig = {
20
20
  prompts: ${promptsPath ? `"${promptsPath}"` : "false"},
21
21
  resources: ${resourcesPath ? `"${resourcesPath}"` : "false"},
22
22
  },`;
23
- if (frameworkAdapter === "nextjs") {
23
+ if (frameworkAdapter === "nextjs" || frameworkAdapter === "tanstack") {
24
24
  configContent += `
25
25
  typescript: {
26
26
  skipTypeCheck: true,
@@ -1,5 +1,6 @@
1
1
  import { Framework } from "./detect-framework.js";
2
2
  interface InitOptions {
3
+ cloudflare?: boolean;
3
4
  projectRoot: string;
4
5
  framework: Framework;
5
6
  toolsPath: string | undefined;
@@ -8,11 +8,18 @@ import { createRoute } from "./create-handler.js";
8
8
  import { createPrompt } from "./create-prompt.js";
9
9
  import { createResources } from "./create-resources.js";
10
10
  import { createNestJsModule } from "./create-nestjs-module.js";
11
+ import { assertTanstackRouteAvailable, createTanstackRoute, getTanstackRoute, } from "./create-tanstack-route.js";
11
12
  export async function init(options) {
12
- const { projectRoot, framework, toolsPath, promptsPath, resourcesPath, routePath, packageManager, version, } = options;
13
- generateConfig(projectRoot, framework, toolsPath, promptsPath, resourcesPath);
13
+ const { projectRoot, framework, toolsPath, promptsPath, resourcesPath, routePath, packageManager, version, cloudflare, } = options;
14
+ if (framework === "tanstack" && routePath) {
15
+ assertTanstackRouteAvailable(projectRoot, routePath);
16
+ }
17
+ const endpoint = framework === "tanstack" && routePath
18
+ ? getTanstackRoute(projectRoot, routePath).endpoint
19
+ : undefined;
20
+ generateConfig(projectRoot, framework, toolsPath, promptsPath, resourcesPath, endpoint);
14
21
  await install(projectRoot, packageManager, version);
15
- updatePackageJson(projectRoot);
22
+ updatePackageJson(projectRoot, { framework, cloudflare });
16
23
  updateTsConfig(projectRoot);
17
24
  updateGitignore(projectRoot);
18
25
  if (toolsPath) {
@@ -27,6 +34,9 @@ export async function init(options) {
27
34
  if (framework === "nextjs" && routePath) {
28
35
  createRoute(projectRoot, routePath);
29
36
  }
37
+ if (framework === "tanstack" && routePath) {
38
+ createTanstackRoute(projectRoot, routePath);
39
+ }
30
40
  if (framework === "nestjs") {
31
41
  createNestJsModule(projectRoot);
32
42
  }
@@ -1,6 +1,10 @@
1
+ import type { Framework } from "./detect-framework.js";
1
2
  /**
2
3
  * update package.json scripts to include xmcp build and dev commands
3
4
  * @param projectPath - The root directory of the project
4
5
  * @returns void
5
6
  */
6
- export declare function updatePackageJson(projectPath: string): void;
7
+ export declare function updatePackageJson(projectPath: string, options?: {
8
+ framework?: Framework;
9
+ cloudflare?: boolean;
10
+ }): void;
@@ -5,7 +5,7 @@ import fs from "fs-extra";
5
5
  * @param projectPath - The root directory of the project
6
6
  * @returns void
7
7
  */
8
- export function updatePackageJson(projectPath) {
8
+ export function updatePackageJson(projectPath, options = {}) {
9
9
  const packageJsonPath = path.join(projectPath, "package.json");
10
10
  const packageJson = fs.readJsonSync(packageJsonPath);
11
11
  if (!packageJson.scripts) {
@@ -13,18 +13,26 @@ export function updatePackageJson(projectPath) {
13
13
  }
14
14
  packageJson.devDependencies = packageJson.devDependencies ?? {};
15
15
  packageJson.devDependencies["@xmcp-dev/compiler"] ??= "latest";
16
+ const tanstack = options.framework === "tanstack";
17
+ const platformFlag = tanstack && options.cloudflare ? " --cf" : "";
18
+ const build = `xmcp build${platformFlag}`;
19
+ const dev = `xmcp dev${platformFlag}`;
16
20
  // prepend commands to existing scripts - prevent overwriting
17
21
  if (packageJson.scripts.build) {
18
- packageJson.scripts.build = `xmcp build && ${packageJson.scripts.build}`;
22
+ packageJson.scripts.build = `${build} && ${packageJson.scripts.build}`;
19
23
  }
20
24
  else {
21
- packageJson.scripts.build = "xmcp build";
25
+ packageJson.scripts.build = tanstack ? `${build} && vite build` : build;
22
26
  }
23
27
  if (packageJson.scripts.dev) {
24
- packageJson.scripts.dev = `xmcp dev & ${packageJson.scripts.dev}`;
28
+ packageJson.scripts.dev = tanstack
29
+ ? `${build} && (${dev} & ${packageJson.scripts.dev})`
30
+ : `${dev} & ${packageJson.scripts.dev}`;
25
31
  }
26
32
  else {
27
- packageJson.scripts.dev = "xmcp dev";
33
+ packageJson.scripts.dev = tanstack
34
+ ? `${build} && (${dev} & vite dev)`
35
+ : dev;
28
36
  }
29
37
  fs.writeJsonSync(packageJsonPath, packageJson, { spaces: 2 });
30
38
  }
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ import { Command } from "commander";
3
3
  import chalk from "chalk";
4
4
  import inquirer from "inquirer";
5
5
  import { init } from "./helpers/init.js";
6
+ import { detectTanstackCloudflare } from "./helpers/create-tanstack-route.js";
6
7
  import { detectFramework, detectTypeScript, } from "./helpers/detect-framework.js";
7
8
  import { detectPackageManager } from "./helpers/install.js";
8
9
  import fs from "fs-extra";
@@ -27,6 +28,7 @@ const program = new Command()
27
28
  .option("--skip-tools", "Skip tool creation", false)
28
29
  .option("--skip-prompts", "Skip prompt creation", false)
29
30
  .option("--skip-resources", "Skip resource creation", false)
31
+ .option("--cf", "Build the TanStack Start adapter for Cloudflare Workers", false)
30
32
  .option("--skip-route", "Skip route creation", false)
31
33
  .action(async (options) => {
32
34
  console.log(chalk.bold(`\ninit-xmcp@${packageJson.version}`));
@@ -97,6 +99,11 @@ const program = new Command()
97
99
  routePath = hasSrcFolder ? "src/app/mcp" : "app/mcp";
98
100
  }
99
101
  }
102
+ if (detectedFramework === "tanstack" && !options.skipRoute) {
103
+ routePath = options.routePath || "src/routes";
104
+ }
105
+ const cloudflare = detectedFramework === "tanstack" &&
106
+ (options.cf || detectTanstackCloudflare(projectRoot));
100
107
  // determine package manager
101
108
  let packageManager;
102
109
  if (detectedPackageManager) {
@@ -144,12 +151,13 @@ const program = new Command()
144
151
  choices: componentChoices,
145
152
  });
146
153
  }
147
- if (detectedFramework === "nextjs" && !options.skipRoute) {
154
+ if ((detectedFramework === "nextjs" || detectedFramework === "tanstack") &&
155
+ !options.skipRoute) {
148
156
  prompts.push({
149
157
  type: "input",
150
158
  name: "routePath",
151
159
  message: "Route directory path:",
152
- default: routePath, // will not be undefined if detectedFramework is nextjs
160
+ default: routePath,
153
161
  });
154
162
  }
155
163
  if (!detectedPackageManager) {
@@ -192,7 +200,7 @@ const program = new Command()
192
200
  resourcesPath = undefined;
193
201
  }
194
202
  }
195
- if (detectedFramework === "nextjs" &&
203
+ if ((detectedFramework === "nextjs" || detectedFramework === "tanstack") &&
196
204
  !options.skipRoute &&
197
205
  answers.routePath) {
198
206
  routePath = answers.routePath;
@@ -226,8 +234,8 @@ const program = new Command()
226
234
  }
227
235
  }
228
236
  // check if route directory already exists and has content
229
- if (routePath) {
230
- // means detectedFramework is nextjs
237
+ if (routePath && detectedFramework === "nextjs") {
238
+ // Existing Next.js route-directory handling.
231
239
  const routeDirPath = path.join(projectRoot, routePath);
232
240
  if (fs.existsSync(routeDirPath)) {
233
241
  const routeDirContent = fs.readdirSync(routeDirPath);
@@ -261,6 +269,7 @@ const program = new Command()
261
269
  routePath,
262
270
  packageManager,
263
271
  version: packageJson.version,
272
+ cloudflare,
264
273
  });
265
274
  console.log(chalk.green("\n✔ xmcp initialized successfully!"));
266
275
  console.log(chalk.blue("\n❯ Files created:"));
@@ -276,7 +285,7 @@ const program = new Command()
276
285
  console.log(` • ${resourcesPath}/(users)/[userId]/profile.ts`);
277
286
  }
278
287
  if (routePath) {
279
- console.log(` • ${routePath}/route.ts`);
288
+ console.log(` • ${routePath}/${detectedFramework === "tanstack" ? "mcp.ts" : "route.ts"}`);
280
289
  }
281
290
  if (detectedFramework === "nestjs") {
282
291
  const hasSrcFolder = fs.existsSync(path.join(projectRoot, "src"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "init-xmcp",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "author": {
5
5
  "name": "xmcp",
6
6
  "email": "support@xmcp.dev",
@@ -0,0 +1,151 @@
1
+ import { afterEach, beforeEach, describe, it } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "fs-extra";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { spawnSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import { detectFramework } from "../helpers/detect-framework.js";
9
+ import {
10
+ createTanstackRoute,
11
+ detectTanstackCloudflare,
12
+ getTanstackRoute,
13
+ } from "../helpers/create-tanstack-route.js";
14
+ import { updatePackageJson } from "../helpers/update-package.js";
15
+ import { generateConfig } from "../helpers/generate-config.js";
16
+
17
+ describe("TanStack initialization", () => {
18
+ let root: string;
19
+ beforeEach(() => {
20
+ root = fs.mkdtempSync(path.join(os.tmpdir(), "xmcp-tanstack-"));
21
+ });
22
+ afterEach(() => fs.removeSync(root));
23
+
24
+ it("detects React Start in either dependency section before Fastify", () => {
25
+ for (const section of ["dependencies", "devDependencies"]) {
26
+ fs.writeJsonSync(path.join(root, "package.json"), {
27
+ [section]: { "@tanstack/react-start": "1", fastify: "5" },
28
+ });
29
+ assert.equal(detectFramework(root), "tanstack");
30
+ assert.equal(detectTanstackCloudflare(root), false);
31
+ }
32
+ fs.writeJsonSync(path.join(root, "package.json"), {
33
+ devDependencies: { "@cloudflare/vite-plugin": "1" },
34
+ });
35
+ assert.equal(detectTanstackCloudflare(root), true);
36
+ });
37
+
38
+ it("generates default and nested routes with resolvable relative imports", () => {
39
+ for (const [directory, endpoint] of [
40
+ ["src/routes", "/mcp"],
41
+ ["src/routes/api", "/api/mcp"],
42
+ ["app/routes", "/mcp"],
43
+ ]) {
44
+ createTanstackRoute(root, directory);
45
+ const route = getTanstackRoute(root, directory);
46
+ assert.equal(route.endpoint, endpoint);
47
+ assert.equal(
48
+ path.resolve(path.dirname(route.file), route.adapterImport),
49
+ path.join(root, ".xmcp/adapter/index.js")
50
+ );
51
+ const content = fs.readFileSync(route.file, "utf8");
52
+ assert.ok(content.includes(`createFileRoute("${endpoint}")`));
53
+ for (const method of ["GET", "POST", "DELETE"])
54
+ assert.ok(content.includes(`${method}: ({ request })`));
55
+ }
56
+ });
57
+
58
+ it("preserves an existing route", () => {
59
+ const file = path.join(root, "src/routes/mcp.ts");
60
+ fs.outputFileSync(file, "existing route");
61
+ assert.throws(
62
+ () => createTanstackRoute(root, "src/routes"),
63
+ /--skip-route/
64
+ );
65
+ assert.equal(fs.readFileSync(file, "utf8"), "existing route");
66
+ });
67
+
68
+ it("builds the adapter before Vite and retains host commands for both platforms", () => {
69
+ for (const cloudflare of [false, true]) {
70
+ fs.writeJsonSync(path.join(root, "package.json"), {
71
+ scripts: {
72
+ dev: "vite dev --port 4321",
73
+ build: "vite build",
74
+ deploy: "wrangler deploy",
75
+ },
76
+ });
77
+ updatePackageJson(root, { framework: "tanstack", cloudflare });
78
+ const { scripts } = fs.readJsonSync(path.join(root, "package.json"));
79
+ const flag = cloudflare ? " --cf" : "";
80
+ assert.equal(
81
+ scripts.dev,
82
+ `xmcp build${flag} && (xmcp dev${flag} & vite dev --port 4321)`
83
+ );
84
+ assert.equal(scripts.build, `xmcp build${flag} && vite build`);
85
+ assert.equal(scripts.deploy, "wrangler deploy");
86
+ }
87
+ });
88
+
89
+ it("runs noninteractively with skip flags and an explicit Workers target", () => {
90
+ fs.writeJsonSync(path.join(root, "package.json"), {
91
+ dependencies: { "@tanstack/react-start": "1" },
92
+ devDependencies: { typescript: "5" },
93
+ scripts: { dev: "vite dev", build: "vite build" },
94
+ });
95
+ fs.writeJsonSync(path.join(root, "tsconfig.json"), { include: ["src"] });
96
+ // Stub dependency installation; this test exercises the real CLI's scaffolding.
97
+ const bin = path.join(root, "bin");
98
+ fs.ensureDirSync(bin);
99
+ fs.writeFileSync(path.join(bin, "npm"), "#!/bin/sh\nexit 0\n", {
100
+ mode: 0o755,
101
+ });
102
+ const result = spawnSync(
103
+ process.execPath,
104
+ [
105
+ fileURLToPath(new URL("../index.js", import.meta.url)),
106
+ "--yes",
107
+ "--package-manager",
108
+ "npm",
109
+ "--cf",
110
+ "--skip-route",
111
+ "--skip-tools",
112
+ "--skip-prompts",
113
+ "--skip-resources",
114
+ ],
115
+ {
116
+ cwd: root,
117
+ encoding: "utf8",
118
+ env: {
119
+ ...process.env,
120
+ PATH: `${bin}${path.delimiter}${process.env.PATH}`,
121
+ },
122
+ }
123
+ );
124
+ assert.equal(result.status, 0, result.stdout + result.stderr);
125
+ assert.equal(fs.existsSync(path.join(root, "src/routes/mcp.ts")), false);
126
+ assert.match(
127
+ fs.readFileSync(path.join(root, "xmcp.config.ts"), "utf8"),
128
+ /adapter: "tanstack"/
129
+ );
130
+ assert.equal(
131
+ fs.readJsonSync(path.join(root, "package.json")).scripts.build,
132
+ "xmcp build --cf && vite build"
133
+ );
134
+ });
135
+
136
+ it("configures TanStack with a custom endpoint and deferred host typechecking", () => {
137
+ generateConfig(
138
+ root,
139
+ "tanstack",
140
+ "src/tools",
141
+ undefined,
142
+ undefined,
143
+ "/api/mcp"
144
+ );
145
+ const config = fs.readFileSync(path.join(root, "xmcp.config.ts"), "utf8");
146
+ assert.match(config, /adapter: "tanstack"/);
147
+ assert.match(config, /endpoint: "\/api\/mcp"/);
148
+ assert.match(config, /skipTypeCheck: true/);
149
+ assert.match(config, /prompts: false/);
150
+ });
151
+ });
@@ -0,0 +1,70 @@
1
+ import fs from "fs-extra";
2
+ import path from "node:path";
3
+
4
+ /** --route-path is a directory; the MCP endpoint is its mcp.ts child. */
5
+ export function getTanstackRoute(projectRoot: string, routeDirectory: string) {
6
+ const file = path.resolve(projectRoot, routeDirectory, "mcp.ts");
7
+ const directory = routeDirectory.replace(/\\/g, "/").replace(/\/$/, "");
8
+ const routesIndex = directory.split("/").lastIndexOf("routes");
9
+ const segments =
10
+ routesIndex < 0 ? [] : directory.split("/").slice(routesIndex + 1);
11
+ const endpoint = `/${[...segments, "mcp"].join("/")}`;
12
+ let adapterImport = path
13
+ .relative(
14
+ path.dirname(file),
15
+ path.join(projectRoot, ".xmcp/adapter/index.js")
16
+ )
17
+ .split(path.sep)
18
+ .join("/");
19
+ if (!adapterImport.startsWith(".")) adapterImport = `./${adapterImport}`;
20
+ return { file, endpoint, adapterImport };
21
+ }
22
+
23
+ export function assertTanstackRouteAvailable(
24
+ projectRoot: string,
25
+ routeDirectory: string
26
+ ) {
27
+ const { file } = getTanstackRoute(projectRoot, routeDirectory);
28
+ if (fs.existsSync(file)) {
29
+ throw new Error(
30
+ `MCP route already exists: ${file}. Use --skip-route to keep it, or choose another --route-path.`
31
+ );
32
+ }
33
+ }
34
+
35
+ export function createTanstackRoute(
36
+ projectRoot: string,
37
+ routeDirectory: string
38
+ ): void {
39
+ assertTanstackRouteAvailable(projectRoot, routeDirectory);
40
+ const { file, endpoint, adapterImport } = getTanstackRoute(
41
+ projectRoot,
42
+ routeDirectory
43
+ );
44
+ fs.ensureDirSync(path.dirname(file));
45
+ fs.writeFileSync(
46
+ file,
47
+ `import { createFileRoute } from "@tanstack/react-router";
48
+ import { xmcpHandler } from ${JSON.stringify(adapterImport)};
49
+
50
+ export const Route = createFileRoute(${JSON.stringify(endpoint)})({
51
+ server: {
52
+ handlers: {
53
+ GET: ({ request }) => xmcpHandler(request),
54
+ POST: ({ request }) => xmcpHandler(request),
55
+ DELETE: ({ request }) => xmcpHandler(request),
56
+ },
57
+ },
58
+ });
59
+ `,
60
+ { flag: "wx" }
61
+ );
62
+ }
63
+
64
+ export function detectTanstackCloudflare(projectRoot: string): boolean {
65
+ const pkg = fs.readJsonSync(path.join(projectRoot, "package.json"));
66
+ return !!(
67
+ pkg.dependencies?.["@cloudflare/vite-plugin"] ||
68
+ pkg.devDependencies?.["@cloudflare/vite-plugin"]
69
+ );
70
+ }
@@ -3,7 +3,12 @@ import fs from "fs-extra";
3
3
  import path from "path";
4
4
  import { readTsConfigFile } from "../utils/read-config-file.js";
5
5
 
6
- export type Framework = "nextjs" | "nestjs" | "express" | "fastify";
6
+ export type Framework =
7
+ | "nextjs"
8
+ | "nestjs"
9
+ | "express"
10
+ | "fastify"
11
+ | "tanstack";
7
12
 
8
13
  export function detectFramework(projectRoot: string): Framework {
9
14
  const packageJson = JSON.parse(
@@ -23,6 +28,13 @@ export function detectFramework(projectRoot: string): Framework {
23
28
  return "nextjs";
24
29
  }
25
30
 
31
+ if (
32
+ packageJson.dependencies?.["@tanstack/react-start"] ||
33
+ packageJson.devDependencies?.["@tanstack/react-start"]
34
+ ) {
35
+ return "tanstack";
36
+ }
37
+
26
38
  // Check for Fastify
27
39
  if (
28
40
  packageJson.dependencies?.fastify ||
@@ -12,12 +12,13 @@ export function generateConfig(
12
12
  frameworkAdapter: string,
13
13
  toolsPath?: string,
14
14
  promptsPath?: string,
15
- resourcesPath?: string
15
+ resourcesPath?: string,
16
+ endpoint?: string
16
17
  ): void {
17
18
  let configContent = `import { type XmcpConfig } from "xmcp";
18
19
 
19
20
  const config: XmcpConfig = {
20
- http: true,
21
+ http: ${endpoint ? `{ endpoint: ${JSON.stringify(endpoint)} }` : "true"},
21
22
  experimental: {
22
23
  adapter: "${frameworkAdapter}",
23
24
  },`;
@@ -29,7 +30,7 @@ const config: XmcpConfig = {
29
30
  resources: ${resourcesPath ? `"${resourcesPath}"` : "false"},
30
31
  },`;
31
32
 
32
- if (frameworkAdapter === "nextjs") {
33
+ if (frameworkAdapter === "nextjs" || frameworkAdapter === "tanstack") {
33
34
  configContent += `
34
35
  typescript: {
35
36
  skipTypeCheck: true,
@@ -10,7 +10,14 @@ import { createPrompt } from "./create-prompt.js";
10
10
  import { createResources } from "./create-resources.js";
11
11
  import { createNestJsModule } from "./create-nestjs-module.js";
12
12
 
13
+ import {
14
+ assertTanstackRouteAvailable,
15
+ createTanstackRoute,
16
+ getTanstackRoute,
17
+ } from "./create-tanstack-route.js";
18
+
13
19
  interface InitOptions {
20
+ cloudflare?: boolean;
14
21
  projectRoot: string;
15
22
  framework: Framework;
16
23
  toolsPath: string | undefined;
@@ -31,13 +38,28 @@ export async function init(options: InitOptions) {
31
38
  routePath,
32
39
  packageManager,
33
40
  version,
41
+ cloudflare,
34
42
  } = options;
35
43
 
36
- generateConfig(projectRoot, framework, toolsPath, promptsPath, resourcesPath);
44
+ if (framework === "tanstack" && routePath) {
45
+ assertTanstackRouteAvailable(projectRoot, routePath);
46
+ }
47
+ const endpoint =
48
+ framework === "tanstack" && routePath
49
+ ? getTanstackRoute(projectRoot, routePath).endpoint
50
+ : undefined;
51
+ generateConfig(
52
+ projectRoot,
53
+ framework,
54
+ toolsPath,
55
+ promptsPath,
56
+ resourcesPath,
57
+ endpoint
58
+ );
37
59
 
38
60
  await install(projectRoot, packageManager, version);
39
61
 
40
- updatePackageJson(projectRoot);
62
+ updatePackageJson(projectRoot, { framework, cloudflare });
41
63
 
42
64
  updateTsConfig(projectRoot);
43
65
 
@@ -59,6 +81,10 @@ export async function init(options: InitOptions) {
59
81
  createRoute(projectRoot, routePath);
60
82
  }
61
83
 
84
+ if (framework === "tanstack" && routePath) {
85
+ createTanstackRoute(projectRoot, routePath);
86
+ }
87
+
62
88
  if (framework === "nestjs") {
63
89
  createNestJsModule(projectRoot);
64
90
  }
@@ -1,12 +1,16 @@
1
1
  import path from "path";
2
2
  import fs from "fs-extra";
3
+ import type { Framework } from "./detect-framework.js";
3
4
 
4
5
  /**
5
6
  * update package.json scripts to include xmcp build and dev commands
6
7
  * @param projectPath - The root directory of the project
7
8
  * @returns void
8
9
  */
9
- export function updatePackageJson(projectPath: string): void {
10
+ export function updatePackageJson(
11
+ projectPath: string,
12
+ options: { framework?: Framework; cloudflare?: boolean } = {}
13
+ ): void {
10
14
  const packageJsonPath = path.join(projectPath, "package.json");
11
15
  const packageJson = fs.readJsonSync(packageJsonPath);
12
16
 
@@ -17,17 +21,26 @@ export function updatePackageJson(projectPath: string): void {
17
21
  packageJson.devDependencies = packageJson.devDependencies ?? {};
18
22
  packageJson.devDependencies["@xmcp-dev/compiler"] ??= "latest";
19
23
 
24
+ const tanstack = options.framework === "tanstack";
25
+ const platformFlag = tanstack && options.cloudflare ? " --cf" : "";
26
+ const build = `xmcp build${platformFlag}`;
27
+ const dev = `xmcp dev${platformFlag}`;
28
+
20
29
  // prepend commands to existing scripts - prevent overwriting
21
30
  if (packageJson.scripts.build) {
22
- packageJson.scripts.build = `xmcp build && ${packageJson.scripts.build}`;
31
+ packageJson.scripts.build = `${build} && ${packageJson.scripts.build}`;
23
32
  } else {
24
- packageJson.scripts.build = "xmcp build";
33
+ packageJson.scripts.build = tanstack ? `${build} && vite build` : build;
25
34
  }
26
35
 
27
36
  if (packageJson.scripts.dev) {
28
- packageJson.scripts.dev = `xmcp dev & ${packageJson.scripts.dev}`;
37
+ packageJson.scripts.dev = tanstack
38
+ ? `${build} && (${dev} & ${packageJson.scripts.dev})`
39
+ : `${dev} & ${packageJson.scripts.dev}`;
29
40
  } else {
30
- packageJson.scripts.dev = "xmcp dev";
41
+ packageJson.scripts.dev = tanstack
42
+ ? `${build} && (${dev} & vite dev)`
43
+ : dev;
31
44
  }
32
45
 
33
46
  fs.writeJsonSync(packageJsonPath, packageJson, { spaces: 2 });
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import { Command } from "commander";
4
4
  import chalk from "chalk";
5
5
  import inquirer from "inquirer";
6
6
  import { init } from "./helpers/init.js";
7
+ import { detectTanstackCloudflare } from "./helpers/create-tanstack-route.js";
7
8
  import {
8
9
  detectFramework,
9
10
  detectTypeScript,
@@ -45,6 +46,11 @@ const program = new Command()
45
46
  .option("--skip-tools", "Skip tool creation", false)
46
47
  .option("--skip-prompts", "Skip prompt creation", false)
47
48
  .option("--skip-resources", "Skip resource creation", false)
49
+ .option(
50
+ "--cf",
51
+ "Build the TanStack Start adapter for Cloudflare Workers",
52
+ false
53
+ )
48
54
  .option("--skip-route", "Skip route creation", false)
49
55
  .action(async (options) => {
50
56
  console.log(chalk.bold(`\ninit-xmcp@${packageJson.version}`));
@@ -129,6 +135,13 @@ const program = new Command()
129
135
  }
130
136
  }
131
137
 
138
+ if (detectedFramework === "tanstack" && !options.skipRoute) {
139
+ routePath = options.routePath || "src/routes";
140
+ }
141
+ const cloudflare =
142
+ detectedFramework === "tanstack" &&
143
+ (options.cf || detectTanstackCloudflare(projectRoot));
144
+
132
145
  // determine package manager
133
146
  let packageManager: "npm" | "yarn" | "pnpm" | "bun";
134
147
  if (detectedPackageManager) {
@@ -183,12 +196,15 @@ const program = new Command()
183
196
  });
184
197
  }
185
198
 
186
- if (detectedFramework === "nextjs" && !options.skipRoute) {
199
+ if (
200
+ (detectedFramework === "nextjs" || detectedFramework === "tanstack") &&
201
+ !options.skipRoute
202
+ ) {
187
203
  prompts.push({
188
204
  type: "input",
189
205
  name: "routePath",
190
206
  message: "Route directory path:",
191
- default: routePath, // will not be undefined if detectedFramework is nextjs
207
+ default: routePath,
192
208
  });
193
209
  }
194
210
 
@@ -240,7 +256,7 @@ const program = new Command()
240
256
  }
241
257
 
242
258
  if (
243
- detectedFramework === "nextjs" &&
259
+ (detectedFramework === "nextjs" || detectedFramework === "tanstack") &&
244
260
  !options.skipRoute &&
245
261
  answers.routePath
246
262
  ) {
@@ -284,8 +300,8 @@ const program = new Command()
284
300
  }
285
301
 
286
302
  // check if route directory already exists and has content
287
- if (routePath) {
288
- // means detectedFramework is nextjs
303
+ if (routePath && detectedFramework === "nextjs") {
304
+ // Existing Next.js route-directory handling.
289
305
  const routeDirPath = path.join(projectRoot, routePath);
290
306
  if (fs.existsSync(routeDirPath)) {
291
307
  const routeDirContent = fs.readdirSync(routeDirPath);
@@ -328,6 +344,7 @@ const program = new Command()
328
344
  routePath,
329
345
  packageManager,
330
346
  version: packageJson.version,
347
+ cloudflare,
331
348
  });
332
349
 
333
350
  console.log(chalk.green("\n✔ xmcp initialized successfully!"));
@@ -348,7 +365,9 @@ const program = new Command()
348
365
  }
349
366
 
350
367
  if (routePath) {
351
- console.log(` • ${routePath}/route.ts`);
368
+ console.log(
369
+ ` • ${routePath}/${detectedFramework === "tanstack" ? "mcp.ts" : "route.ts"}`
370
+ );
352
371
  }
353
372
 
354
373
  if (detectedFramework === "nestjs") {