dynmcp 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1077 -181
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1097 -179
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../package.json","../src/proxy/index.ts","../src/config/schema.ts","../src/config/loader.ts","../src/config/env-sources.ts","../src/config/interpolate.ts","../src/config/json-schema.ts","../src/proxy/transport-factory.ts","../src/proxy/tool-catalog.ts","../src/proxy/upstream-client.ts","../src/proxy/orchestrator.ts","../src/proxy/server.ts","../src/index.ts"],"sourcesContent":["import process from \"node:process\";\nimport { Command } from \"commander\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport figlet from \"figlet\";\nimport chalk from \"chalk\";\nimport { startProxy, startProxyFromConfig } from \"./proxy/index.js\";\n\nconst cliBanner = chalk.bold.magentaBright(\n figlet.textSync(\"DYNAMIC MCP\", {\n font: \"Sub-Zero\",\n horizontalLayout: \"fitted\",\n verticalLayout: \"fitted\",\n }),\n);\n\nexport const cli = new Command(packageJson.name)\n .description(packageJson.description)\n .version(packageJson.version)\n .addHelpText(\"beforeAll\", cliBanner)\n .addHelpText(\n \"after\",\n \"\\nExamples:\\n\" +\n \" dynmcp -- npx -y chrome-devtools-mcp@latest\\n\" +\n \" dynmcp --config ./mcp.json\\n\",\n )\n .option(\"-c, --config <path>\", \"Path to config file (JSON or YAML)\")\n .option(\n \"-e, --env <path>\",\n \"Path to a .env file for environment variable interpolation\",\n )\n .allowExcessArguments(true)\n .passThroughOptions(true)\n .action(async (_options, cmd) => {\n const separatorIndex = process.argv.indexOf(\"--\");\n const configPath = cmd.opts().config as string | undefined;\n const envFilePath = cmd.opts().env as string | undefined;\n\n if (separatorIndex !== -1) {\n const [command, ...args] = process.argv.slice(separatorIndex + 1);\n\n if (command === undefined) {\n process.stderr.write(\n \"dynmcp: no upstream command provided after --.\\n\" +\n \"Usage: dynmcp -- <command> [args...]\\n\",\n );\n process.exit(1);\n }\n\n try {\n await startProxy(command, args);\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n return;\n }\n\n try {\n await startProxyFromConfig({ configPath, envFilePath });\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n });\n","{\n \"name\": \"dynmcp\",\n \"version\": \"0.2.0\",\n \"description\": \"Dynamic MCP context management tool for AI MCP-enabled agents and clients.\",\n \"author\": \"Brandon Burrus <brandon@burrus.io>\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"homepage\": \"https://github.com/brandonburrus/dynamic-discovery-mcp#readme\",\n \"keywords\": [\n \"mcp\",\n \"model-context-protocol\",\n \"ai\",\n \"agent\",\n \"proxy\",\n \"dynamic\",\n \"discovery\",\n \"tools\",\n \"llm\",\n \"cli\"\n ],\n \"engines\": {\n \"node\": \">=20.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/brandonburrus/dynamic-discovery-mcp.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/brandonburrus/dynamic-discovery-mcp/issues\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"dynmcp\": \"./dist/index.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"files\": [\n \"dist\",\n \"schema\"\n ],\n \"scripts\": {\n \"generate:schema\": \"tsx scripts/generate-schema.ts\",\n \"prebuild\": \"tsx scripts/generate-schema.ts\",\n \"build\": \"tsup\",\n \"dev\": \"tsx src/index.ts\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"biome lint .\",\n \"format\": \"biome format --write .\",\n \"check\": \"biome check --write .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"prepare\": \"husky\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"boxen\": \"^8.0.1\",\n \"chalk\": \"^5.6.2\",\n \"commander\": \"^14.0.3\",\n \"dotenv\": \"^17.4.2\",\n \"enquirer\": \"^2.4.1\",\n \"fastmcp\": \"^4.0.1\",\n \"figlet\": \"^1.11.0\",\n \"figures\": \"^6.1.0\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@biomejs/biome\": \"^2.4.15\",\n \"@commitlint/cli\": \"^21.0.1\",\n \"@commitlint/config-conventional\": \"^21.0.1\",\n \"@types/node\": \"^25.9.0\",\n \"husky\": \"^9.1.7\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.22.2\",\n \"typescript\": \"^6.0.3\",\n \"vitest\": \"^4.1.6\"\n }\n}\n","import process from \"node:process\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { loadConfig } from \"../config/index.js\";\nimport { createTransport } from \"./transport-factory.js\";\nimport { Orchestrator } from \"./orchestrator.js\";\nimport { ToolCatalog } from \"./tool-catalog.js\";\nimport { ProxyServer } from \"./server.js\";\nimport { UpstreamClient } from \"./upstream-client.js\";\n\nexport async function startProxy(command: string, args: string[]): Promise<void> {\n let isShuttingDown = false;\n\n const transport = new StdioClientTransport({ command, args });\n\n const upstreamClient = new UpstreamClient({\n name: command,\n transport,\n onTransportError: (error: Error) => {\n process.stderr.write(`Upstream MCP transport error: ${error.message}\\n`);\n shutdown(1);\n },\n });\n\n const shutdown = (exitCode: number): void => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n\n upstreamClient\n .disconnect()\n .catch((error: unknown) => {\n process.stderr.write(\n `dynmcp: error during disconnect: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n })\n .finally(() => process.exit(exitCode));\n };\n\n try {\n await upstreamClient.connect();\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n\n let tools: Awaited<ReturnType<UpstreamClient[\"listTools\"]>>;\n try {\n tools = await upstreamClient.listTools();\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n\n const catalog = ToolCatalog.fromFlat(tools);\n const proxyServer = new ProxyServer({\n catalog,\n callTool: (name, input) => upstreamClient.callTool(name, input),\n });\n\n process.on(\"SIGINT\", () => shutdown(0));\n process.on(\"SIGTERM\", () => shutdown(0));\n process.stdin.on(\"end\", () => shutdown(0));\n process.stdin.on(\"close\", () => shutdown(0));\n\n try {\n await proxyServer.start();\n } catch (error) {\n shutdown(1);\n throw error;\n }\n}\n\nexport interface StartProxyFromConfigOptions {\n configPath?: string;\n envFilePath?: string;\n}\n\nexport async function startProxyFromConfig(\n options: StartProxyFromConfigOptions = {},\n): Promise<void> {\n let isShuttingDown = false;\n\n const config = loadConfig(options);\n\n const mcps = new Map<string, { transport: ReturnType<typeof createTransport> }>();\n for (const [name, entry] of Object.entries(config.mcp)) {\n mcps.set(name, { transport: createTransport(entry) });\n }\n\n const orchestrator = new Orchestrator({\n mcps,\n onTransportError: (mcpName: string, error: Error) => {\n process.stderr.write(`Upstream MCP \"${mcpName}\" transport error: ${error.message}\\n`);\n shutdown(1);\n },\n });\n\n const shutdown = (exitCode: number): void => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n\n orchestrator\n .disconnectAll()\n .catch((error: unknown) => {\n process.stderr.write(\n `dynmcp: error during disconnect: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n })\n .finally(() => process.exit(exitCode));\n };\n\n try {\n await orchestrator.connect();\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n\n const proxyServer = new ProxyServer({\n catalog: orchestrator.catalog,\n callTool: (name, input) => orchestrator.callTool(name, input),\n });\n\n process.on(\"SIGINT\", () => shutdown(0));\n process.on(\"SIGTERM\", () => shutdown(0));\n process.stdin.on(\"end\", () => shutdown(0));\n process.stdin.on(\"close\", () => shutdown(0));\n\n try {\n await proxyServer.start();\n } catch (error) {\n shutdown(1);\n throw error;\n }\n}\n","import { z } from \"zod\";\n\nexport const MCP_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\nconst mcpName = z.string().regex(MCP_NAME_PATTERN);\n\nexport const envModeSchema = z\n .enum([\"enable\", \"dotenv\", \"process\", \"disable\"])\n .describe(\n 'Controls environment variable interpolation in config values. \"enable\" (default) merges .env and process.env (.env wins). \"dotenv\" loads .env only. \"process\" uses process.env only. \"disable\" turns interpolation off.',\n );\n\nexport type EnvMode = z.infer<typeof envModeSchema>;\n\nconst stdioTransport = z\n .object({\n transport: z.literal(\"stdio\"),\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst httpUrl = z\n .string()\n .url()\n .refine(u => u.startsWith(\"http://\") || u.startsWith(\"https://\"), {\n message: \"URL must use http:// or https:// scheme\",\n });\n\nconst streamableHttpTransport = z\n .object({\n transport: z.literal(\"streamable-http\"),\n url: httpUrl,\n headers: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst sseTransport = z\n .object({\n transport: z.literal(\"sse\"),\n url: httpUrl,\n headers: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst transportConfig = z.discriminatedUnion(\"transport\", [\n stdioTransport,\n streamableHttpTransport,\n sseTransport,\n]);\n\nexport const mcpConfigSchema = z.object({\n env: envModeSchema.optional(),\n mcp: z\n .record(mcpName, transportConfig)\n .refine(obj => Object.keys(obj).length > 0, { message: \"At least one MCP must be configured\" }),\n});\n\nexport type McpConfig = z.infer<typeof mcpConfigSchema>;\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { parse as parseYaml } from \"yaml\";\nimport { loadEnv } from \"./env-sources.js\";\nimport { interpolateConfig } from \"./interpolate.js\";\nimport { type EnvMode, type McpConfig, mcpConfigSchema } from \"./schema.js\";\n\nconst AUTO_DISCOVER_NAMES = [\"mcp.json\", \".mcp.json\"] as const;\nconst DEFAULT_ENV_MODE: EnvMode = \"enable\";\nconst VALID_ENV_MODES: readonly EnvMode[] = [\"enable\", \"dotenv\", \"process\", \"disable\"];\n\nexport interface LoadConfigOptions {\n /** Path to the config file. If omitted, auto-discovers `mcp.json` then `.mcp.json` in cwd. */\n configPath?: string;\n /** Path to a custom `.env` file (from the `--env` / `-e` CLI flag). */\n envFilePath?: string;\n}\n\n/**\n * Resolves the config file path without loading or parsing it.\n *\n * @param explicitPath - If provided, resolves this path directly.\n * @returns The absolute path to the config file.\n * @throws If no config file is found at the explicit path or via auto-discovery.\n */\nexport function resolveConfigPath(explicitPath?: string): string {\n if (explicitPath) {\n const resolved = resolve(explicitPath);\n if (!existsSync(resolved)) {\n throw new Error(`Config file not found: ${resolved}`);\n }\n return resolved;\n }\n\n const cwd = process.cwd();\n for (const name of AUTO_DISCOVER_NAMES) {\n const candidate = resolve(cwd, name);\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n const searched = AUTO_DISCOVER_NAMES.map(n => resolve(cwd, n)).join(\", \");\n throw new Error(`No config file found. Searched: ${searched}`);\n}\n\n/**\n * Loads, parses, interpolates, and validates the dynmcp config file.\n *\n * Flow: resolve path → read file → parse JSON/YAML → read env mode →\n * load env sources → interpolate `${VAR}` references → Zod validate.\n *\n * @param options - Config path and optional custom `.env` file path.\n * @returns The validated config object with all interpolations resolved.\n * @throws On missing file, parse errors, missing env vars, or schema validation failures.\n */\nexport function loadConfig(options: LoadConfigOptions = {}): McpConfig {\n const { configPath, envFilePath } = options;\n\n const resolvedPath = resolveConfigPath(configPath);\n const raw = readFileSync(resolvedPath, \"utf-8\");\n\n let content: unknown;\n try {\n content = isYamlFile(resolvedPath) ? parseYaml(raw) : JSON.parse(raw);\n } catch (parseError) {\n const message = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(`Failed to parse config file (${resolvedPath}): ${message}`);\n }\n\n const envMode = readEnvMode(content);\n const loadedEnv = loadEnv({ mode: envMode, envFilePath });\n\n const interpolated = loadedEnv.interpolationEnabled\n ? interpolateConfig(content, loadedEnv.variables)\n : content;\n\n const result = mcpConfigSchema.safeParse(interpolated);\n if (!result.success) {\n const formatted = result.error.issues\n .map(issue => ` - ${issue.path.join(\".\")}: ${issue.message}`)\n .join(\"\\n\");\n throw new Error(`Invalid config file (${resolvedPath}):\\n${formatted}`);\n }\n\n return result.data;\n}\n\n/**\n * Reads the top-level `env` field from raw parsed config content. This runs\n * before Zod validation so we can resolve env vars before validating types.\n *\n * If the field is missing, the default mode is returned. If it is present but\n * not a recognized value, the default is returned so that Zod can surface a\n * specific validation error later.\n */\nfunction readEnvMode(content: unknown): EnvMode {\n if (content === null || typeof content !== \"object\" || Array.isArray(content)) {\n return DEFAULT_ENV_MODE;\n }\n const value = (content as Record<string, unknown>).env;\n if (value === undefined) return DEFAULT_ENV_MODE;\n if (typeof value === \"string\" && (VALID_ENV_MODES as readonly string[]).includes(value)) {\n return value as EnvMode;\n }\n return DEFAULT_ENV_MODE;\n}\n\nfunction isYamlFile(filePath: string): boolean {\n return filePath.endsWith(\".yml\") || filePath.endsWith(\".yaml\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport process from \"node:process\";\nimport dotenv from \"dotenv\";\nimport type { EnvMode } from \"./schema.js\";\n\nconst DEFAULT_DOTENV_FILENAME = \".env\";\n\nexport interface LoadEnvOptions {\n /** Env interpolation mode (from config file top-level `env` field). */\n mode: EnvMode;\n /** Custom `.env` path from the `--env` / `-e` CLI flag. When provided, the file must exist. */\n envFilePath?: string;\n /** Override for cwd (testability). Defaults to `process.cwd()`. */\n cwd?: string;\n /** Override for process.env (testability). Defaults to `process.env`. */\n processEnv?: NodeJS.ProcessEnv;\n}\n\nexport interface LoadedEnv {\n /** Merged variable map ready for interpolation. */\n variables: Record<string, string>;\n /** Whether interpolation should run at all. False only when mode is \"disable\". */\n interpolationEnabled: boolean;\n}\n\n/**\n * Resolves the environment variable map used for config interpolation.\n *\n * Precedence rules:\n * - mode \"enable\": load .env + process.env, .env wins for duplicates.\n * - mode \"dotenv\": load .env only; process.env is ignored.\n * - mode \"process\": process.env only; no .env file is loaded.\n * - mode \"disable\": no sources; interpolation is turned off.\n *\n * The `--env` flag is incompatible with \"disable\" and \"process\" modes and is\n * rejected at startup as an incoherent combination.\n *\n * @throws If `--env` is combined with an incompatible mode.\n * @throws If an explicit `--env` path does not exist or cannot be parsed.\n */\nexport function loadEnv(options: LoadEnvOptions): LoadedEnv {\n const { mode, envFilePath, cwd = process.cwd(), processEnv = process.env } = options;\n\n if (envFilePath !== undefined && (mode === \"disable\" || mode === \"process\")) {\n throw new Error(\n `--env flag is incompatible with env mode \"${mode}\". --env requires env mode \"enable\" or \"dotenv\".`,\n );\n }\n\n if (mode === \"disable\") {\n return { variables: {}, interpolationEnabled: false };\n }\n\n const dotenvVars = mode === \"process\" ? {} : readDotenvFile(envFilePath, cwd);\n const processVars = mode === \"dotenv\" ? {} : filterDefined(processEnv);\n\n // For \"enable\" mode, .env wins (later spread overrides earlier).\n // For \"process\" and \"dotenv\" modes only one source is non-empty, so order is moot.\n const variables = { ...processVars, ...dotenvVars };\n\n return { variables, interpolationEnabled: true };\n}\n\nfunction readDotenvFile(envFilePath: string | undefined, cwd: string): Record<string, string> {\n const isExplicit = envFilePath !== undefined;\n const resolvedPath = isExplicit\n ? resolve(envFilePath as string)\n : resolve(cwd, DEFAULT_DOTENV_FILENAME);\n\n if (!existsSync(resolvedPath)) {\n if (isExplicit) {\n throw new Error(`.env file not found: ${resolvedPath}`);\n }\n // Soft-fail: a missing default .env is not an error.\n return {};\n }\n\n let raw: string;\n try {\n raw = readFileSync(resolvedPath, \"utf-8\");\n } catch (readError) {\n const message = readError instanceof Error ? readError.message : String(readError);\n throw new Error(`Failed to read .env file (${resolvedPath}): ${message}`);\n }\n\n try {\n return dotenv.parse(raw);\n } catch (parseError) {\n const message = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(`Failed to parse .env file (${resolvedPath}): ${message}`);\n }\n}\n\nfunction filterDefined(env: NodeJS.ProcessEnv): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n","/**\n * Environment variable interpolation for dynmcp config files.\n *\n * Runs after JSON/YAML parsing but before Zod validation, so the validated\n * config contains only fully-resolved string values.\n *\n * Supported syntax (per SPEC.md \"Environment Variable Interpolation\"):\n * - `${VAR}` substitute the value of VAR; missing → error\n * - `${VAR:-default}` substitute VAR, or `default` if VAR is unset or empty\n * - `$${...}` escape — resolves to the literal `${...}`\n *\n * Interpolation applies only to leaf string values reached through the `mcp`\n * subtree. The top-level `$schema` and `env` fields are passed through verbatim.\n */\n\nconst TOP_LEVEL_PASSTHROUGH_KEYS = new Set([\"$schema\", \"env\"]);\n\nexport class MissingEnvVarsError extends Error {\n constructor(public readonly missingVars: readonly string[]) {\n const list = missingVars.join(\", \");\n const plural = missingVars.length === 1 ? \"\" : \"s\";\n super(`Missing required environment variable${plural}: ${list}`);\n this.name = \"MissingEnvVarsError\";\n }\n}\n\n/**\n * Walks a parsed config object and substitutes `${VAR}` references in all leaf\n * string values. Top-level `$schema` and `env` keys are not interpolated.\n *\n * @param config - The parsed (but unvalidated) config object.\n * @param env - The resolved environment variable map (already merged per env mode).\n * @returns A structurally identical config with all string leaves interpolated.\n * @throws {MissingEnvVarsError} If any `${VAR}` reference has no default and no value in env.\n */\nexport function interpolateConfig(config: unknown, env: Record<string, string>): unknown {\n if (config === null || typeof config !== \"object\" || Array.isArray(config)) {\n return config;\n }\n\n const missing: string[] = [];\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(config as Record<string, unknown>)) {\n if (TOP_LEVEL_PASSTHROUGH_KEYS.has(key)) {\n result[key] = value;\n } else {\n result[key] = walkNode(value, env, missing);\n }\n }\n\n if (missing.length > 0) {\n const unique = Array.from(new Set(missing)).sort();\n throw new MissingEnvVarsError(unique);\n }\n\n return result;\n}\n\nfunction walkNode(node: unknown, env: Record<string, string>, missing: string[]): unknown {\n if (typeof node === \"string\") {\n return interpolateString(node, env, missing);\n }\n if (Array.isArray(node)) {\n return node.map(item => walkNode(item, env, missing));\n }\n if (node !== null && typeof node === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n result[key] = walkNode(value, env, missing);\n }\n return result;\n }\n return node;\n}\n\nfunction interpolateString(value: string, env: Record<string, string>, missing: string[]): string {\n let result = \"\";\n let i = 0;\n const len = value.length;\n\n while (i < len) {\n const ch = value[i];\n\n if (ch === \"$\" && value[i + 1] === \"$\" && value[i + 2] === \"{\") {\n // Escape: $${...} -> literal ${...} (strip one leading $)\n const close = value.indexOf(\"}\", i + 3);\n if (close === -1) {\n // Unclosed escape; treat the leading $ as literal and advance one char\n result += ch;\n i += 1;\n continue;\n }\n result += value.substring(i + 1, close + 1);\n i = close + 1;\n continue;\n }\n\n if (ch === \"$\" && value[i + 1] === \"{\") {\n const close = value.indexOf(\"}\", i + 2);\n if (close === -1) {\n // Unclosed expression; emit the rest of the string literally\n result += value.substring(i);\n break;\n }\n const expr = value.substring(i + 2, close);\n const { name, defaultValue } = parseExpr(expr);\n const resolved = env[name];\n const hasValue = resolved !== undefined && resolved !== \"\";\n\n if (hasValue) {\n result += resolved;\n } else if (defaultValue !== undefined) {\n result += defaultValue;\n } else if (resolved !== undefined) {\n // Defined but empty string and no default — treat as the empty string.\n // Per spec: ${VAR} without default fails only when VAR is *undefined*.\n result += \"\";\n } else {\n missing.push(name);\n }\n i = close + 1;\n continue;\n }\n\n result += ch;\n i += 1;\n }\n\n return result;\n}\n\nfunction parseExpr(expr: string): { name: string; defaultValue: string | undefined } {\n const sep = expr.indexOf(\":-\");\n if (sep === -1) {\n return { name: expr, defaultValue: undefined };\n }\n return {\n name: expr.substring(0, sep),\n defaultValue: expr.substring(sep + 2),\n };\n}\n","import { z } from \"zod\";\nimport { mcpConfigSchema } from \"./schema.js\";\n\nexport const MCP_CONFIG_SCHEMA_ID = \"https://unpkg.com/dynmcp/schema/mcp-config.json\";\nexport const MCP_CONFIG_SCHEMA_DRAFT = \"http://json-schema.org/draft-07/schema#\";\n\n/**\n * Generates the JSON Schema for the dynmcp config file from the runtime Zod schema.\n *\n * The schema is targeted at JSON Schema draft-07 for the broadest editor support\n * (VS Code, JetBrains, and the JSON Schema Store all consume draft-07 reliably).\n *\n * @returns A JSON Schema document describing the dynmcp config file format.\n */\nexport function generateMcpConfigJsonSchema(): Record<string, unknown> {\n const generated = z.toJSONSchema(mcpConfigSchema, {\n target: \"draft-7\",\n }) as Record<string, unknown>;\n\n const properties = (generated.properties ?? {}) as Record<string, unknown>;\n const mcpProperty = (properties.mcp ?? {}) as Record<string, unknown>;\n\n return {\n $schema: MCP_CONFIG_SCHEMA_DRAFT,\n $id: MCP_CONFIG_SCHEMA_ID,\n title: \"dynmcp config\",\n description:\n \"Configuration file for dynmcp. Declares the set of upstream MCPs to proxy through dynamic-discovery-mcp.\",\n ...generated,\n properties: {\n ...properties,\n $schema: {\n type: \"string\",\n description: \"URL of the JSON Schema for editor validation.\",\n },\n mcp: {\n ...mcpProperty,\n minProperties: 1,\n description:\n \"Map of upstream MCPs to proxy, keyed by MCP name. Each name becomes the namespace prefix for that MCP's tools.\",\n },\n },\n };\n}\n","import { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\n\ninterface StdioTransportConfig {\n transport: \"stdio\";\n command: string;\n args?: string[];\n env?: Record<string, string>;\n}\n\ninterface StreamableHttpTransportConfig {\n transport: \"streamable-http\";\n url: string;\n headers?: Record<string, string>;\n}\n\ninterface SseTransportConfig {\n transport: \"sse\";\n url: string;\n headers?: Record<string, string>;\n}\n\nexport type McpTransportConfig =\n | StdioTransportConfig\n | StreamableHttpTransportConfig\n | SseTransportConfig;\n\nexport function createTransport(config: McpTransportConfig): Transport {\n switch (config.transport) {\n case \"stdio\":\n return new StdioClientTransport({\n command: config.command,\n args: config.args,\n env: config.env,\n });\n\n case \"streamable-http\":\n return new StreamableHTTPClientTransport(\n new URL(config.url),\n config.headers ? { requestInit: { headers: config.headers } } : undefined,\n );\n\n case \"sse\":\n return new SSEClientTransport(\n new URL(config.url),\n config.headers ? { requestInit: { headers: config.headers } } : undefined,\n );\n\n default: {\n const _exhaustive: never = config;\n return _exhaustive;\n }\n }\n}\n","import type { UpstreamTool } from \"./upstream-client.js\";\n\nconst DISCOVER_TOOL_PREAMBLE = `Use this tool to look up the full schema of a tool before calling it with use_tool.\nCall discover_tool with a tool name from the list below to get its complete description,\ninput parameters, and output schema. Always discover a tool before using it.`;\n\nexport class ToolCatalog {\n readonly tools: ReadonlyMap<string, UpstreamTool>;\n readonly discoverToolDescription: string;\n\n private constructor(tools: Map<string, UpstreamTool>, description: string) {\n this.tools = tools;\n this.discoverToolDescription = description;\n }\n\n static fromFlat(upstreamTools: UpstreamTool[]): ToolCatalog {\n const toolMap = new Map<string, UpstreamTool>();\n for (const tool of upstreamTools) {\n toolMap.set(tool.name, tool);\n }\n const description = buildFlatDescription(upstreamTools);\n return new ToolCatalog(toolMap, description);\n }\n\n static fromGrouped(groups: Map<string, UpstreamTool[]>): ToolCatalog {\n const toolMap = new Map<string, UpstreamTool>();\n for (const [mcpName, tools] of groups) {\n for (const tool of tools) {\n toolMap.set(`${mcpName}/${tool.name}`, tool);\n }\n }\n const description = buildGroupedDescription(groups);\n return new ToolCatalog(toolMap, description);\n }\n\n getToolDetails(toolName: string): string {\n const tool = this.tools.get(toolName);\n\n if (tool === undefined) {\n const sortedNames = [...this.tools.keys()].sort().join(\", \");\n return `Unknown tool: \"${toolName}\". Available tools: ${sortedNames}`;\n }\n\n return buildToolDetailsString(toolName, tool);\n }\n}\n\nfunction buildFlatDescription(tools: UpstreamTool[]): string {\n const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));\n const toolLines = sortedTools.map(tool => `- ${tool.name}: ${tool.description}`).join(\"\\n\");\n\n return `${DISCOVER_TOOL_PREAMBLE}\\n\\n<tools>\\n${toolLines}\\n</tools>`;\n}\n\nfunction buildGroupedDescription(groups: Map<string, UpstreamTool[]>): string {\n const sortedMcpNames = [...groups.keys()].sort();\n const sections = sortedMcpNames.map(mcpName => {\n const tools = groups.get(mcpName)!;\n const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));\n const toolLines = sortedTools\n .map(tool => `- ${mcpName}/${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n return `${mcpName}:\\n${toolLines}`;\n });\n\n return `${DISCOVER_TOOL_PREAMBLE}\\n\\n<tools>\\n${sections.join(\"\\n\\n\")}\\n</tools>`;\n}\n\nfunction buildToolDetailsString(displayName: string, tool: UpstreamTool): string {\n const lines: string[] = [\n `Tool: ${displayName}`,\n `Description: ${tool.description}`,\n \"\",\n \"Input Schema:\",\n JSON.stringify(tool.inputSchema, null, 2),\n ];\n\n if (tool.outputSchema !== undefined) {\n lines.push(\"\", \"Output Schema:\", JSON.stringify(tool.outputSchema, null, 2));\n }\n\n const annotationLines = buildAnnotationLines(tool);\n if (annotationLines.length > 0) {\n lines.push(\"\", \"Annotations:\", ...annotationLines);\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction buildAnnotationLines(tool: UpstreamTool): string[] {\n if (tool.annotations === undefined) {\n return [];\n }\n\n const { annotations } = tool;\n const lines: string[] = [];\n\n if (annotations.title !== undefined) {\n lines.push(`- title: ${annotations.title}`);\n }\n if (annotations.readOnlyHint !== undefined) {\n lines.push(`- readOnlyHint: ${annotations.readOnlyHint}`);\n }\n if (annotations.destructiveHint !== undefined) {\n lines.push(`- destructiveHint: ${annotations.destructiveHint}`);\n }\n if (annotations.idempotentHint !== undefined) {\n lines.push(`- idempotentHint: ${annotations.idempotentHint}`);\n }\n if (annotations.openWorldHint !== undefined) {\n lines.push(`- openWorldHint: ${annotations.openWorldHint}`);\n }\n\n return lines;\n}\n","import process from \"node:process\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { ContentResult } from \"fastmcp\";\n\nexport type ToolAnnotations = {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\nexport type UpstreamTool = {\n name: string;\n description: string;\n inputSchema: unknown;\n outputSchema?: unknown;\n annotations?: ToolAnnotations;\n};\n\ntype UpstreamClientConfig = {\n name: string;\n transport: Transport;\n onTransportError?: (error: Error) => void;\n};\n\nexport class UpstreamClient {\n private readonly transport: Transport;\n private readonly onTransportError: (error: Error) => void;\n private client: Client | null = null;\n\n constructor({ name, transport, onTransportError }: UpstreamClientConfig) {\n this.transport = transport;\n this.onTransportError =\n onTransportError ??\n ((error: Error) => {\n process.stderr.write(`[${name}] Upstream MCP transport error: ${error.message}\\n`);\n });\n }\n\n async connect(): Promise<void> {\n this.transport.onerror = this.onTransportError;\n this.client = new Client({ name: \"dynamic-discovery-mcp\", version: \"1.0.0\" });\n await this.client.connect(this.transport);\n }\n\n async listTools(): Promise<UpstreamTool[]> {\n if (this.client === null) {\n throw new Error(\"Client is not connected. Call connect() first.\");\n }\n\n const result = await this.client.listTools();\n\n return result.tools.map(tool => {\n const upstreamTool: UpstreamTool = {\n name: tool.name,\n description: tool.description ?? \"\",\n inputSchema: tool.inputSchema,\n };\n\n if (tool.outputSchema !== undefined) {\n upstreamTool.outputSchema = tool.outputSchema;\n }\n\n if (tool.annotations !== undefined) {\n upstreamTool.annotations = {\n title: tool.annotations.title,\n readOnlyHint: tool.annotations.readOnlyHint,\n destructiveHint: tool.annotations.destructiveHint,\n idempotentHint: tool.annotations.idempotentHint,\n openWorldHint: tool.annotations.openWorldHint,\n };\n }\n\n return upstreamTool;\n });\n }\n\n async callTool(name: string, input: Record<string, unknown>): Promise<ContentResult> {\n if (this.client === null) {\n throw new Error(\"Client is not connected. Call connect() first.\");\n }\n\n const result = await this.client.callTool({ name, arguments: input });\n return result as ContentResult;\n }\n\n async disconnect(): Promise<void> {\n if (this.client === null) {\n return;\n }\n\n await this.client.close();\n this.client = null;\n }\n}\n","import type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type { ContentResult } from \"fastmcp\";\nimport { ToolCatalog } from \"./tool-catalog.js\";\nimport { UpstreamClient } from \"./upstream-client.js\";\n\nexport type OrchestratorConfig = {\n mcps: Map<string, { transport: Transport }>;\n onTransportError?: (mcpName: string, error: Error) => void;\n};\n\nexport class Orchestrator {\n private readonly config: OrchestratorConfig;\n private readonly clients: Map<string, UpstreamClient> = new Map();\n private toolCatalog: ToolCatalog | null = null;\n\n constructor(config: OrchestratorConfig) {\n this.config = config;\n }\n\n async connect(): Promise<void> {\n const groups = new Map<string, import(\"./upstream-client.js\").UpstreamTool[]>();\n\n try {\n for (const [mcpName, { transport }] of this.config.mcps) {\n const client = new UpstreamClient({\n name: mcpName,\n transport,\n onTransportError: (error: Error) => {\n this.config.onTransportError?.(mcpName, error);\n },\n });\n\n await client.connect();\n const tools = await client.listTools();\n\n this.clients.set(mcpName, client);\n groups.set(mcpName, tools);\n }\n } catch (error) {\n await this.disconnectAll();\n throw error;\n }\n\n this.toolCatalog = ToolCatalog.fromGrouped(groups);\n }\n\n get catalog(): ToolCatalog {\n if (this.toolCatalog === null) {\n throw new Error(\"Orchestrator is not connected. Call connect() first.\");\n }\n return this.toolCatalog;\n }\n\n async callTool(namespacedName: string, input: Record<string, unknown>): Promise<ContentResult> {\n const separatorIndex = namespacedName.indexOf(\"/\");\n if (separatorIndex === -1) {\n throw new Error(\n `Invalid namespaced tool name: \"${namespacedName}\". Expected format: \"mcpName/toolName\".`,\n );\n }\n\n const mcpName = namespacedName.slice(0, separatorIndex);\n const toolName = namespacedName.slice(separatorIndex + 1);\n\n const client = this.clients.get(mcpName);\n if (client === undefined) {\n const available = [...this.clients.keys()].sort().join(\", \");\n throw new Error(`Unknown MCP: \"${mcpName}\". Available MCPs: ${available}`);\n }\n\n return client.callTool(toolName, input);\n }\n\n async disconnectAll(): Promise<void> {\n const disconnections = [...this.clients.values()].map(client => client.disconnect());\n await Promise.all(disconnections);\n this.clients.clear();\n this.toolCatalog = null;\n }\n}\n","import process from \"node:process\";\nimport { FastMCP } from \"fastmcp\";\nimport { z } from \"zod\";\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport type { ContentResult } from \"fastmcp\";\nimport type { ToolCatalog } from \"./tool-catalog.js\";\n\ntype ToolCaller = (name: string, input: Record<string, unknown>) => Promise<ContentResult>;\n\ntype ProxyServerConfig = {\n catalog: ToolCatalog;\n callTool: ToolCaller;\n};\n\nexport class ProxyServer {\n private readonly catalog: ToolCatalog;\n private readonly callTool: ToolCaller;\n\n constructor({ catalog, callTool }: ProxyServerConfig) {\n this.catalog = catalog;\n this.callTool = callTool;\n }\n\n async start(): Promise<void> {\n const server = new FastMCP({\n name: \"dynamic-discovery-mcp\",\n version: packageJson.version as `${number}.${number}.${number}`,\n });\n\n server.addTool({\n name: \"discover_tool\",\n description: this.catalog.discoverToolDescription,\n parameters: z.object({ tool_name: z.string() }),\n execute: async ({ tool_name }) => {\n return this.catalog.getToolDetails(tool_name);\n },\n });\n\n server.addTool({\n name: \"use_tool\",\n description: \"Use a tool that was previously discovered with the discover_tool tool.\",\n parameters: z.object({\n tool_name: z.string(),\n tool_input: z.record(z.string(), z.unknown()).default({}),\n }),\n execute: async ({ tool_name, tool_input }) => {\n if (!this.catalog.tools.has(tool_name)) {\n return this.catalog.getToolDetails(tool_name);\n }\n\n const result = await this.callTool(tool_name, tool_input);\n return result;\n },\n });\n\n process.stderr.write(\"Starting dynamic-discovery-mcp server over stdio\\n\");\n await server.start({ transportType: \"stdio\" });\n }\n}\n","import { cli } from \"./cli.js\";\nimport process from \"node:process\";\n\nasync function main() {\n cli.parse(process.argv);\n}\n\nmain();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,uBAAoB;AACpB,uBAAwB;;;ACDxB;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,aAAe;AAAA,EACf,QAAU;AAAA,EACV,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,UAAY;AAAA,EACZ,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA,EACA,eAAiB;AAAA,IACf,QAAU;AAAA,EACZ;AAAA,EACA,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,MAAQ;AAAA,IACN,KAAO;AAAA,EACT;AAAA,EACA,MAAQ;AAAA,EACR,QAAU;AAAA,EACV,OAAS;AAAA,EACT,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,KAAK;AAAA,MACH,OAAS;AAAA,MACT,QAAU;AAAA,MACV,SAAW;AAAA,IACb;AAAA,EACF;AAAA,EACA,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,SAAW;AAAA,IACT,mBAAmB;AAAA,IACnB,UAAY;AAAA,IACZ,OAAS;AAAA,IACT,KAAO;AAAA,IACP,WA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,EACF;AAEA,MAAI;AACF,UAAM,qBAAqB,EAAE,YAAY,YAAY,CAAC;AAAA,EACxD,SAAS,OAAO;AACd,yBAAAA,QAAQ,OAAO,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAC1F,yBAAAA,QAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;;;Aa9DH,IAAAC,uBAAoB;AAEpB,eAAe,OAAO;AACpB,MAAI,MAAM,qBAAAC,QAAQ,IAAI;AACxB;AAEA,KAAK;","names":["import_node_process","import_node_process","import_stdio","import_node_fs","import_node_path","import_node_process","process","dotenv","process","parseYaml","import_zod","mcpName","import_node_process","process","mcpName","import_node_process","import_zod","process","process","mcpName","chalk","figlet","process","import_node_process","process"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../package.json","../src/proxy/index.ts","../src/config/schema.ts","../src/config/loader.ts","../src/config/env-sources.ts","../src/config/interpolate.ts","../src/config/json-schema.ts","../src/proxy/orchestrator.ts","../src/proxy/capability-aggregator.ts","../src/proxy/tool-catalog.ts","../src/proxy/notification-forwarder.ts","../src/proxy/prompt-router.ts","../src/proxy/resource-router.ts","../src/proxy/upstream-client.ts","../src/proxy/upstream-registry.ts","../src/proxy/server.ts","../src/proxy/transport-factory.ts","../src/index.ts"],"sourcesContent":["import process from \"node:process\";\nimport { Command } from \"commander\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport figlet from \"figlet\";\nimport chalk from \"chalk\";\nimport { startProxy, startProxyFromConfig } from \"./proxy/index.js\";\n\nconst cliBanner = chalk.bold.magentaBright(\n figlet.textSync(\"DYNAMIC MCP\", {\n font: \"Sub-Zero\",\n horizontalLayout: \"fitted\",\n verticalLayout: \"fitted\",\n }),\n);\n\nexport const cli = new Command(packageJson.name)\n .description(packageJson.description)\n .version(packageJson.version)\n .addHelpText(\"beforeAll\", cliBanner)\n .addHelpText(\n \"after\",\n \"\\nExamples:\\n\" +\n \" dynmcp -- npx -y chrome-devtools-mcp@latest\\n\" +\n \" dynmcp --config ./mcp.json\\n\",\n )\n .option(\"-c, --config <path>\", \"Path to config file (JSON or YAML)\")\n .option(\"-e, --env <path>\", \"Path to a .env file for environment variable interpolation\")\n .allowExcessArguments(true)\n .passThroughOptions(true)\n .action(async (_options, cmd) => {\n const separatorIndex = process.argv.indexOf(\"--\");\n const configPath = cmd.opts().config as string | undefined;\n const envFilePath = cmd.opts().env as string | undefined;\n\n if (separatorIndex !== -1) {\n const [command, ...args] = process.argv.slice(separatorIndex + 1);\n\n if (command === undefined) {\n process.stderr.write(\n \"dynmcp: no upstream command provided after --.\\n\" +\n \"Usage: dynmcp -- <command> [args...]\\n\",\n );\n process.exit(1);\n }\n\n try {\n await startProxy(command, args);\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n return;\n }\n\n try {\n await startProxyFromConfig({ configPath, envFilePath });\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n }\n });\n","{\n \"name\": \"dynmcp\",\n \"version\": \"0.3.0\",\n \"description\": \"Dynamic MCP context management tool for AI MCP-enabled agents and clients.\",\n \"author\": \"Brandon Burrus <brandon@burrus.io>\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"homepage\": \"https://github.com/brandonburrus/dynamic-discovery-mcp#readme\",\n \"keywords\": [\n \"mcp\",\n \"model-context-protocol\",\n \"ai\",\n \"agent\",\n \"proxy\",\n \"dynamic\",\n \"discovery\",\n \"tools\",\n \"llm\",\n \"cli\"\n ],\n \"engines\": {\n \"node\": \">=20.0.0\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/brandonburrus/dynamic-discovery-mcp.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/brandonburrus/dynamic-discovery-mcp/issues\"\n },\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"bin\": {\n \"dynmcp\": \"./dist/index.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"files\": [\n \"dist\",\n \"schema\"\n ],\n \"scripts\": {\n \"generate:schema\": \"tsx scripts/generate-schema.ts\",\n \"prebuild\": \"tsx scripts/generate-schema.ts\",\n \"build\": \"tsup\",\n \"dev\": \"tsx src/index.ts\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"biome lint .\",\n \"format\": \"biome format --write .\",\n \"check\": \"biome check --write .\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"prepare\": \"husky\"\n },\n \"dependencies\": {\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"boxen\": \"^8.0.1\",\n \"chalk\": \"^5.6.2\",\n \"commander\": \"^14.0.3\",\n \"dotenv\": \"^17.4.2\",\n \"enquirer\": \"^2.4.1\",\n \"fastmcp\": \"^4.0.1\",\n \"figlet\": \"^1.11.0\",\n \"figures\": \"^6.1.0\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@biomejs/biome\": \"^2.4.15\",\n \"@commitlint/cli\": \"^21.0.1\",\n \"@commitlint/config-conventional\": \"^21.0.1\",\n \"@types/node\": \"^25.9.0\",\n \"@vitest/coverage-v8\": \"^4.1.6\",\n \"husky\": \"^9.1.7\",\n \"tsup\": \"^8.5.1\",\n \"tsx\": \"^4.22.2\",\n \"typescript\": \"^6.0.3\",\n \"vitest\": \"^4.1.6\"\n }\n}\n","import process from \"node:process\";\nimport { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport { loadConfig } from \"../config/index.js\";\nimport { Orchestrator } from \"./orchestrator.js\";\nimport { ProxyServer } from \"./server.js\";\nimport { createTransport } from \"./transport-factory.js\";\n\nconst SINGLE_MCP_NAME = \"__default__\";\n\nexport async function startProxy(command: string, args: string[]): Promise<void> {\n const transport = new StdioClientTransport({ command, args });\n const mcps = new Map<string, { transport: Transport }>([[SINGLE_MCP_NAME, { transport }]]);\n\n const orchestrator = buildOrchestrator({\n mcps,\n namespaced: false,\n transportErrorPrefix: () => \"Upstream MCP\",\n });\n\n await runProxy(orchestrator);\n}\n\nexport interface StartProxyFromConfigOptions {\n configPath?: string;\n envFilePath?: string;\n}\n\nexport async function startProxyFromConfig(\n options: StartProxyFromConfigOptions = {},\n): Promise<void> {\n const config = loadConfig(options);\n\n const mcps = new Map<string, { transport: Transport }>();\n for (const [name, entry] of Object.entries(config.mcp)) {\n mcps.set(name, { transport: createTransport(entry) });\n }\n\n const orchestrator = buildOrchestrator({\n mcps,\n namespaced: true,\n transportErrorPrefix: mcpName => `Upstream MCP \"${mcpName}\"`,\n });\n\n await runProxy(orchestrator);\n}\n\ntype BuildOrchestratorParams = {\n mcps: Map<string, { transport: Transport }>;\n namespaced: boolean;\n transportErrorPrefix: (mcpName: string) => string;\n};\n\n// Forward declaration so buildOrchestrator can reference the shutdown closure constructed\n// inside runProxy. Each invocation of runProxy installs its own shutdown function on this\n// holder before the orchestrator's transport-error callbacks can fire.\ntype ShutdownHolder = { shutdown: ((code: number) => void) | null };\n\nconst activeShutdown: ShutdownHolder = { shutdown: null };\n\nfunction buildOrchestrator(params: BuildOrchestratorParams): Orchestrator {\n return new Orchestrator({\n mcps: params.mcps,\n namespaced: params.namespaced,\n onTransportError: (mcpName: string, error: Error) => {\n process.stderr.write(\n `${params.transportErrorPrefix(mcpName)} transport error: ${error.message}\\n`,\n );\n activeShutdown.shutdown?.(1);\n },\n });\n}\n\nasync function runProxy(orchestrator: Orchestrator): Promise<void> {\n let isShuttingDown = false;\n\n const shutdown = (exitCode: number): void => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n\n orchestrator\n .disconnectAll()\n .catch((error: unknown) => {\n process.stderr.write(\n `dynmcp: error during disconnect: ${error instanceof Error ? error.message : String(error)}\\n`,\n );\n })\n .finally(() => process.exit(exitCode));\n };\n\n activeShutdown.shutdown = shutdown;\n\n try {\n await orchestrator.connect();\n } catch (error) {\n process.stderr.write(`dynmcp: ${error instanceof Error ? error.message : String(error)}\\n`);\n process.exit(1);\n return;\n }\n\n const proxyServer = new ProxyServer({\n catalog: () => orchestrator.catalog,\n capabilities: orchestrator.capabilities,\n callTool: (name, input, options) => orchestrator.callTool(name, input, options),\n resources:\n orchestrator.capabilities.resources !== undefined\n ? {\n listResources: () => orchestrator.listResources(),\n listResourceTemplates: () => orchestrator.listResourceTemplates(),\n readResource: (uri, options) => orchestrator.readResource(uri, options),\n subscribeResource: (uri, options) => orchestrator.subscribeResource(uri, options),\n unsubscribeResource: (uri, options) => orchestrator.unsubscribeResource(uri, options),\n }\n : undefined,\n prompts:\n orchestrator.capabilities.prompts !== undefined\n ? {\n listPrompts: () => orchestrator.listPrompts(),\n getPrompt: (name, args, options) => orchestrator.getPrompt(name, args, options),\n }\n : undefined,\n complete:\n orchestrator.capabilities.completions !== undefined\n ? (params, options) => orchestrator.complete(params, options)\n : undefined,\n setLoggingLevel:\n orchestrator.capabilities.logging !== undefined\n ? (level, options) => orchestrator.setLoggingLevel(level, options)\n : undefined,\n onRootsListChanged: () => orchestrator.broadcastRootsListChanged(),\n });\n\n orchestrator.setNotificationHandlers({\n onToolsListChanged: () => proxyServer.sendToolListChanged(),\n onResourcesListChanged: () => proxyServer.sendResourceListChanged(),\n onResourceUpdated: params => proxyServer.sendResourceUpdated(params),\n onPromptsListChanged: () => proxyServer.sendPromptListChanged(),\n onLogMessage: params => proxyServer.sendLoggingMessage(params),\n });\n\n orchestrator.setServerRequestForwarders({\n onCreateMessage: (params, options) => proxyServer.forwardCreateMessage(params, options),\n onElicitInput: (params, options) => proxyServer.forwardElicitInput(params, options),\n onListRoots: (params, options) => proxyServer.forwardListRoots(params, options),\n });\n\n process.on(\"SIGINT\", () => shutdown(0));\n process.on(\"SIGTERM\", () => shutdown(0));\n process.stdin.on(\"end\", () => shutdown(0));\n process.stdin.on(\"close\", () => shutdown(0));\n\n try {\n await proxyServer.start();\n } catch (error) {\n shutdown(1);\n throw error;\n }\n}\n","import { z } from \"zod\";\n\nexport const MCP_NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;\n\nconst mcpName = z.string().regex(MCP_NAME_PATTERN);\n\nexport const envModeSchema = z\n .enum([\"enable\", \"dotenv\", \"process\", \"disable\"])\n .describe(\n 'Controls environment variable interpolation in config values. \"enable\" (default) merges .env and process.env (.env wins). \"dotenv\" loads .env only. \"process\" uses process.env only. \"disable\" turns interpolation off.',\n );\n\nexport type EnvMode = z.infer<typeof envModeSchema>;\n\nconst stdioTransport = z\n .object({\n transport: z.literal(\"stdio\"),\n command: z.string(),\n args: z.array(z.string()).optional(),\n env: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst httpUrl = z\n .string()\n .url()\n .refine(u => u.startsWith(\"http://\") || u.startsWith(\"https://\"), {\n message: \"URL must use http:// or https:// scheme\",\n });\n\nconst streamableHttpTransport = z\n .object({\n transport: z.literal(\"streamable-http\"),\n url: httpUrl,\n headers: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst sseTransport = z\n .object({\n transport: z.literal(\"sse\"),\n url: httpUrl,\n headers: z.record(z.string(), z.string()).optional(),\n })\n .strict();\n\nconst transportConfig = z.discriminatedUnion(\"transport\", [\n stdioTransport,\n streamableHttpTransport,\n sseTransport,\n]);\n\nexport const mcpConfigSchema = z.object({\n env: envModeSchema.optional(),\n mcp: z\n .record(mcpName, transportConfig)\n .refine(obj => Object.keys(obj).length > 0, { message: \"At least one MCP must be configured\" }),\n});\n\nexport type McpConfig = z.infer<typeof mcpConfigSchema>;\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport process from \"node:process\";\nimport { parse as parseYaml } from \"yaml\";\nimport { loadEnv } from \"./env-sources.js\";\nimport { interpolateConfig } from \"./interpolate.js\";\nimport { type EnvMode, type McpConfig, mcpConfigSchema } from \"./schema.js\";\n\nconst AUTO_DISCOVER_NAMES = [\"mcp.json\", \".mcp.json\"] as const;\nconst DEFAULT_ENV_MODE: EnvMode = \"enable\";\nconst VALID_ENV_MODES: readonly EnvMode[] = [\"enable\", \"dotenv\", \"process\", \"disable\"];\n\nexport interface LoadConfigOptions {\n /** Path to the config file. If omitted, auto-discovers `mcp.json` then `.mcp.json` in cwd. */\n configPath?: string;\n /** Path to a custom `.env` file (from the `--env` / `-e` CLI flag). */\n envFilePath?: string;\n}\n\n/**\n * Resolves the config file path without loading or parsing it.\n *\n * @param explicitPath - If provided, resolves this path directly.\n * @returns The absolute path to the config file.\n * @throws If no config file is found at the explicit path or via auto-discovery.\n */\nexport function resolveConfigPath(explicitPath?: string): string {\n if (explicitPath) {\n const resolved = resolve(explicitPath);\n if (!existsSync(resolved)) {\n throw new Error(`Config file not found: ${resolved}`);\n }\n return resolved;\n }\n\n const cwd = process.cwd();\n for (const name of AUTO_DISCOVER_NAMES) {\n const candidate = resolve(cwd, name);\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n const searched = AUTO_DISCOVER_NAMES.map(n => resolve(cwd, n)).join(\", \");\n throw new Error(`No config file found. Searched: ${searched}`);\n}\n\n/**\n * Loads, parses, interpolates, and validates the dynmcp config file.\n *\n * Flow: resolve path → read file → parse JSON/YAML → read env mode →\n * load env sources → interpolate `${VAR}` references → Zod validate.\n *\n * @param options - Config path and optional custom `.env` file path.\n * @returns The validated config object with all interpolations resolved.\n * @throws On missing file, parse errors, missing env vars, or schema validation failures.\n */\nexport function loadConfig(options: LoadConfigOptions = {}): McpConfig {\n const { configPath, envFilePath } = options;\n\n const resolvedPath = resolveConfigPath(configPath);\n const raw = readFileSync(resolvedPath, \"utf-8\");\n\n let content: unknown;\n try {\n content = isYamlFile(resolvedPath) ? parseYaml(raw) : JSON.parse(raw);\n } catch (parseError) {\n const message = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(`Failed to parse config file (${resolvedPath}): ${message}`);\n }\n\n const envMode = readEnvMode(content);\n const loadedEnv = loadEnv({ mode: envMode, envFilePath });\n\n const interpolated = loadedEnv.interpolationEnabled\n ? interpolateConfig(content, loadedEnv.variables)\n : content;\n\n const result = mcpConfigSchema.safeParse(interpolated);\n if (!result.success) {\n const formatted = result.error.issues\n .map(issue => ` - ${issue.path.join(\".\")}: ${issue.message}`)\n .join(\"\\n\");\n throw new Error(`Invalid config file (${resolvedPath}):\\n${formatted}`);\n }\n\n return result.data;\n}\n\n/**\n * Reads the top-level `env` field from raw parsed config content. This runs\n * before Zod validation so we can resolve env vars before validating types.\n *\n * If the field is missing, the default mode is returned. If it is present but\n * not a recognized value, the default is returned so that Zod can surface a\n * specific validation error later.\n */\nfunction readEnvMode(content: unknown): EnvMode {\n if (content === null || typeof content !== \"object\" || Array.isArray(content)) {\n return DEFAULT_ENV_MODE;\n }\n const value = (content as Record<string, unknown>).env;\n if (value === undefined) return DEFAULT_ENV_MODE;\n if (typeof value === \"string\" && (VALID_ENV_MODES as readonly string[]).includes(value)) {\n return value as EnvMode;\n }\n return DEFAULT_ENV_MODE;\n}\n\nfunction isYamlFile(filePath: string): boolean {\n return filePath.endsWith(\".yml\") || filePath.endsWith(\".yaml\");\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport process from \"node:process\";\nimport dotenv from \"dotenv\";\nimport type { EnvMode } from \"./schema.js\";\n\nconst DEFAULT_DOTENV_FILENAME = \".env\";\n\nexport interface LoadEnvOptions {\n /** Env interpolation mode (from config file top-level `env` field). */\n mode: EnvMode;\n /** Custom `.env` path from the `--env` / `-e` CLI flag. When provided, the file must exist. */\n envFilePath?: string;\n /** Override for cwd (testability). Defaults to `process.cwd()`. */\n cwd?: string;\n /** Override for process.env (testability). Defaults to `process.env`. */\n processEnv?: NodeJS.ProcessEnv;\n}\n\nexport interface LoadedEnv {\n /** Merged variable map ready for interpolation. */\n variables: Record<string, string>;\n /** Whether interpolation should run at all. False only when mode is \"disable\". */\n interpolationEnabled: boolean;\n}\n\n/**\n * Resolves the environment variable map used for config interpolation.\n *\n * Precedence rules:\n * - mode \"enable\": load .env + process.env, .env wins for duplicates.\n * - mode \"dotenv\": load .env only; process.env is ignored.\n * - mode \"process\": process.env only; no .env file is loaded.\n * - mode \"disable\": no sources; interpolation is turned off.\n *\n * The `--env` flag is incompatible with \"disable\" and \"process\" modes and is\n * rejected at startup as an incoherent combination.\n *\n * @throws If `--env` is combined with an incompatible mode.\n * @throws If an explicit `--env` path does not exist or cannot be parsed.\n */\nexport function loadEnv(options: LoadEnvOptions): LoadedEnv {\n const { mode, envFilePath, cwd = process.cwd(), processEnv = process.env } = options;\n\n if (envFilePath !== undefined && (mode === \"disable\" || mode === \"process\")) {\n throw new Error(\n `--env flag is incompatible with env mode \"${mode}\". --env requires env mode \"enable\" or \"dotenv\".`,\n );\n }\n\n if (mode === \"disable\") {\n return { variables: {}, interpolationEnabled: false };\n }\n\n const dotenvVars = mode === \"process\" ? {} : readDotenvFile(envFilePath, cwd);\n const processVars = mode === \"dotenv\" ? {} : filterDefined(processEnv);\n\n // For \"enable\" mode, .env wins (later spread overrides earlier).\n // For \"process\" and \"dotenv\" modes only one source is non-empty, so order is moot.\n const variables = { ...processVars, ...dotenvVars };\n\n return { variables, interpolationEnabled: true };\n}\n\nfunction readDotenvFile(envFilePath: string | undefined, cwd: string): Record<string, string> {\n const isExplicit = envFilePath !== undefined;\n const resolvedPath = isExplicit\n ? resolve(envFilePath as string)\n : resolve(cwd, DEFAULT_DOTENV_FILENAME);\n\n if (!existsSync(resolvedPath)) {\n if (isExplicit) {\n throw new Error(`.env file not found: ${resolvedPath}`);\n }\n // Soft-fail: a missing default .env is not an error.\n return {};\n }\n\n let raw: string;\n try {\n raw = readFileSync(resolvedPath, \"utf-8\");\n } catch (readError) {\n const message = readError instanceof Error ? readError.message : String(readError);\n throw new Error(`Failed to read .env file (${resolvedPath}): ${message}`);\n }\n\n try {\n return dotenv.parse(raw);\n } catch (parseError) {\n const message = parseError instanceof Error ? parseError.message : String(parseError);\n throw new Error(`Failed to parse .env file (${resolvedPath}): ${message}`);\n }\n}\n\nfunction filterDefined(env: NodeJS.ProcessEnv): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) {\n result[key] = value;\n }\n }\n return result;\n}\n","/**\n * Environment variable interpolation for dynmcp config files.\n *\n * Runs after JSON/YAML parsing but before Zod validation, so the validated\n * config contains only fully-resolved string values.\n *\n * Supported syntax (per SPEC.md \"Environment Variable Interpolation\"):\n * - `${VAR}` substitute the value of VAR; missing → error\n * - `${VAR:-default}` substitute VAR, or `default` if VAR is unset or empty\n * - `$${...}` escape — resolves to the literal `${...}`\n *\n * Interpolation applies only to leaf string values reached through the `mcp`\n * subtree. The top-level `$schema` and `env` fields are passed through verbatim.\n */\n\nconst TOP_LEVEL_PASSTHROUGH_KEYS = new Set([\"$schema\", \"env\"]);\n\nexport class MissingEnvVarsError extends Error {\n constructor(public readonly missingVars: readonly string[]) {\n const list = missingVars.join(\", \");\n const plural = missingVars.length === 1 ? \"\" : \"s\";\n super(`Missing required environment variable${plural}: ${list}`);\n this.name = \"MissingEnvVarsError\";\n }\n}\n\n/**\n * Walks a parsed config object and substitutes `${VAR}` references in all leaf\n * string values. Top-level `$schema` and `env` keys are not interpolated.\n *\n * @param config - The parsed (but unvalidated) config object.\n * @param env - The resolved environment variable map (already merged per env mode).\n * @returns A structurally identical config with all string leaves interpolated.\n * @throws {MissingEnvVarsError} If any `${VAR}` reference has no default and no value in env.\n */\nexport function interpolateConfig(config: unknown, env: Record<string, string>): unknown {\n if (config === null || typeof config !== \"object\" || Array.isArray(config)) {\n return config;\n }\n\n const missing: string[] = [];\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(config as Record<string, unknown>)) {\n if (TOP_LEVEL_PASSTHROUGH_KEYS.has(key)) {\n result[key] = value;\n } else {\n result[key] = walkNode(value, env, missing);\n }\n }\n\n if (missing.length > 0) {\n const unique = Array.from(new Set(missing)).sort();\n throw new MissingEnvVarsError(unique);\n }\n\n return result;\n}\n\nfunction walkNode(node: unknown, env: Record<string, string>, missing: string[]): unknown {\n if (typeof node === \"string\") {\n return interpolateString(node, env, missing);\n }\n if (Array.isArray(node)) {\n return node.map(item => walkNode(item, env, missing));\n }\n if (node !== null && typeof node === \"object\") {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node as Record<string, unknown>)) {\n result[key] = walkNode(value, env, missing);\n }\n return result;\n }\n return node;\n}\n\nfunction interpolateString(value: string, env: Record<string, string>, missing: string[]): string {\n let result = \"\";\n let i = 0;\n const len = value.length;\n\n while (i < len) {\n const ch = value[i];\n\n if (ch === \"$\" && value[i + 1] === \"$\" && value[i + 2] === \"{\") {\n // Escape: $${...} -> literal ${...} (strip one leading $)\n const close = value.indexOf(\"}\", i + 3);\n if (close === -1) {\n // Unclosed escape; treat the leading $ as literal and advance one char\n result += ch;\n i += 1;\n continue;\n }\n result += value.substring(i + 1, close + 1);\n i = close + 1;\n continue;\n }\n\n if (ch === \"$\" && value[i + 1] === \"{\") {\n const close = value.indexOf(\"}\", i + 2);\n if (close === -1) {\n // Unclosed expression; emit the rest of the string literally\n result += value.substring(i);\n break;\n }\n const expr = value.substring(i + 2, close);\n const { name, defaultValue } = parseExpr(expr);\n const resolved = env[name];\n const hasValue = resolved !== undefined && resolved !== \"\";\n\n if (hasValue) {\n result += resolved;\n } else if (defaultValue !== undefined) {\n result += defaultValue;\n } else if (resolved !== undefined) {\n // Defined but empty string and no default — treat as the empty string.\n // Per spec: ${VAR} without default fails only when VAR is *undefined*.\n result += \"\";\n } else {\n missing.push(name);\n }\n i = close + 1;\n continue;\n }\n\n result += ch;\n i += 1;\n }\n\n return result;\n}\n\nfunction parseExpr(expr: string): { name: string; defaultValue: string | undefined } {\n const sep = expr.indexOf(\":-\");\n if (sep === -1) {\n return { name: expr, defaultValue: undefined };\n }\n return {\n name: expr.substring(0, sep),\n defaultValue: expr.substring(sep + 2),\n };\n}\n","import { z } from \"zod\";\nimport { mcpConfigSchema } from \"./schema.js\";\n\nexport const MCP_CONFIG_SCHEMA_ID = \"https://unpkg.com/dynmcp/schema/mcp-config.json\";\nexport const MCP_CONFIG_SCHEMA_DRAFT = \"http://json-schema.org/draft-07/schema#\";\n\n/**\n * Generates the JSON Schema for the dynmcp config file from the runtime Zod schema.\n *\n * The schema is targeted at JSON Schema draft-07 for the broadest editor support\n * (VS Code, JetBrains, and the JSON Schema Store all consume draft-07 reliably).\n *\n * @returns A JSON Schema document describing the dynmcp config file format.\n */\nexport function generateMcpConfigJsonSchema(): Record<string, unknown> {\n const generated = z.toJSONSchema(mcpConfigSchema, {\n target: \"draft-7\",\n }) as Record<string, unknown>;\n\n const properties = (generated.properties ?? {}) as Record<string, unknown>;\n const mcpProperty = (properties.mcp ?? {}) as Record<string, unknown>;\n\n return {\n $schema: MCP_CONFIG_SCHEMA_DRAFT,\n $id: MCP_CONFIG_SCHEMA_ID,\n title: \"dynmcp config\",\n description:\n \"Configuration file for dynmcp. Declares the set of upstream MCPs to proxy through dynamic-discovery-mcp.\",\n ...generated,\n properties: {\n ...properties,\n $schema: {\n type: \"string\",\n description: \"URL of the JSON Schema for editor validation.\",\n },\n mcp: {\n ...mcpProperty,\n minProperties: 1,\n description:\n \"Map of upstream MCPs to proxy, keyed by MCP name. Each name becomes the namespace prefix for that MCP's tools.\",\n },\n },\n };\n}\n","import process from \"node:process\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport type {\n CallToolResult,\n CompleteRequest,\n CompleteResult,\n CreateMessageRequest,\n CreateMessageResult,\n ElicitRequest,\n ElicitResult,\n GetPromptResult,\n ListRootsRequest,\n ListRootsResult,\n LoggingLevel,\n Prompt,\n ReadResourceResult,\n Resource,\n ResourceTemplate,\n ServerCapabilities,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { aggregateCapabilities } from \"./capability-aggregator.js\";\nimport { NotificationForwarder, type HostNotificationHandlers } from \"./notification-forwarder.js\";\nimport { PromptRouter } from \"./prompt-router.js\";\nimport { ResourceRouter } from \"./resource-router.js\";\nimport { ToolCatalog } from \"./tool-catalog.js\";\nimport type { UpstreamCallOptions, UpstreamClient, UpstreamTool } from \"./upstream-client.js\";\nimport { UpstreamRegistry, type UpstreamConfig } from \"./upstream-registry.js\";\n\nexport type CallOptions = UpstreamCallOptions;\n\nexport type OrchestratorConfig = {\n mcps: Map<string, { transport: Transport }>;\n /**\n * When true (config-file mode), tools are exposed as `<mcpName>/<toolName>` and routed\n * by splitting on the first `/`. When false (single-MCP `--` mode), tools are exposed\n * as bare names and routed to the sole upstream client. In single mode `mcps` must\n * contain exactly one entry.\n */\n namespaced: boolean;\n onTransportError?: (mcpName: string, error: Error) => void;\n};\n\nexport type OrchestratorNotificationHandlers = HostNotificationHandlers;\n\n/**\n * Forwarders for upstream-initiated requests. The Orchestrator wires each upstream\n * client's incoming request handlers to call into these so the proxy can relay the\n * request to the host. `signal` is the upstream's request-abort signal — passing it\n * through to the host call propagates cancellation if the upstream cancels.\n */\nexport type OrchestratorServerRequestForwarders = {\n onCreateMessage?: (\n params: CreateMessageRequest[\"params\"],\n options: { signal: AbortSignal },\n ) => Promise<CreateMessageResult>;\n onElicitInput?: (\n params: ElicitRequest[\"params\"],\n options: { signal: AbortSignal },\n ) => Promise<ElicitResult>;\n onListRoots?: (\n params: ListRootsRequest[\"params\"],\n options: { signal: AbortSignal },\n ) => Promise<ListRootsResult>;\n};\n\n/**\n * Composition root for the proxy hub. Composes {@link UpstreamRegistry} (lifecycle),\n * {@link NotificationForwarder} (upstream→host notification translation), and the\n * routers/catalogs (forward-direction request routing). Public surface is the same\n * across single-MCP and config-file modes; the `namespaced` flag toggles tool-naming\n * behavior internally.\n */\nexport class Orchestrator {\n private readonly config: OrchestratorConfig;\n private readonly registry: UpstreamRegistry = new UpstreamRegistry();\n private readonly toolsByMcp: Map<string, UpstreamTool[]> = new Map();\n private resourceRouter: ResourceRouter | null = null;\n private promptRouter: PromptRouter | null = null;\n private toolCatalog: ToolCatalog | null = null;\n private aggregatedCapabilities: ServerCapabilities | null = null;\n private serverRequestForwarders: OrchestratorServerRequestForwarders = {};\n private readonly forwarder: NotificationForwarder;\n\n constructor(config: OrchestratorConfig) {\n if (!config.namespaced && config.mcps.size !== 1) {\n throw new Error(\n `Single-MCP (non-namespaced) mode requires exactly one upstream; got ${config.mcps.size}.`,\n );\n }\n this.config = config;\n this.forwarder = new NotificationForwarder(\n this.registry,\n () => this.resourceRouter,\n () => this.promptRouter,\n this.toolsByMcp,\n catalog => {\n this.toolCatalog = catalog;\n },\n this.config.namespaced,\n );\n }\n\n setNotificationHandlers(handlers: OrchestratorNotificationHandlers): void {\n this.forwarder.setHostHandlers(handlers);\n }\n\n setServerRequestForwarders(forwarders: OrchestratorServerRequestForwarders): void {\n this.serverRequestForwarders = forwarders;\n }\n\n async connect(): Promise<void> {\n const resourceRouter = new ResourceRouter([...this.config.mcps.keys()]);\n const promptRouter = new PromptRouter([...this.config.mcps.keys()]);\n\n const upstreamEntries: ReadonlyArray<readonly [string, UpstreamConfig]> = [\n ...this.config.mcps,\n ].map(([mcpName, { transport }]) => [\n mcpName,\n {\n transport,\n onTransportError: (error: Error) => {\n this.config.onTransportError?.(mcpName, error);\n },\n notifications: {\n onToolsListChanged: () => this.forwarder.handleToolsListChanged(mcpName),\n onResourcesListChanged: () => this.forwarder.handleResourcesListChanged(mcpName),\n onResourceUpdated: params => this.forwarder.handleResourceUpdated(params),\n onPromptsListChanged: () => this.forwarder.handlePromptsListChanged(mcpName),\n onLogMessage: params => this.forwarder.handleLogMessage(mcpName, params),\n },\n serverRequests: {\n onCreateMessage: (params, opts) => this.forwardCreateMessage(params, opts),\n onElicitInput: (params, opts) => this.forwardElicitInput(params, opts),\n onListRoots: (params, opts) => this.forwardListRoots(params, opts),\n },\n },\n ]);\n\n await this.registry.connectAll(upstreamEntries);\n\n const capabilityList: (ServerCapabilities | undefined)[] = [];\n this.toolsByMcp.clear();\n\n for (const [mcpName, client] of this.registry.entries()) {\n const caps = client.getCapabilities();\n capabilityList.push(caps);\n\n const tools = await client.listTools();\n this.toolsByMcp.set(mcpName, tools);\n\n if (caps?.resources !== undefined) {\n const [resources, templates] = await Promise.all([\n client.listResources().catch(() => [] as Resource[]),\n client.listResourceTemplates().catch(() => [] as ResourceTemplate[]),\n ]);\n resourceRouter.setResources(mcpName, resources);\n resourceRouter.setTemplates(mcpName, templates);\n }\n if (caps?.prompts !== undefined) {\n const prompts = await client.listPrompts().catch(() => [] as Prompt[]);\n promptRouter.setPrompts(mcpName, prompts);\n }\n }\n\n this.toolCatalog = this.config.namespaced\n ? ToolCatalog.fromGrouped(this.toolsByMcp)\n : ToolCatalog.fromFlat([...this.toolsByMcp.values()][0] ?? []);\n this.aggregatedCapabilities = aggregateCapabilities(capabilityList);\n this.resourceRouter = resourceRouter;\n this.promptRouter = promptRouter;\n\n logCollisions(resourceRouter, promptRouter);\n }\n\n async disconnectAll(): Promise<void> {\n await this.registry.disconnectAll();\n this.toolsByMcp.clear();\n this.toolCatalog = null;\n this.aggregatedCapabilities = null;\n this.resourceRouter = null;\n this.promptRouter = null;\n }\n\n get catalog(): ToolCatalog {\n if (this.toolCatalog === null) {\n throw new Error(\"Orchestrator is not connected. Call connect() first.\");\n }\n return this.toolCatalog;\n }\n\n get capabilities(): ServerCapabilities {\n if (this.aggregatedCapabilities === null) {\n throw new Error(\"Orchestrator is not connected. Call connect() first.\");\n }\n return this.aggregatedCapabilities;\n }\n\n // === Forward-direction request routing ===\n\n async callTool(\n displayName: string,\n input: Record<string, unknown>,\n options?: CallOptions,\n ): Promise<CallToolResult> {\n if (this.config.namespaced) {\n const { mcpName, toolName } = splitNamespacedName(displayName, this.registry.names());\n return this.requireClient(mcpName, \"tool\").callTool(toolName, input, options);\n }\n\n const sole = this.registry.sole();\n if (sole === undefined) {\n throw new Error(\"Orchestrator is not connected. Call connect() first.\");\n }\n return sole.callTool(displayName, input, options);\n }\n\n listResources(): Resource[] {\n return this.requireResourceRouter().aggregatedResources();\n }\n\n listResourceTemplates(): ResourceTemplate[] {\n return this.requireResourceRouter().aggregatedTemplates();\n }\n\n async readResource(uri: string, options?: CallOptions): Promise<ReadResourceResult> {\n return this.resolveResourceOwner(uri).readResource(uri, options);\n }\n\n async subscribeResource(uri: string, options?: CallOptions): Promise<void> {\n await this.resolveResourceOwner(uri).subscribeResource(uri, options);\n }\n\n async unsubscribeResource(uri: string, options?: CallOptions): Promise<void> {\n await this.resolveResourceOwner(uri).unsubscribeResource(uri, options);\n }\n\n listPrompts(): Prompt[] {\n return this.requirePromptRouter().aggregatedPrompts();\n }\n\n async getPrompt(\n name: string,\n args?: Record<string, string>,\n options?: CallOptions,\n ): Promise<GetPromptResult> {\n return this.resolvePromptOwner(name).getPrompt(name, args, options);\n }\n\n async complete(\n params: CompleteRequest[\"params\"],\n options?: CallOptions,\n ): Promise<CompleteResult> {\n const client = this.resolveCompletionTarget(params.ref);\n return client.complete(params, options);\n }\n\n // === Broadcasts ===\n\n /**\n * Broadcasts a `logging/setLevel` request to every upstream advertising the logging\n * capability. Errors from individual upstreams are swallowed so a single misbehaving\n * upstream cannot break the broadcast for others; failures are written to stderr.\n */\n async setLoggingLevel(level: LoggingLevel, options?: CallOptions): Promise<void> {\n await this.broadcastAsync(\n client =>\n client.getCapabilities()?.logging !== undefined\n ? client.setLoggingLevel(level, options)\n : Promise.resolve(),\n \"setLoggingLevel\",\n );\n }\n\n /**\n * Broadcasts `notifications/roots/list_changed` to every connected upstream — the\n * proxy declares roots capability uniformly to all upstreams so every one of them\n * may have requested roots and needs to know the list changed.\n */\n async broadcastRootsListChanged(): Promise<void> {\n await this.broadcastAsync(client => client.sendRootsListChanged(), \"sendRootsListChanged\");\n }\n\n // === Server-initiated request forwarders (upstream → host) ===\n\n private async forwardCreateMessage(\n params: CreateMessageRequest[\"params\"],\n options: { signal: AbortSignal },\n ): Promise<CreateMessageResult> {\n const handler = this.serverRequestForwarders.onCreateMessage;\n if (handler === undefined) {\n throw new Error(\"Proxy does not support sampling: host has not registered a handler.\");\n }\n return handler(params, options);\n }\n\n private async forwardElicitInput(\n params: ElicitRequest[\"params\"],\n options: { signal: AbortSignal },\n ): Promise<ElicitResult> {\n const handler = this.serverRequestForwarders.onElicitInput;\n if (handler === undefined) {\n throw new Error(\"Proxy does not support elicitation: host has not registered a handler.\");\n }\n return handler(params, options);\n }\n\n private async forwardListRoots(\n params: ListRootsRequest[\"params\"],\n options: { signal: AbortSignal },\n ): Promise<ListRootsResult> {\n const handler = this.serverRequestForwarders.onListRoots;\n if (handler === undefined) {\n throw new Error(\"Proxy does not support roots: host has not registered a handler.\");\n }\n return handler(params, options);\n }\n\n // === Internal helpers ===\n\n private requireResourceRouter(): ResourceRouter {\n if (this.resourceRouter === null) {\n throw new Error(\"Orchestrator is not connected. Call connect() first.\");\n }\n return this.resourceRouter;\n }\n\n private requirePromptRouter(): PromptRouter {\n if (this.promptRouter === null) {\n throw new Error(\"Orchestrator is not connected. Call connect() first.\");\n }\n return this.promptRouter;\n }\n\n private resolveResourceOwner(uri: string): UpstreamClient {\n const owner = this.requireResourceRouter().ownerOf(uri);\n if (owner === undefined) {\n throw new Error(`Unknown resource URI: \"${uri}\". No upstream MCP advertises it.`);\n }\n return this.requireClient(owner, \"resource\");\n }\n\n private resolvePromptOwner(name: string): UpstreamClient {\n const owner = this.requirePromptRouter().ownerOf(name);\n if (owner === undefined) {\n throw new Error(`Unknown prompt: \"${name}\". No upstream MCP advertises it.`);\n }\n return this.requireClient(owner, \"prompt\");\n }\n\n private resolveCompletionTarget(ref: CompleteRequest[\"params\"][\"ref\"]): UpstreamClient {\n if (ref.type === \"ref/prompt\") {\n return this.resolvePromptOwner(ref.name);\n }\n if (ref.type === \"ref/resource\") {\n return this.resolveResourceOwner(ref.uri);\n }\n const unknownRef: { type: string } = ref;\n throw new Error(`Unsupported completion ref type: \"${unknownRef.type}\"`);\n }\n\n private requireClient(mcpName: string, role: string): UpstreamClient {\n const client = this.registry.get(mcpName);\n if (client === undefined) {\n throw new Error(`Internal error: ${role} owner \"${mcpName}\" has no connected client.`);\n }\n return client;\n }\n\n private async broadcastAsync(\n action: (client: UpstreamClient) => Promise<void>,\n label: string,\n ): Promise<void> {\n const targets: Promise<void>[] = [];\n for (const [mcpName, client] of this.registry.entries()) {\n targets.push(\n action(client).catch((error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(`dynmcp: ${label} failed for \"${mcpName}\": ${message}\\n`);\n }),\n );\n }\n await Promise.all(targets);\n }\n}\n\nfunction splitNamespacedName(\n namespacedName: string,\n knownMcpNames: readonly string[],\n): { mcpName: string; toolName: string } {\n const separatorIndex = namespacedName.indexOf(\"/\");\n if (separatorIndex === -1) {\n throw new Error(\n `Invalid namespaced tool name: \"${namespacedName}\". Expected format: \"mcpName/toolName\".`,\n );\n }\n\n const mcpName = namespacedName.slice(0, separatorIndex);\n const toolName = namespacedName.slice(separatorIndex + 1);\n\n if (!knownMcpNames.includes(mcpName)) {\n const available = [...knownMcpNames].sort().join(\", \");\n throw new Error(`Unknown MCP: \"${mcpName}\". Available MCPs: ${available}`);\n }\n\n return { mcpName, toolName };\n}\n\nfunction logCollisions(resourceRouter: ResourceRouter, promptRouter: PromptRouter): void {\n for (const collision of resourceRouter.collisions()) {\n process.stderr.write(\n `dynmcp: resource URI collision: \"${collision.uri}\" is provided by ` +\n `\"${collision.chosen}\" and \"${collision.shadowed}\"; routing to \"${collision.chosen}\".\\n`,\n );\n }\n for (const collision of promptRouter.collisions()) {\n process.stderr.write(\n `dynmcp: prompt name collision: \"${collision.name}\" is provided by ` +\n `\"${collision.chosen}\" and \"${collision.shadowed}\"; routing to \"${collision.chosen}\".\\n`,\n );\n }\n}\n","import type { ServerCapabilities } from \"@modelcontextprotocol/sdk/types.js\";\n\n/**\n * Aggregates the capabilities advertised by every upstream MCP into the single\n * capability set that the proxy will advertise to the host during `initialize`.\n *\n * Rules (per SPEC.md \"Capability Aggregation\"):\n *\n * - `tools` is always advertised — the proxy itself exposes `discover_tool` and `use_tool`\n * regardless of upstream support.\n * - `tools.listChanged` is always advertised — the proxy emits it when any upstream's tool\n * list changes, even when no individual upstream supports the notification.\n * - All other capabilities (`resources`, `prompts`, `logging`, `completions`) are advertised\n * iff at least one upstream advertises them. Nested booleans (`subscribe`, `listChanged`)\n * are advertised iff at least one supporting upstream advertises them.\n */\nexport function aggregateCapabilities(\n upstreams: ReadonlyArray<ServerCapabilities | undefined>,\n): ServerCapabilities {\n const aggregated: ServerCapabilities = {\n tools: { listChanged: true },\n };\n\n for (const caps of upstreams) {\n if (caps === undefined) continue;\n\n if (caps.resources !== undefined) {\n aggregated.resources ??= {};\n if (caps.resources.subscribe === true) {\n aggregated.resources.subscribe = true;\n }\n if (caps.resources.listChanged === true) {\n aggregated.resources.listChanged = true;\n }\n }\n\n if (caps.prompts !== undefined) {\n aggregated.prompts ??= {};\n if (caps.prompts.listChanged === true) {\n aggregated.prompts.listChanged = true;\n }\n }\n\n if (caps.logging !== undefined) {\n aggregated.logging ??= {};\n }\n\n if (caps.completions !== undefined) {\n aggregated.completions ??= {};\n }\n }\n\n return aggregated;\n}\n","import type { UpstreamTool } from \"./upstream-client.js\";\n\nconst DISCOVER_TOOL_PREAMBLE = `Use this tool to look up the full schema of a tool before calling it with use_tool.\nCall discover_tool with a tool name from the list below to get its complete description,\ninput parameters, and output schema. Always discover a tool before using it.`;\n\nexport class ToolCatalog {\n readonly tools: ReadonlyMap<string, UpstreamTool>;\n readonly discoverToolDescription: string;\n\n private constructor(tools: Map<string, UpstreamTool>, description: string) {\n this.tools = tools;\n this.discoverToolDescription = description;\n }\n\n static fromFlat(upstreamTools: UpstreamTool[]): ToolCatalog {\n const toolMap = new Map<string, UpstreamTool>();\n for (const tool of upstreamTools) {\n toolMap.set(tool.name, tool);\n }\n const description = buildFlatDescription(upstreamTools);\n return new ToolCatalog(toolMap, description);\n }\n\n static fromGrouped(groups: Map<string, UpstreamTool[]>): ToolCatalog {\n const toolMap = new Map<string, UpstreamTool>();\n for (const [mcpName, tools] of groups) {\n for (const tool of tools) {\n toolMap.set(`${mcpName}/${tool.name}`, tool);\n }\n }\n const description = buildGroupedDescription(groups);\n return new ToolCatalog(toolMap, description);\n }\n\n getToolDetails(toolName: string): string {\n const tool = this.tools.get(toolName);\n\n if (tool === undefined) {\n const sortedNames = [...this.tools.keys()].sort().join(\", \");\n return `Unknown tool: \"${toolName}\". Available tools: ${sortedNames}`;\n }\n\n return buildToolDetailsString(toolName, tool);\n }\n}\n\nfunction buildFlatDescription(tools: UpstreamTool[]): string {\n const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));\n const toolLines = sortedTools.map(tool => `- ${tool.name}: ${tool.description}`).join(\"\\n\");\n\n return `${DISCOVER_TOOL_PREAMBLE}\\n\\n<tools>\\n${toolLines}\\n</tools>`;\n}\n\nfunction buildGroupedDescription(groups: Map<string, UpstreamTool[]>): string {\n const sortedMcpNames = [...groups.keys()].sort();\n const sections = sortedMcpNames.map(mcpName => {\n const tools = groups.get(mcpName)!;\n const sortedTools = [...tools].sort((a, b) => a.name.localeCompare(b.name));\n const toolLines = sortedTools\n .map(tool => `- ${mcpName}/${tool.name}: ${tool.description}`)\n .join(\"\\n\");\n return `${mcpName}:\\n${toolLines}`;\n });\n\n return `${DISCOVER_TOOL_PREAMBLE}\\n\\n<tools>\\n${sections.join(\"\\n\\n\")}\\n</tools>`;\n}\n\nfunction buildToolDetailsString(displayName: string, tool: UpstreamTool): string {\n const lines: string[] = [\n `Tool: ${displayName}`,\n `Description: ${tool.description}`,\n \"\",\n \"Input Schema:\",\n JSON.stringify(tool.inputSchema, null, 2),\n ];\n\n if (tool.outputSchema !== undefined) {\n lines.push(\"\", \"Output Schema:\", JSON.stringify(tool.outputSchema, null, 2));\n }\n\n const annotationLines = buildAnnotationLines(tool);\n if (annotationLines.length > 0) {\n lines.push(\"\", \"Annotations:\", ...annotationLines);\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction buildAnnotationLines(tool: UpstreamTool): string[] {\n if (tool.annotations === undefined) {\n return [];\n }\n\n const { annotations } = tool;\n const lines: string[] = [];\n\n if (annotations.title !== undefined) {\n lines.push(`- title: ${annotations.title}`);\n }\n if (annotations.readOnlyHint !== undefined) {\n lines.push(`- readOnlyHint: ${annotations.readOnlyHint}`);\n }\n if (annotations.destructiveHint !== undefined) {\n lines.push(`- destructiveHint: ${annotations.destructiveHint}`);\n }\n if (annotations.idempotentHint !== undefined) {\n lines.push(`- idempotentHint: ${annotations.idempotentHint}`);\n }\n if (annotations.openWorldHint !== undefined) {\n lines.push(`- openWorldHint: ${annotations.openWorldHint}`);\n }\n\n return lines;\n}\n","import type { Prompt, Resource, ResourceTemplate } from \"@modelcontextprotocol/sdk/types.js\";\nimport type { PromptRouter } from \"./prompt-router.js\";\nimport type { ResourceRouter } from \"./resource-router.js\";\nimport { ToolCatalog } from \"./tool-catalog.js\";\nimport type { LogMessageParams, UpstreamTool } from \"./upstream-client.js\";\nimport type { UpstreamRegistry } from \"./upstream-registry.js\";\n\n/**\n * Callbacks the proxy uses to push notifications out to the host once an upstream\n * has emitted the equivalent inbound notification. The {@link NotificationForwarder}\n * is the seam between the upstream-side notification handlers (which it owns) and\n * the host-side outbound calls (which the caller provides).\n */\nexport type HostNotificationHandlers = {\n onToolsListChanged?: () => void | Promise<void>;\n onResourcesListChanged?: () => void | Promise<void>;\n onResourceUpdated?: (params: { uri: string }) => void | Promise<void>;\n onPromptsListChanged?: () => void | Promise<void>;\n onLogMessage?: (params: LogMessageParams) => void | Promise<void>;\n};\n\n/**\n * Translates upstream-emitted notifications into proxy-emitted notifications sent\n * to the host. For list-change notifications this includes re-fetching the affected\n * data from the originating upstream and updating the shared catalogs/routers before\n * propagating the change. For log messages it rewrites the `logger` field with the\n * `<mcp-name>/` prefix in config-file mode.\n *\n * The forwarder holds references to mutable state (the tool catalog, the routers)\n * and is expected to be co-owned with whatever assembles that state — typically the\n * Orchestrator. Catalog rebuilds are performed via the {@link buildToolCatalog}\n * callback so the Orchestrator stays the single owner of the catalog reference.\n */\nexport class NotificationForwarder {\n private hostHandlers: HostNotificationHandlers = {};\n\n constructor(\n private readonly registry: UpstreamRegistry,\n private readonly resourceRouter: () => ResourceRouter | null,\n private readonly promptRouter: () => PromptRouter | null,\n private readonly toolsByMcp: Map<string, UpstreamTool[]>,\n private readonly setToolCatalog: (catalog: ToolCatalog) => void,\n private readonly namespaced: boolean,\n ) {}\n\n setHostHandlers(handlers: HostNotificationHandlers): void {\n this.hostHandlers = handlers;\n }\n\n async handleToolsListChanged(mcpName: string): Promise<void> {\n const client = this.registry.get(mcpName);\n if (client === undefined) return;\n\n const tools = await client.listTools().catch(() => [] as UpstreamTool[]);\n this.toolsByMcp.set(mcpName, tools);\n\n const rebuilt = this.namespaced\n ? ToolCatalog.fromGrouped(this.toolsByMcp)\n : ToolCatalog.fromFlat([...this.toolsByMcp.values()][0] ?? []);\n this.setToolCatalog(rebuilt);\n\n await this.hostHandlers.onToolsListChanged?.();\n }\n\n async handleResourcesListChanged(mcpName: string): Promise<void> {\n const router = this.resourceRouter();\n const client = this.registry.get(mcpName);\n if (router === null || client === undefined) return;\n\n const [resources, templates] = await Promise.all([\n client.listResources().catch(() => [] as Resource[]),\n client.listResourceTemplates().catch(() => [] as ResourceTemplate[]),\n ]);\n router.setResources(mcpName, resources);\n router.setTemplates(mcpName, templates);\n\n await this.hostHandlers.onResourcesListChanged?.();\n }\n\n async handleResourceUpdated(params: { uri: string }): Promise<void> {\n await this.hostHandlers.onResourceUpdated?.(params);\n }\n\n async handlePromptsListChanged(mcpName: string): Promise<void> {\n const router = this.promptRouter();\n const client = this.registry.get(mcpName);\n if (router === null || client === undefined) return;\n\n const prompts = await client.listPrompts().catch(() => [] as Prompt[]);\n router.setPrompts(mcpName, prompts);\n\n await this.hostHandlers.onPromptsListChanged?.();\n }\n\n /**\n * Rewrites the upstream's `logger` field with the originating MCP's name as a\n * prefix so the host can attribute log lines, then forwards the message to the\n * host's log message handler.\n */\n async handleLogMessage(mcpName: string, params: LogMessageParams): Promise<void> {\n const handler = this.hostHandlers.onLogMessage;\n if (handler === undefined) return;\n\n if (!this.namespaced) {\n await handler(params);\n return;\n }\n\n const prefixed: LogMessageParams = {\n ...params,\n logger: params.logger === undefined ? mcpName : `${mcpName}/${params.logger}`,\n };\n await handler(prefixed);\n }\n}\n","import type { Prompt } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type PromptCollision = {\n name: string;\n chosen: string;\n shadowed: string;\n};\n\n/**\n * Tracks which upstream MCP owns each prompt name exposed through the proxy and\n * resolves the owner for any `prompts/get` or `completion/complete` request that\n * references a prompt by name.\n *\n * Collision rule: when two upstreams advertise the same prompt name, the upstream\n * appearing first in config-file order wins; the shadowed upstream's prompt is\n * unreachable through the proxy until the conflict is resolved upstream.\n */\nexport class PromptRouter {\n private readonly mcpOrder: string[];\n private readonly perMcp: Map<string, Prompt[]>;\n\n private nameOwners: Map<string, string> = new Map();\n private detectedCollisions: PromptCollision[] = [];\n\n constructor(mcpOrder: readonly string[]) {\n this.mcpOrder = [...mcpOrder];\n this.perMcp = new Map(this.mcpOrder.map(name => [name, [] as Prompt[]]));\n }\n\n setPrompts(mcpName: string, prompts: Prompt[]): void {\n const entry = this.perMcp.get(mcpName);\n if (entry === undefined) {\n throw new Error(`PromptRouter: unknown mcp \"${mcpName}\"`);\n }\n this.perMcp.set(mcpName, [...prompts]);\n this.rebuild();\n }\n\n aggregatedPrompts(): Prompt[] {\n const result: Prompt[] = [];\n for (const mcpName of this.mcpOrder) {\n const entry = this.perMcp.get(mcpName);\n if (entry !== undefined) {\n result.push(...entry);\n }\n }\n return result;\n }\n\n ownerOf(promptName: string): string | undefined {\n return this.nameOwners.get(promptName);\n }\n\n collisions(): readonly PromptCollision[] {\n return this.detectedCollisions;\n }\n\n private rebuild(): void {\n this.nameOwners = new Map();\n const collisions: PromptCollision[] = [];\n\n for (const mcpName of this.mcpOrder) {\n const prompts = this.perMcp.get(mcpName);\n if (prompts === undefined) continue;\n\n for (const prompt of prompts) {\n const existing = this.nameOwners.get(prompt.name);\n if (existing === undefined) {\n this.nameOwners.set(prompt.name, mcpName);\n } else {\n collisions.push({ name: prompt.name, chosen: existing, shadowed: mcpName });\n }\n }\n }\n\n this.detectedCollisions = collisions;\n }\n}\n","import type { Resource, ResourceTemplate } from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type ResourceCollision = {\n uri: string;\n chosen: string;\n shadowed: string;\n};\n\n/**\n * Tracks which upstream MCP owns each resource URI exposed through the proxy and\n * resolves the owner for any `resources/read`, `resources/subscribe`, or\n * `resources/unsubscribe` request.\n *\n * Collision rule: when two upstreams advertise the same concrete URI, the upstream\n * appearing first in config-file order wins; the shadowed upstream's copy of that\n * resource is unreachable through the proxy until the conflict is resolved upstream.\n *\n * Template URIs (RFC 6570 forms like `file:///{path}`) are matched against incoming\n * URIs by their literal prefix (everything before the first `{`). When more than one\n * upstream advertises an overlapping template, the first-wins rule applies on a\n * prefix-equality basis.\n *\n * Concrete URI matches always take precedence over template matches, regardless of\n * config order.\n */\nexport class ResourceRouter {\n private readonly mcpOrder: string[];\n private readonly perMcp: Map<string, { resources: Resource[]; templates: ResourceTemplate[] }>;\n\n private uriOwners: Map<string, string> = new Map();\n private templateOwners: Array<{ prefix: string; template: ResourceTemplate; mcpName: string }> =\n [];\n private detectedCollisions: ResourceCollision[] = [];\n\n constructor(mcpOrder: readonly string[]) {\n this.mcpOrder = [...mcpOrder];\n this.perMcp = new Map(\n this.mcpOrder.map(name => [name, { resources: [], templates: [] }] as const),\n );\n }\n\n setResources(mcpName: string, resources: Resource[]): void {\n const entry = this.perMcp.get(mcpName);\n if (entry === undefined) {\n throw new Error(`ResourceRouter: unknown mcp \"${mcpName}\"`);\n }\n entry.resources = [...resources];\n this.rebuild();\n }\n\n setTemplates(mcpName: string, templates: ResourceTemplate[]): void {\n const entry = this.perMcp.get(mcpName);\n if (entry === undefined) {\n throw new Error(`ResourceRouter: unknown mcp \"${mcpName}\"`);\n }\n entry.templates = [...templates];\n this.rebuild();\n }\n\n aggregatedResources(): Resource[] {\n const result: Resource[] = [];\n for (const mcpName of this.mcpOrder) {\n const entry = this.perMcp.get(mcpName);\n if (entry !== undefined) {\n result.push(...entry.resources);\n }\n }\n return result;\n }\n\n aggregatedTemplates(): ResourceTemplate[] {\n const result: ResourceTemplate[] = [];\n for (const mcpName of this.mcpOrder) {\n const entry = this.perMcp.get(mcpName);\n if (entry !== undefined) {\n result.push(...entry.templates);\n }\n }\n return result;\n }\n\n /**\n * Returns the mcpName that owns the given URI, or undefined if no upstream advertises it.\n * Concrete URI matches take precedence over template prefix matches; templates are tried\n * in config-file order (first-wins).\n */\n ownerOf(uri: string): string | undefined {\n const concrete = this.uriOwners.get(uri);\n if (concrete !== undefined) {\n return concrete;\n }\n\n for (const { prefix, mcpName } of this.templateOwners) {\n if (prefix.length > 0 && uri.startsWith(prefix)) {\n return mcpName;\n }\n }\n\n return undefined;\n }\n\n collisions(): readonly ResourceCollision[] {\n return this.detectedCollisions;\n }\n\n private rebuild(): void {\n this.uriOwners = new Map();\n this.templateOwners = [];\n const collisions: ResourceCollision[] = [];\n\n for (const mcpName of this.mcpOrder) {\n const entry = this.perMcp.get(mcpName);\n if (entry === undefined) continue;\n\n for (const resource of entry.resources) {\n const existing = this.uriOwners.get(resource.uri);\n if (existing === undefined) {\n this.uriOwners.set(resource.uri, mcpName);\n } else {\n collisions.push({ uri: resource.uri, chosen: existing, shadowed: mcpName });\n }\n }\n\n for (const template of entry.templates) {\n this.templateOwners.push({\n prefix: literalPrefixOf(template.uriTemplate),\n template,\n mcpName,\n });\n }\n }\n\n this.detectedCollisions = collisions;\n }\n}\n\nfunction literalPrefixOf(uriTemplate: string): string {\n const idx = uriTemplate.indexOf(\"{\");\n return idx === -1 ? uriTemplate : uriTemplate.slice(0, idx);\n}\n","import process from \"node:process\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport {\n type CallToolResult,\n type CompleteRequest,\n type CompleteResult,\n type CreateMessageRequest,\n type CreateMessageResult,\n CreateMessageRequestSchema,\n type ElicitRequest,\n type ElicitResult,\n ElicitRequestSchema,\n type GetPromptResult,\n type ListRootsRequest,\n type ListRootsResult,\n ListRootsRequestSchema,\n type LoggingLevel,\n type LoggingMessageNotification,\n LoggingMessageNotificationSchema,\n type Prompt,\n PromptListChangedNotificationSchema,\n type ReadResourceResult,\n type Resource,\n ResourceListChangedNotificationSchema,\n type ResourceTemplate,\n ResourceUpdatedNotificationSchema,\n type ServerCapabilities,\n ToolListChangedNotificationSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\n\nexport type LogMessageParams = LoggingMessageNotification[\"params\"];\n\nexport type ToolAnnotations = {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n};\n\nexport type UpstreamTool = {\n name: string;\n description: string;\n inputSchema: unknown;\n outputSchema?: unknown;\n annotations?: ToolAnnotations;\n};\n\nexport type UpstreamNotificationHandlers = {\n onToolsListChanged?: () => void | Promise<void>;\n onResourcesListChanged?: () => void | Promise<void>;\n onResourceUpdated?: (params: { uri: string }) => void | Promise<void>;\n onPromptsListChanged?: () => void | Promise<void>;\n onLogMessage?: (params: LogMessageParams) => void | Promise<void>;\n};\n\n/**\n * Per-call options forwarded to the SDK so cancellation can propagate from the host\n * down to the upstream MCP. When the host cancels its incoming request, the SDK\n * server handler's `signal` aborts; passing that signal through these options causes\n * the SDK client to emit `notifications/cancelled` to the upstream.\n */\nexport type UpstreamCallOptions = {\n signal?: AbortSignal;\n};\n\n/**\n * Reverse-direction handlers invoked when an upstream MCP sends a server-initiated\n * request to the proxy (e.g. `sampling/createMessage`). The proxy forwards each\n * request to the host via these callbacks; the host's response is returned to the\n * originating upstream by the SDK.\n *\n * The `signal` parameter is the upstream's request abort signal — passing it through\n * to the host call causes the host's request to be cancelled if the upstream cancels.\n */\nexport type UpstreamServerRequestHandlers = {\n onCreateMessage?: (\n params: CreateMessageRequest[\"params\"],\n options: { signal: AbortSignal },\n ) => Promise<CreateMessageResult>;\n onElicitInput?: (\n params: ElicitRequest[\"params\"],\n options: { signal: AbortSignal },\n ) => Promise<ElicitResult>;\n onListRoots?: (\n params: ListRootsRequest[\"params\"],\n options: { signal: AbortSignal },\n ) => Promise<ListRootsResult>;\n};\n\ntype UpstreamClientConfig = {\n name: string;\n transport: Transport;\n onTransportError?: (error: Error) => void;\n notifications?: UpstreamNotificationHandlers;\n serverRequests?: UpstreamServerRequestHandlers;\n};\n\nexport class UpstreamClient {\n private readonly transport: Transport;\n private readonly onTransportError: (error: Error) => void;\n private readonly notificationHandlers: UpstreamNotificationHandlers;\n private readonly serverRequestHandlers: UpstreamServerRequestHandlers;\n private client: Client | null = null;\n\n constructor({\n name,\n transport,\n onTransportError,\n notifications,\n serverRequests,\n }: UpstreamClientConfig) {\n this.transport = transport;\n this.notificationHandlers = notifications ?? {};\n this.serverRequestHandlers = serverRequests ?? {};\n this.onTransportError =\n onTransportError ??\n ((error: Error) => {\n process.stderr.write(`[${name}] Upstream MCP transport error: ${error.message}\\n`);\n });\n }\n\n async connect(): Promise<void> {\n this.transport.onerror = this.onTransportError;\n this.client = new Client(\n { name: \"dynamic-discovery-mcp\", version: \"1.0.0\" },\n {\n capabilities: {\n // Declare every client-side capability the proxy may relay on behalf of the host.\n // Actual reachability of each feature depends on what the host supports — if the\n // host does not support sampling, for instance, the host call returns an error\n // which we forward back to the upstream verbatim.\n sampling: {},\n elicitation: {},\n roots: { listChanged: true },\n },\n },\n );\n\n this.registerServerRequestHandlers(this.client);\n\n if (this.notificationHandlers.onToolsListChanged !== undefined) {\n this.client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {\n await this.notificationHandlers.onToolsListChanged?.();\n });\n }\n if (this.notificationHandlers.onResourcesListChanged !== undefined) {\n this.client.setNotificationHandler(ResourceListChangedNotificationSchema, async () => {\n await this.notificationHandlers.onResourcesListChanged?.();\n });\n }\n if (this.notificationHandlers.onResourceUpdated !== undefined) {\n this.client.setNotificationHandler(ResourceUpdatedNotificationSchema, async notification => {\n await this.notificationHandlers.onResourceUpdated?.({ uri: notification.params.uri });\n });\n }\n if (this.notificationHandlers.onPromptsListChanged !== undefined) {\n this.client.setNotificationHandler(PromptListChangedNotificationSchema, async () => {\n await this.notificationHandlers.onPromptsListChanged?.();\n });\n }\n if (this.notificationHandlers.onLogMessage !== undefined) {\n this.client.setNotificationHandler(LoggingMessageNotificationSchema, async notification => {\n await this.notificationHandlers.onLogMessage?.(notification.params);\n });\n }\n\n await this.client.connect(this.transport);\n }\n\n async setLoggingLevel(level: LoggingLevel, options?: UpstreamCallOptions): Promise<void> {\n const client = this.requireClient();\n await client.setLoggingLevel(level, options);\n }\n\n async listPrompts(options?: UpstreamCallOptions): Promise<Prompt[]> {\n const client = this.requireClient();\n const result = await client.listPrompts(undefined, options);\n return result.prompts;\n }\n\n async getPrompt(\n name: string,\n args?: Record<string, string>,\n options?: UpstreamCallOptions,\n ): Promise<GetPromptResult> {\n const client = this.requireClient();\n const params: { name: string; arguments?: Record<string, string> } = { name };\n if (args !== undefined) {\n params.arguments = args;\n }\n return client.getPrompt(params, options);\n }\n\n async complete(\n params: CompleteRequest[\"params\"],\n options?: UpstreamCallOptions,\n ): Promise<CompleteResult> {\n const client = this.requireClient();\n return client.complete(params, options);\n }\n\n /**\n * Returns the capabilities advertised by the upstream server during initialize.\n * Returns `undefined` if the client is not connected, or if the SDK has not yet\n * recorded the server's capabilities (e.g. during a partially-completed handshake).\n */\n getCapabilities(): ServerCapabilities | undefined {\n return this.client?.getServerCapabilities();\n }\n\n async listTools(options?: UpstreamCallOptions): Promise<UpstreamTool[]> {\n const client = this.requireClient();\n const result = await client.listTools(undefined, options);\n\n return result.tools.map(tool => {\n const upstreamTool: UpstreamTool = {\n name: tool.name,\n description: tool.description ?? \"\",\n inputSchema: tool.inputSchema,\n };\n\n if (tool.outputSchema !== undefined) {\n upstreamTool.outputSchema = tool.outputSchema;\n }\n\n if (tool.annotations !== undefined) {\n upstreamTool.annotations = {\n title: tool.annotations.title,\n readOnlyHint: tool.annotations.readOnlyHint,\n destructiveHint: tool.annotations.destructiveHint,\n idempotentHint: tool.annotations.idempotentHint,\n openWorldHint: tool.annotations.openWorldHint,\n };\n }\n\n return upstreamTool;\n });\n }\n\n async callTool(\n name: string,\n input: Record<string, unknown>,\n options?: UpstreamCallOptions,\n ): Promise<CallToolResult> {\n const client = this.requireClient();\n const result = await client.callTool({ name, arguments: input }, undefined, options);\n return result as CallToolResult;\n }\n\n async listResources(options?: UpstreamCallOptions): Promise<Resource[]> {\n const client = this.requireClient();\n const result = await client.listResources(undefined, options);\n return result.resources;\n }\n\n async listResourceTemplates(options?: UpstreamCallOptions): Promise<ResourceTemplate[]> {\n const client = this.requireClient();\n const result = await client.listResourceTemplates(undefined, options);\n return result.resourceTemplates;\n }\n\n async readResource(uri: string, options?: UpstreamCallOptions): Promise<ReadResourceResult> {\n const client = this.requireClient();\n return client.readResource({ uri }, options);\n }\n\n async subscribeResource(uri: string, options?: UpstreamCallOptions): Promise<void> {\n const client = this.requireClient();\n await client.subscribeResource({ uri }, options);\n }\n\n async unsubscribeResource(uri: string, options?: UpstreamCallOptions): Promise<void> {\n const client = this.requireClient();\n await client.unsubscribeResource({ uri }, options);\n }\n\n async disconnect(): Promise<void> {\n if (this.client === null) {\n return;\n }\n\n await this.client.close();\n this.client = null;\n }\n\n /**\n * Sends `notifications/roots/list_changed` to the upstream, letting it know that\n * the host's set of filesystem roots has changed.\n */\n async sendRootsListChanged(): Promise<void> {\n const client = this.requireClient();\n await client.sendRootsListChanged();\n }\n\n private registerServerRequestHandlers(client: Client): void {\n if (this.serverRequestHandlers.onCreateMessage !== undefined) {\n client.setRequestHandler(\n CreateMessageRequestSchema,\n async (request, extra): Promise<CreateMessageResult> => {\n return this.serverRequestHandlers.onCreateMessage!(request.params, {\n signal: extra.signal,\n });\n },\n );\n }\n if (this.serverRequestHandlers.onElicitInput !== undefined) {\n client.setRequestHandler(\n ElicitRequestSchema,\n async (request, extra): Promise<ElicitResult> => {\n return this.serverRequestHandlers.onElicitInput!(request.params, {\n signal: extra.signal,\n });\n },\n );\n }\n if (this.serverRequestHandlers.onListRoots !== undefined) {\n client.setRequestHandler(\n ListRootsRequestSchema,\n async (request, extra): Promise<ListRootsResult> => {\n return this.serverRequestHandlers.onListRoots!(request.params, {\n signal: extra.signal,\n });\n },\n );\n }\n }\n\n private requireClient(): Client {\n if (this.client === null) {\n throw new Error(\"Client is not connected. Call connect() first.\");\n }\n return this.client;\n }\n}\n","import type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\nimport {\n UpstreamClient,\n type UpstreamNotificationHandlers,\n type UpstreamServerRequestHandlers,\n} from \"./upstream-client.js\";\n\n/**\n * Per-upstream configuration handed to {@link UpstreamRegistry.connectAll}. The registry\n * is intentionally oblivious to what the notification and server-request handlers do —\n * the caller (typically the Orchestrator) owns that logic and supplies pre-built\n * handlers that close over its own state.\n */\nexport type UpstreamConfig = {\n transport: Transport;\n onTransportError?: (error: Error) => void;\n notifications?: UpstreamNotificationHandlers;\n serverRequests?: UpstreamServerRequestHandlers;\n};\n\n/**\n * Owns the lifecycle of every connected upstream MCP. Responsibilities are narrow:\n * spin clients up, expose them by name (or as the unique sole client in single-MCP\n * mode), and tear them all down on shutdown. Catalog building, routing, notification\n * translation, and capability aggregation are deliberately not in scope here — the\n * Orchestrator composes those concerns around this registry.\n *\n * Connection is all-or-nothing: if any client fails to connect during\n * {@link connectAll}, every already-connected client is disconnected before the\n * original error is re-thrown.\n */\nexport class UpstreamRegistry {\n private readonly clients: Map<string, UpstreamClient> = new Map();\n\n async connectAll(entries: ReadonlyArray<readonly [string, UpstreamConfig]>): Promise<void> {\n try {\n for (const [mcpName, config] of entries) {\n const client = new UpstreamClient({\n name: mcpName,\n transport: config.transport,\n onTransportError: config.onTransportError,\n notifications: config.notifications,\n serverRequests: config.serverRequests,\n });\n await client.connect();\n this.clients.set(mcpName, client);\n }\n } catch (error) {\n await this.disconnectAll();\n throw error;\n }\n }\n\n get(mcpName: string): UpstreamClient | undefined {\n return this.clients.get(mcpName);\n }\n\n /**\n * Returns the sole connected client. Used by single-MCP (`--`) mode where the\n * Orchestrator guarantees there is exactly one upstream. Returns undefined when\n * zero or more than one client is connected.\n */\n sole(): UpstreamClient | undefined {\n if (this.clients.size !== 1) return undefined;\n return this.clients.values().next().value;\n }\n\n names(): readonly string[] {\n return [...this.clients.keys()];\n }\n\n entries(): IterableIterator<[string, UpstreamClient]> {\n return this.clients.entries();\n }\n\n size(): number {\n return this.clients.size;\n }\n\n async disconnectAll(): Promise<void> {\n const disconnections = [...this.clients.values()].map(client => client.disconnect());\n await Promise.all(disconnections);\n this.clients.clear();\n }\n}\n","import process from \"node:process\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport {\n CallToolRequestSchema,\n type CallToolResult,\n CompleteRequestSchema,\n type CompleteRequest,\n type CompleteResult,\n type CreateMessageRequest,\n type CreateMessageResult,\n type ElicitRequest,\n type ElicitResult,\n GetPromptRequestSchema,\n type GetPromptResult,\n ListPromptsRequestSchema,\n type ListPromptsResult,\n ListResourcesRequestSchema,\n type ListResourcesResult,\n ListResourceTemplatesRequestSchema,\n type ListResourceTemplatesResult,\n type ListRootsRequest,\n type ListRootsResult,\n ListToolsRequestSchema,\n type LoggingLevel,\n type LoggingMessageNotification,\n type Prompt,\n ReadResourceRequestSchema,\n type ReadResourceResult,\n type Resource,\n type ResourceTemplate,\n RootsListChangedNotificationSchema,\n type ServerCapabilities,\n SetLevelRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport type { ToolCatalog } from \"./tool-catalog.js\";\n\n/**\n * Per-call options forwarded by the proxy server's request handlers to the orchestrator\n * so the host's `AbortSignal` can propagate through to the upstream call.\n */\nexport type ProxyCallOptions = {\n signal?: AbortSignal;\n};\n\nexport type ToolCaller = (\n name: string,\n input: Record<string, unknown>,\n options?: ProxyCallOptions,\n) => Promise<CallToolResult>;\n\nexport type ResourceCallbacks = {\n listResources: () => Resource[];\n listResourceTemplates: () => ResourceTemplate[];\n readResource: (uri: string, options?: ProxyCallOptions) => Promise<ReadResourceResult>;\n subscribeResource: (uri: string, options?: ProxyCallOptions) => Promise<void>;\n unsubscribeResource: (uri: string, options?: ProxyCallOptions) => Promise<void>;\n};\n\nexport type PromptCallbacks = {\n listPrompts: () => Prompt[];\n getPrompt: (\n name: string,\n args?: Record<string, string>,\n options?: ProxyCallOptions,\n ) => Promise<GetPromptResult>;\n};\n\nexport type CompletionCallback = (\n params: CompleteRequest[\"params\"],\n options?: ProxyCallOptions,\n) => Promise<CompleteResult>;\n\nexport type LoggingSetLevelCallback = (\n level: LoggingLevel,\n options?: ProxyCallOptions,\n) => Promise<void>;\n\nexport type LogMessageParams = LoggingMessageNotification[\"params\"];\n\ntype ProxyServerConfig = {\n /**\n * Function returning the current tool catalog. A function (rather than a static value)\n * lets the proxy regenerate `discover_tool`'s description on the fly when an upstream\n * emits `notifications/tools/list_changed`.\n */\n catalog: () => ToolCatalog;\n callTool: ToolCaller;\n /**\n * Aggregated capabilities to advertise to the host during `initialize`. Built by\n * `aggregateCapabilities()` from the union of all upstream capabilities. The proxy\n * always advertises `tools` regardless of upstream support.\n */\n capabilities: ServerCapabilities;\n /**\n * Resource access callbacks. Required when `capabilities.resources` is advertised;\n * otherwise the resource request handlers are not registered.\n */\n resources?: ResourceCallbacks;\n /**\n * Prompt access callbacks. Required when `capabilities.prompts` is advertised;\n * otherwise the prompt request handlers are not registered.\n */\n prompts?: PromptCallbacks;\n /**\n * Completion routing callback. Required when `capabilities.completions` is advertised;\n * otherwise the completion request handler is not registered.\n */\n complete?: CompletionCallback;\n /**\n * Logging set-level callback. Required when `capabilities.logging` is advertised;\n * otherwise the `logging/setLevel` request handler is not registered.\n */\n setLoggingLevel?: LoggingSetLevelCallback;\n /**\n * Invoked when the host emits `notifications/roots/list_changed`. The proxy will\n * call this so the orchestrator can broadcast the change to all upstreams that\n * declared the `roots` client capability to us.\n */\n onRootsListChanged?: () => void | Promise<void>;\n};\n\nconst DISCOVER_TOOL_NAME = \"discover_tool\";\nconst USE_TOOL_NAME = \"use_tool\";\n\nconst USE_TOOL_DESCRIPTION =\n \"Use a tool that was previously discovered with the discover_tool tool.\";\n\nconst DISCOVER_TOOL_INPUT_SCHEMA = {\n type: \"object\" as const,\n properties: {\n tool_name: { type: \"string\" as const },\n },\n required: [\"tool_name\"],\n};\n\nconst USE_TOOL_INPUT_SCHEMA = {\n type: \"object\" as const,\n properties: {\n tool_name: { type: \"string\" as const },\n tool_input: { type: \"object\" as const, additionalProperties: true, default: {} },\n },\n required: [\"tool_name\"],\n};\n\nconst DiscoverToolArgsSchema = z.object({ tool_name: z.string() });\nconst UseToolArgsSchema = z.object({\n tool_name: z.string(),\n tool_input: z.record(z.string(), z.unknown()).default({}),\n});\n\nexport class ProxyServer {\n private readonly catalog: () => ToolCatalog;\n private readonly callTool: ToolCaller;\n private readonly capabilities: ServerCapabilities;\n private readonly resources: ResourceCallbacks | undefined;\n private readonly prompts: PromptCallbacks | undefined;\n private readonly complete: CompletionCallback | undefined;\n private readonly setLoggingLevelCallback: LoggingSetLevelCallback | undefined;\n private readonly onRootsListChangedCallback: (() => void | Promise<void>) | undefined;\n private sdkServer: Server | null = null;\n\n constructor({\n catalog,\n callTool,\n capabilities,\n resources,\n prompts,\n complete,\n setLoggingLevel,\n onRootsListChanged,\n }: ProxyServerConfig) {\n this.catalog = catalog;\n this.callTool = callTool;\n this.capabilities = capabilities;\n this.resources = resources;\n this.prompts = prompts;\n this.complete = complete;\n this.setLoggingLevelCallback = setLoggingLevel;\n this.onRootsListChangedCallback = onRootsListChanged;\n }\n\n buildServer(): Server {\n const server = new Server(\n {\n name: \"dynamic-discovery-mcp\",\n version: packageJson.version,\n },\n {\n capabilities: this.capabilities,\n },\n );\n\n this.registerToolHandlers(server);\n if (this.capabilities.resources !== undefined && this.resources !== undefined) {\n this.registerResourceHandlers(server, this.resources);\n }\n if (this.capabilities.prompts !== undefined && this.prompts !== undefined) {\n this.registerPromptHandlers(server, this.prompts);\n }\n if (this.capabilities.completions !== undefined && this.complete !== undefined) {\n this.registerCompletionHandler(server, this.complete);\n }\n if (this.capabilities.logging !== undefined && this.setLoggingLevelCallback !== undefined) {\n this.registerLoggingHandler(server, this.setLoggingLevelCallback);\n }\n if (this.onRootsListChangedCallback !== undefined) {\n const callback = this.onRootsListChangedCallback;\n server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {\n await callback();\n });\n }\n\n this.sdkServer = server;\n return server;\n }\n\n /**\n * Forwards an upstream-initiated `sampling/createMessage` request to the host. The\n * upstream's abort signal is threaded through so cancellation by the upstream\n * propagates to the host.\n */\n async forwardCreateMessage(\n params: CreateMessageRequest[\"params\"],\n options: { signal: AbortSignal },\n ): Promise<CreateMessageResult> {\n const server = this.requireSdkServer();\n return server.createMessage(params, options);\n }\n\n /**\n * Forwards an upstream-initiated `elicitation/create` request to the host.\n */\n async forwardElicitInput(\n params: ElicitRequest[\"params\"],\n options: { signal: AbortSignal },\n ): Promise<ElicitResult> {\n const server = this.requireSdkServer();\n return server.elicitInput(params, options);\n }\n\n /**\n * Forwards an upstream-initiated `roots/list` request to the host.\n */\n async forwardListRoots(\n params: ListRootsRequest[\"params\"],\n options: { signal: AbortSignal },\n ): Promise<ListRootsResult> {\n const server = this.requireSdkServer();\n return server.listRoots(params, options);\n }\n\n private requireSdkServer(): Server {\n if (this.sdkServer === null) {\n throw new Error(\"ProxyServer is not built. Call buildServer() before forwarding requests.\");\n }\n return this.sdkServer;\n }\n\n async start(): Promise<void> {\n const server = this.buildServer();\n const transport = new StdioServerTransport();\n process.stderr.write(\"Starting dynamic-discovery-mcp server over stdio\\n\");\n await server.connect(transport);\n }\n\n /**\n * Notifies the host that the discover_tool description has changed because an upstream\n * emitted `notifications/tools/list_changed`. The host should re-fetch the tools list\n * to pick up the regenerated catalog. Silently no-ops if `buildServer()` has not been\n * called yet.\n */\n async sendToolListChanged(): Promise<void> {\n if (this.sdkServer !== null) {\n await this.sdkServer.sendToolListChanged();\n }\n }\n\n /**\n * Notifies the host that the proxy's aggregated resource list has changed. Silently\n * no-ops if `buildServer()` has not been called yet. Errors propagate.\n */\n async sendResourceListChanged(): Promise<void> {\n if (this.sdkServer !== null) {\n await this.sdkServer.sendResourceListChanged();\n }\n }\n\n /**\n * Notifies the host that a specific subscribed resource has changed. Silently no-ops\n * if `buildServer()` has not been called yet.\n */\n async sendResourceUpdated(params: { uri: string }): Promise<void> {\n if (this.sdkServer !== null) {\n await this.sdkServer.sendResourceUpdated(params);\n }\n }\n\n /**\n * Notifies the host that the proxy's aggregated prompt list has changed. Silently\n * no-ops if `buildServer()` has not been called yet.\n */\n async sendPromptListChanged(): Promise<void> {\n if (this.sdkServer !== null) {\n await this.sdkServer.sendPromptListChanged();\n }\n }\n\n private registerToolHandlers(server: Server): void {\n server.setRequestHandler(ListToolsRequestSchema, async () => ({\n tools: [\n {\n name: DISCOVER_TOOL_NAME,\n description: this.catalog().discoverToolDescription,\n inputSchema: DISCOVER_TOOL_INPUT_SCHEMA,\n },\n {\n name: USE_TOOL_NAME,\n description: USE_TOOL_DESCRIPTION,\n inputSchema: USE_TOOL_INPUT_SCHEMA,\n },\n ],\n }));\n\n server.setRequestHandler(\n CallToolRequestSchema,\n async (request, extra): Promise<CallToolResult> => {\n const { name, arguments: rawArgs } = request.params;\n const catalog = this.catalog();\n\n if (name === DISCOVER_TOOL_NAME) {\n const args = DiscoverToolArgsSchema.parse(rawArgs ?? {});\n return {\n content: [{ type: \"text\", text: catalog.getToolDetails(args.tool_name) }],\n };\n }\n\n if (name === USE_TOOL_NAME) {\n const args = UseToolArgsSchema.parse(rawArgs ?? {});\n if (!catalog.tools.has(args.tool_name)) {\n return {\n content: [{ type: \"text\", text: catalog.getToolDetails(args.tool_name) }],\n };\n }\n return await this.callTool(args.tool_name, args.tool_input, { signal: extra.signal });\n }\n\n return {\n isError: true,\n content: [{ type: \"text\", text: `Unknown tool: \"${name}\"` }],\n };\n },\n );\n }\n\n private registerResourceHandlers(server: Server, callbacks: ResourceCallbacks): void {\n server.setRequestHandler(\n ListResourcesRequestSchema,\n async (): Promise<ListResourcesResult> => ({\n resources: callbacks.listResources(),\n }),\n );\n\n server.setRequestHandler(\n ListResourceTemplatesRequestSchema,\n async (): Promise<ListResourceTemplatesResult> => ({\n resourceTemplates: callbacks.listResourceTemplates(),\n }),\n );\n\n server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request, extra): Promise<ReadResourceResult> => {\n return callbacks.readResource(request.params.uri, { signal: extra.signal });\n },\n );\n\n server.setRequestHandler(SubscribeRequestSchema, async (request, extra) => {\n await callbacks.subscribeResource(request.params.uri, { signal: extra.signal });\n return {};\n });\n\n server.setRequestHandler(UnsubscribeRequestSchema, async (request, extra) => {\n await callbacks.unsubscribeResource(request.params.uri, { signal: extra.signal });\n return {};\n });\n }\n\n private registerPromptHandlers(server: Server, callbacks: PromptCallbacks): void {\n server.setRequestHandler(\n ListPromptsRequestSchema,\n async (): Promise<ListPromptsResult> => ({\n prompts: callbacks.listPrompts(),\n }),\n );\n\n server.setRequestHandler(\n GetPromptRequestSchema,\n async (request, extra): Promise<GetPromptResult> => {\n return callbacks.getPrompt(request.params.name, request.params.arguments, {\n signal: extra.signal,\n });\n },\n );\n }\n\n private registerCompletionHandler(server: Server, callback: CompletionCallback): void {\n server.setRequestHandler(\n CompleteRequestSchema,\n async (request, extra): Promise<CompleteResult> => {\n return callback(request.params, { signal: extra.signal });\n },\n );\n }\n\n private registerLoggingHandler(server: Server, callback: LoggingSetLevelCallback): void {\n server.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {\n await callback(request.params.level, { signal: extra.signal });\n return {};\n });\n }\n\n /**\n * Forwards a log message from an upstream MCP to the host. Silently no-ops if\n * `buildServer()` has not been called yet.\n */\n async sendLoggingMessage(params: LogMessageParams): Promise<void> {\n if (this.sdkServer !== null) {\n await this.sdkServer.sendLoggingMessage(params);\n }\n }\n}\n","import { StdioClientTransport } from \"@modelcontextprotocol/sdk/client/stdio.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport type { Transport } from \"@modelcontextprotocol/sdk/shared/transport.js\";\n\ninterface StdioTransportConfig {\n transport: \"stdio\";\n command: string;\n args?: string[];\n env?: Record<string, string>;\n}\n\ninterface StreamableHttpTransportConfig {\n transport: \"streamable-http\";\n url: string;\n headers?: Record<string, string>;\n}\n\ninterface SseTransportConfig {\n transport: \"sse\";\n url: string;\n headers?: Record<string, string>;\n}\n\nexport type McpTransportConfig =\n | StdioTransportConfig\n | StreamableHttpTransportConfig\n | SseTransportConfig;\n\nexport function createTransport(config: McpTransportConfig): Transport {\n switch (config.transport) {\n case \"stdio\":\n return new StdioClientTransport({\n command: config.command,\n args: config.args,\n env: config.env,\n });\n\n case \"streamable-http\":\n return new StreamableHTTPClientTransport(\n new URL(config.url),\n config.headers ? { requestInit: { headers: config.headers } } : undefined,\n );\n\n case \"sse\":\n return new SSEClientTransport(\n new URL(config.url),\n config.headers ? { requestInit: { headers: config.headers } } : undefined,\n );\n\n default: {\n const _exhaustive: never = config;\n return _exhaustive;\n }\n }\n}\n","import { cli } from \"./cli.js\";\nimport process from \"node:process\";\n\nasync function main() {\n cli.parse(process.argv);\n}\n\nmain();\n"],"mappings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process","import_node_process","import_stdio","import_node_fs","import_node_path","import_node_process","process","dotenv","process","parseYaml","import_zod","import_node_process","mcpName","mcpName","mcpName","mcpName","import_node_process","process","mcpName","mcpName","process","import_node_process","import_types","import_zod","process","import_stdio","mcpName","process","chalk","figlet","process","import_node_process","process"]}
|