@vitemcp/server 1.8.4 → 1.8.6

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,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/bin/vitemcp.ts
4
- import { execa } from "execa";
5
- import { mkdtemp, rm, writeFile } from "fs/promises";
4
+ import { execa as execa2 } from "execa";
5
+ import { mkdtemp, rm as rm2, writeFile as writeFile2 } from "fs/promises";
6
6
  import { tmpdir } from "os";
7
- import { join } from "path";
7
+ import { join as join2 } from "path";
8
8
  import yargs from "yargs";
9
9
  import { hideBin } from "yargs/helpers";
10
10
 
@@ -50,6 +50,102 @@ var buildDevCommand = (options) => {
50
50
  ];
51
51
  };
52
52
 
53
+ // src/bin/validateCommand.ts
54
+ import { randomUUID } from "crypto";
55
+ import { execa } from "execa";
56
+ import { existsSync } from "fs";
57
+ import { rm, writeFile } from "fs/promises";
58
+ import { dirname, join } from "path";
59
+ import { pathToFileURL } from "url";
60
+ var STRUCTURE_CHECK_SCRIPT = `
61
+ (async () => {
62
+ let failure;
63
+
64
+ try {
65
+ await import("@vitemcp/server");
66
+ await import(process.argv[1]);
67
+ } catch (error) {
68
+ failure = error instanceof Error ? error.message : String(error);
69
+ }
70
+
71
+ if (failure === undefined) {
72
+ process.stdout.write(
73
+ "[ViteMCP] \u2713 Server structure validation passed\\n",
74
+ () => process.exit(0),
75
+ );
76
+ } else {
77
+ process.stderr.write(
78
+ "[ViteMCP] \u2717 Server structure validation failed: " + failure + "\\n",
79
+ () => process.exit(1),
80
+ );
81
+ }
82
+ })();
83
+ `;
84
+ var STANDALONE_COMPILER_OPTIONS = {
85
+ allowImportingTsExtensions: true,
86
+ module: "esnext",
87
+ moduleResolution: "bundler",
88
+ skipLibCheck: true,
89
+ target: "es2022"
90
+ };
91
+ var PROJECT_OVERRIDES = { composite: false, incremental: false };
92
+ var buildStructureCheckCommand = (file, execPath = process.execPath) => [
93
+ execPath,
94
+ "-e",
95
+ STRUCTURE_CHECK_SCRIPT,
96
+ pathToFileURL(file).href
97
+ ];
98
+ var buildTypeCheckCommand = (config, strict = false) => [
99
+ "npx",
100
+ "tsc",
101
+ "--noEmit",
102
+ "--project",
103
+ config,
104
+ ...strict ? ["--strict"] : []
105
+ ];
106
+ var buildTypeCheckConfig = (file, tsconfig) => JSON.stringify(
107
+ tsconfig ? {
108
+ compilerOptions: PROJECT_OVERRIDES,
109
+ extends: tsconfig,
110
+ files: [file],
111
+ include: []
112
+ } : {
113
+ compilerOptions: STANDALONE_COMPILER_OPTIONS,
114
+ files: [file],
115
+ include: []
116
+ },
117
+ null,
118
+ 2
119
+ );
120
+ var findTsconfig = (dir) => {
121
+ for (let current = dir; ; current = dirname(current)) {
122
+ const candidate = join(current, "tsconfig.json");
123
+ if (existsSync(candidate)) {
124
+ return candidate;
125
+ }
126
+ if (dirname(current) === current) {
127
+ return void 0;
128
+ }
129
+ }
130
+ };
131
+ var formatCommandFailure = (result) => [result.stderr, result.stdout].map((output) => typeof output === "string" ? output.trim() : "").filter(Boolean).join("\n");
132
+ var runTypeCheck = async (file, strict = false) => {
133
+ const tsconfig = findTsconfig(dirname(file));
134
+ const config = join(
135
+ dirname(tsconfig ?? file),
136
+ `tsconfig.vitemcp-validate-${randomUUID()}.json`
137
+ );
138
+ await writeFile(config, buildTypeCheckConfig(file, tsconfig), {
139
+ flag: "wx"
140
+ });
141
+ try {
142
+ const [command, ...args] = buildTypeCheckCommand(config, strict);
143
+ return await execa(command, args, { reject: false });
144
+ } finally {
145
+ await rm(config, { force: true });
146
+ }
147
+ };
148
+
53
149
  // src/bin/vitemcp.ts
