fastmcp 4.23.11 → 4.23.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/FastMCP.cjs +3 -3
  2. package/dist/FastMCP.d.cts +2 -2
  3. package/dist/FastMCP.d.ts +2 -2
  4. package/dist/FastMCP.js +2 -2
  5. package/dist/{OAuthProvider-BcDb5bOz.d.cts → OAuthProvider-84BWWDBF.d.cts} +55 -1
  6. package/dist/{OAuthProvider-BcDb5bOz.d.ts → OAuthProvider-84BWWDBF.d.ts} +55 -1
  7. package/dist/auth/index.cjs +4 -2
  8. package/dist/auth/index.cjs.map +1 -1
  9. package/dist/auth/index.d.cts +10 -2
  10. package/dist/auth/index.d.ts +10 -2
  11. package/dist/auth/index.js +3 -1
  12. package/dist/bin/fastmcp.cjs +22 -2
  13. package/dist/bin/fastmcp.cjs.map +1 -1
  14. package/dist/bin/fastmcp.js +22 -2
  15. package/dist/bin/fastmcp.js.map +1 -1
  16. package/dist/{chunk-X5ITW7FV.cjs → chunk-4P2GDM7W.cjs} +74 -35
  17. package/dist/chunk-4P2GDM7W.cjs.map +1 -0
  18. package/dist/{chunk-4OWHPJEL.cjs → chunk-BV4PWTT6.cjs} +214 -43
  19. package/dist/chunk-BV4PWTT6.cjs.map +1 -0
  20. package/dist/{chunk-G44SPVP7.js → chunk-CAQLTSJ5.js} +211 -40
  21. package/dist/chunk-CAQLTSJ5.js.map +1 -0
  22. package/dist/{chunk-XUUJOVC7.js → chunk-ULNQF5KG.js} +57 -18
  23. package/dist/chunk-ULNQF5KG.js.map +1 -0
  24. package/dist/examples/custom-routes.cjs +3 -3
  25. package/dist/examples/custom-routes.js +2 -2
  26. package/dist/openapi/index.cjs +7 -7
  27. package/dist/openapi/index.d.cts +1 -1
  28. package/dist/openapi/index.d.ts +1 -1
  29. package/dist/openapi/index.js +2 -2
  30. package/package.json +2 -1
  31. package/dist/chunk-4OWHPJEL.cjs.map +0 -1
  32. package/dist/chunk-G44SPVP7.js.map +0 -1
  33. package/dist/chunk-X5ITW7FV.cjs.map +0 -1
  34. package/dist/chunk-XUUJOVC7.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/fastmcp.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 buildTypeCheckCommand,\n formatCommandFailure,\n withTypeCheckProject,\n} from \"./validateCommand.js\";\n\nawait yargs(hideBin(process.argv))\n .scriptName(\"fastmcp\")\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(\"[FastMCP Error] --args requires --tool\");\n process.exitCode = 1;\n return;\n }\n\n if (argv.tool && argv.watch) {\n console.warn(\n \"[FastMCP] --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(), \"fastmcp-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 `[FastMCP] Starting server: ${[command, ...commandArgs].join(\" \")}`,\n );\n console.log(`[FastMCP] File: ${argv.file}`);\n console.log(\n `[FastMCP] Watch mode: ${argv.watch ? \"enabled\" : \"disabled\"}`,\n );\n\n if (argv.tool) {\n console.log(`[FastMCP] 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 \"[FastMCP 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(\"[FastMCP 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 \"[FastMCP 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 FastMCP 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(`[FastMCP Error] File not found: ${filePath}`);\n process.exit(1);\n }\n\n console.log(`[FastMCP] Validating server file: ${filePath}`);\n\n try {\n await withTypeCheckProject(filePath, (project) => {\n const [typeCheckCommand, ...typeCheckArgs] = buildTypeCheckCommand(\n filePath,\n { project, strict: argv.strict },\n );\n\n return execa(typeCheckCommand, typeCheckArgs, {\n stderr: \"pipe\",\n stdout: \"pipe\",\n });\n });\n\n console.log(\"[FastMCP] ✓ TypeScript compilation successful\");\n } catch (tsError) {\n console.error(\"[FastMCP] ✗ TypeScript compilation failed\");\n\n const diagnostics = formatCommandFailure(tsError);\n\n if (diagnostics) {\n console.error(diagnostics);\n }\n\n process.exit(1);\n }\n\n const [structureCommand, ...structureArgs] =\n buildStructureCheckCommand(filePath);\n\n try {\n await execa(structureCommand, structureArgs, {\n stderr: \"pipe\",\n stdout: \"pipe\",\n });\n } catch (structureError) {\n // The child reports the reason on stderr, which execa captures. Without\n // replaying it the user only ever sees the generic hint below, even when\n // the server file has an error they could act on.\n const reason = formatCommandFailure(structureError);\n\n if (reason) {\n console.error(reason);\n } else {\n console.error(\"[FastMCP] ✗ Server structure validation failed\");\n console.error(\n \"Make sure the file properly imports and uses FastMCP\",\n );\n }\n\n process.exit(1);\n }\n\n console.log(\n \"[FastMCP] ✓ All validations passed! Server file looks good.\",\n );\n } catch (error) {\n console.error(\n \"[FastMCP Error] Validation failed:\",\n error instanceof Error ? error.message : String(error),\n );\n\n process.exit(1);\n }\n },\n )\n\n .demandCommand(1)\n .strict()\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 { existsSync } from \"node:fs\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * Compiler options for type-checking a server file with no `tsconfig.json`\n * above it. tsc's own defaults (ES5, CommonJS-era module resolution) cannot\n * even read FastMCP's declarations, which use private class fields and a\n * default import of `http`, so no real server file could pass under them.\n * These describe how a server actually runs instead: as an ES module on a\n * current Node, which can import `.ts` files directly.\n */\nexport const DEFAULT_TYPE_CHECK_OPTIONS = [\n \"--allowImportingTsExtensions\",\n \"--module\",\n \"esnext\",\n \"--moduleResolution\",\n \"bundler\",\n \"--skipLibCheck\",\n \"--target\",\n \"es2022\",\n];\n\n/**\n * The script that `fastmcp validate` runs to check a server file can be\n * imported.\n *\n * The target file is read from `process.argv[1]` instead of being spliced into\n * this source. Splicing is not equivalent: the path would land inside a\n * JavaScript string literal, so the child's own parser would consume the\n * backslashes of a Windows path as string escapes. `C:\\Users\\dev\\server.ts`\n * reaches the import as `C:Usersdevserver.ts`, which throws `ERR_INVALID_URL`\n * and is reported to the user as \"does not import FastMCP\" even though the file\n * is fine.\n *\n * The script exits explicitly once the import settles. Importing a server file\n * normally starts the server, and a running server — a stdio transport waiting\n * on stdin, an HTTP listener — keeps the process alive indefinitely, so\n * validating a server that calls `start()` would otherwise never finish.\n */\nexport const STRUCTURE_CHECK_SCRIPT = `\n(async () => {\n try {\n const { FastMCP } = await import(\"fastmcp\");\n await import(process.argv[1]);\n console.log(\"[FastMCP] ✓ Server structure validation passed\");\n } catch (error) {\n console.error(\"[FastMCP] ✗ Server structure validation failed:\", error.message);\n process.exitCode = 1;\n }\n\n process.exit();\n})();\n`;\n\n/**\n * Build the argv for the type-check step.\n *\n * This is an argv array rather than a shell string so that nothing has to be\n * quoted: the file path is passed to tsc verbatim, so a path containing spaces\n * stays one argument. Quoting through a shell would be wrong on Windows, where\n * cmd.exe re-parses the command line and splits such a path into several root\n * files.\n *\n * Given a `project` (see `withTypeCheckProject`), tsc checks the file through\n * it; without one, the file is passed directly with\n * `DEFAULT_TYPE_CHECK_OPTIONS`.\n */\nexport const buildTypeCheckCommand = (\n file: string,\n { project, strict = false }: { project?: string; strict?: boolean } = {},\n): [string, ...string[]] => [\n \"npx\",\n \"tsc\",\n \"--noEmit\",\n ...(strict ? [\"--strict\"] : []),\n ...(project ? [\"--project\", project] : [...DEFAULT_TYPE_CHECK_OPTIONS, file]),\n];\n\n/**\n * Build a tsconfig that checks only `file`, with the compiler options of the\n * project's own `tsconfig`.\n *\n * `tsc <file>` ignores tsconfig.json altogether and falls back to tsc's\n * defaults, while `tsc --project tsconfig.json` checks every file in the\n * project rather than the one being validated. Extending the project's config\n * and listing just `file` gets both right. A project that is `incremental` or\n * `composite` still writes a `.tsbuildinfo` under `--noEmit`, so both are\n * switched off: validating a file should leave the project untouched. Disable\n * declaration output options too, since they may rely on composite's implicit\n * `declaration: true`; `declarationDir` takes a path, so `null` unsets it.\n */\nexport const buildTypeCheckProject = (tsconfig: string, file: string): string =>\n JSON.stringify({\n compilerOptions: {\n composite: false,\n declarationDir: null,\n declarationMap: false,\n emitDeclarationOnly: false,\n incremental: false,\n },\n extends: `./${basename(tsconfig)}`,\n files: [file],\n include: [],\n });\n\n/**\n * Find the `tsconfig.json` that applies to files in `dir`: the nearest one in\n * it or any of its parents, which is where tsc and editors look too.\n */\nexport const findTsconfig = (dir: string): string | undefined => {\n const candidate = join(dir, \"tsconfig.json\");\n\n if (existsSync(candidate)) {\n return candidate;\n }\n\n const parent = dirname(dir);\n\n return parent === dir ? undefined : findTsconfig(parent);\n};\n\n/**\n * Run `check` with a throwaway tsconfig for `file` (see\n * `buildTypeCheckProject`), or with no project when the file has no\n * `tsconfig.json` above it.\n *\n * The throwaway config is written next to the one it extends and removed once\n * `check` settles. It cannot live in a temporary directory: tsc looks for the\n * `@types` packages it includes by default relative to the config file, so\n * from anywhere else a server using, say, `process.env` would stop compiling.\n */\nexport const withTypeCheckProject = async <T>(\n file: string,\n check: (project?: string) => Promise<T>,\n): Promise<T> => {\n const tsconfig = findTsconfig(dirname(file));\n\n if (!tsconfig) {\n return check();\n }\n\n const project = join(\n dirname(tsconfig),\n `tsconfig.fastmcp-validate-${process.pid}.json`,\n );\n\n await writeFile(project, buildTypeCheckProject(tsconfig, file), \"utf8\");\n\n try {\n return await check(project);\n } finally {\n await rm(project, { force: true });\n }\n};\n\n/**\n * Build the argv for the structure-check step.\n *\n * As above, the file is passed as an argument rather than quoted into a shell\n * command. It is converted to a file URL by the parent process, so the child\n * receives the URL as-is and never has to reconstruct it. The child is the same\n * Node binary running the 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 * The output streams a failed command carries. execa sets both on the error it\n * throws, but they are optional here so the extraction stays honest about not\n * every `Error` having them.\n */\ntype CommandOutputStreams = {\n stderr?: unknown;\n stdout?: unknown;\n};\n\nconst hasOutputStreams = (\n error: Error,\n): error is CommandOutputStreams & Error =>\n \"stdout\" in error || \"stderr\" in error;\n\n/**\n * Extract the output of a failed command.\n *\n * tsc writes its diagnostics to stdout, while a failure to launch the compiler\n * at all (a missing `npx`, for instance) reports on stderr — reading only\n * stderr left the message empty for every real type error. The structure check\n * reports the reason on stderr, which execa captures, so it has to be replayed\n * here as well or the caller can only print a generic hint.\n *\n * An error that did not come from a command at all — the throwaway tsconfig\n * could not be written, say — is reported by its message.\n */\nexport const formatCommandFailure = (error: unknown): string => {\n if (!(error instanceof Error)) {\n return \"\";\n }\n\n if (!hasOutputStreams(error)) {\n return error.message;\n }\n\n const collect = (value: unknown): string =>\n typeof value === \"string\" ? value.trim() : \"\";\n\n return [collect(error.st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,YAC5C,QAAQ;AAAA,YACR,QAAQ;AAAA,UACV,CAAC;AAAA,QACH,CAAC;AAED,gBAAQ,IAAI,oDAA+C;AAAA,MAC7D,SAAS,SAAS;AAChB,gBAAQ,MAAM,gDAA2C;AAEzD,cAAM,cAAc,qBAAqB,OAAO;AAEhD,YAAI,aAAa;AACf,kBAAQ,MAAM,WAAW;AAAA,QAC3B;AAEA,gBAAQ,KAAK,CAAC;AAAA,MAChB;AAEA,YAAM,CAAC,kBAAkB,GAAG,aAAa,IACvC,2BAA2B,QAAQ;AAErC,UAAI;AACF,cAAM,MAAM,kBAAkB,eAAe;AAAA,UAC3C,QAAQ;AAAA,UACR,QAAQ;AAAA,QACV,CAAC;AAAA,MACH,SAAS,gBAAgB;AAIvB,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,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,cAAc,CAAC,EACf,OAAO,EACP,KAAK,EACL,WAAW;","names":["rm","writeFile","join","yargs","join","writeFile","rm","existsSync"]}
