@vitemcp/server 1.9.15 → 1.9.17

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 +1 @@
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 missingTsxHint,\n resolveTsxLoader,\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 tsxLoader = resolveTsxLoader(filePath);\n const [structureCommand, ...structureArgs] = buildStructureCheckCommand(\n filePath,\n { tsxLoader },\n );\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 const hint = missingTsxHint(filePath, tsxLoader);\n\n if (hint) {\n console.error(hint);\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 // `--` ends mcp-cli's own options. Its parser reads any flag it meets, known\n // or not, and takes the next word as that flag's value, so `--watch` and the\n // file never reached the server: `npx tsx` started with no file at all.\n return [\n \"npx\",\n \"@wong2/mcp-cli\",\n \"--\",\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 { createRequire } from \"module\";\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 *\n * `composite` also implies `declaration`, which `declarationMap`,\n * `emitDeclarationOnly` and `isolatedDeclarations` each require, so a composite\n * project may set them without it — and with `composite` off, its check failed\n * with TS5069. Nothing is emitted, so they are switched off as well.\n */\nconst PROJECT_OVERRIDES = {\n composite: false,\n declarationMap: false,\n emitDeclarationOnly: false,\n incremental: false,\n isolatedDeclarations: false,\n};\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 *\n * Given the project's tsx loader (see `resolveTsxLoader`), the child imports\n * the file through it, so the file loads the way `vitemcp dev` runs it. tsx\n * registers itself with `module.register()`, which Node 26 deprecates\n * (DEP0205); that warning alone is switched off, because it would otherwise be\n * replayed with a failure as though the file had caused it.\n */\nexport const buildStructureCheckCommand = (\n file: string,\n {\n execPath = process.execPath,\n tsxLoader,\n }: { execPath?: string; tsxLoader?: string } = {},\n): [string, ...string[]] => [\n execPath,\n ...(tsxLoader ? [\"--disable-warning=DEP0205\", \"--import\", tsxLoader] : []),\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 * What to add when the structure check fails without tsx. Plain Node rejects\n * TypeScript that tsx runs, so the failure may be the loader's rather than the\n * file's. Nothing for a JavaScript file, which loads the same either way.\n */\nexport const missingTsxHint = (\n file: string,\n tsxLoader: string | undefined,\n): string | undefined =>\n tsxLoader || !/\\.[cm]?tsx?$/i.test(file)\n ? undefined\n : \"[ViteMCP] tsx is not installed in this project, so the file was loaded with plain Node, which rejects `.js` imports of `.ts` files and syntax such as enums. Install tsx to validate the file the way `vitemcp dev` runs it: npm install --save-dev tsx\";\n\n/**\n * The project's tsx loader, as a `file:` URL for `--import`, or `undefined`\n * when the project does not have tsx installed.\n *\n * `vitemcp dev` runs a server file with tsx, but plain Node only strips types:\n * it rejects a `.js` import of a `.ts` file, and syntax it would have to\n * transform, such as an enum. So without tsx, a file `dev` ran fine failed the\n * check.\n *\n * Looked up in the `node_modules` at or above the file, as an `import` from the\n * file would look, so it is the tsx of the project the file belongs to.\n * `require.resolve` alone also searches `NODE_PATH`, which can point outside\n * the project: pnpm's bin shims set it to a store. A URL, because `--import`\n * takes a specifier, which a Windows path is not.\n */\nexport const resolveTsxLoader = (file: string): string | undefined => {\n for (let current = dirname(file); ; current = dirname(current)) {\n const manifest = join(current, \"node_modules\", \"tsx\", \"package.json\");\n\n if (existsSync(manifest)) {\n try {\n return pathToFileURL(createRequire(manifest).resolve(\"tsx\")).href;\n } catch {\n // Installed, but without the loader `--import tsx` would load.\n return undefined;\n }\n }\n\n if (dirname(current) === current) {\n return undefined;\n }\n }\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,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;AAAA,EACA;AAAA,EACA;AACF;AAeK,IAAM,kBAAkB,CAC7B,YAC0B;AAC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,KAAK,MAAM;AAE1D,UAAI,UAAU,QAAQ;AACpB,gBAAQ,MAAM,gDAA2C;AAEzD,cAAM,cAAc,qBAAqB,SAAS;AAElD,YAAI,aAAa;AACf,kBAAQ,MAAM,WAAW;AAAA,QAC3B;AAEA,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAEA,cAAQ,IAAI,oDAA+C;AAE3D,YAAM,YAAY,iBAAiB,QAAQ;AAC3C,YAAM,CAAC,kBAAkB,GAAG,aAAa,IAAI;AAAA,QAC3C;AAAA,QACA,EAAE,UAAU;AAAA,MACd;AACA,YAAM,iBAAiB,MAAMF,OAAM,kBAAkB,eAAe;AAAA,QAClE,QAAQ;AAAA,MACV,CAAC;AAED,UAAI,eAAe,QAAQ;AAIzB,cAAM,SAAS,qBAAqB,cAAc;AAElD,YAAI,QAAQ;AACV,kBAAQ,MAAM,MAAM;AAAA,QACtB,OAAO;AACL,kBAAQ,MAAM,qDAAgD;AAC9D,kBAAQ;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAEA,cAAM,OAAO,eAAe,UAAU,SAAS;AAE/C,YAAI,MAAM;AACR,kBAAQ,MAAM,IAAI;AAAA,QACpB;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"]}
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 missingTsxHint,\n resolveTsxLoader,\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 tsxLoader = resolveTsxLoader(filePath);\n const [structureCommand, ...structureArgs] = buildStructureCheckCommand(\n filePath,\n { tsxLoader },\n );\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 const hint = missingTsxHint(filePath, tsxLoader);\n\n if (hint) {\n console.error(hint);\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 // `--` ends mcp-cli's own options. Its parser reads any flag it meets, known\n // or not, and takes the next word as that flag's value, so `--watch` and the\n // file never reached the server: `npx tsx` started with no file at all.\n return [\n \"npx\",\n \"@wong2/mcp-cli\",\n \"--\",\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 { createRequire } from \"module\";\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 *\n * It imports nothing but the file. A bare specifier in a `-e` script resolves\n * from the working directory, not from the file, so importing\n * `@vitemcp/server` here failed any file whose project was not the directory\n * the command ran in — `vitemcp validate packages/app/server.ts` from the root\n * of a monorepo — before the file's own imports, which do resolve from beside\n * it, were tried.\n */\nexport const STRUCTURE_CHECK_SCRIPT = `\n(async () => {\n let failure;\n\n try {\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 *\n * `composite` also implies `declaration`, which `declarationMap`,\n * `emitDeclarationOnly` and `isolatedDeclarations` each require, so a composite\n * project may set them without it — and with `composite` off, its check failed\n * with TS5069. Nothing is emitted, so they are switched off as well.\n */\nconst PROJECT_OVERRIDES = {\n composite: false,\n declarationMap: false,\n emitDeclarationOnly: false,\n incremental: false,\n isolatedDeclarations: false,\n};\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 *\n * Given the project's tsx loader (see `resolveTsxLoader`), the child imports\n * the file through it, so the file loads the way `vitemcp dev` runs it. tsx\n * registers itself with `module.register()`, which Node 26 deprecates\n * (DEP0205); that warning alone is switched off, because it would otherwise be\n * replayed with a failure as though the file had caused it.\n */\nexport const buildStructureCheckCommand = (\n file: string,\n {\n execPath = process.execPath,\n tsxLoader,\n }: { execPath?: string; tsxLoader?: string } = {},\n): [string, ...string[]] => [\n execPath,\n ...(tsxLoader ? [\"--disable-warning=DEP0205\", \"--import\", tsxLoader] : []),\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 * What to add when the structure check fails without tsx. Plain Node rejects\n * TypeScript that tsx runs, so the failure may be the loader's rather than the\n * file's. Nothing for a JavaScript file, which loads the same either way.\n */\nexport const missingTsxHint = (\n file: string,\n tsxLoader: string | undefined,\n): string | undefined =>\n tsxLoader || !/\\.[cm]?tsx?$/i.test(file)\n ? undefined\n : \"[ViteMCP] tsx is not installed in this project, so the file was loaded with plain Node, which rejects `.js` imports of `.ts` files and syntax such as enums. Install tsx to validate the file the way `vitemcp dev` runs it: npm install --save-dev tsx\";\n\n/**\n * The project's tsx loader, as a `file:` URL for `--import`, or `undefined`\n * when the project does not have tsx installed.\n *\n * `vitemcp dev` runs a server file with tsx, but plain Node only strips types:\n * it rejects a `.js` import of a `.ts` file, and syntax it would have to\n * transform, such as an enum. So without tsx, a file `dev` ran fine failed the\n * check.\n *\n * Looked up in the `node_modules` at or above the file, as an `import` from the\n * file would look, so it is the tsx of the project the file belongs to.\n * `require.resolve` alone also searches `NODE_PATH`, which can point outside\n * the project: pnpm's bin shims set it to a store. A URL, because `--import`\n * takes a specifier, which a Windows path is not.\n */\nexport const resolveTsxLoader = (file: string): string | undefined => {\n for (let current = dirname(file); ; current = dirname(current)) {\n const manifest = join(current, \"node_modules\", \"tsx\", \"package.json\");\n\n if (existsSync(manifest)) {\n try {\n return pathToFileURL(createRequire(manifest).resolve(\"tsx\")).href;\n } catch {\n // Installed, but without the loader `--import tsx` would load.\n return undefined;\n }\n }\n\n if (dirname(current) === current) {\n return undefined;\n }\n }\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,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;AAAA,EACA;AAAA,EACA;AACF;AAeK,IAAM,kBAAkB,CAC7B,YAC0B;AAC1B,QAAM,EAAE,YAAY,MAAM,MAAM,UAAU,QAAQ,MAAM,IAAI;AAE5D,MAAI,MAAM;AACR,QAAI,CAAC,YAAY;AACf,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AA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CAAC;AAAA,MAChB;AAEA,cAAQ,IAAI,oDAA+C;AAE3D,YAAM,YAAY,iBAAiB,QAAQ;AAC3C,YAAM,CAAC,kBAAkB,GAAG,aAAa,IAAI;AAAA,QAC3C;AAAA,QACA,EAAE,UAAU;AAAA,MACd;AACA,YAAM,iBAAiB,MAAMF,OAAM,kBAAkB,eAAe;AAAA,QAClE,QAAQ;AAAA,MACV,CAAC;AAED,UAAI,eAAe,QAAQ;AAIzB,cAAM,SAAS,qBAAqB,cAAc;AAElD,YAAI,QAAQ;AACV,kBAAQ,MAAM,MAAM;AAAA,QACtB,OAAO;AACL,kBAAQ,MAAM,qDAAgD;AAC9D,kBAAQ;AAAA,YACN;AAAA,UACF;AAAA,QACF;AAEA,cAAM,OAAO,eAAe,UAAU,SAAS;AAE/C,YAAI,MAAM;AACR,kBAAQ,MAAM,IAAI;AAAA,QACpB;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"]}
@@ -392,6 +392,7 @@ var oauthTransactionStorageSchema = z.object({
392
392
  clientCodeChallenge: z.string(),
393
393
  clientCodeChallengeMethod: z.string(),
394
394
  clientId: z.string(),
395
+ consentBinding: z.string().optional(),
395
396
  consentGiven: z.boolean().optional(),
396
397
  createdAt: storedDateSchema,
397
398
  expiresAt: storedDateSchema,
@@ -713,22 +714,31 @@ var ConsentManager = class {
713
714
  }
714
715
  /**
715
716
  * Create HTTP response with consent screen
717
+ *
718
+ * `cookie` is a `Set-Cookie` value that ties the request to the browser the
719
+ * screen is shown to. The screen may not be framed: a page that embeds it
720
+ * could have the user approve without seeing what they are approving.
716
721
  */
717
- createConsentResponse(transaction, provider) {
722
+ createConsentResponse(transaction, provider, options = {}) {
718
723
  const consentData = {
719
- clientName: "MCP Client",
724
+ clientName: options.clientName || "MCP Client",
720
725
  provider,
726
+ redirectUri: transaction.clientCallbackUrl,
721
727
  scope: transaction.scope,
722
728
  timestamp: Date.now(),
723
729
  transactionId: transaction.id
724
730
  };
725
731
  const html = this.generateConsentScreen(consentData);
726
- return new Response(html, {
727
- headers: {
728
- "Content-Type": "text/html; charset=utf-8"
729
- },
730
- status: 200
732
+ const headers = new Headers({
733
+ "Cache-Control": "no-store",
734
+ "Content-Security-Policy": "frame-ancestors 'none'",
735
+ "Content-Type": "text/html; charset=utf-8",
736
+ "X-Frame-Options": "DENY"
731
737
  });
738
+ if (options.cookie) {
739
+ headers.append("Set-Cookie", options.cookie);
740
+ }
741
+ return new Response(html, { headers, status: 200 });
732
742
  }
733
743
  /**
734
744
  * Generate HTML for consent screen
@@ -739,7 +749,8 @@ var ConsentManager = class {
739
749
  * one no route answers, and Approve came back 404.
740
750
  */
741
751
  generateConsentScreen(data) {
742
- const { clientName, provider, scope, transactionId } = data;
752
+ const { clientName, provider, redirectUri, scope, transactionId } = data;
753
+ const destination = redirectUri && this.describeDestination(redirectUri);
743
754
  return `
744
755
  <!DOCTYPE html>
745
756
  <html lang="en">
@@ -807,6 +818,12 @@ var ConsentManager = class {
807
818
  font-weight: 600;
808
819
  }
809
820
 
821
+ .destination {
822
+ color: #4a5568;
823
+ font-size: 14px;
824
+ overflow-wrap: anywhere;
825
+ }
826
+
810
827
  .permissions {
811
828
  margin-top: 16px;
812
829
  }
@@ -905,10 +922,15 @@ var ConsentManager = class {
905
922
 
906
923
  <div class="app-info">
907
924
  <h2>
908
- <span class="app-name">${this.escapeHtml(clientName || "An application")}</span>
925
+ <span class="app-name">${this.escapeHtml((clientName || "An application").slice(0, 100))}</span>
909
926
  requests access
910
927
  </h2>
911
-
928
+ ${destination ? `
929
+ <p class="destination">
930
+ If you approve, you will be sent to
931
+ <strong>${this.escapeHtml(destination)}</strong>
932
+ </p>
933
+ ` : ""}
912
934
  <div class="permissions">
913
935
  <h3>This will allow the app to:</h3>
914
936
  <ul>
@@ -978,6 +1000,23 @@ var ConsentManager = class {
978
1000
  return null;
979
1001
  }
980
1002
  }
1003
+ /**
1004
+ * Where a redirect URI leads, as the browser will read it rather than as it
1005
+ * was typed: the parsed host, so that a look-alike character, a tab or a
1006
+ * backslash shows for what it does. A long host keeps its end, which is the
1007
+ * part that says whose it is.
1008
+ */
1009
+ describeDestination(redirectUri) {
1010
+ let url;
1011
+ try {
1012
+ url = new URL(redirectUri);
1013
+ } catch {
1014
+ return void 0;
1015
+ }
1016
+ const host = url.host.length > 80 ? `\u2026${url.host.slice(-80)}` : url.host;
1017
+ const path = url.pathname.length > 80 ? `${url.pathname.slice(0, 80)}\u2026` : url.pathname;
1018
+ return host ? `${url.protocol}//${host}${path}` : `${url.protocol}${path}`;
1019
+ }
981
1020
  /**
982
1021
  * Escape HTML to prevent XSS
983
1022
  */
@@ -1511,7 +1550,6 @@ var OAuthProxy = class {
1511
1550
  constructor(config) {
1512
1551
  this.config = {
1513
1552
  authorizationCodeTtl: DEFAULT_AUTHORIZATION_CODE_TTL,
1514
- consentRequired: true,
1515
1553
  enableTokenSwap: true,
1516
1554
  // Enabled by default for security
1517
1555
  redirectPath: DEFAULT_REDIRECT_PATH,
@@ -1519,7 +1557,10 @@ var OAuthProxy = class {
1519
1557
  upstreamRequestTimeoutMs: DEFAULT_UPSTREAM_REQUEST_TIMEOUT_MS,
1520
1558
  upstreamTokenEndpointAuthMethod: "client_secret_basic",
1521
1559
  ...config,
1522
- baseUrl: withoutTrailingSlash(config.baseUrl)
1560
+ baseUrl: withoutTrailingSlash(config.baseUrl),
1561
+ // Spreading an explicit `undefined` over the default would turn consent
1562
+ // off for a caller that only meant to pass an option along.
1563
+ consentRequired: config.consentRequired ?? true
1523
1564
  };
1524
1565
  let storage = config.tokenStorage;
1525
1566
  if (!storage) {
@@ -1560,8 +1601,13 @@ var OAuthProxy = class {
1560
1601
  }
1561
1602
  /**
1562
1603
  * OAuth authorization endpoint
1604
+ *
1605
+ * With consent required the response is the consent screen, and it sets the
1606
+ * cookie that the request is approved and finished with: return its headers
1607
+ * to the browser. Pass that browser's `request` as well, so that one with
1608
+ * several authorization requests open keeps a single cookie for all of them.
1563
1609
  */
1564
- async authorize(params) {
1610
+ async authorize(params, request2) {
1565
1611
  if (!params.client_id || !params.redirect_uri || !params.response_type) {
1566
1612
  throw new OAuthProxyError(
1567
1613
  "invalid_request",
@@ -1613,11 +1659,17 @@ var OAuthProxy = class {
1613
1659
  );
1614
1660
  }
1615
1661
  }
1616
- const transaction = await this.createTransaction(params);
1617
- if (this.config.consentRequired && !transaction.consentGiven) {
1662
+ const consentBinding = this.config.consentRequired ? (request2 && this.consentCookieValue(request2)) ?? this.generateId() : void 0;
1663
+ const transaction = await this.createTransaction(params, consentBinding);
1664
+ if (consentBinding && !transaction.consentGiven) {
1665
+ const clientName = registeredClient.metadata?.client_name;
1618
1666
  return this.consentManager.createConsentResponse(
1619
1667
  transaction,
1620
- this.getProviderName()
1668
+ this.getProviderName(),
1669
+ {
1670
+ clientName: typeof clientName === "string" ? clientName : void 0,
1671
+ cookie: this.consentCookie(consentBinding)
1672
+ }
1621
1673
  );
1622
1674
  }
1623
1675
  return this.redirectToUpstream(transaction);
@@ -1801,6 +1853,12 @@ var OAuthProxy = class {
1801
1853
  if (!transaction) {
1802
1854
  throw new OAuthProxyError("invalid_request", "Invalid or expired state");
1803
1855
  }
1856
+ if (this.config.consentRequired && !(transaction.consentGiven && this.isConsentBoundTo(request2, transaction))) {
1857
+ throw new OAuthProxyError(
1858
+ "access_denied",
1859
+ "This authorization request was not approved in this browser"
1860
+ );
1861
+ }
1804
1862
  if (!await this.isTransactionCallbackRegistered(transaction)) {
1805
1863
  throw new OAuthProxyError(
1806
1864
  "invalid_request",
@@ -1850,6 +1908,12 @@ var OAuthProxy = class {
1850
1908
  "Invalid or expired transaction"
1851
1909
  );
1852
1910
  }
1911
+ if (!this.isConsentBoundTo(request2, transaction)) {
1912
+ throw new OAuthProxyError(
1913
+ "invalid_request",
1914
+ "Consent must be given in the browser that requested it"
1915
+ );
1916
+ }
1853
1917
  if (action === "deny") {
1854
1918
  await this.stateStore.deleteTransaction(transactionId);
1855
1919
  if (!await this.isTransactionCallbackRegistered(transaction)) {
@@ -2044,10 +2108,49 @@ var OAuthProxy = class {
2044
2108
  );
2045
2109
  });
2046
2110
  }
2111
+ /**
2112
+ * The cookie that ties consent requests to the browser they were shown to.
2113
+ * A browser holds one, shared by every request it has open, and it lasts as
2114
+ * long as a request does. `Lax` lets it travel with the provider's redirect
2115
+ * back to the callback, which is a cross-site navigation. Over HTTPS the
2116
+ * `__Host-` prefix keeps another host on the same site from setting it.
2117
+ */
2118
+ consentCookie(value) {
2119
+ return [
2120
+ `${this.consentCookieName()}=${value}`,
2121
+ "Path=/",
2122
+ `Max-Age=${this.config.transactionTtl || DEFAULT_TRANSACTION_TTL}`,
2123
+ "HttpOnly",
2124
+ "SameSite=Lax",
2125
+ ...this.isServedOverHttps() ? ["Secure"] : []
2126
+ ].join("; ");
2127
+ }
2128
+ consentCookieName() {
2129
+ return `${this.isServedOverHttps() ? "__Host-" : ""}vitemcp-consent`;
2130
+ }
2131
+ /**
2132
+ * The consent cookie `request` carries, if it carries a well-formed one.
2133
+ *
2134
+ * Only the spaces and tabs that may surround a cookie are dropped. Trimming
2135
+ * all white space would take a cookie whose name begins with, say, a
2136
+ * no-break space for this one, and a browser does not hold such a name to
2137
+ * the `__Host-` rules.
2138
+ */
2139
+ consentCookieValue(request2) {
2140
+ const name = this.consentCookieName();
2141
+ for (const pair of (request2.headers.get("cookie") ?? "").split(";")) {
2142
+ const separator = pair.indexOf("=");
2143
+ if (separator !== -1 && withoutOptionalWhitespace(pair.slice(0, separator)) === name) {
2144
+ const value = withoutOptionalWhitespace(pair.slice(separator + 1));
2145
+ return GENERATED_ID.test(value) ? value : void 0;
2146
+ }
2147
+ }
2148
+ return void 0;
2149
+ }
2047
2150
  /**
2048
2151
  * Create a new OAuth transaction
2049
2152
  */
2050
- async createTransaction(params) {
2153
+ async createTransaction(params, consentBinding) {
2051
2154
  const transactionId = this.generateId();
2052
2155
  const proxyPkce = PKCEUtils.generatePair("S256");
2053
2156
  const transaction = {
@@ -2055,6 +2158,7 @@ var OAuthProxy = class {
2055
2158
  clientCodeChallenge: params.code_challenge || "",
2056
2159
  clientCodeChallengeMethod: params.code_challenge_method || "plain",
2057
2160
  clientId: params.client_id,
2161
+ ...consentBinding && { consentBinding: sha256(consentBinding) },
2058
2162
  createdAt: /* @__PURE__ */ new Date(),
2059
2163
  expiresAt: new Date(
2060
2164
  Date.now() + (this.config.transactionTtl || 600) * 1e3
@@ -2095,7 +2199,7 @@ var OAuthProxy = class {
2095
2199
  let errorCode = "server_error";
2096
2200
  let errorDescription;
2097
2201
  try {
2098
- const error = await tokenResponse.json();
2202
+ const error = await this.readUpstreamError(tokenResponse);
2099
2203
  errorCode = error.error || "server_error";
2100
2204
  errorDescription = error.error_description;
2101
2205
  } catch {
@@ -2299,7 +2403,7 @@ var OAuthProxy = class {
2299
2403
  let errorCode = "invalid_grant";
2300
2404
  let errorDescription;
2301
2405
  try {
2302
- const error = await tokenResponse.json();
2406
+ const error = await this.readUpstreamError(tokenResponse);
2303
2407
  errorCode = error.error || "invalid_grant";
2304
2408
  errorDescription = error.error_description;
2305
2409
  } catch {
@@ -2425,6 +2529,21 @@ var OAuthProxy = class {
2425
2529
  throw error;
2426
2530
  }
2427
2531
  }
2532
+ /**
2533
+ * Whether `request` comes from the browser the transaction's consent screen
2534
+ * was shown to: it carries the cookie that screen set. A transaction that
2535
+ * never had a consent screen is bound to no browser.
2536
+ */
2537
+ isConsentBoundTo(request2, transaction) {
2538
+ const presented = this.consentCookieValue(request2);
2539
+ return Boolean(
2540
+ presented && transaction.consentBinding && secretsMatch(sha256(presented), transaction.consentBinding)
2541
+ );
2542
+ }
2543
+ /** Whether browsers reach this proxy over HTTPS, going by its `baseUrl`. */
2544
+ isServedOverHttps() {
2545
+ return /^https:/i.test(this.config.baseUrl);
2546
+ }
2428
2547
  /**
2429
2548
  * Issue swapped tokens (JWT pattern)
2430
2549
  * Issues short-lived ViteMCP JWTs and stores upstream tokens securely
@@ -2685,6 +2804,40 @@ var OAuthProxy = class {
2685
2804
  const digest = createHash3("sha256").update(refreshToken).digest("base64url");
2686
2805
  return `passthrough-refresh:${this.issuerNs}:${digest}`;
2687
2806
  }
2807
+ /**
2808
+ * What a refusal from the token endpoint says: the `error` and
2809
+ * `error_description` RFC 6749 §5.2 gives it.
2810
+ *
2811
+ * §5.2 sends them as JSON, but a provider that answers a successful request
2812
+ * with a form — GitHub, by default — may refuse with one too, and read as
2813
+ * JSON that lost the provider's own code and description to a bare HTTP
2814
+ * status.
2815
+ *
2816
+ * What parses as JSON is read as JSON, whatever the response declares, as
2817
+ * every refusal was before. A form is read only when the response declares
2818
+ * one, by its media type alone: a 502 page can name that type in a parameter
2819
+ * and carry `error=` in a link, and is no provider's refusal. Rejects when
2820
+ * the body is neither, and the caller falls back to the HTTP status.
2821
+ */
2822
+ async readUpstreamError(response) {
2823
+ const text = await response.text();
2824
+ try {
2825
+ return JSON.parse(text);
2826
+ } catch (cause) {
2827
+ const mediaType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();
2828
+ if (mediaType === "application/x-www-form-urlencoded") {
2829
+ const params = new URLSearchParams(text);
2830
+ const error = params.get("error");
2831
+ if (error) {
2832
+ return {
2833
+ error,
2834
+ error_description: params.get("error_description") ?? void 0
2835
+ };
2836
+ }
2837
+ }
2838
+ throw cause;
2839
+ }
2840
+ }
2688
2841
  /**
2689
2842
  * Send the user's browser back to the client's registered callback with how
2690
2843
  * its request came out: a code, or an error (RFC 6749 §4.1.2). The `state`
@@ -2770,7 +2923,7 @@ var OAuthProxy = class {
2770
2923
  let errorCode = "invalid_grant";
2771
2924
  let errorDescription = "Upstream refresh failed";
2772
2925
  try {
2773
- const error = await tokenResponse.json();
2926
+ const error = await this.readUpstreamError(tokenResponse);
2774
2927
  errorCode = error.error || "invalid_grant";
2775
2928
  errorDescription = error.error_description || "Upstream refresh failed";
2776
2929
  } catch {
@@ -3047,6 +3200,8 @@ var secretsMatch = (presented, expected) => timingSafeEqual4(
3047
3200
  createHash3("sha256").update(presented).digest(),
3048
3201
  createHash3("sha256").update(expected).digest()
3049
3202
  );
3203
+ var sha256 = (value) => createHash3("sha256").update(value).digest("base64url");
3204
+ var withoutOptionalWhitespace = (value) => value.replace(/^[ \t]+|[ \t]+$/g, "");
3050
3205
  var OAuthProxyError = class extends Error {
3051
3206
  constructor(code, description, statusCode = 400) {
3052
3207
  super(code);
@@ -3110,11 +3265,12 @@ var AuthProvider = class {
3110
3265
  if (!request2) {
3111
3266
  return void 0;
3112
3267
  }
3113
- const authHeader = request2.headers.get("authorization");
3114
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
3268
+ const token = /^bearer +(\S.*)$/i.exec(
3269
+ request2.headers.get("authorization") ?? ""
3270
+ )?.[1];
3271
+ if (!token) {
3115
3272
  return void 0;
3116
3273
  }
3117
- const token = authHeader.slice(7);
3118
3274
  const upstreamTokens = await this.proxy.loadUpstreamTokens(token);
3119
3275
  if (!upstreamTokens) {
3120
3276
  return void 0;
@@ -3719,4 +3875,4 @@ export {
3719
3875
  DiskStore,
3720
3876
  JWKSVerifier
3721
3877
  };
3722
- //# sourceMappingURL=chunk-WOQXAQIG.js.map
3878
+ //# sourceMappingURL=chunk-4BX2CT5Z.js.map