54
150
  await yargs(hideBin(process.argv)).scriptName("vitemcp").command(
55
151
  "dev <file>",
@@ -93,9 +189,9 @@ await yargs(hideBin(process.argv)).scriptName("vitemcp").command(
93
189
  }
94
190
  let configPath;
95
191
  if (argv.tool) {
96
- configDir = await mkdtemp(join(tmpdir(), "vitemcp-dev-"));
97
- configPath = join(configDir, "mcp-cli.json");
98
- await writeFile(configPath, buildDevConfig(argv.file), "utf8");
192
+ configDir = await mkdtemp(join2(tmpdir(), "vitemcp-dev-"));
193
+ configPath = join2(configDir, "mcp-cli.json");
194
+ await writeFile2(configPath, buildDevConfig(argv.file), "utf8");
99
195
  }
100
196
  const [command, ...commandArgs] = buildDevCommand({
101
197
  configPath,
@@ -116,7 +212,7 @@ await yargs(hideBin(process.argv)).scriptName("vitemcp").command(
116
212
  console.log(`[ViteMCP] Tool: ${argv.tool}`);
117
213
  }
118
214
  }
119
- await execa(command, commandArgs, {
215
+ await execa2(command, commandArgs, {
120
216
  stderr: "inherit",
121
217
  stdin: "inherit",
122
218
  stdout: "inherit"
@@ -132,7 +228,7 @@ await yargs(hideBin(process.argv)).scriptName("vitemcp").command(
132
228
  process.exitCode = 1;
133
229
  } finally {
134
230
  if (configDir) {
135
- await rm(configDir, { force: true, recursive: true });
231
+ await rm2(configDir, { force: true, recursive: true });
136
232
  }
137
233
  }
138
234
  }
@@ -148,7 +244,7 @@ await yargs(hideBin(process.argv)).scriptName("vitemcp").command(
148
244
  },
149
245
  async (argv) => {
150
246
  try {
151
- await execa({
247
+ await execa2({
152
248
  stderr: "inherit",
153
249
  stdout: "inherit"
154
250
  })`npx @modelcontextprotocol/inspector npx tsx ${argv.file}`;
@@ -177,49 +273,38 @@ await yargs(hideBin(process.argv)).scriptName("vitemcp").command(
177
273
  },
178
274
  async (argv) => {
179
275
  try {
180
- const { existsSync } = await import("fs");
276
+ const { existsSync: existsSync2 } = await import("fs");
181
277
  const { resolve } = await import("path");
182
278
  const filePath = resolve(argv.file);
183
- if (!existsSync(filePath)) {
279
+ if (!existsSync2(filePath)) {
184
280
  console.error(`[ViteMCP Error] File not found: ${filePath}`);
185
281
  process.exit(1);
186
282
  }
187
283
  console.log(`[ViteMCP] Validating server file: ${filePath}`);
188
- const command = argv.strict ? `npx tsc --noEmit --strict ${filePath}` : `npx tsc --noEmit ${filePath}`;
189
- try {
190
- await execa({
191
- shell: true,
192
- stderr: "pipe",
193
- stdout: "pipe"
194
- })`${command}`;
195
- console.log("[ViteMCP] \u2713 TypeScript compilation successful");
196
- } catch (tsError) {
284
+ const typeCheck = await runTypeCheck(filePath, argv.strict);
285
+ if (typeCheck.failed) {
197
286
  console.error("[ViteMCP] \u2717 TypeScript compilation failed");
198
- if (tsError instanceof Error && "stderr" in tsError) {
199
- console.error(tsError.stderr);
287
+ const diagnostics = formatCommandFailure(typeCheck);
288
+ if (diagnostics) {
289
+ console.error(diagnostics);
200
290
  }
201
291
  process.exit(1);
202
292
  }
203
- try {
204
- await execa({
205
- shell: true,
206
- stderr: "pipe",
207
- stdout: "pipe"
208
- })`node -e "
209
- (async () => {
210
- try {
211
- const { ViteMCP } = await import('@vitemcp/server');
212
- await import('file://${filePath}');
213
- console.log('[ViteMCP] ✓ Server structure validation passed');
214
- } catch (error) {
215
- console.error('[ViteMCP] ✗ Server structure validation failed:', error.message);
216
- process.exit(1);
217
- }
218
- })();
219
- "`;
220
- } catch {
221
- console.error("[ViteMCP] \u2717 Server structure validation failed");
222
- console.error("Make sure the file properly imports and uses ViteMCP");
293
+ console.log("[ViteMCP] \u2713 TypeScript compilation successful");
294
+ const [structureCommand, ...structureArgs] = buildStructureCheckCommand(filePath);
295
+ const structureCheck = await execa2(structureCommand, structureArgs, {
296
+ reject: false
297
+ });
298
+ if (structureCheck.failed) {
299
+ const reason = formatCommandFailure(structureCheck);
300
+ if (reason) {
301
+ console.error(reason);
302
+ } else {
303
+ console.error("[ViteMCP] \u2717 Server structure validation failed");
304
+ console.error(
305
+ "Make sure the file properly imports and uses ViteMCP"
306
+ );
307
+ }
223
308
  process.exit(1);
224
309
  }
225
310
  console.log(
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/vitemcp.ts","../../src/bin/devCommand.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { execa } from \"execa\";\nimport { mkdtemp, rm, writeFile } from \"fs/promises\";\nimport { tmpdir } from \"os\";\nimport { join } from \"path\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\n\nimport { buildDevCommand, buildDevConfig } from \"./devCommand.js\";\n\nawait yargs(hideBin(process.argv))\n .scriptName(\"vitemcp\")\n .command(\n \"dev <file>\",\n \"Start a development server\",\n (yargs) => {\n return yargs\n .positional(\"file\", {\n demandOption: true,\n describe: \"The path to the server file\",\n type: \"string\",\n })\n\n .option(\"args\", {\n describe:\n \"JSON arguments passed to the tool (requires --tool), e.g. '{\\\"a\\\":1}'\",\n type: \"string\",\n })\n\n .option(\"tool\", {\n alias: \"t\",\n describe:\n \"Call a tool non-interactively instead of launching the inspector\",\n type: \"string\",\n })\n\n .option(\"watch\", {\n alias: \"w\",\n default: false,\n describe: \"Watch for file changes and restart server\",\n type: \"boolean\",\n })\n\n .option(\"verbose\", {\n alias: \"v\",\n default: false,\n describe: \"Enable verbose logging\",\n type: \"boolean\",\n });\n },\n\n async (argv) => {\n let configDir: string | undefined;\n\n try {\n if (argv.args !== undefined && !argv.tool) {\n console.error(\"[ViteMCP Error] --args requires --tool\");\n process.exitCode = 1;\n return;\n }\n\n if (argv.tool && argv.watch) {\n console.warn(\n \"[ViteMCP] --watch is ignored when calling a tool with --tool: the server runs for a single call.\",\n );\n }\n\n let configPath: string | undefined;\n\n if (argv.tool) {\n configDir = await mkdtemp(join(tmpdir(), \"vitemcp-dev-\"));\n configPath = join(configDir, \"mcp-cli.json\");\n await writeFile(configPath, buildDevConfig(argv.file), \"utf8\");\n }\n\n const [command, ...commandArgs] = buildDevCommand({\n configPath,\n file: argv.file,\n tool: argv.tool,\n toolArgs: argv.args,\n watch: argv.watch,\n });\n\n if (argv.verbose) {\n console.log(\n `[ViteMCP] Starting server: ${[command, ...commandArgs].join(\" \")}`,\n );\n console.log(`[ViteMCP] File: ${argv.file}`);\n console.log(\n `[ViteMCP] Watch mode: ${argv.watch ? \"enabled\" : \"disabled\"}`,\n );\n\n if (argv.tool) {\n console.log(`[ViteMCP] Tool: ${argv.tool}`);\n }\n }\n\n await execa(command, commandArgs, {\n stderr: \"inherit\",\n stdin: \"inherit\",\n stdout: \"inherit\",\n });\n } catch (error) {\n console.error(\n \"[ViteMCP Error] Failed to start development server:\",\n error instanceof Error ? error.message : String(error),\n );\n\n if (argv.verbose && error instanceof Error && error.stack) {\n console.error(\"[ViteMCP Debug] Stack trace:\", error.stack);\n }\n\n // Not process.exit(): that would skip the `finally` block below and\n // leak the temporary config directory on every failed tool call.\n process.exitCode = 1;\n } finally {\n if (configDir) {\n await rm(configDir, { force: true, recursive: true });\n }\n }\n },\n )\n\n .command(\n \"inspect <file>\",\n \"Inspect a server file\",\n (yargs) => {\n return yargs.positional(\"file\", {\n demandOption: true,\n describe: \"The path to the server file\",\n type: \"string\",\n });\n },\n\n async (argv) => {\n try {\n await execa({\n stderr: \"inherit\",\n stdout: \"inherit\",\n })`npx @modelcontextprotocol/inspector npx tsx ${argv.file}`;\n } catch (error) {\n console.error(\n \"[ViteMCP Error] Failed to inspect server:\",\n error instanceof Error ? error.message : String(error),\n );\n\n process.exit(1);\n }\n },\n )\n\n .command(\n \"validate <file>\",\n \"Validate a ViteMCP server file for syntax and basic structure\",\n (yargs) => {\n return yargs\n .positional(\"file\", {\n demandOption: true,\n describe: \"The path to the server file\",\n type: \"string\",\n })\n\n .option(\"strict\", {\n alias: \"s\",\n default: false,\n describe: \"Enable strict validation (type checking)\",\n type: \"boolean\",\n });\n },\n\n async (argv) => {\n try {\n const { existsSync } = await import(\"fs\");\n const { resolve } = await import(\"path\");\n const filePath = resolve(argv.file);\n\n if (!existsSync(filePath)) {\n console.error(`[ViteMCP Error] File not found: ${filePath}`);\n process.exit(1);\n }\n\n console.log(`[ViteMCP] Validating server file: ${filePath}`);\n\n const command = argv.strict\n ? `npx tsc --noEmit --strict ${filePath}`\n : `npx tsc --noEmit ${filePath}`;\n\n try {\n await execa({\n shell: true,\n stderr: \"pipe\",\n stdout: \"pipe\",\n })`${command}`;\n\n console.log(\"[ViteMCP] ✓ TypeScript compilation successful\");\n } catch (tsError) {\n console.error(\"[ViteMCP] ✗ TypeScript compilation failed\");\n\n if (tsError instanceof Error && \"stderr\" in tsError) {\n console.error(tsError.stderr);\n }\n\n process.exit(1);\n }\n\n try {\n await execa({\n shell: true,\n stderr: \"pipe\",\n stdout: \"pipe\",\n })`node -e \"\n (async () => {\n try {\n const { ViteMCP } = await import('@vitemcp/server');\n await import('file://${filePath}');\n console.log('[ViteMCP] ✓ Server structure validation passed');\n } catch (error) {\n console.error('[ViteMCP] ✗ Server structure validation failed:', error.message);\n process.exit(1);\n }\n })();\n \"`;\n } catch {\n console.error(\"[ViteMCP] ✗ Server structure validation failed\");\n console.error(\"Make sure the file properly imports and uses ViteMCP\");\n\n process.exit(1);\n }\n\n console.log(\n \"[ViteMCP] ✓ All validations passed! Server file looks good.\",\n );\n } catch (error) {\n console.error(\n \"[ViteMCP Error] Validation failed:\",\n error instanceof Error ? error.message : String(error),\n );\n\n process.exit(1);\n }\n },\n )\n\n .help()\n .parseAsync();\n","export type DevCommandOptions = {\n /**\n * Path to a temporary mcp-cli config file that registers the dev server.\n * Only used in non-interactive mode (when `tool` is set).\n */\n configPath?: string;\n /**\n * Path to the server file to run.\n */\n file: string;\n /**\n * Name of the tool to call non-interactively. When omitted, the dev\n * command launches the interactive mcp-cli inspector instead.\n */\n tool?: string;\n /**\n * JSON string of arguments forwarded to the tool via mcp-cli `--args`.\n * Only used in non-interactive mode.\n */\n toolArgs?: string;\n /**\n * Watch the file for changes and restart the server. Only used in\n * interactive mode; a non-interactive call runs the server once.\n */\n watch?: boolean;\n};\n\n/**\n * The server name registered in the generated mcp-cli config. mcp-cli\n * addresses non-interactive targets as `<server-name>:<tool>`.\n */\nexport const DEV_SERVER_NAME = \"dev\";\n\n/**\n * Build the JSON config that registers the dev server with mcp-cli so it can\n * be invoked non-interactively. mcp-cli's non-interactive mode resolves the\n * server by name from a config file's `mcpServers` map, so an inline command\n * cannot be passed directly alongside `call-tool`.\n *\n * The server is never started in watch mode here: a non-interactive call\n * connects, calls one tool, and exits, so there is nothing to restart into.\n */\nexport const buildDevConfig = (file: string): string =>\n JSON.stringify(\n {\n mcpServers: {\n [DEV_SERVER_NAME]: {\n args: [\"tsx\", file],\n command: \"npx\",\n },\n },\n },\n null,\n 2,\n );\n\n/**\n * Build the argv that the dev command runs.\n *\n * This is an argv array rather than a shell string so that nothing has to be\n * quoted: file paths, tool names and JSON `--args` are passed to the child\n * process verbatim. Quoting through a shell would be wrong on Windows, where\n * cmd.exe treats single quotes as literal characters rather than as quoting.\n *\n * - Without `tool`: launches the interactive @wong2/mcp-cli inspector\n * against an inline `npx tsx <file>` server (existing behaviour).\n * - With `tool`: runs @wong2/mcp-cli in non-interactive mode against a\n * generated config file, calling the named tool and forwarding `--args`.\n */\nexport const buildDevCommand = (\n options: DevCommandOptions,\n): [string, ...string[]] => {\n const { configPath, file, tool, toolArgs, watch = false } = options;\n\n if (tool) {\n if (!configPath) {\n throw new Error(\n \"configPath is required when calling a tool non-interactively\",\n );\n }\n\n return [\n \"npx\",\n \"@wong2/mcp-cli\",\n \"-c\",\n configPath,\n \"call-tool\",\n `${DEV_SERVER_NAME}:${tool}`,\n ...(toolArgs === undefined ? [] : [\"--args\", toolArgs]),\n ];\n }\n\n return [\n \"npx\",\n \"@wong2/mcp-cli\",\n \"npx\",\n \"tsx\",\n ...(watch ? [\"--watch\"] : []),\n file,\n ];\n};\n"],"mappings":";;;AAEA,SAAS,aAAa;AACtB,SAAS,SAAS,IAAI,iBAAiB;AACvC,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,OAAO,WAAW;AAClB,SAAS,eAAe;;;ACwBjB,IAAM,kBAAkB;AAWxB,IAAM,iBAAiB,CAAC,SAC7B,KAAK;AAAA,EACH;AAAA,IACE,YAAY;AAAA,MACV,CAAC,eAAe,GAAG;AAAA,QACjB,MAAM,CAAC,OAAO,IAAI;AAAA,QAClB,SAAS;AAAA,MACX;AAAA,IACF;AAAA,EACF;A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,QAAQ;AAAA,UACR,QAAQ;AAAA,QACV,CAAC,IAAI,OAAO;AAEZ,gBAAQ,IAAI,oDAA+C;AAAA,MAC7D,SAAS,SAAS;AAChB,gBAAQ,MAAM,gDAA2C;AAEzD,YAAI,mBAAmB,SAAS,YAAY,SAAS;AACnD,kBAAQ,MAAM,QAAQ,MAAM;AAAA,QAC9B;AAEA,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAEA,UAAI;AACF,cAAM,MAAM;AAAA,UACV,OAAO;AAAA,UACP,QAAQ;AAAA,UACR,QAAQ;AAAA,QACV,CAAC;AAAA;AAAA;AAAA;AAAA,uCAI4B,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQvC,QAAQ;AACN,gBAAQ,MAAM,qDAAgD;AAC9D,gBAAQ,MAAM,sDAAsD;AAEpE,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAEA,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ;AAAA,QACN;AAAA,QACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MACvD;AAEA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,EAEC,KAAK,EACL,WAAW;","names":["yargs"]}
1
+ {"version":3,"sources":["../../src/bin/vitemcp.ts","../../src/bin/devCommand.ts","../../src/bin/validateCommand.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { execa } from \"execa\";\nimport { mkdtemp, rm, writeFile } from \"fs/promises\";\nimport { tmpdir } from \"os\";\nimport { join } from \"path\";\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\n\nimport { buildDevCommand, buildDevConfig } from \"./devCommand.js\";\nimport {\n buildStructureCheckCommand,\n formatCommandFailure,\n runTypeCheck,\n} from \"./validateCommand.js\";\n\nawait yargs(hideBin(process.argv))\n .scriptName(\"vitemcp\")\n .command(\n \"dev <file>\",\n \"Start a development server\",\n (yargs) => {\n return yargs\n .positional(\"file\", {\n demandOption: true,\n describe: \"The path to the server file\",\n type: \"string\",\n })\n\n .option(\"args\", {\n describe:\n \"JSON arguments passed to the tool (requires --tool), e.g. '{\\\"a\\\":1}'\",\n type: \"string\",\n })\n\n .option(\"tool\", {\n alias: \"t\",\n describe:\n \"Call a tool non-interactively instead of launching the inspector\",\n type: \"string\",\n })\n\n .option(\"watch\", {\n alias: \"w\",\n default: false,\n describe: \"Watch for file changes and restart server\",\n type: \"boolean\",\n })\n\n .option(\"verbose\", {\n alias: \"v\",\n default: false,\n describe: \"Enable verbose logging\",\n type: \"boolean\",\n });\n },\n\n async (argv) => {\n let configDir: string | undefined;\n\n try {\n if (argv.args !== undefined && !argv.tool) {\n console.error(\"[ViteMCP Error] --args requires --tool\");\n process.exitCode = 1;\n return;\n }\n\n if (argv.tool && argv.watch) {\n console.warn(\n \"[ViteMCP] --watch is ignored when calling a tool with --tool: the server runs for a single call.\",\n );\n }\n\n let configPath: string | undefined;\n\n if (argv.tool) {\n configDir = await mkdtemp(join(tmpdir(), \"vitemcp-dev-\"));\n configPath = join(configDir, \"mcp-cli.json\");\n await writeFile(configPath, buildDevConfig(argv.file), \"utf8\");\n }\n\n const [command, ...commandArgs] = buildDevCommand({\n configPath,\n file: argv.file,\n tool: argv.tool,\n toolArgs: argv.args,\n watch: argv.watch,\n });\n\n if (argv.verbose) {\n console.log(\n `[ViteMCP] Starting server: ${[command, ...commandArgs].join(\" \")}`,\n );\n console.log(`[ViteMCP] File: ${argv.file}`);\n console.log(\n `[ViteMCP] Watch mode: ${argv.watch ? \"enabled\" : \"disabled\"}`,\n );\n\n if (argv.tool) {\n console.log(`[ViteMCP] Tool: ${argv.tool}`);\n }\n }\n\n await execa(command, commandArgs, {\n stderr: \"inherit\",\n stdin: \"inherit\",\n stdout: \"inherit\",\n });\n } catch (error) {\n console.error(\n \"[ViteMCP Error] Failed to start development server:\",\n error instanceof Error ? error.message : String(error),\n );\n\n if (argv.verbose && error instanceof Error && error.stack) {\n console.error(\"[ViteMCP Debug] Stack trace:\", error.stack);\n }\n\n // Not process.exit(): that would skip the `finally` block below and\n // leak the temporary config directory on every failed tool call.\n process.exitCode = 1;\n } finally {\n if (configDir) {\n await rm(configDir, { force: true, recursive: true });\n }\n }\n },\n )\n\n .command(\n \"inspect <file>\",\n \"Inspect a server file\",\n (yargs) => {\n return yargs.positional(\"file\", {\n demandOption: true,\n describe: \"The path to the server file\",\n type: \"string\",\n });\n },\n\n async (argv) => {\n try {\n await execa({\n stderr: \"inherit\",\n stdout: \"inherit\",\n })`npx @modelcontextprotocol/inspector npx tsx ${argv.file}`;\n } catch (error) {\n console.error(\n \"[ViteMCP Error] Failed to inspect server:\",\n error instanceof Error ? error.message : String(error),\n );\n\n process.exit(1);\n }\n },\n )\n\n .command(\n \"validate <file>\",\n \"Validate a ViteMCP server file for syntax and basic structure\",\n (yargs) => {\n return yargs\n .positional(\"file\", {\n demandOption: true,\n describe: \"The path to the server file\",\n type: \"string\",\n })\n\n .option(\"strict\", {\n alias: \"s\",\n default: false,\n describe: \"Enable strict validation (type checking)\",\n type: \"boolean\",\n });\n },\n\n async (argv) => {\n try {\n const { existsSync } = await import(\"fs\");\n const { resolve } = await import(\"path\");\n const filePath = resolve(argv.file);\n\n if (!existsSync(filePath)) {\n console.error(`[ViteMCP Error] File not found: ${filePath}`);\n process.exit(1);\n }\n\n console.log(`[ViteMCP] Validating server file: ${filePath}`);\n\n const typeCheck = await runTypeCheck(filePath, argv.strict);\n\n if (typeCheck.failed) {\n console.error(\"[ViteMCP] ✗ TypeScript compilation failed\");\n\n const diagnostics = formatCommandFailure(typeCheck);\n\n if (diagnostics) {\n console.error(diagnostics);\n }\n\n process.exit(1);\n }\n\n console.log(\"[ViteMCP] ✓ TypeScript compilation successful\");\n\n const [structureCommand, ...structureArgs] =\n buildStructureCheckCommand(filePath);\n const structureCheck = await execa(structureCommand, structureArgs, {\n reject: false,\n });\n\n if (structureCheck.failed) {\n // The child explains the failure on stderr, which execa captures.\n // Without replaying it the user only ever sees the generic hint, even\n // when their server file has an error they could act on.\n const reason = formatCommandFailure(structureCheck);\n\n if (reason) {\n console.error(reason);\n } else {\n console.error(\"[ViteMCP] ✗ Server structure validation failed\");\n console.error(\n \"Make sure the file properly imports and uses ViteMCP\",\n );\n }\n\n process.exit(1);\n }\n\n console.log(\n \"[ViteMCP] ✓ All validations passed! Server file looks good.\",\n );\n } catch (error) {\n console.error(\n \"[ViteMCP Error] Validation failed:\",\n error instanceof Error ? error.message : String(error),\n );\n\n process.exit(1);\n }\n },\n )\n\n .help()\n .parseAsync();\n","export type DevCommandOptions = {\n /**\n * Path to a temporary mcp-cli config file that registers the dev server.\n * Only used in non-interactive mode (when `tool` is set).\n */\n configPath?: string;\n /**\n * Path to the server file to run.\n */\n file: string;\n /**\n * Name of the tool to call non-interactively. When omitted, the dev\n * command launches the interactive mcp-cli inspector instead.\n */\n tool?: string;\n /**\n * JSON string of arguments forwarded to the tool via mcp-cli `--args`.\n * Only used in non-interactive mode.\n */\n toolArgs?: string;\n /**\n * Watch the file for changes and restart the server. Only used in\n * interactive mode; a non-interactive call runs the server once.\n */\n watch?: boolean;\n};\n\n/**\n * The server name registered in the generated mcp-cli config. mcp-cli\n * addresses non-interactive targets as `<server-name>:<tool>`.\n */\nexport const DEV_SERVER_NAME = \"dev\";\n\n/**\n * Build the JSON config that registers the dev server with mcp-cli so it can\n * be invoked non-interactively. mcp-cli's non-interactive mode resolves the\n * server by name from a config file's `mcpServers` map, so an inline command\n * cannot be passed directly alongside `call-tool`.\n *\n * The server is never started in watch mode here: a non-interactive call\n * connects, calls one tool, and exits, so there is nothing to restart into.\n */\nexport const buildDevConfig = (file: string): string =>\n JSON.stringify(\n {\n mcpServers: {\n [DEV_SERVER_NAME]: {\n args: [\"tsx\", file],\n command: \"npx\",\n },\n },\n },\n null,\n 2,\n );\n\n/**\n * Build the argv that the dev command runs.\n *\n * This is an argv array rather than a shell string so that nothing has to be\n * quoted: file paths, tool names and JSON `--args` are passed to the child\n * process verbatim. Quoting through a shell would be wrong on Windows, where\n * cmd.exe treats single quotes as literal characters rather than as quoting.\n *\n * - Without `tool`: launches the interactive @wong2/mcp-cli inspector\n * against an inline `npx tsx <file>` server (existing behaviour).\n * - With `tool`: runs @wong2/mcp-cli in non-interactive mode against a\n * generated config file, calling the named tool and forwarding `--args`.\n */\nexport const buildDevCommand = (\n options: DevCommandOptions,\n): [string, ...string[]] => {\n const { configPath, file, tool, toolArgs, watch = false } = options;\n\n if (tool) {\n if (!configPath) {\n throw new Error(\n \"configPath is required when calling a tool non-interactively\",\n );\n }\n\n return [\n \"npx\",\n \"@wong2/mcp-cli\",\n \"-c\",\n configPath,\n \"call-tool\",\n `${DEV_SERVER_NAME}:${tool}`,\n ...(toolArgs === undefined ? [] : [\"--args\", toolArgs]),\n ];\n }\n\n return [\n \"npx\",\n \"@wong2/mcp-cli\",\n \"npx\",\n \"tsx\",\n ...(watch ? [\"--watch\"] : []),\n file,\n ];\n};\n","import { randomUUID } from \"crypto\";\nimport { execa } from \"execa\";\nimport { existsSync } from \"fs\";\nimport { rm, writeFile } from \"fs/promises\";\nimport { dirname, join } from \"path\";\nimport { pathToFileURL } from \"url\";\n\n/**\n * The script `vitemcp validate` runs to check that a server file loads.\n *\n * The file arrives as `process.argv[1]` rather than being spliced into this\n * source. Spliced into a string literal, a Windows path loses its backslashes\n * to the child's own parser (`C:\\Users\\dev\\server.ts` reaches the import as\n * `C:Usersdevserver.ts`), and a quote or `#` in any path breaks the import —\n * each reported to the user as a problem with their file.\n *\n * It exits as soon as the import settles, once its verdict is flushed. A\n * server file normally starts its transport on load, which would otherwise\n * keep this process, and the command waiting on it, alive forever.\n */\nexport const STRUCTURE_CHECK_SCRIPT = `\n(async () => {\n let failure;\n\n try {\n await import(\"@vitemcp/server\");\n await import(process.argv[1]);\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n\n if (failure === undefined) {\n process.stdout.write(\n \"[ViteMCP] ✓ Server structure validation passed\\\\n\",\n () => process.exit(0),\n );\n } else {\n process.stderr.write(\n \"[ViteMCP] ✗ Server structure validation failed: \" + failure + \"\\\\n\",\n () => process.exit(1),\n );\n }\n})();\n`;\n\n/**\n * Compiler options for a file with no `tsconfig.json` above it. The compiler's\n * own defaults target ES5, which rejects top-level await and the `#private`\n * members in `@vitemcp/server`'s declarations, so no server file could pass.\n */\nconst STANDALONE_COMPILER_OPTIONS = {\n allowImportingTsExtensions: true,\n module: \"esnext\",\n moduleResolution: \"bundler\",\n skipLibCheck: true,\n target: \"es2022\",\n};\n\n/**\n * What the throwaway config overrides in the project's own. `composite`\n * demands that every file the server imports be listed as a root, and only the\n * server file is; `incremental` writes a `.tsbuildinfo` named after the\n * throwaway config into the project.\n */\nconst PROJECT_OVERRIDES = { composite: false, incremental: false };\n\n/**\n * Build the argv for the structure check.\n *\n * An argv array rather than a shell string, as in `buildDevCommand`, so nothing\n * has to be quoted. The file is converted to a `file:` URL here, so the child\n * imports it as given and never has to build the URL itself; and the child is\n * the Node binary running this CLI, so no PATH lookup is involved.\n */\nexport const buildStructureCheckCommand = (\n file: string,\n execPath: string = process.execPath,\n): [string, ...string[]] => [\n execPath,\n \"-e\",\n STRUCTURE_CHECK_SCRIPT,\n pathToFileURL(file).href,\n];\n\n/**\n * Build the argv for the type check. An argv array for the same reason as the\n * structure check: through a shell, a path containing a space reaches `tsc` as\n * several root files.\n */\nexport const buildTypeCheckCommand = (\n config: string,\n strict = false,\n): [string, ...string[]] => [\n \"npx\",\n \"tsc\",\n \"--noEmit\",\n \"--project\",\n config,\n ...(strict ? [\"--strict\"] : []),\n];\n\n/**\n * Build the throwaway config that type-checks one file.\n *\n * `tsc` ignores `tsconfig.json` whenever a file is named on its command line\n * and falls back to defaults no server file passes, so the file is named in a\n * config that extends the project's own instead. `include: []` keeps an\n * inherited `include` from pulling the rest of the project in.\n */\nexport const buildTypeCheckConfig = (file: string, tsconfig?: string): string =>\n JSON.stringify(\n tsconfig\n ? {\n compilerOptions: PROJECT_OVERRIDES,\n extends: tsconfig,\n files: [file],\n include: [],\n }\n : {\n compilerOptions: STANDALONE_COMPILER_OPTIONS,\n files: [file],\n include: [],\n },\n null,\n 2,\n );\n\n/**\n * The `tsconfig.json` that governs a file in `dir`: the nearest one at or above\n * it, which is also the one an editor checks the file against.\n */\nexport const findTsconfig = (dir: string): string | undefined => {\n for (let current = dir; ; current = dirname(current)) {\n const candidate = join(current, \"tsconfig.json\");\n\n if (existsSync(candidate)) {\n return candidate;\n }\n\n if (dirname(current) === current) {\n return undefined;\n }\n }\n};\n\n/**\n * The output of a failed check, for replaying to the user.\n *\n * `tsc` writes its diagnostics to stdout, and only a failure to launch it\n * reaches stderr, so reading stderr alone reported every real type error with\n * no detail. The structure check explains itself on stderr.\n */\nexport const formatCommandFailure = (result: {\n stderr?: unknown;\n stdout?: unknown;\n}): string =>\n [result.stderr, result.stdout]\n .map((output) => (typeof output === \"string\" ? output.trim() : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n\n/**\n * Type-check `file` under the compiler options of the project it belongs to.\n *\n * The throwaway config is written beside the project's own rather than to the\n * OS temp directory, because the compiler resolves type packages — the `types`\n * option and every visible `@types` package — from the config's directory. It\n * is removed before this returns, so a caller may exit straight away.\n */\nexport const runTypeCheck = async (file: string, strict = false) => {\n const tsconfig = findTsconfig(dirname(file));\n const config = join(\n dirname(tsconfig ?? file),\n `tsconfig.vitemcp-validate-${randomUUID()}.json`,\n );\n\n await writeFile(config, buildTypeCheckConfig(file, tsconfig), {\n flag: \"wx\",\n });\n\n try {\n const [command, ...args] = buildTypeCheckCommand(config, strict);\n\n return await execa(command, args, { reject: false });\n } finally {\n await rm(config, { force: true });\n }\n};\n"],"mappings":";;;AAEA,SAAS,SAAAA,cAAa;AACtB,SAAS,SAAS,MAAAC,KAAI,aAAAC,kBAAiB;AACvC,SAAS,cAAc;AACvB,SAAS,QAAAC,aAAY;AACrB,OAAO,WAAW;AAClB,SAAS,eAAe;;;ACwBjB,IAAM,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AAqB,cAAc;AAElD,YAAI,QAAQ;AACV,kBAAQ,MAAM,MAAM;AAAA,QACtB,OAAO;AACL,kBAAQ,MAAM,qDAAgD;AAC9D,kBAAQ;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAEA,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAEA,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ;AAAA,QACN;AAAA,QACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MACvD;AAEA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF,EAEC,KAAK,EACL,WAAW;","names":["execa","rm","writeFile","join","yargs","join","writeFile","execa","rm","existsSync"]}
@@ -444,12 +444,6 @@ var OAuthProxyStateStore = class {
444
444
  }
445
445
  return parsed.data;
446
446
  }
447
- async isTransactionCallbackRegistered(transaction) {
448
- const registeredClient = await this.getRegisteredClientByClientId(
449
- transaction.clientId
450
- );
451
- return registeredClient?.redirectUris.includes(transaction.clientCallbackUrl) ?? false;
452
- }
453
447
  /**
454
448
  * Record that an authorization code has been redeemed, so a later attempt
455
449
  * gets "already used" rather than looking like an unknown code. Keyed and
@@ -1132,6 +1126,40 @@ var JWTIssuer = class {
1132
1126
  }
1133
1127
  };
1134
1128
 
1129
+ // src/auth/utils/loopbackRedirect.ts
1130
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["::1", "127.0.0.1", "localhost"]);
1131
+ var parse = (uri) => {
1132
+ try {
1133
+ return new URL(uri);
1134
+ } catch {
1135
+ return null;
1136
+ }
1137
+ };
1138
+ function loopbackRedirectMatches(declared, requested) {
1139
+ if (declared === requested) {
1140
+ return true;
1141
+ }
1142
+ const a = parse(declared);
1143
+ const b = parse(requested);
1144
+ if (!a || !b) {
1145
+ return false;
1146
+ }
1147
+ if (a.protocol !== "http:" || b.protocol !== "http:") {
1148
+ return false;
1149
+ }
1150
+ const host = a.hostname.replace(/^\[|\]$/g, "");
1151
+ if (!LOOPBACK_HOSTS.has(host) || a.hostname !== b.hostname) {
1152
+ return false;
1153
+ }
1154
+ if (a.port !== "") {
1155
+ return false;
1156
+ }
1157
+ if (a.username !== "" || a.password !== "" || b.username !== "" || b.password !== "") {
1158
+ return false;
1159
+ }
1160
+ return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash;
1161
+ }
1162
+
1135
1163
  // src/auth/utils/pkce.ts
1136
1164
  import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual3 } from "crypto";
1137
1165
  var PKCEUtils = class _PKCEUtils {
@@ -1476,10 +1504,11 @@ var OAuthProxy = class {
1476
1504
  "Only 'code' response type is supported"
1477
1505
  );
1478
1506
  }
1479
- const registeredUris = await this.resolveClientRedirectUris(
1480
- params.client_id
1481
- );
1482
- if (!registeredUris.includes(params.redirect_uri)) {
1507
+ const registeredClient = await this.resolveClient(params.client_id);
1508
+ const registeredUris = registeredClient.redirectUris;
1509
+ if (!registeredUris.some(
1510
+ (uri) => loopbackRedirectMatches(uri, params.redirect_uri)
1511
+ )) {
1483
1512
  throw new OAuthProxyError(
1484
1513
  "invalid_request",
1485
1514
  "redirect_uri is not registered for this client"
@@ -1529,10 +1558,7 @@ var OAuthProxy = class {
1529
1558
  "Only authorization_code grant type is supported"
1530
1559
  );
1531
1560
  }
1532
- const registeredClient = await this.stateStore.getRegisteredClientByClientId(request2.client_id);
1533
- if (!registeredClient) {
1534
- throw new OAuthProxyError("invalid_client", "Unknown client_id");
1535
- }
1561
+ await this.resolveClient(request2.client_id);
1536
1562
  const consumed = await this.stateStore.consumeClientCode(request2.code);
1537
1563
  if (!consumed) {
1538
1564
  throw new OAuthProxyError(
@@ -1623,9 +1649,15 @@ var OAuthProxy = class {
1623
1649
  responseTypesSupported: ["code"],
1624
1650
  scopesSupported: this.config.scopes || [],
1625
1651
  tokenEndpoint: `${this.config.baseUrl}/oauth/token`,
1652
+ // RFC 8414 §2. A CIMD client is a public client: it has no registration
1653
+ // response to carry a secret, and authenticates the exchange with PKCE
1654
+ // alone. A client that reads this list to pick an auth method finds
1655
+ // nothing it can use unless "none" is advertised alongside the
1656
+ // confidential methods DCR clients use.
1626
1657
  tokenEndpointAuthMethodsSupported: [
1627
1658
  "client_secret_basic",
1628
- "client_secret_post"
1659
+ "client_secret_post",
1660
+ ...this.clientIdMetadata.enabled ? ["none"] : []
1629
1661
  ]
1630
1662
  };
1631
1663
  }
@@ -1651,7 +1683,7 @@ var OAuthProxy = class {
1651
1683
  if (!transaction) {
1652
1684
  throw new OAuthProxyError("invalid_request", "Invalid or expired state");
1653
1685
  }
1654
- if (!await this.stateStore.isTransactionCallbackRegistered(transaction)) {
1686
+ if (!await this.isTransactionCallbackRegistered(transaction)) {
1655
1687
  throw new OAuthProxyError(
1656
1688
  "invalid_request",
1657
1689
  "Transaction callback URL is not registered"
@@ -1705,7 +1737,7 @@ var OAuthProxy = class {
1705
1737
  }
1706
1738
  if (action === "deny") {
1707
1739
  await this.stateStore.deleteTransaction(transactionId);
1708
- if (!await this.stateStore.isTransactionCallbackRegistered(transaction)) {
1740
+ if (!await this.isTransactionCallbackRegistered(transaction)) {
1709
1741
  throw new OAuthProxyError(
1710
1742
  "invalid_request",
1711
1743
  "Transaction callback URL is not registered"
@@ -2317,6 +2349,27 @@ var OAuthProxy = class {
2317
2349
  }
2318
2350
  return response;
2319
2351
  }
2352
+ /**
2353
+ * Whether the callback URL a transaction carries is still one its client
2354
+ * declares.
2355
+ *
2356
+ * Resolved through `resolveClient` rather than a raw store lookup so a CIMD
2357
+ * client is visible here too, and so a document that has since dropped the
2358
+ * URI stops matching — the mid-flow revocation this check exists for.
2359
+ * Loopback ports are matched per RFC 8252 §7.3, exactly as `authorize()`
2360
+ * matched them, so the two legs cannot disagree about the same URI.
2361
+ */
2362
+ async isTransactionCallbackRegistered(transaction) {
2363
+ let client;
2364
+ try {
2365
+ client = await this.resolveClient(transaction.clientId);
2366
+ } catch {
2367
+ return false;
2368
+ }
2369
+ return client.redirectUris.some(
2370
+ (uri) => loopbackRedirectMatches(uri, transaction.clientCallbackUrl)
2371
+ );
2372
+ }
2320
2373
  /**
2321
2374
  * Match a parsed URI against an allow-list pattern, one URI component at a
2322
2375
  * time: scheme, host, port, then everything from the path onwards. A `*`
@@ -2483,13 +2536,17 @@ var OAuthProxy = class {
2483
2536
  };
2484
2537
  }
2485
2538
  /**
2486
- * Redirect URIs the given client is allowed to use.
2539
+ * The client behind a client_id, on whichever leg of the flow asks.
2487
2540
  *
2488
2541
  * A URL-formatted client_id is resolved as a Client ID Metadata Document
2489
2542
  * (the preferred mechanism on this revision); anything else must have been
2490
- * registered through DCR.
2543
+ * registered through DCR. Throws `invalid_client` when it is neither.
2491
2544
  */
2492
- async resolveClientRedirectUris(clientId) {
2545
+ async resolveClient(clientId) {
2546
+ const registered = await this.stateStore.getRegisteredClientByClientId(clientId);
2547
+ if (registered) {
2548
+ return registered;
2549
+ }
2493
2550
  if (this.clientIdMetadata.enabled && isClientIdMetadataUrl(clientId)) {
2494
2551
  let metadata;
2495
2552
  try {
@@ -2508,13 +2565,20 @@ var OAuthProxy = class {
2508
2565
  );
2509
2566
  }
2510
2567
  }
2511
- return metadata.redirect_uris;
2512
- }
2513
- const registeredClient = await this.stateStore.getRegisteredClientByClientId(clientId);
2514
- if (!registeredClient) {
2515
- throw new OAuthProxyError("invalid_client", "Unknown client_id");
2568
+ return {
2569
+ callbackUrl: metadata.redirect_uris[0],
2570
+ clientId,
2571
+ clientSecret: void 0,
2572
+ metadata: {
2573
+ client_name: metadata.client_name,
2574
+ client_uri: metadata.client_uri,
2575
+ redirect_uris: metadata.redirect_uris
2576
+ },
2577
+ redirectUris: metadata.redirect_uris,
2578
+ registeredAt: /* @__PURE__ */ new Date()
2579
+ };
2516
2580
  }
2517
- return registeredClient.redirectUris;
2581
+ throw new OAuthProxyError("invalid_client", "Unknown client_id");
2518
2582
  }
2519
2583
  /**
2520
2584
  * Put a claimed refresh-token mapping back after a rotation failed, keeping
@@ -3309,4 +3373,4 @@ export {
3309
3373
  DiskStore,
3310
3374
  JWKSVerifier
3311
3375
  };
3312
- //# sourceMappingURL=chunk-GCCQBATS.js.map
3376
+ //# sourceMappingURL=chunk-5KNSU2F3.js.map