1
+ {"version":3,"sources":["../../src/bin/fastmcp.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 buildTypeCheckCommand,\n formatCommandFailure,\n resolveTsxLoader,\n TSX_HINT,\n withTypeCheckProject,\n} from \"./validateCommand.js\";\n\nawait yargs(hideBin(process.argv))\n .scriptName(\"fastmcp\")\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(\"[FastMCP Error] --args requires --tool\");\n process.exitCode = 1;\n return;\n }\n\n if (argv.tool && argv.watch) {\n console.warn(\n \"[FastMCP] --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(), \"fastmcp-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 `[FastMCP] Starting server: ${[command, ...commandArgs].join(\" \")}`,\n );\n console.log(`[FastMCP] File: ${argv.file}`);\n console.log(\n `[FastMCP] Watch mode: ${argv.watch ? \"enabled\" : \"disabled\"}`,\n );\n\n if (argv.tool) {\n console.log(`[FastMCP] 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 \"[FastMCP 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(\"[FastMCP 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 \"[FastMCP 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 FastMCP 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(`[FastMCP Error] File not found: ${filePath}`);\n process.exit(1);\n }\n\n console.log(`[FastMCP] Validating server file: ${filePath}`);\n\n try {\n await withTypeCheckProject(filePath, (project) => {\n const [typeCheckCommand, ...typeCheckArgs] = buildTypeCheckCommand(\n filePath,\n { project, strict: argv.strict },\n );\n\n return execa(typeCheckCommand, typeCheckArgs, {\n stderr: \"pipe\",\n stdout: \"pipe\",\n });\n });\n\n console.log(\"[FastMCP] ✓ TypeScript compilation successful\");\n } catch (tsError) {\n console.error(\"[FastMCP] ✗ TypeScript compilation failed\");\n\n const diagnostics = formatCommandFailure(tsError);\n\n if (diagnostics) {\n console.error(diagnostics);\n }\n\n process.exit(1);\n }\n\n const tsxLoader = resolveTsxLoader(filePath);\n const [structureCommand, ...structureArgs] = buildStructureCheckCommand(\n filePath,\n { tsxLoader },\n );\n\n try {\n await execa(structureCommand, structureArgs, {\n stderr: \"pipe\",\n stdout: \"pipe\",\n });\n } catch (structureError) {\n // The child reports the reason on stderr, which execa captures. Without\n // replaying it the user only ever sees the generic hint below, even when\n // the server file has an error they could act on.\n const reason = formatCommandFailure(structureError);\n\n if (reason) {\n console.error(reason);\n } else {\n console.error(\"[FastMCP] ✗ Server structure validation failed\");\n console.error(\n \"Make sure the file properly imports and uses FastMCP\",\n );\n }\n\n if (!tsxLoader) {\n console.error(TSX_HINT);\n }\n\n process.exit(1);\n }\n\n console.log(\n \"[FastMCP] ✓ All validations passed! Server file looks good.\",\n );\n } catch (error) {\n console.error(\n \"[FastMCP Error] Validation failed:\",\n error instanceof Error ? error.message : String(error),\n );\n\n process.exit(1);\n }\n },\n )\n\n .demandCommand(1)\n .strict()\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 { existsSync } from \"node:fs\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { basename, dirname, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/**\n * Compiler options for type-checking a server file with no `tsconfig.json`\n * above it. tsc's own defaults (ES5, CommonJS-era module resolution) cannot\n * even read FastMCP's declarations, which use private class fields and a\n * default import of `http`, so no real server file could pass under them.\n * These describe how a server actually runs instead: as an ES module on a\n * current Node, which can import `.ts` files directly.\n */\nexport const DEFAULT_TYPE_CHECK_OPTIONS = [\n \"--allowImportingTsExtensions\",\n \"--module\",\n \"esnext\",\n \"--moduleResolution\",\n \"bundler\",\n \"--skipLibCheck\",\n \"--target\",\n \"es2022\",\n];\n\n/**\n * The script that `fastmcp validate` runs to check a server file can be\n * imported.\n *\n * The target file is read from `process.argv[1]` instead of being spliced into\n * this source. Splicing is not equivalent: the path would land inside a\n * JavaScript string literal, so the child's own parser would consume the\n * backslashes of a Windows path as string escapes. `C:\\Users\\dev\\server.ts`\n * reaches the import as `C:Usersdevserver.ts`, which throws `ERR_INVALID_URL`\n * and is reported to the user as \"does not import FastMCP\" even though the file\n * is fine.\n *\n * The script exits explicitly once the import settles. Importing a server file\n * normally starts the server, and a running server — a stdio transport waiting\n * on stdin, an HTTP listener — keeps the process alive indefinitely, so\n * validating a server that calls `start()` would otherwise never finish.\n */\nexport const STRUCTURE_CHECK_SCRIPT = `\n(async () => {\n try {\n const { FastMCP } = await import(\"fastmcp\");\n await import(process.argv[1]);\n console.log(\"[FastMCP] ✓ Server structure validation passed\");\n } catch (error) {\n console.error(\"[FastMCP] ✗ Server structure validation failed:\", error.message);\n process.exitCode = 1;\n }\n\n process.exit();\n})();\n`;\n\n/**\n * Build the argv for the type-check step.\n *\n * This is an argv array rather than a shell string so that nothing has to be\n * quoted: the file path is passed to tsc verbatim, so a path containing spaces\n * stays one argument. Quoting through a shell would be wrong on Windows, where\n * cmd.exe re-parses the command line and splits such a path into several root\n * files.\n *\n * Given a `project` (see `withTypeCheckProject`), tsc checks the file through\n * it; without one, the file is passed directly with\n * `DEFAULT_TYPE_CHECK_OPTIONS`.\n */\nexport const buildTypeCheckCommand = (\n file: string,\n { project, strict = false }: { project?: string; strict?: boolean } = {},\n): [string, ...string[]] => [\n \"npx\",\n \"tsc\",\n \"--noEmit\",\n ...(strict ? [\"--strict\"] : []),\n ...(project ? [\"--project\", project] : [...DEFAULT_TYPE_CHECK_OPTIONS, file]),\n];\n\n/**\n * Build a tsconfig that checks only `file`, with the compiler options of the\n * project's own `tsconfig`.\n *\n * `tsc <file>` ignores tsconfig.json altogether and falls back to tsc's\n * defaults, while `tsc --project tsconfig.json` checks every file in the\n * project rather than the one being validated. Extending the project's config\n * and listing just `file` gets both right. A project that is `incremental` or\n * `composite` still writes a `.tsbuildinfo` under `--noEmit`, so both are\n * switched off: validating a file should leave the project untouched. Disable\n * declaration output options too, since they may rely on composite's implicit\n * `declaration: true`; `declarationDir` takes a path, so `null` unsets it.\n */\nexport const buildTypeCheckProject = (tsconfig: string, file: string): string =>\n JSON.stringify({\n compilerOptions: {\n composite: false,\n declarationDir: null,\n declarationMap: false,\n emitDeclarationOnly: false,\n incremental: false,\n },\n extends: `./${basename(tsconfig)}`,\n files: [file],\n include: [],\n });\n\n/**\n * Find the `tsconfig.json` that applies to files in `dir`: the nearest one in\n * it or any of its parents, which is where tsc and editors look too.\n */\nexport const findTsconfig = (dir: string): string | undefined => {\n const candidate = join(dir, \"tsconfig.json\");\n\n if (existsSync(candidate)) {\n return candidate;\n }\n\n const parent = dirname(dir);\n\n return parent === dir ? undefined : findTsconfig(parent);\n};\n\n/**\n * Run `check` with a throwaway tsconfig for `file` (see\n * `buildTypeCheckProject`), or with no project when the file has no\n * `tsconfig.json` above it.\n *\n * The throwaway config is written next to the one it extends and removed once\n * `check` settles. It cannot live in a temporary directory: tsc looks for the\n * `@types` packages it includes by default relative to the config file, so\n * from anywhere else a server using, say, `process.env` would stop compiling.\n */\nexport const withTypeCheckProject = async <T>(\n file: string,\n check: (project?: string) => Promise<T>,\n): Promise<T> => {\n const tsconfig = findTsconfig(dirname(file));\n\n if (!tsconfig) {\n return check();\n }\n\n const project = join(\n dirname(tsconfig),\n `tsconfig.fastmcp-validate-${process.pid}.json`,\n );\n\n await writeFile(project, buildTypeCheckProject(tsconfig, file), \"utf8\");\n\n try {\n return await check(project);\n } finally {\n await rm(project, { force: true });\n }\n};\n\n/**\n * Find tsx in the project `file` belongs to, as the file: URL of its loader.\n *\n * `fastmcp dev` runs a server with tsx. Node alone only strips types: it\n * cannot follow the `.js` import of a `.ts` file that TypeScript itself asks\n * for, nor run syntax that has to be transformed, like `enum` — and since Node\n * 26 no flag makes it. So the structure check loads the file through the\n * project's tsx when there is one, the way `dev` runs it.\n *\n * Resolved here rather than by the child: `--import tsx` would resolve from\n * the child's working directory, and fail the whole check wherever tsx is not\n * installed. A URL, because `--import` reads a Windows path as a URL scheme.\n */\nexport const resolveTsxLoader = (file: string): string | undefined => {\n try {\n return pathToFileURL(createRequire(file).resolve(\"tsx\")).href;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Printed when the structure check fails and the project has no tsx, so the\n * file was loaded by Node alone (see `resolveTsxLoader`).\n */\nexport const TSX_HINT =\n \"[FastMCP] Hint: if the file imports .ts files with .js extensions, or uses TypeScript syntax Node cannot strip (such as enum), add tsx to your project's devDependencies. validate then loads the file through tsx, as `fastmcp dev` does.\";\n\n/**\n * Build the argv for the structure-check step.\n *\n * As above, the file is passed as an argument rather than quoted into a shell\n * command. It is converted to a file URL by the parent process, so the child\n * receives the URL as-is and never has to reconstruct it. The child is the same\n * Node binary running the CLI, so no PATH lookup is involved.\n *\n * Given a `tsxLoader` (see `resolveTsxLoader`), the child loads it first.\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 ? [\"--import\", tsxLoader] : []),\n \"-e\",\n STRUCTURE_CHECK_SCRIPT,\n pathToFileURL(file).href,\n];\n\n/**\n * The output streams a failed command carries. execa sets both on the error it\n * throws, but they are optional here so the extraction stays honest about not\n * every `Error` having them.\n */\ntype CommandOutputStreams = {\n stderr?: unknown;\n stdout?: unknown;\n};\n\nconst hasOutputStreams = (\n error: Error,\n): error is CommandOutputStreams & Error =>\n \"stdout\" in error || \"stderr\" in error;\n\n/**\n * Extract the output of a failed command.\n *\n * tsc writes its diagnostics to stdout, while a failure to launch the compiler\n * at all (a missing `npx`, for instance) reports on stderr — reading only\n * stderr left the message empty for every real type error. The structure check\n * reports the reason on stderr, which execa captures, so it has to be replayed\n * here as well or the caller can only print a generic hint.\n *\n * An error that did not come from a command at all — the throwaway tsconfig\n * could not be written, say — is reported by its message.\n */\nexport const formatCommandFailure = (error: unknown): string => {\n if (!(error instanceof Error)) {\n return \"\";\n }\n\n if (!hasOutputStreams(error)) {\n return error.message;\n }\n\n const collect = (value: unknown): string =>\n typeof value === \"string\" ? value.trim() : \"\";\n\n return [collect(error.stderr), collect(error.stdout)]\n .filter(Boolean)\n .join(\"\\n\");\n};\n"],"mappings":";;;AAEA,SAAS,aAAa;AACtB,SAAS,SAAS,MAAAA,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;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,GAAG,eAAe,IAAI,IAAI;AAAA,MAC1B,GAA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,QAAQ;AAAA,UACR,QAAQ;AAAA,QACV,CAAC;AAAA,MACH,SAAS,gBAAgB;AAIvB,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,YAAI,CAAC,WAAW;AACd,kBAAQ,MAAM,QAAQ;AAAA,QACxB;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,cAAc,CAAC,EACf,OAAO,EACP,KAAK,EACL,WAAW;","names":["rm","writeFile","join","yargs","join","writeFile","rm","existsSync"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunk4OWHPJELcjs = require('./chunk-4OWHPJEL.cjs');
3
+ var _chunkBV4PWTT6cjs = require('./chunk-BV4PWTT6.cjs');
4
4
 
5
5
 
6
6
 
@@ -141,7 +141,7 @@ var DiscoveryDocumentCache = class {
141
141
  throw error;
142
142
  }
143
143
  if (!res.ok) {
144
- await _chunk4OWHPJELcjs.cancelResponseBody.call(void 0, res);
144
+ await _chunkBV4PWTT6cjs.cancelResponseBody.call(void 0, res);
145
145
  throw new Error(
146
146
  `Failed to fetch discovery document from ${url}: ${res.status} ${res.statusText}`
147
147
  );
@@ -258,7 +258,7 @@ var imageContent = async (input) => {
258
258
  signal: AbortSignal.timeout(timeoutMs)
259
259
  });
260
260
  if (!response.ok) {
261
- await _chunk4OWHPJELcjs.cancelResponseBody.call(void 0, response);
261
+ await _chunkBV4PWTT6cjs.cancelResponseBody.call(void 0, response);
262
262
  throw new Error(
263
263
  `Server responded with status: ${response.status} - ${response.statusText}`
264
264
  );
@@ -340,7 +340,7 @@ var audioContent = async (input) => {
340
340
  signal: AbortSignal.timeout(timeoutMs)
341
341
  });
342
342
  if (!response.ok) {
343
- await _chunk4OWHPJELcjs.cancelResponseBody.call(void 0, response);
343
+ await _chunkBV4PWTT6cjs.cancelResponseBody.call(void 0, response);
344
344
  throw new Error(
345
345
  `Server responded with status: ${response.status} - ${response.statusText}`
346
346
  );
@@ -1914,15 +1914,20 @@ function normalizePath(path) {
1914
1914
  return path.startsWith("/") ? path : `/${path}`;
1915
1915
  }
1916
1916
  function parseBasicAuthHeader(authHeader) {
1917
- const basicMatch = _optionalChain([authHeader, 'optionalAccess', _66 => _66.match, 'call', _67 => _67(/^Basic\s+(.+)$/)]);
1917
+ const basicMatch = _optionalChain([authHeader, 'optionalAccess', _66 => _66.match, 'call', _67 => _67(/^Basic\s+(.*)$/i)]);
1918
1918
  if (!basicMatch) return null;
1919
+ const credentials = Buffer.from(basicMatch[1].trim(), "base64").toString(
1920
+ "utf-8"
1921
+ );
1922
+ const separator = credentials.indexOf(":");
1923
+ if (separator <= 0) return "malformed";
1919
1924
  try {
1920
- const credentials = Buffer.from(basicMatch[1], "base64").toString("utf-8");
1921
- const credMatch = credentials.match(/^([^:]+):(.*)$/);
1922
- if (!credMatch) return null;
1923
- return { clientId: credMatch[1], clientSecret: credMatch[2] };
1925
+ return {
1926
+ clientId: decodeURIComponent(credentials.slice(0, separator)),
1927
+ clientSecret: decodeURIComponent(credentials.slice(separator + 1))
1928
+ };
1924
1929
  } catch (e6) {
1925
- return null;
1930
+ return "malformed";
1926
1931
  }
1927
1932
  }
1928
1933
  function parseBooleanSetting(value, source) {
@@ -1971,6 +1976,10 @@ var OAUTH_CREDENTIAL_RESPONSE_HEADERS = {
1971
1976
  "Content-Type": "application/json",
1972
1977
  Pragma: "no-cache"
1973
1978
  };
1979
+ var OAUTH_INVALID_CLIENT_RESPONSE_HEADERS = {
1980
+ ...OAUTH_CREDENTIAL_RESPONSE_HEADERS,
1981
+ "WWW-Authenticate": 'Basic realm="oauth", charset="UTF-8"'
1982
+ };
1974
1983
  function stripBasePath(path, basePath) {
1975
1984
  if (!basePath) {
1976
1985
  return path;
@@ -3054,8 +3063,37 @@ var FastMCP = class extends FastMCPEventEmitter {
3054
3063
  const basicAuth = parseBasicAuthHeader(
3055
3064
  req.headers.authorization
3056
3065
  );
3057
- const clientId = _optionalChain([basicAuth, 'optionalAccess', _84 => _84.clientId]) || params.get("client_id") || "";
3058
- const clientSecret = _nullishCoalesce(_nullishCoalesce(_optionalChain([basicAuth, 'optionalAccess', _85 => _85.clientSecret]), () => ( params.get("client_secret"))), () => ( void 0));
3066
+ if (basicAuth === "malformed") {
3067
+ throw {
3068
+ toJSON: () => ({
3069
+ error: "invalid_client",
3070
+ error_description: "Malformed Basic Authorization header"
3071
+ })
3072
+ };
3073
+ }
3074
+ if (basicAuth) {
3075
+ if (params.has("client_secret")) {
3076
+ throw {
3077
+ statusCode: 400,
3078
+ toJSON: () => ({
3079
+ error: "invalid_request",
3080
+ error_description: "Send client credentials in the Authorization header or the request body, not both"
3081
+ })
3082
+ };
3083
+ }
3084
+ const bodyClientId = params.get("client_id");
3085
+ if (bodyClientId !== null && bodyClientId !== basicAuth.clientId) {
3086
+ throw {
3087
+ statusCode: 400,
3088
+ toJSON: () => ({
3089
+ error: "invalid_request",
3090
+ error_description: "client_id in the request body does not match the Authorization header"
3091
+ })
3092
+ };
3093
+ }
3094
+ }
3095
+ const clientId = basicAuth ? basicAuth.clientId : params.get("client_id") || "";
3096
+ const clientSecret = basicAuth ? basicAuth.clientSecret : _nullishCoalesce(params.get("client_secret"), () => ( void 0));
3059
3097
  let response;
3060
3098
  if (grantType === "authorization_code") {
3061
3099
  response = await oauthProxy.exchangeAuthorizationCode({
@@ -3082,14 +3120,15 @@ var FastMCP = class extends FastMCPEventEmitter {
3082
3120
  }
3083
3121
  res.writeHead(200, OAUTH_CREDENTIAL_RESPONSE_HEADERS).end(JSON.stringify(response));
3084
3122
  } catch (error) {
3085
- const statusCode = error.statusCode || 400;
3086
- res.writeHead(statusCode, OAUTH_CREDENTIAL_RESPONSE_HEADERS).end(
3087
- JSON.stringify(
3088
- _optionalChain([error, 'access', _86 => _86.toJSON, 'optionalCall', _87 => _87()]) || {
3089
- error: "invalid_request"
3090
- }
3091
- )
3092
- );
3123
+ const body = _optionalChain([error, 'access', _84 => _84.toJSON, 'optionalCall', _85 => _85()]) || {
3124
+ error: "invalid_request"
3125
+ };
3126
+ if (body.error === "invalid_client") {
3127
+ res.writeHead(401, OAUTH_INVALID_CLIENT_RESPONSE_HEADERS).end(JSON.stringify(body));
3128
+ } else {
3129
+ const statusCode = error.statusCode || 400;
3130
+ res.writeHead(statusCode, OAUTH_CREDENTIAL_RESPONSE_HEADERS).end(JSON.stringify(body));
3131
+ }
3093
3132
  }
3094
3133
  resolve();
3095
3134
  });
@@ -3111,7 +3150,7 @@ var FastMCP = class extends FastMCPEventEmitter {
3111
3150
  * regardless (RFC 7235), so no config is needed just to get the header.
3112
3151
  */
3113
3152
  #httpStreamOAuthConfig() {
3114
- const resource = _optionalChain([this, 'access', _88 => _88.#options, 'access', _89 => _89.oauth, 'optionalAccess', _90 => _90.enabled]) ? _optionalChain([this, 'access', _91 => _91.#options, 'access', _92 => _92.oauth, 'access', _93 => _93.protectedResource, 'optionalAccess', _94 => _94.resource]) : void 0;
3153
+ const resource = _optionalChain([this, 'access', _86 => _86.#options, 'access', _87 => _87.oauth, 'optionalAccess', _88 => _88.enabled]) ? _optionalChain([this, 'access', _89 => _89.#options, 'access', _90 => _90.oauth, 'access', _91 => _91.protectedResource, 'optionalAccess', _92 => _92.resource]) : void 0;
3115
3154
  if (!resource) {
3116
3155
  return {};
3117
3156
  }
@@ -3217,24 +3256,24 @@ var FastMCP = class extends FastMCPEventEmitter {
3217
3256
  const envBasePath = process.env.FASTMCP_BASE_PATH;
3218
3257
  const envStateless = process.env.FASTMCP_STATELESS;
3219
3258
  const envHost = process.env.FASTMCP_HOST;
3220
- const transportType = _optionalChain([overrides, 'optionalAccess', _95 => _95.transportType]) || parseTransportSetting(transportArg, "--transport") || parseTransportSetting(envTransport, "FASTMCP_TRANSPORT") || "stdio";
3259
+ const transportType = _optionalChain([overrides, 'optionalAccess', _93 => _93.transportType]) || parseTransportSetting(transportArg, "--transport") || parseTransportSetting(envTransport, "FASTMCP_TRANSPORT") || "stdio";
3221
3260
  if (transportType === "httpStream") {
3222
3261
  const port = parseInt(
3223
- _optionalChain([overrides, 'optionalAccess', _96 => _96.httpStream, 'optionalAccess', _97 => _97.port, 'optionalAccess', _98 => _98.toString, 'call', _99 => _99()]) || portArg || envPort || "8080"
3262
+ _optionalChain([overrides, 'optionalAccess', _94 => _94.httpStream, 'optionalAccess', _95 => _95.port, 'optionalAccess', _96 => _96.toString, 'call', _97 => _97()]) || portArg || envPort || "8080"
3224
3263
  );
3225
- const host = _optionalChain([overrides, 'optionalAccess', _100 => _100.httpStream, 'optionalAccess', _101 => _101.host]) || hostArg || envHost || "localhost";
3226
- const endpoint = _optionalChain([overrides, 'optionalAccess', _102 => _102.httpStream, 'optionalAccess', _103 => _103.endpoint]) || endpointArg || envEndpoint || "/mcp";
3264
+ const host = _optionalChain([overrides, 'optionalAccess', _98 => _98.httpStream, 'optionalAccess', _99 => _99.host]) || hostArg || envHost || "localhost";
3265
+ const endpoint = _optionalChain([overrides, 'optionalAccess', _100 => _100.httpStream, 'optionalAccess', _101 => _101.endpoint]) || endpointArg || envEndpoint || "/mcp";
3227
3266
  const basePath = normalizeBasePath(
3228
- _optionalChain([overrides, 'optionalAccess', _104 => _104.httpStream, 'optionalAccess', _105 => _105.basePath]) || basePathArg || envBasePath
3267
+ _optionalChain([overrides, 'optionalAccess', _102 => _102.httpStream, 'optionalAccess', _103 => _103.basePath]) || basePathArg || envBasePath
3229
3268
  );
3230
- const enableJsonResponse = _optionalChain([overrides, 'optionalAccess', _106 => _106.httpStream, 'optionalAccess', _107 => _107.enableJsonResponse]) || false;
3231
- const stateless = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([overrides, 'optionalAccess', _108 => _108.httpStream, 'optionalAccess', _109 => _109.stateless]), () => ( // A bare `--stateless` means `--stateless true`.
3269
+ const enableJsonResponse = _optionalChain([overrides, 'optionalAccess', _104 => _104.httpStream, 'optionalAccess', _105 => _105.enableJsonResponse]) || false;
3270
+ const stateless = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([overrides, 'optionalAccess', _106 => _106.httpStream, 'optionalAccess', _107 => _107.stateless]), () => ( // A bare `--stateless` means `--stateless true`.
3232
3271
  (statelessArg === "" ? true : parseBooleanSetting(statelessArg, "--stateless")))), () => ( parseBooleanSetting(envStateless, "FASTMCP_STATELESS"))), () => ( false));
3233
- const cors = _optionalChain([overrides, 'optionalAccess', _110 => _110.httpStream, 'optionalAccess', _111 => _111.cors]);
3234
- const eventStore = _optionalChain([overrides, 'optionalAccess', _112 => _112.httpStream, 'optionalAccess', _113 => _113.eventStore]);
3235
- const sslCa = _optionalChain([overrides, 'optionalAccess', _114 => _114.httpStream, 'optionalAccess', _115 => _115.sslCa]);
3236
- const sslCert = _optionalChain([overrides, 'optionalAccess', _116 => _116.httpStream, 'optionalAccess', _117 => _117.sslCert]);
3237
- const sslKey = _optionalChain([overrides, 'optionalAccess', _118 => _118.httpStream, 'optionalAccess', _119 => _119.sslKey]);
3272
+ const cors = _optionalChain([overrides, 'optionalAccess', _108 => _108.httpStream, 'optionalAccess', _109 => _109.cors]);
3273
+ const eventStore = _optionalChain([overrides, 'optionalAccess', _110 => _110.httpStream, 'optionalAccess', _111 => _111.eventStore]);
3274
+ const sslCa = _optionalChain([overrides, 'optionalAccess', _112 => _112.httpStream, 'optionalAccess', _113 => _113.sslCa]);
3275
+ const sslCert = _optionalChain([overrides, 'optionalAccess', _114 => _114.httpStream, 'optionalAccess', _115 => _115.sslCert]);
3276
+ const sslKey = _optionalChain([overrides, 'optionalAccess', _116 => _116.httpStream, 'optionalAccess', _117 => _117.sslKey]);
3238
3277
  return {
3239
3278
  httpStream: {
3240
3279
  basePath,
@@ -3326,7 +3365,7 @@ var FastMCP = class extends FastMCPEventEmitter {
3326
3365
  */
3327
3366
  #useEndpointAsResource(endpoint) {
3328
3367
  const oauth = this.#options.oauth;
3329
- if (this.#providerResourceBase === void 0 || !_optionalChain([oauth, 'optionalAccess', _120 => _120.protectedResource]))
3368
+ if (this.#providerResourceBase === void 0 || !_optionalChain([oauth, 'optionalAccess', _118 => _118.protectedResource]))
3330
3369
  return;
3331
3370
  this.#options = {
3332
3371
  ...this.#options,
@@ -3355,4 +3394,4 @@ var FastMCP = class extends FastMCPEventEmitter {
3355
3394
 
3356
3395
 
3357
3396
  exports.DiscoveryDocumentCache = DiscoveryDocumentCache; exports.jsonSchemaAdapter = jsonSchemaAdapter; exports.MEDIA_FETCH_TIMEOUT_MS = MEDIA_FETCH_TIMEOUT_MS; exports.imageContent = imageContent; exports.audioContent = audioContent; exports.FastMCPError = FastMCPError; exports.SessionError = SessionError; exports.UnexpectedStateError = UnexpectedStateError; exports.UserError = UserError; exports.ServerState = ServerState; exports.FastMCPSession = FastMCPSession; exports.FastMCP = FastMCP;
3358
- //# sourceMappingURL=chunk-X5ITW7FV.cjs.map
3397
+ //# sourceMappingURL=chunk-4P2GDM7W.cjs.map