diff --git a/.github/workflows/cli_tests.yml b/.github/workflows/cli_tests.yml index 106d98f13..9fe2f710f 100644 --- a/.github/workflows/cli_tests.yml +++ b/.github/workflows/cli_tests.yml @@ -15,10 +15,10 @@ jobs: run: working-directory: ./cli steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v4 - name: Set up Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v4 with: node-version-file: package.json cache: npm @@ -28,8 +28,13 @@ jobs: cd .. npm ci --ignore-scripts + - name: Build shared package + working-directory: . + run: npm run build-shared + - name: Build CLI - run: npm run build + working-directory: . + run: npm run build-cli - name: Run tests run: npm test diff --git a/.gitignore b/.gitignore index 230d72d41..c05a512e6 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,12 @@ server/build client/dist client/tsconfig.app.tsbuildinfo client/tsconfig.node.tsbuildinfo +web/tsconfig.app.tsbuildinfo +web/tsconfig.node.tsbuildinfo +web/tsconfig.jest.tsbuildinfo cli/build +tui/build +shared/build test-output tool-test-output metadata-test-output @@ -19,3 +24,10 @@ client/test-results/ client/e2e/test-results/ mcp.json .claude/settings.local.json + +# Environment variables +.env +.env.local +.env.development +.env.test +.env.production diff --git a/cli/__tests__/cli.test.ts b/cli/__tests__/cli.test.ts index b263f618c..32f4779f7 100644 --- a/cli/__tests__/cli.test.ts +++ b/cli/__tests__/cli.test.ts @@ -12,12 +12,12 @@ import { createInvalidConfig, deleteConfigFile, } from "./helpers/fixtures.js"; -import { getTestMcpServerCommand } from "./helpers/test-server-stdio.js"; -import { createTestServerHttp } from "./helpers/test-server-http.js"; +import { getTestMcpServerCommand } from "../../shared/test/test-server-stdio.js"; +import { createTestServerHttp } from "../../shared/test/test-server-http.js"; import { createEchoTool, createTestServerInfo, -} from "./helpers/test-fixtures.js"; +} from "../../shared/test/test-server-fixtures.js"; describe("CLI Tests", () => { describe("Basic CLI Mode", () => { @@ -59,6 +59,17 @@ describe("CLI Tests", () => { expectCliFailure(result); }); + + // Temporary: remove .skip to verify that expectCliSuccess shows CLI stdout/stderr when the CLI fails + it.skip("TEMP: expect success when CLI fails (validates error output in assertion)", async () => { + const result = await runCli([ + NO_SERVER_SENTINEL, + "--cli", + "--method", + "tools/list", + ]); + expectCliSuccess(result); // will fail; failure message should include result.stdout and result.stderr + }); }); describe("Environment Variables", () => { @@ -370,11 +381,9 @@ describe("CLI Tests", () => { }); try { - const port = await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + const port = await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "logging/setLevel", @@ -741,11 +750,9 @@ describe("CLI Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -768,11 +775,9 @@ describe("CLI Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--transport", "http", "--cli", @@ -797,11 +802,9 @@ describe("CLI Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--transport", "http", "--cli", @@ -826,11 +829,9 @@ describe("CLI Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--transport", "sse", "--cli", diff --git a/cli/__tests__/headers.test.ts b/cli/__tests__/headers.test.ts index 6adf1effe..7f7d9b496 100644 --- a/cli/__tests__/headers.test.ts +++ b/cli/__tests__/headers.test.ts @@ -5,11 +5,11 @@ import { expectOutputContains, expectCliSuccess, } from "./helpers/assertions.js"; -import { createTestServerHttp } from "./helpers/test-server-http.js"; +import { createTestServerHttp } from "../../shared/test/test-server-http.js"; import { createEchoTool, createTestServerInfo, -} from "./helpers/test-fixtures.js"; +} from "../../shared/test/test-server-fixtures.js"; describe("Header Parsing and Validation", () => { describe("Valid Headers", () => { @@ -20,11 +20,9 @@ describe("Header Parsing and Validation", () => { }); try { - const port = await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + const port = await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -60,11 +58,9 @@ describe("Header Parsing and Validation", () => { }); try { - const port = await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + const port = await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -95,11 +91,9 @@ describe("Header Parsing and Validation", () => { }); try { - const port = await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + const port = await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -129,11 +123,9 @@ describe("Header Parsing and Validation", () => { }); try { - const port = await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + const port = await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", diff --git a/cli/__tests__/helpers/fixtures.ts b/cli/__tests__/helpers/fixtures.ts index c7f10fc7a..2ff2f48ec 100644 --- a/cli/__tests__/helpers/fixtures.ts +++ b/cli/__tests__/helpers/fixtures.ts @@ -2,7 +2,7 @@ import * as fs from "fs"; import * as path from "path"; import * as os from "os"; import * as crypto from "crypto"; -import { getTestMcpServerCommand } from "./test-server-stdio.js"; +import { getTestMcpServerCommand } from "../../../shared/test/test-server-stdio.js"; /** * Sentinel value for tests that don't need a real server diff --git a/cli/__tests__/metadata.test.ts b/cli/__tests__/metadata.test.ts index 93d5f8ca6..d37236685 100644 --- a/cli/__tests__/metadata.test.ts +++ b/cli/__tests__/metadata.test.ts @@ -5,12 +5,12 @@ import { expectCliFailure, expectValidJson, } from "./helpers/assertions.js"; -import { createTestServerHttp } from "./helpers/test-server-http.js"; +import { createTestServerHttp } from "../../shared/test/test-server-http.js"; import { createEchoTool, createAddTool, createTestServerInfo, -} from "./helpers/test-fixtures.js"; +} from "../../shared/test/test-server-fixtures.js"; import { NO_SERVER_SENTINEL } from "./helpers/fixtures.js"; describe("Metadata Tests", () => { @@ -22,11 +22,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -65,11 +63,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "resources/list", @@ -104,16 +100,15 @@ describe("Metadata Tests", () => { { name: "test-prompt", description: "A test prompt", + promptString: "test prompt", }, ], }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "prompts/list", @@ -154,11 +149,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "resources/read", @@ -193,16 +186,15 @@ describe("Metadata Tests", () => { { name: "test-prompt", description: "A test prompt", + promptString: "test prompt", }, ], }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "prompts/get", @@ -239,11 +231,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -280,11 +270,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -324,11 +312,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -371,11 +357,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -412,11 +396,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -453,11 +435,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -496,11 +476,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -533,11 +511,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -612,11 +588,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -661,11 +635,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "resources/list", @@ -698,16 +670,15 @@ describe("Metadata Tests", () => { { name: "test-prompt", description: "A test prompt", + promptString: "test prompt", }, ], }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "prompts/get", @@ -744,11 +715,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -791,11 +760,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/list", @@ -830,11 +797,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -884,11 +849,9 @@ describe("Metadata Tests", () => { }); try { - await server.start("http"); - const serverUrl = `${server.getUrl()}/mcp`; - + await server.start(); const result = await runCli([ - serverUrl, + server.url, "--cli", "--method", "tools/call", @@ -930,4 +893,42 @@ describe("Metadata Tests", () => { } }); }); + + describe("SSE Transport Tests", () => { + it("should work with tools/list using SSE transport", async () => { + const server = createTestServerHttp({ + serverType: "sse", + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + try { + await server.start(); + const result = await runCli([ + server.url, + "--cli", + "--method", + "tools/list", + "--metadata", + "client=test-client", + "--transport", + "sse", + ]); + + expectCliSuccess(result); + const json = expectValidJson(result); + expect(json).toHaveProperty("tools"); + + // Validate metadata was sent + const recordedRequests = server.getRecordedRequests(); + const toolsListRequest = recordedRequests.find( + (r) => r.method === "tools/list", + ); + expect(toolsListRequest).toBeDefined(); + expect(toolsListRequest?.metadata).toEqual({ client: "test-client" }); + } finally { + await server.stop(); + } + }); + }); }); diff --git a/cli/__tests__/tools.test.ts b/cli/__tests__/tools.test.ts index e83b5ea0d..461a77026 100644 --- a/cli/__tests__/tools.test.ts +++ b/cli/__tests__/tools.test.ts @@ -6,7 +6,7 @@ import { expectValidJson, expectJsonError, } from "./helpers/assertions.js"; -import { getTestMcpServerCommand } from "./helpers/test-server-stdio.js"; +import { getTestMcpServerCommand } from "../../shared/test/test-server-stdio.js"; describe("Tool Tests", () => { describe("Tool Discovery", () => { diff --git a/cli/package.json b/cli/package.json index 94a59d848..5ac1bc0a2 100644 --- a/cli/package.json +++ b/cli/package.json @@ -2,8 +2,8 @@ "name": "@modelcontextprotocol/inspector-cli", "version": "0.20.0", "description": "CLI for the Model Context Protocol inspector", - "license": "SEE LICENSE IN LICENSE", - "author": "Model Context Protocol a Series of LF Projects, LLC.", + "license": "MIT", + "author": "Anthropic, PBC (https://anthropic.com)", "homepage": "https://modelcontextprotocol.io", "bugs": "https://github.com/modelcontextprotocol/inspector/issues", "main": "build/cli.js", @@ -30,9 +30,10 @@ "vitest": "^4.0.17" }, "dependencies": { + "@modelcontextprotocol/inspector-shared": "*", "@modelcontextprotocol/sdk": "^1.25.2", "commander": "^13.1.0", - "express": "^5.2.1", + "express": "^5.1.0", "spawn-rx": "^5.1.2" } } diff --git a/cli/src/cli.ts b/cli/src/cli.ts index f4187e02d..e4bca5ec4 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -9,21 +9,28 @@ import { fileURLToPath } from "url"; const __dirname = dirname(fileURLToPath(import.meta.url)); +// This represents the parsed arguments produced by parseArgs() +// type Args = { command: string; args: string[]; envArgs: Record; cli: boolean; + dev?: boolean; transport?: "stdio" | "sse" | "streamable-http"; serverUrl?: string; headers?: Record; }; +// This is only to provide typed access to the parsed program options +// This could just be defined locally in parseArgs() since that's the only place it is used +// type CliOptions = { e?: Record; config?: string; server?: string; cli?: boolean; + dev?: boolean; transport?: string; serverUrl?: string; header?: Record; @@ -116,6 +123,64 @@ async function runWebClient(args: Args): Promise { } } +async function runWeb(args: Args): Promise { + // Path to the web entry point + const inspectorWebPath = resolve( + __dirname, + "../../", + "web", + "bin", + "start.js", + ); + + const abort = new AbortController(); + let cancelled: boolean = false; + process.on("SIGINT", () => { + cancelled = true; + abort.abort(); + }); + + // Build arguments to pass to start.js + const startArgs: string[] = []; + + if (args.dev) { + startArgs.push("--dev"); + } + + // Pass environment variables + for (const [key, value] of Object.entries(args.envArgs)) { + startArgs.push("-e", `${key}=${value}`); + } + + // Pass transport type if specified + if (args.transport) { + startArgs.push("--transport", args.transport); + } + + // Pass server URL if specified + if (args.serverUrl) { + startArgs.push("--server-url", args.serverUrl); + } + + // Pass command and args (using -- to separate them) + if (args.command) { + startArgs.push("--", args.command, ...args.args); + } + + try { + await spawnPromise("node", [inspectorWebPath, ...startArgs], { + signal: abort.signal, + echoOutput: true, + // pipe the stdout through here, prevents issues with buffering and + // dropping the end of console.out after 8192 chars due to node + // closing the stdout pipe before the output has finished flushing + stdio: "inherit", + }); + } catch (e) { + if (!cancelled || process.env.DEBUG) throw e; + } +} + async function runCli(args: Args): Promise { const projectRoot = resolve(__dirname, ".."); const cliPath = resolve(projectRoot, "build", "index.js"); @@ -167,6 +232,36 @@ async function runCli(args: Args): Promise { } } +async function runTui(tuiArgs: string[]): Promise { + const projectRoot = resolve(__dirname, "../.."); + const tuiPath = resolve(projectRoot, "tui", "build", "tui.js"); + + const abort = new AbortController(); + + let cancelled = false; + + process.on("SIGINT", () => { + cancelled = true; + abort.abort(); + }); + + try { + // Remove --tui flag and pass everything else directly to TUI + const filteredArgs = tuiArgs.filter((arg) => arg !== "--tui"); + + await spawnPromise("node", [tuiPath, ...filteredArgs], { + env: process.env, + signal: abort.signal, + echoOutput: true, + stdio: "inherit", + }); + } catch (e) { + if (!cancelled || process.env.DEBUG) { + throw e; + } + } +} + function loadConfigFile(configPath: string, serverName: string): ServerConfig { try { const resolvedConfigPath = path.isAbsolute(configPath) @@ -267,6 +362,8 @@ function parseArgs(): Args { .option("--config ", "config file path") .option("--server ", "server name from config file") .option("--cli", "enable CLI mode") + .option("--dev", "run web in dev mode (Vite)") + .option("--tui", "enable TUI mode") .option("--transport ", "transport type (stdio, sse, http)") .option("--server-url ", "server URL for SSE/HTTP transport") .option( @@ -326,6 +423,7 @@ function parseArgs(): Args { args: [...(config.args || []), ...finalArgs], envArgs: { ...(config.env || {}), ...(options.e || {}) }, cli: options.cli || false, + dev: options.dev || false, transport: "stdio", headers: options.header, }; @@ -335,6 +433,7 @@ function parseArgs(): Args { args: finalArgs, envArgs: options.e || {}, cli: options.cli || false, + dev: options.dev || false, transport: config.type, serverUrl: config.url, headers: options.header, @@ -346,6 +445,7 @@ function parseArgs(): Args { args: [...((config as any).args || []), ...finalArgs], envArgs: { ...((config as any).env || {}), ...(options.e || {}) }, cli: options.cli || false, + dev: options.dev || false, transport: "stdio", headers: options.header, }; @@ -367,6 +467,7 @@ function parseArgs(): Args { args, envArgs: options.e || {}, cli: options.cli || false, + dev: options.dev || false, transport: transport as "stdio" | "sse" | "streamable-http" | undefined, serverUrl: options.serverUrl, headers: options.header, @@ -379,10 +480,29 @@ async function main(): Promise { }); try { + // For now we just pass the raw args to TUI (we'll integrate config later) + // The main issue is that Inspector only supports a single server and the TUI supports a set + // + // Check for --tui in raw argv - if present, bypass all parsing + if (process.argv.includes("--tui")) { + await runTui(process.argv.slice(2)); + return; + } + + // Check for --web in raw argv - if present, use web app instead of client + const useWeb = process.argv.includes("--web"); + if (useWeb) { + // Remove --web from args before parsing + const filteredArgs = process.argv.filter((arg) => arg !== "--web"); + process.argv = filteredArgs; + } + const args = parseArgs(); if (args.cli) { await runCli(args); + } else if (useWeb) { + await runWeb(args); } else { await runWebClient(args); } diff --git a/cli/src/client/connection.ts b/cli/src/client/connection.ts deleted file mode 100644 index dcbe8e518..000000000 --- a/cli/src/client/connection.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { McpResponse } from "./types.js"; - -export const validLogLevels = [ - "trace", - "debug", - "info", - "warn", - "error", -] as const; - -export type LogLevel = (typeof validLogLevels)[number]; - -export async function connect( - client: Client, - transport: Transport, -): Promise { - try { - await client.connect(transport); - - if (client.getServerCapabilities()?.logging) { - // default logging level is undefined in the spec, but the user of the - // inspector most likely wants debug. - await client.setLoggingLevel("debug"); - } - } catch (error) { - throw new Error( - `Failed to connect to MCP server: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -export async function disconnect(transport: Transport): Promise { - try { - await transport.close(); - } catch (error) { - throw new Error( - `Failed to disconnect from MCP server: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -// Set logging level -export async function setLoggingLevel( - client: Client, - level: LogLevel, -): Promise { - try { - const response = await client.setLoggingLevel(level as any); - return response; - } catch (error) { - throw new Error( - `Failed to set logging level: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} diff --git a/cli/src/client/index.ts b/cli/src/client/index.ts deleted file mode 100644 index 095d716b2..000000000 --- a/cli/src/client/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Re-export everything from the client modules -export * from "./connection.js"; -export * from "./prompts.js"; -export * from "./resources.js"; -export * from "./tools.js"; -export * from "./types.js"; diff --git a/cli/src/client/prompts.ts b/cli/src/client/prompts.ts deleted file mode 100644 index e7a1cf2f2..000000000 --- a/cli/src/client/prompts.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { McpResponse } from "./types.js"; - -// JSON value type matching the client utils -type JsonValue = - | string - | number - | boolean - | null - | undefined - | JsonValue[] - | { [key: string]: JsonValue }; - -// List available prompts -export async function listPrompts( - client: Client, - metadata?: Record, -): Promise { - try { - const params = - metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; - const response = await client.listPrompts(params); - return response; - } catch (error) { - throw new Error( - `Failed to list prompts: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -// Get a prompt -export async function getPrompt( - client: Client, - name: string, - args?: Record, - metadata?: Record, -): Promise { - try { - // Convert all arguments to strings for prompt arguments - const stringArgs: Record = {}; - if (args) { - for (const [key, value] of Object.entries(args)) { - if (typeof value === "string") { - stringArgs[key] = value; - } else if (value === null || value === undefined) { - stringArgs[key] = String(value); - } else { - stringArgs[key] = JSON.stringify(value); - } - } - } - - const params: any = { - name, - arguments: stringArgs, - }; - - if (metadata && Object.keys(metadata).length > 0) { - params._meta = metadata; - } - - const response = await client.getPrompt(params); - - return response; - } catch (error) { - throw new Error( - `Failed to get prompt: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} diff --git a/cli/src/client/resources.ts b/cli/src/client/resources.ts deleted file mode 100644 index 3e44820ca..000000000 --- a/cli/src/client/resources.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { McpResponse } from "./types.js"; - -// List available resources -export async function listResources( - client: Client, - metadata?: Record, -): Promise { - try { - const params = - metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; - const response = await client.listResources(params); - return response; - } catch (error) { - throw new Error( - `Failed to list resources: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -// Read a resource -export async function readResource( - client: Client, - uri: string, - metadata?: Record, -): Promise { - try { - const params: any = { uri }; - if (metadata && Object.keys(metadata).length > 0) { - params._meta = metadata; - } - const response = await client.readResource(params); - return response; - } catch (error) { - throw new Error( - `Failed to read resource ${uri}: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -// List resource templates -export async function listResourceTemplates( - client: Client, - metadata?: Record, -): Promise { - try { - const params = - metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; - const response = await client.listResourceTemplates(params); - return response; - } catch (error) { - throw new Error( - `Failed to list resource templates: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} diff --git a/cli/src/client/tools.ts b/cli/src/client/tools.ts deleted file mode 100644 index 516814115..000000000 --- a/cli/src/client/tools.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { Tool } from "@modelcontextprotocol/sdk/types.js"; -import { McpResponse } from "./types.js"; - -// JSON value type matching the client utils -type JsonValue = - | string - | number - | boolean - | null - | undefined - | JsonValue[] - | { [key: string]: JsonValue }; - -type JsonSchemaType = { - type: "string" | "number" | "integer" | "boolean" | "array" | "object"; - description?: string; - properties?: Record; - items?: JsonSchemaType; -}; - -export async function listTools( - client: Client, - metadata?: Record, -): Promise { - try { - const params = - metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; - const response = await client.listTools(params); - return response; - } catch (error) { - throw new Error( - `Failed to list tools: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -function convertParameterValue( - value: string, - schema: JsonSchemaType, -): JsonValue { - if (!value) { - return value; - } - - if (schema.type === "number" || schema.type === "integer") { - return Number(value); - } - - if (schema.type === "boolean") { - return value.toLowerCase() === "true"; - } - - if (schema.type === "object" || schema.type === "array") { - try { - return JSON.parse(value) as JsonValue; - } catch (error) { - return value; - } - } - - return value; -} - -function convertParameters( - tool: Tool, - params: Record, -): Record { - const result: Record = {}; - const properties = tool.inputSchema.properties || {}; - - for (const [key, value] of Object.entries(params)) { - const paramSchema = properties[key] as JsonSchemaType | undefined; - - if (paramSchema) { - result[key] = convertParameterValue(value, paramSchema); - } else { - // If no schema is found for this parameter, keep it as string - result[key] = value; - } - } - - return result; -} - -export async function callTool( - client: Client, - name: string, - args: Record, - generalMetadata?: Record, - toolSpecificMetadata?: Record, -): Promise { - try { - const toolsResponse = await listTools(client, generalMetadata); - const tools = toolsResponse.tools as Tool[]; - const tool = tools.find((t) => t.name === name); - - let convertedArgs: Record = args; - - if (tool) { - // Convert parameters based on the tool's schema, but only for string values - // since we now accept pre-parsed values from the CLI - const stringArgs: Record = {}; - for (const [key, value] of Object.entries(args)) { - if (typeof value === "string") { - stringArgs[key] = value; - } - } - - if (Object.keys(stringArgs).length > 0) { - const convertedStringArgs = convertParameters(tool, stringArgs); - convertedArgs = { ...args, ...convertedStringArgs }; - } - } - - // Merge general metadata with tool-specific metadata - // Tool-specific metadata takes precedence over general metadata - let mergedMetadata: Record | undefined; - if (generalMetadata || toolSpecificMetadata) { - mergedMetadata = { - ...(generalMetadata || {}), - ...(toolSpecificMetadata || {}), - }; - } - - const response = await client.callTool({ - name: name, - arguments: convertedArgs, - _meta: - mergedMetadata && Object.keys(mergedMetadata).length > 0 - ? mergedMetadata - : undefined, - }); - return response; - } catch (error) { - throw new Error( - `Failed to call tool ${name}: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} diff --git a/cli/src/client/types.ts b/cli/src/client/types.ts deleted file mode 100644 index bbbe1bf4f..000000000 --- a/cli/src/client/types.ts +++ /dev/null @@ -1 +0,0 @@ -export type McpResponse = Record; diff --git a/cli/src/index.ts b/cli/src/index.ts index 45a71a052..98a82eaf9 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -1,36 +1,29 @@ #!/usr/bin/env node import * as fs from "fs"; -import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Command } from "commander"; -import { - callTool, - connect, - disconnect, - getPrompt, - listPrompts, - listResources, - listResourceTemplates, - listTools, - LogLevel, - McpResponse, - readResource, - setLoggingLevel, - validLogLevels, -} from "./client/index.js"; +// CLI helper functions moved to InspectorClient methods +type McpResponse = Record; import { handleError } from "./error-handler.js"; -import { createTransport, TransportOptions } from "./transport.js"; import { awaitableLog } from "./utils/awaitable-log.js"; +import type { + MCPServerConfig, + StdioServerConfig, + SseServerConfig, + StreamableHttpServerConfig, +} from "@modelcontextprotocol/inspector-shared/mcp/types.js"; +import { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { createTransportNode } from "@modelcontextprotocol/inspector-shared/mcp/node/index.js"; +import type { JsonValue } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { + LoggingLevelSchema, + type LoggingLevel, +} from "@modelcontextprotocol/sdk/types.js"; +import { getDefaultEnvironment } from "@modelcontextprotocol/sdk/client/stdio.js"; -// JSON value type for CLI arguments -type JsonValue = - | string - | number - | boolean - | null - | undefined - | JsonValue[] - | { [key: string]: JsonValue }; +export const validLogLevels: LoggingLevel[] = Object.values( + LoggingLevelSchema.enum, +); type Args = { target: string[]; @@ -38,7 +31,7 @@ type Args = { promptName?: string; promptArgs?: Record; uri?: string; - logLevel?: LogLevel; + logLevel?: LoggingLevel; toolName?: string; toolArg?: Record; toolMeta?: Record; @@ -47,58 +40,119 @@ type Args = { metadata?: Record; }; -function createTransportOptions( - target: string[], - transport?: "sse" | "stdio" | "http", - headers?: Record, -): TransportOptions { - if (target.length === 0) { +/** + * Converts CLI Args to MCPServerConfig format + * This will be used to create an InspectorClient + */ +function argsToMcpServerConfig(args: Args): MCPServerConfig { + if (args.target.length === 0) { throw new Error( "Target is required. Specify a URL or a command to execute.", ); } - const [command, ...commandArgs] = target; + const [firstTarget, ...targetArgs] = args.target; - if (!command) { - throw new Error("Command is required."); + if (!firstTarget) { + throw new Error("Target is required."); } - const isUrl = command.startsWith("http://") || command.startsWith("https://"); + const isUrl = + firstTarget.startsWith("http://") || firstTarget.startsWith("https://"); - if (isUrl && commandArgs.length > 0) { + // Validation: URLs cannot have additional arguments + if (isUrl && targetArgs.length > 0) { throw new Error("Arguments cannot be passed to a URL-based MCP server."); } - let transportType: "sse" | "stdio" | "http"; - if (transport) { - if (!isUrl && transport !== "stdio") { + // Validation: Transport/URL combinations + if (args.transport) { + if (!isUrl && args.transport !== "stdio") { throw new Error("Only stdio transport can be used with local commands."); } - if (isUrl && transport === "stdio") { + if (isUrl && args.transport === "stdio") { throw new Error("stdio transport cannot be used with URLs."); } - transportType = transport; - } else if (isUrl) { - const url = new URL(command); - if (url.pathname.endsWith("/mcp")) { - transportType = "http"; - } else if (url.pathname.endsWith("/sse")) { - transportType = "sse"; + } + + // Handle URL-based transports (SSE or streamable-http) + if (isUrl) { + const url = new URL(firstTarget); + + // Determine transport type + let transportType: "sse" | "streamable-http"; + if (args.transport) { + // Convert CLI's "http" to "streamable-http" + if (args.transport === "http") { + transportType = "streamable-http"; + } else if (args.transport === "sse") { + transportType = "sse"; + } else { + // Should not happen due to validation above, but default to SSE + transportType = "sse"; + } + } else { + // Auto-detect from URL path + if (url.pathname.endsWith("/mcp")) { + transportType = "streamable-http"; + } else if (url.pathname.endsWith("/sse")) { + transportType = "sse"; + } else { + // Default to SSE if path doesn't match known patterns + transportType = "sse"; + } + } + + // Create SSE or streamable-http config + if (transportType === "sse") { + const config: SseServerConfig = { + type: "sse", + url: firstTarget, + }; + if (args.headers) { + config.headers = args.headers; + } + return config; } else { - transportType = "sse"; + const config: StreamableHttpServerConfig = { + type: "streamable-http", + url: firstTarget, + }; + if (args.headers) { + config.headers = args.headers; + } + return config; } - } else { - transportType = "stdio"; } - return { - transportType, - command: isUrl ? undefined : command, - args: isUrl ? undefined : commandArgs, - url: isUrl ? command : undefined, - headers, + // Handle stdio transport (command-based) + const config: StdioServerConfig = { + type: "stdio", + command: firstTarget, + }; + + if (targetArgs.length > 0) { + config.args = targetArgs; + } + + const processEnv: Record = {}; + + for (const [key, value] of Object.entries(process.env)) { + if (value !== undefined) { + processEnv[key] = value; + } + } + + const defaultEnv = getDefaultEnvironment(); + + const env: Record = { + ...defaultEnv, + ...processEnv, }; + + config.env = env; + + return config; } async function callMethod(args: Args): Promise { @@ -111,27 +165,30 @@ async function callMethod(args: Args): Promise { }); packageJson = packageJsonData.default; - const transportOptions = createTransportOptions( - args.target, - args.transport, - args.headers, - ); - const transport = createTransport(transportOptions); - const [, name = packageJson.name] = packageJson.name.split("/"); const version = packageJson.version; const clientIdentity = { name, version }; - const client = new Client(clientIdentity); + const inspectorClient = new InspectorClient(argsToMcpServerConfig(args), { + environment: { + transport: createTransportNode, + }, + clientIdentity, + autoSyncLists: false, // CLI doesn't need auto-syncing, it calls methods directly + initialLoggingLevel: "debug", // Set debug logging level for CLI + progress: false, // CLI doesn't use progress; avoids SDK injecting progressToken into _meta + sample: false, // CLI doesn't need sampling capability + elicit: false, // CLI doesn't need elicitation capability + }); try { - await connect(client, transport); + await inspectorClient.connect(); let result: McpResponse; // Tools methods if (args.method === "tools/list") { - result = await listTools(client, args.metadata); + result = { tools: await inspectorClient.listAllTools(args.metadata) }; } else if (args.method === "tools/call") { if (!args.toolName) { throw new Error( @@ -139,17 +196,34 @@ async function callMethod(args: Args): Promise { ); } - result = await callTool( - client, + const invocation = await inspectorClient.callTool( args.toolName, args.toolArg || {}, args.metadata, args.toolMeta, ); + // Extract the result from the invocation object for CLI compatibility + if (invocation.result !== null) { + // Success case: result is a valid CallToolResult + result = invocation.result; + } else { + // Error case: construct an error response matching CallToolResult structure + result = { + content: [ + { + type: "text" as const, + text: invocation.error || "Tool call failed", + }, + ], + isError: true, + }; + } } // Resources methods else if (args.method === "resources/list") { - result = await listResources(client, args.metadata); + result = { + resources: await inspectorClient.listAllResources(args.metadata), + }; } else if (args.method === "resources/read") { if (!args.uri) { throw new Error( @@ -157,13 +231,22 @@ async function callMethod(args: Args): Promise { ); } - result = await readResource(client, args.uri, args.metadata); + const invocation = await inspectorClient.readResource( + args.uri, + args.metadata, + ); + // Extract the result from the invocation object for CLI compatibility + result = invocation.result; } else if (args.method === "resources/templates/list") { - result = await listResourceTemplates(client, args.metadata); + result = { + resourceTemplates: await inspectorClient.listAllResourceTemplates( + args.metadata, + ), + }; } // Prompts methods else if (args.method === "prompts/list") { - result = await listPrompts(client, args.metadata); + result = { prompts: await inspectorClient.listAllPrompts(args.metadata) }; } else if (args.method === "prompts/get") { if (!args.promptName) { throw new Error( @@ -171,12 +254,13 @@ async function callMethod(args: Args): Promise { ); } - result = await getPrompt( - client, + const invocation = await inspectorClient.getPrompt( args.promptName, args.promptArgs || {}, args.metadata, ); + // Extract the result from the invocation object for CLI compatibility + result = invocation.result; } // Logging methods else if (args.method === "logging/setLevel") { @@ -186,7 +270,8 @@ async function callMethod(args: Args): Promise { ); } - result = await setLoggingLevel(client, args.logLevel); + await inspectorClient.setLoggingLevel(args.logLevel); + result = {}; } else { throw new Error( `Unsupported method: ${args.method}. Supported methods include: tools/list, tools/call, resources/list, resources/read, resources/templates/list, prompts/list, prompts/get, logging/setLevel`, @@ -196,7 +281,7 @@ async function callMethod(args: Args): Promise { await awaitableLog(JSON.stringify(result, null, 2)); } finally { try { - await disconnect(transport); + await inspectorClient.disconnect(); } catch (disconnectError) { throw disconnectError; } @@ -308,13 +393,13 @@ function parseArgs(): Args { "--log-level ", "Logging level (for logging/setLevel method)", (value: string) => { - if (!validLogLevels.includes(value as any)) { + if (!validLogLevels.includes(value as LoggingLevel)) { throw new Error( `Invalid log level: ${value}. Valid levels are: ${validLogLevels.join(", ")}`, ); } - return value as LogLevel; + return value as LoggingLevel; }, ) // diff --git a/cli/src/transport.ts b/cli/src/transport.ts deleted file mode 100644 index 84af393b9..000000000 --- a/cli/src/transport.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; -import { - getDefaultEnvironment, - StdioClientTransport, -} from "@modelcontextprotocol/sdk/client/stdio.js"; -import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; -import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; -import { findActualExecutable } from "spawn-rx"; - -export type TransportOptions = { - transportType: "sse" | "stdio" | "http"; - command?: string; - args?: string[]; - url?: string; - headers?: Record; -}; - -function createStdioTransport(options: TransportOptions): Transport { - let args: string[] = []; - - if (options.args !== undefined) { - args = options.args; - } - - const processEnv: Record = {}; - - for (const [key, value] of Object.entries(process.env)) { - if (value !== undefined) { - processEnv[key] = value; - } - } - - const defaultEnv = getDefaultEnvironment(); - - const env: Record = { - ...defaultEnv, - ...processEnv, - }; - - const { cmd: actualCommand, args: actualArgs } = findActualExecutable( - options.command ?? "", - args, - ); - - return new StdioClientTransport({ - command: actualCommand, - args: actualArgs, - env, - stderr: "pipe", - }); -} - -export function createTransport(options: TransportOptions): Transport { - const { transportType } = options; - - try { - if (transportType === "stdio") { - return createStdioTransport(options); - } - - // If not STDIO, then it must be either SSE or HTTP. - if (!options.url) { - throw new Error("URL must be provided for SSE or HTTP transport types."); - } - const url = new URL(options.url); - - if (transportType === "sse") { - const transportOptions = options.headers - ? { - requestInit: { - headers: options.headers, - }, - } - : undefined; - return new SSEClientTransport(url, transportOptions); - } - - if (transportType === "http") { - const transportOptions = options.headers - ? { - requestInit: { - headers: options.headers, - }, - } - : undefined; - return new StreamableHTTPClientTransport(url, transportOptions); - } - - throw new Error(`Unsupported transport type: ${transportType}`); - } catch (error) { - throw new Error( - `Failed to create transport: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} diff --git a/cli/tsconfig.json b/cli/tsconfig.json index effa34f2b..952a54ca8 100644 --- a/cli/tsconfig.json +++ b/cli/tsconfig.json @@ -13,5 +13,6 @@ "noUncheckedIndexedAccess": true }, "include": ["src/**/*"], - "exclude": ["node_modules", "packages", "**/*.spec.ts", "build"] + "exclude": ["node_modules", "packages", "**/*.spec.ts", "build"], + "references": [{ "path": "../shared" }] } diff --git a/docs/environment-isolation.md b/docs/environment-isolation.md new file mode 100644 index 000000000..73a738856 --- /dev/null +++ b/docs/environment-isolation.md @@ -0,0 +1,328 @@ +# Environment Isolation + +## Overview + +**Environment isolation** is the design principle of separating pure, portable JavaScript from environment-specific code (Node.js, browser). The shared `InspectorClient` (including OAuth support) runs in Node (CLI, TUI) and in the web UX—a combination of JavaScript in the browser and Node (API endpoints on the UX server or a separate remote server). Environment-specific APIs are isolated behind abstractions or in separate modules (e.g., Node.js's `fs` and `child_process`, or the browser's `sessionStorage`). + +We use the term **seams** for the individual integration points where environment-specific behavior plugs in. Each seam has an abstraction (interface or injection point) and one or more implementations per environment. + +**Dependency consolidation:** All environment-specific dependencies are consolidated into a single `InspectorClientEnvironment` interface. Callers pass one `environment` object; each environment (Node, browser, tests) provides its implementation bundle. This simplifies wiring, clarifies the contract, and keeps optional properties optional. + +## Seams + +These seams provide environment-specific functionality to InspectorClient: + +| Seam | Abstraction | Node Implementation | Browser Implementation (Web App) | +| ---------------------- | ---------------------------- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| **Transport creation** | `CreateTransport` (required) | `createTransportNode` (creates stdio, SSE, streamable-http) | `createRemoteTransport` (creates `RemoteClientTransport` talking to remote API) | +| **OAuth storage** | `OAuthStorage` | `NodeOAuthStorage` (file-based / Zustand) | `BrowserOAuthStorage` (sessionStorage via Zustand)
`RemoteOAuthStorage` (HTTP API → file-based / Zustand via `/api/storage/oauth`) | +| **OAuth navigation** | `OAuthNavigation` | `CallbackNavigation` (e.g. opens URL via `open`) | `BrowserNavigation` (redirects) | +| **OAuth redirect URL** | `RedirectUrlProvider` | `MutableRedirectUrlProvider` (populated from callback server) | `() => \`${window.location.origin}/oauth/callback\`` (single redirect URL with state parameter) | +| **OAuth HTTP fetch** | Optional `fetchFn` | N/A (Node has no CORS) | `createRemoteFetch` (POSTs to `/api/fetch` for OAuth CORS bypass) | +| **Logging** | Optional `logger` | File-based pino logger | `createRemoteLogger` (POSTs to `/api/log`) | + +**InspectorClientEnvironment structure:** + +All environment-specific dependencies are consolidated into a single `environment` object passed to `InspectorClient`: + +```typescript +interface InspectorClientEnvironment { + transport: CreateTransport; // Required + fetch?: typeof fetch; // Optional, for OAuth and transport HTTP + logger?: pino.Logger; // Optional, for InspectorClient events + oauth?: { + storage?: OAuthStorage; + navigation?: OAuthNavigation; + redirectUrlProvider?: RedirectUrlProvider; + }; +} +``` + +**Node usage example:** + +```typescript +const client = new InspectorClient(config, { + environment: { + transport: createTransportNode, + logger: createFileLogger({ logPath: "/path/to/logs" }), + oauth: { + storage: new NodeOAuthStorage({ dataDir: "/path/to/data" }), + navigation: new ConsoleNavigation(), + redirectUrlProvider: createCallbackServerRedirectUrlProvider(), + }, + }, + oauth: { + clientId: "my-client-id", + clientSecret: "my-secret", + }, +}); +``` + +**Browser usage example (Web App):** + +```typescript +// web/src/lib/adapters/environmentFactory.ts +export function createWebEnvironment( + authToken: string | undefined, + redirectUrlProvider: RedirectUrlProvider, +): InspectorClientEnvironment { + const baseUrl = `${window.location.protocol}//${window.location.host}`; + const fetchFn: typeof fetch = (...args) => globalThis.fetch(...args); + + return { + transport: createRemoteTransport({ + baseUrl, + authToken, + fetchFn, + }), + fetch: createRemoteFetch({ + baseUrl, + authToken, + fetchFn, + }), + logger: createRemoteLogger({ + baseUrl, + authToken, + fetchFn, + }), + oauth: { + storage: new BrowserOAuthStorage(), + navigation: new BrowserNavigation(), + redirectUrlProvider, + }, + }; +} + +// Usage in web app: +const client = new InspectorClient(config, { + environment: createWebEnvironment( + authToken, + () => `${window.location.origin}/oauth/callback`, + ), + oauth: { + clientId: "my-client-id", + clientSecret: "my-secret", // optional + }, +}); +``` + +**Note:** OAuth configuration (clientId, clientSecret, clientMetadataUrl, scope) is separate from environment components and goes in the top-level `oauth` property. The web app uses `BrowserOAuthStorage` (sessionStorage) for browser-only OAuth state. For shared state with Node apps (TUI/CLI), use `RemoteOAuthStorage` instead. + +--- + +## Remote API Server + +The remote API server (`createRemoteApp` in `shared/mcp/remote/node/`) is a Hono-based server that hosts all Node-backed endpoints required by browser-based InspectorClient. The server is integrated directly into the Vite dev server (same origin as the web client) and exposes environment-specific functionality as HTTP APIs. The browser uses pure JavaScript wrappers that call these APIs where the Node-specific logic is implemented; InspectorClient remains unaware of whether it is talking to local or remote services. + +**Rationale for Hono** + +Hono is lightweight, framework-agnostic, and supports Node. Using Hono keeps the API surface simple and consistent with the goal of a single server hosting transport, fetch, logging, and storage. The Hono server is integrated into the Vite dev server as middleware, eliminating the need for a separate Express server. This provides same-origin requests (no CORS issues) and simplifies deployment. + +**Integration in Web App** + +- **Dev Mode:** Hono middleware plugin (`honoMiddlewarePlugin`) in `web/vite.config.ts` mounts the Hono app at the root and handles `/api/*` routes +- **Prod Mode:** Standalone Hono server (`web/bin/server.js`) serves both static files and API endpoints +- **Same Origin:** Both dev and prod modes serve from the same origin, eliminating CORS issues +- **Auth Token:** Passed via `MCP_INSPECTOR_API_TOKEN` environment variable (read-only, set by start script) + +**Security** + +All endpoints require authentication via `x-mcp-remote-auth` header (Bearer token format), origin validation, and timing-safe token comparison. The auth token is generated from options, environment variable (`MCP_INSPECTOR_API_TOKEN`), or randomly generated. + +**Endpoints** + +| Endpoint | Purpose | Seam | +| ------------------------------ | ----------------------------------------------------------------- | ----------------- | +| `GET /api/config` | Return initial server config (command, args, transport, URL, env) | Config | +| `POST /api/mcp/connect` | Create session and client transport (stdio, SSE, streamable HTTP) | Remote transports | +| `POST /api/mcp/send` | Forward JSON-RPC message to MCP server | Remote transports | +| `GET /api/mcp/events` | Stream responses and side-channel events (SSE) | Remote transports | +| `POST /api/mcp/disconnect` | Cleanup session | Remote transports | +| `POST /api/fetch` | Remote HTTP requests for OAuth (CORS bypass) | Remote fetch | +| `POST /api/log` | Receive log events from browser for server-side logging | Remote logging | +| `GET /api/storage/:storeId` | Read entire store (generic, e.g. oauth, preferences) | Remote storage | +| `POST /api/storage/:storeId` | Write entire store (generic) | Remote storage | +| `DELETE /api/storage/:storeId` | Delete store (generic) | Remote storage | + +**Out of scope for the API** + +- **OAuth callback** — The web app implements its own `/oauth/callback` route. OAuth redirects hit the web app directly; the callback is not part of the remote API. The web app handles both normal and guided OAuth flows via a single callback endpoint, with mode distinguished by the `state` parameter (`"guided:{random}"` or `"normal:{random}"`). + +--- + +## Remote Infrastructure Details + +These remote seams enable InspectorClient to run in the browser. They fall into two groups: browser integration (new functionality for InspectorClient in the web UX) and code structure (refactoring so the shared package can run in the browser without pulling in Node-only code). + +### Remote Transports (Transport Seam) + +The browser cannot use stdio transports (no `child_process` in browser) and faces CORS/header limitations with direct HTTP connections (e.g. `mcp-session-id` hidden, many servers don't send `Access-Control-Expose-Headers`). + +**Design:** The browser always uses remote transports for all transport types (stdio, SSE, streamable-http). A **remote server** creates real SDK transports in Node and forwards JSON-RPC messages to/from the browser. The browser uses a `RemoteClientTransport` that talks to the remote; it implements the same `Transport` interface as local transports. + +Unlike a proxy that maintains duplicate SDK clients and protocol state, the remote server is **stateless**—it only creates transports and forwards messages. `InspectorClient` runs in the browser and remains the single source of truth for protocol state, message tracking, and server data. This allows the same `InspectorClient` code to work identically in Node (CLI, TUI) and browser, with only the transport factory differing. The remote server runs on the same server as the UX server (Vite dev server or equivalent), though it can run as a separate remote server if needed. + +**Implementation:** `createRemoteTransport` and `RemoteClientTransport` (in `shared/mcp/remote/`); `createRemoteApp` (in `shared/mcp/remote/node/`). Tests in `shared/__tests__/remote-transport.test.ts` cover stdio, SSE, streamable-http. + +**Relevant endpoints:** + +- `POST /api/mcp/connect` — Create session and transport (stdio, SSE, or streamable HTTP). Accepts `{ config: MCPServerConfig, oauthTokens?: {...} }`, creates Node transport, returns `{ sessionId }`. +- `POST /api/mcp/send` — Forward JSON-RPC message to MCP server. Accepts `{ message: JSONRPCMessage, relatedRequestId?: string }`, forwards to transport, returns response. +- `GET /api/mcp/events` — Stream responses (SSE). Multiplexes `message`, `fetch_request`, and `stdio_log` events. +- `POST /api/mcp/disconnect` — Cleanup session. Closes transport and removes session. + +**Design Details** + +The remote server forwards messages only; it holds no SDK `Client` and no protocol state. `InspectorClient` runs in the browser (or Node for CLI/TUI) and remains the single source of truth. The browser always uses remote transports for all transport types; the remote server creates the real transports (stdio, SSE, streamable-http) in Node, so the browser never loads Node-specific transport code or `child_process`. + +When the underlying transport returns 401 (e.g., OAuth required), the remote server preserves the status code and returns HTTP 401 (not 500). `RemoteClientTransport` receives the 401 response and throws an error with the status code preserved, allowing callers to detect authentication failures and trigger OAuth flow manually (consistent with the "authenticate first, then connect" pattern). + +**Event stream and message handlers** + +The remote server multiplexes multiple event types on the SSE stream (`/api/mcp/events`). The browser's `RemoteClientTransport` subscribes to this stream and routes each event to the appropriate handler on the JavaScript side: + +- `event: message` + JSON-RPC data → pass to `transport.onmessage` (protocol messages) +- `event: fetch_request` + `FetchRequestEntry` → call `onFetchRequest` (HTTP request/response tracking for the Requests tab) +- `event: stdio_log` (or `notifications/message`) + stderr payload → call `onStderr` (console output from stdio transports) + +The remote server uses `createFetchTracker` when creating HTTP transports and emits `fetch_request` events when requests complete. For stdio transports, the remote server listens to the child process stderr and emits `stdio_log` (or equivalent) events. The `RemoteClientTransport` implements the same handler interface as local transports, so `InspectorClient` does not need to know whether it is using a local or remote transport. + +**Fetch usage in transports** + +Transports (SSE, streamable-http) use fetch for HTTP and **must support streaming responses** (SSE stream, NDJSON stream). Recording is the **transport creator's responsibility**: wrap the base fetch with createFetchTracker and pass onFetchRequest. The tracking wrapper **does support streaming** (it detects stream content-types and returns the original response without reading the body), so recording does not break streaming. + +- **Node (createTransportNode):** Receives `environment.fetch` from InspectorClient; uses (`environment.fetch ?? globalThis.fetch`) wrapped with createFetchTracker for SSE/streamable-http. If a non-streaming fetch were passed, transport would break; today callers use default or real fetch. + +- **Remote:** The **server** creates the real transport with createTransportNode; it does not receive InspectorClient's `environment.fetch` (that's on the client). So the server uses Node's fetch for the transport. Recording is applied on the server (onFetchRequest → session → fetch_request events to client). The **client**'s RemoteClientTransport uses fetch only for its own HTTP (connect, GET events, send, disconnect). GET /api/mcp/events is SSE, so that fetch must support streaming. **Design decision:** createRemoteTransport does **not** pass InspectorClient's `environment.fetch` to RemoteClientTransport; it uses only the factory's fetchFn (or undefined → globalThis.fetch). So the transport's HTTP always uses a streaming-capable fetch. OAuth can still use a remoted fetch via InspectorClient's `environment.fetch` (effectiveAuthFetch). + +--- + +### Remote Fetch (OAuth CORS Bypass) + +CORS blocks OAuth-related HTTP requests in the browser: discovery, client registration, token exchange, scope discovery, and others. Many authorization servers (e.g., GitHub MCP at `https://api.githubcopilot.com/mcp/`) do not include `Access-Control-Allow-Origin`, causing OAuth flows to fail with: + +``` +Failed to start OAuth flow: Failed to discover OAuth metadata +``` + +**Design:** Pass `fetchFn` in `environment.fetch` to route OAuth-related HTTP requests through the remote server (Node.js), which has no CORS restrictions. InspectorClient uses this fetch for all OAuth operations (discovery, registration, token exchange, etc.). + +**Implementation** + +**InspectorClient:** Accepts optional `environment.fetch` and builds `effectiveAuthFetch` = createFetchTracker(baseFetch, trackRequest) with baseFetch = `environment.fetch ?? fetch`. All OAuth HTTP requests use this effective fetch. + +**`createRemoteFetch`** (in `shared/mcp/remote/`): Returns a fetch function that POSTs to `/api/fetch`. The remote server performs the actual HTTP request in Node and returns the response. OAuth responses are JSON (not streaming), so the buffered response from `createRemoteFetch` is sufficient. + +**Relevant endpoint:** + +- `POST /api/fetch` — Accepts `{ url, method?, headers?, body? }`, performs the fetch in Node, returns `{ ok, status, statusText, headers, body }`. Protected by `x-mcp-remote-auth` when `authToken` is set. + +**Client usage:** Pass `createRemoteFetch({ baseUrl, authToken?, fetchFn? })` as `environment.fetch` when in browser. + +**Limitations:** `createRemoteFetch` buffers the response body and cannot stream. It is intended for OAuth (and other non-streaming HTTP) only. Do not use as a general-purpose or transport-level fetchFn where the response might be streaming. + +--- + +### Remote Logging + +InspectorClient accepts optional `environment.logger` (pino `Logger`) for customizable logging. + +The CLI and TUI use a file-based logger. + +Browser clients are unable to write to the server console or the file system, so an optional remote logger may be provided by a browser client user of InspectorClient. The browser client uses a remote logger to forward log events to the server (Node endpoints) where configured loggers may write to the system console, a file-based log, or any other supported Pino log target. + +**Implementation:** `createRemoteLogger` (in `shared/mcp/remote/`) returns a pino logger that POSTs to `/api/log` via `pino/browser` transmit. + +**Relevant endpoint:** + +- `POST /api/log` — Receives log events from browser, forwards to file logger when `createRemoteApp({ logger })` is passed. Protected by `x-mcp-remote-auth` when `authToken` is set. + +Tests in `shared/__tests__/remote-transport.test.ts` validate the flow. + +--- + +### Remote Storage + +The browser cannot read/write the filesystem directly, so a generic storage API enables shared on-disk state between web app and Node apps (TUI, CLI). + +OAuth tokens and other state need to persist across sessions. In Node (TUI, CLI), we use file-based storage. In the browser, we need a way to share this state with Node apps when the web app runs alongside the Node process hosting the remote API. + +**Design:** A generic storage API that treats stores as opaque JSON blobs (Zustand's persist format). The server stores entire stores as files; clients read/write entire stores via HTTP. + +**Implementation:** + +- **Storage adapters** (`shared/storage/adapters/`): Reusable Zustand storage adapters: + - `FileStorageAdapter` — file-based storage for Node (uses `fs/promises`) + - `RemoteStorageAdapter` — HTTP-based storage for browser (uses `/api/storage/:storeId`) +- **OAuth storage implementations**: + - `NodeOAuthStorage` — uses `FileStorageAdapter` with Zustand persist middleware + - `BrowserOAuthStorage` — uses Zustand with `sessionStorage` adapter (browser-only) + - `RemoteOAuthStorage` — uses `RemoteStorageAdapter` for shared state with Node apps + +**Relevant endpoints:** + +- `GET /api/storage/:storeId` — Returns entire store as JSON (empty object `{}` if not found). Protected by `x-mcp-remote-auth` when `authToken` is set. +- `POST /api/storage/:storeId` — Overwrites entire store with provided JSON. Protected by `x-mcp-remote-auth` when `authToken` is set. +- `DELETE /api/storage/:storeId` — Deletes store (idempotent). Protected by `x-mcp-remote-auth` when `authToken` is set. + +**Design Details:** The server treats stores as opaque JSON blobs (Zustand's persist format: `{ state: {...}, version: 0 }`). Store IDs are arbitrary (e.g. `oauth`, `inspector-settings`). All OAuth storage implementations use the same Zustand-backed pattern for consistency. `RemoteOAuthStorage` fetches the store on initialization, implements `OAuthStorage` against the in-memory structure, and persists changes via POST. This enables shared OAuth state when the web app runs alongside the Node process hosting the remote API (e.g. Vite dev server with Hono backend). + +**Web App Usage:** The web app uses `BrowserOAuthStorage` (sessionStorage) for browser-only OAuth state. This provides isolation between browser sessions but does not share state with TUI/CLI. To enable shared OAuth state with Node apps, switch to `RemoteOAuthStorage` in `createWebEnvironment()`. + +**Session persistence across OAuth:** InspectorClient can optionally persist session state (e.g. fetch history) across the OAuth redirect. This is an InspectorClient feature that reuses the same remote storage seam: the web app passes optional `sessionStorage` (e.g. `RemoteInspectorClientStorage`) and `sessionId` (from the OAuth `state` parameter). InspectorClient saves session before navigating to the auth provider and restores it when the client is recreated after the callback. Store IDs follow the pattern `inspector-session-{sessionId}` and use the existing `GET/POST /api/storage/:storeId` endpoints. + +--- + +## Module Organization + +Environment-specific code is under `node` or `browser` subdirectories so the core `auth` and `mcp` modules stay portable. + +### Auth + +| Module | Environment | Contents | Package Export | +| ---------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | +| `shared/auth/` | Portable | Types, interfaces, base providers, utilities (no `fs`, `window`, or `sessionStorage`). Exports storage interface, `CallbackNavigation`, `ConsoleNavigation`, `BaseOAuthClientProvider`, etc. | `"./auth"` | +| `shared/auth/node/` | Node-only | `NodeOAuthStorage`, `createOAuthCallbackServer`, `clearAllOAuthClientState` | `"./auth/node"` | +| `shared/auth/browser/` | Browser-only | `BrowserOAuthStorage` (sessionStorage), `BrowserNavigation`, `BrowserOAuthClientProvider` | `"./auth/browser"` | + +**Usage:** Node consumers (TUI, CLI, tests) import from `inspector-shared/auth/node`. Browser consumers import from `inspector-shared/auth/browser`. Core auth is imported from `inspector-shared/auth` only. + +### MCP + +Remote transport code follows the same pattern: portable client in the module root, Node-specific server under `node/`. + +| Module | Environment | Contents | Package Export | +| ------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | +| `shared/mcp/` | Portable | `InspectorClient`, types, `getServerType`, `createFetchTracker`, message tracking, etc. No Node-only APIs. | `"./mcp"` | +| `shared/mcp/node/` | Node-only | `loadMcpServersConfig`, `argsToMcpServerConfig`, `createTransportNode` | `"./mcp/node"` | +| `shared/mcp/remote/` | Portable | `createRemoteTransport`, `createRemoteFetch`, `createRemoteLogger`, `RemoteClientTransport`. Pure TypeScript; runs in browser, Deno, or Node. | `"./mcp/remote"` | +| `shared/mcp/remote/node/` | Node-only | Remote server (Hono, spawn, etc.). The server that hosts `/api/mcp/*`, `/api/fetch`, `/api/log`, `/api/storage/*`. | `"./mcp/remote/node"` | + +**Usage:** Node consumers (TUI, CLI) import from `inspector-shared/mcp/node` for config loading and transport creation. Web consumers import `createRemoteTransport` from `inspector-shared/mcp/remote`; the UX server or a separate remote server runs the remote API from `inspector-shared/mcp/remote/node`. + +--- + +## Web App Integration + +The current web client and server functionality has been ported to a new web app (`web/`) that uses `InspectorClient` with remote infrastructure, implementing all functionality previously supported. The separate proxy server/endpoint has been removed. Security via token is retained by implementation of an "API Token" that the local client app uses to access local API endpoints. The `useConnection` hook, auth logic and state machine, etc, have been removed. The new web app is a fairly thin UX wrapper of `InspectorClient` + +**Architecture:** + +- **Environment Factory:** `web/src/lib/adapters/environmentFactory.ts` provides `createWebEnvironment()` that configures: + - `createRemoteTransport()` for all transport types (stdio, SSE, streamable-http) + - `createRemoteFetch()` for OAuth HTTP requests (CORS bypass) + - `createRemoteLogger()` for persistent logging + - `BrowserOAuthStorage` and `BrowserNavigation` for OAuth flows +- **Lazy Client Creation:** Uses `ensureInspectorClient()` helper that validates API token before creating client +- **OAuth Integration:** Single redirect URL (`/oauth/callback`) with mode encoded in state parameter; supports both normal and guided flows +- **Initial Config:** Web app fetches `GET /api/config` (with `x-mcp-remote-auth`) on load; response sets command, args, transport, server URL, and env. Same in dev and prod. + +**Hono Integration:** + +- **Dev Mode:** Hono middleware plugin (`honoMiddlewarePlugin`) in `web/vite.config.ts` mounts the Hono app at the root and handles `/api/*` routes +- **Prod Mode:** Standalone Hono server (`web/bin/server.js`) serves both static files and API endpoints +- **Same Origin:** Both dev and prod modes serve from the same origin, eliminating CORS issues + +**Legacy Client:** + +The legacy web client (`client/`) still exists but is deprecated. It uses `useConnection` with direct SDK transports and a separate Express server. New development should use the `web/` app with `InspectorClient`. diff --git a/docs/inspector-client-details.svg b/docs/inspector-client-details.svg new file mode 100644 index 000000000..d0c9a6aaf --- /dev/null +++ b/docs/inspector-client-details.svg @@ -0,0 +1,52 @@ + + + + + + + + + + + InspectorClient + + + Implements all business logic for MCP client operations + Wraps MCP SDK Client and manages lifecycle + + + Core Responsibilities + + + Client and Transport Lifecycle Management + + + Message Tracking (all JSON-RPC messages) + + + Stderr Logging (stdio transports) + + + Server Data Management (tools, resources, prompts) + + + Event-Driven Updates (EventTarget-based) + + + State Management (connection status, history) + + + Transport Abstraction (stdio, SSE, streamable-http) + + + High-Level MCP Method Wrappers + diff --git a/docs/inspector-client-todo.md b/docs/inspector-client-todo.md new file mode 100644 index 000000000..19a842879 --- /dev/null +++ b/docs/inspector-client-todo.md @@ -0,0 +1,99 @@ +# Inspector client TODO + +NOTE: This document is maintained by a human developer. Agents should never update this document unless directed specifically to do so. + +## Auth Issues + +If we can't bring up a browser endpoint for redirect (like if we're in a container or sandbox) + +- Can we implement "device flow" (RFC 8628) and will IDPs support it generally? +- Device flow feature advertisement has issues (for example, GitHub doesn't show it in metadata, but supports it based on app setting) +- Device flow returns "devide_flow_disabed" error, as well as "access_denied", so maybe we just always try, and on those specific error we try the token mode + +If we are in a container: + +- We can set the callback url via config (--callback-url) for creating the local server (binding / serving) +- We don't have a way to specify a different callback url for the protocol (for example, using a host address and/or mapped port) + +CIMD + +- We need to publish a static document for inspector client info +- We have a TUI command line param to set it (--client-metadata-url) + +If we get auth server metadata, then we know definitively whether DCR or CIMD are supported + +- We should not attempt unsupported mechanisms and report an appropriate error if not mechanisms are supported + - For example, GitHub only supports preregisgtered static client - if we don't have client info and CIMD and DCR not supported, stop and error + - This could be "no client_id provided and no other client identification mechanisms supported by server" +- If we don't get auth server metadata, we will fall back to trying default endpoints + - It's highly unlikely that CIMD would be supported by an auth server without metadata + - It's possible that DCR could be supported + +Here are some sampole CIMD files: + +- MCPJam - https://www.mcpjam.com/.well-known/oauth/client-metadata.json +- VS Code - https://vscode.dev/oauth/client-metadata.json +- mcp-inspect: https://teamsparkai.github.io/mcp-inspect/.well-known/auth/client-metadata.json + +Inspector v1 Supports + +- Auth + - Custom headers (list of headers with name/value, can be individually turned on/off) + - Client ID + - Client Secret + - Redirect URL (default to self server + /oauth/callback) + - Scopes (space separated list) +- Configuration + - Request timeout (ms) + - Reset timeout on progress (bool) + - Maximum total timeout (ms) + - Inspector proxy address + - Proxy session token + - Task TTL (ms) + +Auth: + +- Custom headers, Client ID, Client Secret, and Scopes are per-server config elements +- Client Metadata URL (CIMD), callback port and url are global config + Configuration: +- All global config + +## Auth Issues (for v2?) + +Found issues with servers not supporting the registeration of multiple callback URLs + +- Consolidated quick/guided into one endpoint (embedded "mode" in oauth state token, use a single endpoint) + +Found many CORS auth issues from browser + +- Must proxy fetch to node (see PR #1047 against v1) + +Found issue with CORS stripping mcp-session-id header + +- Certain http servers with auth only work via proxy + +CIMD - Need static document for Inspector + +## TODO + +clientMetadataUrl + +- After we makde one for Inspector, make it the default for --client-metadata-url + +Create CIMD file and test in TUI + +- Figure out how to verify it's using CIMD + +Implement and test device flow / device code to see if it's supported + +- Hosted everything - https://example-server.modelcontextprotocol.io/mcp - not supported +- GitHub - https://api.githubcopilot.com/mcp + - DevReorganiice flow enabled in Github OAuth app, doesn't show in metadata (which isn't client specific) + - Try it and see if it works (if it works, try it without client_secret to see if that works) +- Others if neither of those work? + +Testing + +- Static client: https://api.githubcopilot.com/mcp (works, requires client_id AND client_secret) +- DCR: https://example-server.modelcontextprotocol.io/mcp (works) +- CIMD: https://stytch-as-demo.val.run/mcp (works - as long as client_id and client_uri use the same domain) diff --git a/docs/oauth-inspectorclient-design.md b/docs/oauth-inspectorclient-design.md new file mode 100644 index 000000000..bdc4014a0 --- /dev/null +++ b/docs/oauth-inspectorclient-design.md @@ -0,0 +1,1333 @@ +# OAuth Support in InspectorClient - Design and Implementation Plan + +## Overview + +This document outlines the design and implementation plan for adding MCP OAuth 2.1 support to `InspectorClient`. The goal is to extract the general-purpose OAuth logic from the web client into the shared package and integrate it into `InspectorClient`, making OAuth available for CLI, TUI, and other InspectorClient consumers. + +**Important**: The web client OAuth code will remain in place and will not be modified to use the shared code at this time. Future migration options (using shared code directly, relying on InspectorClient, or a combination) should be considered in the design but not implemented. + +## Goals + +1. **Extract General-Purpose OAuth Logic**: Copy reusable OAuth components from `client/src/lib/` and `client/src/utils/` to `shared/auth/` (leaving originals in place) +2. **Abstract Platform Dependencies**: Create interfaces for storage, navigation, and redirect URLs to support both browser and Node.js environments +3. **Integrate with InspectorClient**: Add OAuth support to `InspectorClient` with both direct and indirect (401-triggered) OAuth flow initiation +4. **Support All Client Identification Modes**: Support static/preregistered clients, DCR (Dynamic Client Registration), and CIMD (Client ID Metadata Documents) +5. **Enable CLI/TUI OAuth**: Provide a foundation for OAuth support in CLI and TUI applications +6. **Event-Driven Architecture**: Design OAuth flow to be notification/callback driven for client-side integration + +## Architecture + +### Current State + +The web client's OAuth implementation consists of: + +- **OAuth Client Providers** (`client/src/lib/auth.ts`): + - `InspectorOAuthClientProvider`: Standard OAuth provider for automatic flow + - `GuidedInspectorOAuthClientProvider`: Extended provider for guided flow that saves server metadata and uses guided redirect URL +- **OAuth State Machine** (`client/src/lib/oauth-state-machine.ts`): Step-by-step OAuth flow that breaks OAuth into discrete, manually-progressible steps +- **OAuth Utilities** (`client/src/utils/oauthUtils.ts`): Pure functions for parsing callbacks and generating state +- **Scope Discovery** (`client/src/lib/auth.ts`): `discoverScopes()` function +- **Storage Functions** (`client/src/lib/auth.ts`): SessionStorage-based storage helpers +- **UI Components**: + - `AuthDebugger.tsx`: Core OAuth UI providing both "Guided" (step-by-step) and "Quick" (automatic) flows + - `OAuthFlowProgress.tsx`: Visual progress indicator showing OAuth step status + - OAuth callback handlers (web-specific, not moving) + +**Note on "Guided" Mode**: The Auth Debugger (guided mode) is a **core feature** of the web client, not an optional debug tool. It provides: + +- **Guided Flow**: Manual step-by-step progression with full state visibility +- **Quick Flow**: Automatic progression through all steps +- **State Inspection**: Full visibility into OAuth state (tokens, metadata, client info, etc.) +- **Error Debugging**: Clear error messages and validation at each step + +This guided mode should be considered a core requirement for InspectorClient OAuth support, not a future enhancement. + +### Target Architecture + +``` +shared/auth/ +├── storage.ts # Storage abstraction using Zustand with persistence +├── providers.ts # Abstract OAuth client provider base class +├── state-machine.ts # OAuth state machine (general-purpose logic) +├── utils.ts # General-purpose utilities +├── types.ts # OAuth-related types +├── discovery.ts # Scope discovery utilities +├── store.ts # Zustand store for OAuth state (vanilla, no React deps) +└── __tests__/ # Tests + +shared/mcp/ +└── inspectorClient.ts # InspectorClient with OAuth integration + +shared/react/ +└── auth/ # Optional: Shareable React hooks for OAuth state + └── hooks.ts # React hooks (useOAuthStore, etc.) - requires React peer dep + # Note: UI components cannot be shared between TUI (Ink) and web (DOM) + # Each client must implement its own OAuth UI components + +client/src/lib/ # Web client OAuth code (unchanged) +├── auth.ts +└── oauth-state-machine.ts +``` + +## Abstraction Strategy + +### 1. Storage Abstraction with Zustand + +**Storage Strategy**: Use Zustand with persistent middleware for OAuth state management. Zustand's vanilla API allows non-React usage (CLI), while React bindings enable UI integration (TUI, web client). + +**Zustand Store Structure**: + +```typescript +interface OAuthStoreState { + // Server-scoped OAuth data + servers: Record< + string, + { + tokens?: OAuthTokens; + clientInformation?: OAuthClientInformation; + preregisteredClientInformation?: OAuthClientInformation; + codeVerifier?: string; + scope?: string; + serverMetadata?: OAuthMetadata; + } + >; + + // Actions + setTokens: (serverUrl: string, tokens: OAuthTokens) => void; + getTokens: (serverUrl: string) => OAuthTokens | undefined; + clearServer: (serverUrl: string) => void; + // ... other actions +} +``` + +**Storage Implementations**: + +- **Browser**: Zustand store with `persist` middleware using `sessionStorage` adapter +- **Node.js**: Zustand store with `persist` middleware using file-based storage adapter +- **Memory**: Zustand store without persistence (for testing) + +**Storage Location for InspectorClient**: + +- Default: `~/.mcp-inspector/oauth/state.json` (single Zustand store file) +- Configurable via `InspectorClientOptions.oauth?.storagePath` + +**Benefits of Zustand**: + +- Vanilla API works without React (CLI support) +- React hooks available for UI components (TUI, web client) +- Built-in persistence middleware +- Type-safe state management +- Easier to backup/restore (one file) +- Small bundle size + +### 2. Redirect URL Abstraction + +**Interface**: + +```typescript +interface RedirectUrlProvider { + /** + * Returns the redirect URL for normal mode + */ + getRedirectUrl(): string; + + /** + * Returns the redirect URL for guided mode + */ + getDebugRedirectUrl(): string; +} +``` + +**Implementations**: + +- `BrowserRedirectUrlProvider`: + - Normal: `window.location.origin + "/oauth/callback"` + - Guided: `window.location.origin + "/oauth/callback/guided"` +- `LocalServerRedirectUrlProvider`: + - Constructor takes `port: number` parameter + - Normal: `http://localhost:${port}/oauth/callback` + - Guided: `http://localhost:${port}/oauth/callback/guided` +- `ManualRedirectUrlProvider`: + - Constructor takes `baseUrl: string` parameter + - Normal: `${baseUrl}/oauth/callback` + - Guided: `${baseUrl}/oauth/callback/guided` + +**Design Rationale**: + +- Both redirect URLs are available from the provider +- Both URLs are registered with the OAuth server during client registration (like web client) +- This allows switching between normal and guided modes without re-registering the client +- The provider's mode determines which URL is used for the current flow, but both are registered for flexibility + +### 3. Navigation Abstraction + +**Interface**: + +```typescript +interface OAuthNavigation { + redirectToAuthorization(url: URL): void | Promise; +} +``` + +**Implementations**: + +- `BrowserNavigation`: Sets `window.location.href` (for web client) +- `ConsoleNavigation`: Prints URL to console and waits for callback (for CLI/TUI) +- `CallbackNavigation`: Calls a provided callback function (for InspectorClient) + +### 4. OAuth Client Provider Abstraction + +**Base Class**: + +```typescript +abstract class BaseOAuthClientProvider implements OAuthClientProvider { + constructor( + protected serverUrl: string, + protected storage: OAuthStorage, + protected redirectUrlProvider: RedirectUrlProvider, + protected navigation: OAuthNavigation, + protected mode: "normal" | "guided" = "normal", // OAuth flow mode + ) {} + + // Abstract methods implemented by subclasses + abstract get scope(): string | undefined; + + // Returns the redirect URL for the current mode + get redirectUrl(): string { + return this.mode === "guided" + ? this.redirectUrlProvider.getDebugRedirectUrl() + : this.redirectUrlProvider.getRedirectUrl(); + } + + // Returns both redirect URIs (registered with OAuth server for flexibility) + get redirect_uris(): string[] { + return [ + this.redirectUrlProvider.getRedirectUrl(), + this.redirectUrlProvider.getDebugRedirectUrl(), + ]; + } + + abstract get clientMetadata(): OAuthClientMetadata; + + // Shared implementation for SDK interface methods + async clientInformation(): Promise { ... } + saveClientInformation(clientInformation: OAuthClientInformation): void { ... } + async tokens(): Promise { ... } + saveTokens(tokens: OAuthTokens): void { ... } + saveCodeVerifier(codeVerifier: string): void { ... } + codeVerifier(): string { ... } + clear(): void { ... } + redirectToAuthorization(authorizationUrl: URL): void { ... } + state(): string | Promise { ... } +} +``` + +**Implementations**: + +- `BrowserOAuthClientProvider`: Extends base, uses browser storage and navigation (for web client) +- `NodeOAuthClientProvider`: Extends base, uses Zustand store and console navigation (for InspectorClient/CLI/TUI) + +**Mode Selection**: + +- **Normal mode** (`mode: "normal"`): Provider uses `/oauth/callback` for the current flow +- **Guided mode** (`mode: "guided"`): Provider uses `/oauth/callback/guided` for the current flow +- Both URLs are registered with the OAuth server during client registration (allows switching modes without re-registering) +- The mode is determined when creating the provider - specify normal or debug and it "just works" +- Both callback handlers are mounted (one at `/oauth/callback`, one at `/oauth/callback/guided`) +- The handler behavior matches the provider's mode (normal handler auto-completes, debug handler shows code) + +**Client Identification Modes**: + +- **Static/Preregistered**: Uses `clientId` and optional `clientSecret` from config +- **DCR (Dynamic Client Registration)**: Falls back to DCR if no static client provided +- **CIMD (Client ID Metadata Documents)**: Uses `clientMetadataUrl` from config to enable URL-based client IDs (SEP-991) + +## Module Structure + +### `shared/auth/store.ts` + +**Exports** (vanilla-only, no React dependencies): + +- `createOAuthStore()` - Factory function to create Zustand store +- `getOAuthStore()` - Vanilla API for accessing store (no React dependency) + +**Note**: React hooks (if needed) would be in `shared/react/auth/hooks.ts` as an optional export that requires React as a peer dependency. + +**Store Implementation**: + +- Uses Zustand's `create` function with `persist` middleware +- Browser: Persists to `sessionStorage` via Zustand's `persist` middleware +- Node.js: Persists to file via custom storage adapter for Zustand's `persist` middleware +- Memory: No persistence (for testing) + +**Storage Adapter for Node.js**: + +- Custom Zustand storage adapter that uses Node.js `fs/promises` +- Stores single JSON file: `~/.mcp-inspector/oauth/state.json` +- Handles file creation, reading, and writing atomically + +### `shared/auth/providers.ts` + +**Exports**: + +- `BaseOAuthClientProvider` abstract class +- `BrowserOAuthClientProvider` class (for web client, uses sessionStorage directly) +- `NodeOAuthClientProvider` class (for InspectorClient/CLI/TUI, uses Zustand store) + +**Key Methods**: + +- All SDK `OAuthClientProvider` interface methods +- Server-specific state management via Zustand store +- Token and client information management +- Support for `clientMetadataUrl` for CIMD mode + +### `shared/auth/state-machine.ts` + +**Exports**: + +- `OAuthStateMachine` class +- `oauthTransitions` object (state transition definitions) +- `StateMachineContext` interface +- `StateTransition` interface + +**Changes from Current Implementation**: + +- Accepts abstract `OAuthClientProvider` instead of `DebugInspectorOAuthClientProvider` +- Removes web-specific dependencies (sessionStorage, window.location) +- General-purpose state transition logic + +### `shared/auth/utils.ts` + +**Exports**: + +- `parseOAuthCallbackParams(location: string): CallbackParams` - Pure function +- `generateOAuthErrorDescription(params: CallbackParams): string` - Pure function +- `generateOAuthState(): string` - Uses `globalThis.crypto` or Node.js `crypto` module + +**Changes from Current Implementation**: + +- `generateOAuthState()` checks for `globalThis.crypto` first (browser), falls back to Node.js `crypto.randomBytes()` + +### `shared/auth/types.ts` + +**Exports**: + +- `CallbackParams` type (from `oauthUtils.ts`) +- Re-export SDK OAuth types as needed + +### `shared/auth/discovery.ts` + +**Exports**: + +- `discoverScopes(serverUrl: string, resourceMetadata?: OAuthProtectedResourceMetadata): Promise` + +**Note**: This is already general-purpose (uses only SDK functions), just needs to be moved. + +### `shared/react/auth/` (Optional - Shareable React Hooks Only) + +**What Can Be Shared**: + +- `hooks.ts` - React hooks for accessing OAuth state: + - `useOAuthStore()` - Hook to access Zustand OAuth store + - `useOAuthTokens()` - Hook to get current OAuth tokens + - `useOAuthState()` - Hook to get current OAuth state machine state + - These hooks are pure logic - no rendering, so they work with both Ink (TUI) and DOM (web) + +**What Cannot Be Shared**: + +- **UI Components** (`.tsx` files with visual rendering) cannot be shared because: + - TUI uses **Ink** (terminal rendering) with components like ``, ``, etc. + - Web client uses **DOM** (browser rendering) with components like `
`, ``, etc. + - They have completely different rendering targets, styling systems, and component APIs +- Each client must implement its own OAuth UI components: + - TUI: `tui/src/components/OAuthFlowProgress.tsx` (using Ink components) + - Web: `client/src/components/OAuthFlowProgress.tsx` (using DOM/HTML components) + +## OAuth Guided Mode (Core Feature) + +### What is the Auth Debugger? + +The "Auth Debugger" (guided mode) in the web client is **not** an optional debug tool - it's a **core feature** that provides two modes of OAuth flow: + +1. **Guided Flow** (Step-by-Step): + - Breaks OAuth into discrete, manually-progressible steps + - User clicks "Next" to advance through each step + - Full state visibility at each step (metadata, client info, tokens, etc.) + - Allows inspection and debugging of OAuth flow + - Steps: `metadata_discovery` → `client_registration` → `authorization_redirect` → `authorization_code` → `token_request` → `complete` + +2. **Quick Flow** (Automatic): + - Automatically progresses through all OAuth steps + - Still uses the state machine internally + - Redirects to authorization URL automatically + - Returns to callback with authorization code + +### How It Works + +**Components**: + +- **`OAuthStateMachine`**: Manages step-by-step progression through OAuth flow +- **`GuidedInspectorOAuthClientProvider`** (shared: `GuidedNodeOAuthClientProvider`): Extended provider that: + - Uses guided redirect URL (`/oauth/callback/guided` instead of `/oauth/callback`) + - Saves server OAuth metadata to storage for UI display + - Provides `getServerMetadata()` and `saveServerMetadata()` methods +- **`AuthGuidedState`**: Comprehensive state object tracking all OAuth data: + - Current step (`oauthStep`) + - OAuth metadata, client info, tokens + - Authorization URL, code, errors + - Resource metadata, validation errors + +**State Machine Steps** (Detailed): + +1. **`metadata_discovery`**: **RFC 8414 Discovery** - Client discovers authorization server metadata + - Always client-initiated (never uses server-provided metadata from MCP capabilities) + - Calls SDK `discoverOAuthProtectedResourceMetadata()` which makes HTTP request to `/.well-known/oauth-protected-resource` + - Calls SDK `discoverAuthorizationServerMetadata()` which makes HTTP request to `/.well-known/oauth-authorization-server` + - The SDK methods handle the actual HTTP requests to well-known endpoints + - Discovery Flow: + 1. Attempts to discover resource metadata from the MCP server URL + 2. If resource metadata contains `authorization_servers`, uses the first one; otherwise defaults to MCP server base URL + 3. Discovers OAuth authorization server metadata from the determined authorization server URL + 4. Uses discovered metadata for client registration and authorization +2. **`client_registration`**: **Registers client** (static, DCR, or CIMD) + - First tries preregistered/static client information (from config) + - Falls back to Dynamic Client Registration (DCR) if no static client available + - If `clientMetadataUrl` is provided, uses CIMD (Client ID Metadata Documents) mode + - Implementation pattern: + ```typescript + // Try Static client first, with DCR as fallback + let fullInformation = await context.provider.clientInformation(); + if (!fullInformation) { + fullInformation = await registerClient(context.serverUrl, { + metadata, + clientMetadata, + }); + context.provider.saveClientInformation(fullInformation); + } + ``` +3. **`authorization_redirect`**: Generates authorization URL with PKCE + - Calls SDK `startAuthorization()` which generates PKCE code challenge + - Builds authorization URL with all required parameters + - Saves code verifier for later token exchange +4. **`authorization_code`**: User provides authorization code (manual entry or callback) + - Validates authorization code input + - In guided mode, waits for user to enter code or receive via callback +5. **`token_request`**: Exchanges code for tokens + - Calls SDK `exchangeAuthorization()` with authorization code and code verifier + - Receives OAuth tokens (access_token, refresh_token, etc.) + - Saves tokens to storage +6. **`complete`**: Final state with tokens + - OAuth flow complete + - Tokens available for use in requests + +**Why It's Core**: + +- Provides transparency into OAuth flow (critical for debugging) +- Allows manual intervention at each step +- Shows full OAuth state (metadata, client info, tokens) +- Essential for troubleshooting OAuth issues +- Users expect this level of visibility in a developer tool + +**InspectorClient Integration**: + +- InspectorClient should support both automatic and guided modes +- Guided mode should expose state machine state via events/API +- CLI/TUI can use guided mode for step-by-step OAuth flow +- State machine should be part of initial implementation, not a future enhancement + +### OAuth Mode Implementation Details + +#### DCR (Dynamic Client Registration) Support + +**Behavior**: + +- ✅ Tries preregistered/static client info first (from Zustand store, set via config) +- ✅ Falls back to DCR via SDK `registerClient()` if no static client is found +- ✅ Client information is stored in Zustand store after registration + +**Storage**: + +- Preregistered clients: Stored in Zustand store as `preregisteredClientInformation` +- Dynamically registered clients: Stored in Zustand store as `clientInformation` +- The `clientInformation()` method checks preregistered first, then dynamic + +#### RFC 8414 Authorization Server Metadata Discovery + +**Behavior**: + +- ✅ Always initiates discovery client-side (never uses server-provided metadata from MCP capabilities) +- ✅ Discovers resource metadata from `/.well-known/oauth-protected-resource` via SDK `discoverOAuthProtectedResourceMetadata()` +- ✅ Discovers OAuth authorization server metadata from `/.well-known/oauth-authorization-server` via SDK `discoverAuthorizationServerMetadata()` +- ✅ No code path uses server-provided metadata from MCP server capabilities +- ✅ SDK methods handle the actual HTTP requests to well-known endpoints + +**Discovery Flow**: + +1. Attempts to discover resource metadata from the MCP server URL +2. If resource metadata contains `authorization_servers`, uses the first one; otherwise defaults to MCP server base URL +3. Discovers OAuth authorization server metadata from the determined authorization server URL +4. Uses discovered metadata for client registration and authorization + +**Note**: This is RFC 8414 discovery (client discovering server endpoints), not CIMD. CIMD is a separate concept (server discovering client information via URL-based client IDs). + +#### CIMD (Client ID Metadata Documents) Support + +**Status**: ✅ **Supported** (new in InspectorClient, not in current web client) + +**What CIMD Is**: + +- CIMD (Client ID Metadata Documents, SEP-991) is the DCR replacement introduced in the November 2025 MCP spec +- The client publishes its metadata at a URL (e.g., `https://inspector.app/.well-known/oauth-client-metadata`) +- That URL becomes the `client_id` (instead of a random string from DCR) +- The authorization server fetches that URL to discover client information (name, redirect_uris, etc.) +- This is "reverse discovery" - the server discovers the client, not the client discovering the server + +**How InspectorClient Supports CIMD**: + +- User provides `clientMetadataUrl` in OAuth config +- `NodeOAuthClientProvider` sets `clientMetadataUrl` in `clientMetadata` +- SDK checks for CIMD support and uses URL-based client ID if supported +- Falls back to DCR if authorization server doesn't support CIMD + +**What's Required for CIMD**: + +1. Publish client metadata at a publicly accessible URL +2. Set `clientMetadataUrl` in OAuth config +3. The authorization server must support `client_id_metadata_document_supported: true` + +### OAuth Flow Descriptions + +#### Automatic Flow (Quick Mode) + +1. **Configuration**: User provides OAuth config (clientId, clientSecret, scope, clientMetadataUrl) via `InspectorClientOptions` or `setOAuthConfig()` +2. **Storage**: Config saved to Zustand store as `preregisteredClientInformation` (if static client provided) +3. **Initiation**: User calls `authenticate()` (or `authenticateGuided()` for guided mode). We do not auto-initiate on 401; callers authenticate first, then connect. +4. **SDK Handles**: + - Authorization server metadata discovery (RFC 8414 - always client-initiated) + - Client registration (static, DCR, or CIMD based on config) + - Authorization redirect (generates PKCE challenge, builds authorization URL) +5. **Navigation**: Authorization URL dispatched via `oauthAuthorizationRequired` event +6. **User Action**: User navigates to authorization URL (via callback handler, browser open, or manual navigation) +7. **Callback**: Authorization server redirects to callback URL with authorization code +8. **Processing**: User provides authorization code via `completeOAuthFlow()` +9. **Token Exchange**: SDK exchanges code for tokens (using stored code verifier) +10. **Storage**: Tokens saved to Zustand store +11. **Connect**: User calls `connect()`. Transport is created with `authProvider` (tokens in storage). SDK injects tokens and handles 401 (auth, retry) inside the transport. We do not retry connect or requests after OAuth; the transport does. + +#### Guided Flow (Step-by-Step Mode) + +1. **Initiation**: User calls `authenticateGuided()` to begin guided flow +2. **State Machine**: `OAuthStateMachine` executes steps manually +3. **Step Control**: Each step can be viewed and manually progressed via `proceedOAuthStep()` +4. **State Visibility**: Full OAuth state available via `getOAuthState()` and `oauthStepChange` events +5. **Events**: `oauthStepChange` event dispatched on each step transition with current state + - Event detail includes: `step`, `previousStep`, and `state` (partial state update) + - UX layer can listen to update UI, enable/disable buttons, show step-specific information +6. **Authorization**: Authorization URL generated and dispatched via `oauthAuthorizationRequired` event +7. **Code Entry**: Authorization code can be entered manually or received via callback +8. **Completion**: `oauthComplete` event dispatched, full state visible, tokens stored in Zustand store + +## InspectorClient Integration + +### New Options + +```typescript +export interface InspectorClientOptions { + // ... existing options ... + + /** + * OAuth configuration + */ + oauth?: { + /** + * Preregistered client ID (optional, will use DCR if not provided) + * If clientMetadataUrl is provided, this is ignored (CIMD mode) + */ + clientId?: string; + + /** + * Preregistered client secret (optional, only if client requires secret) + * If clientMetadataUrl is provided, this is ignored (CIMD mode) + */ + clientSecret?: string; + + /** + * Client metadata URL for CIMD (Client ID Metadata Documents) mode + * If provided, enables URL-based client IDs (SEP-991) + * The URL becomes the client_id, and the authorization server fetches it to discover client metadata + */ + clientMetadataUrl?: string; + + /** + * OAuth scope (optional, will be discovered if not provided) + */ + scope?: string; + + /** + * Redirect URL for OAuth callback (required for OAuth flow) + * For CLI/TUI, this should be a local server URL or manual callback URL + */ + redirectUrl?: string; + + /** + * Storage path for OAuth data (default: ~/.mcp-inspector/oauth/) + */ + storagePath?: string; + }; +} +``` + +### New Methods + +```typescript +class InspectorClient { + // OAuth configuration + setOAuthConfig(config: { + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; // For CIMD mode + scope?: string; + redirectUrl?: string; + }): void; + + // OAuth flow initiation (normal mode) + /** + * Initiates OAuth flow (user-initiated or 401-triggered). Both paths use this method. + * Returns the authorization URL. Dispatches 'oauthAuthorizationRequired' event. + */ + async authenticate(): Promise; + + /** + * Completes OAuth flow with authorization code + * @param authorizationCode - Authorization code from OAuth callback + * Dispatches 'oauthComplete' event on success + * Dispatches 'oauthError' event on failure + */ + async completeOAuthFlow(authorizationCode: string): Promise; + + // OAuth state management + /** + * Gets current OAuth tokens (if authorized) + */ + getOAuthTokens(): OAuthTokens | undefined; + + /** + * Clears OAuth tokens and client information + */ + clearOAuthTokens(): void; + + /** + * Checks if client is currently OAuth authorized + */ + isOAuthAuthorized(): boolean; + + /** + * Initiates OAuth flow in guided mode (step-by-step, state machine). + * Returns the authorization URL. Dispatches 'oauthAuthorizationRequired' and 'oauthStepChange' events. + */ + async authenticateGuided(): Promise; + + // Guided mode state management + /** + * Get current OAuth state machine state (for guided mode) + * Returns undefined if not in guided mode + */ + getOAuthState(): AuthGuidedState | undefined; + + /** + * Get current OAuth step (for guided mode) + * Returns undefined if not in guided mode + */ + getOAuthStep(): OAuthStep | undefined; + + /** + * Manually progress to next step in guided OAuth flow + * Only works when in guided mode + * Dispatches 'oauthStepChange' event on step transition + */ + async proceedOAuthStep(): Promise; +} +``` + +### OAuth Flow Initiation + +**Two Modes of Initiation**: + +1. **Normal Mode** (User-Initiated): + - User calls `client.authenticate()` explicitly + - Uses SDK's `auth()` function internally + - Returns authorization URL + - Dispatches `oauthAuthorizationRequired` event + - Client-side (CLI/TUI) listens for events and handles navigation + - User completes OAuth (e.g. via callback), then calls `completeOAuthFlow(code)`, then `connect()`. The transport uses `authProvider` to inject tokens; the SDK handles 401 (auth, retry) internally. We do not automatically retry connect or requests after OAuth. + +2. **Guided Mode** (User-Initiated): + - User calls `client.authenticateGuided()` explicitly + - Uses state machine for step-by-step control + - Dispatches `oauthStepChange` events as flow progresses + - Returns authorization URL + - Dispatches `oauthAuthorizationRequired` event + - Client-side listens for events and handles navigation + - Same flow as normal: complete OAuth, then `connect()`. + +**Event-Driven Architecture**: + +```typescript +// InspectorClient dispatches events for OAuth flow +this.dispatchTypedEvent("oauthAuthorizationRequired", { + url: authorizationUrl, +}); + +this.dispatchTypedEvent("oauthComplete", { tokens }); +this.dispatchTypedEvent("oauthError", { error }); + +// InspectorClient dispatches events for guided flow +this.dispatchTypedEvent("oauthStepChange", { + step: OAuthStep, + previousStep?: OAuthStep, + state: Partial +}); + +// Client-side (CLI/TUI) listens for events +client.addEventListener("oauthAuthorizationRequired", (event) => { + const { url } = event.detail; + // Handle navigation (print URL, open browser, etc.) + // Wait for user to provide authorization code + // Call client.completeOAuthFlow(code) +}); + +// For guided mode, listen for step changes +client.addEventListener("oauthStepChange", (event) => { + const { step, state } = event.detail; + // Update UI to show current step and state + // Enable/disable "Continue" button based on step +}); +``` + +**Event-Driven Architecture**: + +- InspectorClient dispatches `oauthAuthorizationRequired` events +- Callers are responsible for registering event listeners to handle the authorization URL +- CLI/TUI applications should register listeners to display the URL (e.g., print to console, show in UI) +- No default console output - callers must explicitly handle events + +**401 Error Handling (legacy; see authProvider migration below)**: + +InspectorClient previously detected 401 in `connect()` and request methods, called `authenticate()`, stored a pending request, and retried after OAuth. This custom logic has been **removed**. 401 handling is now delegated to the SDK transport via `authProvider`. + +### Token Injection and authProvider (Current Implementation) + +**Integration Point**: For HTTP-based transports (SSE, streamable-http), we pass an **`authProvider`** (`OAuthClientProvider`) into `createTransport`. The SDK injects tokens and handles 401 via the provider; we do not manually add `Authorization` headers or detect 401. + +- **Transport creation**: All transport creation happens in **`connect()`** (single place for create, wrap, attach). When OAuth is configured, we create a provider via `createOAuthProvider("normal" | "guided")` and pass it as `authProvider` to `createTransport`; the provider is created async there. +- **Flow**: Callers **authenticate first**, then connect. Run `authenticate()` or `authenticateGuided()`, complete OAuth with `completeOAuthFlow(code)`, then call `connect()`. The transport uses `authProvider` to inject tokens; the SDK handles 401 (auth, retry) inside the transport. +- **No connect-time 401 retry**: We do not catch 401 on `connect()` or retry. If `connect()` is called without tokens, the transport/SDK may throw (e.g. `Unauthorized`). Callers must run `authenticate()` (or guided flow), then retry `connect()`. +- **Request methods**: We no longer wrap `listTools`, `listResources`, etc. with 401 detection or retry. The transport handles 401 for all requests when `authProvider` is used. +- **Removed**: `getOAuthToken` callback, `createOAuthFetchWrapper`, `is401Error`, `handleRequestWithOAuth`, `pendingOAuthRequest`, and connect-time 401 catch block. + +## Implementation Plan + +### Phase 1: Extract and Abstract OAuth Components + +**Goal**: Copy general-purpose OAuth code to shared package with abstractions (leaving web client code unchanged) + +1. **Create Zustand Store** (`shared/auth/store.ts`) + - Install Zustand dependency (with persist middleware support) + - Create `createOAuthStore()` factory function + - Implement browser storage adapter (sessionStorage) for Zustand persist + - Implement file storage adapter (Node.js fs) for Zustand persist + - Export vanilla API (`getOAuthStore()`) only (no React dependencies) + - React hooks (if needed) would be in separate `shared/react/auth/hooks.ts` file + - Add `getServerSpecificKey()` helper + +2. **Create Redirect URL Abstraction** (`shared/auth/providers.ts` - part 1) + - Define `RedirectUrlProvider` interface with `getRedirectUrl()` and `getDebugRedirectUrl()` methods + - Implement `BrowserRedirectUrlProvider` (returns normal and debug URLs based on `window.location.origin`) + - Implement `LocalServerRedirectUrlProvider` (constructor takes `port`, returns normal and debug URLs) + - Implement `ManualRedirectUrlProvider` (constructor takes `baseUrl`, returns normal and debug URLs) + - **Key**: Both URLs are available, both are registered with OAuth server, mode determines which is used for current flow + +3. **Create Navigation Abstraction** (`shared/auth/providers.ts` - part 2) + - Define `OAuthNavigation` interface + - Implement `BrowserNavigation` + - Implement `ConsoleNavigation` + - Implement `CallbackNavigation` + +4. **Create Base OAuth Provider** (`shared/auth/providers.ts` - part 3) + - Create `BaseOAuthClientProvider` abstract class + - Implement shared SDK interface methods + - Move storage, redirect URL, and navigation logic to base class + - Add support for `clientMetadataUrl` (CIMD mode) + +5. **Create Provider Implementations** (`shared/auth/providers.ts` - part 4) + - Create `BrowserOAuthClientProvider` (extends base, uses sessionStorage directly - for web client reference) + - Create `NodeOAuthClientProvider` (extends base, uses Zustand store - for InspectorClient/CLI/TUI) + - Support all three client identification modes: static, DCR, CIMD + +6. **Copy OAuth Utilities** (`shared/auth/utils.ts`) + - Copy `parseOAuthCallbackParams()` from `client/src/utils/oauthUtils.ts` + - Copy `generateOAuthErrorDescription()` from `client/src/utils/oauthUtils.ts` + - Adapt `generateOAuthState()` to support both browser and Node.js + +7. **Copy OAuth State Machine** (`shared/auth/state-machine.ts`) + - Copy `OAuthStateMachine` class from `client/src/lib/oauth-state-machine.ts` + - Copy `oauthTransitions` object + - Update to use abstract `OAuthClientProvider` instead of `DebugInspectorOAuthClientProvider` + +8. **Copy Scope Discovery** (`shared/auth/discovery.ts`) + - Copy `discoverScopes()` from `client/src/lib/auth.ts` + +9. **Create Types Module** (`shared/auth/types.ts`) + - Copy `CallbackParams` type from `client/src/utils/oauthUtils.ts` + - Re-export SDK OAuth types as needed + +### Phase 2: (Skipped - Web Client Unchanged) + +**Note**: Web client OAuth code remains in place and is not modified at this time. Future migration options: + +- Option A: Web client uses shared auth code directly +- Option B: Web client relies on InspectorClient for OAuth +- Option C: Hybrid approach (some components use shared code, others use InspectorClient) + +These options should be considered in the design but not implemented now. + +### Phase 3: Integrate OAuth into InspectorClient + +**Goal**: Add OAuth support to InspectorClient with both direct and indirect initiation + +1. **Add OAuth Options to InspectorClientOptions** + - Add `oauth` configuration option with support for `clientMetadataUrl` (CIMD) + - Define OAuth configuration interface + - Support all three client identification modes + +2. **Add OAuth Provider to InspectorClient** + - Store OAuth config + - Create `NodeOAuthClientProvider` instances on-demand based on mode (lazy initialization) + - Normal mode provider created by default (for automatic flows) + - Guided mode provider created when `authenticateGuided()` is called + - Initialize Zustand store for OAuth state + - **Important**: Both redirect URLs are registered with OAuth server (allows switching modes without re-registering) + - Both callback handlers are mounted (normal at `/oauth/callback`, guided at `/oauth/callback/guided`) + - The provider's mode determines which URL is used for the current flow + +3. **Implement OAuth Methods** + - Implement `setOAuthConfig()` (supports clientMetadataUrl for CIMD) + - Implement `authenticate()` (direct and 401-triggered initiation, uses normal-mode provider) + - Implement `completeOAuthFlow()` + - Implement `getOAuthTokens()` + - Implement `clearOAuthTokens()` + - Implement `isOAuthAuthorized()` + - Implement guided mode state management methods: + - `getOAuthState()` - Get current OAuth state machine state (returns undefined if not in guided mode) + - `getOAuthStep()` - Get current OAuth step (returns undefined if not in guided mode) + - `proceedOAuthStep()` - Manually progress to next step (only works in guided mode, dispatches `oauthStepChange` event) + - **Note**: Guided mode is initiated via `authenticateGuided()`, which creates a provider with `mode="guided"` and initiates the flow + - **Note**: When creating `NodeOAuthClientProvider`, pass the `mode` parameter. Both redirect URLs are registered, but the provider uses the URL matching its mode for the current flow. + +4. **~~Add 401 Error Detection~~** (removed in authProvider migration) + - We no longer use `is401Error()` or detect 401 in connect/request methods. The transport handles 401 via `authProvider`. + +5. **Add OAuth Flow Initiation (User-Initiated Only)** + - User calls `authenticate()` or `authenticateGuided()` first, then `completeOAuthFlow(code)`, then `connect()`. We do not catch 401 or retry; the transport uses `authProvider` for token injection and 401 handling. + +6. **Add Guided Mode** + - Implement `authenticateGuided()` for step-by-step OAuth flow + - Create provider with `mode="guided"` when `authenticateGuided()` is called + - Dispatch `oauthAuthorizationRequired` and `oauthStepChange` events as state machine progresses + +7. **Add Token Injection (via authProvider)** + - For HTTP-based transports with OAuth, pass `authProvider` into `createTransport`. The SDK injects tokens and handles 401. We do not manually add `Authorization` headers. All transport creation happens in `connect()`. + - Refresh tokens if expired (future enhancement) – handled by SDK/authProvider when supported. + +8. **Add OAuth Events** + - Add `oauthAuthorizationRequired` event (dispatches authorization URL, mode, optional originalError) + - Add `oauthComplete` event (dispatches tokens) + - Add `oauthError` event (dispatches error) + - Add `oauthStepChange` event (dispatches step, previousStep, state) - for guided mode + - All events are event-driven for client-side integration + - Callers must register event listeners to handle `oauthAuthorizationRequired` events + +### Phase 4: Testing + +**Goal**: Comprehensive testing of OAuth support + +1. **Unit Tests for Shared OAuth Components** + - Test storage adapters (Browser, Memory, File) + - Test redirect URL providers + - Test navigation handlers + - Test OAuth utilities + - Test state machine transitions + - Test scope discovery + +2. **Integration Tests for InspectorClient OAuth** + - Test OAuth configuration + - Test 401 error detection and OAuth flow initiation + - Test token injection in HTTP transports + - Test OAuth flow completion + - Test token storage and retrieval + - Test OAuth error handling + +3. **End-to-End Tests with OAuth Test Server** + - Test full OAuth flow with test server (see "OAuth Test Server Infrastructure" below) + - Test static/preregistered client mode + - Test DCR (Dynamic Client Registration) mode + - Test CIMD (Client ID Metadata Documents) mode + - Test scope discovery + - Test token refresh (if supported) + - Test OAuth cleanup + - Test 401 error handling and automatic retry + +4. **Web Client Regression Tests** + - Verify all existing OAuth tests still pass + - Test normal OAuth flow + - Test debug OAuth flow + - Test OAuth callback handling + +## OAuth Test Server Infrastructure + +### Overview + +OAuth testing requires a full OAuth 2.1 authorization server that can: + +- Return 401 errors on MCP requests (to trigger OAuth flow initiation) +- Serve OAuth metadata endpoints (RFC 8414 discovery) +- Handle all three client identification modes (static, DCR, CIMD) +- Support authorization and token exchange flows +- Verify Bearer tokens on protected MCP endpoints + +**Decision**: Use **better-auth** (or similar third-party OAuth library) for the test server rather than implementing OAuth from scratch. This provides: + +- Faster implementation +- Production-like OAuth behavior +- Better security coverage +- Reduced maintenance burden + +### Integration with Existing Test Infrastructure + +The OAuth test server will integrate with the existing `composable-test-server.ts` infrastructure: + +1. **Extend `ServerConfig` Interface** (`shared/test/composable-test-server.ts`): + + ```typescript + export interface ServerConfig { + // ... existing config ... + oauth?: { + /** + * Whether OAuth is enabled for this test server + */ + enabled: boolean; + + /** + * OAuth authorization server issuer URL + * Used for metadata endpoints and token issuance + */ + issuerUrl: URL; + + /** + * List of scopes supported by this authorization server + */ + scopesSupported?: string[]; + + /** + * If true, MCP endpoints require valid Bearer token + * Returns 401 Unauthorized if token is missing or invalid + */ + requireAuth?: boolean; + + /** + * Static/preregistered clients for testing + * These clients are pre-configured and don't require DCR + */ + staticClients?: Array<{ + clientId: string; + clientSecret?: string; + redirectUris?: string[]; + }>; + + /** + * Whether to support Dynamic Client Registration (DCR) + * If true, exposes /register endpoint for client registration + */ + supportDCR?: boolean; + + /** + * Whether to support CIMD (Client ID Metadata Documents) + * If true, server will fetch client metadata from clientMetadataUrl + */ + supportCIMD?: boolean; + + /** + * Token expiration time in seconds (default: 3600) + */ + tokenExpirationSeconds?: number; + + /** + * Whether to support refresh tokens (default: true) + */ + supportRefreshTokens?: boolean; + }; + } + ``` + +2. **Extend `TestServerHttp`** (`shared/test/test-server-http.ts`): + - Install better-auth OAuth router on Express app (before MCP routes) + - Add Bearer token verification middleware on `/mcp` endpoint + - Return 401 if `requireAuth: true` and no valid token present + - Serve OAuth metadata endpoints: + - `/.well-known/oauth-authorization-server` (RFC 8414) + - `/.well-known/oauth-protected-resource` (RFC 8414) + - Handle client registration endpoint (`/register`) if DCR enabled + - Handle authorization endpoint (`/authorize`) - see "Authorization Endpoint" below + - Handle token endpoint (`/token`) + - Handle token revocation endpoint (`/revoke`) if supported + + **Authorization Endpoint Implementation**: + - better-auth provides the authorization endpoint (`/oauth/authorize` or similar) + - For automated testing, create a **test authorization page** that: + - Accepts authorization requests (client_id, redirect_uri, scope, state, code_challenge) + - Automatically approves the request (no user interaction required) + - Redirects to `redirect_uri` with authorization code and state + - This allows tests to programmatically complete the OAuth flow without browser automation + - For true E2E tests requiring user interaction, better-auth's built-in UI can be used + +3. **Create OAuth Test Fixtures** (`shared/test/test-server-fixtures.ts`): + + ```typescript + /** + * Creates a test server configuration with OAuth enabled + */ + export function createOAuthTestServerConfig(options: { + requireAuth?: boolean; + scopesSupported?: string[]; + staticClients?: Array<{ clientId: string; clientSecret?: string }>; + supportDCR?: boolean; + supportCIMD?: boolean; + }): ServerConfig; + + /** + * Creates OAuth configuration for InspectorClient tests + */ + export function createOAuthClientConfig(options: { + mode: "static" | "dcr" | "cimd"; + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + redirectUrl: string; + }): InspectorClientOptions["oauth"]; + + /** + * Helper function to programmatically complete OAuth authorization + * Makes HTTP GET request to authorization URL and extracts authorization code + * @param authorizationUrl - The authorization URL from oauthAuthorizationRequired event + * @returns Authorization code extracted from redirect URL + */ + export async function completeOAuthAuthorization( + authorizationUrl: URL, + ): Promise; + ``` + +### Authorization Endpoint and Test Flow + +**Authorization Endpoint**: +The test server will provide a functioning OAuth authorization endpoint (via better-auth) that: + +1. **Accepts Authorization Requests**: The endpoint receives authorization requests with: + - `client_id`: The OAuth client identifier + - `redirect_uri`: Where to redirect after approval + - `scope`: Requested OAuth scopes + - `state`: CSRF protection state parameter + - `code_challenge`: PKCE code challenge + - `response_type`: Always "code" for authorization code flow + +2. **Test Authorization Page**: For automated testing, the test server will provide a simple authorization page that: + - Automatically approves all authorization requests (no user interaction) + - Generates an authorization code + - Redirects to `redirect_uri` with the code and state parameter + - This allows tests to programmatically complete OAuth without browser automation + +3. **Programmatic Authorization Helper**: Tests can use a helper function to: + - Extract authorization URL from `oauthAuthorizationRequired` event + - Make HTTP GET request to authorization URL + - Parse redirect response to extract authorization code + - Call `client.completeOAuthFlow(authorizationCode)` to complete the flow + +**Example Test Flow**: + +```typescript +// 1. Configure test server with OAuth enabled +const server = new TestServerHttp({ + ...getDefaultServerConfig(), + oauth: { + enabled: true, + requireAuth: true, + staticClients: [{ clientId: "test-client", clientSecret: "test-secret" }], + }, +}); +await server.start(); + +// 2. Configure InspectorClient with OAuth +const client = new InspectorClient({ + serverUrl: server.url, + oauth: { + clientId: "test-client", + clientSecret: "test-secret", + redirectUrl: "http://localhost:3000/oauth/callback", + }, +}); + +// 3. Listen for OAuth authorization required event +let authUrl: URL | null = null; +client.addEventListener("oauthAuthorizationRequired", (event) => { + authUrl = event.detail.url; +}); + +// 4. Make MCP request (triggers 401, then OAuth flow) +try { + await client.listTools(); +} catch (error) { + // Expected: 401 error triggers OAuth flow +} + +// 5. Programmatically complete authorization +if (authUrl) { + // Make GET request to authorization URL (auto-approves in test server) + const response = await fetch(authUrl.toString(), { redirect: "manual" }); + const redirectUrl = response.headers.get("location"); + + // Extract authorization code from redirect URL + const redirectUrlObj = new URL(redirectUrl!); + const code = redirectUrlObj.searchParams.get("code"); + + // Complete OAuth flow + await client.completeOAuthFlow(code!); + + // 6. Retry original request (should succeed with token) + const tools = await client.listTools(); + expect(tools).toBeDefined(); +} +``` + +### Test Scenarios + +**Static Client Mode**: + +- Configure test server with `staticClients` +- Configure InspectorClient with matching `clientId`/`clientSecret` +- Test full OAuth flow without DCR +- Verify authorization endpoint auto-approves and redirects with code + +**DCR Mode**: + +- Configure test server with `supportDCR: true` +- Configure InspectorClient without `clientId` (triggers DCR) +- Test client registration, then full OAuth flow +- Verify DCR endpoint registers client, then authorization flow proceeds + +**CIMD Mode**: + +- Configure test server with `supportCIMD: true` +- Configure InspectorClient with `clientMetadataUrl` +- Test server fetches client metadata from URL +- Test full OAuth flow with URL-based client ID + +**401 Error Handling**: + +- Configure test server with `requireAuth: true` +- Make MCP request without token → expect 401 +- Verify `oauthAuthorizationRequired` event dispatched +- Programmatically complete OAuth flow (auto-approve authorization) +- Verify original request automatically retried with token + +**Token Verification**: + +- Configure test server with `requireAuth: true` +- Make MCP request with valid Bearer token → expect success +- Make MCP request with invalid/expired token → expect 401 + +### Implementation Steps + +1. **Install better-auth dependency** (or chosen OAuth library) + - Add to `shared/package.json` as dev dependency + +2. **Create OAuth test server wrapper** (`shared/test/oauth-test-server.ts`) + - Wrap better-auth configuration + - Integrate with Express app in `TestServerHttp` + - Handle static clients, DCR, CIMD modes + - Create test authorization page that auto-approves requests + - Provide helper function to programmatically extract authorization code from redirect + +3. **Extend `ServerConfig` interface** + - Add `oauth` configuration option + - Update `createMcpServer()` to handle OAuth config + +4. **Extend `TestServerHttp`** + - Install OAuth router before MCP routes + - Add Bearer token middleware + - Return 401 when `requireAuth: true` and token invalid + +5. **Create test fixtures** + - `createOAuthTestServerConfig()` + - `createOAuthClientConfig()` + - Helper functions for common OAuth test scenarios + +6. **Write integration tests** + - Test each client identification mode + - Test 401 error handling + - Test token verification + - Test full OAuth flow end-to-end + +## Storage Strategy + +### InspectorClient Storage (Node.js) - Zustand with File Persistence + +**Location**: `~/.mcp-inspector/oauth/state.json` (single Zustand store file) + +**Storage Format**: + +```json +{ + "state": { + "servers": { + "https://example.com/mcp": { + "tokens": { "access_token": "...", "refresh_token": "..." }, + "clientInformation": { "client_id": "...", ... }, + "preregisteredClientInformation": { "client_id": "...", ... }, + "codeVerifier": "...", + "scope": "...", + "serverMetadata": { ... } + } + } + }, + "version": 0 +} +``` + +**Benefits**: + +- Single file for all OAuth state across all servers +- Zustand handles serialization/deserialization automatically +- Atomic writes via Zustand's persist middleware +- Type-safe state management +- Easier to backup/restore (one file) + +**Security Considerations**: + +- File contains sensitive data (tokens, secrets) +- Use restrictive file permissions (600) for state.json +- Consider encryption for production use (future enhancement) + +### Web Client Storage (Browser) + +**Location**: Browser `sessionStorage` (unchanged - web client code not modified) + +**Key Format**: `[${serverUrl}] ${baseKey}` (unchanged) + +## Navigation Strategy + +### InspectorClient Navigation + +**Event-Driven Architecture**: InspectorClient dispatches `oauthAuthorizationRequired` events. Callers must register event listeners to handle these events. + +**UX Layer Options**: + +1. **Console Output**: Register event listener to print URL, wait for user to paste callback URL or authorization code +2. **Browser Open**: Register event listener to open URL in default browser (if available) +3. **Custom Navigation**: Register event listener to handle redirect in any custom way + +**Example Flow**: + +``` +1. InspectorClient detects 401 error +2. Initiates OAuth flow +3. Dispatches 'oauthAuthorizationRequired' event +4. If no listener registered, prints: "Please navigate to: https://auth.example.com/authorize?..." +5. UX layer listens for event and handles navigation (print, open browser, etc.) +6. Waits for user to provide authorization code or callback URL +7. User calls client.completeOAuthFlow(code) +8. Dispatches 'oauthComplete' event +9. Retries original request +``` + +## Error Handling + +### OAuth Flow Errors + +- **Discovery Errors**: Log and continue (fallback to server URL) +- **Registration Errors**: Log and throw (user must provide static client) +- **Authorization Errors**: Dispatch `oauthError` event, throw error +- **Token Exchange Errors**: Dispatch `oauthError` event, throw error + +### 401 Error Handling + +- **Transport / authProvider**: The SDK transport handles 401 when `authProvider` is used (token injection, auth, retry). InspectorClient does not detect 401 or retry connect/requests. +- **Caller flow**: Authenticate first (`authenticate()` or `authenticateGuided()`), complete OAuth, then `connect()`. If `connect()` is called without tokens, the transport may throw; callers retry `connect()` after OAuth. +- **Event-Based**: Dispatch events for UI to handle OAuth flow (`oauthAuthorizationRequired`, etc.) + +## Migration Notes + +### authProvider Migration (2025) + +InspectorClient now uses the SDK’s **`authProvider`** (`OAuthClientProvider`) for OAuth on HTTP transports (SSE, streamable-http) instead of a `getOAuthToken` callback and custom 401 handling. + +**Summary of changes**: + +- **Transport**: `createTransport` accepts `authProvider` (optional). For SSE and streamable-http with OAuth, we pass the provider; the SDK injects tokens and handles 401. `getOAuthToken` and OAuth-specific fetch wrapping have been removed. +- **InspectorClient**: All transport creation happens in `connect()` (single place for create, wrap, attach); for HTTP+OAuth the provider is created async there. We pass `authProvider` when creating the transport. On `disconnect()`, we null out the transport so the next `connect()` creates a fresh one. Removed: `is401Error`, `handleRequestWithOAuth`, connect-time 401 catch, and `pendingOAuthRequest`. +- **Caller flow**: **Authenticate first, then connect.** Call `authenticate()` or `authenticateGuided()`, have the user complete OAuth, call `completeOAuthFlow(code)`, then `connect()`. We no longer detect 401 on `connect()` or retry internally; the transport handles 401 when `authProvider` is used. +- **Guided mode**: Unchanged. Use `authenticateGuided()` → `completeOAuthFlow()` → `connect()`. The same provider (or shared storage) is used as `authProvider` when connecting after guided auth. +- **Custom headers**: Config `headers` / `requestInit` / `eventSourceInit` continue to be passed at transport creation and are merged with `authProvider` by the SDK. + +See **"Token Injection and authProvider"** above for details. + +### Web Client Migration (Future Consideration) + +**Current State**: Web client OAuth code remains unchanged and in place. + +**Future Migration Options** (not implemented now, but design should support): + +1. **Option A: Web Client Uses Shared Auth Code Directly** + - Web client imports from `shared/auth/` + - Uses `BrowserOAuthClientProvider` from shared + - Uses Zustand store with sessionStorage adapter + - Minimal changes to web client code + +2. **Option B: Web Client Relies on InspectorClient for OAuth** + - Web client creates `InspectorClient` instance + - Uses InspectorClient's OAuth methods and events + - InspectorClient handles all OAuth logic + - Web client UI listens to InspectorClient events + +3. **Option C: Hybrid Approach** + - Some components use shared auth code directly (e.g., utilities, state machine) + - Other components use InspectorClient (e.g., OAuth flow initiation) + - Flexible migration path + +**Design Considerations**: + +- Shared auth code should be usable independently (not require InspectorClient) +- InspectorClient should be usable independently (not require web client) +- React hooks in `shared/react/auth/hooks.ts` can be shared (pure logic, no rendering) +- React UI components cannot be shared (TUI uses Ink, web uses DOM) - each client implements its own + +### Breaking Changes + +- **None Expected**: All changes are additive (new shared code, new InspectorClient features) +- **Web Client**: Remains completely unchanged +- **API Compatibility**: InspectorClient API is additive only + +## Future Enhancements + +1. **Token Refresh**: Implemented via the SDK's `authProvider` when `refresh_token` is available; the provider persists and uses refresh tokens for automatic refresh after 401. No additional work required for standard flows. +2. **Encrypted Storage**: Encrypt sensitive OAuth data in Zustand store +3. **Multiple OAuth Providers**: Support multiple OAuth configurations per InspectorClient +4. **Web Client Migration**: Consider migrating web client to use shared auth code or InspectorClient + +## References + +- Web client OAuth implementation (unchanged): `client/src/lib/auth.ts`, `client/src/lib/oauth-state-machine.ts`, `client/src/utils/oauthUtils.ts` +- [MCP SDK OAuth APIs](https://github.com/modelcontextprotocol/typescript-sdk) - SDK OAuth client and server APIs +- [OAuth 2.1 Specification](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1) - OAuth 2.1 protocol specification +- [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) - OAuth 2.0 Authorization Server Metadata +- [Zustand Documentation](https://github.com/pmndrs/zustand) - Zustand state management library +- [Zustand Persist Middleware](https://github.com/pmndrs/zustand/blob/main/docs/integrations/persisting-store-data.md) - Zustand persistence middleware +- [SEP-991: Client ID Metadata Documents](https://modelcontextprotocol.io/specification/security/oauth/#client-id-metadata-documents) - CIMD specification diff --git a/docs/shared-code-architecture.md b/docs/shared-code-architecture.md new file mode 100644 index 000000000..a1009ce2a --- /dev/null +++ b/docs/shared-code-architecture.md @@ -0,0 +1,533 @@ +# Shared Code Architecture for MCP Inspector + +## Overview + +This document describes a shared code architecture that enables code reuse across the MCP Inspector's three user interfaces: the **CLI**, **TUI** (Terminal User Interface), and **web client** (likely targeting v2). The shared codebase approach prevents the feature drift and maintenance burden that can occur when each app has a separate implementation. + +### Environment Isolation + +The architecture uses **environment isolation** to separate portable JavaScript from environment-specific code (Node.js vs. browser). `InspectorClient` is portable and accepts **injected dependencies** (seams) for environment-specific behavior: + +- **CLI/TUI (Node)**: Inject Node-specific implementations (`createTransportNode`, `NodeOAuthStorage`, file-based logging) +- **Web client (Browser)**: Inject browser-specific implementations (`createRemoteTransport`, `BrowserOAuthStorage` or `RemoteOAuthStorage`, remote logging) + +`InspectorClient` remains unaware of which environment it's running in—it just uses the injected dependencies. This allows the same code to run in Node (CLI, TUI) and browser (web client). See [environment-isolation.md](environment-isolation.md) for detailed design. + +### Motivation + +Previously, the CLI and web client had no shared code, leading to: + +- **Feature drift**: Implementations diverged over time +- **Maintenance burden**: Bug fixes and features had to be implemented twice +- **Inconsistency**: Different behavior across interfaces +- **Duplication**: Similar logic implemented separately in each interface + +Adding the TUI (as-is) with yet another separate implementation seemed problematic given the above. + +The shared code architecture addresses these issues by providing a single source of truth for MCP client operations that all three interfaces can use. + +## Proposed Architecture + +### Architecture Diagram + +![Shared Code Architecture](shared-code-architecture.svg) + +**Key concept**: Each environment (CLI, TUI, web client) injects environment-specific dependencies into `InspectorClient`: + +- **CLI/TUI**: Pass `environment` object with `transport: createTransportNode` (creates stdio, SSE, streamable-http transports directly in Node), `oauth.storage: NodeOAuthStorage` (file-based), `logger` (file-based pino logger) +- **Web client**: Pass `environment` object with `transport: createRemoteTransport` (creates `RemoteClientTransport` that talks to remote API server), `fetch: createRemoteFetch`, `logger: createRemoteLogger`, `oauth.storage: BrowserOAuthStorage` or `RemoteOAuthStorage` (sessionStorage or HTTP API) + +`InspectorClient` uses these injected dependencies to create transports and manage OAuth, remaining portable across all environments. + +### Project Structure + +``` +inspector/ +├── cli/ # CLI workspace (uses shared code) +├── tui/ # TUI workspace (uses shared code) +├── client/ # Web client workspace (to be migrated) +├── server/ # Proxy server workspace +├── shared/ # Shared code workspace package +│ ├── mcp/ # MCP client/server interaction +│ ├── react/ # Shared React code +│ ├── json/ # JSON utilities +│ └── test/ # Test fixtures and harness servers +└── package.json # Root workspace config +``` + +### Shared Package (`@modelcontextprotocol/inspector-shared`) + +The `shared/` directory is a **workspace package** that: + +- **Private** (`"private": true`) - internal-only, not published +- **Built separately** - compiles to `shared/build/` with TypeScript declarations +- **Referenced via package name** - workspaces import using `@modelcontextprotocol/inspector-shared/*` +- **Uses TypeScript Project References** - CLI and TUI reference shared for build ordering and type resolution +- **React peer dependency** - declares React 19.2.3 as peer dependency (consumers provide React) + +**Build Order**: Shared must be built before CLI and TUI (enforced via TypeScript Project References and CI workflows). + +## InspectorClient: The Core Shared Component + +### Overview + +`InspectorClient` (`shared/mcp/inspectorClient.ts`) is a comprehensive wrapper around the MCP SDK `Client` that manages the creation and lifecycle of the MCP client and transport. It provides: + +- **Unified Client Interface**: Single class handles all client operations +- **Client and Transport Lifecycle**: Manages creation, connection, and cleanup of MCP SDK `Client` and `Transport` instances +- **Message Tracking**: Automatically tracks all JSON-RPC messages (requests, responses, notifications) +- **Stderr Logging**: Captures and stores stderr output from stdio transports +- **Event-Driven Updates**: Uses `EventTarget` for reactive UI updates (cross-platform: works in browser and Node.js) +- **Server Data Management**: Automatically fetches and caches tools, resources, prompts, capabilities, server info, and instructions +- **State Management**: Manages connection status, message history, and server state +- **Transport Abstraction**: Works with all `Transport` types (stdio, SSE, streamable-http) +- **High-Level Methods**: Provides convenient wrappers for tools, resources, prompts, and logging + +![InspectorClient Details](inspector-client-details.svg) + +### Key Features + +**Connection Management:** + +- `connect()` - Establishes connection and optionally fetches server data +- `disconnect()` - Closes connection and clears server state +- Connection status tracking (`disconnected`, `connecting`, `connected`, `error`) + +**Message Tracking:** + +- Tracks all JSON-RPC messages with timestamps, direction, and duration +- `MessageEntry[]` format with full request/response/notification history +- Event-driven updates (`message`, `messagesChange` events) + +**Server Data Management:** + +- Auto-fetches tools, resources, prompts (configurable via `autoFetchServerContents`) +- Caches capabilities, serverInfo, instructions +- Event-driven updates for all server data (`toolsChange`, `resourcesChange`, `promptsChange`, etc.) + +**Request History Tracking:** + +- Tracks HTTP requests for OAuth (discovery, registration, token exchange) and transport +- Categorizes requests as `'auth'` or `'transport'` +- `FetchRequestEntry[]` format with full request/response details +- Event-driven updates (`fetchRequest` event) +- Configurable via `maxFetchRequests` option + +**Stderr Log Tracking:** + +- Captures and stores stderr output from stdio transports (when `pipeStderr` is enabled) +- `StderrLogEntry[]` format with timestamps +- Event-driven updates (`stderrLog`, `stderrLogsChange` events) +- Configurable via `maxStderrLogEvents` and `pipeStderr` options + +**MCP Method Wrappers:** + +- `listTools(metadata?)` - List available tools +- `callTool(name, args, generalMetadata?, toolSpecificMetadata?)` - Call a tool with automatic parameter conversion +- `listResources(metadata?)` - List available resources +- `readResource(uri, metadata?)` - Read a resource by URI +- `listResourceTemplates(metadata?)` - List resource templates +- `listPrompts(metadata?)` - List available prompts +- `getPrompt(name, args?, metadata?)` - Get a prompt with automatic argument stringification +- `getCompletions(resourceUri, prompt, metadata?)` - Get completions for resource templates or prompts +- `getRoots()` - List roots +- `setRoots(roots)` - Set roots +- `setLoggingLevel(level)` - Set logging level with capability checks + +**Advanced Features:** + +- **OAuth 2.1** - Full OAuth support (static client, DCR, CIMD, guided auth) with injectable storage, navigation, and redirect URL providers +- **Sampling** - Handles sampling requests, tracks pending samples, dispatches `newPendingSample` events +- **Elicitation** - Handles elicitation requests (form and URL), tracks pending elicitations, dispatches `newPendingElicitation` events +- **Roots** - Manages roots capability, handles `roots/list` requests, dispatches `rootsChange` events +- **Progress Notifications** - Handles progress notifications, dispatches `progressNotification` events, resets request timeout on progress +- **ListChanged Notifications** - Automatically reloads tools/resources/prompts when `listChanged` notifications are received + +**Configurable Options:** + +- `autoFetchServerContents` - Controls whether to auto-fetch tools/resources/prompts on connect (default: `true` for TUI, `false` for CLI) +- `initialLoggingLevel` - Sets the logging level on connect if server supports logging (optional) +- `maxMessages` - Maximum number of messages to store (default: 1000) +- `maxStderrLogEvents` - Maximum number of stderr log entries to store (default: 1000) +- `maxFetchRequests` - Maximum number of fetch requests to store (default: 1000) +- `pipeStderr` - Whether to pipe stderr for stdio transports (default: `false`; TUI and CLI set this explicitly) + +### Event System + +`InspectorClient` extends `EventTarget` for cross-platform compatibility: + +**Events with payloads:** + +- `statusChange` → `ConnectionStatus` +- `toolsChange` → `Tool[]` +- `resourcesChange` → `ResourceReference[]` +- `promptsChange` → `PromptReference[]` +- `capabilitiesChange` → `ServerCapabilities | undefined` +- `serverInfoChange` → `Implementation | undefined` +- `instructionsChange` → `string | undefined` +- `message` → `MessageEntry` +- `stderrLog` → `StderrLogEntry` +- `error` → `Error` + +**Events without payloads (signals):** + +- `connect` - Connection established +- `disconnect` - Connection closed +- `messagesChange` - Message list changed (fetch via `getMessages()`) +- `stderrLogsChange` - Stderr logs changed (fetch via `getStderrLogs()`) + +### Shared Module Structure + +The shared package is organized with environment-specific code separated into `node/` and `browser/` subdirectories. Portable code (no environment-specific APIs) lives in module roots; Node-specific code is under `node/` subdirectories; browser-specific code is under `browser/` subdirectories. + +**Main modules:** + +- **`shared/mcp/`** - `InspectorClient` and core MCP functionality +- **`shared/mcp/remote/`** - Remote transport infrastructure (portable client code) +- **`shared/auth/`** - OAuth infrastructure (portable base code) +- **`shared/storage/`** - Storage abstraction layer +- **`shared/react/`** - `useInspectorClient` React hook +- **`shared/json/`** - JSON utilities +- **`shared/test/`** - Test fixtures and harness servers + +For detailed module organization, environment-specific modules, and package exports, see [environment-isolation.md](environment-isolation.md). + +## Integration History + +### Phase 1: TUI Integration (Complete) + +The TUI was integrated from the [`mcp-inspect`](https://github.com/TeamSparkAI/mcp-inspect) project as a standalone workspace. During integration, the TUI developed `InspectorClient` as a comprehensive client wrapper, providing a good foundation for code sharing. + +**Key decisions:** + +- TUI developed `InspectorClient` to wrap MCP SDK `Client` +- Organized MCP code into `tui/src/mcp/` module +- Created React hook `useInspectorClient` for reactive state management + +### Phase 2: Extract to Shared Package (Complete) + +All MCP-related code was moved from TUI to `shared/` to enable reuse: + +**Moved to `shared/mcp/`:** + +- `inspectorClient.ts` - Main client wrapper +- `transport.ts` - Transport creation +- `config.ts` - Config loading +- `types.ts` - Shared types +- `messageTrackingTransport.ts` - Message tracking wrapper + +**Moved to `shared/react/`:** + +- `useInspectorClient.ts` - React hook + +**Moved to `shared/test/`:** + +- Test fixtures and harness servers (from CLI tests) + +**Configuration:** + +- Created `shared/package.json` as workspace package +- Configured TypeScript Project References +- Set React 19.2.3 as peer dependency +- Aligned all workspaces to React 19.2.3 + +### Phase 3: CLI Migration (Complete) + +The CLI was migrated to use `InspectorClient` from the shared package: + +**Changes:** + +- Replaced direct SDK `Client` usage with `InspectorClient` +- Moved CLI helper functions (`tools.ts`, `resources.ts`, `prompts.ts`) into `InspectorClient` as methods +- Extracted JSON utilities to `shared/json/jsonUtils.ts` +- Deleted `cli/src/client/` directory +- Implemented local `argsToMcpServerConfig()` function in CLI to convert CLI arguments to `MCPServerConfig` +- CLI now uses `inspectorClient.listTools()`, `inspectorClient.callTool()`, etc. directly + +**Configuration:** + +- CLI sets `autoFetchServerContents: false` (calls methods directly) +- CLI sets `initialLoggingLevel: "debug"` for consistent logging + +## Current Usage + +### CLI Usage + +The CLI uses `InspectorClient` for all MCP operations: + +```typescript +// Convert CLI args to MCPServerConfig +const config = argsToMcpServerConfig(args); + +// Create InspectorClient +const inspectorClient = new InspectorClient(config, { + clientIdentity, + autoFetchServerContents: false, // CLI calls methods directly + initialLoggingLevel: "debug", +}); + +// Connect and use +await inspectorClient.connect(); +const result = await inspectorClient.listTools(args.metadata); +await inspectorClient.disconnect(); +``` + +### TUI Usage + +The TUI uses `InspectorClient` via the `useInspectorClient` React hook: + +```typescript +// In TUI component +const { status, messages, tools, resources, prompts, connect, disconnect } = + useInspectorClient(inspectorClient); + +// InspectorClient is created from config and managed by App.tsx +// The hook automatically subscribes to events and provides reactive state +``` + +**TUI Configuration:** + +- Sets `autoFetchServerContents: true` (default) - automatically fetches server data on connect +- Uses `useInspectorClient` hook for reactive UI updates +- `ToolTestModal` uses `inspectorClient.callTool()` directly + +**TUI Status:** + +- **Experimental**: The TUI functionality may be considered "experimental" until sufficient testing and review of features and implementation. This allows for iteration and refinement based on user feedback before committing to a stable feature set. +- **Feature parity**: The TUI now supports OAuth (static client, CIMD, DCR, guided auth), completions, elicitation, sampling, and HTTP request tracking. InspectorClient provides all of these. + +**Entry Point:** +The TUI is invoked via the main `mcp-inspector` command with a `--tui` flag: + +- `mcp-inspector --tui ...` → TUI mode +- `mcp-inspector --cli ...` → CLI mode +- `mcp-inspector ...` → Web client mode (default) + +This provides a single entry point with consistent argument parsing across all three UX modes. + +## Phase 4: TUI Feature Gaps (Complete) + +InspectorClient supports OAuth (static client, CIMD, DCR, guided auth), completions (`getCompletions`), elicitation (pending elicitations, `newPendingElicitation` event), sampling (pending samples, `newPendingSample` event), roots (`getRoots`, `setRoots`), progress notifications, and custom headers via `MCPServerConfig`. For details on which features are implemented in the TUI vs. web client, see [tui-web-client-feature-gaps.md](tui-web-client-feature-gaps.md). + +## InspectorClient Readiness for Web App + +### Current State + +InspectorClient is **close to ready** for web app support. The core functionality matches what the web client needs: + +| Capability | InspectorClient | Web Client useConnection | +| ------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| Connection management | ✅ `connect()`, `disconnect()`, status events | ✅ | +| Tools, resources, prompts | ✅ Auto-fetch, events, methods | ✅ | +| Message tracking | ✅ `MessageEntry[]`, `messagesChange` | Different format (`{ request, response }[]`) | +| OAuth | ✅ Injected via `environment.oauth` (storage, navigation, redirect), `environment.fetch` | ✅ Own flow, session storage | +| Custom headers | ✅ `headers` in SSE/streamable-http config | ✅ | +| Elicitation | ✅ Pending elicitations, events | ✅ | +| Completion | ✅ `getCompletions()` | ✅ | +| Sampling | ✅ Pending samples, events | ✅ | +| Roots | ✅ `getRoots()`, `setRoots()`, events | ✅ | +| Progress | ✅ `progressNotification` event, timeout reset | ✅ | +| Request history | ✅ Auth + transport request tracking | ✅ Request history | +| Logger | ✅ Optional injected (pino) | — | +| Transport factory | ✅ Required `CreateTransport` | Creates transports directly (web servers) or via proxy (stdio/CORS) | + +### Environment Isolation: What's Done vs. Pending + +Per [environment-isolation.md](environment-isolation.md): + +**Implemented:** All environment-specific dependencies are consolidated into `InspectorClientEnvironment` (transport, fetch, logger, oauth.storage, oauth.navigation, oauth.redirectUrlProvider). Transport is required; fetch, logger, and OAuth components are optional. Node uses `createTransportNode`; browser uses `createRemoteTransport`, `createRemoteFetch`, `createRemoteLogger`. The shared package works in Node (CLI, TUI). + +**Implemented (remote infrastructure):** + +- **Hono API server** — In `shared/mcp/remote/node/`. Endpoints for transport (`/api/mcp/connect`, `send`, `events`, `disconnect`), proxy fetch (`/api/fetch`), logging (`/api/log`), and storage (`/api/storage/:storeId`). +- **createRemoteTransport + RemoteClientTransport** — In `shared/mcp/remote/` (portable). Browser transport that talks to the remote server. +- **createRemoteFetch** — In `shared/mcp/remote/`. Fetch that POSTs to `/api/fetch` for OAuth (CORS bypass). +- **createRemoteLogger** — In `shared/mcp/remote/`. Pino logger that POSTs to `/api/log` via `pino/browser` transmit. +- **Storage abstraction** — `FileStorageAdapter` (Node), `RemoteStorageAdapter` (browser), `RemoteOAuthStorage` (HTTP API). All OAuth storage implementations use Zustand persist middleware for consistency. +- **Generic storage API** — `GET/POST/DELETE /api/storage/:storeId` endpoints for shared on-disk state between web app and TUI/CLI. See [environment-isolation.md](environment-isolation.md). +- **Node code organization** — `shared/auth/node/`, `shared/mcp/node/`, `shared/mcp/remote/node/`. + +**Summary:** InspectorClient and the remote infrastructure (Hono API, createRemoteTransport, createRemoteFetch, createRemoteLogger, storage API) are implemented. The remaining effort is: + +1. Integrating `createRemoteApp` (Hono) into the Vite dev server as middleware +2. Refactoring the web client to use InspectorClient + `createRemoteTransport` instead of `useConnection` +3. Removing the separate Express server once integration is complete + +## Web Client Integration Plan + +### Current Web Client Architecture + +The web client currently uses `useConnection` hook (`client/src/lib/hooks/useConnection.ts`) that handles: + +1. **Connection Management** + - Connection status state (`disconnected`, `connecting`, `connected`, `error`, `error-connecting-to-proxy`) + - Direct vs. proxy connection modes + - Proxy health checking + +2. **Transport Creation** + - Creates SSE or StreamableHTTP transports directly + - Handles proxy mode (connects to proxy server endpoints) + - Handles direct mode (connects directly to MCP server) + - Manages transport options (headers, fetch wrappers, reconnection options) + +3. **OAuth Authentication** + - Browser-based OAuth flow (authorization code flow) + - OAuth token management via `InspectorOAuthClientProvider` + - Session storage for OAuth tokens + - OAuth callback handling + - Token refresh + +4. **Custom Headers** + - Custom header management (migration from legacy auth) + - Header validation + - OAuth token injection into headers + - Special header processing (`x-custom-auth-headers`) + +5. **Request/Response Tracking** + - Request history (`{ request: string, response?: string }[]`) + - History management (`pushHistory`, `clearRequestHistory`) + - Different format than InspectorClient's `MessageEntry[]` + +6. **Notification Handling** + - Notification handlers via callbacks (`onNotification`, `onStdErrNotification`) + - Multiple notification schemas (Cancelled, Logging, ResourceUpdated, etc.) + - Fallback notification handler + +7. **Request Handlers** + - Elicitation request handling (`onElicitationRequest`) + - Pending request handling (`onPendingRequest`) + - Roots request handling (`getRoots`) + +8. **Completion Support** + - Completion capability detection + - Completion state management + +9. **Progress Notifications** + - Progress notification handling + - Timeout reset on progress + +10. **Session Management** + - Session ID tracking (`mcpSessionId`) + - Protocol version tracking (`mcpProtocolVersion`) + - Response header capture + +11. **Server Information** + - Server capabilities + - Server implementation info + - Protocol version + +12. **Error Handling** + - Proxy auth errors + - OAuth errors + - Connection errors + - Retry logic + +The main `App.tsx` component manages extensive state including: + +- Resources, resource templates, resource content +- Prompts, prompt content +- Tools, tool results +- Errors per tab +- Connection configuration (command, args, sseUrl, transportType, etc.) +- OAuth configuration +- Custom headers +- Notifications +- Roots +- Environment variables +- Log level +- Active tab +- Pending requests + +### Integration Challenges + +**1. OAuth Authentication** + +- Web client uses browser-based OAuth flow (authorization code with PKCE) +- Requires browser redirects and callback handling +- **Solution**: InspectorClient supports injectable OAuth components via `environment.oauth` (storage, navigation, redirectUrlProvider) and `environment.fetch` for auth requests. Web client injects `BrowserOAuthStorage` or `RemoteOAuthStorage`, `BrowserNavigation`, and a redirect provider using `window.location.origin`. The web app implements its own `oauth/callback` route. + +**2. Remote Transport** + +- Web client must use remote transports for all transport types (stdio, SSE, streamable-http) +- **Solution**: Use `createRemoteTransport` as the transport factory. This handles all transport types via the remote API server. + +**3. Custom Headers** + +- Web client manages custom headers (OAuth tokens, custom auth headers) +- **Solution**: `MCPServerConfig` already supports `headers` in `SseServerConfig` and `StreamableHttpServerConfig` + +**4. Request History Format** + +- Web client uses `{ request: string, response?: string }[]` +- `InspectorClient` uses `MessageEntry[]` (more detailed) +- **Solution**: Migrate web client to use `MessageEntry[]` format + +**5. Completion Support** + +- Web client detects and manages completion capability +- **Solution**: Use `inspectorClient.getCapabilities()?.completions` to detect support, access SDK client via `getClient()` for completion requests + +**6. Elicitation and Request Handlers** + +- Web client sets request handlers for elicitation, pending requests, roots +- **Solution**: Use `inspectorClient.getClient()` to set request handlers (minimal change) + +**7. Progress Notifications** + +- Web client handles progress notifications and timeout reset +- **Solution**: Handle progress via existing notification system (`InspectorClient` already tracks notifications) + +**8. Session Management** + +- Web client tracks session ID and protocol version +- **Solution**: Access transport via `inspectorClient.getClient()` to get session info + +### Integration Strategy + +InspectorClient already has the needed features (see "InspectorClient Readiness for Web App" above). The remaining integration work is: + +1. **Integrate Hono server into Vite** — Mount `createRemoteApp` (Hono) as middleware in the Vite dev server. This eliminates the need for a separate Express server. The Hono app handles all `/api/*` routes (`/api/mcp/*`, `/api/fetch`, `/api/log`, `/api/storage/*`) on the same origin as the web client. +2. **Web-specific adapters** — Create adapter that converts web client config to `MCPServerConfig` and manages OAuth token injection into headers. Use `createRemoteTransport` as the transport factory, `createRemoteFetch` (POST to `/api/fetch`) for OAuth, `createRemoteLogger` (POST to `/api/log`) for logging, and OAuth providers (`BrowserOAuthStorage`, `BrowserNavigation`, or `RemoteOAuthStorage` for shared state). +3. **Replace useConnection** — Use `InspectorClient` + `useInspectorClient` instead of `useConnection`; migrate state and request history to `MessageEntry[]`; wire OAuth via web app's `oauth/callback` route. +4. **Remove Express server** — Delete or deprecate the separate Express server (`server/` directory) once Hono is integrated into Vite and the web client is ported. + +### Benefits of Web Client Integration + +1. **Code Reuse**: Share MCP client logic across all three interfaces, including the shared React hook (`useInspectorClient`) between TUI and web client +2. **Consistency**: Same behavior across CLI, TUI, and web client +3. **Maintainability**: Single source of truth for MCP operations +4. **Features**: Web client gets message tracking, stderr logging, event-driven updates +5. **Type Safety**: Shared types ensure consistency +6. **Testing**: Shared code is tested once, works everywhere + +### Implementation Steps + +The remote infrastructure is complete (Hono API server, `createRemoteTransport`, `createRemoteFetch`, `createRemoteLogger`, storage abstraction, Node code organization). Remaining steps: + +1. **Integrate Hono into Vite dev server** — Mount `createRemoteApp` as middleware in Vite configuration. Configure auth token, storage directory, and optional origin validation. This eliminates the separate Express server. +2. **Create adapter** — Convert web client config to `MCPServerConfig`; use `createRemoteTransport` as transport factory, `createRemoteFetch` for OAuth, `createRemoteLogger` for logging, and OAuth providers (`BrowserOAuthStorage`, `BrowserNavigation`, or `RemoteOAuthStorage` for shared state). +3. **Replace useConnection** — Use `InspectorClient` + `useInspectorClient` instead of `useConnection`; migrate state to `MessageEntry[]` format. +4. **Remove Express server** — Delete `server/` directory and update startup scripts once integration is complete. + +## Summary + +The shared code architecture provides: + +- **Single source of truth** for MCP client operations via `InspectorClient` +- **Code reuse** across CLI, TUI, and (planned) web client +- **Consistent behavior** across all interfaces +- **Reduced maintenance burden** - fix once, works everywhere +- **Type safety** through shared types +- **Event-driven updates** via EventTarget (cross-platform compatible) + +**Current Status:** + +- ✅ Phase 1: TUI integrated and using shared code +- ✅ Phase 2: Shared package created and configured +- ✅ Phase 3: CLI migrated to use shared code +- ✅ Phase 4: InspectorClient feature support added (OAuth, completions, elicitation, sampling, etc.). See [tui-web-client-feature-gaps.md](tui-web-client-feature-gaps.md) for TUI implementation status. +- 🔄 Phase 5: v2 web client integration (planned) + +**Next Steps:** + +1. Integrate `InspectorClient` with v2 web client: replace `useConnection` with `InspectorClient` + `useInspectorClient`, add adapters for config conversion and OAuth providers, wire OAuth providers diff --git a/docs/shared-code-architecture.svg b/docs/shared-code-architecture.svg new file mode 100644 index 000000000..59189bc3b --- /dev/null +++ b/docs/shared-code-architecture.svg @@ -0,0 +1,88 @@ + + + + + + + + + + MCP Inspector Shared Code Architecture + + + + CLI + Workspace + + + TUI + Workspace + React + Ink + + + Web Client + Workspace + React + + + + Shared Package + @modelcontextprotocol/inspector-shared + + + + InspectorClient + Core Wrapper - Manages Client & Transport Lifecycle + + + + shared/mcp/ + MCP Client/Server + + + shared/react/ + React Hooks + + + shared/json/ + JSON Utils + + + shared/test/ + Test Fixtures + + + + MCP SDK + + Client + + Transports + + + + MCP Server + External + stdio/SSE/HTTP + + + + + + + + + + + + diff --git a/docs/tui-oauth-implementation-plan.md b/docs/tui-oauth-implementation-plan.md new file mode 100644 index 000000000..76cb53eb2 --- /dev/null +++ b/docs/tui-oauth-implementation-plan.md @@ -0,0 +1,184 @@ +# TUI OAuth Implementation Plan + +## Overview + +This document describes OAuth 2.1 support in the TUI for MCP servers that require OAuth (e.g. GitHub Copilot MCP). The implementation supports **DCR**, **CIMD**, and **static client** (clientId/clientSecret in config). + +**Goals:** + +- Enable TUI to connect to OAuth-protected MCP servers (SSE, streamable-http). +- Use a **localhost callback server** to receive the OAuth redirect (authorization code). +- Share callback-server logic between TUI and CLI where possible. +- Support both **Quick Auth** (automatic flow) and **Guided Auth** (step-by-step) with a **single redirect URL**. + +**Scope:** + +- **Quick Auth**: Automatic flow via `authenticate()`. Single redirect URI `http://localhost:/oauth/callback`. +- **Guided Auth**: Step-by-step flow via `beginGuidedAuth()`, `proceedOAuthStep()`, `runGuidedAuth()`. Same redirect URI; mode embedded in OAuth `state` parameter. + +--- + +## Implementation Status + +### Completed + +| Component | Status | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| **Callback server** | Done. `shared/auth/oauth-callback-server.ts`, single path `/oauth/callback`, serves both normal and guided flows. | +| **TUI integration** | Done. Auth available for all HTTP servers (SSE, streamable-http). Auth tab with Guided / Quick / Clear. | +| **Quick Auth** | Done. `authenticate()`, callback server, `openUrl`, `completeOAuthFlow`. | +| **Guided Auth** | Done. `beginGuidedAuth`, `proceedOAuthStep`, `runGuidedAuth`. Step progress UI, Space to advance, Enter to run to completion. | +| **Single redirect URL** | Done. Mode embedded in `state` (`normal:...` or `guided:...`). One `redirect_uri` registered with OAuth server. | +| **401 handling** | Done. On connect failure, if 401 seen in fetch history, show "401 Unauthorized. Press A to authenticate." | +| **DCR / CIMD** | Done. InspectorClient supports Dynamic Client Registration and CIMD. | + +### Static Client Auth + +**InspectorClient** supports static client configuration (`clientId`, `clientSecret` in oauth config). The **TUI does not yet support static client configuration**—there is no UI or config wiring for `clientId`/`clientSecret`. Adding this is pending work. + +### Pending Work + +1. **Callback state validation (optional)** + - Store the state we sent when building the auth URL. On callback, parse `state` via `parseOAuthState()` and verify the random part matches. + - Hardening step; current flow works without it since only one active flow runs at a time. + +2. **OAuth config in TUI** + - Add support for oauth options: `scope`, `storagePath`, `clientId`, `clientSecret`, `clientMetadataUrl`. + - Store in auth store for the server (or elsewhere)—**not** in server config. + - Wire through to InspectorClient when creating auth provider. + +3. **Redirect URI / port change** + - If the callback server restarts with a different port (e.g. between auth attempts), the OAuth server may have the old redirect_uri registered, causing "Unregistered redirect_uri". Workaround: clear OAuth state before retrying. Potential improvement: reuse port or document the limitation. + +4. **CLI OAuth** + - Wire the same callback server into the CLI for HTTP servers. Flow: start callback server, run `authenticate()`, open URL, receive callback, `completeOAuthFlow`, then connect. + +--- + +## Assumptions + +- **DCR, CIMD, or static client**: Auth options (clientId, clientSecret, clientMetadataUrl, etc.) live in auth store or similar—not in server config. +- **Discovery runs in Node**: TUI and CLI run in Node. OAuth metadata discovery uses `fetch` in Node—**no CORS** issues. +- **Single redirect URI**: Both normal and guided flows use `http://localhost:/oauth/callback`. Mode is embedded in the `state` parameter. + +--- + +## Single Redirect URL (Mode in State) + +We use **one redirect URL** for both normal and guided flows. The **mode** is embedded in the OAuth `state` parameter, which the authorization server echoes back unchanged. + +### State Format + +``` +{mode}:{random} +``` + +- `normal:a1b2c3...` (64 hex chars after colon) +- `guided:a1b2c3...` + +The random part is 32 bytes (64 hex chars) for CSRF protection. Legacy state (plain 64-char hex) is treated as `"normal"`. + +### Implementation + +- `generateOAuthStateWithMode(mode)` and `parseOAuthState(state)` in `shared/auth/utils.ts` +- `BaseOAuthClientProvider.state()` uses mode-embedded state +- `redirect_uris` returns a single URL for both modes +- Callback server serves `/oauth/callback` only + +--- + +## Callback Server + +### Location + +- `shared/auth/oauth-callback-server.ts` +- Exported from `@modelcontextprotocol/inspector-shared/auth` + +### API + +```ts +type OAuthCallbackHandler = (params: { code: string; state?: string }) => Promise; +type OAuthErrorHandler = (params: { error: string; error_description?: string }) => void; + +start(options: { + port?: number; + onCallback?: OAuthCallbackHandler; + onError?: OAuthErrorHandler; +}): Promise<{ port: number; redirectUrl: string }>; + +stop(): Promise; +``` + +### Behavior + +1. Listens on configurable port (default `0` → OS-assigned). +2. Serves `GET /oauth/callback` only (both normal and guided). +3. On success: invokes `onCallback` with `{ code, state }`, responds with "OAuth complete. You can close this window.", then stops. +4. On error: invokes `onError`, responds with error HTML. +5. Caller must **not** `await callbackServer.stop()` inside `onCallback`; the server stops itself after sending the response (avoids deadlock). + +--- + +## TUI Flow + +### Config + +- Auth is available for all HTTP servers (SSE, streamable-http). +- **Auth config is not stored in server config.** OAuth options (scope, storagePath, clientId, clientSecret, clientMetadataUrl) will live in the auth store for the server or elsewhere—not in the MCP server config. +- `redirectUrl` is set from the callback server when the user starts auth. + +### Auth Tab + +- **Guided Auth**: Step-by-step. Space to advance one step, Enter to run to completion. +- **Quick Auth**: Automatic flow. +- **Clear OAuth State**: Clears tokens and state. +- Accelerators: G (Guided), Q (Quick), S (Clear) switch to Auth tab and select the corresponding action. + +### End-to-End Flow (Quick Auth) + +1. User selects HTTP server, presses Q or selects Quick Auth and Enter. +2. TUI starts callback server, sets `redirectUrl` on provider. +3. Calls `authenticate()`. +4. On `oauthAuthorizationRequired`, opens auth URL in browser. +5. User signs in; IdP redirects to `http://localhost:/oauth/callback?code=...&state=...`. +6. Callback server receives request, calls `completeOAuthFlow(code)`, responds with success page. +7. TUI shows "OAuth complete. Press C to connect." + +### End-to-End Flow (Guided Auth) + +1. User selects HTTP server, presses G or selects Guided Auth. +2. TUI starts callback server, sets `redirectUrl`, calls `beginGuidedAuth()`. +3. User advances with Space (or runs to completion with Enter). +4. At authorization step, browser opens with auth URL (state includes `guided:...`). +5. User signs in; IdP redirects to same `/oauth/callback` with code and state. +6. Callback server receives, calls `completeOAuthFlow(code)`, responds with success page. +7. TUI shows completion. + +--- + +## Config Shape + +**MCP server config:** + +```json +{ + "mcpServers": { + "hosted-everything": { + "type": "streamable-http", + "url": "https://example-server.modelcontextprotocol.io/mcp" + } + } +} +``` + +- Auth is available for all HTTP servers. Server config stays clean—**no oauth block**. +- Auth options (scope, storagePath, clientId, clientSecret, clientMetadataUrl) are **not** stored in server config. They will live in the auth store for the server or elsewhere. TUI does not yet support configuring these; defaults only. + +--- + +## References + +- [OAuth Support in InspectorClient](./oauth-inspectorclient-design.md) +- [TUI and Web Client Feature Gaps](./tui-web-client-feature-gaps.md) +- `shared/auth/`: providers, state-machine, utils, storage-node, oauth-callback-server +- `shared/mcp/inspectorClient.ts`: `authenticate`, `beginGuidedAuth`, `runGuidedAuth`, `proceedOAuthStep`, `completeOAuthFlow`, `authProvider` diff --git a/docs/tui-web-client-feature-gaps.md b/docs/tui-web-client-feature-gaps.md new file mode 100644 index 000000000..3151ef5e0 --- /dev/null +++ b/docs/tui-web-client-feature-gaps.md @@ -0,0 +1,812 @@ +# TUI and Web Client Feature Gap Analysis + +## Overview + +This document details the feature gaps between the TUI (Terminal User Interface) and the web client. The goal is to identify all missing features in the TUI and create a plan to close these gaps by extending `InspectorClient` and implementing the features in the TUI. + +## Feature Comparison + +**InspectorClient** is the shared client library that provides the core MCP functionality. Both the TUI and web client use `InspectorClient` under the hood. The gaps documented here are primarily **UI-level gaps** - features that `InspectorClient` supports but are not yet exposed in the TUI interface. + +| Feature | InspectorClient | Web Client v1 | TUI | Gap Priority | +| ------------------------------------------ | --------------- | ------------- | --- | ------------ | +| **Resources** | +| List resources | ✅ | ✅ | ✅ | - | +| Read resource content | ✅ | ✅ | ✅ | - | +| List resource templates | ✅ | ✅ | ✅ | - | +| Read templated resources | ✅ | ✅ | ✅ | - | +| Resource subscriptions | ✅ | ✅ | ❌ | Medium | +| Resources listChanged notifications | ✅ | ✅ | ❌ | Medium | +| Pagination (resources) | ✅ | ✅ | ✅ | - | +| Pagination (resource templates) | ✅ | ✅ | ✅ | - | +| **Prompts** | +| List prompts | ✅ | ✅ | ✅ | - | +| Get prompt (no params) | ✅ | ✅ | ✅ | - | +| Get prompt (with params) | ✅ | ✅ | ✅ | - | +| Prompts listChanged notifications | ✅ | ✅ | ❌ | Medium | +| Pagination (prompts) | ✅ | ✅ | ✅ | - | +| **Tools** | +| List tools | ✅ | ✅ | ✅ | - | +| Call tool | ✅ | ✅ | ✅ | - | +| Tools listChanged notifications | ✅ | ✅ | ❌ | Medium | +| Pagination (tools) | ✅ | ✅ | ✅ | - | +| **Roots** | +| List roots | ✅ | ✅ | ❌ | Medium | +| Set roots | ✅ | ✅ | ❌ | Medium | +| Roots listChanged notifications | ✅ | ✅ | ❌ | Medium | +| **Authentication** | +| OAuth 2.1 flow | ✅ | ✅ | ✅ | - | +| OAuth: Static/Preregistered clients | ✅ | ✅ | ✅ | - | +| OAuth: DCR (Dynamic Client Registration) | ✅ | ✅ | ✅ | - | +| OAuth: CIMD (Client ID Metadata Documents) | ✅ | ❌ | ✅ | - | +| OAuth: Guided Auth (step-by-step) | ✅ | ✅ | ✅ | - | +| Custom headers | ✅ (config) | ✅ (UI) | ❌ | Medium | +| **Advanced Features** | +| Sampling requests | ✅ | ✅ | ❌ | High | +| Elicitation requests (form) | ✅ | ✅ | ❌ | High | +| Elicitation requests (url) | ✅ | ❌ | ❌ | High | +| Tasks (long-running operations) | ✅ | ✅ | ❌ | Medium | +| Completions (resource templates) | ✅ | ✅ | ❌ | Medium | +| Completions (prompts with params) | ✅ | ✅ | ❌ | Medium | +| Progress tracking | ✅ | ✅ | ❌ | Medium | +| **Other** | +| HTTP request tracking | ✅ | ❌ | ✅ | | + +## Detailed Feature Gaps + +### 1. Resource Subscriptions + +**Web Client Support:** + +- Subscribes to resources via `resources/subscribe` +- Unsubscribes via `resources/unsubscribe` +- Tracks subscribed resources in state +- UI shows subscription status and subscribe/unsubscribe buttons +- Handles `notifications/resources/updated` notifications for subscribed resources + +**TUI Status:** + +- ❌ No support for resource subscriptions +- ❌ No subscription state management +- ❌ No UI for subscribe/unsubscribe actions + +**InspectorClient Status:** + +- ✅ `subscribeToResource(uri)` method - **COMPLETED** +- ✅ `unsubscribeFromResource(uri)` method - **COMPLETED** +- ✅ Subscription state tracking - **COMPLETED** (`getSubscribedResources()`, `isSubscribedToResource()`) +- ✅ Handler for `notifications/resources/updated` - **COMPLETED** +- ✅ `resourceSubscriptionsChange` event - **COMPLETED** +- ✅ `resourceUpdated` event - **COMPLETED** +- ✅ Cache clearing on resource updates - **COMPLETED** (clears both regular resources and resource templates with matching expandedUri) + +**TUI Status:** + +- ❌ No UI for resource subscriptions +- ❌ No subscription state management in UI +- ❌ No UI for subscribe/unsubscribe actions +- ❌ No handling of resource update notifications in UI + +**Implementation Requirements:** + +- ✅ Add `subscribeToResource(uri)` and `unsubscribeFromResource(uri)` methods to `InspectorClient` - **COMPLETED** +- ✅ Add subscription state tracking in `InspectorClient` - **COMPLETED** +- ❌ Add UI in TUI `ResourcesTab` for subscribe/unsubscribe actions +- ✅ Handle resource update notifications for subscribed resources - **COMPLETED** (in InspectorClient) + +**Code References:** + +- Web client: `client/src/App.tsx` (lines 781-809) +- Web client: `client/src/components/ResourcesTab.tsx` (lines 207-221) + +### 2. OAuth 2.1 Authentication + +**InspectorClient Support:** + +- OAuth 2.1 support in shared package (`shared/auth/`), integrated via `authProvider` on HTTP transports (SSE, streamable-http) +- **Static/Preregistered Clients**: ✅ Supported +- **DCR (Dynamic Client Registration)**: ✅ Supported +- **CIMD (Client ID Metadata Documents)**: ✅ Supported via `clientMetadataUrl` in OAuth config +- Authorization code flow with PKCE, token exchange, token refresh (via SDK `authProvider` when `refresh_token` available) +- Guided mode (`authenticateGuided()`, `proceedOAuthStep()`, `getOAuthStep()`) and normal mode (`authenticate()`, `completeOAuthFlow()`) +- Configurable storage path (`oauth.storagePath`), default `~/.mcp-inspector/oauth/state.json` +- Events: `oauthAuthorizationRequired`, `oauthComplete`, `oauthError`, `oauthStepChange` + +**Web Client Support:** + +- Full browser-based OAuth 2.1 flow (uses its own OAuth code in `client/src/lib/`, unchanged): + - **Static/Preregistered Clients**: ✅ Supported - User provides client ID and secret via UI + - **DCR (Dynamic Client Registration)**: ✅ Supported - Falls back to DCR if no static client available + - **CIMD (Client ID Metadata Documents)**: ❌ Not supported - Web client does not set `clientMetadataUrl` + - Authorization code flow with PKCE, token exchange, token refresh +- OAuth state management via `InspectorOAuthClientProvider` +- Session storage for OAuth tokens, OAuth callback handling, automatic token injection into request headers + +**TUI Status:** + +- ✅ OAuth 2.1 support including static client, CIMD, DCR, and guided auth +- ✅ OAuth token management via Auth tab +- ✅ Browser-based OAuth flow with localhost callback server +- ✅ CLI options: `--client-id`, `--client-secret`, `--client-metadata-url`, `--callback-url` + +**Code References:** + +- InspectorClient OAuth: `shared/mcp/inspectorClient.ts` (OAuth options, `authenticate`, `authenticateGuided`, `completeOAuthFlow`, events), `shared/auth/` +- Web client: `client/src/lib/hooks/useConnection.ts`, `client/src/lib/auth.ts`, `client/src/lib/oauth-state-machine.ts` +- Design: [OAuth Support in InspectorClient](./oauth-inspectorclient-design.md) + +**Note:** OAuth in TUI requires a browser-based flow with a localhost callback server, which is feasible but different from the web client's approach. + +### 3. Sampling Requests + +**InspectorClient Support:** + +- ✅ Declares `sampling: {}` capability in client initialization (via `sample` option, default: `true`) +- ✅ Sets up request handler for `sampling/createMessage` requests automatically +- ✅ Tracks pending sampling requests via `getPendingSamples()` +- ✅ Provides `SamplingCreateMessage` class with `respond()` and `reject()` methods +- ✅ Dispatches `newPendingSample` and `pendingSamplesChange` events +- ✅ Methods: `getPendingSamples()`, `removePendingSample(id)` + +**Web Client Support:** + +- UI tab (`SamplingTab`) displays pending sampling requests +- `SamplingRequest` component shows request details and approval UI +- Handles approve/reject actions via `SamplingCreateMessage.respond()`/`reject()` +- Listens to `newPendingSample` events to update UI + +**TUI Status:** + +- ❌ No UI for sampling requests +- ❌ No sampling request display or handling UI + +**Implementation Requirements:** + +- Add UI in TUI for displaying pending sampling requests +- Add UI for approve/reject actions (call `respond()` or `reject()` on `SamplingCreateMessage`) +- Listen to `newPendingSample` and `pendingSamplesChange` events +- Add sampling tab or integrate into existing tabs + +**Code References:** + +- `InspectorClient`: `shared/mcp/inspectorClient.ts` (lines 85-87, 225-226, 401-417, 573-600) +- Web client: `client/src/components/SamplingTab.tsx` +- Web client: `client/src/components/SamplingRequest.tsx` +- Web client: `client/src/App.tsx` (lines 328-333, 637-652) + +### 4. Elicitation Requests + +**InspectorClient Support:** + +- ✅ Declares `elicitation: {}` capability in client initialization (via `elicit` option, default: `true`) +- ✅ Sets up request handler for `elicitation/create` requests automatically +- ✅ Tracks pending elicitation requests via `getPendingElicitations()` +- ✅ Provides `ElicitationCreateMessage` class with `respond()` and `remove()` methods +- ✅ Dispatches `newPendingElicitation` and `pendingElicitationsChange` events +- ✅ Methods: `getPendingElicitations()`, `removePendingElicitation(id)` +- ✅ Supports both form-based (user-input) and URL-based elicitation modes + +#### 4a. Form-Based Elicitation (User-Input) + +**InspectorClient Support:** + +- ✅ Handles `ElicitRequest` with `requestedSchema` (form-based mode) +- ✅ Extracts `taskId` from `related-task` metadata when present +- ✅ Test fixtures: `createCollectElicitationTool()` for testing form-based elicitation + +**Web Client Support:** + +- ✅ UI tab (`ElicitationTab`) displays pending form-based elicitation requests +- ✅ `ElicitationRequest` component: + - Shows request message and schema + - Generates dynamic form from JSON schema + - Validates form data against schema + - Handles accept/decline/cancel actions via `ElicitationCreateMessage.respond()` +- ✅ Listens to `newPendingElicitation` events to update UI + +**TUI Status:** + +- ❌ No UI for form-based elicitation requests +- ❌ No form generation from JSON schema +- ❌ No UI for accept/decline/cancel actions + +**Implementation Requirements:** + +- Add UI in TUI for displaying pending form-based elicitation requests +- Add form generation from JSON schema (similar to tool parameter forms) +- Add UI for accept/decline/cancel actions (call `respond()` on `ElicitationCreateMessage`) +- Listen to `newPendingElicitation` and `pendingElicitationsChange` events +- Add elicitation tab or integrate into existing tabs + +#### 4b. URL-Based Elicitation + +**InspectorClient Support:** + +- ✅ Handles `ElicitRequest` with `mode: "url"` and `url` parameter +- ✅ Extracts `taskId` from `related-task` metadata when present +- ✅ Test fixtures: `createCollectUrlElicitationTool()` for testing URL-based elicitation + +**Web Client Support:** + +- ❌ No UI for URL-based elicitation requests +- ❌ No handling for URL-based elicitation mode + +**TUI Status:** + +- ❌ No UI for URL-based elicitation requests +- ❌ No handling for URL-based elicitation mode + +**Implementation Requirements:** + +- Add UI in TUI for displaying pending URL-based elicitation requests +- Add UI to display URL and message to user +- Add UI for accept/decline/cancel actions (call `respond()` on `ElicitationCreateMessage`) +- Optionally: Open URL in browser or provide copy-to-clipboard functionality +- Listen to `newPendingElicitation` and `pendingElicitationsChange` events +- Add elicitation tab or integrate into existing tabs + +**Code References:** + +- `InspectorClient`: `shared/mcp/inspectorClient.ts` (lines 90-92, 227-228, 420-433, 606-639) +- `ElicitationCreateMessage`: `shared/mcp/elicitationCreateMessage.ts` +- Test fixtures: `shared/test/test-server-fixtures.ts` (`createCollectElicitationTool`, `createCollectUrlElicitationTool`) +- Web client: `client/src/components/ElicitationTab.tsx` +- Web client: `client/src/components/ElicitationRequest.tsx` (form-based only) +- Web client: `client/src/App.tsx` (lines 334-356, 653-669) +- Web client: `client/src/utils/schemaUtils.ts` (schema resolution for form-based elicitation) + +### 5. Tasks (Long-Running Operations) + +**Status:** + +- ✅ **COMPLETED** - Fully implemented in InspectorClient +- ✅ Implemented in web client (as of recent release) +- ❌ Not yet implemented in TUI + +**Overview:** +Tasks (SEP-1686) were introduced in MCP version 2025-11-25 to support long-running operations through a "call-now, fetch-later" pattern. Tasks enable servers to return a taskId immediately and allow clients to poll for status and retrieve results later, avoiding connection timeouts. + +**InspectorClient Support:** + +- ✅ `callToolStream()` method - Calls tools with task support, returns streaming updates +- ✅ `getTask(taskId)` method - Retrieves task status by taskId +- ✅ `getTaskResult(taskId)` method - Retrieves task result once completed +- ✅ `cancelTask(taskId)` method - Cancels a running task +- ✅ `listTasks(cursor?)` method - Lists all active tasks with pagination support +- ✅ `getClientTasks()` method - Returns array of currently tracked tasks +- ✅ Task state tracking - Maintains cache of active tasks with automatic updates +- ✅ Task lifecycle events - Dispatches `taskCreated`, `taskStatusChange`, `taskCompleted`, `taskFailed`, `taskCancelled`, `tasksChange` events +- ✅ Elicitation integration - Links elicitation requests to tasks via `related-task` metadata +- ✅ Sampling integration - Links sampling requests to tasks via `related-task` metadata +- ✅ Progress notifications - Links progress notifications to tasks via `related-task` metadata +- ✅ Capability detection - `getTaskCapabilities()` checks server task support +- ✅ `callTool()` validation - Throws error if attempting to call tool with `taskSupport: "required"` using `callTool()` +- ✅ Task cleanup - Clears task cache on disconnect + +**Web Client Support:** + +- UI displays active tasks with status indicators +- Task status updates in real-time via event listeners +- Task cancellation UI (cancel button for running tasks) +- Task result display when tasks complete +- Integration with tool calls - shows task creation from `callToolStream()` +- Links tasks to elicitation/sampling requests when task is `input_required` + +**TUI Status:** + +- ❌ No UI for displaying active tasks +- ❌ No task status display or monitoring +- ❌ No task cancellation UI +- ❌ No task result display +- ❌ No integration with tool calls (tasks created via `callToolStream()` are not visible) +- ❌ No indication when tool requires task support (`taskSupport: "required"`) +- ❌ No linking of tasks to elicitation/sampling requests in UI +- ❌ No task lifecycle event handling in UI + +**Implementation Requirements:** + +- ✅ InspectorClient task support - **COMPLETED** (see [Task Support Design](./task-support-design.md)) +- ❌ Add TUI UI for task management: + - Display list of active tasks with status (`working`, `input_required`, `completed`, `failed`, `cancelled`) + - Show task details (taskId, status, statusMessage, createdAt, lastUpdatedAt) + - Display task results when completed + - Cancel button for running tasks (call `cancelTask()`) + - Real-time status updates via `taskStatusChange` event listener + - Task lifecycle event handling (`taskCreated`, `taskCompleted`, `taskFailed`, `taskCancelled`) +- ❌ Integrate tasks with tool calls: + - Use `callToolStream()` for tools with `taskSupport: "required"` (instead of `callTool()`) + - Show task creation when tool call creates a task + - Link tool call results to tasks +- ❌ Integrate tasks with elicitation/sampling: + - Display which task is waiting for input when elicitation/sampling request has `taskId` + - Show task status as `input_required` while waiting for user response + - Link elicitation/sampling UI to associated task +- ❌ Add task capability detection: + - Check `getTaskCapabilities()` to determine if server supports tasks + - Only show task UI if server supports tasks +- ❌ Handle task-related errors: + - Show error when attempting to call `taskSupport: "required"` tool with `callTool()` + - Display task failure messages from `taskFailed` events + +### 6. Completions + +**InspectorClient Support:** + +- ✅ `getCompletions()` method sends `completion/complete` requests +- ✅ Supports resource template completions: `{ type: "ref/resource", uri: string }` +- ✅ Supports prompt argument completions: `{ type: "ref/prompt", name: string }` +- ✅ Handles `MethodNotFound` errors gracefully (returns empty array if server doesn't support completions) +- ✅ Completion requests include: + - `ref`: Resource template URI or prompt name + - `argument`: Field name and current (partial) value + - `context`: Optional context with other argument values +- ✅ Returns `{ values: string[] }` with completion suggestions + +**Web Client Support:** + +- Detects completion capability via `serverCapabilities.completions` +- `handleCompletion()` function calls `InspectorClient.getCompletions()` +- Used in resource template forms for autocomplete +- Used in prompt forms with parameters for autocomplete +- `useCompletionState` hook manages completion state and debouncing + +**TUI Status:** + +- ✅ Prompt fetching with parameters - **COMPLETED** (modal form for collecting prompt arguments) +- ❌ No completion support for resource template forms +- ❌ No completion support for prompt parameter forms +- ❌ No completion capability detection in UI +- ❌ No completion request handling in UI + +**Implementation Requirements:** + +- Add completion capability detection in TUI (via `InspectorClient.getCapabilities()?.completions`) +- Integrate `InspectorClient.getCompletions()` into TUI forms: + - **Resource template forms** (`ResourceTestModal`) - autocomplete for template variable values + - **Prompt parameter forms** (`PromptTestModal`) - autocomplete for prompt argument values +- Add completion state management (debouncing, loading states) +- Trigger completions on input change with debouncing + +**Code References:** + +- `InspectorClient`: `shared/mcp/inspectorClient.ts` (lines 902-966) - `getCompletions()` method +- Web client: `client/src/lib/hooks/useConnection.ts` (lines 309, 384-386) +- Web client: `client/src/lib/hooks/useCompletionState.ts` +- Web client: `client/src/components/ResourcesTab.tsx` (lines 88-101) +- TUI: `tui/src/components/PromptTestModal.tsx` - Prompt form (needs completion integration) +- TUI: `tui/src/components/ResourceTestModal.tsx` - Resource template form (needs completion integration) + +### 6. Progress Tracking + +**Use Case:** + +Long-running operations (tool calls, resource reads, prompt invocations, etc.) can send progress notifications (`notifications/progress`) to keep clients informed of execution status. This is useful for: + +- Showing progress bars or status updates +- Resetting request timeouts on progress notifications +- Providing user feedback during long operations + +**Request timeouts and `resetTimeoutOnProgress`:** + +The MCP SDK applies a **per-request timeout** to all client requests (`listTools`, `callTool`, `getPrompt`, etc.). If no `timeout` is passed in `RequestOptions`, the SDK uses `DEFAULT_REQUEST_TIMEOUT_MSEC` (60 seconds). When the timeout is exceeded, the SDK raises an `McpError` with code `RequestTimeout` and the request fails—even if the server is still working and sending progress. + +**`resetTimeoutOnProgress`** is an SDK `RequestOptions` flag. When `true`, each `notifications/progress` received for that request **resets** the per-request timeout. That allows long-running operations that send periodic progress to run beyond 60 seconds without failing. (An optional `maxTotalTimeout` caps total wait time regardless of progress.) + +The SDK runs timeout reset **only** when a per-request `onprogress` callback exists; it also injects `progressToken: messageId` for routing. `InspectorClient` passes per-request `onprogress` when progress is enabled (so timeout reset **takes effect**) and collects the caller's `progressToken` from metadata. We **do not** expose that token to the server—the SDK overwrites it with `messageId`—we inject it only into dispatched `progressNotification` events so listeners can correlate progress with the request that triggered it. We pass `resetTimeoutOnProgress` (default: `true`) and optional `timeout` through; both are honored. Set `resetTimeoutOnProgress: false` for strict timeout caps or fail-fast behavior. + +**Web Client Support:** + +- **Progress Token**: Generates and includes `progressToken` in request metadata: + ```typescript + const mergedMetadata = { + ...metadata, + progressToken: progressTokenRef.current++, + ...toolMetadata, + }; + ``` +- **Progress Callback**: Sets up `onprogress` callback in `useConnection`: + ```typescript + if (mcpRequestOptions.resetTimeoutOnProgress) { + mcpRequestOptions.onprogress = (params: Progress) => { + if (onNotification) { + onNotification({ + method: "notifications/progress", + params, + }); + } + }; + } + ``` +- **Progress Display**: Progress notifications are displayed in the "Server Notifications" window +- **Timeout Reset**: `resetTimeoutOnProgress` option resets request timeout when progress notifications are received + +**InspectorClient Status:** + +- ✅ Progress - Per-request `onprogress` when `progress` enabled; dispatches `progressNotification` events (no global progress handler) +- ✅ Progress token - Accepts `progressToken` in metadata; we inject it into dispatched events only (not sent to server), so listeners can correlate +- ✅ Event-based - Clients listen for `progressNotification` events +- ✅ Timeout reset - `resetTimeoutOnProgress` (default: `true`), optional `timeout`; both honored via per-request `onprogress` + +**TUI Status:** + +- ❌ No progress tracking support +- ❌ No progress notification display +- ❌ No progress token management + +**Implementation Requirements:** + +- ✅ **Completed in InspectorClient:** + - Per-request `onprogress` when `progress: true`; dispatch `progressNotification` events from callback (no global progress handler) + - Caller's `progressToken` from metadata injected into events only (not sent to server); full params include `progress`, `total`, `message` + - `progressToken` in metadata supported (e.g. `callTool`, `getPrompt`, `readResource`, list methods) + - `resetTimeoutOnProgress` (default: `true`) and optional `timeout` passed as `RequestOptions`; timeout reset honored +- ❌ **TUI UI Support Needed:** + - Show progress notifications during long-running operations + - Display progress status in results view + - Optional: Progress bars or percentage indicators + +**Code References:** + +- InspectorClient: `shared/mcp/inspectorClient.ts` - `getRequestOptions(progressToken?)` builds per-request `onprogress`, injects token into dispatched events +- InspectorClient: `shared/mcp/inspectorClient.ts` - `callTool`, `callToolStream`, `getPrompt`, `readResource`, list methods pass `metadata?.progressToken` into `getRequestOptions` +- Web client: `client/src/App.tsx` (lines 840-892) - Progress token generation and tool call +- Web client: `client/src/lib/hooks/useConnection.ts` (lines 214-226) - Progress callback setup +- SDK: `@modelcontextprotocol/sdk` `shared/protocol` - `DEFAULT_REQUEST_TIMEOUT_MSEC` (60_000), `RequestOptions` (`timeout`, `resetTimeoutOnProgress`, `maxTotalTimeout`), `Progress` type + +### 7. ListChanged Notifications + +**Use Case:** + +MCP servers can send `listChanged` notifications when the list of tools, resources, or prompts changes. This allows clients to automatically refresh their UI when the server's capabilities change, without requiring manual refresh actions. + +**Web Client Support:** + +- **Capability Declaration**: Declares `roots: { listChanged: true }` in client capabilities +- **Notification Handlers**: Sets up handlers for: + - `notifications/tools/list_changed` + - `notifications/resources/list_changed` + - `notifications/prompts/list_changed` +- **Auto-refresh**: When a `listChanged` notification is received, the web client automatically calls the corresponding `list*()` method to refresh the UI +- **Notification Processing**: All notifications are passed to `onNotification` callback, which stores them in state for display + +**InspectorClient Status:** + +- ✅ Notification handlers for `notifications/tools/list_changed` - **COMPLETED** +- ✅ Notification handlers for `notifications/resources/list_changed` - **COMPLETED** (reloads both resources and resource templates) +- ✅ Notification handlers for `notifications/prompts/list_changed` - **COMPLETED** +- ✅ Automatic list refresh on `listChanged` notifications - **COMPLETED** +- ✅ Configurable via `listChangedNotifications` option - **COMPLETED** (tools, resources, prompts) +- ✅ Cache preservation for existing items - **COMPLETED** +- ✅ Cache cleanup for removed items - **COMPLETED** +- ✅ Event dispatching (`toolsChange`, `resourcesChange`, `resourceTemplatesChange`, `promptsChange`) - **COMPLETED** + +**TUI Status:** + +- ✅ `listChanged` notifications automatically handled by `InspectorClient` - **COMPLETED** +- ✅ Lists automatically reload when notifications are received - **COMPLETED** +- ✅ Events dispatched (`toolsChange`, `resourcesChange`, `promptsChange`) - **COMPLETED** +- ✅ TUI automatically reflects changes when events are received - **COMPLETED** (if TUI listens to these events) +- ❌ No UI indication when lists are auto-refreshed (optional, but useful for debugging) + +**Note on TUI Support:** + +The TUI automatically supports `listChanged` notifications through `InspectorClient`. The implementation works as follows: + +1. **Server Capability**: The MCP server must advertise `listChanged` capability in its server capabilities (e.g., `tools: { listChanged: true }`, `resources: { listChanged: true }`, `prompts: { listChanged: true }`) + +2. **Automatic Handler Registration**: When `InspectorClient` connects, it checks if the server advertises `listChanged` capability. If it does, `InspectorClient` automatically registers notification handlers for: + - `notifications/tools/list_changed` + - `notifications/resources/list_changed` + - `notifications/prompts/list_changed` + +3. **Automatic List Reload**: When a `listChanged` notification is received, `InspectorClient` automatically calls the corresponding `listAll*()` method to reload the list + +4. **Event Dispatching**: `InspectorClient` dispatches events (`toolsChange`, `resourcesChange`, `resourceTemplatesChange`, `promptsChange`) that the TUI can listen to + +5. **TUI Auto-Refresh**: The TUI will automatically reflect changes if it listens to these events (which it should, as it uses `InspectorClient`) + +**Important**: The client does NOT need to advertise `listChanged` capability - it only needs to check if the server supports it. The handlers are registered automatically based on server capabilities. + +**Implementation Requirements:** + +- ✅ Add notification handlers in `InspectorClient.connect()` for `listChanged` notifications - **COMPLETED** +- ✅ When a `listChanged` notification is received, automatically call the corresponding `list*()` method - **COMPLETED** +- ✅ Dispatch events to notify UI of list changes - **COMPLETED** +- ✅ TUI inherits support automatically through `InspectorClient` - **COMPLETED** +- ❌ Add UI in TUI to handle and display these notifications (optional, but useful for debugging) + +**Code References:** + +- Web client: `client/src/lib/hooks/useConnection.ts` (lines 422-424, 699-704) - Capability declaration and notification handlers +- InspectorClient: `shared/mcp/inspectorClient.ts` (listChanged handlers in `connect()`, ~lines 537-573) - Auto-refresh on `list_changed` + +### 8. Roots Support + +**Use Case:** + +Roots are file system paths (as `file://` URIs) that define which directories an MCP server can access. This is a security feature that allows servers to operate within a sandboxed set of directories. Clients can: + +- List the current roots configured on the server +- Set/update the roots (if the server supports it) +- Receive notifications when roots change + +**Web Client Support:** + +- **Capability Declaration**: Declares `roots: { listChanged: true }` in client capabilities +- **UI Component**: `RootsTab` component allows users to: + - View current roots + - Add new roots (with URI and optional name) + - Remove roots + - Save changes (calls `listRoots` with updated roots) +- **Roots Management**: + - `getRoots` callback passed to `useConnection` hook + - Roots are stored in component state + - When roots are changed, `handleRootsChange` is called to send updated roots to server +- **Notification Support**: Handles `notifications/roots/list_changed` notifications (via fallback handler) + +**InspectorClient Support:** + +- ✅ `getRoots()` method - Returns current roots +- ✅ `setRoots(roots)` method - Updates roots and sends notification to server if supported +- ✅ Handler for `roots/list` requests from server (returns current roots) +- ✅ Notification handler for `notifications/roots/list_changed` from server +- ✅ `roots: { listChanged: true }` capability declaration (when `roots` option is provided) +- ✅ `rootsChange` event dispatched when roots are updated +- ✅ Roots configured via `roots` option in `InspectorClientOptions` (even empty array enables capability) + +**TUI Status:** + +- ❌ No roots management UI +- ❌ No roots configuration support + +**Implementation Requirements:** + +- ✅ `getRoots()` and `setRoots()` methods - **COMPLETED** in `InspectorClient` +- ✅ Handler for `roots/list` requests - **COMPLETED** in `InspectorClient` +- ✅ Notification handler for `notifications/roots/list_changed` - **COMPLETED** in `InspectorClient` +- ✅ `roots: { listChanged: true }` capability declaration - **COMPLETED** in `InspectorClient` +- ❌ Add UI in TUI for managing roots (similar to web client's `RootsTab`) + +**Code References:** + +- `InspectorClient`: `shared/mcp/inspectorClient.ts` - `getRoots()`, `setRoots()`, roots/list handler, and notification support +- Web client: `client/src/components/RootsTab.tsx` - Roots management UI +- Web client: `client/src/lib/hooks/useConnection.ts` (lines 422-424, 357) - Capability declaration and `getRoots` callback +- Web client: `client/src/App.tsx` (lines 1225-1229) - RootsTab usage + +### 9. Custom Headers + +**Use Case:** + +Custom headers are used to send additional HTTP headers when connecting to MCP servers over HTTP-based transports (SSE or streamable-http). Common use cases include: + +- **Authentication**: API keys, bearer tokens, or custom authentication schemes + - Example: `Authorization: Bearer ` + - Example: `X-API-Key: ` +- **Multi-tenancy**: Tenant or organization identifiers + - Example: `X-Tenant-ID: acme-inc` +- **Environment identification**: Staging vs production + - Example: `X-Environment: staging` +- **Custom server requirements**: Any headers required by the MCP server + +**InspectorClient Support:** + +- ✅ `MCPServerConfig` supports `headers: Record` for SSE and streamable-http transports +- ✅ Headers are passed to the SDK transport during creation +- ✅ Headers are included in all HTTP requests to the MCP server +- ✅ Works with both SSE and streamable-http transports +- ❌ Not supported for stdio transport (stdio doesn't use HTTP) + +**Web Client Support:** + +- **UI Component**: `CustomHeaders` component in the Sidebar's authentication section +- **Features**: + - Add/remove headers with name/value pairs + - Enable/disable individual headers (toggle switch) + - Mask header values by default (password field with show/hide toggle) + - Form mode: Individual header inputs + - JSON mode: Edit all headers as a JSON object + - Validation: Only enabled headers with both name and value are sent +- **Integration**: + - Headers are stored in component state + - Passed to `useConnection` hook + - Converted to `Record` format for transport + - OAuth tokens can be automatically injected into `Authorization` header if no custom `Authorization` header exists + - Custom header names are tracked and sent to the proxy server via `x-custom-auth-headers` header + +**TUI Status:** + +- ❌ No header configuration UI +- ❌ No way for users to specify custom headers in TUI server config +- ✅ `InspectorClient` supports headers if provided in config (but TUI doesn't expose this) + +**Implementation Requirements:** + +- Add header configuration UI in TUI server configuration +- Allow users to add/edit/remove headers similar to web client +- Store headers in TUI server config +- Pass headers to `InspectorClient` via `MCPServerConfig.headers` +- Consider masking sensitive header values in the UI + +**Code References:** + +- Web client: `client/src/components/CustomHeaders.tsx` - Header management UI component +- Web client: `client/src/lib/hooks/useConnection.ts` (lines 453-514) - Header processing and transport creation +- `InspectorClient`: `shared/mcp/config.ts` (lines 118-129) - Headers in `MCPServerConfig` +- `InspectorClient`: `shared/mcp/transport.ts` (lines 100-134) - Headers passed to SDK transports + +## Implementation Priority + +### High Priority (Core MCP Features) + +1. **OAuth** - Required for many MCP servers, critical for production use +2. **Sampling** - Core MCP capability, enables LLM sampling workflows +3. **Elicitation** - Core MCP capability, enables interactive workflows +4. **Tasks** - Core MCP capability (v2025-11-25), enables long-running operations without timeouts - ✅ **COMPLETED** in InspectorClient + +### Medium Priority (Enhanced Features) + +5. **Resource Subscriptions** - Useful for real-time resource updates +6. **Completions** - Enhances UX for form filling +7. **Custom Headers** - Useful for custom authentication schemes +8. **ListChanged Notifications** - Auto-refresh lists when server data changes +9. **Roots Support** - Manage file system access for servers +10. **Progress Tracking** - User feedback during long-running operations +11. **Pagination Support** - Handle large lists efficiently (COMPLETED) + +## InspectorClient Extensions Needed + +Based on this analysis, `InspectorClient` needs the following additions: + +1. **Resource Methods** (some already exist): + - ✅ `readResource(uri, metadata?)` - Already exists + - ✅ `listResourceTemplates()` - Already exists + - ✅ Resource template `list` callback support - Already exists (via `listResources()`) + - ✅ `subscribeToResource(uri)` - **COMPLETED** + - ✅ `unsubscribeFromResource(uri)` - **COMPLETED** + - ✅ `getSubscribedResources()` - **COMPLETED** + - ✅ `isSubscribedToResource(uri)` - **COMPLETED** + - ✅ `supportsResourceSubscriptions()` - **COMPLETED** + - ✅ Resource content caching - **COMPLETED** (via `client.cache.getResource()`) + - ✅ Resource template content caching - **COMPLETED** (via `client.cache.getResourceTemplate()`) + - ✅ Prompt content caching - **COMPLETED** (via `client.cache.getPrompt()`) + - ✅ Tool call result caching - **COMPLETED** (via `client.cache.getToolCallResult()`) + +2. **Sampling Support**: + - ✅ `getPendingSamples()` - Already exists + - ✅ `removePendingSample(id)` - Already exists + - ✅ `SamplingCreateMessage.respond(result)` - Already exists + - ✅ `SamplingCreateMessage.reject(error)` - Already exists + - ✅ Automatic request handler setup - Already exists + - ✅ `sampling: {}` capability declaration - Already exists (via `sample` option) + +3. **Elicitation Support**: + - ✅ `getPendingElicitations()` - Already exists + - ✅ `removePendingElicitation(id)` - Already exists + - ✅ `ElicitationCreateMessage.respond(result)` - Already exists + - ✅ Automatic request handler setup - Already exists + - ✅ `elicitation: {}` capability declaration - Already exists (via `elicit` option) + +4. **Completion Support**: + - ✅ `getCompletions(ref, argumentName, argumentValue, context?, metadata?)` - Already exists + - ✅ Supports resource template completions - Already exists + - ✅ Supports prompt argument completions - Already exists + - ❌ Integration into TUI `ResourceTestModal` for template variable completion + - ❌ Integration into TUI `PromptTestModal` for prompt argument completion + +5. **OAuth Support**: + - ✅ OAuth token management (shared auth, configurable storage) + - ✅ OAuth flow initiation (`authenticate()`, `authenticateGuided()`, `completeOAuthFlow()`) + - ✅ Token injection via `authProvider` on HTTP transports + - ✅ TUI integration and UI (OAuth 2.1, static client, CIMD, DCR, guided auth, browser-based flow, localhost callback server) + +6. **ListChanged Notifications**: + - ✅ Notification handlers for `notifications/tools/list_changed` - **COMPLETED** + - ✅ Notification handlers for `notifications/resources/list_changed` - **COMPLETED** + - ✅ Notification handlers for `notifications/prompts/list_changed` - **COMPLETED** + - ✅ Auto-refresh lists when notifications received - **COMPLETED** + - ✅ Configurable via `listChangedNotifications` option - **COMPLETED** + - ✅ Cache preservation and cleanup - **COMPLETED** + +7. **Roots Support**: + - ✅ `getRoots()` method - Already exists + - ✅ `setRoots(roots)` method - Already exists + - ✅ Handler for `roots/list` requests - Already exists + - ✅ Notification handler for `notifications/roots/list_changed` - Already exists + - ✅ `roots: { listChanged: true }` capability declaration - Already exists (when `roots` option provided) + - ❌ Integration into TUI for managing roots + +8. **Pagination Support**: + - ✅ Cursor parameter support in `listResources()` - **COMPLETED** + - ✅ Cursor parameter support in `listResourceTemplates()` - **COMPLETED** + - ✅ Cursor parameter support in `listPrompts()` - **COMPLETED** + - ✅ Cursor parameter support in `listTools()` - **COMPLETED** + - ✅ Return `nextCursor` from list methods - **COMPLETED** + - ✅ Pagination helper methods (`listAll*()`) - **COMPLETED** + +9. **Progress Tracking**: + - ✅ Progress notification handling - Implemented (dispatches `progressNotification` events) + - ✅ Progress token support - Implemented (accepts `progressToken` in metadata) + - ✅ Event-based API - Clients listen for `progressNotification` events (no callbacks needed) + - ✅ Timeout reset on progress - Per-request `onprogress` when progress enabled; `resetTimeoutOnProgress` and `timeout` honored + +## Notes + +- **HTTP Request Tracking**: `InspectorClient` tracks HTTP requests for SSE and streamable-http transports via `getFetchRequests()`. TUI displays these requests in a `RequestsTab`. Web client does not currently display HTTP request tracking, though the underlying `InspectorClient` supports it. This is a TUI advantage, not a gap. +- **Resource Subscriptions**: Web client supports this, but TUI does not. `InspectorClient` now fully supports resource subscriptions with `subscribeToResource()`, `unsubscribeFromResource()`, and automatic handling of `notifications/resources/updated` notifications. +- **OAuth**: Web client has full OAuth support. TUI now supports OAuth 2.1 including static client, CIMD, DCR, and guided auth, with browser-based flow and localhost callback server. +- **Completions**: `InspectorClient` has full completion support via `getCompletions()`. Web client uses this for resource template forms and prompt parameter forms. TUI has both resource template forms and prompt parameter forms, but completion support is still needed to provide autocomplete suggestions. +- **Sampling**: `InspectorClient` has full sampling support. Web client UI displays and handles sampling requests. TUI needs UI to display and handle sampling requests. +- **Elicitation**: `InspectorClient` has full elicitation support. Web client UI displays and handles elicitation requests. TUI needs UI to display and handle elicitation requests. +- **ListChanged Notifications**: Web client handles `listChanged` notifications for tools, resources, and prompts, automatically refreshing lists when notifications are received. `InspectorClient` now fully supports these notifications with automatic list refresh, cache preservation/cleanup, and configurable handlers. TUI automatically benefits from this functionality but doesn't have UI to display notification events. +- **Roots**: `InspectorClient` has full roots support with `getRoots()` and `setRoots()` methods, handler for `roots/list` requests, and notification support. Web client has a `RootsTab` UI for managing roots. TUI does not yet have UI for managing roots. +- **Pagination**: Web client supports cursor-based pagination for all list methods (tools, resources, resource templates, prompts), tracking `nextCursor` state and making multiple requests to fetch all items. `InspectorClient` now fully supports pagination with cursor parameters in all list methods and `listAll*()` helper methods that automatically fetch all pages. TUI inherits this pagination support from `InspectorClient`. +- **Progress Tracking**: Web client supports progress tracking by generating `progressToken`, using `onprogress` callbacks, and displaying progress notifications. `InspectorClient` passes per-request `onprogress` when progress is enabled (so timeout reset is honored), collects `progressToken` from metadata, injects it only into dispatched `progressNotification` events (not sent to server), and passes `resetTimeoutOnProgress`/`timeout` through. TUI does not yet have UI support for displaying progress notifications. +- **Tasks**: Tasks (SEP-1686) were introduced in MCP version 2025-11-25 to support long-running operations through a standardized "call-now, fetch-later" pattern. Web client supports tasks (as of recent release). InspectorClient now fully supports tasks with `callToolStream()`, task management methods, event-driven API, and integration with elicitation/sampling/progress. TUI does not yet have UI for task management. See [Task Support Design](./task-support-design.md) for implementation details. + +## Related Documentation + +- [Shared Code Architecture](./shared-code-architecture.md) - Overall architecture and integration plan +- [InspectorClient Details](./inspector-client-details.svg) - Visual diagram of InspectorClient responsibilities +- [Task Support Design](./task-support-design.md) - Design and implementation plan for Task support +- [MCP Clients Feature Support](https://modelcontextprotocol.info/docs/clients/) - High-level overview of MCP feature support across different clients + +## OAuth in TUI + +Hosted everything test server: https://example-server.modelcontextprotocol.io/mcp + +- Works from web client and TUI +- Determine if it's using DCR or CIMD + - Whichever one, find server that uses the other + +GitHub: https://github.com/github/github-mcp-server/ + +- This fails discovery in web client - appears related to CORS: https://github.com/modelcontextprotocol/inspector/issues/995 +- Test in TUI + +Guided auth + +- Try it in web ux to see how it works + - Record steps and output at each step +- Implement in TUI + +Let's make the "OAuth complete. You can close this window." page a little fancier + +Auth step change give prev/current step, use client.getOAuthState() to get current state (is automatically update as state machine progresses) + +Guided: + +| previousStep | step | state (payload — delta for this transition) | +| ------------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | +| `metadata_discovery` | `client_registration` | `resourceMetadata?`, `resource?`, `resourceMetadataError?`, `authServerUrl`, `oauthMetadata`, `oauthStep: "client_registration"` | +| `client_registration` | `authorization_redirect` | `oauthClientInfo`, `oauthStep: "authorization_redirect"` | +| `authorization_redirect` | `authorization_code` | `authorizationUrl`, `oauthStep: "authorization_code"` | +| `authorization_code` | `token_request` | `validationError: null` (or error string if code missing), `oauthStep: "token_request"` | +| `token_request` | `complete` | `oauthTokens`, `oauthStep: "complete"` | + +Normal: + +| When | oauthStep | getOAuthState() — populated fields | +| ------------------------------------ | -------------------- | ---------------------------------------------------------------------------------------------- | +| Before `authenticate()` | — | `undefined` (no state) | +| After `authenticate()` returns | `authorization_code` | `authType: "normal"`, `oauthStep: "authorization_code"`, `authorizationUrl`, `oauthClientInfo` | +| After `completeOAuthFlow()` succeeds | `complete` | `oauthStep: "complete"`, `oauthTokens`, `completedAt`. | + +Discovery fields (`resourceMetadata`, `oauthMetadata`, `authServerUrl`, `resource`) are null. + +Look at how web client displays Auth info (tab?) + +- We might want to have am Auth tab to show auth details + - Will differ between normal and guided (per above tables) + +## Issues + +Web client / proxy + +When attempting to auth to GitHub, it failed to be able to read the auth server metatata due to CORS + +- auth takes a fetch function for this purpose, and that fetch funciton needs to run in Node (not the browser) for this to work + +When attempting to connect in direct mode to the hosted "everything" server it failed because a CORS issue blocked the mcp-session-id response header from the initialize message + +- This can be addressed by running in proxy mode diff --git a/docs/web-client-port-plan.md b/docs/web-client-port-plan.md new file mode 100644 index 000000000..97975043a --- /dev/null +++ b/docs/web-client-port-plan.md @@ -0,0 +1,1894 @@ +# Web Client Port to InspectorClient - Step-by-Step Plan + +## Overview + +This document provides a step-by-step plan for porting the `web/` application to use `InspectorClient` instead of `useConnection`, integrating the Hono remote API server directly into Vite (eliminating the separate Express server), and ensuring functional parity with the existing `client/` application. + +**Goal:** The `web/` app should function identically to `client/` but use `InspectorClient` and the integrated Hono server instead of `useConnection` and the separate Express proxy. + +## Progress Summary + +- ✅ **Phase 1:** Integrate Hono Server into Vite - **COMPLETE** +- ✅ **Phase 2:** Create Web Client Adapter - **COMPLETE** +- ✅ **Phase 3:** Replace useConnection with InspectorClient - **COMPLETE** (All steps complete) + cd web- ✅ **Phase 4:** OAuth Integration - **COMPLETE** (All OAuth tests rewritten and passing) +- ✅ **Phase 5:** Remove Express Server Dependency - **COMPLETE** (Express proxy completely removed, Hono server handles all functionality) +- ⏸️ **Phase 6:** Testing and Validation - **IN PROGRESS** (Unit tests passing, integration testing remaining) +- ⏸️ **Phase 7:** Cleanup - **PARTIALLY COMPLETE** (useConnection removed, console.log cleaned up) + +**Current Status:** Core InspectorClient integration complete. OAuth integration complete with all tests rewritten. Express proxy completely removed. All unit tests passing (396 tests). Remaining work: Integration testing (Phase 6) and final cleanup (Phase 7). + +**Reference Documents:** + +- [Environment Isolation](./environment-isolation.md) - Details on remote infrastructure and seams +- [Shared Code Architecture](./shared-code-architecture.md) - High-level architecture and integration strategy +- [TUI Web Client Feature Gaps](./tui-web-client-feature-gaps.md) - Feature comparison + +--- + +## Phase 1: Integrate Hono Server into Vite ✅ COMPLETE + +**Goal:** Integrate the Hono remote API server into Vite (dev) and create a production server, making `/api/*` endpoints available. The web app will continue using the existing proxy/useConnection during this phase, allowing us to validate that the new API endpoints are working before migrating the app to use them. + +**Status:** ✅ Complete - Hono server integrated into Vite dev mode and production server created. Both Express proxy and Hono server run simultaneously. + +**Validation:** After Phase 1, you should be able to: + +- Start the dev server: Vite serves static files + Hono middleware handles `/api/*` routes, Express proxy runs separately +- Start the production server: Hono server (`bin/server.js`) serves static files + `/api/*` routes, Express proxy runs separately +- The existing web app continues to work normally in both dev and prod (still uses Express proxy for API calls) +- Hono endpoints (`/api/*`) are available and can be tested, but web app doesn't use them yet + +--- + +### Step 1.1: Create Vite Plugin for Hono Middleware ✅ COMPLETE + +**File:** `web/vite.config.ts` + +**Status:** ✅ Complete + +Create a Vite plugin that adds Hono middleware to handle `/api/*` routes. This runs alongside the existing Express proxy server (which the web app still uses). + +**As-Built:** + +- Implemented `honoMiddlewarePlugin` that mounts Hono middleware at root and checks for `/api` prefix +- Fixed Connect middleware path stripping issue by mounting at root and checking path manually +- Auth token passed via `process.env.MCP_INSPECTOR_API_TOKEN` (read-only, set by start script) + +```typescript +import { defineConfig, Plugin } from "vite"; +import react from "@vitejs/plugin-react"; +import { createRemoteApp } from "@modelcontextprotocol/inspector-shared/mcp/remote/node"; +import { randomBytes } from "node:crypto"; +import type { ConnectMiddleware } from "vite"; + +function honoMiddlewarePlugin(authToken: string): Plugin { + return { + name: "hono-api-middleware", + configureServer(server) { + // createRemoteApp returns { app, authToken } - we pass authToken explicitly + // If not provided, it will read from env or generate one + const { app: honoApp, authToken: resolvedAuthToken } = createRemoteApp({ + authToken, // Pass token explicitly (from start script) + storageDir: process.env.MCP_STORAGE_DIR, + allowedOrigins: [ + `http://localhost:${process.env.CLIENT_PORT || "6274"}`, + `http://127.0.0.1:${process.env.CLIENT_PORT || "6274"}`, + ], + logger: process.env.MCP_LOG_FILE + ? createFileLogger({ logPath: process.env.MCP_LOG_FILE }) + : undefined, + }); + + // Store resolved token for potential use (though we already have it) + // This ensures we use the same token that createRemoteApp is using + const finalAuthToken = authToken || resolvedAuthToken; + + // Convert Connect middleware to handle Hono app + const honoMiddleware: ConnectMiddleware = async (req, res, next) => { + try { + // Convert Node req/res to Web Standard Request + const url = `http://${req.headers.host}${req.url}`; + const headers = new Headers(); + Object.entries(req.headers).forEach(([key, value]) => { + if (value) { + headers.set(key, Array.isArray(value) ? value.join(", ") : value); + } + }); + + const init: RequestInit = { + method: req.method, + headers, + }; + + // Handle body for non-GET requests + if (req.method !== "GET" && req.method !== "HEAD") { + const chunks: Buffer[] = []; + req.on("data", (chunk) => chunks.push(chunk)); + await new Promise((resolve) => { + req.on("end", () => resolve()); + }); + if (chunks.length > 0) { + init.body = Buffer.concat(chunks); + } + } + + const request = new Request(url, init); + const response = await honoApp.fetch(request); + + // Convert Web Standard Response back to Node res + res.statusCode = response.status; + response.headers.forEach((value, key) => { + res.setHeader(key, value); + }); + + if (response.body) { + const reader = response.body.getReader(); + const pump = async () => { + const { done, value } = await reader.read(); + if (done) { + res.end(); + } else { + res.write(Buffer.from(value)); + await pump(); + } + }; + await pump(); + } else { + res.end(); + } + } catch (error) { + next(error); + } + }; + + server.middlewares.use("/api", honoMiddleware); + }, + }; +} + +export default defineConfig({ + plugins: [ + react(), + // Auth token is passed via env var (read-only, set by start script) + // Vite plugin reads it and passes explicitly to createRemoteApp + honoMiddlewarePlugin(process.env.MCP_INSPECTOR_API_TOKEN || ""), + ], + // ... rest of config +}); +``` + +**Dependencies needed:** + +- `@modelcontextprotocol/inspector-shared` (already in workspace) +- `node:crypto` for `randomBytes` + +**Auth Token Handling:** + +The auth token flow: + +1. **Start script (`bin/start.js`)**: Reads `process.env.MCP_INSPECTOR_API_TOKEN` or generates one +2. **Vite plugin**: Receives token via env var (read-only, passed to spawned process). Plugin reads it and passes explicitly to `createRemoteApp()` +3. **Client browser**: Receives token via URL params (`?MCP_INSPECTOR_API_TOKEN=...`) + +**Key principle:** We never write to `process.env` to pass values between our own code. The token is: + +- Generated/read once in the start script +- Passed explicitly to Vite via env var (read-only, for the spawned process) +- Passed explicitly to `createRemoteApp()` via function parameter +- Passed to client via URL params + +**Testing:** + +- Start dev server: `npm run dev` (this will start both Vite with Hono middleware AND the Express proxy) +- Verify `/api/mcp/connect` endpoint responds (should return 401 without auth token) + - Test: `curl http://localhost:6274/api/mcp/connect` (should return 401) +- Verify `/api/fetch` endpoint exists: `curl http://localhost:6274/api/fetch` +- Verify `/api/log` endpoint exists: `curl http://localhost:6274/api/log` +- Check browser console for errors (should be none - web app still uses Express proxy) +- Verify auth token is passed to client via URL params (for future use) +- **Important:** The web app should still work normally using the Express proxy - we're just validating the new endpoints exist + +--- + +### Step 1.2: Create Production Server ✅ COMPLETE + +**File:** `web/bin/server.js` (new file) + +**Status:** ✅ Complete + +Create a production server that serves static files and API routes: + +**As-Built:** + +- Created `web/bin/server.js` that serves static files and routes `/api/*` to `apiApp` +- Static files served without authentication, API routes require auth token +- Auth token read from `process.env.MCP_INSPECTOR_API_TOKEN` + +```typescript +#!/usr/bin/env node + +import { serve } from "@hono/node-server"; +import { serveStatic } from "@hono/node-server/serve-static"; +import { Hono } from "hono"; +import { createRemoteApp } from "@modelcontextprotocol/inspector-shared/mcp/remote/node"; +import { join, dirname } from "path"; +import { fileURLToPath } from "url"; +import { randomBytes } from "node:crypto"; +import { createFileLogger } from "@modelcontextprotocol/inspector-shared/mcp/node/logger"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const distPath = join(__dirname, "../dist"); + +const app = new Hono(); + +// Read auth token from env (provided by start script via spawn env) +// createRemoteApp will use this, or generate one if not provided +// The token is passed explicitly from start script, not written to process.env +const authToken = + process.env.MCP_INSPECTOR_API_TOKEN || randomBytes(32).toString("hex"); + +// Note: createRemoteApp returns the authToken it uses, so we could also +// let it generate one and return it, but for consistency we generate/read it here + +// Add API routes first (more specific) +const port = parseInt(process.env.CLIENT_PORT || "6274", 10); +const host = process.env.HOST || "localhost"; +const baseUrl = `http://${host}:${port}`; + +const { app: apiApp } = createRemoteApp({ + authToken, + storageDir: process.env.MCP_STORAGE_DIR, + allowedOrigins: process.env.ALLOWED_ORIGINS?.split(",") || [baseUrl], + logger: process.env.MCP_LOG_FILE + ? createFileLogger({ logPath: process.env.MCP_LOG_FILE }) + : undefined, +}); +app.route("/api", apiApp); + +// Then add static file serving (fallback for SPA routing) +app.use( + "/*", + serveStatic({ + root: distPath, + rewriteRequestPath: (path) => { + // If path doesn't exist and doesn't have extension, serve index.html (SPA routing) + if (!path.includes(".") && !path.startsWith("/api")) { + return "/index.html"; + } + return path; + }, + }), +); + +serve( + { + fetch: app.fetch, + port, + hostname: host, + }, + (info) => { + console.log( + `\n🚀 MCP Inspector Web is up and running at:\n http://${host}:${info.port}\n`, + ); + console.log(` Auth token: ${authToken}\n`); + }, +); +``` + +**Update `web/package.json`:** + +- Add `start` script: `"start": "node bin/server.js"` +- Ensure `bin/server.js` is executable (chmod +x) + +**Dependencies needed:** + +- `@hono/node-server` (add to `web/package.json`) + +**Testing:** + +- Build: `npm run build` +- Start: `npm start` (via `bin/start.js` - starts Hono server for static files + `/api/*` endpoints, AND Express proxy) +- Verify static files serve correctly: `curl http://localhost:6274/` (should return index.html from Hono server) +- Verify `/api/mcp/connect` endpoint works: `curl http://localhost:6274/api/mcp/connect` (should return 401) +- Verify `/api/fetch` endpoint exists: `curl http://localhost:6274/api/fetch` +- Verify `/api/log` endpoint exists: `curl http://localhost:6274/api/log` +- Verify auth token is logged/available +- **Note:** Both Hono server (serving static files) and Express proxy run simultaneously. Web app uses Express proxy for API calls, but static files come from Hono server. + +--- + +### Step 1.3: Update Start Script (Keep Express Proxy for Now) ✅ COMPLETE + +**File:** `web/bin/start.js` + +**Status:** ✅ Complete + +**Important:** During Phase 1, both servers run: + +**As-Built:** + +- Start script generates both `proxySessionToken` (for Express) and `honoAuthToken` (for Hono) +- Tokens passed explicitly via environment variables (for spawned processes) and URL params (for browser) +- Both Express proxy and Vite/Hono server run simultaneously in dev/prod mode + +- **Hono server**: Serves static files (dev: via Vite middleware, prod: via `bin/server.js`) + `/api/*` endpoints +- **Express proxy**: Handles web app API calls (`/mcp`, `/stdio`, `/sse`, etc.) +- Web app loads static files from Hono server but makes API calls to Express proxy + +**Changes:** + +1. **Keep server spawning functions (for now):** + - Keep `startDevServer()` function (spawns Express proxy) + - Keep `startProdServer()` function (spawns Express proxy) + - Both Hono (via Vite middleware) and Express will run simultaneously in dev mode + +2. **Update `startDevClient()` to pass auth token to Vite:** + + ```typescript + async function startDevClient(clientOptions) { + const { CLIENT_PORT, honoAuthToken, abort, cancelled } = clientOptions; + const clientCommand = "npx"; + const host = process.env.HOST || "localhost"; + const clientArgs = ["vite", "--port", CLIENT_PORT, "--host", host]; + + const client = spawn(clientCommand, clientArgs, { + cwd: resolve(__dirname, ".."), + env: { + ...process.env, + CLIENT_PORT, + MCP_INSPECTOR_API_TOKEN: honoAuthToken, // Pass token to Vite (read-only) + // Note: Express proxy still uses MCP_PROXY_AUTH_TOKEN (different token) + }, + signal: abort.signal, + echoOutput: true, + }); + + // Include auth token in URL for client (Phase 3 will use this) + const params = new URLSearchParams(); + params.set("MCP_INSPECTOR_API_TOKEN", honoAuthToken); + const url = `http://${host}:${CLIENT_PORT}/?${params.toString()}`; + + setTimeout(() => { + console.log(`\n🚀 MCP Inspector Web is up and running at:\n ${url}\n`); + console.log( + ` Static files served by: Vite (dev) / Hono server (prod)\n`, + ); + console.log(` Hono API endpoints: ${url}/api/*\n`); + console.log( + ` Express proxy: http://localhost:${SERVER_PORT} (web app API calls)\n`, + ); + if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") { + console.log("🌐 Opening browser..."); + open(url); + } + }, 3000); + + await new Promise((resolve) => { + client.subscribe({ + complete: resolve, + error: (err) => { + if (!cancelled || process.env.DEBUG) { + console.error("Client error:", err); + } + resolve(null); + }, + next: () => {}, + }); + }); + } + ``` + + **Note:** In dev mode, both servers run: + - Express proxy: `http://localhost:6277` (web app uses this) + - Hono API (via Vite): `http://localhost:6274/api/*` (available for validation) + +3. **Update `startProdClient()` - Use Hono server for static files:** + + ```typescript + async function startProdClient(clientOptions) { + const { CLIENT_PORT, honoAuthToken, abort } = clientOptions; + const honoServerPath = resolve(__dirname, "bin", "server.js"); + + // Hono server serves static files + /api/* endpoints + // Pass auth token explicitly via env var (read-only, server reads it) + await spawnPromise("node", [honoServerPath], { + env: { + ...process.env, + CLIENT_PORT, + MCP_INSPECTOR_API_TOKEN: honoAuthToken, // Pass token explicitly + }, + signal: abort.signal, + echoOutput: true, + }); + } + ``` + + **Note:** In Phase 1, prod mode uses Hono server to serve static files (just like Vite does in dev mode). Express proxy still runs separately for API calls. Web app loads static files from Hono server but makes API calls to Express proxy. Auth token is passed explicitly via env var (read-only). + +4. **Update `main()` function to run both servers in dev mode:** + + ```typescript + async function main() { + // ... parse args (same as before) ... + + const CLIENT_PORT = process.env.CLIENT_PORT ?? "6274"; + const SERVER_PORT = + process.env.SERVER_PORT ?? DEFAULT_MCP_PROXY_LISTEN_PORT; + + // Generate auth tokens (separate tokens for Express proxy and Hono API) + const proxySessionToken = + process.env.MCP_PROXY_AUTH_TOKEN || randomBytes(32).toString("hex"); + const honoAuthToken = + process.env.MCP_INSPECTOR_API_TOKEN || randomBytes(32).toString("hex"); + + const abort = new AbortController(); + let cancelled = false; + process.on("SIGINT", () => { + cancelled = true; + abort.abort(); + }); + + let server, serverOk; + + if (isDev) { + // In dev mode: start Express proxy (web app uses this) AND Vite with Hono middleware + try { + const serverOptions = { + SERVER_PORT, + CLIENT_PORT, + sessionToken: proxySessionToken, + envVars, + abort, + command, + mcpServerArgs, + transport, + serverUrl, + }; + + const result = await startDevServer(serverOptions); + server = result.server; + serverOk = result.serverOk; + } catch (error) { + // Continue even if Express proxy fails - Hono API still works + console.warn("Express proxy failed to start:", error); + serverOk = false; + } + + if (serverOk) { + // Start Vite with Hono middleware (runs alongside Express proxy) + try { + const clientOptions = { + CLIENT_PORT, + SERVER_PORT, + honoAuthToken, // Pass Hono auth token explicitly + abort, + cancelled, + }; + await startDevClient(clientOptions); + } catch (e) { + if (!cancelled || process.env.DEBUG) throw e; + } + } + } else { + // In prod mode: start Express proxy (web app uses this) AND Hono server + try { + const serverOptions = { + SERVER_PORT, + CLIENT_PORT, + sessionToken: proxySessionToken, + envVars, + abort, + command, + mcpServerArgs, + transport, + serverUrl, + }; + + const result = await startProdServer(serverOptions); + server = result.server; + serverOk = result.serverOk; + } catch (error) { + console.warn("Express proxy failed to start:", error); + serverOk = false; + } + + if (serverOk) { + // Start Hono server (serves static files + /api/* endpoints) + try { + const clientOptions = { + CLIENT_PORT, + honoAuthToken, // Pass token explicitly + abort, + cancelled, + }; + await startProdClient(clientOptions); + } catch (e) { + if (!cancelled || process.env.DEBUG) throw e; + } + } + + // Both servers run: + // - Hono server (via startProdClient) serves static files + /api/* endpoints + // - Express proxy (via startProdServer) handles web app API calls + } + + return 0; + } + ``` + + **Key points:** + - In dev mode: Both Express proxy (port 6277) and Hono API (port 6274/api/\*) run simultaneously + - Web app continues using Express proxy (no changes needed yet) + - Hono API endpoints are available for validation/testing + - Separate auth tokens: `MCP_PROXY_AUTH_TOKEN` (Express) and `MCP_INSPECTOR_API_TOKEN` (Hono) + +--- + +## Phase 2: Create Web Client Adapter ✅ COMPLETE + +### Step 2.1: Create Config to MCPServerConfig Adapter ✅ COMPLETE + +**File:** `web/src/lib/adapters/configAdapter.ts` (new file) + +**Status:** ✅ Complete + +**Existing Code Reference:** + +- `client/src/components/Sidebar.tsx` has `generateServerConfig()` (lines 137-160) that converts web client format, but it's missing `type: "stdio"` and doesn't handle `customHeaders` +- `shared/mcp/node/config.ts` has `argsToMcpServerConfig()` for CLI format, but not web client format + +Create an adapter that converts the web client's configuration format to `MCPServerConfig`: + +```typescript +import type { MCPServerConfig } from "@modelcontextprotocol/inspector-shared/mcp/types"; +import type { CustomHeaders } from "../types/customHeaders"; + +export function webConfigToMcpServerConfig( + transportType: "stdio" | "sse" | "streamable-http", + command?: string, + args?: string, + sseUrl?: string, + env?: Record, + customHeaders?: CustomHeaders, +): MCPServerConfig { + switch (transportType) { + case "stdio": { + if (!command) { + throw new Error("Command is required for stdio transport"); + } + const config: MCPServerConfig = { + type: "stdio", + command, + }; + if (args?.trim()) { + config.args = args.split(/\s+/); + } + if (env && Object.keys(env).length > 0) { + config.env = env; + } + return config; + } + case "sse": { + if (!sseUrl) { + throw new Error("SSE URL is required for SSE transport"); + } + const headers: Record = {}; + customHeaders?.forEach((header) => { + if (header.enabled) { + headers[header.name] = header.value; + } + }); + const config: MCPServerConfig = { + type: "sse", + url: sseUrl, + }; + if (Object.keys(headers).length > 0) { + config.headers = headers; + } + return config; + } + case "streamable-http": { + if (!sseUrl) { + throw new Error("Server URL is required for streamable-http transport"); + } + const headers: Record = {}; + customHeaders?.forEach((header) => { + if (header.enabled) { + headers[header.name] = header.value; + } + }); + const config: MCPServerConfig = { + type: "streamable-http", + url: sseUrl, + }; + if (Object.keys(headers).length > 0) { + config.headers = headers; + } + return config; + } + } +} +``` + +**Note:** This is similar to `generateServerConfig()` in `Sidebar.tsx` but: + +- Adds `type: "stdio"` for stdio transport +- Converts `customHeaders` array to `headers` object (only enabled headers) +- Returns proper `MCPServerConfig` type (no `note` field) + +--- + +### Step 2.2: Create Environment Factory ✅ COMPLETE + +**File:** `web/src/lib/adapters/environmentFactory.ts` (new file) + +**Status:** ✅ Complete + +Create a factory function that builds the `InspectorClientEnvironment` object: + +**As-Built:** + +- Fixed "Illegal invocation" error by wrapping `window.fetch` to preserve `this` context: `const fetchFn: typeof fetch = (...args) => globalThis.fetch(...args)` +- Uses `BrowserOAuthStorage` and `BrowserNavigation` for OAuth +- `redirectUrlProvider` consistently returns `/oauth/callback` regardless of mode (mode stored in state, not URL) + +```typescript +import type { InspectorClientEnvironment } from "@modelcontextprotocol/inspector-shared/mcp/inspectorClient"; +import { createRemoteTransport } from "@modelcontextprotocol/inspector-shared/mcp/remote/createRemoteTransport"; +import { createRemoteFetch } from "@modelcontextprotocol/inspector-shared/mcp/remote/createRemoteFetch"; +import { createRemoteLogger } from "@modelcontextprotocol/inspector-shared/mcp/remote/createRemoteLogger"; +import { BrowserOAuthStorage } from "@modelcontextprotocol/inspector-shared/auth/browser"; +import { BrowserNavigation } from "@modelcontextprotocol/inspector-shared/auth/browser"; +import type { RedirectUrlProvider } from "@modelcontextprotocol/inspector-shared/auth/types"; + +export function createWebEnvironment( + authToken: string | undefined, + redirectUrlProvider: RedirectUrlProvider, +): InspectorClientEnvironment { + const baseUrl = `${window.location.protocol}//${window.location.host}`; + + return { + transport: createRemoteTransport({ + baseUrl, + authToken, + fetchFn: window.fetch, + }), + fetch: createRemoteFetch({ + baseUrl, + authToken, + fetchFn: window.fetch, + }), + logger: createRemoteLogger({ + baseUrl, + authToken, + fetchFn: window.fetch, + }), + oauth: { + storage: new BrowserOAuthStorage(), // or RemoteOAuthStorage for shared state + navigation: new BrowserNavigation(), + redirectUrlProvider, + }, + }; +} +``` + +**Note:** Consider using `RemoteOAuthStorage` if you want shared OAuth state with TUI/CLI. The auth token should come from the Hono server (same token used to create the server). + +--- + +## Phase 3: Replace useConnection with InspectorClient ✅ COMPLETE + +### Step 3.1: Understand useInspectorClient Interface ✅ COMPLETE + +**Reference:** `shared/react/useInspectorClient.ts` + +**Status:** ✅ Complete - Hook interface understood and used throughout implementation + +The `useInspectorClient` hook returns: + +```typescript +interface UseInspectorClientResult { + status: ConnectionStatus; // 'disconnected' | 'connecting' | 'connected' | 'error' + messages: MessageEntry[]; + stderrLogs: StderrLogEntry[]; + fetchRequests: FetchRequestEntry[]; + tools: Tool[]; + resources: Resource[]; + resourceTemplates: ResourceTemplate[]; + prompts: Prompt[]; + capabilities?: ServerCapabilities; + serverInfo?: Implementation; + instructions?: string; + client: Client | null; // The underlying MCP SDK Client + connect: () => Promise; + disconnect: () => Promise; +} +``` + +**Note:** The hook uses `status` (not `connectionStatus`). You'll need to map this when replacing `useConnection` calls in components. + +--- + +### Step 3.2: Update App.tsx to Use InspectorClient ✅ COMPLETE + +**File:** `web/src/App.tsx` + +**Status:** ✅ Complete + +**Changes:** + +**As-Built:** + +- Removed local state syncing (`useEffect` blocks) for resources, prompts, tools, resourceTemplates +- Removed local state declarations - now using hook values directly (`inspectorResources`, `inspectorPrompts`, `inspectorTools`, `inspectorResourceTemplates`) +- Updated all component props to use hook values +- InspectorClient instance created in `useMemo` with proper dependencies +- Auth token extracted from URL params (`MCP_INSPECTOR_API_TOKEN`) +- `useInspectorClient` hook used to get all state and methods + +1. **Replace imports:** + + ```typescript + // Remove + import { useConnection } from "./lib/hooks/useConnection"; + + // Add + import { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/inspectorClient"; + import { useInspectorClientWeb } from "./lib/hooks/useInspectorClientWeb"; + import { createWebEnvironment } from "./lib/adapters/environmentFactory"; + import { webConfigToMcpServerConfig } from "./lib/adapters/configAdapter"; + ``` + +2. **Get auth token and create InspectorClient instance:** + + ```typescript + // Get auth token from URL params (set by start script) or localStorage + const authToken = useMemo(() => { + const params = new URLSearchParams(window.location.search); + return params.get("MCP_INSPECTOR_API_TOKEN") || null; + }, []); + + const inspectorClient = useMemo(() => { + if (!command && !sseUrl) return null; // Can't create without config + if (!authToken) return null; // Need auth token for remote API + + const config = webConfigToMcpServerConfig( + transportType, + command, + args, + sseUrl, + env, + customHeaders, + ); + + const environment = createWebEnvironment(authToken, () => { + return `${window.location.origin}/oauth/callback`; + }); + + return new InspectorClient(config, { + environment, + autoFetchServerContents: true, // Match current behavior + maxMessages: 1000, + maxStderrLogEvents: 1000, + maxFetchRequests: 1000, + oauth: { + clientId: oauthClientId || undefined, + clientSecret: oauthClientSecret || undefined, + scope: oauthScope || undefined, + }, + }); + }, [ + transportType, + command, + args, + sseUrl, + env, + customHeaders, + oauthClientId, + oauthClientSecret, + oauthScope, + authToken, + ]); + ``` + +3. **Replace useConnection hook:** + + ```typescript + // Remove + const { connectionStatus, ... } = useConnection({ ... }); + + // Add + const { + status: connectionStatus, // Map 'status' to 'connectionStatus' for compatibility + tools, + resources, + prompts, + messages, + stderrLogs, + fetchRequests, + capabilities, + serverInfo, + instructions, + client: mcpClient, + connect: connectMcpServer, + disconnect: disconnectMcpServer, + } = useInspectorClient(inspectorClient); + ``` + +4. **Update connect/disconnect handlers:** + + ```typescript + // These are now provided by useInspectorClient hook: + // connectMcpServer and disconnectMcpServer are already available from the hook + // No need to create separate handlers unless you need custom logic + ``` + +5. **Update OAuth handlers:** + - Replace `useConnection` OAuth methods with `InspectorClient` methods: + - `authenticate()` → `inspectorClient.authenticate()` + - `completeOAuthFlow()` → `inspectorClient.completeOAuthFlow()` + - `getOAuthTokens()` → `inspectorClient.getOAuthTokens()` + +--- + +### Step 3.3: Migrate State Format ✅ COMPLETE + +**File:** `web/src/App.tsx` + +**Status:** ✅ Complete + +**Changes:** + +1. **Message History:** ✅ Complete + - **As-Built:** `requestHistory` now uses MCP protocol messages from `inspectorMessages` + - Filters `inspectorMessages` for `direction === "request"` (non-notification messages) + - Converts to format: `{ request: string, response?: string }[]` for `HistoryAndNotifications` component + - **Note:** History tab shows MCP protocol messages (requests/responses), not HTTP requests + +2. **Request History:** ✅ Complete + - **As-Built:** Not using `FetchRequestEntry[]` - instead using MCP protocol messages for History tab + - `fetchRequests` removed from hook destructuring (not needed for current UI) + +3. **Stderr Logs:** ✅ Complete + - `stderrLogs` destructured from hook and passed to `ConsoleTab` + - `ConsoleTab` displays `StderrLogEntry[]` with timestamps and messages + - **As-Built:** Console tab trigger added to UI, only shown when `transportType === "stdio"` (since stderr logs are only available for stdio transports) + - Console tab added to valid tabs list for routing + +4. **Server Data:** ✅ Complete + - Tools, Resources, Prompts: Using hook values directly (`inspectorTools`, `inspectorResources`, `inspectorPrompts`) + - Manual fetching logic removed - InspectorClient handles this automatically + +--- + +### Step 3.4: Update Notification Handlers ✅ COMPLETE + +**File:** `web/src/App.tsx` + +**Status:** ✅ Complete + +**Changes:** + +1. **Replace notification callbacks:** ✅ Complete + - **As-Built:** Notifications extracted from `inspectorMessages` via `useMemo` + `useEffect` with content comparison to prevent infinite loops: + + ```typescript + const extractedNotifications = useMemo(() => { + return inspectorMessages + .filter((msg) => msg.direction === "notification" && msg.message) + .map((msg) => msg.message as ServerNotification); + }, [inspectorMessages]); + + const previousNotificationsRef = useRef("[]"); + useEffect(() => { + const currentSerialized = JSON.stringify(extractedNotifications); + if (currentSerialized !== previousNotificationsRef.current) { + setNotifications(extractedNotifications); + previousNotificationsRef.current = currentSerialized; + } + }, [extractedNotifications]); + ``` + + - **Bug Fix:** Fixed infinite loop caused by `InspectorClient.getMessages()` returning new array references. Fixed in `useInspectorClient` hook by comparing serialized content before updating state. + - No separate event listeners needed - notifications come from message stream + +2. **Update request handlers:** ✅ Complete + - **Elicitation:** ✅ Complete - Using `inspectorClient.addEventListener("newPendingElicitation", ...)` + - **Sampling:** ✅ Complete - Using `inspectorClient.addEventListener("newPendingSample", ...)` + - **Roots:** ✅ Complete - Using `inspectorClient.getRoots()`, `inspectorClient.setRoots()`, and listening to `rootsChange` event + - `handleRootsChange()` calls `inspectorClient.setRoots(roots)` which handles sending notification internally + - Roots synced with InspectorClient via `useEffect` and `rootsChange` event listener + +3. **Stderr Logs:** ✅ Complete + - **As-Built:** `stderrLogs` destructured from `useInspectorClient` hook + - `ConsoleTab` component updated to accept and display `StderrLogEntry[]` + - Displays timestamp and message for each stderr log entry + - Shows "No stderr output yet" when empty + +--- + +### Step 3.5: Update Method Calls ✅ COMPLETE + +**File:** `web/src/App.tsx` and component files + +**Status:** ✅ Complete + +**Changes:** + +Replace all `mcpClient` method calls with `inspectorClient` methods: + +**As-Built:** + +- ✅ `listResources()` → `inspectorClient.listResources(cursor, metadata)` +- ✅ `listResourceTemplates()` → `inspectorClient.listResourceTemplates(cursor, metadata)` +- ✅ `readResource()` → `inspectorClient.readResource(uri, metadata)` +- ✅ `subscribeToResource()` → `inspectorClient.subscribeToResource(uri)` +- ✅ `unsubscribeFromResource()` → `inspectorClient.unsubscribeFromResource(uri)` +- ✅ `listPrompts()` → `inspectorClient.listPrompts(cursor, metadata)` +- ✅ `getPrompt()` → `inspectorClient.getPrompt(name, args, metadata)` (with JsonValue conversion) +- ✅ `listTools()` → `inspectorClient.listTools(cursor, metadata)` +- ✅ `callTool()` → `inspectorClient.callTool(name, args, generalMetadata, toolSpecificMetadata)` (with ToolCallInvocation → CompatibilityCallToolResult conversion) +- ✅ `sendLogLevelRequest()` → `inspectorClient.setLoggingLevel(level)` +- ✅ Ping → `mcpClient.request({ method: "ping" }, EmptyResultSchema)` (direct SDK call) +- ✅ Removed `sendMCPRequest()` wrapper function +- ✅ Removed `makeRequest()` wrapper function +- ✅ All methods include proper error handling with `clearError()` calls + +--- + +## Phase 4: OAuth Integration + +**Status:** ✅ COMPLETE + +**Goal:** Replace custom OAuth implementation (`InspectorOAuthClientProvider`, `OAuthStateMachine`, manual state management) with `InspectorClient`'s built-in OAuth support, matching the TUI implementation pattern. + +--- + +### Architecture Overview + +**Current State (Web App):** + +- Custom `InspectorOAuthClientProvider` and `DebugInspectorOAuthClientProvider` classes (`web/src/lib/auth.ts`) +- Custom `OAuthStateMachine` class (`web/src/lib/oauth-state-machine.ts`) - duplicates shared implementation +- Manual OAuth state management via `AuthGuidedState` in `App.tsx` +- `OAuthCallback` component uses SDK `auth()` directly +- `AuthDebugger` component uses custom state machine for guided flow +- `OAuthFlowProgress` component displays custom state + +**Target State (After Port):** + +- Use `InspectorClient` OAuth methods: `authenticate()`, `completeOAuthFlow()`, `beginGuidedAuth()`, `proceedOAuthStep()`, `getOAuthState()`, `getOAuthTokens()` +- Use shared `BrowserOAuthStorage` and `BrowserNavigation` (already configured in `createWebEnvironment`) +- Listen to `InspectorClient` OAuth events: `oauthStepChange`, `oauthComplete`, `oauthError` +- Remove custom OAuth providers and state machine +- Simplify components to read from `InspectorClient.getOAuthState()` + +**Reference Implementation (TUI):** + +- TUI uses `InspectorClient` OAuth methods directly +- Quick Auth: Creates callback server → sets redirect URL → calls `authenticate()` → waits for callback → calls `completeOAuthFlow()` +- Guided Auth: Calls `beginGuidedAuth()` → listens to `oauthStepChange` events → calls `proceedOAuthStep()` for each step +- OAuth state synced via `inspectorClient.getOAuthState()` and `oauthStepChange` events + +--- + +### Step 4.1: Follow TUI Pattern - Components Manage OAuth State Directly + +**Approach:** Follow the TUI pattern where components that need OAuth state manage it directly, rather than extending the hook. + +**Rationale:** TUI's `AuthTab` component doesn't use `useInspectorClient` for OAuth state. Instead, it: + +1. Receives `inspectorClient` as a prop +2. Uses `useState` to manage `oauthState` locally +3. Uses `useEffect` to sync state by calling `inspectorClient.getOAuthState()` directly +4. Listens to `oauthStepChange` and `oauthComplete` events directly on `inspectorClient` + +**Alternative Approach (Optional):** We could extend `useInspectorClient` to expose OAuth state, which would be more DRY if multiple components need it. However, since only `AuthDebugger` needs OAuth state in the web app, following the TUI pattern is simpler and more consistent. + +**Implementation Pattern (for AuthDebugger):** + +```typescript +const AuthDebugger = ({ inspectorClient, onBack }: AuthDebuggerProps) => { + const { toast } = useToast(); + const [oauthState, setOauthState] = useState( + undefined, + ); + const [isInitiatingAuth, setIsInitiatingAuth] = useState(false); + + // Sync oauthState from InspectorClient (TUI pattern) + useEffect(() => { + if (!inspectorClient) { + setOauthState(undefined); + return; + } + + const update = () => setOauthState(inspectorClient.getOAuthState()); + update(); + + const onStepChange = () => update(); + inspectorClient.addEventListener("oauthStepChange", onStepChange); + inspectorClient.addEventListener("oauthComplete", onStepChange); + inspectorClient.addEventListener("oauthError", onStepChange); + + return () => { + inspectorClient.removeEventListener("oauthStepChange", onStepChange); + inspectorClient.removeEventListener("oauthComplete", onStepChange); + inspectorClient.removeEventListener("oauthError", onStepChange); + }; + }, [inspectorClient]); + + // OAuth methods call InspectorClient directly + const handleQuickOAuth = useCallback(async () => { + if (!inspectorClient) return; + setIsInitiatingAuth(true); + try { + await inspectorClient.authenticate(); + } catch (error) { + // Handle error + } finally { + setIsInitiatingAuth(false); + } + }, [inspectorClient]); + + const handleGuidedOAuth = useCallback(async () => { + if (!inspectorClient) return; + setIsInitiatingAuth(true); + try { + await inspectorClient.beginGuidedAuth(); + } catch (error) { + // Handle error + } finally { + setIsInitiatingAuth(false); + } + }, [inspectorClient]); + + const proceedToNextStep = useCallback(async () => { + if (!inspectorClient) return; + setIsInitiatingAuth(true); + try { + await inspectorClient.proceedOAuthStep(); + } catch (error) { + // Handle error + } finally { + setIsInitiatingAuth(false); + } + }, [inspectorClient]); + + // ... rest of component uses oauthState ... +}; +``` + +**Benefits of This Approach:** + +- Matches TUI implementation exactly +- No changes needed to shared hook (avoids affecting TUI) +- Simpler - OAuth state only where needed +- Components have direct access to `inspectorClient` methods + +**Note:** If we later need OAuth state in multiple components, we can refactor to extend the hook then. For now, following TUI pattern is the simplest path. + +--- + +### Step 4.2: Update OAuth Callback Component (Single Redirect URL Approach) + +**File:** `web/src/components/OAuthCallback.tsx` + +**Current Implementation:** + +- Uses `InspectorOAuthClientProvider` + SDK `auth()` function +- Reads `serverUrl` from `sessionStorage` +- Calls `onConnect(serverUrl)` after success + +**As-Built Implementation:** + +**Key Design Decision: Single Redirect URL with State Parameter** + +- Uses a single `/oauth/callback` endpoint for both normal and guided modes +- Mode is encoded in the OAuth `state` parameter: `"guided:{random}"` or `"normal:{random}"` +- Matches TUI implementation pattern (no separate debug endpoint) + +**Changes:** + +1. **Remove custom provider imports:** + + ```typescript + // Remove + import { InspectorOAuthClientProvider } from "../lib/auth"; + import { auth } from "@modelcontextprotocol/sdk/client/auth.js"; + import { SESSION_KEYS } from "../lib/constants"; + + // Add + import type { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; + import { parseOAuthState } from "@modelcontextprotocol/inspector-shared/auth/index.js"; + ``` + +2. **Update component props:** + + ```typescript + interface OAuthCallbackProps { + inspectorClient: InspectorClient | null; + ensureInspectorClient: () => InspectorClient | null; + onConnect: () => void; + } + ``` + +3. **Guided Mode Handling (New Tab Scenario):** + - When callback occurs in a new tab without `InspectorClient` context: + - Parse `state` parameter to detect guided mode + - Display authorization code for manual copying + - Store code in `sessionStorage` for potential auto-fill (future enhancement) + - **Do NOT redirect** - user must manually copy code and return to Guided Auth flow + - Message: "Please copy this authorization code and return to the Guided Auth flow:" + +4. **Guided Mode Handling (Same Tab Scenario):** + - When callback occurs in same tab with `InspectorClient` available: + - Call `client.setGuidedAuthorizationCode(code, false)` to set code without auto-completing + - Show toast notification + - **Do NOT redirect** - user controls progression manually + +5. **Normal Mode Handling:** + - Call `client.completeOAuthFlow(code)` to complete flow automatically + - Trigger auto-connect + - Redirect to root (`/`) after completion + +**Key Implementation Details:** + +- Uses `parseOAuthState()` to extract mode from `state` parameter +- Early return for guided mode without client to avoid "API token required" toast +- Remote logging via `InspectorClient.logger` (persists through redirects) +- Handles both `/oauth/callback` and `/` paths (some auth servers redirect incorrectly) + +**Key Changes:** + +- Removed `sessionStorage` dependency (server URL comes from `InspectorClient` config) +- Replaced `InspectorOAuthClientProvider` + `auth()` with `inspectorClient.completeOAuthFlow()` or `setGuidedAuthorizationCode()` +- Single callback endpoint handles both modes via state parameter +- Guided mode shows code for manual copying (no redirect) +- Normal mode auto-completes and redirects + +--- + +### Step 4.3: Remove OAuth Debug Callback Component (Consolidated) + +**File:** `web/src/components/OAuthDebugCallback.tsx` + +**Status:** ✅ Removed - functionality consolidated into `OAuthCallback.tsx` + +**Rationale:** + +- Single redirect URL approach eliminates need for separate debug endpoint +- Guided mode is handled via state parameter in single callback +- Component removed, functionality merged into `OAuthCallback` + +--- + +### Step 4.4: Update App.tsx OAuth Routes and Handlers + +**File:** `web/src/App.tsx` + +**Current Implementation:** + +- Routes `/oauth/callback` and `/oauth/callback/debug` render callback components +- `onOAuthConnect` and `onOAuthDebugConnect` handlers manage state +- OAuth config (clientId, clientSecret, scope) stored in component state + +**As-Built Changes:** + +1. **Single OAuth callback route:** + + ```typescript + // Handle both /oauth/callback and / paths (some auth servers redirect incorrectly) + const hasOAuthCallbackParams = urlParams.has("code") || urlParams.has("error"); + + if ( + window.location.pathname === "/oauth/callback" || + (hasOAuthCallbackParams && window.location.pathname === "/") + ) { + const OAuthCallback = React.lazy( + () => import("./components/OAuthCallback"), + ); + return ( + Loading...
}> + + + ); + } + ``` + +2. **Removed `/oauth/callback/debug` route** - consolidated into single callback + +3. **OAuth handlers:** + - `onOAuthConnect`: Calls `connectMcpServer()` after successful OAuth + - Quick Auth handled in `AuthDebugger` component (calls `client.authenticate()`) + - Guided Auth handled in `AuthDebugger` component (calls `client.beginGuidedAuth()`) + +4. **InspectorClient Creation Strategy:** + - Uses `ensureInspectorClient()` helper for lazy creation + - Validates API token before creating client + - Shows toast error if API token missing + - Client created on-demand when needed (connect or auth operations) + +**Key Implementation Details:** + +- Single callback endpoint handles both normal and guided modes +- Callback routing handles both `/oauth/callback` and `/` paths (auth server compatibility) +- `BrowserNavigation` automatically redirects for quick auth +- Guided auth uses manual code entry (no auto-redirect) + +--- + +### Step 4.5: Refactor AuthDebugger Component to Use InspectorClient + +**File:** `web/src/components/AuthDebugger.tsx` + +**Current Implementation:** + +- Uses custom `OAuthStateMachine` and `DebugInspectorOAuthClientProvider` +- Manages `AuthGuidedState` manually via `updateAuthState` +- Has "Guided OAuth Flow" and "Quick OAuth Flow" buttons + +**Changes:** + +1. **Update component props:** + + ```typescript + interface AuthDebuggerProps { + inspectorClient: InspectorClient | null; + onBack: () => void; + } + ``` + +2. **Remove custom state machine and provider:** + + ```typescript + // Remove + import { OAuthStateMachine } from "../lib/oauth-state-machine"; + import { DebugInspectorOAuthClientProvider } from "../lib/auth"; + import type { AuthGuidedState } from "../lib/auth-types"; + + // Add + import type { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; + import type { AuthGuidedState } from "@modelcontextprotocol/inspector-shared/auth/types.js"; + ``` + +3. **Follow TUI pattern - manage OAuth state directly:** + + ```typescript + const AuthDebugger = ({ + inspectorClient, + onBack, + }: AuthDebuggerProps) => { + const { toast } = useToast(); + const [oauthState, setOauthState] = useState( + undefined, + ); + const [isInitiatingAuth, setIsInitiatingAuth] = useState(false); + + // Sync oauthState from InspectorClient (TUI pattern - Step 4.1) + useEffect(() => { + if (!inspectorClient) { + setOauthState(undefined); + return; + } + + const update = () => setOauthState(inspectorClient.getOAuthState()); + update(); + + const onStepChange = () => update(); + inspectorClient.addEventListener("oauthStepChange", onStepChange); + inspectorClient.addEventListener("oauthComplete", onStepChange); + inspectorClient.addEventListener("oauthError", onStepChange); + + return () => { + inspectorClient.removeEventListener("oauthStepChange", onStepChange); + inspectorClient.removeEventListener("oauthComplete", onStepChange); + inspectorClient.removeEventListener("oauthError", onStepChange); + }; + }, [inspectorClient]); + ``` + +4. **Update Quick OAuth handler:** + + ```typescript + const handleQuickOAuth = useCallback(async () => { + if (!inspectorClient) return; + + setIsInitiatingAuth(true); + try { + // Quick Auth: normal flow (automatic redirect via BrowserNavigation) + await inspectorClient.authenticate(); + // BrowserNavigation handles redirect automatically + } catch (error) { + console.error("Quick OAuth failed:", error); + toast({ + title: "OAuth Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } finally { + setIsInitiatingAuth(false); + } + }, [inspectorClient, toast]); + ``` + +5. **Update Guided OAuth handler:** + + ```typescript + const handleGuidedOAuth = useCallback(async () => { + if (!inspectorClient) return; + + setIsInitiatingAuth(true); + try { + // Start guided flow + await inspectorClient.beginGuidedAuth(); + // State updates via oauthStepChange events (handled in useEffect above) + } catch (error) { + console.error("Guided OAuth start failed:", error); + toast({ + title: "OAuth Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } finally { + setIsInitiatingAuth(false); + } + }, [inspectorClient, toast]); + ``` + +6. **Update proceed to next step handler:** + + ```typescript + const proceedToNextStep = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client || !oauthState) return; + + setIsInitiatingAuth(true); + try { + await client.proceedOAuthStep(); + // Note: For guided flow, users manually copy the authorization code. + // There's a manual button in OAuthFlowProgress to open the URL if needed. + // Quick auth handles redirects automatically via BrowserNavigation. + } catch (error) { + console.error("OAuth step failed:", error); + toast({ + title: "OAuth Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } finally { + setIsInitiatingAuth(false); + } + }, [ensureInspectorClient, oauthState, toast]); + ``` + + **Key Change:** Removed auto-opening of authorization URL. In guided flow, users manually copy the code. There's a manual button (external link icon) in `OAuthFlowProgress` at the `authorization_redirect` step if users want to open the URL. + +7. **Update clear OAuth handler:** + + ```typescript + const handleClearOAuth = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client) return; + + client.clearOAuthTokens(); + toast({ + title: "OAuth Cleared", + description: "OAuth tokens have been cleared", + variant: "default", + }); + }, [ensureInspectorClient, toast]); + ``` + + **Note:** Uses `InspectorClient.clearOAuthTokens()` method which clears tokens from storage. + +8. **Update component props and ensureInspectorClient pattern:** + + ```typescript + interface AuthDebuggerProps { + inspectorClient: InspectorClient | null; + ensureInspectorClient: () => InspectorClient | null; + canCreateInspectorClient: () => boolean; + onBack: () => void; + } + ``` + + - Uses `ensureInspectorClient()` helper for lazy client creation + - Validates API token before creating client + - Buttons enabled when `canCreateInspectorClient()` returns true (even if `inspectorClient` is null) + +9. **Check for existing tokens on mount:** + + ```typescript + useEffect(() => { + if (inspectorClient && !oauthState?.oauthTokens) { + inspectorClient.getOAuthTokens().then((tokens) => { + if (tokens) { + // State will be updated via getOAuthState() in sync effect + setOauthState(inspectorClient.getOAuthState()); + } + }); + } + }, [inspectorClient, oauthState]); + ``` + +--- + +### Step 4.6: Update OAuthFlowProgress Component + +**File:** `web/src/components/OAuthFlowProgress.tsx` + +**Current Implementation:** + +- Receives `authState`, `updateAuthState`, and `proceedToNextStep` as props +- Uses custom `DebugInspectorOAuthClientProvider` to fetch client info + +**As-Built Changes:** + +1. **Update component props:** + + ```typescript + interface OAuthFlowProgressProps { + oauthState: AuthGuidedState | undefined; + proceedToNextStep: () => Promise; + ensureInspectorClient: () => InspectorClient | null; + } + ``` + + **Note:** Component receives `oauthState` as prop (from `AuthDebugger`'s local state) rather than accessing `inspectorClient` directly. This keeps the component simpler and follows React best practices. + +2. **Remove custom provider usage:** + + ```typescript + // Remove + import { DebugInspectorOAuthClientProvider } from "../lib/auth"; + + // Add + import type { AuthGuidedState } from "@modelcontextprotocol/inspector-shared/auth/types.js"; + import type { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; + ``` + +3. **Manual Authorization Code Entry:** + - Added input field at `authorization_code` step for manual code entry + - Uses `localAuthCode` state synchronized with `oauthState.authorizationCode` + - `onBlur` and `Enter` key: calls `client.setGuidedAuthorizationCode(code, false)` + - "Continue" button checks if code needs to be set before proceeding + +4. **Manual URL Opening Button:** + - External link icon button at `authorization_redirect` step + - Opens authorization URL in new tab when clicked + - No auto-opening - user must manually click button + +5. **Update step rendering to use `oauthState`:** + + ```typescript + // Replace `authState` references with `oauthState` + const currentStepIdx = steps.findIndex((s) => s === oauthState?.oauthStep); + + const getStepProps = (stepName: OAuthStep) => ({ + isComplete: + currentStepIdx > steps.indexOf(stepName) || + currentStepIdx === steps.length - 1, + isCurrent: oauthState?.oauthStep === stepName, + error: oauthState?.oauthStep === stepName ? oauthState.latestError : null, + }); + ``` + +6. **Update `AuthDebugger` to pass props:** + + ```typescript + // In AuthDebugger component: + + ``` + +**Key Implementation Details:** + +- Manual code entry matches TUI UX pattern +- No auto-opening of authorization URL (removed from `proceedToNextStep`) +- Manual button available for users who want to open URL +- Code synchronization between input field and `InspectorClient` state + +--- + +### Step 4.7: Remove Custom OAuth Code + +**Files to Delete:** + +- `web/src/lib/auth.ts` - Custom `InspectorOAuthClientProvider` and `DebugInspectorOAuthClientProvider` +- `web/src/lib/oauth-state-machine.ts` - Custom `OAuthStateMachine` (duplicates shared implementation) +- `web/src/lib/auth-types.ts` - Custom `AuthGuidedState` type (use shared type instead) + +**Files to Update:** + +- `web/src/components/AuthDebugger.tsx` - Remove imports of deleted files +- `web/src/components/OAuthFlowProgress.tsx` - Remove imports of deleted files +- `web/src/App.tsx` - Remove imports of deleted files, remove `authState` state management + +**Note:** `web/src/utils/oauthUtils.ts` (OAuth URL parsing utilities) should be kept as it's still needed. + +--- + +### Step 4.8: Update Environment Factory (Already Complete) + +**File:** `web/src/lib/adapters/environmentFactory.ts` + +**Status:** ✅ Already configured correctly + +The environment factory already uses `BrowserOAuthStorage` and `BrowserNavigation` from shared: + +```typescript +import { + BrowserOAuthStorage, + BrowserNavigation, +} from "@modelcontextprotocol/inspector-shared/auth/browser/index.js"; + +export function createWebEnvironment( + authToken: string | undefined, + redirectUrlProvider: RedirectUrlProvider, +): InspectorClientEnvironment { + // ... + oauth: { + storage: new BrowserOAuthStorage(), + navigation: new BrowserNavigation(), + redirectUrlProvider, + }, +} +``` + +**No changes needed.** + +--- + +### Step 4.9: Update Tests + +**Files to Update:** + +- `web/src/components/__tests__/AuthDebugger.test.tsx` - Mock `InspectorClient` OAuth methods instead of custom providers +- `web/src/components/__tests__/OAuthCallback.test.tsx` (if exists) - Update to use `InspectorClient` +- `web/src/__tests__/App.config.test.tsx` - Verify OAuth config is passed to `InspectorClient` + +**Test Strategy:** + +1. Mock `InspectorClient` methods: `authenticate()`, `completeOAuthFlow()`, `beginGuidedAuth()`, `proceedOAuthStep()`, `getOAuthState()`, `getOAuthTokens()` +2. Test that OAuth callbacks call `inspectorClient.completeOAuthFlow()` with correct code +3. Test that guided flow calls `beginGuidedAuth()` and `proceedOAuthStep()` correctly +4. Test that OAuth state updates via `oauthStepChange` events + +--- + +### Implementation Order (As-Built) + +1. **Step 4.1:** Follow TUI pattern - components manage OAuth state directly (no hook changes needed) ✅ +2. **Step 4.2:** Update `OAuthCallback` component - single redirect URL with state parameter ✅ +3. **Step 4.3:** Remove `OAuthDebugCallback` component - consolidated into single callback ✅ +4. **Step 4.4:** Update `App.tsx` routes - single callback route, `ensureInspectorClient` pattern ✅ +5. **Step 4.5:** Refactor `AuthDebugger` component - OAuth state management, lazy client creation ✅ +6. **Step 4.6:** Update `OAuthFlowProgress` component - manual code entry, manual URL button ✅ +7. **Step 4.7:** Remove custom OAuth code (cleanup) ✅ +8. **Step 4.9:** Update tests - all tests rewritten and passing ✅ + +**Dependencies:** + +- Step 4.1 is a pattern decision (no code changes) - components will manage OAuth state directly +- Steps 4.2-4.4 can be done independently (they don't need OAuth state) +- Step 4.5 implements the OAuth state management pattern from Step 4.1 +- Step 4.6 depends on Step 4.5 (receives `oauthState` as prop) +- Step 4.7 should be done last (after all components updated) +- Step 4.9 should be done alongside component updates + +--- + +### Migration Notes + +**Breaking Changes:** + +- `OAuthCallback` now requires `inspectorClient` and `ensureInspectorClient` props +- `OAuthDebugCallback` removed (consolidated into `OAuthCallback`) +- `AuthDebugger` no longer uses `authState` prop (reads from `InspectorClient`) +- `OAuthFlowProgress` no longer uses `authState` prop +- Single redirect URL (`/oauth/callback`) for both normal and guided modes + +**Backward Compatibility:** + +- OAuth redirect URL changed: single `/oauth/callback` endpoint (removed `/oauth/callback/debug`) +- OAuth storage location remains the same (sessionStorage via `BrowserOAuthStorage`) +- OAuth flow behavior remains the same (normal vs guided), but mode determined by state parameter +- Guided mode callback shows code for manual copying (matches TUI UX) + +**Testing Checklist:** + +- [x] Quick OAuth flow (normal mode) works end-to-end - ✅ Tests written and passing +- [x] Guided OAuth flow works step-by-step - ✅ Tests written and passing +- [x] OAuth callback handles success case - ✅ Updated to use InspectorClient +- [x] OAuth callback handles error cases - ✅ Updated to use InspectorClient +- [x] OAuth callback handles guided mode (new tab scenario) - ✅ Shows code for manual copying +- [x] OAuth callback handles guided mode (same tab scenario) - ✅ Sets code without auto-completing +- [x] Single redirect URL approach works - ✅ State parameter distinguishes modes +- [x] Manual code entry in OAuthFlowProgress - ✅ Tests written and passing +- [x] OAuth tokens persist across page reloads - ✅ Handled by BrowserOAuthStorage +- [x] OAuth state updates correctly via events - ✅ Tests written and passing +- [x] Clear OAuth functionality works - ✅ Tests written and passing +- [x] No auto-opening of authorization URL in guided flow - ✅ Test updated +- [ ] OAuth works with both SSE and streamable-http transports - ⏸️ Needs integration testing + +**Key Implementation Details Discovered:** + +1. **Single Redirect URL with State Parameter:** + - Uses `/oauth/callback` for both normal and guided modes + - Mode encoded in OAuth `state` parameter: `"guided:{random}"` or `"normal:{random}"` + - Matches TUI implementation pattern + - Eliminates need for separate debug endpoint + +2. **Guided Mode Callback Handling:** + - **New Tab Scenario:** Shows authorization code for manual copying, no redirect + - **Same Tab Scenario:** Sets code via `setGuidedAuthorizationCode(code, false)` without auto-completing + - Message: "Please copy this authorization code and return to the Guided Auth flow:" + - Code stored in `sessionStorage` for potential auto-fill (future enhancement) + +3. **InspectorClient Creation Strategy:** + - Lazy creation via `ensureInspectorClient()` helper + - Validates API token before creating client + - Shows toast error if API token missing + - Client created on-demand when needed (connect or auth operations) + - Prevents creating client without API token (would fail API calls) + +4. **Manual Code Entry:** + - Input field added to `OAuthFlowProgress` at `authorization_code` step + - Synchronized with `InspectorClient` state via `setGuidedAuthorizationCode()` + - Matches TUI UX pattern for guided flow + +5. **No Auto-Opening of Authorization URL:** + - Removed auto-opening logic from `proceedToNextStep()` + - Manual button (external link icon) available at `authorization_redirect` step + - Users manually copy code in guided flow (no auto-redirect) + +6. **Remote Logging:** + - Uses `InspectorClient.logger` for persistent logging through redirects + - Logs written to server via `/api/mcp/log` endpoint + - Helps debug OAuth flow across page redirects + +7. **Callback Routing:** + - Handles both `/oauth/callback` and `/` paths (some auth servers redirect incorrectly) + - Checks for OAuth callback parameters in URL search string + - Early return for guided mode without client to avoid unnecessary API calls + +**Functionality Comparison:** + +**Old Implementation Features:** + +- ✅ Explicit error message when serverUrl missing - **Now:** InspectorClient throws error if OAuth not configured (handled via toast) +- ✅ Manual sessionStorage management - **Now:** Handled by BrowserOAuthStorage in InspectorClient +- ✅ Explicit scope discovery (`discoverScopes()`) - **Now:** Handled internally by InspectorClient +- ✅ Manual client registration (static vs DCR) - **Now:** Handled internally by InspectorClient +- ✅ Protected resource metadata discovery - **Now:** Handled internally by InspectorClient +- ✅ State persistence before redirect - **Now:** Handled internally by InspectorClient via BrowserOAuthStorage +- ✅ Step-by-step guided flow with manual state updates - **Now:** Handled by InspectorClient's guided auth flow + +**Potential Gaps/Notes:** + +- ⚠️ **Server URL validation**: Old code showed explicit error "Please enter a server URL in the sidebar before authenticating". New code relies on InspectorClient being properly configured with OAuth config. If InspectorClient is null or OAuth not configured, error is shown via toast (different UX but same functionality). +- ⚠️ **Manual authorization code entry in guided flow**: Old `OAuthFlowProgress` component had an input field for manual authorization code entry during guided flow. New implementation shows the code if received but doesn't have an input field. However: + - Normal flow: Authorization code handled automatically via callback (`completeOAuthFlow()`) + - Debug flow: `OAuthDebugCallback` component still shows code for manual copying + - If manual entry needed: Can call `inspectorClient.completeOAuthFlow(code)` directly, but UI doesn't expose this + - **Status**: Minor UX gap - functionality exists but not exposed in UI. Could add input field to `OAuthFlowProgress` if needed. +- ✅ **All OAuth features preserved**: Static client, DCR, CIMD, scope discovery, resource metadata, token refresh - all handled by InspectorClient internally. + +--- + +## Phase 5: Remove Express Server Dependency ✅ COMPLETE + +**Status:** ✅ Complete - Express proxy server has been completely removed. No Express server code exists in `web/bin/start.js`. The web app uses only Hono server (via Vite middleware in dev, or `bin/server.js` in prod) for all API endpoints and static file serving. + +**Verification:** + +- ✅ No Express imports or references in `web/bin/start.js` +- ✅ No Express imports or references in `web/src/` (except one test mock value) +- ✅ No Express dependencies in `web/package.json` +- ✅ No proxy server spawning code in start scripts +- ✅ `/config` endpoint replaced with HTML template injection + +**Remaining Legacy References:** + +- `web/src/components/__tests__/Sidebar.test.tsx:64` - Test mock has `connectionType: "proxy"` - This is an unused prop in the test mock (not in actual `SidebarProps` interface). Harmless but should be removed for cleanliness. + +### Step 5.1: Update Start Scripts ✅ COMPLETE + +**File:** `web/bin/start.js` + +**Status:** ✅ Complete + +**As-Built:** + +- `startDevClient()` starts only Vite (Hono middleware handles `/api/*` routes) +- `startProdClient()` starts only Hono server (`bin/server.js`) which serves static files + `/api/*` endpoints +- No Express server spawning code exists +- No `startDevServer()` or `startProdServer()` functions exist + +--- + +### Step 5.2: Remove Proxy Configuration ✅ COMPLETE + +**File:** `web/src/utils/configUtils.ts` + +**Status:** ✅ Complete + +**As-Built:** + +- No `getMCPProxyAddress()` function exists +- No proxy auth token handling (uses `MCP_INSPECTOR_API_TOKEN` for remote API auth) +- No proxy server references in code + +--- + +### Step 5.3: Replace `/config` Endpoint with HTML Template Injection ✅ COMPLETE + +**Files:** `web/bin/server.js`, `web/vite.config.ts`, `web/bin/start.js`, `web/src/App.tsx` + +**Status:** ✅ Complete + +**Approach:** Instead of fetching initial configuration from the Express proxy's `/config` endpoint, we inject configuration values directly into the HTML template served by the Hono server (prod) and Vite dev server (dev). This eliminates the dependency on the Express proxy for initial configuration. + +**Implementation:** + +1. **Start Script (`web/bin/start.js`):** + - Passes config values (command, args, transport, serverUrl, envVars) via environment variables (`MCP_INITIAL_COMMAND`, `MCP_INITIAL_ARGS`, `MCP_INITIAL_TRANSPORT`, `MCP_INITIAL_SERVER_URL`, `MCP_ENV_VARS`) to both Vite (dev) and Hono server (prod) + +2. **Hono Server (`web/bin/server.js`):** + - Intercepts requests to `/` (root) + - Reads `index.html` from dist folder + - Builds `initialConfig` object from env vars (includes `defaultEnvironment` from `getDefaultEnvironment()` + `MCP_ENV_VARS`) + - Injects `` before `` + - Returns modified HTML + +3. **Vite Config (`web/vite.config.ts`):** + - Adds middleware to intercept `/` and `/index.html` requests + - Same injection logic as Hono server (reads from `index.html` source, injects config, returns modified HTML) + +4. **App.tsx (`web/src/App.tsx`):** + - Removed `/config` endpoint fetch + - Reads from `window.__INITIAL_CONFIG__` in a `useEffect` (runs once on mount) + - Applies config values to state (env, command, args, transport, serverUrl) + +**Benefits:** + +- No network request needed for initial config (available immediately) +- Removes dependency on Express proxy for config +- Clean URLs (no query params required for config) +- Works in both dev and prod modes +- Values available synchronously before React renders + +**As-Built:** + +- Config injection happens in both dev (Vite middleware) and prod (Hono server route) +- Uses `getDefaultEnvironment()` from SDK to get default env vars (PATH, HOME, USER, etc.) +- Merges with `MCP_ENV_VARS` if provided +- Config object structure matches what `/config` endpoint returned: `{ defaultCommand?, defaultArgs?, defaultTransport?, defaultServerUrl?, defaultEnvironment }` + +--- + +## Phase 6: Testing and Validation ⏸️ IN PROGRESS + +### Step 6.1: Functional Testing + +Test each feature to ensure parity with `client/`: + +- [x] Connection management (connect/disconnect) - ✅ Basic functionality working +- [x] Transport types (stdio, SSE, streamable-http) - ✅ All transport types supported +- [x] Tools (list, call, test) - ✅ Working via InspectorClient +- [x] Resources (list, read, subscribe) - ✅ Working via InspectorClient +- [x] Prompts (list, get) - ✅ Working via InspectorClient +- [x] OAuth flows (static client, DCR, CIMD) - ✅ Integrated via InspectorClient (Phase 4 complete) +- [x] Custom headers - ✅ Supported in config adapter +- [x] Request history - ✅ Using MCP protocol messages +- [x] Stderr logging - ✅ ConsoleTab displays stderr logs +- [x] Notifications - ✅ Extracted from message stream +- [x] Elicitation requests - ✅ Event listeners working +- [x] Sampling requests - ✅ Event listeners working +- [x] Roots management - ✅ getRoots/setRoots working +- [ ] Progress notifications - ⏸️ Needs validation + +**Recent Bug Fixes:** + +- ✅ Fixed infinite loop in `useInspectorClient` hook (messages/stderrLogs/fetchRequests) - root cause: `InspectorClient.getMessages()` returns new array references. Fixed by comparing serialized content before updating state. +- ✅ Fixed infinite loop in `App.tsx` notifications extraction - fixed by using `useMemo` + `useRef` with content comparison +- ✅ Removed debug `console.log` statements from `App.tsx` +- ✅ Added console output capture in tests (schemaUtils, auth tests) to validate expected warnings/debug messages + +--- + +### Step 6.2: Integration Testing + +- [ ] Dev mode: Vite + Hono middleware works +- [ ] Prod mode: Hono server serves static files and API +- [ ] Same-origin requests (no CORS issues) +- [ ] Auth token handling +- [ ] Storage persistence +- [ ] Error handling + +--- + +## Phase 7: Cleanup + +### Step 7.1: Remove Unused Code + +- [x] Delete `useConnection.ts` hook - ✅ Already removed (no files found) +- [x] Remove Express server references - ✅ Express proxy completely removed (no Express code exists) +- [x] Remove proxy-related utilities - ✅ No proxy utilities found in codebase +- [x] Clean up unused imports - ✅ Basic cleanup done (console.log removed) +- [x] Remove unused test prop - ✅ Removed `connectionType` and `setConnectionType` from `Sidebar.test.tsx` mock + +--- + +### Step 7.2: Update Documentation + +- [ ] Update README with new architecture +- [ ] Document Hono integration +- [ ] Update development setup instructions + +--- + +## Implementation Order + +**Recommended order:** + +1. **Phase 1** (Hono Integration) - Foundation for everything else +2. **Phase 2** (Adapters) - Needed before Phase 3 +3. **Phase 3** (InspectorClient Integration) - Core functionality +4. **Phase 4** (OAuth) - Can be done in parallel with Phase 3 +5. **Phase 5** (Remove Express) - After everything works +6. **Phase 6** (Testing) - Throughout, but comprehensive at end (functional and integration testing only) +7. **Phase 7** (Cleanup) - Final step + +--- + +## Key Differences from Current Client + +| Aspect | Current Client | New Web App | +| -------------- | ----------------------------- | ---------------------------------------------- | +| **Transport** | Direct SDK transports + proxy | Remote transport via Hono API | +| **Server** | Separate Express server | Hono middleware in Vite | +| **OAuth** | Custom state machine | InspectorClient OAuth methods | +| **State** | Custom formats | InspectorClient formats (MessageEntry[], etc.) | +| **Connection** | useConnection hook | InspectorClient + useInspectorClient | +| **Fetch** | Direct fetch | createRemoteFetch (for OAuth) | +| **Logging** | Console only | createRemoteLogger | + +--- + +## Success Criteria + +The port is complete when: + +1. ✅ All features from `client/` work identically in `web/` +2. ✅ No separate Express server required +3. ✅ Same-origin requests (no CORS) +4. ✅ OAuth flows work (static, DCR, CIMD) +5. ✅ All transport types work (stdio, SSE, streamable-http) +6. ✅ Request history, stderr logs, notifications all work +7. ✅ Code is cleaner and more maintainable + +--- + +## Notes + +- Keep `client/` unchanged during port (it's the reference implementation) +- Test incrementally - don't try to port everything at once +- Use feature flags if needed to test new code alongside old code +- The web app can be deleted from the PR after POC is complete (if not merging) + +--- + +## Issues + +Future: Extend useInspectorClient to expose OAuth state (for guided flow in web and TUI) + +node cli/build/cli.js --web --config mcp.json --server hosted-everything diff --git a/package-lock.json b/package-lock.json index 6b4dbc29b..3999db496 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,11 @@ "license": "SEE LICENSE IN LICENSE", "workspaces": [ "client", + "web", "server", - "cli" + "cli", + "tui", + "shared" ], "dependencies": { "@modelcontextprotocol/inspector-cli": "^0.20.0", @@ -19,6 +22,7 @@ "@modelcontextprotocol/inspector-server": "^0.20.0", "@modelcontextprotocol/sdk": "^1.25.2", "concurrently": "^9.2.0", + "hono": "^4.11.7", "node-fetch": "^3.3.2", "open": "^10.2.0", "shell-quote": "^1.8.3", @@ -49,11 +53,12 @@ "cli": { "name": "@modelcontextprotocol/inspector-cli", "version": "0.20.0", - "license": "SEE LICENSE IN LICENSE", + "license": "MIT", "dependencies": { + "@modelcontextprotocol/inspector-shared": "*", "@modelcontextprotocol/sdk": "^1.25.2", "commander": "^13.1.0", - "express": "^5.2.1", + "express": "^5.1.0", "spawn-rx": "^5.1.2" }, "bin": { @@ -65,15 +70,6 @@ "vitest": "^4.0.17" } }, - "cli/node_modules/commander": { - "version": "13.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", - "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, "client": { "name": "@modelcontextprotocol/inspector-client", "version": "0.20.0", @@ -174,6 +170,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@alcalzone/ansi-tokenize": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.1.3.tgz", + "integrity": "sha512-3yWxPTq3UQ/FY9p1ErPxIyfT64elWaMvM9lIHnaqpyft63tkxodF5aUElYHrdisWve5cETkh1+KBw1yJuW0aRw==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=14.13.1" + } + }, + "node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", @@ -211,13 +232,13 @@ "peer": true }, "node_modules/@babel/code-frame": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", - "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" }, @@ -226,9 +247,9 @@ } }, "node_modules/@babel/compat-data": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz", - "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz", + "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==", "dev": true, "license": "MIT", "engines": { @@ -236,21 +257,21 @@ } }, "node_modules/@babel/core": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz", - "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", + "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/generator": "^7.28.5", - "@babel/helper-compilation-targets": "^7.27.2", - "@babel/helper-module-transforms": "^7.28.3", - "@babel/helpers": "^7.28.4", - "@babel/parser": "^7.28.5", - "@babel/template": "^7.27.2", - "@babel/traverse": "^7.28.5", - "@babel/types": "^7.28.5", + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-compilation-targets": "^7.28.6", + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helpers": "^7.28.6", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/traverse": "^7.29.0", + "@babel/types": "^7.29.0", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", @@ -267,14 +288,14 @@ } }, "node_modules/@babel/generator": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz", - "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==", + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/parser": "^7.28.5", - "@babel/types": "^7.28.5", + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" @@ -284,13 +305,13 @@ } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.27.2", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", - "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", + "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.27.2", + "@babel/compat-data": "^7.28.6", "@babel/helper-validator-option": "^7.27.1", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", @@ -311,29 +332,29 @@ } }, "node_modules/@babel/helper-module-imports": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz", - "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/traverse": "^7.27.1", - "@babel/types": "^7.27.1" + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.28.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz", - "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-module-imports": "^7.27.1", - "@babel/helper-validator-identifier": "^7.27.1", - "@babel/traverse": "^7.28.3" + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -343,9 +364,9 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz", - "integrity": "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", "dev": true, "license": "MIT", "engines": { @@ -383,27 +404,27 @@ } }, "node_modules/@babel/helpers": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz", - "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.6.tgz", + "integrity": "sha512-xOBvwq86HHdB7WUDTfKfT/Vuxh7gElQ+Sfti2Cy6yIWNW05P8iUslOVcZ4/sKbE+/jQaukQAdz/gf3724kYdqw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/template": "^7.27.2", - "@babel/types": "^7.28.4" + "@babel/template": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/parser": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", - "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.0.tgz", + "integrity": "sha512-IyDgFV5GeDUVX4YdF/3CPULtVGSXXMLh1xVIgdCgxApktqnQV0r7/8Nqthg+8YLGaAtdyIlo2qIdZrbCv4+7ww==", "dev": true, "license": "MIT", "dependencies": { - "@babel/types": "^7.28.5" + "@babel/types": "^7.29.0" }, "bin": { "parser": "bin/babel-parser.js" @@ -468,13 +489,13 @@ } }, "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.27.1.tgz", - "integrity": "sha512-oFT0FrKHgF53f4vOsZGi2Hh3I35PfSmVs4IBFLFj4dnafP+hIWDLg3VyKmUHfLoLHlyxY4C7DGtmHuJgn+IGww==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", + "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -510,13 +531,13 @@ } }, "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.27.1.tgz", - "integrity": "sha512-y8YTNIeKoyhGd9O0Jiyzyyqk8gdjnumGTQPsz0xOZOQ2RmkVJeZ1vmmfIvFEKqucBG6axJGBZDE/7iI5suUI/w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz", + "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -636,13 +657,13 @@ } }, "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.27.1.tgz", - "integrity": "sha512-xfYCBMxveHrRMnAWl1ZlPXOZjzkN82THFvLhQhFXFt81Z5HnN+EtUkZhv/zcKpmT3fzmWZB0ywiBrbC3vogbwQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.28.6.tgz", + "integrity": "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.27.1" + "@babel/helper-plugin-utils": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -684,9 +705,9 @@ } }, "node_modules/@babel/runtime": { - "version": "7.28.4", - "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz", - "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz", + "integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==", "dev": true, "license": "MIT", "engines": { @@ -694,33 +715,33 @@ } }, "node_modules/@babel/template": { - "version": "7.27.2", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", - "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/parser": "^7.27.2", - "@babel/types": "^7.27.1" + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.5.tgz", - "integrity": "sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.27.1", - "@babel/generator": "^7.28.5", + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", "@babel/helper-globals": "^7.28.0", - "@babel/parser": "^7.28.5", - "@babel/template": "^7.27.2", - "@babel/types": "^7.28.5", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", "debug": "^4.3.1" }, "engines": { @@ -728,9 +749,9 @@ } }, "node_modules/@babel/types": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", - "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", "dev": true, "license": "MIT", "dependencies": { @@ -891,9 +912,9 @@ } }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", - "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.3.tgz", + "integrity": "sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==", "cpu": [ "ppc64" ], @@ -908,9 +929,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", - "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.3.tgz", + "integrity": "sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==", "cpu": [ "arm" ], @@ -925,9 +946,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", - "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.3.tgz", + "integrity": "sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==", "cpu": [ "arm64" ], @@ -942,9 +963,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", - "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.3.tgz", + "integrity": "sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==", "cpu": [ "x64" ], @@ -959,9 +980,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", - "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.3.tgz", + "integrity": "sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==", "cpu": [ "arm64" ], @@ -976,9 +997,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", - "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.3.tgz", + "integrity": "sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==", "cpu": [ "x64" ], @@ -993,9 +1014,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", - "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.3.tgz", + "integrity": "sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==", "cpu": [ "arm64" ], @@ -1010,9 +1031,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", - "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.3.tgz", + "integrity": "sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==", "cpu": [ "x64" ], @@ -1027,9 +1048,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", - "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.3.tgz", + "integrity": "sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==", "cpu": [ "arm" ], @@ -1044,9 +1065,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", - "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.3.tgz", + "integrity": "sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==", "cpu": [ "arm64" ], @@ -1061,9 +1082,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", - "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.3.tgz", + "integrity": "sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==", "cpu": [ "ia32" ], @@ -1078,9 +1099,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", - "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.3.tgz", + "integrity": "sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==", "cpu": [ "loong64" ], @@ -1095,9 +1116,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", - "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.3.tgz", + "integrity": "sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==", "cpu": [ "mips64el" ], @@ -1112,9 +1133,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", - "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.3.tgz", + "integrity": "sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==", "cpu": [ "ppc64" ], @@ -1129,9 +1150,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", - "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.3.tgz", + "integrity": "sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==", "cpu": [ "riscv64" ], @@ -1146,9 +1167,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", - "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.3.tgz", + "integrity": "sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==", "cpu": [ "s390x" ], @@ -1163,9 +1184,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", - "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.3.tgz", + "integrity": "sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==", "cpu": [ "x64" ], @@ -1180,9 +1201,9 @@ } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", - "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.3.tgz", + "integrity": "sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==", "cpu": [ "arm64" ], @@ -1197,9 +1218,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", - "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.3.tgz", + "integrity": "sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==", "cpu": [ "x64" ], @@ -1214,9 +1235,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", - "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.3.tgz", + "integrity": "sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==", "cpu": [ "arm64" ], @@ -1231,9 +1252,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", - "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.3.tgz", + "integrity": "sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==", "cpu": [ "x64" ], @@ -1248,9 +1269,9 @@ } }, "node_modules/@esbuild/openharmony-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", - "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.3.tgz", + "integrity": "sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==", "cpu": [ "arm64" ], @@ -1265,9 +1286,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", - "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.3.tgz", + "integrity": "sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==", "cpu": [ "x64" ], @@ -1282,9 +1303,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", - "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.3.tgz", + "integrity": "sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==", "cpu": [ "arm64" ], @@ -1299,9 +1320,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", - "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.3.tgz", + "integrity": "sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==", "cpu": [ "ia32" ], @@ -1316,9 +1337,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", - "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.3.tgz", + "integrity": "sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==", "cpu": [ "x64" ], @@ -1333,9 +1354,9 @@ } }, "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.0", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", - "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1490,31 +1511,31 @@ } }, "node_modules/@floating-ui/core": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz", - "integrity": "sha512-sGnvb5dmrJaKEZ+LDIpguvdX3bDlEllmv4/ClQ9awcmCZrlx5jQyyMWFM5kBI+EyNOCDDiKk8il0zeuX3Zlg/w==", + "version": "1.7.4", + "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.4.tgz", + "integrity": "sha512-C3HlIdsBxszvm5McXlB8PeOEWfBhcGBTZGkGlWc2U0KFY5IwG5OQEuQ8rq52DZmcHDlPLd+YFBK+cZcytwIFWg==", "license": "MIT", "dependencies": { "@floating-ui/utils": "^0.2.10" } }, "node_modules/@floating-ui/dom": { - "version": "1.7.4", - "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.4.tgz", - "integrity": "sha512-OOchDgh4F2CchOX94cRVqhvy7b3AFb+/rQXyswmzmGakRfkMgoWVjfnLWkRirfLEfuD4ysVW16eXzwt3jHIzKA==", + "version": "1.7.5", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.5.tgz", + "integrity": "sha512-N0bD2kIPInNHUHehXhMke1rBGs1dwqvC9O9KYMyyjK7iXt7GAhnro7UlcuYcGdS/yYOlq0MAVgrow8IbWJwyqg==", "license": "MIT", "dependencies": { - "@floating-ui/core": "^1.7.3", + "@floating-ui/core": "^1.7.4", "@floating-ui/utils": "^0.2.10" } }, "node_modules/@floating-ui/react-dom": { - "version": "2.1.6", - "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.6.tgz", - "integrity": "sha512-4JX6rEatQEvlmgU80wZyq9RT96HZJa88q8hp0pBd+LrczeDI4o6uA2M+uvxngVHo4Ihr8uibXxH6+70zhAFrVw==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@floating-ui/react-dom/-/react-dom-2.1.7.tgz", + "integrity": "sha512-0tLRojf/1Go2JgEVm+3Frg9A3IW8bJgKgdO0BN5RkF//ufuz2joZM63Npau2ff3J6lUVYgDSNzNkR+aH3IVfjg==", "license": "MIT", "dependencies": { - "@floating-ui/dom": "^1.7.4" + "@floating-ui/dom": "^1.7.5" }, "peerDependencies": { "react": ">=16.8.0", @@ -1797,6 +1818,22 @@ } } }, + "node_modules/@jest/core/node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@jest/core/node_modules/ansi-styles": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", @@ -1832,6 +1869,19 @@ "dev": true, "license": "MIT" }, + "node_modules/@jest/core/node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/@jest/environment": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", @@ -1948,9 +1998,9 @@ } }, "node_modules/@jest/environment-jsdom-abstract/node_modules/@sinclair/typebox": { - "version": "0.34.41", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.41.tgz", - "integrity": "sha512-6gS8pZzSXdyRHTIqoqSVknxolr1kzfy4/CeDnrzsVz8TTIWUbOBr6gnzOmTYJ3eXQNh4IYHIGi5aIL7sOZ2G/g==", + "version": "0.34.48", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.48.tgz", + "integrity": "sha512-kKJTNuK3AQOrgjjotVxMrCn1sUJwM76wMszfq1kdU4uYVJjvEWuFQ6HgvLt4Xz3fSmZlTOxJ/Ie13KnIcWQXFA==", "dev": true, "license": "MIT", "peer": true @@ -1994,9 +2044,9 @@ } }, "node_modules/@jest/environment-jsdom-abstract/node_modules/ci-info": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", - "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", "dev": true, "funding": [ { @@ -2452,9 +2502,9 @@ } }, "node_modules/@modelcontextprotocol/ext-apps": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-1.0.0.tgz", - "integrity": "sha512-d5vGKBhWkRoa3xlKOynF8kd+sTSY2D3QSjTMCs46/ddOUOSn5e/E0SaShixFm7H7mNlj4uY0RuU0jAsPM/0qwA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/ext-apps/-/ext-apps-1.0.1.tgz", + "integrity": "sha512-rAPzBbB5GNgYk216paQjGKUgbNXSy/yeR95c0ni6Y4uvhWI2AeF+ztEOqQFLBMQy/MPM+02pbVK1HaQmQjMwYQ==", "hasInstallScript": true, "license": "MIT", "workspaces": [ @@ -2506,6 +2556,18 @@ "resolved": "server", "link": true }, + "node_modules/@modelcontextprotocol/inspector-shared": { + "resolved": "shared", + "link": true + }, + "node_modules/@modelcontextprotocol/inspector-tui": { + "resolved": "tui", + "link": true + }, + "node_modules/@modelcontextprotocol/inspector-web": { + "resolved": "web", + "link": true + }, "node_modules/@modelcontextprotocol/sdk": { "version": "1.26.0", "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.26.0.tgz", @@ -2616,9 +2678,9 @@ } }, "node_modules/@oven/bun-darwin-aarch64": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-darwin-aarch64/-/bun-darwin-aarch64-1.3.6.tgz", - "integrity": "sha512-27rypIapNkYboOSylkf1tD9UW9Ado2I+P1NBL46Qz29KmOjTL6WuJ7mHDC5O66CYxlOkF5r93NPDAC3lFHYBXw==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-aarch64/-/bun-darwin-aarch64-1.3.9.tgz", + "integrity": "sha512-df7smckMWSUfaT5mzwN9Lfpd3ZGkOqo+vmQ8VV2a32gl14v6uZ/qeeo+1RlANXn8M0uzXPWWCkrKZIWSZUR0qw==", "cpu": [ "arm64" ], @@ -2629,9 +2691,9 @@ ] }, "node_modules/@oven/bun-darwin-x64": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64/-/bun-darwin-x64-1.3.6.tgz", - "integrity": "sha512-I82xGzPkBxzBKgbl8DsA0RfMQCWTWjNmLjIEkW1ECiv3qK02kHGQ5FGUr/29L/SuvnGsULW4tBTRNZiMzL37nA==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64/-/bun-darwin-x64-1.3.9.tgz", + "integrity": "sha512-YiLxfsPzQqaVvT2a+nxH9do0YfUjrlxF3tKP0b1DDgvfgCcVKGsrQH3Wa82qHgL4dnT8h2bqi94JxXESEuPmcA==", "cpu": [ "x64" ], @@ -2642,9 +2704,9 @@ ] }, "node_modules/@oven/bun-darwin-x64-baseline": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64-baseline/-/bun-darwin-x64-baseline-1.3.6.tgz", - "integrity": "sha512-nqtr+pTsHqusYpG2OZc6s+AmpWDB/FmBvstrK0y5zkti4OqnCuu7Ev2xNjS7uyb47NrAFF40pWqkpaio5XEd7w==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-darwin-x64-baseline/-/bun-darwin-x64-baseline-1.3.9.tgz", + "integrity": "sha512-XbhsA2XAFzvFr0vPSV6SNqGxab4xHKdPmVTLqoSHAx9tffrSq/012BDptOskulwnD+YNsrJUx2D2Ve1xvfgGcg==", "cpu": [ "x64" ], @@ -2655,9 +2717,9 @@ ] }, "node_modules/@oven/bun-linux-aarch64": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64/-/bun-linux-aarch64-1.3.6.tgz", - "integrity": "sha512-YaQEAYjBanoOOtpqk/c5GGcfZIyxIIkQ2m1TbHjedRmJNwxzWBhGinSARFkrRIc3F8pRIGAopXKvJ/2rjN1LzQ==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64/-/bun-linux-aarch64-1.3.9.tgz", + "integrity": "sha512-VaNQTu0Up4gnwZLQ6/Hmho6jAlLxTQ1PwxEth8EsXHf82FOXXPV5OCQ6KC9mmmocjKlmWFaIGebThrOy8DUo4g==", "cpu": [ "arm64" ], @@ -2668,9 +2730,9 @@ ] }, "node_modules/@oven/bun-linux-aarch64-musl": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64-musl/-/bun-linux-aarch64-musl-1.3.6.tgz", - "integrity": "sha512-FR+iJt17rfFgYgpxL3M67AUwujOgjw52ZJzB9vElI5jQXNjTyOKf8eH4meSk4vjlYF3h/AjKYd6pmN0OIUlVKQ==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-aarch64-musl/-/bun-linux-aarch64-musl-1.3.9.tgz", + "integrity": "sha512-t8uimCVBTw5f9K2QTZE5wN6UOrFETNrh/Xr7qtXT9nAOzaOnIFvYA+HcHbGfi31fRlCVfTxqm/EiCwJ1gEw9YQ==", "cpu": [ "arm64" ], @@ -2681,9 +2743,9 @@ ] }, "node_modules/@oven/bun-linux-x64": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64/-/bun-linux-x64-1.3.6.tgz", - "integrity": "sha512-egfngj0dfJ868cf30E7B+ye9KUWSebYxOG4l9YP5eWeMXCtenpenx0zdKtAn9qxJgEJym5AN6trtlk+J6x8Lig==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64/-/bun-linux-x64-1.3.9.tgz", + "integrity": "sha512-oQyAW3+ugulvXTZ+XYeUMmNPR94sJeMokfHQoKwPvVwhVkgRuMhcLGV2ZesHCADVu30Oz2MFXbgdC8x4/o9dRg==", "cpu": [ "x64" ], @@ -2694,9 +2756,9 @@ ] }, "node_modules/@oven/bun-linux-x64-baseline": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-baseline/-/bun-linux-x64-baseline-1.3.6.tgz", - "integrity": "sha512-jRmnX18ak8WzqLrex3siw0PoVKyIeI5AiCv4wJLgSs7VKfOqrPycfHIWfIX2jdn7ngqbHFPzI09VBKANZ4Pckg==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-baseline/-/bun-linux-x64-baseline-1.3.9.tgz", + "integrity": "sha512-nZ12g22cy7pEOBwAxz2tp0wVqekaCn9QRKuGTHqOdLlyAqR4SCdErDvDhUWd51bIyHTQoCmj72TegGTgG0WNPw==", "cpu": [ "x64" ], @@ -2707,9 +2769,9 @@ ] }, "node_modules/@oven/bun-linux-x64-musl": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl/-/bun-linux-x64-musl-1.3.6.tgz", - "integrity": "sha512-YeXcJ9K6vJAt1zSkeA21J6pTe7PgDMLTHKGI3nQBiMYnYf7Ob3K+b/ChSCznrJG7No5PCPiQPg4zTgA+BOTmSA==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl/-/bun-linux-x64-musl-1.3.9.tgz", + "integrity": "sha512-4ZjIUgCxEyKwcKXideB5sX0KJpnHTZtu778w73VNq2uNH2fNpMZv98+DBgJyQ9OfFoRhmKn1bmLmSefvnHzI9w==", "cpu": [ "x64" ], @@ -2720,9 +2782,9 @@ ] }, "node_modules/@oven/bun-linux-x64-musl-baseline": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl-baseline/-/bun-linux-x64-musl-baseline-1.3.6.tgz", - "integrity": "sha512-7FjVnxnRTp/AgWqSQRT/Vt9TYmvnZ+4M+d9QOKh/Lf++wIFXFGSeAgD6bV1X/yr2UPVmZDk+xdhr2XkU7l2v3w==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-linux-x64-musl-baseline/-/bun-linux-x64-musl-baseline-1.3.9.tgz", + "integrity": "sha512-3FXQgtYFsT0YOmAdMcJn56pLM5kzSl6y942rJJIl5l2KummB9Ea3J/vMJMzQk7NCAGhleZGWU/pJSS/uXKGa7w==", "cpu": [ "x64" ], @@ -2733,9 +2795,9 @@ ] }, "node_modules/@oven/bun-windows-x64": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64/-/bun-windows-x64-1.3.6.tgz", - "integrity": "sha512-Sr1KwUcbB0SEpnSPO22tNJppku2khjFluEst+mTGhxHzAGQTQncNeJxDnt3F15n+p9Q+mlcorxehd68n1siikQ==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64/-/bun-windows-x64-1.3.9.tgz", + "integrity": "sha512-/d6vAmgKvkoYlsGPsRPlPmOK1slPis/F40UG02pYwypTH0wmY0smgzdFqR4YmryxFh17XrW1kITv+U99Oajk9Q==", "cpu": [ "x64" ], @@ -2746,9 +2808,9 @@ ] }, "node_modules/@oven/bun-windows-x64-baseline": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64-baseline/-/bun-windows-x64-baseline-1.3.6.tgz", - "integrity": "sha512-PFUa7JL4lGoyyppeS4zqfuoXXih+gSE0XxhDMrCPVEUev0yhGNd/tbWBvcdpYnUth80owENoGjc8s5Knopv9wA==", + "version": "1.3.9", + "resolved": "https://registry.npmjs.org/@oven/bun-windows-x64-baseline/-/bun-windows-x64-baseline-1.3.9.tgz", + "integrity": "sha512-a/+hSrrDpMD7THyXvE2KJy1skxzAD0cnW4K1WjuI/91VqsphjNzvf5t/ZgxEVL4wb6f+hKrSJ5J3aH47zPr61g==", "cpu": [ "x64" ], @@ -2758,14 +2820,20 @@ "win32" ] }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, "node_modules/@playwright/test": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.57.0.tgz", - "integrity": "sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==", + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.58.2.tgz", + "integrity": "sha512-akea+6bHYBBfA9uQqSYmlJXn61cTa+jbO87xVLCWbTqbWadRVmhxlXATaOjOgcBaWU4ePo0wB41KMFv3o35IXA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.57.0" + "playwright": "1.58.2" }, "bin": { "playwright": "cli.js" @@ -2775,9 +2843,9 @@ } }, "node_modules/@preact/signals-core": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.12.2.tgz", - "integrity": "sha512-5Yf8h1Ke3SMHr15xl630KtwPTW4sYDFkkxS0vQ8UiQLWwZQnrF9IKaVG1mN5VcJz52EcWs2acsc/Npjha/7ysA==", + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.13.0.tgz", + "integrity": "sha512-slT6XeTCAbdql61GVLlGU4x7XHI7kCZV5Um5uhE4zLX4ApgiiXc0UYFvVOKq06xcovzp7p+61l68oPi563ARKg==", "license": "MIT", "funding": { "type": "opencollective", @@ -3835,16 +3903,16 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-beta.53", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.53.tgz", - "integrity": "sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==", + "version": "1.0.0-rc.3", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.3.tgz", + "integrity": "sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==", "dev": true, "license": "MIT" }, "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.53.3.tgz", - "integrity": "sha512-mRSi+4cBjrRLoaal2PnqH82Wqyb+d3HsPUN/W+WslCXsZsyHa9ZeQQX/pQsZaVIWDkPcpV6jJ+3KLbTbgnwv8w==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.1.tgz", + "integrity": "sha512-A6ehUVSiSaaliTxai040ZpZ2zTevHYbvu/lDoeAteHI8QnaosIzm4qwtezfRg1jOYaUmnzLX1AOD6Z+UJjtifg==", "cpu": [ "arm" ], @@ -3856,9 +3924,9 @@ ] }, "node_modules/@rollup/rollup-android-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.53.3.tgz", - "integrity": "sha512-CbDGaMpdE9sh7sCmTrTUyllhrg65t6SwhjlMJsLr+J8YjFuPmCEjbBSx4Z/e4SmDyH3aB5hGaJUP2ltV/vcs4w==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.57.1.tgz", + "integrity": "sha512-dQaAddCY9YgkFHZcFNS/606Exo8vcLHwArFZ7vxXq4rigo2bb494/xKMMwRRQW6ug7Js6yXmBZhSBRuBvCCQ3w==", "cpu": [ "arm64" ], @@ -3870,9 +3938,9 @@ ] }, "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.53.3.tgz", - "integrity": "sha512-Nr7SlQeqIBpOV6BHHGZgYBuSdanCXuw09hon14MGOLGmXAFYjx1wNvquVPmpZnl0tLjg25dEdr4IQ6GgyToCUA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.57.1.tgz", + "integrity": "sha512-crNPrwJOrRxagUYeMn/DZwqN88SDmwaJ8Cvi/TN1HnWBU7GwknckyosC2gd0IqYRsHDEnXf328o9/HC6OkPgOg==", "cpu": [ "arm64" ], @@ -3883,9 +3951,9 @@ ] }, "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.53.3.tgz", - "integrity": "sha512-DZ8N4CSNfl965CmPktJ8oBnfYr3F8dTTNBQkRlffnUarJ2ohudQD17sZBa097J8xhQ26AwhHJ5mvUyQW8ddTsQ==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.57.1.tgz", + "integrity": "sha512-Ji8g8ChVbKrhFtig5QBV7iMaJrGtpHelkB3lsaKzadFBe58gmjfGXAOfI5FV0lYMH8wiqsxKQ1C9B0YTRXVy4w==", "cpu": [ "x64" ], @@ -3896,9 +3964,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.53.3.tgz", - "integrity": "sha512-yMTrCrK92aGyi7GuDNtGn2sNW+Gdb4vErx4t3Gv/Tr+1zRb8ax4z8GWVRfr3Jw8zJWvpGHNpss3vVlbF58DZ4w==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.57.1.tgz", + "integrity": "sha512-R+/WwhsjmwodAcz65guCGFRkMb4gKWTcIeLy60JJQbXrJ97BOXHxnkPFrP+YwFlaS0m+uWJTstrUA9o+UchFug==", "cpu": [ "arm64" ], @@ -3910,9 +3978,9 @@ ] }, "node_modules/@rollup/rollup-freebsd-x64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.53.3.tgz", - "integrity": "sha512-lMfF8X7QhdQzseM6XaX0vbno2m3hlyZFhwcndRMw8fbAGUGL3WFMBdK0hbUBIUYcEcMhVLr1SIamDeuLBnXS+Q==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.57.1.tgz", + "integrity": "sha512-IEQTCHeiTOnAUC3IDQdzRAGj3jOAYNr9kBguI7MQAAZK3caezRrg0GxAb6Hchg4lxdZEI5Oq3iov/w/hnFWY9Q==", "cpu": [ "x64" ], @@ -3924,9 +3992,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.53.3.tgz", - "integrity": "sha512-k9oD15soC/Ln6d2Wv/JOFPzZXIAIFLp6B+i14KhxAfnq76ajt0EhYc5YPeX6W1xJkAdItcVT+JhKl1QZh44/qw==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.57.1.tgz", + "integrity": "sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==", "cpu": [ "arm" ], @@ -3938,9 +4006,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm-musleabihf": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.53.3.tgz", - "integrity": "sha512-vTNlKq+N6CK/8UktsrFuc+/7NlEYVxgaEgRXVUVK258Z5ymho29skzW1sutgYjqNnquGwVUObAaxae8rZ6YMhg==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.57.1.tgz", + "integrity": "sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==", "cpu": [ "arm" ], @@ -3952,9 +4020,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.53.3.tgz", - "integrity": "sha512-RGrFLWgMhSxRs/EWJMIFM1O5Mzuz3Xy3/mnxJp/5cVhZ2XoCAxJnmNsEyeMJtpK+wu0FJFWz+QF4mjCA7AUQ3w==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.57.1.tgz", + "integrity": "sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==", "cpu": [ "arm64" ], @@ -3965,9 +4033,9 @@ ] }, "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.53.3.tgz", - "integrity": "sha512-kASyvfBEWYPEwe0Qv4nfu6pNkITLTb32p4yTgzFCocHnJLAHs+9LjUu9ONIhvfT/5lv4YS5muBHyuV84epBo/A==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.57.1.tgz", + "integrity": "sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==", "cpu": [ "arm64" ], @@ -3979,9 +4047,23 @@ ] }, "node_modules/@rollup/rollup-linux-loong64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.53.3.tgz", - "integrity": "sha512-JiuKcp2teLJwQ7vkJ95EwESWkNRFJD7TQgYmCnrPtlu50b4XvT5MOmurWNrCj3IFdyjBQ5p9vnrX4JM6I8OE7g==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.57.1.tgz", + "integrity": "sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.57.1.tgz", + "integrity": "sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==", "cpu": [ "loong64" ], @@ -3993,9 +4075,23 @@ ] }, "node_modules/@rollup/rollup-linux-ppc64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.53.3.tgz", - "integrity": "sha512-EoGSa8nd6d3T7zLuqdojxC20oBfNT8nexBbB/rkxgKj5T5vhpAQKKnD+h3UkoMuTyXkP5jTjK/ccNRmQrPNDuw==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.57.1.tgz", + "integrity": "sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.57.1.tgz", + "integrity": "sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==", "cpu": [ "ppc64" ], @@ -4007,9 +4103,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.53.3.tgz", - "integrity": "sha512-4s+Wped2IHXHPnAEbIB0YWBv7SDohqxobiiPA1FIWZpX+w9o2i4LezzH/NkFUl8LRci/8udci6cLq+jJQlh+0g==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.57.1.tgz", + "integrity": "sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==", "cpu": [ "riscv64" ], @@ -4021,9 +4117,9 @@ ] }, "node_modules/@rollup/rollup-linux-riscv64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.53.3.tgz", - "integrity": "sha512-68k2g7+0vs2u9CxDt5ktXTngsxOQkSEV/xBbwlqYcUrAVh6P9EgMZvFsnHy4SEiUl46Xf0IObWVbMvPrr2gw8A==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.57.1.tgz", + "integrity": "sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==", "cpu": [ "riscv64" ], @@ -4035,9 +4131,9 @@ ] }, "node_modules/@rollup/rollup-linux-s390x-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.53.3.tgz", - "integrity": "sha512-VYsFMpULAz87ZW6BVYw3I6sWesGpsP9OPcyKe8ofdg9LHxSbRMd7zrVrr5xi/3kMZtpWL/wC+UIJWJYVX5uTKg==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.57.1.tgz", + "integrity": "sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==", "cpu": [ "s390x" ], @@ -4049,9 +4145,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.3.tgz", - "integrity": "sha512-3EhFi1FU6YL8HTUJZ51imGJWEX//ajQPfqWLI3BQq4TlvHy4X0MOr5q3D2Zof/ka0d5FNdPwZXm3Yyib/UEd+w==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.57.1.tgz", + "integrity": "sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==", "cpu": [ "x64" ], @@ -4062,9 +4158,9 @@ ] }, "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.3.tgz", - "integrity": "sha512-eoROhjcc6HbZCJr+tvVT8X4fW3/5g/WkGvvmwz/88sDtSJzO7r/blvoBDgISDiCjDRZmHpwud7h+6Q9JxFwq1Q==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.57.1.tgz", + "integrity": "sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==", "cpu": [ "x64" ], @@ -4075,10 +4171,24 @@ "linux" ] }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.57.1.tgz", + "integrity": "sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, "node_modules/@rollup/rollup-openharmony-arm64": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.53.3.tgz", - "integrity": "sha512-OueLAWgrNSPGAdUdIjSWXw+u/02BRTcnfw9PN41D2vq/JSEPnJnVuBgw18VkN8wcd4fjUs+jFHVM4t9+kBSNLw==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.57.1.tgz", + "integrity": "sha512-4wYoDpNg6o/oPximyc/NG+mYUejZrCU2q+2w6YZqrAs2UcNUChIZXjtafAiiZSUc7On8v5NyNj34Kzj/Ltk6dQ==", "cpu": [ "arm64" ], @@ -4090,9 +4200,9 @@ ] }, "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.53.3.tgz", - "integrity": "sha512-GOFuKpsxR/whszbF/bzydebLiXIHSgsEUp6M0JI8dWvi+fFa1TD6YQa4aSZHtpmh2/uAlj/Dy+nmby3TJ3pkTw==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.57.1.tgz", + "integrity": "sha512-O54mtsV/6LW3P8qdTcamQmuC990HDfR71lo44oZMZlXU4tzLrbvTii87Ni9opq60ds0YzuAlEr/GNwuNluZyMQ==", "cpu": [ "arm64" ], @@ -4103,9 +4213,9 @@ ] }, "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.53.3.tgz", - "integrity": "sha512-iah+THLcBJdpfZ1TstDFbKNznlzoxa8fmnFYK4V67HvmuNYkVdAywJSoteUszvBQ9/HqN2+9AZghbajMsFT+oA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.57.1.tgz", + "integrity": "sha512-P3dLS+IerxCT/7D2q2FYcRdWRl22dNbrbBEtxdWhXrfIMPP9lQhb5h4Du04mdl5Woq05jVCDPCMF7Ub0NAjIew==", "cpu": [ "ia32" ], @@ -4117,9 +4227,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-gnu": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.53.3.tgz", - "integrity": "sha512-J9QDiOIZlZLdcot5NXEepDkstocktoVjkaKUtqzgzpt2yWjGlbYiKyp05rWwk4nypbYUNoFAztEgixoLaSETkg==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.57.1.tgz", + "integrity": "sha512-VMBH2eOOaKGtIJYleXsi2B8CPVADrh+TyNxJ4mWPnKfLB/DBUmzW+5m1xUrcwWoMfSLagIRpjUFeW5CO5hyciQ==", "cpu": [ "x64" ], @@ -4131,9 +4241,9 @@ ] }, "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.53.3.tgz", - "integrity": "sha512-UhTd8u31dXadv0MopwGgNOBpUVROFKWVQgAg5N1ESyCz8AuBcMqm4AuTjrwgQKGDfoFuz02EuMRHQIw/frmYKQ==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.57.1.tgz", + "integrity": "sha512-mxRFDdHIWRxg3UfIIAwCm6NzvxG0jDX/wBN6KsQFTvKFqqg9vTrWUE68qEjHt19A5wwx5X5aUi2zuZT7YR0jrA==", "cpu": [ "x64" ], @@ -4144,9 +4254,9 @@ ] }, "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", + "version": "0.27.10", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz", + "integrity": "sha512-MTBk/3jGLNB2tVxv6uLlFh1iu64iYOQ2PbdOSK3NW8JZsmlaOh2q6sdtKowBhfw8QFLmYNzTW4/oK4uATIi6ZA==", "dev": true, "license": "MIT" }, @@ -4226,9 +4336,9 @@ "license": "MIT" }, "node_modules/@testing-library/react": { - "version": "16.3.0", - "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.0.tgz", - "integrity": "sha512-kFSyxiEDwv1WLl2fgsq6pPBbw5aWKrsY2/noi1Id0TK0UParSF62oFQFGHXIyaG4pp2tEub/Zlel+fjjZILDsw==", + "version": "16.3.2", + "resolved": "https://registry.npmjs.org/@testing-library/react/-/react-16.3.2.tgz", + "integrity": "sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==", "dev": true, "license": "MIT", "dependencies": { @@ -4531,18 +4641,18 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "22.19.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.2.tgz", - "integrity": "sha512-LPM2G3Syo1GLzXLGJAKdqoU35XvrWzGJ21/7sgZTUpbkBaOasTj8tjwn6w+hCkqaa1TfJ/w67rJSwYItlJ2mYw==", + "version": "22.19.11", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz", + "integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==", "license": "MIT", "dependencies": { "undici-types": "~6.21.0" } }, "node_modules/@types/prismjs": { - "version": "1.26.5", - "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz", - "integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==", + "version": "1.26.6", + "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.6.tgz", + "integrity": "sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==", "dev": true, "license": "MIT" }, @@ -4567,9 +4677,9 @@ "license": "MIT" }, "node_modules/@types/react": { - "version": "18.3.27", - "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.27.tgz", - "integrity": "sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w==", + "version": "18.3.28", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz", + "integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==", "license": "MIT", "dependencies": { "@types/prop-types": "*", @@ -4666,20 +4776,20 @@ "license": "MIT" }, "node_modules/@typescript-eslint/eslint-plugin": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.49.0.tgz", - "integrity": "sha512-JXij0vzIaTtCwu6SxTh8qBc66kmf1xs7pI4UOiMDFVct6q86G0Zs7KRcEoJgY3Cav3x5Tq0MF5jwgpgLqgKG3A==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.55.0.tgz", + "integrity": "sha512-1y/MVSz0NglV1ijHC8OT49mPJ4qhPYjiK08YUQVbIOyu+5k862LKUHFkpKHWu//zmr7hDR2rhwUm6gnCGNmGBQ==", "dev": true, "license": "MIT", "dependencies": { - "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "8.49.0", - "@typescript-eslint/type-utils": "8.49.0", - "@typescript-eslint/utils": "8.49.0", - "@typescript-eslint/visitor-keys": "8.49.0", - "ignore": "^7.0.0", + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.55.0", + "@typescript-eslint/type-utils": "8.55.0", + "@typescript-eslint/utils": "8.55.0", + "@typescript-eslint/visitor-keys": "8.55.0", + "ignore": "^7.0.5", "natural-compare": "^1.4.0", - "ts-api-utils": "^2.1.0" + "ts-api-utils": "^2.4.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4689,7 +4799,7 @@ "url": "https://opencollective.com/typescript-eslint" }, "peerDependencies": { - "@typescript-eslint/parser": "^8.49.0", + "@typescript-eslint/parser": "^8.55.0", "eslint": "^8.57.0 || ^9.0.0", "typescript": ">=4.8.4 <6.0.0" } @@ -4705,17 +4815,17 @@ } }, "node_modules/@typescript-eslint/parser": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.49.0.tgz", - "integrity": "sha512-N9lBGA9o9aqb1hVMc9hzySbhKibHmB+N3IpoShyV6HyQYRGIhlrO5rQgttypi+yEeKsKI4idxC8Jw6gXKD4THA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.55.0.tgz", + "integrity": "sha512-4z2nCSBfVIMnbuu8uinj+f0o4qOeggYJLbjpPHka3KH1om7e+H9yLKTYgksTaHcGco+NClhhY2vyO3HsMH1RGw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/scope-manager": "8.49.0", - "@typescript-eslint/types": "8.49.0", - "@typescript-eslint/typescript-estree": "8.49.0", - "@typescript-eslint/visitor-keys": "8.49.0", - "debug": "^4.3.4" + "@typescript-eslint/scope-manager": "8.55.0", + "@typescript-eslint/types": "8.55.0", + "@typescript-eslint/typescript-estree": "8.55.0", + "@typescript-eslint/visitor-keys": "8.55.0", + "debug": "^4.4.3" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4730,15 +4840,15 @@ } }, "node_modules/@typescript-eslint/project-service": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.49.0.tgz", - "integrity": "sha512-/wJN0/DKkmRUMXjZUXYZpD1NEQzQAAn9QWfGwo+Ai8gnzqH7tvqS7oNVdTjKqOcPyVIdZdyCMoqN66Ia789e7g==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.55.0.tgz", + "integrity": "sha512-zRcVVPFUYWa3kNnjaZGXSu3xkKV1zXy8M4nO/pElzQhFweb7PPtluDLQtKArEOGmjXoRjnUZ29NjOiF0eCDkcQ==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/tsconfig-utils": "^8.49.0", - "@typescript-eslint/types": "^8.49.0", - "debug": "^4.3.4" + "@typescript-eslint/tsconfig-utils": "^8.55.0", + "@typescript-eslint/types": "^8.55.0", + "debug": "^4.4.3" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4752,14 +4862,14 @@ } }, "node_modules/@typescript-eslint/scope-manager": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.49.0.tgz", - "integrity": "sha512-npgS3zi+/30KSOkXNs0LQXtsg9ekZ8OISAOLGWA/ZOEn0ZH74Ginfl7foziV8DT+D98WfQ5Kopwqb/PZOaIJGg==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.55.0.tgz", + "integrity": "sha512-fVu5Omrd3jeqeQLiB9f1YsuK/iHFOwb04bCtY4BSCLgjNbOD33ZdV6KyEqplHr+IlpgT0QTZ/iJ+wT7hvTx49Q==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.49.0", - "@typescript-eslint/visitor-keys": "8.49.0" + "@typescript-eslint/types": "8.55.0", + "@typescript-eslint/visitor-keys": "8.55.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4770,9 +4880,9 @@ } }, "node_modules/@typescript-eslint/tsconfig-utils": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.49.0.tgz", - "integrity": "sha512-8prixNi1/6nawsRYxet4YOhnbW+W9FK/bQPxsGB1D3ZrDzbJ5FXw5XmzxZv82X3B+ZccuSxo/X8q9nQ+mFecWA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.55.0.tgz", + "integrity": "sha512-1R9cXqY7RQd7WuqSN47PK9EDpgFUK3VqdmbYrvWJZYDd0cavROGn+74ktWBlmJ13NXUQKlZ/iAEQHI/V0kKe0Q==", "dev": true, "license": "MIT", "engines": { @@ -4787,17 +4897,17 @@ } }, "node_modules/@typescript-eslint/type-utils": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.49.0.tgz", - "integrity": "sha512-KTExJfQ+svY8I10P4HdxKzWsvtVnsuCifU5MvXrRwoP2KOlNZ9ADNEWWsQTJgMxLzS5VLQKDjkCT/YzgsnqmZg==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.55.0.tgz", + "integrity": "sha512-x1iH2unH4qAt6I37I2CGlsNs+B9WGxurP2uyZLRz6UJoZWDBx9cJL1xVN/FiOmHEONEg6RIufdvyT0TEYIgC5g==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.49.0", - "@typescript-eslint/typescript-estree": "8.49.0", - "@typescript-eslint/utils": "8.49.0", - "debug": "^4.3.4", - "ts-api-utils": "^2.1.0" + "@typescript-eslint/types": "8.55.0", + "@typescript-eslint/typescript-estree": "8.55.0", + "@typescript-eslint/utils": "8.55.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.4.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4812,9 +4922,9 @@ } }, "node_modules/@typescript-eslint/types": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.49.0.tgz", - "integrity": "sha512-e9k/fneezorUo6WShlQpMxXh8/8wfyc+biu6tnAqA81oWrEic0k21RHzP9uqqpyBBeBKu4T+Bsjy9/b8u7obXQ==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.55.0.tgz", + "integrity": "sha512-ujT0Je8GI5BJWi+/mMoR0wxwVEQaxM+pi30xuMiJETlX80OPovb2p9E8ss87gnSVtYXtJoU9U1Cowcr6w2FE0w==", "dev": true, "license": "MIT", "engines": { @@ -4826,21 +4936,21 @@ } }, "node_modules/@typescript-eslint/typescript-estree": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.49.0.tgz", - "integrity": "sha512-jrLdRuAbPfPIdYNppHJ/D0wN+wwNfJ32YTAm10eJVsFmrVpXQnDWBn8niCSMlWjvml8jsce5E/O+86IQtTbJWA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.55.0.tgz", + "integrity": "sha512-EwrH67bSWdx/3aRQhCoxDaHM+CrZjotc2UCCpEDVqfCE+7OjKAGWNY2HsCSTEVvWH2clYQK8pdeLp42EVs+xQw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/project-service": "8.49.0", - "@typescript-eslint/tsconfig-utils": "8.49.0", - "@typescript-eslint/types": "8.49.0", - "@typescript-eslint/visitor-keys": "8.49.0", - "debug": "^4.3.4", - "minimatch": "^9.0.4", - "semver": "^7.6.0", + "@typescript-eslint/project-service": "8.55.0", + "@typescript-eslint/tsconfig-utils": "8.55.0", + "@typescript-eslint/types": "8.55.0", + "@typescript-eslint/visitor-keys": "8.55.0", + "debug": "^4.4.3", + "minimatch": "^9.0.5", + "semver": "^7.7.3", "tinyglobby": "^0.2.15", - "ts-api-utils": "^2.1.0" + "ts-api-utils": "^2.4.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4880,9 +4990,9 @@ } }, "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", "dev": true, "license": "ISC", "bin": { @@ -4893,16 +5003,16 @@ } }, "node_modules/@typescript-eslint/utils": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.49.0.tgz", - "integrity": "sha512-N3W7rJw7Rw+z1tRsHZbK395TWSYvufBXumYtEGzypgMUthlg0/hmCImeA8hgO2d2G4pd7ftpxxul2J8OdtdaFA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.55.0.tgz", + "integrity": "sha512-BqZEsnPGdYpgyEIkDC1BadNY8oMwckftxBT+C8W0g1iKPdeqKZBtTfnvcq0nf60u7MkjFO8RBvpRGZBPw4L2ow==", "dev": true, "license": "MIT", "dependencies": { - "@eslint-community/eslint-utils": "^4.7.0", - "@typescript-eslint/scope-manager": "8.49.0", - "@typescript-eslint/types": "8.49.0", - "@typescript-eslint/typescript-estree": "8.49.0" + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.55.0", + "@typescript-eslint/types": "8.55.0", + "@typescript-eslint/typescript-estree": "8.55.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -4917,13 +5027,13 @@ } }, "node_modules/@typescript-eslint/visitor-keys": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.49.0.tgz", - "integrity": "sha512-LlKaciDe3GmZFphXIc79THF/YYBugZ7FS1pO581E/edlVVNbZKDy93evqmrfQ9/Y4uN0vVhX4iuchq26mK/iiA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.55.0.tgz", + "integrity": "sha512-AxNRwEie8Nn4eFS1FzDMJWIISMGoXMb037sgCBJ3UR6o0fQTzr2tqN9WT+DkWJPhIdQCfV7T6D387566VtnCJA==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/types": "8.49.0", + "@typescript-eslint/types": "8.55.0", "eslint-visitor-keys": "^4.2.1" }, "engines": { @@ -4935,16 +5045,16 @@ } }, "node_modules/@vitejs/plugin-react": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.1.2.tgz", - "integrity": "sha512-EcA07pHJouywpzsoTUqNh5NwGayl2PPVEJKUSinGGSxFGYn+shYbqMGBg6FXDqgXum9Ou/ecb+411ssw8HImJQ==", + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.1.4.tgz", + "integrity": "sha512-VIcFLdRi/VYRU8OL/puL7QXMYafHmqOnwTZY50U1JPlCNj30PxCMx65c494b1K9be9hX83KVt0+gTEwTWLqToA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/core": "^7.28.5", + "@babel/core": "^7.29.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", - "@rolldown/pluginutils": "1.0.0-beta.53", + "@rolldown/pluginutils": "1.0.0-rc.3", "@types/babel__core": "^7.20.5", "react-refresh": "^0.18.0" }, @@ -4956,16 +5066,16 @@ } }, "node_modules/@vitest/expect": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.17.tgz", - "integrity": "sha512-mEoqP3RqhKlbmUmntNDDCJeTDavDR+fVYkSOw8qRwJFaW/0/5zA9zFeTrHqNtcmwh6j26yMmwx2PqUDPzt5ZAQ==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.18.tgz", + "integrity": "sha512-8sCWUyckXXYvx4opfzVY03EOiYVxyNrHS5QxX3DAIi5dpJAAkyJezHCP77VMX4HKA2LDT/Jpfo8i2r5BE3GnQQ==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.0.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.0.17", - "@vitest/utils": "4.0.17", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", "chai": "^6.2.1", "tinyrainbow": "^3.0.3" }, @@ -4974,13 +5084,13 @@ } }, "node_modules/@vitest/mocker": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.17.tgz", - "integrity": "sha512-+ZtQhLA3lDh1tI2wxe3yMsGzbp7uuJSWBM1iTIKCbppWTSBN09PUC+L+fyNlQApQoR+Ps8twt2pbSSXg2fQVEQ==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.18.tgz", + "integrity": "sha512-HhVd0MDnzzsgevnOWCBj5Otnzobjy5wLBe4EdeeFGv8luMsGcYqDuFRMcttKWZA5vVO8RFjexVovXvAM4JoJDQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.0.17", + "@vitest/spy": "4.0.18", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -5001,9 +5111,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.17.tgz", - "integrity": "sha512-Ah3VAYmjcEdHg6+MwFE17qyLqBHZ+ni2ScKCiW2XrlSBV4H3Z7vYfPfz7CWQ33gyu76oc0Ai36+kgLU3rfF4nw==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.18.tgz", + "integrity": "sha512-P24GK3GulZWC5tz87ux0m8OADrQIUVDPIjjj65vBXYG17ZeU3qD7r+MNZ1RNv4l8CGU2vtTRqixrOi9fYk/yKw==", "dev": true, "license": "MIT", "dependencies": { @@ -5014,13 +5124,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.17.tgz", - "integrity": "sha512-JmuQyf8aMWoo/LmNFppdpkfRVHJcsgzkbCA+/Bk7VfNH7RE6Ut2qxegeyx2j3ojtJtKIbIGy3h+KxGfYfk28YQ==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.18.tgz", + "integrity": "sha512-rpk9y12PGa22Jg6g5M3UVVnTS7+zycIGk9ZNGN+m6tZHKQb7jrP7/77WfZy13Y/EUDd52NDsLRQhYKtv7XfPQw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.0.17", + "@vitest/utils": "4.0.18", "pathe": "^2.0.3" }, "funding": { @@ -5028,13 +5138,13 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.17.tgz", - "integrity": "sha512-npPelD7oyL+YQM2gbIYvlavlMVWUfNNGZPcu0aEUQXt7FXTuqhmgiYupPnAanhKvyP6Srs2pIbWo30K0RbDtRQ==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.18.tgz", + "integrity": "sha512-PCiV0rcl7jKQjbgYqjtakly6T1uwv/5BQ9SwBLekVg/EaYeQFPiXcgrC2Y7vDMA8dM1SUEAEV82kgSQIlXNMvA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.0.17", + "@vitest/pretty-format": "4.0.18", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -5043,9 +5153,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.17.tgz", - "integrity": "sha512-I1bQo8QaP6tZlTomQNWKJE6ym4SHf3oLS7ceNjozxxgzavRAgZDc06T7kD8gb9bXKEgcLNt00Z+kZO6KaJ62Ew==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.18.tgz", + "integrity": "sha512-cbQt3PTSD7P2OARdVW3qWER5EGq7PHlvE+QfzSC0lbwO+xnt7+XH06ZzFjFRgzUX//JmpxrCu92VdwvEPlWSNw==", "dev": true, "license": "MIT", "funding": { @@ -5053,13 +5163,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.17.tgz", - "integrity": "sha512-RG6iy+IzQpa9SB8HAFHJ9Y+pTzI+h8553MrciN9eC6TFBErqrQaTas4vG+MVj8S4uKk8uTT2p0vgZPnTdxd96w==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.18.tgz", + "integrity": "sha512-msMRKLMVLWygpK3u2Hybgi4MNjcYJvwTb0Ru09+fOyCXIgT5raYP041DRRdiJiI3k/2U6SEbAETB3YtBrUkCFA==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.0.17", + "@vitest/pretty-format": "4.0.18", "tinyrainbow": "^3.0.3" }, "funding": { @@ -5201,16 +5311,12 @@ "license": "MIT" }, "node_modules/ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-6.2.1.tgz", + "integrity": "sha512-4nJ3yixlEthEJ9Rk4vPcdBRkZvQZlYyu8j4/Mqz5sgIkddmEnH2Yj2ZrnP9S3tQOvSNRUIgVNF/1yPpRAGNRig==", "license": "MIT", - "dependencies": { - "type-fest": "^0.21.3" - }, "engines": { - "node": ">=8" + "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -5297,6 +5403,15 @@ "dequal": "^2.0.3" } }, + "node_modules/arr-rotate": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/arr-rotate/-/arr-rotate-1.0.0.tgz", + "integrity": "sha512-yOzOZcR9Tn7enTF66bqKorGGH0F36vcPaSWg8fO0c0UYb3LX3VMXj5ZxEqQLNOecAhlRJ7wYZja5i4jTlnbIfQ==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -5314,10 +5429,31 @@ "dev": true, "license": "MIT" }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/auto-bind": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz", + "integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/autoprefixer": { - "version": "10.4.22", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.22.tgz", - "integrity": "sha512-ARe0v/t9gO28Bznv6GgqARmVqcWOV3mfgUPn9becPHMiD3o9BwlRgaeccZnwTpZ7Zwqrm+c1sUSsMxIzQzc8Xg==", + "version": "10.4.24", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.24.tgz", + "integrity": "sha512-uHZg7N9ULTVbutaIsDRoUkoS8/h3bdsmVJYZ5l3wv8Cp/6UIIoRDm90hZ+BwxUj/hGBEzLxdHNSKuFpn8WOyZw==", "dev": true, "funding": [ { @@ -5335,10 +5471,9 @@ ], "license": "MIT", "dependencies": { - "browserslist": "^4.27.0", - "caniuse-lite": "^1.0.30001754", + "browserslist": "^4.28.1", + "caniuse-lite": "^1.0.30001766", "fraction.js": "^5.3.4", - "normalize-range": "^0.1.2", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, @@ -5475,9 +5610,9 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.9.7", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.7.tgz", - "integrity": "sha512-k9xFKplee6KIio3IDbwj+uaCLpqzOwakOgmqzPezM0sFJlFKcg30vk2wOiAJtkTSfx0SSQDSe8q+mWA/fSH5Zg==", + "version": "2.9.19", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.19.tgz", + "integrity": "sha512-ipDqC8FrAl/76p2SSWKSI+H9tFwm7vYqXQrItCuiVPt26Km0jS+NzSsBWAaBusvSbQcfJG+JitdMm+wZAgTYqg==", "dev": true, "license": "Apache-2.0", "bin": { @@ -5498,9 +5633,9 @@ } }, "node_modules/body-parser": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.1.tgz", - "integrity": "sha512-nfDwkulwiZYQIGwxdy0RUmowMhKcFVcYXUU7m4QlKYim1rUtg83xm2yjZ40QjDuc291AJjjeSc9b++AWHSgSHw==", + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", + "integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==", "license": "MIT", "dependencies": { "bytes": "^3.1.2", @@ -5509,7 +5644,7 @@ "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", - "qs": "^6.14.0", + "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" }, @@ -5692,9 +5827,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001760", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001760.tgz", - "integrity": "sha512-7AAMPcueWELt1p3mi13HR/LHH0TJLT11cnwDJEs3xA4+CK/PLKeO9Kl1oru24htkyUKtkGCvAx4ohB0Ttry8Dw==", + "version": "1.0.30001769", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001769.tgz", + "integrity": "sha512-BCfFL1sHijQlBGWBMuJyhZUhzo7wer5sVj9hqekB/7xn0Ypy+pER/edCYQm4exbXj4WiySGp40P8UuTh6w1srg==", "dev": true, "funding": [ { @@ -5790,7 +5925,6 @@ "version": "3.9.0", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, "funding": [ { "type": "github", @@ -5821,39 +5955,77 @@ "url": "https://polar.sh/cva" } }, + "node_modules/cli-boxes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz", + "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/cli-cursor": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", - "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", - "dev": true, + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", "license": "MIT", "dependencies": { - "restore-cursor": "^5.0.0" + "restore-cursor": "^4.0.0" }, "engines": { - "node": ">=18" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/cli-truncate": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.1.1.tgz", - "integrity": "sha512-SroPvNHxUnk+vIW/dOSfNqdy1sPEFkrTk6TUtqLCnBlo3N7TNYYkzzN7uSD6+jVjrdO4+p8nH7JzH6cIvUem6A==", - "dev": true, + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-3.1.0.tgz", + "integrity": "sha512-wfOBkjXteqSnI59oPcJkcPl/ZmwvMMOj340qUIY1SKZCv0B9Cf4D4fAucRkIKQmsIuYK3x1rrgU7MeGRruiuiA==", "license": "MIT", "dependencies": { - "slice-ansi": "^7.1.0", - "string-width": "^8.0.0" + "slice-ansi": "^5.0.0", + "string-width": "^5.0.0" }, "engines": { - "node": ">=20" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/cli-truncate/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cli-truncate/node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, "node_modules/cliui": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", @@ -5868,6 +6040,12 @@ "node": ">=12" } }, + "node_modules/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/cliui/node_modules/is-fullwidth-code-point": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", @@ -5944,6 +6122,18 @@ "node": ">= 0.12.0" } }, + "node_modules/code-excerpt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz", + "integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==", + "license": "MIT", + "dependencies": { + "convert-to-spaces": "^2.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/collect-v8-coverage": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", @@ -5990,13 +6180,12 @@ } }, "node_modules/commander": { - "version": "14.0.2", - "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.2.tgz", - "integrity": "sha512-TywoWNNRbhoD0BXs1P3ZEScW8W5iKrnbithIl0YH+uCmBd0QpPOA8yc82DS3BIE5Ma6FnBVUsJ7wVUDz4dvOWQ==", - "dev": true, + "version": "13.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz", + "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==", "license": "MIT", "engines": { - "node": ">=20" + "node": ">=18" } }, "node_modules/concat-map": { @@ -6073,6 +6262,15 @@ "dev": true, "license": "MIT" }, + "node_modules/convert-to-spaces": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz", + "integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/cookie": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", @@ -6092,9 +6290,9 @@ } }, "node_modules/cors": { - "version": "2.8.5", - "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", - "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "version": "2.8.6", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz", + "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==", "license": "MIT", "dependencies": { "object-assign": "^4", @@ -6102,6 +6300,10 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/create-jest": { @@ -6248,9 +6450,9 @@ "license": "MIT" }, "node_modules/dedent": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.0.tgz", - "integrity": "sha512-HGFtf8yhuhGhqO07SV79tRp+br4MnbdjeVxotpn1QBl30pcLLCQjX5b2295ll0fv8RKDKsmWYrl05usHM9CewQ==", + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.1.tgz", + "integrity": "sha512-9JmrhGZpOlEgOLdQgSm0zxFaYoQon408V1v49aqTWuXENVlnCuY9JBZcXZiCsZQWDjTm5Qf/nIvAy77mXDAjEg==", "dev": true, "license": "MIT", "peerDependencies": { @@ -6280,9 +6482,9 @@ } }, "node_modules/default-browser": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.4.0.tgz", - "integrity": "sha512-XDuvSq38Hr1MdN47EDvYtx3U0MTqpCEn+F6ft8z2vYDzMrvQhVp0ui9oQdqW3MvK3vqUETglt1tVGgjLuJ5izg==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.0.tgz", + "integrity": "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==", "license": "MIT", "dependencies": { "bundle-name": "^4.1.0", @@ -6433,6 +6635,12 @@ "node": ">= 0.4" } }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", + "license": "MIT" + }, "node_modules/ee-first": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", @@ -6440,9 +6648,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.267", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", - "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "version": "1.5.286", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.286.tgz", + "integrity": "sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A==", "dev": true, "license": "ISC" }, @@ -6460,9 +6668,9 @@ } }, "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "license": "MIT" }, "node_modules/encodeurl": { @@ -6491,7 +6699,6 @@ "version": "1.1.0", "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -6563,10 +6770,20 @@ "node": ">= 0.4" } }, + "node_modules/es-toolkit": { + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.44.0.tgz", + "integrity": "sha512-6penXeZalaV88MM3cGkFZZfOoLGWshWWfdy0tWw/RlVVyhvMaWSBTOvXNeiW3e5FwdS5ePW0LGEu17zT139ktg==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks" + ] + }, "node_modules/esbuild": { - "version": "0.25.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", - "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", + "version": "0.27.3", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.3.tgz", + "integrity": "sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -6577,32 +6794,32 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.12", - "@esbuild/android-arm": "0.25.12", - "@esbuild/android-arm64": "0.25.12", - "@esbuild/android-x64": "0.25.12", - "@esbuild/darwin-arm64": "0.25.12", - "@esbuild/darwin-x64": "0.25.12", - "@esbuild/freebsd-arm64": "0.25.12", - "@esbuild/freebsd-x64": "0.25.12", - "@esbuild/linux-arm": "0.25.12", - "@esbuild/linux-arm64": "0.25.12", - "@esbuild/linux-ia32": "0.25.12", - "@esbuild/linux-loong64": "0.25.12", - "@esbuild/linux-mips64el": "0.25.12", - "@esbuild/linux-ppc64": "0.25.12", - "@esbuild/linux-riscv64": "0.25.12", - "@esbuild/linux-s390x": "0.25.12", - "@esbuild/linux-x64": "0.25.12", - "@esbuild/netbsd-arm64": "0.25.12", - "@esbuild/netbsd-x64": "0.25.12", - "@esbuild/openbsd-arm64": "0.25.12", - "@esbuild/openbsd-x64": "0.25.12", - "@esbuild/openharmony-arm64": "0.25.12", - "@esbuild/sunos-x64": "0.25.12", - "@esbuild/win32-arm64": "0.25.12", - "@esbuild/win32-ia32": "0.25.12", - "@esbuild/win32-x64": "0.25.12" + "@esbuild/aix-ppc64": "0.27.3", + "@esbuild/android-arm": "0.27.3", + "@esbuild/android-arm64": "0.27.3", + "@esbuild/android-x64": "0.27.3", + "@esbuild/darwin-arm64": "0.27.3", + "@esbuild/darwin-x64": "0.27.3", + "@esbuild/freebsd-arm64": "0.27.3", + "@esbuild/freebsd-x64": "0.27.3", + "@esbuild/linux-arm": "0.27.3", + "@esbuild/linux-arm64": "0.27.3", + "@esbuild/linux-ia32": "0.27.3", + "@esbuild/linux-loong64": "0.27.3", + "@esbuild/linux-mips64el": "0.27.3", + "@esbuild/linux-ppc64": "0.27.3", + "@esbuild/linux-riscv64": "0.27.3", + "@esbuild/linux-s390x": "0.27.3", + "@esbuild/linux-x64": "0.27.3", + "@esbuild/netbsd-arm64": "0.27.3", + "@esbuild/netbsd-x64": "0.27.3", + "@esbuild/openbsd-arm64": "0.27.3", + "@esbuild/openbsd-x64": "0.27.3", + "@esbuild/openharmony-arm64": "0.27.3", + "@esbuild/sunos-x64": "0.27.3", + "@esbuild/win32-arm64": "0.27.3", + "@esbuild/win32-ia32": "0.27.3", + "@esbuild/win32-x64": "0.27.3" } }, "node_modules/escalade": { @@ -6729,9 +6946,9 @@ } }, "node_modules/eslint-plugin-react-refresh": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.24.tgz", - "integrity": "sha512-nLHIW7TEq3aLrEYWpVaJ1dRgFR+wLDPN8e8FpYAql/bMV2oBEfC37K0gLEGgv9fy66juNShSMV8OkTqzltcG/w==", + "version": "0.4.26", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.26.tgz", + "integrity": "sha512-1RETEylht2O6FM/MvgnyvT+8K21wLqDNg4qD51Zj3guhjt433XbnnkVttHMyaVyAFD03QSV4LPS5iE3VQmO7XQ==", "dev": true, "license": "MIT", "peerDependencies": { @@ -6801,9 +7018,9 @@ } }, "node_modules/esquery": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", - "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -6866,9 +7083,9 @@ } }, "node_modules/eventemitter3": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", - "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==", + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", "dev": true, "license": "MIT" }, @@ -7080,9 +7297,9 @@ "license": "BSD-3-Clause" }, "node_modules/fastq": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", - "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", "dev": true, "license": "ISC", "dependencies": { @@ -7122,6 +7339,34 @@ "node": "^12.20 || >= 14.13" } }, + "node_modules/figures": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/figures/-/figures-5.0.0.tgz", + "integrity": "sha512-ej8ksPF4x6e5wvK9yevct0UCXh8TTFlWGVLlgjZuoBH1HwjIfKE/IdL5mq89sFA7zELi1VhKpmtDnrs7zWyeyg==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^5.0.0", + "is-unicode-supported": "^1.2.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/figures/node_modules/escape-string-regexp": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz", + "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -7312,6 +7557,16 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/fullscreen-ink": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/fullscreen-ink/-/fullscreen-ink-0.1.0.tgz", + "integrity": "sha512-GkyPG5Y8YxRT6i1Q8mZ0BCMSpgQjdBY+C39DnCUMswBpSypTk0G80rAYs6FoEp6Da2gzAwygXbJbju6GahbrFQ==", + "license": "MIT", + "dependencies": { + "ink": ">=4.4.1", + "react": ">=18.2.0" + } + }, "node_modules/function-bind": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", @@ -7344,7 +7599,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.4.0.tgz", "integrity": "sha512-QZjmEOC+IT1uk6Rx0sX22V6uHWVwbdbxf1faPqJ1QhLdGgsRGCZoyaQBm/piRdJy/D2um6hM1UP7ZEeQ4EkP+Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=18" @@ -7423,9 +7677,9 @@ } }, "node_modules/get-tsconfig": { - "version": "4.13.0", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", - "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", + "version": "4.13.6", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.6.tgz", + "integrity": "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw==", "dev": true, "license": "MIT", "dependencies": { @@ -7439,7 +7693,7 @@ "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Glob versions prior to v9 are no longer supported", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", "license": "ISC", "dependencies": { "fs.realpath": "^1.0.0", @@ -7573,9 +7827,9 @@ } }, "node_modules/hono": { - "version": "4.11.7", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.7.tgz", - "integrity": "sha512-l7qMiNee7t82bH3SeyUCt9UF15EVmaBvsppY2zQtrbIhl/yzBTny+YUxsVjSjQ6gaqaeVtZmGocom8TzBlA4Yw==", + "version": "4.11.9", + "resolved": "https://registry.npmjs.org/hono/-/hono-4.11.9.tgz", + "integrity": "sha512-Eaw2YTGM6WOxA6CXbckaEvslr2Ne4NFsKrvc0v97JD5awbmeBLO5w9Ho9L9kmKonrwF9RJlW6BxT1PVv/agBHQ==", "license": "MIT", "engines": { "node": ">=16.9.0" @@ -7683,9 +7937,9 @@ } }, "node_modules/iconv-lite": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", - "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -7756,13 +8010,15 @@ } }, "node_modules/indent-string": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", - "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", - "dev": true, + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", + "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", "license": "MIT", "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/inflight": { @@ -7782,6 +8038,150 @@ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "license": "ISC" }, + "node_modules/ink": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/ink/-/ink-4.4.1.tgz", + "integrity": "sha512-rXckvqPBB0Krifk5rn/5LvQGmyXwCUpBfmTwbkQNBY9JY8RSl3b8OftBNEYxg4+SWUhEKcPifgope28uL9inlA==", + "license": "MIT", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.1.3", + "ansi-escapes": "^6.0.0", + "auto-bind": "^5.0.1", + "chalk": "^5.2.0", + "cli-boxes": "^3.0.0", + "cli-cursor": "^4.0.0", + "cli-truncate": "^3.1.0", + "code-excerpt": "^4.0.0", + "indent-string": "^5.0.0", + "is-ci": "^3.0.1", + "is-lower-case": "^2.0.2", + "is-upper-case": "^2.0.2", + "lodash": "^4.17.21", + "patch-console": "^2.0.0", + "react-reconciler": "^0.29.0", + "scheduler": "^0.23.0", + "signal-exit": "^3.0.7", + "slice-ansi": "^6.0.0", + "stack-utils": "^2.0.6", + "string-width": "^5.1.2", + "type-fest": "^0.12.0", + "widest-line": "^4.0.1", + "wrap-ansi": "^8.1.0", + "ws": "^8.12.0", + "yoga-wasm-web": "~0.3.3" + }, + "engines": { + "node": ">=14.16" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "react": ">=18.0.0", + "react-devtools-core": "^4.19.1" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-devtools-core": { + "optional": true + } + } + }, + "node_modules/ink-form": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/ink-form/-/ink-form-2.0.1.tgz", + "integrity": "sha512-vo0VMwHf+HOOJo7026K4vJEN8xm4sP9iWlQLx4bngNEEY5K8t30CUvVjQCCNAV6Mt2ODt2Aq+2crCuBONReJUg==", + "license": "MIT", + "dependencies": { + "ink-select-input": "^5.0.0", + "ink-text-input": "^6.0.0" + }, + "peerDependencies": { + "ink": ">=4", + "react": ">=18" + } + }, + "node_modules/ink-form/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink-form/node_modules/ink-text-input": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/ink-text-input/-/ink-text-input-6.0.0.tgz", + "integrity": "sha512-Fw64n7Yha5deb1rHY137zHTAbSTNelUKuB5Kkk2HACXEtwIHBCf9OH2tP/LQ9fRYTl1F0dZgbW0zPnZk6FA9Lw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.3.0", + "type-fest": "^4.18.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "ink": ">=5", + "react": ">=18" + } + }, + "node_modules/ink-scroll-view": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/ink-scroll-view/-/ink-scroll-view-0.3.6.tgz", + "integrity": "sha512-XqLkmFFCA5Ow2lVyvv7q0aVHzB78XojIM8gZMQ3//lvy8ZDpJsXWtTRwsCEsdQHnwvMCDCnKCzgF4xkkzoN8mQ==", + "license": "MIT", + "peerDependencies": { + "ink": "^5 || ^6", + "react": "^18 || ^19" + } + }, + "node_modules/ink-select-input": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ink-select-input/-/ink-select-input-5.0.0.tgz", + "integrity": "sha512-VkLEogN3KTgAc0W/u9xK3+44x8JyKfmBvPQyvniJ/Hj0ftg9vWa/YecvZirevNv2SAvgoA2GIlTLCQouzgPKDg==", + "license": "MIT", + "dependencies": { + "arr-rotate": "^1.0.0", + "figures": "^5.0.0", + "lodash.isequal": "^4.5.0" + }, + "engines": { + "node": ">=14.16" + }, + "peerDependencies": { + "ink": "^4.0.0", + "react": "^18.0.0" + } + }, + "node_modules/ink/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink/node_modules/type-fest": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.12.0.tgz", + "integrity": "sha512-53RyidyjvkGpnWPMF9bQgFtWp+Sl8O2Rp13VavmJgfAP9WWG6q6TkrKU8iyJdnwnfgHI6k2hTlgqH4aSdjoTbg==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/interpret": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz", @@ -7829,6 +8229,18 @@ "node": ">=8" } }, + "node_modules/is-ci": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-3.0.1.tgz", + "integrity": "sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==", + "license": "MIT", + "dependencies": { + "ci-info": "^3.2.0" + }, + "bin": { + "is-ci": "bin.js" + } + }, "node_modules/is-core-module": { "version": "2.16.1", "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", @@ -7870,16 +8282,12 @@ } }, "node_modules/is-fullwidth-code-point": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", - "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", - "dev": true, + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", "license": "MIT", - "dependencies": { - "get-east-asian-width": "^1.3.1" - }, "engines": { - "node": ">=18" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -7908,6 +8316,21 @@ "node": ">=0.10.0" } }, + "node_modules/is-in-ci": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-1.0.0.tgz", + "integrity": "sha512-eUuAjybVTHMYWm/U+vBO1sY/JOCgoPCXRxzdju0K+K0BiGW0SChEL1MLC0PoCIR1OlPo5YAp8HuQoUlsWEICwg==", + "license": "MIT", + "bin": { + "is-in-ci": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-inside-container": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", @@ -7926,6 +8349,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-lower-case": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-lower-case/-/is-lower-case-2.0.2.tgz", + "integrity": "sha512-bVcMJy4X5Og6VZfdOZstSexlEy20Sr0k/p/b2IlQJlfdKAQuMpiv5w2Ccxb8sKdRUNAG1PnHVHjFSdRDVS6NlQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.3" + } + }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -7962,6 +8394,27 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-unicode-supported": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-1.3.0.tgz", + "integrity": "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-upper-case": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-upper-case/-/is-upper-case-2.0.2.tgz", + "integrity": "sha512-44pxmxAvnnAOwBg4tHPnkfvgjPwbc5QIsSstNU+YcJ1ovxVzCWpSGosPJOZh/a1tdl81fbgnLc9LLv+x2ywbPQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.3" + } + }, "node_modules/is-wsl": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz", @@ -8011,9 +8464,9 @@ } }, "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", "dev": true, "license": "ISC", "bin": { @@ -8504,9 +8957,9 @@ } }, "node_modules/jest-environment-jsdom/node_modules/@sinclair/typebox": { - "version": "0.34.41", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.41.tgz", - "integrity": "sha512-6gS8pZzSXdyRHTIqoqSVknxolr1kzfy4/CeDnrzsVz8TTIWUbOBr6gnzOmTYJ3eXQNh4IYHIGi5aIL7sOZ2G/g==", + "version": "0.34.48", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.48.tgz", + "integrity": "sha512-kKJTNuK3AQOrgjjotVxMrCn1sUJwM76wMszfq1kdU4uYVJjvEWuFQ6HgvLt4Xz3fSmZlTOxJ/Ie13KnIcWQXFA==", "dev": true, "license": "MIT", "peer": true @@ -8561,9 +9014,9 @@ } }, "node_modules/jest-environment-jsdom/node_modules/ci-info": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.3.1.tgz", - "integrity": "sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", + "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", "dev": true, "funding": [ { @@ -8847,6 +9300,7 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", "dev": true, "license": "MIT", "peer": true, @@ -9330,9 +9784,9 @@ "license": "MIT" }, "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", "dev": true, "license": "ISC", "bin": { @@ -9446,6 +9900,35 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "node_modules/jest-watcher/node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jest-watcher/node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-worker": { "version": "29.7.0", "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", @@ -9710,6 +10193,16 @@ "url": "https://opencollective.com/lint-staged" } }, + "node_modules/lint-staged/node_modules/commander": { + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + } + }, "node_modules/listr2": { "version": "9.0.5", "resolved": "https://registry.npmjs.org/listr2/-/listr2-9.0.5.tgz", @@ -9728,161 +10221,166 @@ "node": ">=20.0.0" } }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "node_modules/listr2/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", "dev": true, "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/log-update": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", - "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "node_modules/listr2/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", "dev": true, "license": "MIT", - "dependencies": { - "ansi-escapes": "^7.0.0", - "cli-cursor": "^5.0.0", - "slice-ansi": "^7.1.0", - "strip-ansi": "^7.1.0", - "wrap-ansi": "^9.0.0" - }, "engines": { - "node": ">=18" + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/log-update/node_modules/ansi-escapes": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.2.0.tgz", - "integrity": "sha512-g6LhBsl+GBPRWGWsBtutpzBYuIIdBkLEvad5C/va/74Db018+5TZiyA26cZJAr3Rft5lprVqOIPxf5Vid6tqAw==", + "node_modules/listr2/node_modules/cli-truncate": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.1.1.tgz", + "integrity": "sha512-SroPvNHxUnk+vIW/dOSfNqdy1sPEFkrTk6TUtqLCnBlo3N7TNYYkzzN7uSD6+jVjrdO4+p8nH7JzH6cIvUem6A==", "dev": true, "license": "MIT", "dependencies": { - "environment": "^1.0.0" + "slice-ansi": "^7.1.0", + "string-width": "^8.0.0" }, "engines": { - "node": ">=18" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/log-update/node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "node_modules/listr2/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" + }, + "node_modules/listr2/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", "dev": true, "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/log-update/node_modules/strip-ansi": { + "node_modules/listr2/node_modules/slice-ansi": { "version": "7.1.2", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", - "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", "dev": true, "license": "MIT", "dependencies": { - "ansi-regex": "^6.0.1" + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" }, "engines": { - "node": ">=12" + "node": ">=18" }, "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" + "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, - "node_modules/loose-envify": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", - "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "node_modules/listr2/node_modules/string-width": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.1.1.tgz", + "integrity": "sha512-KpqHIdDL9KwYk22wEOg/VIqYbrnLeSApsKT/bSj6Ez7pn3CftUiLAv2Lccpq1ALcpLV9UX1Ppn92npZWu2w/aw==", + "dev": true, "license": "MIT", "dependencies": { - "js-tokens": "^3.0.0 || ^4.0.0" + "get-east-asian-width": "^1.3.0", + "strip-ansi": "^7.1.0" }, - "bin": { - "loose-envify": "cli.js" + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "node_modules/listr2/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", "dev": true, - "license": "ISC", + "license": "MIT", "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/lucide-react": { - "version": "0.523.0", - "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.523.0.tgz", - "integrity": "sha512-rUjQoy7egZT9XYVXBK1je9ckBnNp7qzRZOhLQx5RcEp2dCGlXo+mv6vf7Am4LimEcFBJIIZzSGfgTqc9QCrPSw==", - "license": "ISC", - "peerDependencies": { - "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "node_modules/lz-string": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", - "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", "dev": true, "license": "MIT", - "peer": true, - "bin": { - "lz-string": "bin/bin.js" + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/magic-string": { - "version": "0.30.21", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", - "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "node_modules/listr2/node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", "dev": true, "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.5" + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", "dev": true, "license": "MIT", "dependencies": { - "semver": "^7.5.3" + "p-locate": "^5.0.0" }, "engines": { "node": ">=10" @@ -9891,58 +10389,104 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/make-dir/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "node_modules/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==", + "license": "MIT" + }, + "node_modules/lodash.isequal": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz", + "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==", + "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.", + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "license": "MIT" + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/log-update": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", + "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^7.1.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" }, "engines": { - "node": ">=10" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "license": "ISC" - }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "node_modules/log-update/node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", "dev": true, - "license": "BSD-3-Clause", + "license": "MIT", "dependencies": { - "tmpl": "1.0.5" + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "node_modules/log-update/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "dev": true, "license": "MIT", "engines": { - "node": ">= 0.4" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" } }, - "node_modules/media-typer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", - "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "node_modules/log-update/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "dev": true, "license": "MIT", "engines": { - "node": ">= 0.8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/merge-descriptors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", - "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "node_modules/log-update/node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "dev": true, "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, "engines": { "node": ">=18" }, @@ -9950,41 +10494,306 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "node_modules/log-update/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", "dev": true, "license": "MIT" }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "node_modules/log-update/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", "dev": true, "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, "engines": { - "node": ">= 8" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "node_modules/log-update/node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", "dev": true, "license": "MIT", "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" + "mimic-function": "^5.0.0" }, "engines": { - "node": ">=8.6" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/mime-db": { - "version": "1.54.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", - "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "node_modules/log-update/node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "dev": true, + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/lucide-react": { + "version": "0.523.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.523.0.tgz", + "integrity": "sha512-rUjQoy7egZT9XYVXBK1je9ckBnNp7qzRZOhLQx5RcEp2dCGlXo+mv6vf7Am4LimEcFBJIIZzSGfgTqc9QCrPSw==", + "license": "ISC", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "peer": true, + "bin": { + "lz-string": "bin/bin.js" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/make-dir/node_modules/semver": { + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", + "license": "ISC" + }, + "node_modules/makeerror": { + "version": "1.0.12", + "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", + "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tmpl": "1.0.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", + "dev": true, + "license": "MIT" + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", "license": "MIT", "engines": { "node": ">= 0.6" @@ -10010,7 +10819,6 @@ "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -10205,16 +11013,6 @@ "node": ">=0.10.0" } }, - "node_modules/normalize-range": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/normalize-range/-/normalize-range-0.1.2.tgz", - "integrity": "sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/npm-run-path": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", @@ -10277,6 +11075,15 @@ ], "license": "MIT" }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -10302,7 +11109,6 @@ "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, "license": "MIT", "dependencies": { "mimic-fn": "^2.1.0" @@ -10453,6 +11259,15 @@ "node": ">= 0.8" } }, + "node_modules/patch-console": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz", + "integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -10511,9 +11326,9 @@ } }, "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.2.4", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", - "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "version": "11.2.6", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.6.tgz", + "integrity": "sha512-ESL2CrkS/2wTPfuend7Zhkzo2u0daGJ/A2VucJOgQ/C48S/zB8MMeMHSGKYpXhIjbPxfuezITkaBH1wqv00DDQ==", "dev": true, "license": "BlueOak-1.0.0", "engines": { @@ -10580,6 +11395,43 @@ "node": ">=0.10.0" } }, + "node_modules/pino": { + "version": "9.14.0", + "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", + "integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^2.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^3.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", + "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, "node_modules/pirates": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", @@ -10669,13 +11521,13 @@ } }, "node_modules/playwright": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.57.0.tgz", - "integrity": "sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==", + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz", + "integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.57.0" + "playwright-core": "1.58.2" }, "bin": { "playwright": "cli.js" @@ -10688,9 +11540,9 @@ } }, "node_modules/playwright-core": { - "version": "1.57.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.57.0.tgz", - "integrity": "sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==", + "version": "1.58.2", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz", + "integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==", "dev": true, "license": "Apache-2.0", "bin": { @@ -10889,9 +11741,9 @@ } }, "node_modules/prettier": { - "version": "3.7.4", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.7.4.tgz", - "integrity": "sha512-v6UNi1+3hSlVvv8fSaoUbggEM5VErKmmpGA7Pl3HF8V6uKY7rvClBOJlH6yNwQtfTueNkGVpOv/mtWL9L4bgRA==", + "version": "3.8.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.1.tgz", + "integrity": "sha512-UOnG6LftzbdaHZcKoPFtOcCKztrQ57WkHDeRD9t/PTQtmT0NHSeWWepj6pS0z/N7+08BHFDQVUrfmfMRcZwbMg==", "dev": true, "license": "MIT", "bin": { @@ -10943,6 +11795,22 @@ "node": ">=6" } }, + "node_modules/process-warning": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.0.0.tgz", + "integrity": "sha512-a39t9ApHNx2L4+HBnQKqxxHNs1r7KF+Intd8Q/g1bUh6q0WIp9voPXJ/x0j+ZL45KF1pJd9+q2jLIRMfvEshkA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, "node_modules/prompts": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", @@ -11010,9 +11878,9 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.14.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", - "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "version": "6.14.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz", + "integrity": "sha512-V/yCWTTF7VJ9hIh18Ugr2zhJMP01MY7c5kh4J870L7imm6/DIzBsNLTXzMwUA3yZ5b/KBqLx8Kp3uRvd7xSe3Q==", "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" @@ -11052,6 +11920,12 @@ ], "license": "MIT" }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, "node_modules/range-parser": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", @@ -11109,6 +11983,22 @@ "license": "MIT", "peer": true }, + "node_modules/react-reconciler": { + "version": "0.29.2", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.29.2.tgz", + "integrity": "sha512-zZQqIiYgDCTP/f1N/mAR10nJGrPD2ZR+jDSEsKWJHYC7Cm2wodlwbR3upZRdC3cjIjSlTLNVyO7Iu0Yy7t2AYg==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, "node_modules/react-refresh": { "version": "0.18.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", @@ -11221,6 +12111,15 @@ "node": ">=8.10.0" } }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, "node_modules/rechoir": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", @@ -11246,6 +12145,16 @@ "node": ">=8" } }, + "node_modules/redent/node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -11345,51 +12254,21 @@ } }, "node_modules/restore-cursor": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", - "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", - "dev": true, - "license": "MIT", - "dependencies": { - "onetime": "^7.0.0", - "signal-exit": "^4.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/restore-cursor/node_modules/onetime": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", - "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", - "dev": true, + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", "license": "MIT", "dependencies": { - "mimic-function": "^5.0.0" + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" }, "engines": { - "node": ">=18" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/restore-cursor/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/reusify": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", @@ -11429,13 +12308,13 @@ } }, "node_modules/rimraf/node_modules/glob": { - "version": "13.0.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.0.tgz", - "integrity": "sha512-tvZgpqk6fz4BaNZ66ZsRaZnbHvP/jG3uKJvAZOwEVUL4RTA5nJeeLYfyN9/VA8NX/V3IBG+hkeuGpKjvELkVhA==", + "version": "13.0.2", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.2.tgz", + "integrity": "sha512-035InabNu/c1lW0tzPhAgapKctblppqsKKG9ZaNzbr+gXwWMjXoiyGSyB9sArzrjG7jY+zntRq5ZSUYemrnWVQ==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "minimatch": "^10.1.1", + "minimatch": "^10.1.2", "minipass": "^7.1.2", "path-scurry": "^2.0.0" }, @@ -11447,13 +12326,13 @@ } }, "node_modules/rimraf/node_modules/minimatch": { - "version": "10.1.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.1.1.tgz", - "integrity": "sha512-enIvLvRAFZYXJzkCYG5RKmPfrFArdLv+R+lbQ53BmIMLIry74bjKzX6iHAm8WYamJkhSSEabrWN5D97XnKObjQ==", + "version": "10.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.1.2.tgz", + "integrity": "sha512-fu656aJ0n2kcXwsnwnv9g24tkU5uSmOlTjd6WyyaKm2Z+h1qmY6bAjrcaIxF/BslFqbZ8UBtbJi7KgQOZD2PTw==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { - "@isaacs/brace-expansion": "^5.0.0" + "@isaacs/brace-expansion": "^5.0.1" }, "engines": { "node": "20 || >=22" @@ -11463,9 +12342,9 @@ } }, "node_modules/rollup": { - "version": "4.53.3", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.3.tgz", - "integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==", + "version": "4.57.1", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz", + "integrity": "sha512-oQL6lgK3e2QZeQ7gcgIkS2YZPg5slw37hYufJ3edKlfQSGGm8ICoxswK15ntSzF/a8+h7ekRy7k7oWc3BQ7y8A==", "dev": true, "license": "MIT", "dependencies": { @@ -11479,28 +12358,31 @@ "npm": ">=8.0.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.53.3", - "@rollup/rollup-android-arm64": "4.53.3", - "@rollup/rollup-darwin-arm64": "4.53.3", - "@rollup/rollup-darwin-x64": "4.53.3", - "@rollup/rollup-freebsd-arm64": "4.53.3", - "@rollup/rollup-freebsd-x64": "4.53.3", - "@rollup/rollup-linux-arm-gnueabihf": "4.53.3", - "@rollup/rollup-linux-arm-musleabihf": "4.53.3", - "@rollup/rollup-linux-arm64-gnu": "4.53.3", - "@rollup/rollup-linux-arm64-musl": "4.53.3", - "@rollup/rollup-linux-loong64-gnu": "4.53.3", - "@rollup/rollup-linux-ppc64-gnu": "4.53.3", - "@rollup/rollup-linux-riscv64-gnu": "4.53.3", - "@rollup/rollup-linux-riscv64-musl": "4.53.3", - "@rollup/rollup-linux-s390x-gnu": "4.53.3", - "@rollup/rollup-linux-x64-gnu": "4.53.3", - "@rollup/rollup-linux-x64-musl": "4.53.3", - "@rollup/rollup-openharmony-arm64": "4.53.3", - "@rollup/rollup-win32-arm64-msvc": "4.53.3", - "@rollup/rollup-win32-ia32-msvc": "4.53.3", - "@rollup/rollup-win32-x64-gnu": "4.53.3", - "@rollup/rollup-win32-x64-msvc": "4.53.3", + "@rollup/rollup-android-arm-eabi": "4.57.1", + "@rollup/rollup-android-arm64": "4.57.1", + "@rollup/rollup-darwin-arm64": "4.57.1", + "@rollup/rollup-darwin-x64": "4.57.1", + "@rollup/rollup-freebsd-arm64": "4.57.1", + "@rollup/rollup-freebsd-x64": "4.57.1", + "@rollup/rollup-linux-arm-gnueabihf": "4.57.1", + "@rollup/rollup-linux-arm-musleabihf": "4.57.1", + "@rollup/rollup-linux-arm64-gnu": "4.57.1", + "@rollup/rollup-linux-arm64-musl": "4.57.1", + "@rollup/rollup-linux-loong64-gnu": "4.57.1", + "@rollup/rollup-linux-loong64-musl": "4.57.1", + "@rollup/rollup-linux-ppc64-gnu": "4.57.1", + "@rollup/rollup-linux-ppc64-musl": "4.57.1", + "@rollup/rollup-linux-riscv64-gnu": "4.57.1", + "@rollup/rollup-linux-riscv64-musl": "4.57.1", + "@rollup/rollup-linux-s390x-gnu": "4.57.1", + "@rollup/rollup-linux-x64-gnu": "4.57.1", + "@rollup/rollup-linux-x64-musl": "4.57.1", + "@rollup/rollup-openbsd-x64": "4.57.1", + "@rollup/rollup-openharmony-arm64": "4.57.1", + "@rollup/rollup-win32-arm64-msvc": "4.57.1", + "@rollup/rollup-win32-ia32-msvc": "4.57.1", + "@rollup/rollup-win32-x64-gnu": "4.57.1", + "@rollup/rollup-win32-x64-msvc": "4.57.1", "fsevents": "~2.3.2" } }, @@ -11573,6 +12455,15 @@ "tslib": "^2.1.0" } }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", @@ -11612,25 +12503,29 @@ } }, "node_modules/send": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/send/-/send-1.2.0.tgz", - "integrity": "sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", "license": "MIT", "dependencies": { - "debug": "^4.3.5", + "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", - "http-errors": "^2.0.0", - "mime-types": "^3.0.1", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", - "statuses": "^2.0.1" + "statuses": "^2.0.2" }, "engines": { "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/serve-handler": { @@ -11703,9 +12598,9 @@ } }, "node_modules/serve-static": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", - "integrity": "sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", "license": "MIT", "dependencies": { "encodeurl": "^2.0.0", @@ -11715,6 +12610,10 @@ }, "engines": { "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/setprototypeof": { @@ -11872,7 +12771,6 @@ "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, "license": "ISC" }, "node_modules/sisteransi": { @@ -11893,17 +12791,16 @@ } }, "node_modules/slice-ansi": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", - "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", - "dev": true, + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-6.0.0.tgz", + "integrity": "sha512-6bn4hRfkTvDfUoEQYkERg0BVF1D0vrX9HEkMl08uDiNWvVvjylLHvZFZWkDo6wjT8tUctbYl1nCOuE66ZTaUtA==", "license": "MIT", "dependencies": { "ansi-styles": "^6.2.1", - "is-fullwidth-code-point": "^5.0.0" + "is-fullwidth-code-point": "^4.0.0" }, "engines": { - "node": ">=18" + "node": ">=14.16" }, "funding": { "url": "https://github.com/chalk/slice-ansi?sponsor=1" @@ -11913,7 +12810,6 @@ "version": "6.2.3", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -11922,6 +12818,15 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -11963,6 +12868,15 @@ "rxjs": "^7.8.1" } }, + "node_modules/split2": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", + "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", + "license": "ISC", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -11974,7 +12888,6 @@ "version": "2.0.6", "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, "license": "MIT", "dependencies": { "escape-string-regexp": "^2.0.0" @@ -11987,7 +12900,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -12041,17 +12953,17 @@ } }, "node_modules/string-width": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.1.0.tgz", - "integrity": "sha512-Kxl3KJGb/gxkaUMOjRsQ8IrXiGW75O4E3RPjFIINOVH8AMl2SQ/yWdTzWwF3FevIX9LcMAjJW+GRwAlAbTSXdg==", - "dev": true, + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", "license": "MIT", "dependencies": { - "get-east-asian-width": "^1.3.0", - "strip-ansi": "^7.1.0" + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=20" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -12061,7 +12973,6 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -12074,7 +12985,6 @@ "version": "7.1.2", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.0.1" @@ -12209,9 +13119,9 @@ "license": "MIT" }, "node_modules/tailwind-merge": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.0.tgz", - "integrity": "sha512-P+Vu1qXfzediirmHOC3xKGAYeZtPcV9g76X+xg2FD4tYgR71ewMA35Y3sCz3zhiN/dwefRpJX0yBcgwi1fXNQA==", + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz", + "integrity": "sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==", "license": "MIT", "funding": { "type": "github", @@ -12304,6 +13214,15 @@ "node": ">=0.8" } }, + "node_modules/thread-stream": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz", + "integrity": "sha512-OqyPZ9u96VohAyMfJykzmivOrY2wfMSf3C5TtFJVgN+Hm6aj+voFhlK+kZEIv2FBh1X6Xp3DlnCOfEQ3B2J86A==", + "license": "MIT", + "dependencies": { + "real-require": "^0.2.0" + } + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -12469,9 +13388,9 @@ } }, "node_modules/ts-api-utils": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", - "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.4.0.tgz", + "integrity": "sha512-3TaVTaAv2gTiMB35i3FiGJaRfwb3Pyn/j3m/bfAvGe8FB7CF6u+LMYqYlDh7reQf7UNvoTvdfAqHGmPGOSsPmA==", "dev": true, "license": "MIT", "engines": { @@ -12542,9 +13461,9 @@ } }, "node_modules/ts-jest/node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "version": "7.7.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz", + "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==", "dev": true, "license": "ISC", "bin": { @@ -12554,19 +13473,6 @@ "node": ">=10" } }, - "node_modules/ts-jest/node_modules/type-fest": { - "version": "4.41.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", - "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/ts-node": { "version": "10.9.2", "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.2.tgz", @@ -12642,538 +13548,53 @@ "fsevents": "~2.3.3" } }, - "node_modules/tsx/node_modules/@esbuild/aix-ppc64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.1.tgz", - "integrity": "sha512-HHB50pdsBX6k47S4u5g/CaLjqS3qwaOVE5ILsq64jyzgMhLuCuZ8rGzM9yhsAjfjkbgUPMzZEPa7DAp7yz6vuA==", - "cpu": [ - "ppc64" - ], + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "aix" - ], + "dependencies": { + "prelude-ls": "^1.2.1" + }, "engines": { - "node": ">=18" + "node": ">= 0.8.0" } }, - "node_modules/tsx/node_modules/@esbuild/android-arm": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.1.tgz", - "integrity": "sha512-kFqa6/UcaTbGm/NncN9kzVOODjhZW8e+FRdSeypWe6j33gzclHtwlANs26JrupOntlcWmB0u8+8HZo8s7thHvg==", - "cpu": [ - "arm" - ], + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true, "license": "MIT", - "optional": true, - "os": [ - "android" - ], "engines": { - "node": ">=18" + "node": ">=4" } }, - "node_modules/tsx/node_modules/@esbuild/android-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.1.tgz", - "integrity": "sha512-45fuKmAJpxnQWixOGCrS+ro4Uvb4Re9+UTieUY2f8AEc+t7d4AaZ6eUJ3Hva7dtrxAAWHtlEFsXFMAgNnGU9uQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], + "node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "license": "(MIT OR CC0-1.0)", "engines": { - "node": ">=18" + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/tsx/node_modules/@esbuild/android-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.1.tgz", - "integrity": "sha512-LBEpOz0BsgMEeHgenf5aqmn/lLNTFXVfoWMUox8CtWWYK9X4jmQzWjoGoNb8lmAYml/tQ/Ysvm8q7szu7BoxRQ==", - "cpu": [ - "x64" - ], - "dev": true, + "node_modules/type-is": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", + "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", "license": "MIT", - "optional": true, - "os": [ - "android" - ], + "dependencies": { + "content-type": "^1.0.5", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/darwin-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.1.tgz", - "integrity": "sha512-veg7fL8eMSCVKL7IW4pxb54QERtedFDfY/ASrumK/SbFsXnRazxY4YykN/THYqFnFwJ0aVjiUrVG2PwcdAEqQQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/darwin-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.1.tgz", - "integrity": "sha512-+3ELd+nTzhfWb07Vol7EZ+5PTbJ/u74nC6iv4/lwIU99Ip5uuY6QoIf0Hn4m2HoV0qcnRivN3KSqc+FyCHjoVQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.1.tgz", - "integrity": "sha512-/8Rfgns4XD9XOSXlzUDepG8PX+AVWHliYlUkFI3K3GB6tqbdjYqdhcb4BKRd7C0BhZSoaCxhv8kTcBrcZWP+xg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/freebsd-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.1.tgz", - "integrity": "sha512-GITpD8dK9C+r+5yRT/UKVT36h/DQLOHdwGVwwoHidlnA168oD3uxA878XloXebK4Ul3gDBBIvEdL7go9gCUFzQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-arm": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.1.tgz", - "integrity": "sha512-ieMID0JRZY/ZeCrsFQ3Y3NlHNCqIhTprJfDgSB3/lv5jJZ8FX3hqPyXWhe+gvS5ARMBJ242PM+VNz/ctNj//eA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.1.tgz", - "integrity": "sha512-W9//kCrh/6in9rWIBdKaMtuTTzNj6jSeG/haWBADqLLa9P8O5YSRDzgD5y9QBok4AYlzS6ARHifAb75V6G670Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-ia32": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.1.tgz", - "integrity": "sha512-VIUV4z8GD8rtSVMfAj1aXFahsi/+tcoXXNYmXgzISL+KB381vbSTNdeZHHHIYqFyXcoEhu9n5cT+05tRv13rlw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-loong64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.1.tgz", - "integrity": "sha512-l4rfiiJRN7sTNI//ff65zJ9z8U+k6zcCg0LALU5iEWzY+a1mVZ8iWC1k5EsNKThZ7XCQ6YWtsZ8EWYm7r1UEsg==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-mips64el": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.1.tgz", - "integrity": "sha512-U0bEuAOLvO/DWFdygTHWY8C067FXz+UbzKgxYhXC0fDieFa0kDIra1FAhsAARRJbvEyso8aAqvPdNxzWuStBnA==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-ppc64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.1.tgz", - "integrity": "sha512-NzdQ/Xwu6vPSf/GkdmRNsOfIeSGnh7muundsWItmBsVpMoNPVpM61qNzAVY3pZ1glzzAxLR40UyYM23eaDDbYQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-riscv64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.1.tgz", - "integrity": "sha512-7zlw8p3IApcsN7mFw0O1Z1PyEk6PlKMu18roImfl3iQHTnr/yAfYv6s4hXPidbDoI2Q0pW+5xeoM4eTCC0UdrQ==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-s390x": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.1.tgz", - "integrity": "sha512-cGj5wli+G+nkVQdZo3+7FDKC25Uh4ZVwOAK6A06Hsvgr8WqBBuOy/1s+PUEd/6Je+vjfm6stX0kmib5b/O2Ykw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/linux-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.1.tgz", - "integrity": "sha512-z3H/HYI9MM0HTv3hQZ81f+AKb+yEoCRlUby1F80vbQ5XdzEMyY/9iNlAmhqiBKw4MJXwfgsh7ERGEOhrM1niMA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.1.tgz", - "integrity": "sha512-wzC24DxAvk8Em01YmVXyjl96Mr+ecTPyOuADAvjGg+fyBpGmxmcr2E5ttf7Im8D0sXZihpxzO1isus8MdjMCXQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/netbsd-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.1.tgz", - "integrity": "sha512-1YQ8ybGi2yIXswu6eNzJsrYIGFpnlzEWRl6iR5gMgmsrR0FcNoV1m9k9sc3PuP5rUBLshOZylc9nqSgymI+TYg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.1.tgz", - "integrity": "sha512-5Z+DzLCrq5wmU7RDaMDe2DVXMRm2tTDvX2KU14JJVBN2CT/qov7XVix85QoJqHltpvAOZUAc3ndU56HSMWrv8g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openbsd-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.1.tgz", - "integrity": "sha512-Q73ENzIdPF5jap4wqLtsfh8YbYSZ8Q0wnxplOlZUOyZy7B4ZKW8DXGWgTCZmF8VWD7Tciwv5F4NsRf6vYlZtqg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.1.tgz", - "integrity": "sha512-ajbHrGM/XiK+sXM0JzEbJAen+0E+JMQZ2l4RR4VFwvV9JEERx+oxtgkpoKv1SevhjavK2z2ReHk32pjzktWbGg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/sunos-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.1.tgz", - "integrity": "sha512-IPUW+y4VIjuDVn+OMzHc5FV4GubIwPnsz6ubkvN8cuhEqH81NovB53IUlrlBkPMEPxvNnf79MGBoz8rZ2iW8HA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-arm64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.1.tgz", - "integrity": "sha512-RIVRWiljWA6CdVu8zkWcRmGP7iRRIIwvhDKem8UMBjPql2TXM5PkDVvvrzMtj1V+WFPB4K7zkIGM7VzRtFkjdg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-ia32": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.1.tgz", - "integrity": "sha512-2BR5M8CPbptC1AK5JbJT1fWrHLvejwZidKx3UMSF0ecHMa+smhi16drIrCEggkgviBwLYd5nwrFLSl5Kho96RQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/@esbuild/win32-x64": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.1.tgz", - "integrity": "sha512-d5X6RMYv6taIymSk8JBP+nxv8DQAMY6A51GPgusqLdK9wBz5wWIXy1KjTck6HnjE9hqJzJRdk+1p/t5soSbCtw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/tsx/node_modules/esbuild": { - "version": "0.27.1", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.1.tgz", - "integrity": "sha512-yY35KZckJJuVVPXpvjgxiCuVEJT67F6zDeVTv4rizyPrfGBUpZQsvmxnN+C371c2esD/hNMjj4tpBhuueLN7aA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.27.1", - "@esbuild/android-arm": "0.27.1", - "@esbuild/android-arm64": "0.27.1", - "@esbuild/android-x64": "0.27.1", - "@esbuild/darwin-arm64": "0.27.1", - "@esbuild/darwin-x64": "0.27.1", - "@esbuild/freebsd-arm64": "0.27.1", - "@esbuild/freebsd-x64": "0.27.1", - "@esbuild/linux-arm": "0.27.1", - "@esbuild/linux-arm64": "0.27.1", - "@esbuild/linux-ia32": "0.27.1", - "@esbuild/linux-loong64": "0.27.1", - "@esbuild/linux-mips64el": "0.27.1", - "@esbuild/linux-ppc64": "0.27.1", - "@esbuild/linux-riscv64": "0.27.1", - "@esbuild/linux-s390x": "0.27.1", - "@esbuild/linux-x64": "0.27.1", - "@esbuild/netbsd-arm64": "0.27.1", - "@esbuild/netbsd-x64": "0.27.1", - "@esbuild/openbsd-arm64": "0.27.1", - "@esbuild/openbsd-x64": "0.27.1", - "@esbuild/openharmony-arm64": "0.27.1", - "@esbuild/sunos-x64": "0.27.1", - "@esbuild/win32-arm64": "0.27.1", - "@esbuild/win32-ia32": "0.27.1", - "@esbuild/win32-x64": "0.27.1" - } - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/type-is": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz", - "integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==", - "license": "MIT", - "dependencies": { - "content-type": "^1.0.5", - "media-typer": "^1.1.0", - "mime-types": "^3.0.0" - }, - "engines": { - "node": ">= 0.6" + "node": ">= 0.6" } }, "node_modules/typescript": { @@ -13190,16 +13611,16 @@ } }, "node_modules/typescript-eslint": { - "version": "8.49.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.49.0.tgz", - "integrity": "sha512-zRSVH1WXD0uXczCXw+nsdjGPUdx4dfrs5VQoHnUWmv1U3oNlAKv4FUNdLDhVUg+gYn+a5hUESqch//Rv5wVhrg==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.55.0.tgz", + "integrity": "sha512-HE4wj+r5lmDVS9gdaN0/+iqNvPZwGfnJ5lZuz7s5vLlg9ODw0bIiiETaios9LvFI1U94/VBXGm3CB2Y5cNFMpw==", "dev": true, "license": "MIT", "dependencies": { - "@typescript-eslint/eslint-plugin": "8.49.0", - "@typescript-eslint/parser": "8.49.0", - "@typescript-eslint/typescript-estree": "8.49.0", - "@typescript-eslint/utils": "8.49.0" + "@typescript-eslint/eslint-plugin": "8.55.0", + "@typescript-eslint/parser": "8.55.0", + "@typescript-eslint/typescript-estree": "8.55.0", + "@typescript-eslint/utils": "8.55.0" }, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" @@ -13253,9 +13674,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.2.tgz", - "integrity": "sha512-E85pfNzMQ9jpKkA7+TJAi4TJN+tBCuWh5rUcS/sv6cFi+1q9LYDwDI5dpUL0u/73EElyQ8d3TEaeW4sPedBqYA==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ { @@ -13384,13 +13805,13 @@ } }, "node_modules/vite": { - "version": "7.2.7", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.2.7.tgz", - "integrity": "sha512-ITcnkFeR3+fI8P1wMgItjGrR10170d8auB4EpMLPqmx6uxElH3a/hHGQabSHKdqd4FXWO1nFIp9rRn7JQ34ACQ==", + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", + "integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", "dev": true, "license": "MIT", "dependencies": { - "esbuild": "^0.25.0", + "esbuild": "^0.27.0", "fdir": "^6.5.0", "picomatch": "^4.0.3", "postcss": "^8.5.6", @@ -13490,19 +13911,19 @@ } }, "node_modules/vitest": { - "version": "4.0.17", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.17.tgz", - "integrity": "sha512-FQMeF0DJdWY0iOnbv466n/0BudNdKj1l5jYgl5JVTwjSsZSlqyXFt/9+1sEyhR6CLowbZpV7O1sCHrzBhucKKg==", + "version": "4.0.18", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.18.tgz", + "integrity": "sha512-hOQuK7h0FGKgBAas7v0mSAsnvrIgAvWmRFjmzpJ7SwFHH3g1k2u37JtYwOwmEKhK6ZO3v9ggDBBm0La1LCK4uQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.0.17", - "@vitest/mocker": "4.0.17", - "@vitest/pretty-format": "4.0.17", - "@vitest/runner": "4.0.17", - "@vitest/snapshot": "4.0.17", - "@vitest/spy": "4.0.17", - "@vitest/utils": "4.0.17", + "@vitest/expect": "4.0.18", + "@vitest/mocker": "4.0.18", + "@vitest/pretty-format": "4.0.18", + "@vitest/runner": "4.0.18", + "@vitest/snapshot": "4.0.18", + "@vitest/spy": "4.0.18", + "@vitest/utils": "4.0.18", "es-module-lexer": "^1.7.0", "expect-type": "^1.2.2", "magic-string": "^0.30.21", @@ -13530,10 +13951,10 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.0.17", - "@vitest/browser-preview": "4.0.17", - "@vitest/browser-webdriverio": "4.0.17", - "@vitest/ui": "4.0.17", + "@vitest/browser-playwright": "4.0.18", + "@vitest/browser-preview": "4.0.18", + "@vitest/browser-webdriverio": "4.0.18", + "@vitest/ui": "4.0.18", "happy-dom": "*", "jsdom": "*" }, @@ -13626,6 +14047,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz", "integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", "dev": true, "license": "MIT", "dependencies": { @@ -13701,7 +14123,22 @@ "why-is-node-running": "cli.js" }, "engines": { - "node": ">=8" + "node": ">=8" + } + }, + "node_modules/widest-line": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-4.0.1.tgz", + "integrity": "sha512-o0cyEG0e8GPzT4iGHphIOh0cJOV8fivsXxddQasHPHfoZf1ZexrfeA21w2NaEN1RHE+fXlfISmOE8R9N3u3Qig==", + "license": "MIT", + "dependencies": { + "string-width": "^5.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/word-wrap": { @@ -13722,18 +14159,17 @@ "license": "MIT" }, "node_modules/wrap-ansi": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", - "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", - "dev": true, + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", "license": "MIT", "dependencies": { - "ansi-styles": "^6.2.1", - "string-width": "^7.0.0", - "strip-ansi": "^7.1.0" + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=18" + "node": ">=12" }, "funding": { "url": "https://github.com/chalk/wrap-ansi?sponsor=1" @@ -13743,7 +14179,6 @@ "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -13756,7 +14191,6 @@ "version": "6.2.3", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -13765,36 +14199,10 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/wrap-ansi/node_modules/emoji-regex": { - "version": "10.6.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", - "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi/node_modules/string-width": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", - "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^10.3.0", - "get-east-asian-width": "^1.0.0", - "strip-ansi": "^7.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/wrap-ansi/node_modules/strip-ansi": { "version": "7.1.2", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.0.1" @@ -13827,9 +14235,9 @@ } }, "node_modules/ws": { - "version": "8.18.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz", - "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", "license": "MIT", "engines": { "node": ">=10.0.0" @@ -13905,145 +14313,564 @@ "yaml": "bin.mjs" }, "engines": { - "node": ">= 14.6" + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/yargs/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yoga-layout": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", + "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", + "license": "MIT" + }, + "node_modules/yoga-wasm-web": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/yoga-wasm-web/-/yoga-wasm-web-0.3.3.tgz", + "integrity": "sha512-N+d4UJSJbt/R3wqY7Coqs5pcV0aUj2j9IaQ3rNj9bVCLld8tTGKRa2USARjnvZJWVx1NDmQev8EknoczaOQDOA==", + "license": "MIT" + }, + "node_modules/zod": { + "version": "3.25.76", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", + "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.1", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", + "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25 || ^4" + } + }, + "node_modules/zustand": { + "version": "5.0.11", + "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.11.tgz", + "integrity": "sha512-fdZY+dk7zn/vbWNCYmzZULHRrss0jx5pPFiOuMZ/5HJN6Yv3u+1Wswy/4MpZEkEGhtNH+pwxZB8OKgUBPzYAGg==", + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "immer": ">=9.0.6", + "react": ">=18.0.0", + "use-sync-external-store": ">=1.2.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "immer": { + "optional": true + }, + "react": { + "optional": true + }, + "use-sync-external-store": { + "optional": true + } + } + }, + "server": { + "name": "@modelcontextprotocol/inspector-server", + "version": "0.20.0", + "license": "SEE LICENSE IN LICENSE", + "dependencies": { + "@modelcontextprotocol/sdk": "^1.25.2", + "cors": "^2.8.5", + "express": "^5.1.0", + "express-rate-limit": "^8.2.1", + "shell-quote": "^1.8.3", + "shx": "^0.3.4", + "spawn-rx": "^5.1.2", + "ws": "^8.18.0", + "zod": "^3.25.76" + }, + "bin": { + "mcp-inspector-server": "build/index.js" + }, + "devDependencies": { + "@types/cors": "^2.8.19", + "@types/express": "^5.0.0", + "@types/shell-quote": "^1.7.5", + "@types/ws": "^8.5.12", + "tsx": "^4.19.0", + "typescript": "^5.6.2" + } + }, + "shared": { + "name": "@modelcontextprotocol/inspector-shared", + "version": "0.18.0", + "dependencies": { + "hono": "^4.6.0", + "zustand": "^5.0.10" + }, + "devDependencies": { + "@hono/node-server": "^1.19.0", + "@modelcontextprotocol/sdk": "^1.25.2", + "@types/react": "^18.3.23", + "pino": "^9.6.0", + "typescript": "^5.4.2", + "vitest": "^4.0.17" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2", + "pino": "^9.6.0", + "react": "^18.3.1" + } + }, + "tui": { + "name": "@modelcontextprotocol/inspector-tui", + "version": "0.20.0", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/inspector-shared": "*", + "@modelcontextprotocol/sdk": "^1.25.2", + "commander": "^13.1.0", + "fullscreen-ink": "^0.1.0", + "ink": "^5.2.1", + "ink-form": "^2.0.1", + "ink-scroll-view": "^0.3.6", + "open": "^10.2.0", + "pino": "^9.6.0", + "react": "^18.3.1" + }, + "bin": { + "mcp-inspector-tui": "build/tui.js" + }, + "devDependencies": { + "@types/node": "^25.0.3", + "@types/react": "^18.3.23", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } + }, + "tui/node_modules/@types/node": { + "version": "25.2.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.2.3.tgz", + "integrity": "sha512-m0jEgYlYz+mDJZ2+F4v8D1AyQb+QzsNqRuI7xg1VQX/KlKS0qT9r1Mo16yo5F/MtifXFgaofIFsdFMox2SxIbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "tui/node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "tui/node_modules/ansi-regex": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "tui/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "tui/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" }, "funding": { - "url": "https://github.com/sponsors/eemeli" + "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "tui/node_modules/cli-truncate": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", + "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", "license": "MIT", "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" + "slice-ansi": "^5.0.0", + "string-width": "^7.0.0" }, "engines": { - "node": ">=12" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "license": "ISC", + "tui/node_modules/cli-truncate/node_modules/slice-ansi": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", + "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.0.0", + "is-fullwidth-code-point": "^4.0.0" + }, "engines": { "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, - "node_modules/yargs/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "tui/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "tui/node_modules/ink": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/ink/-/ink-5.2.1.tgz", + "integrity": "sha512-BqcUyWrG9zq5HIwW6JcfFHsIYebJkWWb4fczNah1goUO0vv5vneIlfwuS85twyJ5hYR/y18FlAYUxrO9ChIWVg==", "license": "MIT", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.1.3", + "ansi-escapes": "^7.0.0", + "ansi-styles": "^6.2.1", + "auto-bind": "^5.0.1", + "chalk": "^5.3.0", + "cli-boxes": "^3.0.0", + "cli-cursor": "^4.0.0", + "cli-truncate": "^4.0.0", + "code-excerpt": "^4.0.0", + "es-toolkit": "^1.22.0", + "indent-string": "^5.0.0", + "is-in-ci": "^1.0.0", + "patch-console": "^2.0.0", + "react-reconciler": "^0.29.0", + "scheduler": "^0.23.0", + "signal-exit": "^3.0.7", + "slice-ansi": "^7.1.0", + "stack-utils": "^2.0.6", + "string-width": "^7.2.0", + "type-fest": "^4.27.0", + "widest-line": "^5.0.0", + "wrap-ansi": "^9.0.0", + "ws": "^8.18.0", + "yoga-layout": "~3.2.1" + }, "engines": { - "node": ">=8" + "node": ">=18" + }, + "peerDependencies": { + "@types/react": ">=18.0.0", + "react": ">=18.0.0", + "react-devtools-core": "^4.19.1" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-devtools-core": { + "optional": true + } } }, - "node_modules/yargs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "tui/node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", "license": "MIT", "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" }, "engines": { - "node": ">=8" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, - "node_modules/yn": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", - "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "tui/node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, "engines": { - "node": ">=6" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, + "tui/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, "engines": { - "node": ">=10" + "node": ">=18" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/zod": { - "version": "3.25.76", - "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", - "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", + "tui/node_modules/strip-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", + "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, "funding": { - "url": "https://github.com/sponsors/colinhacks" + "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, - "node_modules/zod-to-json-schema": { - "version": "3.25.1", - "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.1.tgz", - "integrity": "sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==", - "license": "ISC", - "peerDependencies": { - "zod": "^3.25 || ^4" + "tui/node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, + "tui/node_modules/widest-line": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-5.0.0.tgz", + "integrity": "sha512-c9bZp7b5YtRj2wOe6dlj32MK+Bx/M/d+9VB2SHM1OtsUHR0aV0tdP6DWh/iMt0kWi1t5g1Iudu6hQRNd1A4PVA==", + "license": "MIT", + "dependencies": { + "string-width": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "server": { - "name": "@modelcontextprotocol/inspector-server", + "tui/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "web": { + "name": "@modelcontextprotocol/inspector-web", "version": "0.20.0", - "license": "SEE LICENSE IN LICENSE", + "license": "MIT", "dependencies": { + "@hono/node-server": "^1.19.0", + "@modelcontextprotocol/inspector-shared": "*", "@modelcontextprotocol/sdk": "^1.25.2", - "cors": "^2.8.5", - "express": "^5.1.0", - "express-rate-limit": "^8.2.1", - "shell-quote": "^1.8.3", - "shx": "^0.3.4", - "spawn-rx": "^5.1.2", - "ws": "^8.18.0", + "@radix-ui/react-checkbox": "^1.1.4", + "@radix-ui/react-dialog": "^1.1.3", + "@radix-ui/react-icons": "^1.3.0", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-popover": "^1.1.3", + "@radix-ui/react-select": "^2.1.2", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-switch": "^1.2.6", + "@radix-ui/react-tabs": "^1.1.1", + "@radix-ui/react-toast": "^1.2.6", + "@radix-ui/react-tooltip": "^1.1.8", + "ajv": "^6.12.6", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "cmdk": "^1.0.4", + "lucide-react": "^0.523.0", + "pino": "^9.6.0", + "pkce-challenge": "^4.1.0", + "prismjs": "^1.30.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-simple-code-editor": "^0.14.1", + "serve-handler": "^6.1.6", + "tailwind-merge": "^2.5.3", "zod": "^3.25.76" }, "bin": { - "mcp-inspector-server": "build/index.js" + "mcp-inspector-web": "bin/start.js" }, "devDependencies": { - "@types/cors": "^2.8.19", - "@types/express": "^5.0.0", - "@types/shell-quote": "^1.7.5", - "@types/ws": "^8.5.12", - "tsx": "^4.19.0", - "typescript": "^5.6.2" + "@eslint/js": "^9.11.1", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.2.0", + "@types/jest": "^29.5.14", + "@types/node": "^22.17.0", + "@types/prismjs": "^1.26.5", + "@types/react": "^18.3.23", + "@types/react-dom": "^18.3.0", + "@types/serve-handler": "^6.1.4", + "@vitejs/plugin-react": "^5.0.4", + "autoprefixer": "^10.4.20", + "co": "^4.6.0", + "eslint": "^9.11.1", + "eslint-plugin-react-hooks": "^5.1.0-rc.0", + "eslint-plugin-react-refresh": "^0.4.12", + "globals": "^15.9.0", + "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "jest-fixed-jsdom": "^0.0.9", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.13", + "tailwindcss-animate": "^1.0.7", + "ts-jest": "^29.4.0", + "typescript": "^5.5.3", + "typescript-eslint": "^8.38.0", + "vite": "^7.1.11" } }, - "server/node_modules/express-rate-limit": { - "version": "8.2.1", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.2.1.tgz", - "integrity": "sha512-PCZEIEIxqwhzw4KF0n7QF4QqruVTcF73O5kFKUnGOyjbCCgizBBiFaYpd/fnBLUMPw/BWw9OsiN7GgrNYr7j6g==", + "web/node_modules/jest-environment-jsdom": { + "version": "29.7.0", + "resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-29.7.0.tgz", + "integrity": "sha512-k9iQbsf9OyOfdzWH8HDmrRT0gSIcX+FLNW7IQq94tFX0gynPwqDTW0Ho6iMVNjGz/nb+l/vW3dWM2bbLLpkbXA==", + "dev": true, "license": "MIT", "dependencies": { - "ip-address": "10.0.1" + "@jest/environment": "^29.7.0", + "@jest/fake-timers": "^29.7.0", + "@jest/types": "^29.6.3", + "@types/jsdom": "^20.0.0", + "@types/node": "*", + "jest-mock": "^29.7.0", + "jest-util": "^29.7.0", + "jsdom": "^20.0.0" }, "engines": { - "node": ">= 16" - }, - "funding": { - "url": "https://github.com/sponsors/express-rate-limit" + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" }, "peerDependencies": { - "express": ">= 4.11" + "canvas": "^2.5.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } } } } diff --git a/package.json b/package.json index 948f361e6..1cbea87b3 100644 --- a/package.json +++ b/package.json @@ -13,19 +13,28 @@ "files": [ "client/bin", "client/dist", + "web/bin", + "web/dist", "server/build", - "cli/build" + "cli/build", + "tui/build" ], "workspaces": [ "client", + "web", "server", - "cli" + "cli", + "tui", + "shared" ], "scripts": { - "build": "npm run build-server && npm run build-client && npm run build-cli", + "build": "npm run build-shared && npm run build-server && npm run build-client && npm run build-web && npm run build-cli && npm run build-tui", + "build-shared": "cd shared && npm run build", "build-server": "cd server && npm run build", "build-client": "cd client && npm run build", + "build-web": "cd web && npm run build", "build-cli": "cd cli && npm run build", + "build-tui": "cd tui && npm run build", "clean": "rimraf ./node_modules ./client/node_modules ./cli/node_modules ./build ./client/dist ./server/build ./cli/build ./package-lock.json && npm install", "dev": "node client/bin/start.js --dev", "dev:windows": "node client/bin/start.js --dev", @@ -35,8 +44,11 @@ "start": "node client/bin/start.js", "start-server": "cd server && npm run start", "start-client": "cd client && npm run preview", + "web": "sh scripts/run-web.sh", + "web:dev": "sh scripts/run-web.sh --dev", "test": "npm run prettier-check && cd client && npm test", "test-cli": "cd cli && npm run test", + "test-shared": "cd shared && npm run test", "test:e2e": "MCP_AUTO_OPEN_ENABLED=false npm run test:e2e --workspace=client", "prettier-fix": "prettier --write .", "prettier-check": "prettier --check .", @@ -52,6 +64,7 @@ "@modelcontextprotocol/inspector-server": "^0.20.0", "@modelcontextprotocol/sdk": "^1.25.2", "concurrently": "^9.2.0", + "hono": "^4.11.7", "node-fetch": "^3.3.2", "open": "^10.2.0", "shell-quote": "^1.8.3", diff --git a/scripts/check-version-consistency.js b/scripts/check-version-consistency.js index 379931dea..cfe44d52e 100755 --- a/scripts/check-version-consistency.js +++ b/scripts/check-version-consistency.js @@ -21,6 +21,7 @@ const packagePaths = [ "client/package.json", "server/package.json", "cli/package.json", + "tui/package.json", ]; const versions = new Map(); @@ -135,6 +136,8 @@ if (!fs.existsSync(lockPath)) { { path: "client", name: "@modelcontextprotocol/inspector-client" }, { path: "server", name: "@modelcontextprotocol/inspector-server" }, { path: "cli", name: "@modelcontextprotocol/inspector-cli" }, + { path: "tui", name: "@modelcontextprotocol/inspector-tui" }, + { path: "web", name: "@modelcontextprotocol/inspector-web" }, ]; workspacePackages.forEach(({ path, name }) => { diff --git a/scripts/run-web.sh b/scripts/run-web.sh new file mode 100644 index 000000000..47a8170a5 --- /dev/null +++ b/scripts/run-web.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env sh +# Run the inspector web app. Usage: npm run web [-- SERVER] or npm run web [-- --dev [SERVER]] +# SERVER defaults to "everything" if omitted. Pass --dev for Vite dev mode. +DEV="" +if [ "$1" = "--dev" ]; then + shift + DEV="--dev" +fi +SERVER="${1:-everything}" +exec node cli/build/cli.js --web --config mcp.json --server "$SERVER" $DEV diff --git a/scripts/update-version.js b/scripts/update-version.js index 91b69f3bf..b2934ab31 100755 --- a/scripts/update-version.js +++ b/scripts/update-version.js @@ -40,6 +40,7 @@ const packagePaths = [ "client/package.json", "server/package.json", "cli/package.json", + "tui/package.json", ]; const updatedFiles = []; diff --git a/shared/__tests__/auth/discovery.test.ts b/shared/__tests__/auth/discovery.test.ts new file mode 100644 index 000000000..591701291 --- /dev/null +++ b/shared/__tests__/auth/discovery.test.ts @@ -0,0 +1,179 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { discoverScopes } from "../../auth/discovery.js"; +import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; + +// Mock SDK functions +vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + discoverAuthorizationServerMetadata: vi.fn(), +})); + +describe("OAuth Scope Discovery", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("should return scopes from resource metadata when available", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: ["read", "write"], + }); + + const resourceMetadata: OAuthProtectedResourceMetadata = { + resource: "http://localhost:3000", + authorization_servers: ["http://localhost:3000"], + scopes_supported: ["read", "write", "admin"], + }; + + const scopes = await discoverScopes( + "http://localhost:3000", + resourceMetadata, + ); + + expect(scopes).toBe("read write admin"); + }); + + it("should fall back to OAuth metadata scopes when resource metadata has no scopes", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: ["read", "write"], + }); + + const resourceMetadata: OAuthProtectedResourceMetadata = { + resource: "http://localhost:3000", + authorization_servers: ["http://localhost:3000"], + scopes_supported: [], + }; + + const scopes = await discoverScopes( + "http://localhost:3000", + resourceMetadata, + ); + + expect(scopes).toBe("read write"); + }); + + it("should fall back to OAuth metadata scopes when resource metadata is not provided", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: ["read", "write"], + }); + + const scopes = await discoverScopes("http://localhost:3000"); + + expect(scopes).toBe("read write"); + }); + + it("should return undefined when no scopes are available", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: [], + }); + + const scopes = await discoverScopes("http://localhost:3000"); + + expect(scopes).toBeUndefined(); + }); + + it("should return undefined when discovery fails", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockRejectedValue( + new Error("Discovery failed"), + ); + + const scopes = await discoverScopes("http://localhost:3000"); + + expect(scopes).toBeUndefined(); + }); + + it("should return undefined when metadata is undefined", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue(undefined); + + const scopes = await discoverScopes("http://localhost:3000"); + + expect(scopes).toBeUndefined(); + }); + + it("should use OAuth metadata scopes when resource has scopes_supported undefined", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: ["read", "write"], + }); + + const resourceMetadata: OAuthProtectedResourceMetadata = { + resource: "http://localhost:3000", + authorization_servers: ["http://localhost:3000"], + scopes_supported: undefined as unknown as string[], + }; + + const scopes = await discoverScopes( + "http://localhost:3000", + resourceMetadata, + ); + + expect(scopes).toBe("read write"); + }); + + it("should return single scope when only one scope is supported", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: ["openid"], + }); + + const scopes = await discoverScopes("http://localhost:3000"); + + expect(scopes).toBe("openid"); + }); + + it("should pass fetchFn to discoverAuthorizationServerMetadata when provided", async () => { + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockFetchFn = vi.fn(); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + scopes_supported: ["read", "write"], + }); + + await discoverScopes("http://localhost:3000", undefined, mockFetchFn); + + expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith( + new URL("/", "http://localhost:3000"), + { fetchFn: mockFetchFn }, + ); + }); +}); diff --git a/shared/__tests__/auth/oauth-callback-server.test.ts b/shared/__tests__/auth/oauth-callback-server.test.ts new file mode 100644 index 000000000..f900fcb91 --- /dev/null +++ b/shared/__tests__/auth/oauth-callback-server.test.ts @@ -0,0 +1,196 @@ +import { describe, it, expect, afterEach } from "vitest"; +import { + createOAuthCallbackServer, + type OAuthCallbackServer, +} from "../../auth/node/oauth-callback-server.js"; + +describe("OAuthCallbackServer", () => { + let server: OAuthCallbackServer; + + afterEach(async () => { + if (server) await server.stop(); + }); + + it("start() returns port and redirectUrl", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ port: 0 }); + + expect(result.port).toBeGreaterThan(0); + expect(result.redirectUrl).toBe( + `http://127.0.0.1:${result.port}/oauth/callback`, + ); + }); + + it("start() supports custom host, path, and port", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ + hostname: "127.0.0.1", + port: 0, + path: "/custom/path", + }); + + expect(result.redirectUrl).toBe( + `http://127.0.0.1:${result.port}/custom/path`, + ); + }); + + it("GET /oauth/callback?code=abc&state=xyz returns 200 and invokes onCallback", async () => { + server = createOAuthCallbackServer(); + const received: { code?: string; state?: string } = {}; + const result = await server.start({ + port: 0, + onCallback: async (p) => { + received.code = p.code; + received.state = p.state; + }, + }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback?code=authcode123&state=mystate`, + ); + + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("text/html"); + const html = await res.text(); + expect(html).toContain("OAuth complete"); + expect(html).toContain("close this window"); + expect(received.code).toBe("authcode123"); + expect(received.state).toBe("mystate"); + }); + + it("GET /oauth/callback?code=abc returns 200 and invokes onCallback without state", async () => { + server = createOAuthCallbackServer(); + const received: { code?: string; state?: string } = {}; + const result = await server.start({ + port: 0, + onCallback: async (p) => { + received.code = p.code; + received.state = p.state; + }, + }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback?code=xyz`, + ); + + expect(res.status).toBe(200); + expect(received.code).toBe("xyz"); + expect(received.state).toBeUndefined(); + }); + + it("GET /oauth/callback/guided returns 404 (single path only)", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ port: 0 }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback/guided?code=guided-code`, + ); + + expect(res.status).toBe(404); + }); + + it("GET /oauth/callback?error=access_denied returns 400 and invokes onError", async () => { + server = createOAuthCallbackServer(); + const errors: Array<{ + error: string; + error_description?: string | null; + }> = []; + const result = await server.start({ + port: 0, + onError: (p) => errors.push(p), + }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback?error=access_denied&error_description=User%20denied`, + ); + + expect(res.status).toBe(400); + const html = await res.text(); + expect(html).toContain("OAuth failed"); + expect(html).toContain("access_denied"); + expect(errors).toHaveLength(1); + expect(errors[0]!.error).toBe("access_denied"); + expect(errors[0]!.error_description).toBe("User denied"); + }); + + it("GET /oauth/callback (missing code and error) returns 400", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ port: 0 }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback?state=foo`, + ); + + expect(res.status).toBe(400); + const html = await res.text(); + expect(html).toContain("OAuth failed"); + }); + + it("GET /other returns 404", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ port: 0 }); + + const res = await fetch(`http://localhost:${result.port}/other`); + + expect(res.status).toBe(404); + }); + + it("POST /oauth/callback returns 405", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ port: 0 }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback?code=x`, + { method: "POST" }, + ); + + expect(res.status).toBe(405); + }); + + it("stops server after first successful callback so second request fails", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ + port: 0, + onCallback: async () => {}, + }); + + const first = await fetch( + `http://localhost:${result.port}/oauth/callback?code=first`, + ); + expect(first.status).toBe(200); + + // Server stops after sending 200, so second request gets connection refused + await expect( + fetch(`http://localhost:${result.port}/oauth/callback?code=second`), + ).rejects.toThrow(); + }); + + it("stop() closes the server", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ port: 0 }); + await server.stop(); + + await expect( + fetch(`http://localhost:${result.port}/oauth/callback?code=x`), + ).rejects.toThrow(); + }); + + it("onCallback rejection returns 500 and error HTML", async () => { + server = createOAuthCallbackServer(); + const result = await server.start({ + port: 0, + onCallback: async () => { + throw new Error("exchange failed"); + }, + }); + + const res = await fetch( + `http://localhost:${result.port}/oauth/callback?code=abc`, + ); + + expect(res.status).toBe(500); + const html = await res.text(); + expect(html).toContain("OAuth failed"); + expect(html).toContain("exchange failed"); + }); +}); diff --git a/shared/__tests__/auth/providers.test.ts b/shared/__tests__/auth/providers.test.ts new file mode 100644 index 000000000..55d787fb1 --- /dev/null +++ b/shared/__tests__/auth/providers.test.ts @@ -0,0 +1,73 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { ConsoleNavigation, CallbackNavigation } from "../../auth/providers.js"; +import { BrowserNavigation } from "../../auth/browser/providers.js"; + +describe("OAuthNavigation", () => { + describe("ConsoleNavigation", () => { + it("should log authorization URL to console", () => { + const navigation = new ConsoleNavigation(); + const authUrl = new URL("http://example.com/authorize?client_id=123"); + + const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {}); + + navigation.navigateToAuthorization(authUrl); + + expect(consoleSpy).toHaveBeenCalledWith( + "Please navigate to: http://example.com/authorize?client_id=123", + ); + + consoleSpy.mockRestore(); + }); + }); + + describe("CallbackNavigation", () => { + it("should invoke callback and store authorization URL for retrieval", () => { + const callback = vi.fn(); + const navigation = new CallbackNavigation(callback); + const authUrl = new URL("http://example.com/authorize?client_id=123"); + + expect(navigation.getAuthorizationUrl()).toBeNull(); + + navigation.navigateToAuthorization(authUrl); + + expect(callback).toHaveBeenCalledWith(authUrl); + expect(navigation.getAuthorizationUrl()).toBe(authUrl); + }); + }); + + describe("BrowserNavigation", () => { + // Mock window.location for Node.js environment + const originalWindow = global.window; + + beforeEach(() => { + (global as any).window = { + location: { + href: "http://localhost:5173", + }, + }; + }); + + afterEach(() => { + global.window = originalWindow; + }); + + it("should set window.location.href to authorization URL", () => { + const navigation = new BrowserNavigation(); + const authUrl = new URL("http://example.com/authorize?client_id=123"); + + navigation.navigateToAuthorization(authUrl); + + expect((global as any).window.location.href).toBe(authUrl.toString()); + }); + + it("should throw error in non-browser environment", () => { + delete (global as any).window; + const navigation = new BrowserNavigation(); + const authUrl = new URL("http://example.com/authorize"); + + expect(() => navigation.navigateToAuthorization(authUrl)).toThrow( + "BrowserNavigation requires browser environment", + ); + }); + }); +}); diff --git a/shared/__tests__/auth/state-machine.test.ts b/shared/__tests__/auth/state-machine.test.ts new file mode 100644 index 000000000..32c600d41 --- /dev/null +++ b/shared/__tests__/auth/state-machine.test.ts @@ -0,0 +1,331 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { + OAuthStateMachine, + oauthTransitions, +} from "../../auth/state-machine.js"; +import type { AuthGuidedState, OAuthStep } from "../../auth/types.js"; +import { EMPTY_GUIDED_STATE } from "../../auth/types.js"; +import type { BaseOAuthClientProvider } from "../../auth/providers.js"; +import type { OAuthMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; + +// Mock SDK functions +vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + discoverAuthorizationServerMetadata: vi.fn(), + discoverOAuthProtectedResourceMetadata: vi.fn(), + registerClient: vi.fn(), + startAuthorization: vi.fn(), + exchangeAuthorization: vi.fn(), + selectResourceURL: vi.fn(), +})); + +describe("OAuthStateMachine", () => { + let mockProvider: BaseOAuthClientProvider; + let updateState: (updates: Partial) => void; + let state: AuthGuidedState; + + beforeEach(() => { + state = { ...EMPTY_GUIDED_STATE }; + updateState = vi.fn((updates: Partial) => { + state = { ...state, ...updates }; + }); + + mockProvider = { + serverUrl: "http://localhost:3000", + redirectUrl: "http://localhost:3000/callback", + scope: "read write", + clientMetadata: { + redirect_uris: ["http://localhost:3000/callback"], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], + response_types: ["code"], + client_name: "Test Client", + scope: "read write", + }, + clientInformation: vi.fn(), + saveClientInformation: vi.fn(), + tokens: vi.fn(), + saveTokens: vi.fn(), + codeVerifier: vi.fn(() => "test-code-verifier"), + clear: vi.fn(), + state: vi.fn(() => "test-state"), + getServerMetadata: vi.fn(() => null), + saveServerMetadata: vi.fn(), + } as unknown as BaseOAuthClientProvider; + }); + + describe("oauthTransitions", () => { + it("should have transitions for all OAuth steps", () => { + const steps: OAuthStep[] = [ + "metadata_discovery", + "client_registration", + "authorization_redirect", + "authorization_code", + "token_request", + "complete", + ]; + + steps.forEach((step) => { + expect(oauthTransitions[step]).toBeDefined(); + expect(oauthTransitions[step].canTransition).toBeDefined(); + expect(oauthTransitions[step].execute).toBeDefined(); + }); + }); + }); + + describe("OAuthStateMachine", () => { + it("should create state machine instance", () => { + const stateMachine = new OAuthStateMachine( + "http://localhost:3000", + mockProvider, + updateState, + ); + + expect(stateMachine).toBeDefined(); + }); + + it("should update state when executeStep is called", async () => { + const stateMachine = new OAuthStateMachine( + "http://localhost:3000", + mockProvider, + updateState, + ); + + const { discoverAuthorizationServerMetadata } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + } as OAuthMetadata); + + await stateMachine.executeStep(state); + + expect(updateState).toHaveBeenCalled(); + }); + }); + + describe("Resource metadata discovery and selection", () => { + const serverUrl = "http://localhost:3000"; + const resourceMetadata = { + resource: "http://localhost:3000", + authorization_servers: ["http://localhost:3000"], + scopes_supported: ["read", "write"], + }; + + beforeEach(async () => { + const { + discoverAuthorizationServerMetadata, + discoverOAuthProtectedResourceMetadata, + selectResourceURL, + } = await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + } as OAuthMetadata); + vi.mocked(discoverOAuthProtectedResourceMetadata).mockReset(); + vi.mocked(selectResourceURL).mockReset(); + }); + + it("should discover resource metadata from well-known and use first authorization server", async () => { + const selectedResource = new URL("http://localhost:3000"); + const { discoverOAuthProtectedResourceMetadata, selectResourceURL } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue( + resourceMetadata as any, + ); + vi.mocked(selectResourceURL).mockResolvedValue(selectedResource); + + const stateMachine = new OAuthStateMachine( + serverUrl, + mockProvider, + updateState, + ); + await stateMachine.executeStep(state); + + expect(discoverOAuthProtectedResourceMetadata).toHaveBeenCalledWith( + serverUrl, + ); + expect(selectResourceURL).toHaveBeenCalledWith( + serverUrl, + mockProvider, + resourceMetadata, + ); + expect(updateState).toHaveBeenCalledWith( + expect.objectContaining({ + resourceMetadata, + resource: selectedResource, + resourceMetadataError: null, + authServerUrl: new URL("http://localhost:3000"), + oauthStep: "client_registration", + }), + ); + }); + + it("should call selectResourceURL only when resource metadata is present", async () => { + const { discoverOAuthProtectedResourceMetadata, selectResourceURL } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValue( + new Error( + "Resource server does not implement OAuth 2.0 Protected Resource Metadata.", + ), + ); + + const stateMachine = new OAuthStateMachine( + serverUrl, + mockProvider, + updateState, + ); + await stateMachine.executeStep(state); + + expect(selectResourceURL).not.toHaveBeenCalled(); + expect(updateState).toHaveBeenCalledWith( + expect.objectContaining({ + resourceMetadata: null, + resourceMetadataError: expect.any(Error), + oauthStep: "client_registration", + }), + ); + }); + + it("should use default auth server URL when discovery fails", async () => { + const { + discoverOAuthProtectedResourceMetadata, + discoverAuthorizationServerMetadata, + } = await import("@modelcontextprotocol/sdk/client/auth.js"); + vi.mocked(discoverOAuthProtectedResourceMetadata).mockRejectedValue( + new Error("Discovery failed"), + ); + vi.mocked(discoverAuthorizationServerMetadata).mockResolvedValue({ + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + } as OAuthMetadata); + + const stateMachine = new OAuthStateMachine( + serverUrl, + mockProvider, + updateState, + ); + await stateMachine.executeStep(state); + + expect(discoverAuthorizationServerMetadata).toHaveBeenCalledWith( + new URL("/", serverUrl), + {}, // No fetchFn when not provided (conditional spread omits it) + ); + expect(updateState).toHaveBeenCalledWith( + expect.objectContaining({ + authServerUrl: new URL("/", serverUrl), + }), + ); + }); + + it("should use default auth server when metadata has empty authorization_servers", async () => { + const { discoverOAuthProtectedResourceMetadata, selectResourceURL } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + const metaNoServers = { + ...resourceMetadata, + authorization_servers: [] as string[], + }; + vi.mocked(discoverOAuthProtectedResourceMetadata).mockResolvedValue( + metaNoServers as any, + ); + vi.mocked(selectResourceURL).mockResolvedValue( + new URL("http://localhost:3000"), + ); + + const stateMachine = new OAuthStateMachine( + serverUrl, + mockProvider, + updateState, + ); + await stateMachine.executeStep(state); + + expect(selectResourceURL).toHaveBeenCalledWith( + serverUrl, + mockProvider, + metaNoServers, + ); + expect(updateState).toHaveBeenCalledWith( + expect.objectContaining({ + resourceMetadata: metaNoServers, + authServerUrl: new URL("/", serverUrl), + oauthStep: "client_registration", + }), + ); + }); + + it("should pass fetchFn to registerClient when provided", async () => { + const { registerClient } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockFetchFn = vi.fn(); + vi.mocked(registerClient).mockResolvedValue({ + client_id: "registered-client-id", + } as any); + + const stateMachine = new OAuthStateMachine( + serverUrl, + mockProvider, + updateState, + mockFetchFn, + ); + await stateMachine.executeStep(state); + expect(state.oauthStep).toBe("client_registration"); + + await stateMachine.executeStep(state); + + expect(registerClient).toHaveBeenCalledWith( + serverUrl, + expect.objectContaining({ + fetchFn: mockFetchFn, + }), + ); + }); + + it("should pass fetchFn to exchangeAuthorization when provided", async () => { + const { exchangeAuthorization } = + await import("@modelcontextprotocol/sdk/client/auth.js"); + const mockFetchFn = vi.fn(); + const metadata = { + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + }; + vi.mocked(exchangeAuthorization).mockResolvedValue({ + access_token: "test-token", + } as any); + + const providerWithMetadata = { + ...mockProvider, + getServerMetadata: vi.fn(() => metadata), + } as unknown as BaseOAuthClientProvider; + + const tokenRequestState: AuthGuidedState = { + ...EMPTY_GUIDED_STATE, + oauthStep: "token_request", + oauthMetadata: metadata as any, + oauthClientInfo: { client_id: "test-client" }, + authorizationCode: "test-code", + }; + + const stateMachine = new OAuthStateMachine( + serverUrl, + providerWithMetadata, + updateState, + mockFetchFn, + ); + await stateMachine.executeStep(tokenRequestState); + + expect(exchangeAuthorization).toHaveBeenCalledWith( + serverUrl, + expect.objectContaining({ + fetchFn: mockFetchFn, + }), + ); + }); + }); +}); diff --git a/shared/__tests__/auth/storage-browser.test.ts b/shared/__tests__/auth/storage-browser.test.ts new file mode 100644 index 000000000..ec3acd3a8 --- /dev/null +++ b/shared/__tests__/auth/storage-browser.test.ts @@ -0,0 +1,302 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { BrowserOAuthStorage } from "../../auth/browser/storage.js"; +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; + +// Mock sessionStorage for Node.js environment +class MockSessionStorage { + private storage: Map = new Map(); + + getItem(key: string): string | null { + return this.storage.get(key) || null; + } + + setItem(key: string, value: string): void { + this.storage.set(key, value); + } + + removeItem(key: string): void { + this.storage.delete(key); + } + + clear(): void { + this.storage.clear(); + } +} + +// Set up global sessionStorage mock +const mockSessionStorage = new MockSessionStorage(); +(global as any).sessionStorage = mockSessionStorage; + +describe("BrowserOAuthStorage", () => { + let storage: BrowserOAuthStorage; + const testServerUrl = "http://localhost:3000"; + + beforeEach(() => { + storage = new BrowserOAuthStorage(); + mockSessionStorage.clear(); + }); + + afterEach(() => { + mockSessionStorage.clear(); + }); + + describe("getClientInformation", () => { + it("should return undefined when no client information is stored", async () => { + const result = await storage.getClientInformation(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored client information", async () => { + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + client_secret: "test-secret", + }; + + storage.saveClientInformation(testServerUrl, clientInfo); + const result = await storage.getClientInformation(testServerUrl); + + expect(result).toEqual(clientInfo); + }); + + it("should return preregistered client information when requested", async () => { + const preregisteredInfo: OAuthClientInformation = { + client_id: "preregistered-id", + client_secret: "preregistered-secret", + }; + + // Use the storage API instead of manually setting sessionStorage + // since BrowserOAuthStorage now uses Zustand with a different storage format + storage.savePreregisteredClientInformation( + testServerUrl, + preregisteredInfo, + ); + + // Wait for Zustand to persist + await new Promise((resolve) => setTimeout(resolve, 100)); + + const result = await storage.getClientInformation(testServerUrl, true); + + expect(result).toEqual(preregisteredInfo); + }); + }); + + describe("saveClientInformation", () => { + it("should save client information", async () => { + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + + storage.saveClientInformation(testServerUrl, clientInfo); + const result = await storage.getClientInformation(testServerUrl); + + expect(result).toEqual(clientInfo); + }); + + it("should overwrite existing client information", async () => { + const firstInfo: OAuthClientInformation = { + client_id: "first-id", + }; + + const secondInfo: OAuthClientInformation = { + client_id: "second-id", + }; + + storage.saveClientInformation(testServerUrl, firstInfo); + storage.saveClientInformation(testServerUrl, secondInfo); + const result = await storage.getClientInformation(testServerUrl); + + expect(result).toEqual(secondInfo); + }); + }); + + describe("getTokens", () => { + it("should return undefined when no tokens are stored", async () => { + const result = await storage.getTokens(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored tokens", async () => { + const tokens: OAuthTokens = { + access_token: "test-access-token", + token_type: "Bearer", + expires_in: 3600, + }; + + storage.saveTokens(testServerUrl, tokens); + const result = await storage.getTokens(testServerUrl); + + expect(result).toEqual(tokens); + }); + }); + + describe("saveTokens", () => { + it("should save tokens", async () => { + const tokens: OAuthTokens = { + access_token: "test-access-token", + token_type: "Bearer", + }; + + storage.saveTokens(testServerUrl, tokens); + const result = await storage.getTokens(testServerUrl); + + expect(result).toEqual(tokens); + }); + }); + + describe("getCodeVerifier", () => { + it("should return undefined when no code verifier is stored", async () => { + const result = await storage.getCodeVerifier(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored code verifier", async () => { + const codeVerifier = "test-code-verifier"; + + storage.saveCodeVerifier(testServerUrl, codeVerifier); + const result = await storage.getCodeVerifier(testServerUrl); + + expect(result).toBe(codeVerifier); + }); + }); + + describe("saveCodeVerifier", () => { + it("should save code verifier", async () => { + const codeVerifier = "test-code-verifier"; + + storage.saveCodeVerifier(testServerUrl, codeVerifier); + const result = await storage.getCodeVerifier(testServerUrl); + + expect(result).toBe(codeVerifier); + }); + }); + + describe("getScope", () => { + it("should return undefined when no scope is stored", async () => { + const result = await storage.getScope(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored scope", async () => { + const scope = "read write"; + + storage.saveScope(testServerUrl, scope); + const result = await storage.getScope(testServerUrl); + + expect(result).toBe(scope); + }); + }); + + describe("saveScope", () => { + it("should save scope", async () => { + const scope = "read write"; + + storage.saveScope(testServerUrl, scope); + const result = await storage.getScope(testServerUrl); + + expect(result).toBe(scope); + }); + }); + + describe("getServerMetadata", () => { + it("should return null when no metadata is stored", async () => { + const result = await storage.getServerMetadata(testServerUrl); + expect(result).toBeNull(); + }); + + it("should return stored metadata", async () => { + const metadata: OAuthMetadata = { + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + }; + + storage.saveServerMetadata(testServerUrl, metadata); + const result = await storage.getServerMetadata(testServerUrl); + + expect(result).toEqual(metadata); + }); + }); + + describe("saveServerMetadata", () => { + it("should save server metadata", async () => { + const metadata: OAuthMetadata = { + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + }; + + storage.saveServerMetadata(testServerUrl, metadata); + const result = await storage.getServerMetadata(testServerUrl); + + expect(result).toEqual(metadata); + }); + }); + + describe("clearServerState", () => { + it("should clear all state for a server", async () => { + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + const tokens: OAuthTokens = { + access_token: "test-token", + token_type: "Bearer", + }; + + storage.saveClientInformation(testServerUrl, clientInfo); + storage.saveTokens(testServerUrl, tokens); + + storage.clear(testServerUrl); + + expect(await storage.getClientInformation(testServerUrl)).toBeUndefined(); + expect(await storage.getTokens(testServerUrl)).toBeUndefined(); + }); + + it("should not affect state for other servers", async () => { + const otherServerUrl = "http://localhost:4000"; + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + + storage.saveClientInformation(testServerUrl, clientInfo); + storage.saveClientInformation(otherServerUrl, clientInfo); + + storage.clear(testServerUrl); + + expect(await storage.getClientInformation(testServerUrl)).toBeUndefined(); + expect(await storage.getClientInformation(otherServerUrl)).toEqual( + clientInfo, + ); + }); + }); + + describe("multiple servers", () => { + it("should store separate state for different servers", async () => { + const server1Url = "http://localhost:3000"; + const server2Url = "http://localhost:4000"; + + const clientInfo1: OAuthClientInformation = { + client_id: "client-1", + }; + + const clientInfo2: OAuthClientInformation = { + client_id: "client-2", + }; + + storage.saveClientInformation(server1Url, clientInfo1); + storage.saveClientInformation(server2Url, clientInfo2); + + expect(await storage.getClientInformation(server1Url)).toEqual( + clientInfo1, + ); + expect(await storage.getClientInformation(server2Url)).toEqual( + clientInfo2, + ); + }); + }); +}); diff --git a/shared/__tests__/auth/storage-node.test.ts b/shared/__tests__/auth/storage-node.test.ts new file mode 100644 index 000000000..7145d98eb --- /dev/null +++ b/shared/__tests__/auth/storage-node.test.ts @@ -0,0 +1,496 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { + NodeOAuthStorage, + getOAuthStore, + getStateFilePath, +} from "../../auth/node/storage-node.js"; +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import * as os from "node:os"; +import { waitForStateFile } from "../../test/test-helpers.js"; + +describe("NodeOAuthStorage", () => { + let storage: NodeOAuthStorage; + const testServerUrl = "http://localhost:3000"; + const stateFilePath = getStateFilePath(); + + beforeEach(async () => { + // Clean up any existing state file + try { + await fs.unlink(stateFilePath); + } catch { + // Ignore if file doesn't exist + } + + // Reset store state by clearing all servers + const store = getOAuthStore(); + const state = store.getState(); + // Clear all server states + Object.keys(state.servers).forEach((url) => { + state.clearServerState(url); + }); + + storage = new NodeOAuthStorage(); + }); + + afterEach(async () => { + // Clean up state file after each test + try { + await fs.unlink(stateFilePath); + } catch { + // Ignore if file doesn't exist + } + + // Reset store state + const store = getOAuthStore(); + const state = store.getState(); + Object.keys(state.servers).forEach((url) => { + state.clearServerState(url); + }); + }); + + describe("getClientInformation", () => { + it("should return undefined when no client information is stored", async () => { + const result = await storage.getClientInformation(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored client information", async () => { + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + client_secret: "test-secret", + }; + + await storage.saveClientInformation(testServerUrl, clientInfo); + + const result = await storage.getClientInformation(testServerUrl); + expect(result).toBeDefined(); + expect(result?.client_id).toBe(clientInfo.client_id); + expect(result?.client_secret).toBe(clientInfo.client_secret); + }); + + it("should return preregistered client information when requested", async () => { + const preregisteredInfo: OAuthClientInformation = { + client_id: "preregistered-id", + client_secret: "preregistered-secret", + }; + + // Store as preregistered by directly setting it in the store + const store = getOAuthStore(); + store.getState().setServerState(testServerUrl, { + preregisteredClientInformation: preregisteredInfo, + }); + + const result = await storage.getClientInformation(testServerUrl, true); + + expect(result).toBeDefined(); + expect(result?.client_id).toBe(preregisteredInfo.client_id); + expect(result?.client_secret).toBe(preregisteredInfo.client_secret); + }); + }); + + describe("saveClientInformation", () => { + it("should save client information", async () => { + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + + await storage.saveClientInformation(testServerUrl, clientInfo); + const result = await storage.getClientInformation(testServerUrl); + + expect(result).toBeDefined(); + expect(result?.client_id).toBe(clientInfo.client_id); + }); + + it("should overwrite existing client information", async () => { + const firstInfo: OAuthClientInformation = { + client_id: "first-id", + }; + + const secondInfo: OAuthClientInformation = { + client_id: "second-id", + }; + + storage.saveClientInformation(testServerUrl, firstInfo); + storage.saveClientInformation(testServerUrl, secondInfo); + const result = await storage.getClientInformation(testServerUrl); + + expect(result).toBeDefined(); + expect(result?.client_id).toBe(secondInfo.client_id); + }); + }); + + describe("getTokens", () => { + it("should return undefined when no tokens are stored", async () => { + const result = await storage.getTokens(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored tokens", async () => { + const tokens: OAuthTokens = { + access_token: "test-access-token", + token_type: "Bearer", + expires_in: 3600, + }; + + await storage.saveTokens(testServerUrl, tokens); + const result = await storage.getTokens(testServerUrl); + + expect(result).toEqual(tokens); + }); + + it("should persist and return refresh_token", async () => { + const tokens: OAuthTokens = { + access_token: "test-access-token", + token_type: "Bearer", + expires_in: 3600, + refresh_token: "test-refresh-token", + }; + + await storage.saveTokens(testServerUrl, tokens); + const result = await storage.getTokens(testServerUrl); + + expect(result).toBeDefined(); + expect(result?.access_token).toBe(tokens.access_token); + expect(result?.refresh_token).toBe(tokens.refresh_token); + }); + }); + + describe("saveTokens", () => { + it("should save tokens", async () => { + const tokens: OAuthTokens = { + access_token: "test-access-token", + token_type: "Bearer", + }; + + await storage.saveTokens(testServerUrl, tokens); + const result = await storage.getTokens(testServerUrl); + + expect(result).toEqual(tokens); + }); + + it("should overwrite existing tokens", async () => { + const firstTokens: OAuthTokens = { + access_token: "first-token", + token_type: "Bearer", + }; + + const secondTokens: OAuthTokens = { + access_token: "second-token", + token_type: "Bearer", + }; + + await storage.saveTokens(testServerUrl, firstTokens); + await storage.saveTokens(testServerUrl, secondTokens); + const result = await storage.getTokens(testServerUrl); + + expect(result).toEqual(secondTokens); + }); + }); + + describe("getCodeVerifier", () => { + it("should return undefined when no code verifier is stored", async () => { + const result = await storage.getCodeVerifier(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored code verifier", async () => { + const codeVerifier = "test-code-verifier"; + + await storage.saveCodeVerifier(testServerUrl, codeVerifier); + const result = await storage.getCodeVerifier(testServerUrl); + + expect(result).toBe(codeVerifier); + }); + }); + + describe("saveCodeVerifier", () => { + it("should save code verifier", async () => { + const codeVerifier = "test-code-verifier"; + + await storage.saveCodeVerifier(testServerUrl, codeVerifier); + const result = await storage.getCodeVerifier(testServerUrl); + + expect(result).toBe(codeVerifier); + }); + }); + + describe("getScope", () => { + it("should return undefined when no scope is stored", async () => { + const result = await storage.getScope(testServerUrl); + expect(result).toBeUndefined(); + }); + + it("should return stored scope", async () => { + const scope = "read write"; + + await storage.saveScope(testServerUrl, scope); + const result = await storage.getScope(testServerUrl); + + expect(result).toBe(scope); + }); + }); + + describe("saveScope", () => { + it("should save scope", async () => { + const scope = "read write"; + + await storage.saveScope(testServerUrl, scope); + const result = await storage.getScope(testServerUrl); + + expect(result).toBe(scope); + }); + }); + + describe("getServerMetadata", () => { + it("should return null when no metadata is stored", async () => { + const result = await storage.getServerMetadata(testServerUrl); + expect(result).toBeNull(); + }); + + it("should return stored metadata", async () => { + const metadata: OAuthMetadata = { + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + }; + + await storage.saveServerMetadata(testServerUrl, metadata); + const result = await storage.getServerMetadata(testServerUrl); + + expect(result).toEqual(metadata); + }); + }); + + describe("saveServerMetadata", () => { + it("should save server metadata", async () => { + const metadata: OAuthMetadata = { + issuer: "http://localhost:3000", + authorization_endpoint: "http://localhost:3000/authorize", + token_endpoint: "http://localhost:3000/token", + response_types_supported: ["code"], + }; + + await storage.saveServerMetadata(testServerUrl, metadata); + const result = await storage.getServerMetadata(testServerUrl); + + expect(result).toEqual(metadata); + }); + }); + + describe("clearServerState", () => { + it("should clear all state for a server", async () => { + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + const tokens: OAuthTokens = { + access_token: "test-token", + token_type: "Bearer", + }; + + await storage.saveClientInformation(testServerUrl, clientInfo); + await storage.saveTokens(testServerUrl, tokens); + + storage.clear(testServerUrl); + + expect(await storage.getClientInformation(testServerUrl)).toBeUndefined(); + expect(await storage.getTokens(testServerUrl)).toBeUndefined(); + }); + + it("should not affect state for other servers", async () => { + const otherServerUrl = "http://localhost:4000"; + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + + await storage.saveClientInformation(testServerUrl, clientInfo); + await storage.saveClientInformation(otherServerUrl, clientInfo); + + storage.clear(testServerUrl); + + expect(await storage.getClientInformation(testServerUrl)).toBeUndefined(); + const otherResult = await storage.getClientInformation(otherServerUrl); + expect(otherResult).toBeDefined(); + expect(otherResult?.client_id).toBe(clientInfo.client_id); + expect(otherResult).toEqual(clientInfo); + }); + }); + + describe("multiple servers", () => { + it("should store separate state for different servers", async () => { + const server1Url = "http://localhost:3000"; + const server2Url = "http://localhost:4000"; + + const clientInfo1: OAuthClientInformation = { + client_id: "client-1", + }; + + const clientInfo2: OAuthClientInformation = { + client_id: "client-2", + }; + + storage.saveClientInformation(server1Url, clientInfo1); + storage.saveClientInformation(server2Url, clientInfo2); + + const result1 = await storage.getClientInformation(server1Url); + const result2 = await storage.getClientInformation(server2Url); + expect(result1).toEqual(clientInfo1); + expect(result2).toEqual(clientInfo2); + }); + }); +}); + +describe("OAuth Store (Zustand)", () => { + const stateFilePath = getStateFilePath(); + + beforeEach(async () => { + try { + await fs.unlink(stateFilePath); + } catch { + // Ignore if file doesn't exist + } + }); + + afterEach(async () => { + try { + await fs.unlink(stateFilePath); + } catch { + // Ignore if file doesn't exist + } + }); + + it("should create a new store", () => { + const store = getOAuthStore(); + expect(store).toBeDefined(); + expect(store.getState).toBeDefined(); + expect(store.setState).toBeDefined(); + }); + + it("should return the same store instance via getOAuthStore", () => { + const store1 = getOAuthStore(); + const store2 = getOAuthStore(); + expect(store1).toBe(store2); + }); + + it("should persist state to file", async () => { + const store = getOAuthStore(); + const serverUrl = "http://localhost:3000"; + const clientInfo: OAuthClientInformation = { + client_id: "test-client-id", + }; + + store.getState().setServerState(serverUrl, { + clientInformation: clientInfo, + }); + + type StateShape = { + state: { + servers: Record; + }; + }; + const parsed = await waitForStateFile( + stateFilePath, + (p) => { + const s = (p as StateShape)?.state?.servers?.[serverUrl]; + return !!s?.clientInformation; + }, + { timeout: 2000, interval: 50 }, + ); + expect(parsed.state.servers[serverUrl]?.clientInformation).toEqual( + clientInfo, + ); + }); +}); + +describe("NodeOAuthStorage with custom storagePath", () => { + const testServerUrl = "http://localhost:3999"; + + it("should use custom path for state file", async () => { + const customPath = path.join( + os.tmpdir(), + `mcp-inspector-oauth-test-${Date.now()}-${Math.random().toString(36).slice(2)}.json`, + ); + + try { + const storage = new NodeOAuthStorage(customPath); + const tokens: OAuthTokens = { + access_token: "custom-path-token", + token_type: "Bearer", + refresh_token: "custom-refresh", + }; + await storage.saveTokens(testServerUrl, tokens); + + type StateShape = { + state: { + servers: Record; + }; + }; + const parsed = await waitForStateFile( + customPath, + (p) => { + const t = (p as StateShape)?.state?.servers?.[testServerUrl]?.tokens; + return t?.access_token === tokens.access_token; + }, + { timeout: 2000, interval: 50 }, + ); + + expect(parsed.state.servers[testServerUrl]?.tokens?.access_token).toBe( + tokens.access_token, + ); + + const stored = await storage.getTokens(testServerUrl); + expect(stored?.access_token).toBe(tokens.access_token); + expect(stored?.refresh_token).toBe(tokens.refresh_token); + } finally { + try { + await fs.unlink(customPath); + } catch { + /* ignore */ + } + } + }); + + it("should isolate state from default store", async () => { + const customPath = path.join( + os.tmpdir(), + `mcp-inspector-oauth-isolate-${Date.now()}-${Math.random().toString(36).slice(2)}.json`, + ); + + try { + const defaultStore = getOAuthStore(); + defaultStore.getState().setServerState(testServerUrl, { + tokens: { + access_token: "default-token", + token_type: "Bearer", + }, + }); + + const customStorage = new NodeOAuthStorage(customPath); + await customStorage.saveTokens(testServerUrl, { + access_token: "custom-token", + token_type: "Bearer", + }); + + const fromCustom = await customStorage.getTokens(testServerUrl); + expect(fromCustom?.access_token).toBe("custom-token"); + + const defaultStorage = new NodeOAuthStorage(); + const fromDefault = await defaultStorage.getTokens(testServerUrl); + expect(fromDefault?.access_token).toBe("default-token"); + + defaultStore.getState().clearServerState(testServerUrl); + } finally { + try { + await fs.unlink(customPath); + } catch { + /* ignore */ + } + } + }); +}); diff --git a/shared/__tests__/auth/utils.test.ts b/shared/__tests__/auth/utils.test.ts new file mode 100644 index 000000000..bfc19d727 --- /dev/null +++ b/shared/__tests__/auth/utils.test.ts @@ -0,0 +1,232 @@ +import { describe, it, expect } from "vitest"; +import { + parseOAuthCallbackParams, + generateOAuthState, + generateOAuthStateWithMode, + parseOAuthState, + generateOAuthErrorDescription, +} from "../../auth/utils.js"; + +describe("OAuth Utils", () => { + describe("parseOAuthCallbackParams", () => { + it("should parse successful callback with code", () => { + const location = "?code=abc123&state=xyz789"; + const result = parseOAuthCallbackParams(location); + + expect(result.successful).toBe(true); + if (result.successful) { + expect(result.code).toBe("abc123"); + } + }); + + it("should parse error callback", () => { + const location = + "?error=access_denied&error_description=User%20denied%20access"; + const result = parseOAuthCallbackParams(location); + + expect(result.successful).toBe(false); + if (!result.successful) { + expect(result.error).toBe("access_denied"); + expect(result.error_description).toBe("User denied access"); + } + }); + + it("should parse error callback with error_uri", () => { + const location = + "?error=invalid_request&error_description=Invalid%20request&error_uri=https://example.com/error"; + const result = parseOAuthCallbackParams(location); + + expect(result.successful).toBe(false); + if (!result.successful) { + expect(result.error).toBe("invalid_request"); + expect(result.error_description).toBe("Invalid request"); + expect(result.error_uri).toBe("https://example.com/error"); + } + }); + + it("should return invalid_request when neither code nor error is present", () => { + const location = "?state=xyz789"; + const result = parseOAuthCallbackParams(location); + + expect(result.successful).toBe(false); + if (!result.successful) { + expect(result.error).toBe("invalid_request"); + expect(result.error_description).toBe( + "Missing code or error in response", + ); + } + }); + + it("should handle empty query string", () => { + const location = ""; + const result = parseOAuthCallbackParams(location); + + expect(result.successful).toBe(false); + if (!result.successful) { + expect(result.error).toBe("invalid_request"); + } + }); + + it("should handle URL-encoded values", () => { + const location = "?code=abc%20123&error_description=Test%20%26%20More"; + const result = parseOAuthCallbackParams(location); + + expect(result.successful).toBe(true); + if (result.successful) { + expect(result.code).toBe("abc 123"); + } + }); + }); + + describe("generateOAuthState", () => { + it("should generate a random state string", () => { + const state1 = generateOAuthState(); + const state2 = generateOAuthState(); + + expect(typeof state1).toBe("string"); + expect(state1.length).toBeGreaterThan(0); + expect(state1).not.toBe(state2); // Should be different each time + }); + + it("should generate state with consistent length", () => { + const states = Array.from({ length: 10 }, () => generateOAuthState()); + const lengths = states.map((s) => s.length); + const uniqueLengths = new Set(lengths); + + // All states should have the same length (64 hex characters for 32 bytes) + expect(uniqueLengths.size).toBe(1); + expect(lengths[0]).toBe(64); + }); + + it("should generate valid hex string", () => { + const state = generateOAuthState(); + const hexPattern = /^[0-9a-f]+$/; + + expect(hexPattern.test(state)).toBe(true); + }); + }); + + describe("generateOAuthStateWithMode", () => { + it("should generate state with normal prefix", () => { + const state = generateOAuthStateWithMode("normal"); + expect(state.startsWith("normal:")).toBe(true); + expect(state.slice(7)).toMatch(/^[0-9a-f]{64}$/); + }); + + it("should generate state with guided prefix", () => { + const state = generateOAuthStateWithMode("guided"); + expect(state.startsWith("guided:")).toBe(true); + expect(state.slice(7)).toMatch(/^[0-9a-f]{64}$/); + }); + + it("should generate unique states", () => { + const s1 = generateOAuthStateWithMode("normal"); + const s2 = generateOAuthStateWithMode("normal"); + expect(s1).not.toBe(s2); + }); + }); + + describe("parseOAuthState", () => { + it("should parse normal prefix", () => { + const parsed = parseOAuthState("normal:abc123def456"); + expect(parsed).toEqual({ mode: "normal", authId: "abc123def456" }); + }); + + it("should parse guided prefix", () => { + const parsed = parseOAuthState("guided:a1b2c3d4e5f6"); + expect(parsed).toEqual({ mode: "guided", authId: "a1b2c3d4e5f6" }); + }); + + it("should parse legacy 64-char hex as normal", () => { + const hex = "a".repeat(64); + const parsed = parseOAuthState(hex); + expect(parsed).toEqual({ mode: "normal", authId: hex }); + }); + + it("should return null for invalid state", () => { + expect(parseOAuthState("")).toBeNull(); + expect(parseOAuthState("invalid")).toBeNull(); + expect(parseOAuthState("other:xyz")).toBeNull(); + }); + }); + + describe("generateOAuthErrorDescription", () => { + it("should generate error description with error code only", () => { + const params = { + successful: false as const, + error: "access_denied", + error_description: null, + error_uri: null, + }; + + const description = generateOAuthErrorDescription(params); + + expect(description).toBe("Error: access_denied."); + }); + + it("should generate error description with error code and description", () => { + const params = { + successful: false as const, + error: "invalid_request", + error_description: "The request is missing a required parameter", + error_uri: null, + }; + + const description = generateOAuthErrorDescription(params); + + expect(description).toContain("Error: invalid_request."); + expect(description).toContain( + "Details: The request is missing a required parameter.", + ); + }); + + it("should generate error description with all fields", () => { + const params = { + successful: false as const, + error: "server_error", + error_description: "An internal server error occurred", + error_uri: "https://example.com/errors/server_error", + }; + + const description = generateOAuthErrorDescription(params); + + expect(description).toContain("Error: server_error."); + expect(description).toContain( + "Details: An internal server error occurred.", + ); + expect(description).toContain( + "More info: https://example.com/errors/server_error.", + ); + }); + + it("should handle null error_description", () => { + const params = { + successful: false as const, + error: "access_denied", + error_description: null, + error_uri: "https://example.com/error", + }; + + const description = generateOAuthErrorDescription(params); + + expect(description).toContain("Error: access_denied."); + expect(description).not.toContain("Details:"); + expect(description).toContain("More info: https://example.com/error."); + }); + + it("should handle null error_uri", () => { + const params = { + successful: false as const, + error: "invalid_client", + error_description: "Invalid client credentials", + error_uri: null, + }; + + const description = generateOAuthErrorDescription(params); + + expect(description).toContain("Error: invalid_client."); + expect(description).toContain("Details: Invalid client credentials."); + expect(description).not.toContain("More info:"); + }); + }); +}); diff --git a/shared/__tests__/contentCache.test.ts b/shared/__tests__/contentCache.test.ts new file mode 100644 index 000000000..01f8a9304 --- /dev/null +++ b/shared/__tests__/contentCache.test.ts @@ -0,0 +1,564 @@ +import { describe, it, expect, beforeEach } from "vitest"; +import { + ContentCache, + type ReadOnlyContentCache, + type ReadWriteContentCache, +} from "../mcp/contentCache.js"; +import type { + ResourceReadInvocation, + ResourceTemplateReadInvocation, + PromptGetInvocation, + ToolCallInvocation, +} from "../mcp/types.js"; +import type { + ReadResourceResult, + GetPromptResult, + CallToolResult, +} from "@modelcontextprotocol/sdk/types.js"; + +// Helper functions to create test invocation objects +function createResourceReadInvocation( + uri: string, + timestamp: Date = new Date(), +): ResourceReadInvocation { + return { + uri, + timestamp, + result: { + contents: [ + { + uri: uri, + text: `Content for ${uri}`, + }, + ], + } as ReadResourceResult, + }; +} + +function createResourceTemplateReadInvocation( + uriTemplate: string, + expandedUri: string, + params: Record = {}, + timestamp: Date = new Date(), +): ResourceTemplateReadInvocation { + return { + uriTemplate, + expandedUri, + params, + timestamp, + result: { + contents: [ + { + uri: expandedUri, + text: `Content for ${expandedUri}`, + }, + ], + } as ReadResourceResult, + }; +} + +function createPromptGetInvocation( + name: string, + params: Record = {}, + timestamp: Date = new Date(), +): PromptGetInvocation { + return { + name, + params, + timestamp, + result: { + messages: [ + { + role: "user", + content: { + type: "text", + text: `Prompt content for ${name}`, + }, + }, + ], + } as GetPromptResult, + }; +} + +function createToolCallInvocation( + toolName: string, + success: boolean = true, + params: Record = {}, + timestamp: Date = new Date(), +): ToolCallInvocation { + return { + toolName, + params, + timestamp, + success, + result: success + ? ({ + content: [ + { + type: "text", + text: `Result from ${toolName}`, + }, + ], + } as CallToolResult) + : null, + error: success ? undefined : "Tool call failed", + }; +} + +describe("ContentCache", () => { + let cache: ContentCache; + + beforeEach(() => { + cache = new ContentCache(); + }); + + describe("instantiation", () => { + it("should create an empty cache", () => { + expect(cache).toBeInstanceOf(ContentCache); + expect(cache.getResource("test://uri")).toBeNull(); + expect(cache.getResourceTemplate("test://{path}")).toBeNull(); + expect(cache.getPrompt("testPrompt")).toBeNull(); + expect(cache.getToolCallResult("testTool")).toBeNull(); + }); + }); + + describe("Resource caching", () => { + it("should store and retrieve resource content", () => { + const uri = "file:///test.txt"; + const invocation = createResourceReadInvocation(uri); + + cache.setResource(uri, invocation); + const retrieved = cache.getResource(uri); + + expect(retrieved).toBe(invocation); // Object identity preserved + expect(retrieved?.uri).toBe(uri); + const content = retrieved?.result.contents[0]; + expect(content && "text" in content ? content.text : undefined).toBe( + "Content for file:///test.txt", + ); + }); + + it("should return null for non-existent resource", () => { + expect(cache.getResource("file:///nonexistent.txt")).toBeNull(); + }); + + it("should replace existing resource content", () => { + const uri = "file:///test.txt"; + const invocation1 = createResourceReadInvocation(uri, new Date(1000)); + const invocation2 = createResourceReadInvocation(uri, new Date(2000)); + + cache.setResource(uri, invocation1); + cache.setResource(uri, invocation2); + + const retrieved = cache.getResource(uri); + expect(retrieved).toBe(invocation2); + expect(retrieved?.timestamp.getTime()).toBe(2000); + }); + + it("should clear specific resource", () => { + const uri1 = "file:///test1.txt"; + const uri2 = "file:///test2.txt"; + cache.setResource(uri1, createResourceReadInvocation(uri1)); + cache.setResource(uri2, createResourceReadInvocation(uri2)); + + cache.clearResource(uri1); + + expect(cache.getResource(uri1)).toBeNull(); + expect(cache.getResource(uri2)).not.toBeNull(); + }); + + it("should handle clearing non-existent resource", () => { + expect(() => + cache.clearResource("file:///nonexistent.txt"), + ).not.toThrow(); + }); + }); + + describe("Resource template caching", () => { + it("should store and retrieve resource template content", () => { + const uriTemplate = "file:///{path}"; + const expandedUri = "file:///test.txt"; + const params = { path: "test.txt" }; + const invocation = createResourceTemplateReadInvocation( + uriTemplate, + expandedUri, + params, + ); + + cache.setResourceTemplate(uriTemplate, invocation); + const retrieved = cache.getResourceTemplate(uriTemplate); + + expect(retrieved).toBe(invocation); // Object identity preserved + expect(retrieved?.uriTemplate).toBe(uriTemplate); + expect(retrieved?.expandedUri).toBe(expandedUri); + expect(retrieved?.params).toEqual(params); + }); + + it("should return null for non-existent resource template", () => { + expect(cache.getResourceTemplate("file:///{path}")).toBeNull(); + }); + + it("should replace existing resource template content", () => { + const uriTemplate = "file:///{path}"; + const invocation1 = createResourceTemplateReadInvocation( + uriTemplate, + "file:///test1.txt", + { path: "test1.txt" }, + new Date(1000), + ); + const invocation2 = createResourceTemplateReadInvocation( + uriTemplate, + "file:///test2.txt", + { path: "test2.txt" }, + new Date(2000), + ); + + cache.setResourceTemplate(uriTemplate, invocation1); + cache.setResourceTemplate(uriTemplate, invocation2); + + const retrieved = cache.getResourceTemplate(uriTemplate); + expect(retrieved).toBe(invocation2); + expect(retrieved?.expandedUri).toBe("file:///test2.txt"); + }); + + it("should clear specific resource template", () => { + const template1 = "file:///{path1}"; + const template2 = "file:///{path2}"; + cache.setResourceTemplate( + template1, + createResourceTemplateReadInvocation(template1, "file:///test1.txt"), + ); + cache.setResourceTemplate( + template2, + createResourceTemplateReadInvocation(template2, "file:///test2.txt"), + ); + + cache.clearResourceTemplate(template1); + + expect(cache.getResourceTemplate(template1)).toBeNull(); + expect(cache.getResourceTemplate(template2)).not.toBeNull(); + }); + + it("should handle clearing non-existent resource template", () => { + expect(() => + cache.clearResourceTemplate("file:///{nonexistent}"), + ).not.toThrow(); + }); + }); + + describe("Prompt caching", () => { + it("should store and retrieve prompt content", () => { + const name = "testPrompt"; + const params = { city: "NYC" }; + const invocation = createPromptGetInvocation(name, params); + + cache.setPrompt(name, invocation); + const retrieved = cache.getPrompt(name); + + expect(retrieved).toBe(invocation); // Object identity preserved + expect(retrieved?.name).toBe(name); + expect(retrieved?.params).toEqual(params); + const messageContent = retrieved?.result.messages[0]?.content; + expect( + messageContent && "text" in messageContent + ? messageContent.text + : undefined, + ).toBe("Prompt content for testPrompt"); + }); + + it("should return null for non-existent prompt", () => { + expect(cache.getPrompt("nonexistentPrompt")).toBeNull(); + }); + + it("should replace existing prompt content", () => { + const name = "testPrompt"; + const invocation1 = createPromptGetInvocation( + name, + { city: "NYC" }, + new Date(1000), + ); + const invocation2 = createPromptGetInvocation( + name, + { city: "LA" }, + new Date(2000), + ); + + cache.setPrompt(name, invocation1); + cache.setPrompt(name, invocation2); + + const retrieved = cache.getPrompt(name); + expect(retrieved).toBe(invocation2); + expect(retrieved?.params?.city).toBe("LA"); + }); + + it("should clear specific prompt", () => { + const name1 = "prompt1"; + const name2 = "prompt2"; + cache.setPrompt(name1, createPromptGetInvocation(name1)); + cache.setPrompt(name2, createPromptGetInvocation(name2)); + + cache.clearPrompt(name1); + + expect(cache.getPrompt(name1)).toBeNull(); + expect(cache.getPrompt(name2)).not.toBeNull(); + }); + + it("should handle clearing non-existent prompt", () => { + expect(() => cache.clearPrompt("nonexistentPrompt")).not.toThrow(); + }); + }); + + describe("Tool call result caching", () => { + it("should store and retrieve successful tool call result", () => { + const toolName = "testTool"; + const params = { arg1: "value1" }; + const invocation = createToolCallInvocation(toolName, true, params); + + cache.setToolCallResult(toolName, invocation); + const retrieved = cache.getToolCallResult(toolName); + + expect(retrieved).toBe(invocation); // Object identity preserved + expect(retrieved?.toolName).toBe(toolName); + expect(retrieved?.success).toBe(true); + expect(retrieved?.result).not.toBeNull(); + const toolContent = retrieved?.result?.content[0]; + expect( + toolContent && "text" in toolContent ? toolContent.text : undefined, + ).toBe("Result from testTool"); + }); + + it("should store and retrieve failed tool call result", () => { + const toolName = "failingTool"; + const params = { arg1: "value1" }; + const invocation = createToolCallInvocation(toolName, false, params); + + cache.setToolCallResult(toolName, invocation); + const retrieved = cache.getToolCallResult(toolName); + + expect(retrieved).toBe(invocation); // Object identity preserved + expect(retrieved?.toolName).toBe(toolName); + expect(retrieved?.success).toBe(false); + expect(retrieved?.result).toBeNull(); + expect(retrieved?.error).toBe("Tool call failed"); + }); + + it("should return null for non-existent tool call result", () => { + expect(cache.getToolCallResult("nonexistentTool")).toBeNull(); + }); + + it("should replace existing tool call result", () => { + const toolName = "testTool"; + const invocation1 = createToolCallInvocation( + toolName, + true, + { arg1: "value1" }, + new Date(1000), + ); + const invocation2 = createToolCallInvocation( + toolName, + true, + { arg1: "value2" }, + new Date(2000), + ); + + cache.setToolCallResult(toolName, invocation1); + cache.setToolCallResult(toolName, invocation2); + + const retrieved = cache.getToolCallResult(toolName); + expect(retrieved).toBe(invocation2); + expect(retrieved?.params.arg1).toBe("value2"); + }); + + it("should clear specific tool call result", () => { + const tool1 = "tool1"; + const tool2 = "tool2"; + cache.setToolCallResult(tool1, createToolCallInvocation(tool1)); + cache.setToolCallResult(tool2, createToolCallInvocation(tool2)); + + cache.clearToolCallResult(tool1); + + expect(cache.getToolCallResult(tool1)).toBeNull(); + expect(cache.getToolCallResult(tool2)).not.toBeNull(); + }); + + it("should handle clearing non-existent tool call result", () => { + expect(() => cache.clearToolCallResult("nonexistentTool")).not.toThrow(); + }); + }); + + describe("clearAll", () => { + it("should clear all cached content", () => { + // Populate all caches + cache.setResource( + "file:///test.txt", + createResourceReadInvocation("file:///test.txt"), + ); + cache.setResourceTemplate( + "file:///{path}", + createResourceTemplateReadInvocation( + "file:///{path}", + "file:///test.txt", + ), + ); + cache.setPrompt("testPrompt", createPromptGetInvocation("testPrompt")); + cache.setToolCallResult("testTool", createToolCallInvocation("testTool")); + + cache.clearAll(); + + expect(cache.getResource("file:///test.txt")).toBeNull(); + expect(cache.getResourceTemplate("file:///{path}")).toBeNull(); + expect(cache.getPrompt("testPrompt")).toBeNull(); + expect(cache.getToolCallResult("testTool")).toBeNull(); + }); + + it("should handle clearAll on empty cache", () => { + expect(() => cache.clearAll()).not.toThrow(); + }); + }); + + describe("Type safety", () => { + it("should implement ReadWriteContentCache interface", () => { + const cache: ReadWriteContentCache = new ContentCache(); + expect(cache).toBeInstanceOf(ContentCache); + }); + + it("should be assignable to ReadOnlyContentCache", () => { + const cache: ReadOnlyContentCache = new ContentCache(); + expect(cache).toBeInstanceOf(ContentCache); + }); + + it("should maintain type safety for all cache operations", () => { + const uri = "file:///test.txt"; + const invocation = createResourceReadInvocation(uri); + + cache.setResource(uri, invocation); + const retrieved = cache.getResource(uri); + + // TypeScript should infer the correct types + if (retrieved) { + expect(typeof retrieved.uri).toBe("string"); + expect(retrieved.timestamp).toBeInstanceOf(Date); + expect(retrieved.result).toBeDefined(); + } + }); + }); + + describe("clearByUri", () => { + it("should clear regular resource by URI", () => { + const uri = "file:///test.txt"; + cache.setResource(uri, createResourceReadInvocation(uri)); + expect(cache.getResource(uri)).not.toBeNull(); + + cache.clearResourceAndResourceTemplate(uri); + expect(cache.getResource(uri)).toBeNull(); + }); + + it("should clear resource template with matching expandedUri", () => { + const uriTemplate = "file:///{path}"; + const expandedUri = "file:///test.txt"; + const params = { path: "test.txt" }; + cache.setResourceTemplate( + uriTemplate, + createResourceTemplateReadInvocation(uriTemplate, expandedUri, params), + ); + expect(cache.getResourceTemplate(uriTemplate)).not.toBeNull(); + + cache.clearResourceAndResourceTemplate(expandedUri); + expect(cache.getResourceTemplate(uriTemplate)).toBeNull(); + }); + + it("should clear both regular resource and resource template with same URI", () => { + const uri = "file:///test.txt"; + const uriTemplate = "file:///{path}"; + const params = { path: "test.txt" }; + + // Set both a regular resource and a resource template with the same expanded URI + cache.setResource(uri, createResourceReadInvocation(uri)); + cache.setResourceTemplate( + uriTemplate, + createResourceTemplateReadInvocation(uriTemplate, uri, params), + ); + + expect(cache.getResource(uri)).not.toBeNull(); + expect(cache.getResourceTemplate(uriTemplate)).not.toBeNull(); + + // clearByUri should clear both + cache.clearResourceAndResourceTemplate(uri); + + expect(cache.getResource(uri)).toBeNull(); + expect(cache.getResourceTemplate(uriTemplate)).toBeNull(); + }); + + it("should not clear resource template with different expandedUri", () => { + const uriTemplate = "file:///{path}"; + const expandedUri1 = "file:///test1.txt"; + const expandedUri2 = "file:///test2.txt"; + const params1 = { path: "test1.txt" }; + const params2 = { path: "test2.txt" }; + + cache.setResourceTemplate( + uriTemplate, + createResourceTemplateReadInvocation( + uriTemplate, + expandedUri1, + params1, + ), + ); + cache.setResourceTemplate( + "file:///{other}", + createResourceTemplateReadInvocation( + "file:///{other}", + expandedUri2, + params2, + ), + ); + + // Clear by first URI + cache.clearResourceAndResourceTemplate(expandedUri1); + + // First template should be cleared, second should remain + expect(cache.getResourceTemplate(uriTemplate)).toBeNull(); + expect(cache.getResourceTemplate("file:///{other}")).not.toBeNull(); + }); + + it("should handle clearing non-existent URI", () => { + expect(() => + cache.clearResourceAndResourceTemplate("file:///nonexistent.txt"), + ).not.toThrow(); + }); + }); + + describe("Edge cases", () => { + it("should handle multiple operations on the same entry", () => { + const uri = "file:///test.txt"; + const invocation1 = createResourceReadInvocation(uri, new Date(1000)); + const invocation2 = createResourceReadInvocation(uri, new Date(2000)); + const invocation3 = createResourceReadInvocation(uri, new Date(3000)); + + cache.setResource(uri, invocation1); + expect(cache.getResource(uri)).toBe(invocation1); + + cache.setResource(uri, invocation2); + expect(cache.getResource(uri)).toBe(invocation2); + + cache.clearResource(uri); + expect(cache.getResource(uri)).toBeNull(); + + cache.setResource(uri, invocation3); + expect(cache.getResource(uri)).toBe(invocation3); + }); + + it("should handle empty strings as keys", () => { + const invocation = createResourceReadInvocation(""); + cache.setResource("", invocation); + expect(cache.getResource("")).toBe(invocation); + }); + + it("should handle special characters in keys", () => { + const uri = "file:///test with spaces & special chars.txt"; + const invocation = createResourceReadInvocation(uri); + cache.setResource(uri, invocation); + expect(cache.getResource(uri)).toBe(invocation); + }); + }); +}); diff --git a/shared/__tests__/inspectorClient-oauth-e2e.test.ts b/shared/__tests__/inspectorClient-oauth-e2e.test.ts new file mode 100644 index 000000000..91ac17a7d --- /dev/null +++ b/shared/__tests__/inspectorClient-oauth-e2e.test.ts @@ -0,0 +1,1809 @@ +/** + * End-to-end OAuth tests for InspectorClient + * These tests require a test server with OAuth enabled + * Tests are parameterized to run against both SSE and streamable-http transports + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import * as fs from "node:fs/promises"; +import * as os from "node:os"; +import * as path from "node:path"; +import { InspectorClient } from "../mcp/inspectorClient.js"; +import { createTransportNode } from "../mcp/node/transport.js"; +import { TestServerHttp } from "../test/test-server-http.js"; +import { waitForStateFile } from "../test/test-helpers.js"; +import { getDefaultServerConfig } from "../test/test-server-fixtures.js"; +import { + createOAuthTestServerConfig, + createOAuthClientConfig, + completeOAuthAuthorization, + createClientMetadataServer, + type ClientMetadataDocument, +} from "../test/test-server-fixtures.js"; +import { + clearOAuthTestData, + getDCRRequests, + invalidateAccessToken, +} from "../test/test-server-oauth.js"; +import { + clearAllOAuthClientState, + NodeOAuthStorage, +} from "../auth/node/index.js"; +import type { InspectorClientOptions } from "../mcp/inspectorClient.js"; +import type { MCPServerConfig } from "../mcp/types.js"; + +type TransportType = "sse" | "streamable-http"; + +interface TransportConfig { + name: string; + serverType: "sse" | "streamable-http"; + clientType: "sse" | "streamable-http"; + endpoint: string; // "/sse" or "/mcp" +} + +const transports: TransportConfig[] = [ + { + name: "SSE", + serverType: "sse", + clientType: "sse", + endpoint: "/sse", + }, + { + name: "Streamable HTTP", + serverType: "streamable-http", + clientType: "streamable-http", + endpoint: "/mcp", + }, +]; + +describe("InspectorClient OAuth E2E", () => { + let server: TestServerHttp; + let client: InspectorClient; + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + beforeEach(() => { + clearOAuthTestData(); + clearAllOAuthClientState(); + // Capture console.log output instead of printing to stdout during tests + vi.spyOn(console, "log").mockImplementation(() => {}); + }); + + afterEach(async () => { + if (client) { + await client.disconnect(); + } + if (server) { + await server.stop(); + } + // Restore console.log after each test + vi.restoreAllMocks(); + }); + + describe.each(transports)( + "Static/Preregistered Client Mode ($name)", + (transport) => { + it("should complete OAuth flow with static client", async () => { + const staticClientId = "test-static-client"; + const staticClientSecret = "test-static-secret"; + + // Create test server with OAuth enabled and static client + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + // Create client with static OAuth config + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + // Verify tokens are stored + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(tokens?.token_type).toBe("Bearer"); + + // Connection should now be successful + expect(client.getStatus()).toBe("connected"); + }); + + it("should complete OAuth flow with static client using authenticate() (normal mode)", async () => { + const staticClientId = "test-static-client-normal"; + const staticClientSecret = "test-static-secret-normal"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, // Needed for authenticate() to work + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + // Use authenticate() (normal mode) - should use SDK's auth() + const authUrl = await client.authenticate(); + expect(authUrl.href).toContain("/oauth/authorize"); + + const stateAfterAuth = client.getOAuthState(); + expect(stateAfterAuth?.authType).toBe("normal"); + expect(stateAfterAuth?.oauthStep).toBe("authorization_code"); + expect(stateAfterAuth?.authorizationUrl?.href).toBe(authUrl.href); + expect(stateAfterAuth?.oauthClientInfo).toBeDefined(); + expect(stateAfterAuth?.oauthClientInfo?.client_id).toBe(staticClientId); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const stateAfterComplete = client.getOAuthState(); + expect(stateAfterComplete?.authType).toBe("normal"); + expect(stateAfterComplete?.oauthStep).toBe("complete"); + expect(stateAfterComplete?.oauthTokens).toBeDefined(); + expect(stateAfterComplete?.completedAt).toBeDefined(); + expect(typeof stateAfterComplete?.completedAt).toBe("number"); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(tokens?.token_type).toBe("Bearer"); + expect(client.getStatus()).toBe("connected"); + }); + + it("should retry original request after OAuth completion", async () => { + const staticClientId = "test-static-client-2"; + const staticClientSecret = "test-static-secret-2"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + // Auth-provider flow: authenticate first, complete OAuth, then connect. + const authUrl = await client.authenticate(); + expect(authUrl.href).toContain("/oauth/authorize"); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + expect(client.getStatus()).toBe("connected"); + const toolsResult = await client.listTools(); + expect(toolsResult).toBeDefined(); + }); + }, + ); + + describe.each(transports)( + "CIMD (Client ID Metadata Documents) Mode ($name)", + (transport) => { + let metadataServer: { url: string; stop: () => Promise } | null = + null; + + afterEach(async () => { + if (metadataServer) { + await metadataServer.stop(); + metadataServer = null; + } + }); + + it("should complete OAuth flow with CIMD client", async () => { + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + // Create client metadata document + const clientMetadata: ClientMetadataDocument = { + redirect_uris: [testRedirectUrl], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_name: "MCP Inspector Test Client", + client_uri: "https://github.com/modelcontextprotocol/inspector", + scope: "mcp", + }; + + // Start metadata server + metadataServer = await createClientMetadataServer(clientMetadata); + const metadataUrl = metadataServer.url; + + // Create test server with OAuth enabled and CIMD support + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportCIMD: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + // Create client with CIMD config + const oauthConfig = createOAuthClientConfig({ + mode: "cimd", + clientMetadataUrl: metadataUrl, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + // CIMD uses guided mode (HTTP clientMetadataUrl); auth() requires HTTPS + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + // Verify tokens are stored + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(tokens?.token_type).toBe("Bearer"); + + // Connection should now be successful + expect(client.getStatus()).toBe("connected"); + }); + + it("should retry original request after OAuth completion with CIMD", async () => { + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + const clientMetadata: ClientMetadataDocument = { + redirect_uris: [testRedirectUrl], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_name: "MCP Inspector Test Client", + scope: "mcp", + }; + + metadataServer = await createClientMetadataServer(clientMetadata); + const metadataUrl = metadataServer.url; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportCIMD: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "cimd", + clientMetadataUrl: metadataUrl, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + expect(client.getStatus()).toBe("connected"); + const toolsResult = await client.listTools(); + expect(toolsResult).toBeDefined(); + }); + }, + ); + + describe.each(transports)( + "DCR (Dynamic Client Registration) Mode ($name)", + (transport) => { + it("should register client and complete OAuth flow", async () => { + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "dcr", + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.authenticate(); + expect(authUrl.href).toContain("/oauth/authorize"); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(client.getStatus()).toBe("connected"); + }); + + it("should register client and complete OAuth flow using authenticate() (normal mode)", async () => { + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "dcr", + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + // Use authenticate() (normal mode) - should trigger DCR via SDK's auth() + const authUrl = await client.authenticate(); + expect(authUrl.href).toContain("/oauth/authorize"); + + const stateAfterAuth = client.getOAuthState(); + expect(stateAfterAuth?.authType).toBe("normal"); + expect(stateAfterAuth?.oauthStep).toBe("authorization_code"); + expect(stateAfterAuth?.oauthClientInfo).toBeDefined(); + expect(stateAfterAuth?.oauthClientInfo?.client_id).toBeDefined(); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const stateAfterComplete = client.getOAuthState(); + expect(stateAfterComplete?.authType).toBe("normal"); + expect(stateAfterComplete?.oauthStep).toBe("complete"); + expect(stateAfterComplete?.oauthTokens).toBeDefined(); + expect(stateAfterComplete?.completedAt).toBeDefined(); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(client.getStatus()).toBe("connected"); + }); + + it("should register client and complete OAuth flow using runGuidedAuth() (automated guided mode)", async () => { + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "dcr", + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const stateAfterComplete = client.getOAuthState(); + expect(stateAfterComplete?.authType).toBe("guided"); + expect(stateAfterComplete?.oauthStep).toBe("complete"); + expect(stateAfterComplete?.completedAt).toBeDefined(); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(client.getStatus()).toBe("connected"); + }); + + it("should complete OAuth flow using manual guided mode (beginGuidedAuth + proceedOAuthStep)", async () => { + const staticClientId = "test-static-manual"; + const staticClientSecret = "test-static-secret-manual"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + await client.beginGuidedAuth(); + + while (true) { + const state = client.getOAuthState(); + if ( + state?.oauthStep === "authorization_code" || + state?.oauthStep === "complete" + ) { + break; + } + await client.proceedOAuthStep(); + } + + const state = client.getOAuthState(); + const authUrl = state?.authorizationUrl; + if (!authUrl) throw new Error("Expected authorizationUrl"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const stateAfterComplete = client.getOAuthState(); + expect(stateAfterComplete?.authType).toBe("guided"); + expect(stateAfterComplete?.oauthStep).toBe("complete"); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(client.getStatus()).toBe("connected"); + }); + + it("should set authorization code without completing flow (completeFlow=false)", async () => { + const staticClientId = "test-static-set-code-false"; + const staticClientSecret = "test-static-secret-set-code-false"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + // Start guided auth and progress to authorization_code step + await client.beginGuidedAuth(); + while (true) { + const state = client.getOAuthState(); + if (state?.oauthStep === "authorization_code") { + break; + } + await client.proceedOAuthStep(); + } + + const stateBefore = client.getOAuthState(); + expect(stateBefore?.oauthStep).toBe("authorization_code"); + expect(stateBefore?.authorizationCode).toBe(""); + + const authUrl = stateBefore?.authorizationUrl; + if (!authUrl) throw new Error("Expected authorizationUrl"); + const authCode = await completeOAuthAuthorization(authUrl); + + // Set code without completing flow + const stepEvents: Array<{ step: string; previousStep: string }> = []; + client.addEventListener("oauthStepChange", (event) => { + stepEvents.push({ + step: event.detail.step, + previousStep: event.detail.previousStep, + }); + }); + + await client.setGuidedAuthorizationCode(authCode, false); + + // Verify code was set but flow didn't complete + const stateAfter = client.getOAuthState(); + expect(stateAfter?.oauthStep).toBe("authorization_code"); + expect(stateAfter?.authorizationCode).toBe(authCode); + expect(stateAfter?.oauthTokens).toBeFalsy(); + + // Should have dispatched one event (code set, but step unchanged) + expect(stepEvents.length).toBe(1); + expect(stepEvents[0]?.step).toBe("authorization_code"); + expect(stepEvents[0]?.previousStep).toBe("authorization_code"); + + // Now manually proceed to complete + await client.proceedOAuthStep(); // authorization_code -> token_request + await client.proceedOAuthStep(); // token_request -> complete + + const finalState = client.getOAuthState(); + expect(finalState?.oauthStep).toBe("complete"); + expect(finalState?.oauthTokens).toBeDefined(); + }); + + it("should set authorization code and complete flow (completeFlow=true)", async () => { + const staticClientId = "test-static-set-code-true"; + const staticClientSecret = "test-static-secret-set-code-true"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + // Start guided auth and progress to authorization_code step + await client.beginGuidedAuth(); + while (true) { + const state = client.getOAuthState(); + if (state?.oauthStep === "authorization_code") { + break; + } + await client.proceedOAuthStep(); + } + + const stateBefore = client.getOAuthState(); + expect(stateBefore?.oauthStep).toBe("authorization_code"); + expect(stateBefore?.authorizationCode).toBe(""); + + const authUrl = stateBefore?.authorizationUrl; + if (!authUrl) throw new Error("Expected authorizationUrl"); + const authCode = await completeOAuthAuthorization(authUrl); + + // Set code with completeFlow=true (should auto-complete) + const stepEvents: Array<{ step: string; previousStep: string }> = []; + client.addEventListener("oauthStepChange", (event) => { + stepEvents.push({ + step: event.detail.step, + previousStep: event.detail.previousStep, + }); + }); + + await client.setGuidedAuthorizationCode(authCode, true); + + // Verify flow completed automatically + const stateAfter = client.getOAuthState(); + expect(stateAfter?.oauthStep).toBe("complete"); + expect(stateAfter?.authorizationCode).toBe(authCode); + expect(stateAfter?.oauthTokens).toBeDefined(); + + // Should have dispatched step change events for transitions (not for code setting) + // authorization_code -> token_request -> complete + expect(stepEvents.length).toBeGreaterThanOrEqual(2); + const lastEvent = stepEvents[stepEvents.length - 1]; + expect(lastEvent?.step).toBe("complete"); + }); + + it("runGuidedAuth continues from already-started guided flow", async () => { + const staticClientId = "test-run-from-started"; + const staticClientSecret = "test-secret-run-from-started"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + await client.beginGuidedAuth(); + await client.proceedOAuthStep(); + + const stateBeforeRun = client.getOAuthState(); + expect(stateBeforeRun?.oauthStep).not.toBe("authorization_code"); + expect(stateBeforeRun?.oauthStep).not.toBe("complete"); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(client.getStatus()).toBe("connected"); + }); + + it("runGuidedAuth returns undefined when already complete", async () => { + const staticClientId = "test-run-complete"; + const staticClientSecret = "test-secret-run-complete"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + + const stateAfterComplete = client.getOAuthState(); + expect(stateAfterComplete?.oauthStep).toBe("complete"); + + const authUrlAgain = await client.runGuidedAuth(); + expect(authUrlAgain).toBeUndefined(); + }); + }, + ); + + describe.each(transports)( + "Single redirect URL (DCR) ($name)", + (transport) => { + const redirectUrl = testRedirectUrl; + + it("should include single redirect_uri in DCR registration", async () => { + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "dcr", + redirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.authenticate(); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const dcr = getDCRRequests(); + expect(dcr.length).toBeGreaterThanOrEqual(1); + const uris = dcr[dcr.length - 1]!.redirect_uris; + expect(uris).toEqual([redirectUrl]); + }); + + it("should accept single redirect_uri for both normal and guided auth", async () => { + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "dcr", + redirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrlNormal = await client.authenticate(); + const authCodeNormal = await completeOAuthAuthorization(authUrlNormal); + await client.completeOAuthFlow(authCodeNormal); + await client.connect(); + expect(client.getStatus()).toBe("connected"); + + await client.disconnect(); + + const authUrlGuided = await client.runGuidedAuth(); + if (!authUrlGuided) throw new Error("Expected authorization URL"); + const authCodeGuided = await completeOAuthAuthorization(authUrlGuided); + await client.completeOAuthFlow(authCodeGuided); + await client.connect(); + expect(client.getStatus()).toBe("connected"); + }); + }, + ); + + describe.each(transports)("401 Error Handling ($name)", (transport) => { + it("should dispatch oauthAuthorizationRequired when authenticating", async () => { + const staticClientId = "test-client-401"; + const staticClientSecret = "test-secret-401"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + let authEventReceived = false; + client.addEventListener("oauthAuthorizationRequired", (event) => { + authEventReceived = true; + expect(event.detail.url).toBeInstanceOf(URL); + }); + + await client.authenticate(); + expect(authEventReceived).toBe(true); + }); + }); + + describe.each(transports)( + "Resource metadata discovery and oauthStepChange ($name)", + (transport) => { + it("should discover resource metadata and set resource in guided flow", async () => { + const staticClientId = "test-resource-metadata"; + const staticClientSecret = "test-secret-rm"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + await client.runGuidedAuth(); + + const state = client.getOAuthState(); + expect(state).toBeDefined(); + expect(state?.authType).toBe("guided"); + expect(state?.resourceMetadata).toBeDefined(); + expect(state?.resourceMetadata?.resource).toBeDefined(); + expect( + state?.resourceMetadata?.authorization_servers?.length, + ).toBeGreaterThanOrEqual(1); + expect(state?.resourceMetadata?.scopes_supported).toBeDefined(); + expect(state?.resource).toBeInstanceOf(URL); + expect(state?.resource?.href).toBe(state?.resourceMetadata?.resource); + expect(state?.resourceMetadataError).toBeNull(); + }); + + it("should dispatch oauthStepChange on each step transition in guided flow", async () => { + const staticClientId = "test-step-events"; + const staticClientSecret = "test-secret-se"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const stepEvents: Array<{ + step: string; + previousStep: string; + state: unknown; + }> = []; + client.addEventListener("oauthStepChange", (event) => { + stepEvents.push({ + step: event.detail.step, + previousStep: event.detail.previousStep, + state: event.detail.state, + }); + }); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + + const expectedTransitions = [ + { previousStep: "metadata_discovery", step: "client_registration" }, + { + previousStep: "client_registration", + step: "authorization_redirect", + }, + { + previousStep: "authorization_redirect", + step: "authorization_code", + }, + { previousStep: "authorization_code", step: "token_request" }, + { previousStep: "token_request", step: "complete" }, + ]; + + expect(stepEvents.length).toBe(expectedTransitions.length); + for (let i = 0; i < expectedTransitions.length; i++) { + const e = stepEvents[i]; + expect(e).toBeDefined(); + expect(e?.step).toBe(expectedTransitions[i]!.step); + expect(e?.previousStep).toBe(expectedTransitions[i]!.previousStep); + expect(e?.state).toBeDefined(); + expect(typeof e?.state === "object" && e?.state !== null).toBe(true); + } + + const finalState = client.getOAuthState(); + expect(finalState?.authType).toBe("guided"); + expect(finalState?.oauthStep).toBe("complete"); + expect(finalState?.oauthTokens).toBeDefined(); + expect(finalState?.completedAt).toBeDefined(); + expect(typeof finalState?.completedAt).toBe("number"); + }); + }, + ); + + describe.each(transports)( + "Token refresh (authProvider) ($name)", + (transport) => { + it("should persist refresh_token and succeed connect after 401 via refresh", async () => { + const staticClientId = "test-refresh"; + const staticClientSecret = "test-secret-refresh"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportRefreshTokens: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.authenticate(); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(tokens?.refresh_token).toBeDefined(); + + invalidateAccessToken(tokens!.access_token); + + await client.disconnect(); + await client.connect(); + + expect(client.getStatus()).toBe("connected"); + const toolsResult = await client.listTools(); + expect(toolsResult).toBeDefined(); + }); + }, + ); + + describe.each(transports)("Token Management ($name)", (transport) => { + it("should store and retrieve OAuth tokens", async () => { + const staticClientId = "test-client-tokens"; + const staticClientSecret = "test-secret-tokens"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.authenticate(); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(await client.isOAuthAuthorized()).toBe(true); + + client.clearOAuthTokens(); + expect(await client.isOAuthAuthorized()).toBe(false); + expect(await client.getOAuthTokens()).toBeUndefined(); + }); + }); + + describe.each(transports)("Storage path (custom) ($name)", (transport) => { + it("should persist OAuth state to custom storagePath", async () => { + const customPath = path.join( + os.tmpdir(), + `mcp-inspector-e2e-${Date.now()}-${Math.random().toString(36).slice(2)}.json`, + ); + + const staticClientId = "test-storage-path"; + const staticClientSecret = "test-secret-sp"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: new NodeOAuthStorage(customPath), + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + try { + const authUrl = await client.authenticate(); + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + expect(client.getStatus()).toBe("connected"); + + type StateShape = { + state?: { + servers?: Record; + }; + }; + const parsed = await waitForStateFile( + customPath, + (p) => { + const servers = (p as StateShape)?.state?.servers ?? {}; + return Object.values(servers).some( + (s) => + !!(s as { tokens?: { access_token?: string } })?.tokens + ?.access_token, + ); + }, + { timeout: 2000, interval: 50 }, + ); + expect(Object.keys(parsed.state?.servers ?? {}).length).toBeGreaterThan( + 0, + ); + } finally { + try { + await fs.unlink(customPath); + } catch { + /* ignore */ + } + } + }); + }); + + describe("fetchFn integration", () => { + it("should use provided fetchFn for OAuth HTTP requests", async () => { + const tracker: Array<{ url: string; method: string }> = []; + const fetchFn: typeof fetch = ( + input: RequestInfo | URL, + init?: RequestInit, + ) => { + tracker.push({ + url: typeof input === "string" ? input : input.toString(), + method: init?.method ?? "GET", + }); + return fetch(input, init); + }; + + const staticClientId = "test-fetchFn-client"; + const staticClientSecret = "test-fetchFn-secret"; + const transport = transports[0]!; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + server = new TestServerHttp(serverConfig); + const port = await server.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + fetch: fetchFn, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + expect(client.getStatus()).toBe("connected"); + + expect(tracker.length).toBeGreaterThan(0); + const oauthUrls = tracker.filter( + (c) => + c.url.includes("well-known") || + c.url.includes("/oauth/") || + c.url.includes("token"), + ); + expect(oauthUrls.length).toBeGreaterThan(0); + + // Verify fetch tracking categories: auth vs transport + const fetchRequests = client.getFetchRequests(); + const authFetches = fetchRequests.filter((r) => r.category === "auth"); + const transportFetches = fetchRequests.filter( + (r) => r.category === "transport", + ); + expect(authFetches.length).toBeGreaterThan(0); + expect(transportFetches.length).toBeGreaterThan(0); + }); + }); +}); diff --git a/shared/__tests__/inspectorClient-oauth-fetchFn.test.ts b/shared/__tests__/inspectorClient-oauth-fetchFn.test.ts new file mode 100644 index 000000000..8f81b9636 --- /dev/null +++ b/shared/__tests__/inspectorClient-oauth-fetchFn.test.ts @@ -0,0 +1,172 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { InspectorClient } from "../mcp/inspectorClient.js"; +import { createTransportNode } from "../mcp/node/transport.js"; +import type { MCPServerConfig } from "../mcp/types.js"; +import { createOAuthClientConfig } from "../test/test-server-fixtures.js"; +import type { + InspectorClientOptions, + InspectorClientEnvironment, +} from "../mcp/inspectorClient.js"; + +const mockAuth = vi.fn(); +vi.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + auth: (...args: unknown[]) => mockAuth(...args), +})); + +describe("InspectorClient OAuth fetchFn", () => { + let client: InspectorClient; + + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(console, "log").mockImplementation(() => {}); + + mockAuth.mockImplementation( + async (provider: { redirectToAuthorization: (url: URL) => void }) => { + provider.redirectToAuthorization( + new URL("http://example.com/oauth/authorize"), + ); + return "REDIRECT"; + }, + ); + }); + + afterEach(async () => { + if (client) { + try { + await client.disconnect(); + } catch { + // Ignore disconnect errors + } + } + vi.restoreAllMocks(); + }); + + it("should pass fetchFn to auth() when provided", async () => { + const mockFetchFn = vi.fn(); + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: "test-client", + redirectUrl: "http://localhost:3000/callback", + }); + + client = new InspectorClient( + { type: "sse", url: "http://localhost:3000/sse" } as MCPServerConfig, + { + environment: { + transport: createTransportNode, + fetch: mockFetchFn, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }, + ); + + const url = await client.authenticate(); + + expect(url).toBeInstanceOf(URL); + expect(mockAuth).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + fetchFn: expect.any(Function), + }), + ); + }); + + it("should pass fetchFn to auth() when not provided (uses default fetch)", async () => { + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: "test-client", + redirectUrl: "http://localhost:3000/callback", + }); + + client = new InspectorClient( + { type: "sse", url: "http://localhost:3000/sse" } as MCPServerConfig, + { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + } as InspectorClientOptions, + ); + + await client.authenticate(); + + expect(mockAuth).toHaveBeenCalled(); + const callArgs = mockAuth.mock.calls[0]!; + const options = callArgs[1]; + expect(options).toHaveProperty("fetchFn"); + expect(typeof options.fetchFn).toBe("function"); + }); + + it("should pass fetchFn to auth() in completeOAuthFlow when provided", async () => { + const mockFetchFn = vi.fn(); + mockAuth.mockImplementation( + async (provider: { saveTokens: (tokens: unknown) => void }) => { + provider.saveTokens({ + access_token: "test-token", + token_type: "Bearer", + }); + return "AUTHORIZED"; + }, + ); + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: "test-client", + redirectUrl: "http://localhost:3000/callback", + }); + + client = new InspectorClient( + { type: "sse", url: "http://localhost:3000/sse" } as MCPServerConfig, + { + environment: { + transport: createTransportNode, + fetch: mockFetchFn, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }, + ); + + await client.completeOAuthFlow("test-authorization-code"); + + expect(mockAuth).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + authorizationCode: "test-authorization-code", + fetchFn: expect.any(Function), + }), + ); + }); +}); diff --git a/shared/__tests__/inspectorClient-oauth-remote-storage-e2e.test.ts b/shared/__tests__/inspectorClient-oauth-remote-storage-e2e.test.ts new file mode 100644 index 000000000..f1da292bd --- /dev/null +++ b/shared/__tests__/inspectorClient-oauth-remote-storage-e2e.test.ts @@ -0,0 +1,464 @@ +/** + * End-to-end OAuth tests for InspectorClient using RemoteOAuthStorage. + * Tests OAuth flows with remote storage (HTTP API) instead of file storage. + * These tests verify that OAuth state persists correctly via the remote storage API. + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { serve } from "@hono/node-server"; +import type { ServerType } from "@hono/node-server"; +import { InspectorClient } from "../mcp/inspectorClient.js"; +import { createRemoteTransport } from "../mcp/remote/createRemoteTransport.js"; +import { createRemoteFetch } from "../mcp/remote/createRemoteFetch.js"; +import { RemoteOAuthStorage } from "../auth/remote/storage-remote.js"; +import { createRemoteApp } from "../mcp/remote/node/server.js"; +import { TestServerHttp } from "../test/test-server-http.js"; +import { getDefaultServerConfig } from "../test/test-server-fixtures.js"; +import { + createOAuthTestServerConfig, + createOAuthClientConfig, + completeOAuthAuthorization, + createClientMetadataServer, + type ClientMetadataDocument, +} from "../test/test-server-fixtures.js"; +import { ConsoleNavigation } from "../auth/providers.js"; +import { + clearOAuthTestData, + getDCRRequests, + invalidateAccessToken, +} from "../test/test-server-oauth.js"; +import type { InspectorClientOptions } from "../mcp/inspectorClient.js"; +import type { MCPServerConfig } from "../mcp/types.js"; + +type TransportType = "sse" | "streamable-http"; + +interface TransportConfig { + name: string; + serverType: "sse" | "streamable-http"; + clientType: "sse" | "streamable-http"; + endpoint: string; +} + +const transports: TransportConfig[] = [ + { + name: "SSE", + serverType: "sse", + clientType: "sse", + endpoint: "/sse", + }, + { + name: "Streamable HTTP", + serverType: "streamable-http", + clientType: "streamable-http", + endpoint: "/mcp", + }, +]; + +interface StartRemoteServerOptions { + storageDir?: string; +} + +async function startRemoteServer( + port: number, + options: StartRemoteServerOptions = {}, +): Promise<{ + baseUrl: string; + server: ServerType; + authToken: string; +}> { + const { app, authToken } = createRemoteApp({ + storageDir: options.storageDir, + }); + return new Promise((resolve, reject) => { + const server = serve( + { fetch: app.fetch, port, hostname: "127.0.0.1" }, + (info) => { + const actualPort = + info && typeof info === "object" && "port" in info + ? (info as { port: number }).port + : port; + resolve({ + baseUrl: `http://127.0.0.1:${actualPort}`, + server, + authToken, + }); + }, + ); + server.on("error", reject); + }); +} + +describe("InspectorClient OAuth E2E with Remote Storage", () => { + let mcpServer: TestServerHttp; + let remoteServer: ServerType | null = null; + let remoteBaseUrl: string | null = null; + let remoteAuthToken: string | null = null; + let client: InspectorClient; + let tempDir: string | null = null; + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + beforeEach(() => { + clearOAuthTestData(); + tempDir = mkdtempSync(join(tmpdir(), "inspector-remote-storage-test-")); + vi.spyOn(console, "log").mockImplementation(() => {}); + }); + + afterEach(async () => { + if (client) { + await client.disconnect(); + } + if (mcpServer) { + await mcpServer.stop(); + } + if (remoteServer) { + await new Promise((resolve, reject) => { + remoteServer!.close((err) => (err ? reject(err) : resolve())); + }); + remoteServer = null; + } + if (tempDir) { + try { + rmSync(tempDir, { recursive: true }); + } catch { + // Ignore cleanup errors + } + tempDir = null; + } + vi.restoreAllMocks(); + }); + + async function setupRemoteServer(): Promise { + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir!, + }); + remoteServer = server; + remoteBaseUrl = baseUrl; + remoteAuthToken = authToken; + } + + describe.each(transports)( + "Static/Preregistered Client Mode ($name)", + (transport) => { + it("should complete OAuth flow with static client using remote storage", async () => { + await setupRemoteServer(); + + const staticClientId = "test-static-client"; + const staticClientSecret = "test-static-secret"; + + // Create test server with OAuth enabled and static client + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + mcpServer = new TestServerHttp(serverConfig); + const port = await mcpServer.start(); + const serverUrl = `http://localhost:${port}`; + + // Create client with remote transport and remote OAuth storage + const createTransport = createRemoteTransport({ + baseUrl: remoteBaseUrl!, + authToken: remoteAuthToken!, + }); + const remoteFetch = createRemoteFetch({ + baseUrl: remoteBaseUrl!, + authToken: remoteAuthToken!, + }); + const remoteStorage = new RemoteOAuthStorage({ + baseUrl: remoteBaseUrl!, + storeId: "oauth", + authToken: remoteAuthToken!, + }); + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransport, + fetch: remoteFetch, + oauth: { + storage: remoteStorage, + navigation: new ConsoleNavigation(), + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + // Verify tokens are stored + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + expect(tokens?.token_type).toBe("Bearer"); + + // Connection should now be successful + expect(client.getStatus()).toBe("connected"); + }); + + it("should persist OAuth state and reload on new client instance", async () => { + await setupRemoteServer(); + + const staticClientId = "test-static-client-reload"; + const staticClientSecret = "test-static-secret-reload"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + mcpServer = new TestServerHttp(serverConfig); + const port = await mcpServer.start(); + const serverUrl = `http://localhost:${port}`; + + const createTransport = createRemoteTransport({ + baseUrl: remoteBaseUrl!, + authToken: remoteAuthToken!, + }); + const remoteFetch = createRemoteFetch({ + baseUrl: remoteBaseUrl!, + authToken: remoteAuthToken!, + }); + const remoteStorage = new RemoteOAuthStorage({ + baseUrl: remoteBaseUrl!, + storeId: "oauth", + authToken: remoteAuthToken!, + }); + + // First client: complete OAuth flow + const oauthConfig1 = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig1: InspectorClientOptions = { + environment: { + transport: createTransport, + fetch: remoteFetch, + oauth: { + storage: remoteStorage, + navigation: oauthConfig1.navigation, + redirectUrlProvider: oauthConfig1.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig1.clientId, + clientSecret: oauthConfig1.clientSecret, + clientMetadataUrl: oauthConfig1.clientMetadataUrl, + scope: oauthConfig1.scope, + }, + }; + + const client1 = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig1, + ); + + const authUrl = await client1.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + const authCode = await completeOAuthAuthorization(authUrl); + await client1.completeOAuthFlow(authCode); + await client1.connect(); + + const tokens1 = await client1.getOAuthTokens(); + expect(tokens1).toBeDefined(); + await client1.disconnect(); + + // Wait for persistence + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Second client: should load persisted state + const remoteStorage2 = new RemoteOAuthStorage({ + baseUrl: remoteBaseUrl!, + storeId: "oauth", + authToken: remoteAuthToken!, + }); + + const oauthConfig2 = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig2: InspectorClientOptions = { + environment: { + transport: createTransport, + fetch: remoteFetch, + oauth: { + storage: remoteStorage2, + navigation: oauthConfig2.navigation, + redirectUrlProvider: oauthConfig2.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig2.clientId, + clientSecret: oauthConfig2.clientSecret, + clientMetadataUrl: oauthConfig2.clientMetadataUrl, + scope: oauthConfig2.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig2, + ); + + // Wait for storage to hydrate and tokens to be available + await vi.waitFor( + async () => { + const tokens = await client.getOAuthTokens(); + if (!tokens) { + throw new Error("Tokens not yet loaded from storage"); + } + return tokens; + }, + { timeout: 2000, interval: 50 }, + ); + + // Should be able to connect without re-authenticating + await client.connect(); + expect(client.getStatus()).toBe("connected"); + + // Tokens should be loaded from remote storage + const tokens2 = await client.getOAuthTokens(); + expect(tokens2).toBeDefined(); + expect(tokens2?.access_token).toBe(tokens1?.access_token); + }); + }, + ); + + describe.each(transports)( + "DCR (Dynamic Client Registration) Mode ($name)", + (transport) => { + it("should register client and complete OAuth flow using remote storage", async () => { + await setupRemoteServer(); + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: transport.serverType, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + }), + }; + + mcpServer = new TestServerHttp(serverConfig); + const port = await mcpServer.start(); + const serverUrl = `http://localhost:${port}`; + + const createTransport = createRemoteTransport({ + baseUrl: remoteBaseUrl!, + authToken: remoteAuthToken!, + }); + const remoteFetch = createRemoteFetch({ + baseUrl: remoteBaseUrl!, + authToken: remoteAuthToken!, + }); + const remoteStorage = new RemoteOAuthStorage({ + baseUrl: remoteBaseUrl!, + storeId: "oauth", + authToken: remoteAuthToken!, + }); + + const oauthConfig = createOAuthClientConfig({ + mode: "dcr", + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransport, + fetch: remoteFetch, + oauth: { + storage: remoteStorage, + navigation: new ConsoleNavigation(), + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + client = new InspectorClient( + { + type: transport.clientType, + url: `${serverUrl}${transport.endpoint}`, + } as MCPServerConfig, + clientConfig, + ); + + const authUrl = await client.runGuidedAuth(); + if (!authUrl) throw new Error("Expected authorization URL"); + expect(authUrl.href).toContain("/oauth/authorize"); + + const authCode = await completeOAuthAuthorization(authUrl); + await client.completeOAuthFlow(authCode); + await client.connect(); + + // Verify tokens are stored + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + + expect(client.getStatus()).toBe("connected"); + }); + }, + ); +}); diff --git a/shared/__tests__/inspectorClient-oauth.test.ts b/shared/__tests__/inspectorClient-oauth.test.ts new file mode 100644 index 000000000..aafa21175 --- /dev/null +++ b/shared/__tests__/inspectorClient-oauth.test.ts @@ -0,0 +1,518 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { InspectorClient } from "../mcp/inspectorClient.js"; +import { createTransportNode } from "../mcp/node/transport.js"; +import type { MCPServerConfig } from "../mcp/types.js"; +import { TestServerHttp } from "../test/test-server-http.js"; +import { waitForEvent } from "../test/test-helpers.js"; +import { getDefaultServerConfig } from "../test/test-server-fixtures.js"; +import { + createOAuthTestServerConfig, + createOAuthClientConfig, + completeOAuthAuthorization, +} from "../test/test-server-fixtures.js"; +import { clearOAuthTestData } from "../test/test-server-oauth.js"; +import type { InspectorClientOptions } from "../mcp/inspectorClient.js"; + +describe("InspectorClient OAuth", () => { + let client: InspectorClient; + + beforeEach(() => { + vi.spyOn(console, "log").mockImplementation(() => {}); + // Create client with HTTP transport (OAuth only works with HTTP transports) + const config: MCPServerConfig = { + type: "sse", + url: "http://localhost:3000/sse", + }; + client = new InspectorClient(config, { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }); + }); + + afterEach(async () => { + if (client) { + try { + await client.disconnect(); + } catch { + // Ignore disconnect errors + } + } + vi.restoreAllMocks(); + }); + + describe("OAuth Configuration", () => { + it("should set OAuth configuration", () => { + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: "test-client-id", + clientSecret: "test-secret", + redirectUrl: "http://localhost:3000/callback", + scope: "read write", + }); + client = new InspectorClient( + { type: "sse", url: "http://localhost:3000/sse" }, + { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }, + ); + + // Configuration should be set (no error thrown) + expect(client).toBeDefined(); + }); + + it("should set OAuth configuration with clientMetadataUrl for CIMD", () => { + const oauthConfig = createOAuthClientConfig({ + mode: "cimd", + clientMetadataUrl: "https://example.com/client-metadata.json", + redirectUrl: "http://localhost:3000/callback", + scope: "read write", + }); + client = new InspectorClient( + { type: "sse", url: "http://localhost:3000/sse" }, + { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }, + ); + + expect(client).toBeDefined(); + }); + }); + + describe("OAuth Token Management", () => { + beforeEach(() => { + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: "test-client-id", + redirectUrl: "http://localhost:3000/callback", + }); + client = new InspectorClient( + { type: "sse", url: "http://localhost:3000/sse" }, + { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }, + ); + }); + + it("should return undefined tokens when not authorized", async () => { + const tokens = await client.getOAuthTokens(); + expect(tokens).toBeUndefined(); + }); + + it("should clear OAuth tokens", () => { + client.clearOAuthTokens(); + // Should not throw + expect(client).toBeDefined(); + }); + + it("should return false for isOAuthAuthorized when not authorized", async () => { + const isAuthorized = await client.isOAuthAuthorized(); + expect(isAuthorized).toBe(false); + }); + }); + + describe("OAuth fetch tracking", () => { + let testServer: TestServerHttp; + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + beforeEach(() => { + clearOAuthTestData(); + }); + + afterEach(async () => { + if (testServer) { + await testServer.stop(); + } + }); + + it("should track auth fetches with category 'auth' during guided auth", async () => { + const staticClientId = "test-auth-fetch-client"; + const staticClientSecret = "test-auth-fetch-secret"; + + const serverConfig = { + ...getDefaultServerConfig(), + serverType: "sse" as const, + ...createOAuthTestServerConfig({ + requireAuth: false, + supportDCR: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + testServer = new TestServerHttp(serverConfig); + const port = await testServer.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const testClient = new InspectorClient( + { + type: "sse", + url: `${serverUrl}/sse`, + } as MCPServerConfig, + { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + autoSyncLists: false, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }, + ); + + // beginGuidedAuth runs metadata_discovery, client_registration, authorization_redirect + // (stops at authorization_code awaiting user). Produces auth fetches only (no connect yet). + await testClient.beginGuidedAuth(); + + const fetchRequests = testClient.getFetchRequests(); + const authFetches = fetchRequests.filter( + (req) => req.category === "auth", + ); + expect(authFetches.length).toBeGreaterThan(0); + const hasOAuthUrls = authFetches.some( + (req) => + req.url.includes("well-known") || + req.url.includes("/oauth/") || + req.url.includes("token"), + ); + expect(hasOAuthUrls).toBe(true); + + await testClient.disconnect(); + }); + }); + + describe("OAuth Events", () => { + let testServer: TestServerHttp; + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + beforeEach(() => { + clearOAuthTestData(); + }); + + afterEach(async () => { + if (testServer) { + await testServer.stop(); + } + }); + + it("should dispatch oauthAuthorizationRequired event", async () => { + const staticClientId = "test-event-client"; + const staticClientSecret = "test-event-secret"; + + // Create test server with OAuth enabled and DCR support (for authenticate() normal mode) + const serverConfig = { + ...getDefaultServerConfig(), + serverType: "sse" as const, + ...createOAuthTestServerConfig({ + requireAuth: false, // Don't require auth for this test + supportDCR: true, // Enable DCR so authenticate() can work + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + testServer = new TestServerHttp(serverConfig); + const port = await testServer.start(); + const serverUrl = `http://localhost:${port}`; + + // Create client with OAuth config pointing to test server + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + const testClient = new InspectorClient( + { + type: "sse", + url: `${serverUrl}/sse`, + } as MCPServerConfig, + clientConfig, + ); + + testClient.authenticate().catch(() => {}); + + const detail = await waitForEvent<{ url: URL }>( + testClient, + "oauthAuthorizationRequired", + { timeout: 5000 }, + ); + expect(detail).toHaveProperty("url"); + expect(detail.url).toBeInstanceOf(URL); + expect(detail.url.href).toContain("/oauth/authorize"); + await testClient.disconnect(); + }); + + it("should dispatch oauthError event when OAuth flow fails", async () => { + // Create a minimal test server just for metadata discovery + const serverConfig = { + ...getDefaultServerConfig(), + serverType: "sse" as const, + ...createOAuthTestServerConfig({ + requireAuth: false, + supportDCR: true, + }), + }; + + testServer = new TestServerHttp(serverConfig); + const port = await testServer.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: "test-error-client", + clientSecret: "test-error-secret", + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + const testClient = new InspectorClient( + { + type: "sse", + url: `${serverUrl}/sse`, + } as MCPServerConfig, + clientConfig, + ); + + testClient.completeOAuthFlow("invalid-test-code").catch(() => {}); + + const detail = await waitForEvent<{ error: Error }>( + testClient, + "oauthError", + { + timeout: 3000, + }, + ); + expect(detail).toHaveProperty("error"); + expect(detail.error).toBeInstanceOf(Error); + await testClient.disconnect(); + }); + }); + + describe("Token Injection in HTTP Transports", () => { + let testServer: TestServerHttp; + const testRedirectUrl = "http://localhost:3001/oauth/callback"; + + beforeEach(() => { + clearOAuthTestData(); + }); + + afterEach(async () => { + if (testServer) { + await testServer.stop(); + } + }); + + it("should inject Bearer token in HTTP requests when OAuth is configured", async () => { + const staticClientId = "test-token-injection-client"; + const staticClientSecret = "test-token-injection-secret"; + + // Create test server with OAuth enabled and auth required + const serverConfig = { + ...getDefaultServerConfig(), + serverType: "sse" as const, + ...createOAuthTestServerConfig({ + requireAuth: true, + supportDCR: true, + staticClients: [ + { + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUris: [testRedirectUrl], + }, + ], + }), + }; + + testServer = new TestServerHttp(serverConfig); + const port = await testServer.start(); + const serverUrl = `http://localhost:${port}`; + + const oauthConfig = createOAuthClientConfig({ + mode: "static", + clientId: staticClientId, + clientSecret: staticClientSecret, + redirectUrl: testRedirectUrl, + }); + const clientConfig: InspectorClientOptions = { + environment: { + transport: createTransportNode, + oauth: { + storage: oauthConfig.storage, + navigation: oauthConfig.navigation, + redirectUrlProvider: oauthConfig.redirectUrlProvider, + }, + }, + oauth: { + clientId: oauthConfig.clientId, + clientSecret: oauthConfig.clientSecret, + clientMetadataUrl: oauthConfig.clientMetadataUrl, + scope: oauthConfig.scope, + }, + }; + + const testClient = new InspectorClient( + { + type: "sse", + url: `${serverUrl}/sse`, + } as MCPServerConfig, + clientConfig, + ); + + // Auth-provider flow: authenticate first, complete OAuth, then connect. + // connect() creates transport with authProvider; tokens are already in storage. + const authorizationUrl = await testClient.authenticate(); + const authCode = await completeOAuthAuthorization(authorizationUrl); + await testClient.completeOAuthFlow(authCode); + + await testClient.connect(); + + const tokens = await testClient.getOAuthTokens(); + expect(tokens).toBeDefined(); + expect(tokens?.access_token).toBeDefined(); + + // listTools() succeeds only if authProvider injects Bearer token + const toolsResult = await testClient.listTools(); + expect(toolsResult).toBeDefined(); + + const fetchRequests = testClient.getFetchRequests(); + expect(fetchRequests.length).toBeGreaterThan(0); + + // Auth fetches (discovery, token exchange) should have category 'auth' + const authFetches = fetchRequests.filter( + (req) => req.category === "auth", + ); + expect(authFetches.length).toBeGreaterThan(0); + const oauthFetches = authFetches.filter( + (req) => + req.url.includes("well-known") || + req.url.includes("/oauth/") || + req.url.includes("/token"), + ); + expect(oauthFetches.length).toBeGreaterThan(0); + + // Transport fetches (SSE, MCP) should have category 'transport' + const transportFetches = fetchRequests.filter( + (req) => req.category === "transport", + ); + expect(transportFetches.length).toBeGreaterThan(0); + + const mcpPostRequests = transportFetches.filter( + (req) => + req.method === "POST" && + (req.url.includes("/sse") || req.url.includes("/mcp")) && + !req.url.includes("/oauth"), + ); + if (mcpPostRequests.length > 0) { + const hasAuthHeader = mcpPostRequests.some((req) => { + const authHeader = + req.requestHeaders?.["Authorization"] || + req.requestHeaders?.["authorization"]; + return authHeader && authHeader.startsWith("Bearer "); + }); + if (hasAuthHeader) { + expect(hasAuthHeader).toBe(true); + } + } + + await testClient.disconnect(); + }); + }); +}); diff --git a/shared/__tests__/inspectorClient.test.ts b/shared/__tests__/inspectorClient.test.ts new file mode 100644 index 000000000..14bb6319c --- /dev/null +++ b/shared/__tests__/inspectorClient.test.ts @@ -0,0 +1,5692 @@ +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { InspectorClient } from "../mcp/inspectorClient.js"; +import { createTransportNode } from "../mcp/node/transport.js"; +import { SamplingCreateMessage } from "../mcp/samplingCreateMessage.js"; +import { ElicitationCreateMessage } from "../mcp/elicitationCreateMessage.js"; +import { getTestMcpServerCommand } from "../test/test-server-stdio.js"; +import { + createTestServerHttp, + type TestServerHttp, +} from "../test/test-server-http.js"; +import { waitForEvent, waitForProgressCount } from "../test/test-helpers.js"; +import { + createEchoTool, + createTestServerInfo, + createFileResourceTemplate, + createCollectSampleTool, + createCollectFormElicitationTool, + createCollectUrlElicitationTool, + createSendNotificationTool, + createListRootsTool, + createArgsPrompt, + createArchitectureResource, + createTestCwdResource, + createSimplePrompt, + createUserResourceTemplate, + createNumberedTools, + createNumberedResources, + createNumberedResourceTemplates, + createNumberedPrompts, + getTaskServerConfig, + createElicitationTaskTool, + createSamplingTaskTool, + createProgressTaskTool, + createFlexibleTaskTool, +} from "../test/test-server-fixtures.js"; +import type { MessageEntry, ConnectionStatus } from "../mcp/types.js"; +import type { TypedEvent } from "../mcp/inspectorClientEventTarget.js"; +import type { + CreateMessageResult, + ElicitResult, + CallToolResult, + Task, +} from "@modelcontextprotocol/sdk/types.js"; +import { + RELATED_TASK_META_KEY, + McpError, + ErrorCode, +} from "@modelcontextprotocol/sdk/types.js"; + +describe("InspectorClient", () => { + let client: InspectorClient; + let server: TestServerHttp | null; + let serverCommand: { command: string; args: string[] }; + + beforeEach(() => { + serverCommand = getTestMcpServerCommand(); + server = null; + }); + + afterEach(async () => { + // Orderly teardown: disconnect client first, then stop server. + // HTTP test server sets closing before close so in-flight progress tools skip sending. + if (client) { + try { + await client.disconnect(); + } catch { + // Ignore disconnect errors + } + client = null as any; + } + if (server) { + try { + await server.stop(); + } catch { + // Ignore server stop errors + } + server = null; + } + }); + + describe("Connection Management", () => { + it("should create client with stdio transport", () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { environment: { transport: createTransportNode } }, + ); + + expect(client.getStatus()).toBe("disconnected"); + expect(client.getServerType()).toBe("stdio"); + }); + + it("should connect to server", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + expect(client.getStatus()).toBe("connected"); + }); + + it("should disconnect from server", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + expect(client.getStatus()).toBe("connected"); + + await client.disconnect(); + expect(client.getStatus()).toBe("disconnected"); + }); + + it("should clear server state on disconnect", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + expect(client.getTools().length).toBeGreaterThan(0); + + await client.disconnect(); + expect(client.getTools().length).toBe(0); + expect(client.getResources().length).toBe(0); + expect(client.getPrompts().length).toBe(0); + }); + + it("should clear messages on connect", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + // Make a request to generate messages + await client.listAllTools(); + const firstConnectMessages = client.getMessages(); + expect(firstConnectMessages.length).toBeGreaterThan(0); + + // Disconnect and reconnect + await client.disconnect(); + await client.connect(); + // After reconnect, messages should be cleared, but connect() itself creates new messages (initialize) + // So we should have messages from the new connection, but not from the old one + const secondConnectMessages = client.getMessages(); + // The new connection should have at least the initialize message + expect(secondConnectMessages.length).toBeGreaterThan(0); + // But the first message should be from the new connection (check timestamp) + if (firstConnectMessages.length > 0 && secondConnectMessages.length > 0) { + const lastFirstMessage = + firstConnectMessages[firstConnectMessages.length - 1]; + const firstSecondMessage = secondConnectMessages[0]; + if (lastFirstMessage && firstSecondMessage) { + expect(firstSecondMessage.timestamp.getTime()).toBeGreaterThanOrEqual( + lastFirstMessage.timestamp.getTime(), + ); + } + } + }); + }); + + describe("Message Tracking", () => { + it("should track requests", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + await client.listAllTools(); + + const messages = client.getMessages(); + expect(messages.length).toBeGreaterThan(0); + const request = messages.find((m) => m.direction === "request"); + expect(request).toBeDefined(); + if (request) { + expect("method" in request.message).toBe(true); + } + }); + + it("should track responses", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + await client.listAllTools(); + + const messages = client.getMessages(); + const request = messages.find((m) => m.direction === "request"); + expect(request).toBeDefined(); + if (request && "response" in request) { + expect(request.response).toBeDefined(); + expect(request.duration).toBeDefined(); + } + }); + + it("should respect maxMessages limit", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + maxMessages: 5, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Make multiple requests to exceed the limit + for (let i = 0; i < 10; i++) { + await client.listAllTools(); + } + + expect(client.getMessages().length).toBeLessThanOrEqual(5); + }); + + it("should emit message events", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + const messageEvents: MessageEntry[] = []; + client.addEventListener("message", (event) => { + messageEvents.push(event.detail); + }); + + await client.connect(); + await client.listAllTools(); + + expect(messageEvents.length).toBeGreaterThan(0); + }); + + it("should emit messagesChange events", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + let changeCount = 0; + client.addEventListener("messagesChange", () => { + changeCount++; + }); + + await client.connect(); + await client.listAllTools(); + + expect(changeCount).toBeGreaterThan(0); + }); + }); + + describe("Fetch Request Tracking", () => { + it("should track HTTP requests for SSE transport", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "sse", + }); + + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + await client.listAllTools(); + + const fetchRequests = client.getFetchRequests(); + expect(fetchRequests.length).toBeGreaterThan(0); + const request = fetchRequests[0]; + expect(request).toBeDefined(); + if (request) { + expect(request.url).toContain("/sse"); + expect(request.method).toBe("GET"); + expect(request.category).toBe("transport"); + } + }); + + it("should track HTTP requests for streamable-http transport", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + await server.start(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + await client.listAllTools(); + + const fetchRequests = client.getFetchRequests(); + expect(fetchRequests.length).toBeGreaterThan(0); + const request = fetchRequests[0]; + expect(request).toBeDefined(); + if (request) { + expect(request.url).toContain("/mcp"); + expect(request.method).toBe("POST"); + expect(request.category).toBe("transport"); + } + }); + + it("should track request and response details", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + await server.start(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + await client.listAllTools(); + + const fetchRequests = client.getFetchRequests(); + expect(fetchRequests.length).toBeGreaterThan(0); + // Find a request that has response details (not just the initial connection) + const request = fetchRequests.find((r) => r.responseStatus !== undefined); + expect(request).toBeDefined(); + if (request) { + expect(request.requestHeaders).toBeDefined(); + expect(request.responseStatus).toBeDefined(); + expect(request.responseHeaders).toBeDefined(); + expect(request.duration).toBeDefined(); + expect(request.category).toBe("transport"); + } + }); + + it("should respect maxFetchRequests limit", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + await server.start(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + maxFetchRequests: 3, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Make multiple requests to exceed the limit + for (let i = 0; i < 10; i++) { + await client.listAllTools(); + } + + expect(client.getFetchRequests().length).toBeLessThanOrEqual(3); + }); + + it("should emit fetchRequest events", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + await server.start(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + const fetchRequestEvents: any[] = []; + client.addEventListener("fetchRequest", (event) => { + fetchRequestEvents.push(event.detail); + }); + + await client.connect(); + await client.listAllTools(); + + expect(fetchRequestEvents.length).toBeGreaterThan(0); + }); + + it("should emit fetchRequestsChange events", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + + await server.start(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + let changeFired = false; + client.addEventListener("fetchRequestsChange", () => { + changeFired = true; + }); + + await client.connect(); + await client.listAllTools(); + + expect(changeFired).toBe(true); + }); + }); + + describe("Server Data Management", () => { + it("should auto-fetch server contents when enabled", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + expect(client.getTools().length).toBeGreaterThan(0); + expect(client.getCapabilities()).toBeDefined(); + expect(client.getServerInfo()).toBeDefined(); + }); + + it("should not auto-fetch server contents when disabled", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + expect(client.getTools().length).toBe(0); + }); + + it("should emit toolsChange event", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + const toolsEvents: any[][] = []; + client.addEventListener("toolsChange", (event) => { + toolsEvents.push(event.detail); + }); + + await client.connect(); + + expect(toolsEvents.length).toBeGreaterThan(0); + expect(toolsEvents[0]?.length).toBeGreaterThan(0); + }); + }); + + describe("Tool Methods", () => { + beforeEach(async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + }); + + it("should list tools", async () => { + const tools = await client.listAllTools(); + expect(Array.isArray(tools)).toBe(true); + expect(tools.length).toBeGreaterThan(0); + }); + + it("should call tool with string arguments", async () => { + const result = await client.callTool("echo", { + message: "hello world", + }); + + expect(result).toHaveProperty("result"); + expect(result.success).toBe(true); + expect(result.result).toHaveProperty("content"); + const content = result.result!.content as any[]; + expect(Array.isArray(content)).toBe(true); + expect(content[0]).toHaveProperty("type", "text"); + expect(content[0].text).toContain("hello world"); + }); + + it("should call tool with number arguments", async () => { + const result = await client.callTool("get-sum", { + a: 42, + b: 58, + }); + expect(result.success).toBe(true); + + expect(result.result).toHaveProperty("content"); + const content = result.result!.content as any[]; + const resultData = JSON.parse(content[0].text); + expect(resultData.result).toBe(100); + }); + + it("should call tool with boolean arguments", async () => { + const result = await client.callTool("get-annotated-message", { + messageType: "success", + includeImage: true, + }); + + expect(result.result).toHaveProperty("content"); + const content = result.result!.content as any[]; + expect(content.length).toBeGreaterThan(1); + const hasImage = content.some((item: any) => item.type === "image"); + expect(hasImage).toBe(true); + }); + + it("should handle tool not found", async () => { + const result = await client.callTool("nonexistent-tool", {}); + // When tool is not found, the SDK returns an error response, not an exception + expect(result.success).toBe(true); // SDK returns error in result, not as exception + expect(result.result).toHaveProperty("isError", true); + expect(result.result).toBeDefined(); + if (result.result) { + expect(result.result).toHaveProperty("content"); + const content = result.result.content as any[]; + expect(content[0]).toHaveProperty("text"); + expect(content[0].text).toContain("not found"); + } + }); + + it("should paginate tools when maxPageSize is set", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 10 tools and page size of 3 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: createNumberedTools(10), + maxPageSize: { + tools: 3, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First page should have 3 tools + const page1 = await client.listTools(); + expect(page1.tools.length).toBe(3); + expect(page1.nextCursor).toBeDefined(); + expect(page1.tools[0]?.name).toBe("tool-1"); + expect(page1.tools[1]?.name).toBe("tool-2"); + expect(page1.tools[2]?.name).toBe("tool-3"); + + // Second page should have 3 more tools + const page2 = await client.listTools(page1.nextCursor); + expect(page2.tools.length).toBe(3); + expect(page2.nextCursor).toBeDefined(); + expect(page2.tools[0]?.name).toBe("tool-4"); + expect(page2.tools[1]?.name).toBe("tool-5"); + expect(page2.tools[2]?.name).toBe("tool-6"); + + // Third page should have 3 more tools + const page3 = await client.listTools(page2.nextCursor); + expect(page3.tools.length).toBe(3); + expect(page3.nextCursor).toBeDefined(); + expect(page3.tools[0]?.name).toBe("tool-7"); + expect(page3.tools[1]?.name).toBe("tool-8"); + expect(page3.tools[2]?.name).toBe("tool-9"); + + // Fourth page should have 1 tool and no next cursor + const page4 = await client.listTools(page3.nextCursor); + expect(page4.tools.length).toBe(1); + expect(page4.nextCursor).toBeUndefined(); + expect(page4.tools[0]?.name).toBe("tool-10"); + + // listAllTools should get all 10 tools + const allTools = await client.listAllTools(); + expect(allTools.length).toBe(10); + }); + + it("should suppress events during listAllTools pagination and emit final event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: createNumberedTools(6), + maxPageSize: { + tools: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"toolsChange">[] = []; + client.addEventListener("toolsChange", (e) => { + events.push(e); + }); + + // listAllTools should suppress events during pagination and emit one final event + await client.listAllTools(); + expect(client.getTools().length).toBe(6); + // Should only emit one event (final), not one per page + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(6); + }); + + it("should accumulate tools when paginating with cursor", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 6 tools and page size of 2 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: createNumberedTools(6), + maxPageSize: { + tools: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Initially empty + expect(client.getTools().length).toBe(0); + + // First page (no cursor) - should clear and load 2 tools + const page1 = await client.listTools(); + expect(page1.tools.length).toBe(2); + expect(client.getTools().length).toBe(2); + expect(client.getTools()[0]?.name).toBe("tool-1"); + expect(client.getTools()[1]?.name).toBe("tool-2"); + + // Second page (with cursor) - should append 2 more tools + const page2 = await client.listTools(page1.nextCursor); + expect(page2.tools.length).toBe(2); + expect(client.getTools().length).toBe(4); + expect(client.getTools()[2]?.name).toBe("tool-3"); + expect(client.getTools()[3]?.name).toBe("tool-4"); + + // Third page (with cursor) - should append 2 more tools + const page3 = await client.listTools(page2.nextCursor); + expect(page3.tools.length).toBe(2); + expect(client.getTools().length).toBe(6); + expect(client.getTools()[4]?.name).toBe("tool-5"); + expect(client.getTools()[5]?.name).toBe("tool-6"); + + // Calling without cursor again should reset + const page1Again = await client.listTools(); + expect(page1Again.tools.length).toBe(2); + expect(client.getTools().length).toBe(2); + expect(client.getTools()[0]?.name).toBe("tool-1"); + }); + + it("should emit toolsChange events when paginating", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: createNumberedTools(6), + maxPageSize: { + tools: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"toolsChange">[] = []; + client.addEventListener("toolsChange", (e) => { + events.push(e); + }); + + // First page should emit event + const page1 = await client.listTools(); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(2); + + // Second page should emit event (with cursor, appends) + await client.listTools(page1.nextCursor); + expect(events.length).toBe(2); + expect(events[1]!.detail.length).toBe(4); + }); + + it("should clear tools and emit event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: createNumberedTools(3), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Load some tools + await client.listAllTools(); + expect(client.getTools().length).toBe(3); + + const events: TypedEvent<"toolsChange">[] = []; + client.addEventListener("toolsChange", (e) => { + events.push(e); + }); + + // Clear should emit event and empty the list + client.clearTools(); + expect(client.getTools().length).toBe(0); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(0); + }); + }); + + describe("Resource Methods", () => { + beforeEach(async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + }); + + it("should list resources", async () => { + const resources = await client.listAllResources(); + expect(Array.isArray(resources)).toBe(true); + }); + + it("should read resource", async () => { + // First get list of resources + const resources = await client.listAllResources(); + if (resources.length > 0) { + const uri = resources[0]!.uri; + const readResult = await client.readResource(uri); + expect(readResult).toHaveProperty("result"); + expect(readResult.result).toHaveProperty("contents"); + } + }); + + it("should paginate resources when maxPageSize is set", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 10 resources and page size of 3 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: createNumberedResources(10), + maxPageSize: { + resources: 3, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First page should have 3 resources + const page1 = await client.listResources(); + expect(page1.resources.length).toBe(3); + expect(page1.nextCursor).toBeDefined(); + expect(page1.resources[0]?.uri).toBe("test://resource-1"); + expect(page1.resources[1]?.uri).toBe("test://resource-2"); + expect(page1.resources[2]?.uri).toBe("test://resource-3"); + + // Second page should have 3 more resources + const page2 = await client.listResources(page1.nextCursor); + expect(page2.resources.length).toBe(3); + expect(page2.nextCursor).toBeDefined(); + expect(page2.resources[0]?.uri).toBe("test://resource-4"); + expect(page2.resources[1]?.uri).toBe("test://resource-5"); + expect(page2.resources[2]?.uri).toBe("test://resource-6"); + + // Third page should have 3 more resources + const page3 = await client.listResources(page2.nextCursor); + expect(page3.resources.length).toBe(3); + expect(page3.nextCursor).toBeDefined(); + expect(page3.resources[0]?.uri).toBe("test://resource-7"); + expect(page3.resources[1]?.uri).toBe("test://resource-8"); + expect(page3.resources[2]?.uri).toBe("test://resource-9"); + + // Fourth page should have 1 resource and no next cursor + const page4 = await client.listResources(page3.nextCursor); + expect(page4.resources.length).toBe(1); + expect(page4.nextCursor).toBeUndefined(); + expect(page4.resources[0]?.uri).toBe("test://resource-10"); + + // listAllResources should get all 10 resources + const allResources = await client.listAllResources(); + expect(allResources.length).toBe(10); + }); + + it("should suppress events during listAllResources pagination and emit final event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: createNumberedResources(6), + maxPageSize: { + resources: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"resourcesChange">[] = []; + client.addEventListener("resourcesChange", (e) => { + events.push(e); + }); + + // listAllResources should suppress events during pagination and emit one final event + await client.listAllResources(); + expect(client.getResources().length).toBe(6); + // Should only emit one event (final), not one per page + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(6); + }); + + it("should accumulate resources when paginating with cursor", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 6 resources and page size of 2 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: createNumberedResources(6), + maxPageSize: { + resources: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Initially empty + expect(client.getResources().length).toBe(0); + + // First page (no cursor) - should clear and load 2 resources + const page1 = await client.listResources(); + expect(page1.resources.length).toBe(2); + expect(client.getResources().length).toBe(2); + expect(client.getResources()[0]?.uri).toBe("test://resource-1"); + expect(client.getResources()[1]?.uri).toBe("test://resource-2"); + + // Second page (with cursor) - should append 2 more resources + const page2 = await client.listResources(page1.nextCursor); + expect(page2.resources.length).toBe(2); + expect(client.getResources().length).toBe(4); + expect(client.getResources()[2]?.uri).toBe("test://resource-3"); + expect(client.getResources()[3]?.uri).toBe("test://resource-4"); + + // Third page (with cursor) - should append 2 more resources + const page3 = await client.listResources(page2.nextCursor); + expect(page3.resources.length).toBe(2); + expect(client.getResources().length).toBe(6); + expect(client.getResources()[4]?.uri).toBe("test://resource-5"); + expect(client.getResources()[5]?.uri).toBe("test://resource-6"); + + // Calling without cursor again should reset + const page1Again = await client.listResources(); + expect(page1Again.resources.length).toBe(2); + expect(client.getResources().length).toBe(2); + expect(client.getResources()[0]?.uri).toBe("test://resource-1"); + }); + + it("should emit resourcesChange events when paginating", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: createNumberedResources(6), + maxPageSize: { + resources: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"resourcesChange">[] = []; + client.addEventListener("resourcesChange", (e) => { + events.push(e); + }); + + // First page should emit event + const page1 = await client.listResources(); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(2); + + // Second page should emit event (with cursor, appends) + await client.listResources(page1.nextCursor); + expect(events.length).toBe(2); + expect(events[1]!.detail.length).toBe(4); + }); + + it("should not emit events when suppressEvents is true", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: createNumberedResources(6), + maxPageSize: { + resources: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"resourcesChange">[] = []; + client.addEventListener("resourcesChange", (e) => { + events.push(e); + }); + + // Suppress events - should update state but not emit + await client.listResources(undefined, undefined, true); + expect(client.getResources().length).toBe(2); + expect(events.length).toBe(0); + + // Normal call should emit + await client.listResources(); + expect(events.length).toBe(1); + }); + + it("should clear resources and emit event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: createNumberedResources(3), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Load some resources + await client.listAllResources(); + expect(client.getResources().length).toBe(3); + + const events: TypedEvent<"resourcesChange">[] = []; + client.addEventListener("resourcesChange", (e) => { + events.push(e); + }); + + // Clear should emit event and empty the list + client.clearResources(); + expect(client.getResources().length).toBe(0); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(0); + }); + }); + + describe("Resource Template Methods", () => { + beforeEach(async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [createFileResourceTemplate()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + }); + + it("should list resource templates", async () => { + const resourceTemplates = await client.listAllResourceTemplates(); + expect(Array.isArray(resourceTemplates)).toBe(true); + expect(resourceTemplates.length).toBeGreaterThan(0); + + const templates = resourceTemplates; + const fileTemplate = templates.find((t) => t.name === "file"); + expect(fileTemplate).toBeDefined(); + expect(fileTemplate?.uriTemplate).toBe("file:///{path}"); + }); + + it("should read resource from template", async () => { + // First get the template + const templates = await client.listAllResourceTemplates(); + const fileTemplate = templates.find((t) => t.name === "file"); + expect(fileTemplate).toBeDefined(); + + // Use a URI that matches the template pattern file:///{path} + // The path variable will be "test.txt" + const expandedUri = "file:///test.txt"; + + // Read the resource using the expanded URI + const readResult = await client.readResource(expandedUri); + expect(readResult).toHaveProperty("result"); + expect(readResult.result).toHaveProperty("contents"); + const contents = readResult.result.contents; + expect(Array.isArray(contents)).toBe(true); + expect(contents.length).toBeGreaterThan(0); + + const content = contents[0]; + expect(content).toHaveProperty("uri"); + if (content && "text" in content) { + expect(content.text).toContain("Mock file content for: test.txt"); + } + }); + + it("should include resources from template list callback in listResources", async () => { + // Create a server with a resource template that has a list callback + const listCallback = async () => { + return ["file:///file1.txt", "file:///file2.txt", "file:///file3.txt"]; + }; + + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [ + createFileResourceTemplate(undefined, listCallback), + ], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Call listResources - this should include resources from the template's list callback + const resources = await client.listAllResources(); + expect(Array.isArray(resources)).toBe(true); + + // Verify that the resources from the list callback are included + const uris = resources.map((r) => r.uri); + expect(uris).toContain("file:///file1.txt"); + expect(uris).toContain("file:///file2.txt"); + expect(uris).toContain("file:///file3.txt"); + }); + + it("should paginate resource templates when maxPageSize is set", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 10 resource templates and page size of 3 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: createNumberedResourceTemplates(10), + maxPageSize: { + resourceTemplates: 3, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First page should have 3 templates + const page1 = await client.listResourceTemplates(); + expect(page1.resourceTemplates.length).toBe(3); + expect(page1.nextCursor).toBeDefined(); + expect(page1.resourceTemplates[0]?.uriTemplate).toBe( + "test://template-1/{param}", + ); + expect(page1.resourceTemplates[1]?.uriTemplate).toBe( + "test://template-2/{param}", + ); + expect(page1.resourceTemplates[2]?.uriTemplate).toBe( + "test://template-3/{param}", + ); + + // Second page should have 3 more templates + const page2 = await client.listResourceTemplates(page1.nextCursor); + expect(page2.resourceTemplates.length).toBe(3); + expect(page2.nextCursor).toBeDefined(); + expect(page2.resourceTemplates[0]?.uriTemplate).toBe( + "test://template-4/{param}", + ); + expect(page2.resourceTemplates[1]?.uriTemplate).toBe( + "test://template-5/{param}", + ); + expect(page2.resourceTemplates[2]?.uriTemplate).toBe( + "test://template-6/{param}", + ); + + // Third page should have 3 more templates + const page3 = await client.listResourceTemplates(page2.nextCursor); + expect(page3.resourceTemplates.length).toBe(3); + expect(page3.nextCursor).toBeDefined(); + expect(page3.resourceTemplates[0]?.uriTemplate).toBe( + "test://template-7/{param}", + ); + expect(page3.resourceTemplates[1]?.uriTemplate).toBe( + "test://template-8/{param}", + ); + expect(page3.resourceTemplates[2]?.uriTemplate).toBe( + "test://template-9/{param}", + ); + + // Fourth page should have 1 template and no next cursor + const page4 = await client.listResourceTemplates(page3.nextCursor); + expect(page4.resourceTemplates.length).toBe(1); + expect(page4.nextCursor).toBeUndefined(); + expect(page4.resourceTemplates[0]?.uriTemplate).toBe( + "test://template-10/{param}", + ); + + // listAllResourceTemplates should get all 10 templates + const allTemplates = await client.listAllResourceTemplates(); + expect(allTemplates.length).toBe(10); + }); + + it("should accumulate resource templates when paginating with cursor", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 6 templates and page size of 2 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: createNumberedResourceTemplates(6), + maxPageSize: { + resourceTemplates: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Initially empty + expect(client.getResourceTemplates().length).toBe(0); + + // First page (no cursor) - should clear and load 2 templates + const page1 = await client.listResourceTemplates(); + expect(page1.resourceTemplates.length).toBe(2); + expect(client.getResourceTemplates().length).toBe(2); + expect(client.getResourceTemplates()[0]?.uriTemplate).toBe( + "test://template-1/{param}", + ); + expect(client.getResourceTemplates()[1]?.uriTemplate).toBe( + "test://template-2/{param}", + ); + + // Second page (with cursor) - should append 2 more templates + const page2 = await client.listResourceTemplates(page1.nextCursor); + expect(page2.resourceTemplates.length).toBe(2); + expect(client.getResourceTemplates().length).toBe(4); + expect(client.getResourceTemplates()[2]?.uriTemplate).toBe( + "test://template-3/{param}", + ); + expect(client.getResourceTemplates()[3]?.uriTemplate).toBe( + "test://template-4/{param}", + ); + + // Third page (with cursor) - should append 2 more templates + const page3 = await client.listResourceTemplates(page2.nextCursor); + expect(page3.resourceTemplates.length).toBe(2); + expect(client.getResourceTemplates().length).toBe(6); + expect(client.getResourceTemplates()[4]?.uriTemplate).toBe( + "test://template-5/{param}", + ); + expect(client.getResourceTemplates()[5]?.uriTemplate).toBe( + "test://template-6/{param}", + ); + + // Calling without cursor again should reset + const page1Again = await client.listResourceTemplates(); + expect(page1Again.resourceTemplates.length).toBe(2); + expect(client.getResourceTemplates().length).toBe(2); + expect(client.getResourceTemplates()[0]?.uriTemplate).toBe( + "test://template-1/{param}", + ); + }); + + it("should clear resource templates and emit event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: createNumberedResourceTemplates(3), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Load some templates + await client.listAllResourceTemplates(); + expect(client.getResourceTemplates().length).toBe(3); + + const events: TypedEvent<"resourceTemplatesChange">[] = []; + client.addEventListener("resourceTemplatesChange", (e) => { + events.push(e); + }); + + // Clear should emit event and empty the list + client.clearResourceTemplates(); + expect(client.getResourceTemplates().length).toBe(0); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(0); + }); + }); + + describe("Prompt Methods", () => { + beforeEach(async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + }); + + it("should list prompts", async () => { + const prompts = await client.listAllPrompts(); + expect(Array.isArray(prompts)).toBe(true); + }); + + it("should paginate prompts when maxPageSize is set", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 10 prompts and page size of 3 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: createNumberedPrompts(10), + maxPageSize: { + prompts: 3, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First page should have 3 prompts + const page1 = await client.listPrompts(); + expect(page1.prompts.length).toBe(3); + expect(page1.nextCursor).toBeDefined(); + expect(page1.prompts[0]?.name).toBe("prompt-1"); + expect(page1.prompts[1]?.name).toBe("prompt-2"); + expect(page1.prompts[2]?.name).toBe("prompt-3"); + + // Second page should have 3 more prompts + const page2 = await client.listPrompts(page1.nextCursor); + expect(page2.prompts.length).toBe(3); + expect(page2.nextCursor).toBeDefined(); + expect(page2.prompts[0]?.name).toBe("prompt-4"); + expect(page2.prompts[1]?.name).toBe("prompt-5"); + expect(page2.prompts[2]?.name).toBe("prompt-6"); + + // Third page should have 3 more prompts + const page3 = await client.listPrompts(page2.nextCursor); + expect(page3.prompts.length).toBe(3); + expect(page3.nextCursor).toBeDefined(); + expect(page3.prompts[0]?.name).toBe("prompt-7"); + expect(page3.prompts[1]?.name).toBe("prompt-8"); + expect(page3.prompts[2]?.name).toBe("prompt-9"); + + // Fourth page should have 1 prompt and no next cursor + const page4 = await client.listPrompts(page3.nextCursor); + expect(page4.prompts.length).toBe(1); + expect(page4.nextCursor).toBeUndefined(); + expect(page4.prompts[0]?.name).toBe("prompt-10"); + + // listAllPrompts should get all 10 prompts + const allPrompts = await client.listAllPrompts(); + expect(allPrompts.length).toBe(10); + }); + + it("should suppress events during listAllPrompts pagination and emit final event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: createNumberedPrompts(6), + maxPageSize: { + prompts: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"promptsChange">[] = []; + client.addEventListener("promptsChange", (e) => { + events.push(e); + }); + + // listAllPrompts should suppress events during pagination and emit one final event + await client.listAllPrompts(); + expect(client.getPrompts().length).toBe(6); + // Should only emit one event (final), not one per page + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(6); + }); + + it("should accumulate prompts when paginating with cursor", async () => { + // Disconnect and create a new server with pagination + await client.disconnect(); + if (server) { + await server.stop(); + } + + // Create server with 6 prompts and page size of 2 + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: createNumberedPrompts(6), + maxPageSize: { + prompts: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Initially empty + expect(client.getPrompts().length).toBe(0); + + // First page (no cursor) - should clear and load 2 prompts + const page1 = await client.listPrompts(); + expect(page1.prompts.length).toBe(2); + expect(client.getPrompts().length).toBe(2); + expect(client.getPrompts()[0]?.name).toBe("prompt-1"); + expect(client.getPrompts()[1]?.name).toBe("prompt-2"); + + // Second page (with cursor) - should append 2 more prompts + const page2 = await client.listPrompts(page1.nextCursor); + expect(page2.prompts.length).toBe(2); + expect(client.getPrompts().length).toBe(4); + expect(client.getPrompts()[2]?.name).toBe("prompt-3"); + expect(client.getPrompts()[3]?.name).toBe("prompt-4"); + + // Third page (with cursor) - should append 2 more prompts + const page3 = await client.listPrompts(page2.nextCursor); + expect(page3.prompts.length).toBe(2); + expect(client.getPrompts().length).toBe(6); + expect(client.getPrompts()[4]?.name).toBe("prompt-5"); + expect(client.getPrompts()[5]?.name).toBe("prompt-6"); + + // Calling without cursor again should reset + const page1Again = await client.listPrompts(); + expect(page1Again.prompts.length).toBe(2); + expect(client.getPrompts().length).toBe(2); + expect(client.getPrompts()[0]?.name).toBe("prompt-1"); + }); + + it("should emit promptsChange events when paginating", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: createNumberedPrompts(6), + maxPageSize: { + prompts: 2, + }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const events: TypedEvent<"promptsChange">[] = []; + client.addEventListener("promptsChange", (e) => { + events.push(e); + }); + + // First page should emit event + const page1 = await client.listPrompts(); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(2); + + // Second page should emit event (with cursor, appends) + await client.listPrompts(page1.nextCursor); + expect(events.length).toBe(2); + expect(events[1]!.detail.length).toBe(4); + }); + + it("should clear prompts and emit event", async () => { + await client.disconnect(); + if (server) { + await server.stop(); + } + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: createNumberedPrompts(3), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Load some prompts + await client.listAllPrompts(); + expect(client.getPrompts().length).toBe(3); + + const events: TypedEvent<"promptsChange">[] = []; + client.addEventListener("promptsChange", (e) => { + events.push(e); + }); + + // Clear should emit event and empty the list + client.clearPrompts(); + expect(client.getPrompts().length).toBe(0); + expect(events.length).toBe(1); + expect(events[0]!.detail.length).toBe(0); + }); + }); + + describe("Progress Tracking", () => { + it("should dispatch progressNotification events when progress notifications are received", async () => { + const { createSendProgressTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendProgressTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + progress: true, + }, + ); + + await client.connect(); + + const progressToken = 12345; + + client.callTool( + "sendProgress", + { + units: 3, + delayMs: 50, + total: 3, + message: "Test progress", + }, + undefined, // generalMetadata + { progressToken: progressToken.toString() }, // toolSpecificMetadata + ); + + const progressEvents = await waitForProgressCount(client, 3, { + timeout: 3000, + }); + + expect(progressEvents.length).toBe(3); + expect(progressEvents[0]).toMatchObject({ + progress: 1, + total: 3, + message: "Test progress (1/3)", + progressToken: progressToken.toString(), + }); + + // Verify second progress event + expect(progressEvents[1]).toMatchObject({ + progress: 2, + total: 3, + message: "Test progress (2/3)", + progressToken: progressToken.toString(), + }); + + // Verify third progress event + expect(progressEvents[2]).toMatchObject({ + progress: 3, + total: 3, + message: "Test progress (3/3)", + progressToken: progressToken.toString(), + }); + + await client.disconnect(); + await server.stop(); + }); + + it("should not dispatch progressNotification events when progress is disabled", async () => { + const { createSendProgressTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendProgressTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + progress: false, // Disable progress + }, + ); + + await client.connect(); + + const progressEvents: any[] = []; + const progressListener = (event: TypedEvent<"progressNotification">) => { + progressEvents.push(event.detail); + }; + client.addEventListener("progressNotification", progressListener); + + const progressToken = 12345; + + // Call the tool with progressToken in metadata + await client.callTool( + "sendProgress", + { + units: 2, + delayMs: 50, + }, + undefined, // generalMetadata + { progressToken: progressToken.toString() }, // toolSpecificMetadata + ); + + // Observation window: we assert no progressNotification events; can't wait for a non-event. + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Remove listener + client.removeEventListener("progressNotification", progressListener); + + // Verify no progress events were received + expect(progressEvents.length).toBe(0); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle progress notifications without total", async () => { + const { createSendProgressTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendProgressTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + progress: true, + }, + ); + + await client.connect(); + + const progressToken = 67890; + + client.callTool( + "sendProgress", + { + units: 2, + delayMs: 50, + message: "Indeterminate progress", + }, + undefined, // generalMetadata + { progressToken: progressToken.toString() }, // toolSpecificMetadata + ); + + const progressEvents = await waitForProgressCount(client, 2, { + timeout: 3000, + }); + + expect(progressEvents.length).toBe(2); + expect(progressEvents[0]).toMatchObject({ + progress: 1, + message: "Indeterminate progress (1/2)", + progressToken: progressToken.toString(), + }); + expect((progressEvents[0] as { total?: number }).total).toBeUndefined(); + + expect(progressEvents[1]).toMatchObject({ + progress: 2, + message: "Indeterminate progress (2/2)", + progressToken: progressToken.toString(), + }); + expect((progressEvents[1] as { total?: number }).total).toBeUndefined(); + + await client.disconnect(); + await server.stop(); + }); + + it("should complete when timeout and resetTimeoutOnProgress are set (options passed through)", async () => { + const { createSendProgressTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendProgressTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + progress: true, + timeout: 2000, + resetTimeoutOnProgress: true, + }, + ); + + await client.connect(); + + const progressToken = 999; + const result = await client.callTool( + "sendProgress", + { units: 3, delayMs: 100, total: 3, message: "Timeout test" }, + undefined, + { progressToken: progressToken.toString() }, + ); + + expect(result.success).toBe(true); + expect((result.result as { content?: unknown[] }).content).toBeDefined(); + const text = ( + result.result as { content?: { type: string; text?: string }[] } + ).content?.find((c) => c.type === "text")?.text; + expect(text).toContain("Completed 3 progress notifications"); + + await client.disconnect(); + await server.stop(); + }); + + it("should not timeout when resetTimeoutOnProgress is true and progress is sent (reset extends timeout)", async () => { + const { createSendProgressTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendProgressTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + progress: true, + timeout: 350, + resetTimeoutOnProgress: true, + }, + ); + + await client.connect(); + + const result = await client.callTool( + "sendProgress", + { units: 4, delayMs: 200, total: 4, message: "Reset test" }, + undefined, + { progressToken: "reset-test" }, + ); + + expect(result.success).toBe(true); + expect((result.result as { content?: unknown[] }).content).toBeDefined(); + const text = ( + result.result as { content?: { type: string; text?: string }[] } + ).content?.find((c) => c.type === "text")?.text; + expect(text).toContain("Completed 4 progress notifications"); + + await client.disconnect(); + await server.stop(); + }); + + it("should timeout with RequestTimeout when resetTimeoutOnProgress is false and gap exceeds timeout", async () => { + const { createSendProgressTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendProgressTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + clientIdentity: { name: "test", version: "1.0.0" }, + autoSyncLists: false, + progress: true, + timeout: 150, + resetTimeoutOnProgress: false, + }, + ); + + await client.connect(); + + const progressToken = 888; + let err: unknown; + try { + await client.callTool( + "sendProgress", + { units: 4, delayMs: 200, total: 4, message: "Timeout test" }, + undefined, + { progressToken: progressToken.toString() }, + ); + } catch (e) { + err = e; + } + expect(err).toBeInstanceOf(McpError); + expect((err as McpError).code).toBe(ErrorCode.RequestTimeout); + + await client.disconnect(); + await server.stop(); + }); + }); + + describe("Logging", () => { + it("should set logging level when server supports it", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + initialLoggingLevel: "debug", + }, + ); + + await client.connect(); + + // If server supports logging, the level should be set + // We can't directly verify this, but it shouldn't throw + const capabilities = client.getCapabilities(); + if (capabilities?.logging) { + await client.setLoggingLevel("info"); + } + }); + + it("should track stderr logs for stdio transport", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + pipeStderr: true, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const testMessage = `stderr-direct-${Date.now()}`; + await client.callTool("writeToStderr", { message: testMessage }); + + const logs = client.getStderrLogs(); + expect(Array.isArray(logs)).toBe(true); + const matching = logs.filter((l) => l.message.includes(testMessage)); + expect(matching.length).toBeGreaterThan(0); + expect(matching[0]!.message).toContain(testMessage); + }); + }); + + describe("Events", () => { + it("should emit statusChange events", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + const statuses: ConnectionStatus[] = []; + client.addEventListener("statusChange", (event) => { + statuses.push(event.detail); + }); + + await client.connect(); + await client.disconnect(); + + expect(statuses).toContain("connecting"); + expect(statuses).toContain("connected"); + expect(statuses).toContain("disconnected"); + }); + + it("should emit connect event", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + let connectFired = false; + client.addEventListener("connect", () => { + connectFired = true; + }); + + await client.connect(); + expect(connectFired).toBe(true); + }); + + it("should emit disconnect event", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + let disconnectFired = false; + client.addEventListener("disconnect", () => { + disconnectFired = true; + }); + + await client.connect(); + await client.disconnect(); + expect(disconnectFired).toBe(true); + }); + }); + + describe("Sampling Requests", () => { + it("should handle sampling requests from server and respond", async () => { + // Create a test server with the collectSample tool + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createCollectSampleTool()], + serverType: "streamable-http", + }); + + await server.start(); + + // Create client with sampling enabled + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + sample: true, // Enable sampling capability + }, + ); + + await client.connect(); + + // Set up Promise to wait for sampling request event + const samplingRequestPromise = new Promise( + (resolve) => { + client.addEventListener( + "newPendingSample", + (event) => { + resolve(event.detail); + }, + { once: true }, + ); + }, + ); + + // Start the tool call (don't await yet - it will block until sampling is responded to) + const toolResultPromise = client.callTool("collectSample", { + text: "Hello, world!", + }); + + // Wait for the sampling request to arrive via event + const pendingSample = await samplingRequestPromise; + + // Verify we received a sampling request + expect(pendingSample.request.method).toBe("sampling/createMessage"); + const messages = pendingSample.request.params.messages; + expect(messages.length).toBeGreaterThan(0); + const firstMessage = messages[0]; + expect(firstMessage).toBeDefined(); + if ( + firstMessage && + firstMessage.content && + typeof firstMessage.content === "object" && + "text" in firstMessage.content + ) { + expect((firstMessage.content as { text: string }).text).toBe( + "Hello, world!", + ); + } + + // Respond to the sampling request + const samplingResponse: CreateMessageResult = { + model: "test-model", + role: "assistant", + stopReason: "endTurn", + content: { + type: "text", + text: "This is a test response", + }, + }; + + await pendingSample.respond(samplingResponse); + + // Now await the tool result (it should complete now that we've responded) + const toolResult = await toolResultPromise; + + // Verify the tool result contains the sampling response + expect(toolResult).toBeDefined(); + expect(toolResult.success).toBe(true); + expect(toolResult.result).toBeDefined(); + expect(toolResult.result!.content).toBeDefined(); + expect(Array.isArray(toolResult.result!.content)).toBe(true); + const toolContent = toolResult.result!.content as any[]; + expect(toolContent.length).toBeGreaterThan(0); + const toolMessage = toolContent[0]; + expect(toolMessage).toBeDefined(); + expect(toolMessage.type).toBe("text"); + if (toolMessage.type === "text") { + expect(toolMessage.text).toContain("Sampling response:"); + expect(toolMessage.text).toContain("test-model"); + expect(toolMessage.text).toContain("This is a test response"); + } + + // Verify the pending sample was removed + const pendingSamples = client.getPendingSamples(); + expect(pendingSamples.length).toBe(0); + }); + }); + + describe("Server-Initiated Notifications", () => { + it("should receive server-initiated notifications via stdio transport", async () => { + // Note: stdio test server uses getDefaultServerConfig which now includes sendNotification tool + // Create client with stdio transport + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Set up Promise to wait for notification + const notificationPromise = new Promise((resolve) => { + client.addEventListener("message", (event) => { + const entry = event.detail; + if (entry.direction === "notification") { + resolve(entry); + } + }); + }); + + // Call the sendNotification tool + await client.callTool("sendNotification", { + message: "Test notification from stdio", + level: "info", + }); + + // Wait for the notification + const notificationEntry = await notificationPromise; + + // Validate the notification + expect(notificationEntry).toBeDefined(); + expect(notificationEntry.direction).toBe("notification"); + if ("method" in notificationEntry.message) { + expect(notificationEntry.message.method).toBe("notifications/message"); + if ("params" in notificationEntry.message) { + const params = notificationEntry.message.params as any; + expect(params.data.message).toBe("Test notification from stdio"); + expect(params.level).toBe("info"); + expect(params.logger).toBe("test-server"); + } + } + }); + + it("should receive server-initiated notifications via SSE transport", async () => { + // Create a test server with the sendNotification tool and logging enabled + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendNotificationTool()], + serverType: "sse", + logging: true, // Required for notifications/message + }); + + await server.start(); + + // Create client with SSE transport + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Set up Promise to wait for notification + const notificationPromise = new Promise((resolve) => { + client.addEventListener("message", (event) => { + const entry = event.detail; + if (entry.direction === "notification") { + resolve(entry); + } + }); + }); + + // Call the sendNotification tool + await client.callTool("sendNotification", { + message: "Test notification from SSE", + level: "warning", + }); + + // Wait for the notification + const notificationEntry = await notificationPromise; + + // Validate the notification + expect(notificationEntry).toBeDefined(); + expect(notificationEntry.direction).toBe("notification"); + if ("method" in notificationEntry.message) { + expect(notificationEntry.message.method).toBe("notifications/message"); + if ("params" in notificationEntry.message) { + const params = notificationEntry.message.params as any; + expect(params.data.message).toBe("Test notification from SSE"); + expect(params.level).toBe("warning"); + expect(params.logger).toBe("test-server"); + } + } + }); + + it("should receive server-initiated notifications via streamable-http transport", async () => { + // Create a test server with the sendNotification tool and logging enabled + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createSendNotificationTool()], + serverType: "streamable-http", + logging: true, // Required for notifications/message + }); + + await server.start(); + + // Create client with streamable-http transport + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Set up Promise to wait for notification + const notificationPromise = new Promise((resolve) => { + client.addEventListener("message", (event) => { + const entry = event.detail; + if (entry.direction === "notification") { + resolve(entry); + } + }); + }); + + // Call the sendNotification tool + await client.callTool("sendNotification", { + message: "Test notification from streamable-http", + level: "error", + }); + + // Wait for the notification + const notificationEntry = await notificationPromise; + + // Validate the notification + expect(notificationEntry).toBeDefined(); + expect(notificationEntry.direction).toBe("notification"); + if ("method" in notificationEntry.message) { + expect(notificationEntry.message.method).toBe("notifications/message"); + if ("params" in notificationEntry.message) { + const params = notificationEntry.message.params as any; + expect(params.data.message).toBe( + "Test notification from streamable-http", + ); + expect(params.level).toBe("error"); + expect(params.logger).toBe("test-server"); + } + } + }); + }); + + describe("Elicitation Requests", () => { + it("should handle form-based elicitation requests from server and respond", async () => { + // Create a test server with the collectElicitation tool + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createCollectFormElicitationTool()], + serverType: "streamable-http", + }); + + await server.start(); + + // Create client with elicitation enabled + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + elicit: true, // Enable elicitation capability + }, + ); + + await client.connect(); + + // Set up Promise to wait for elicitation request event + const elicitationRequestPromise = new Promise( + (resolve) => { + client.addEventListener( + "newPendingElicitation", + (event) => { + resolve(event.detail); + }, + { once: true }, + ); + }, + ); + + // Start the tool call (don't await yet - it will block until elicitation is responded to) + const toolResultPromise = client.callTool("collectElicitation", { + message: "Please provide your name", + schema: { + type: "object", + properties: { + name: { + type: "string", + description: "Your name", + }, + }, + required: ["name"], + }, + }); + + // Wait for the elicitation request to arrive via event + const pendingElicitation = await elicitationRequestPromise; + + // Verify we received an elicitation request + expect(pendingElicitation.request.method).toBe("elicitation/create"); + expect(pendingElicitation.request.params.message).toBe( + "Please provide your name", + ); + if ("requestedSchema" in pendingElicitation.request.params) { + expect(pendingElicitation.request.params.requestedSchema).toBeDefined(); + expect(pendingElicitation.request.params.requestedSchema.type).toBe( + "object", + ); + } + + // Respond to the elicitation request + const elicitationResponse: ElicitResult = { + action: "accept", + content: { + name: "Test User", + }, + }; + + await pendingElicitation.respond(elicitationResponse); + + // Now await the tool result (it should complete now that we've responded) + const toolResult = await toolResultPromise; + + // Verify the tool result contains the elicitation response + expect(toolResult).toBeDefined(); + expect(toolResult.success).toBe(true); + expect(toolResult.result).toBeDefined(); + expect(toolResult.result!.content).toBeDefined(); + expect(Array.isArray(toolResult.result!.content)).toBe(true); + const toolContent = toolResult.result!.content as any[]; + expect(toolContent.length).toBeGreaterThan(0); + const toolMessage = toolContent[0]; + expect(toolMessage).toBeDefined(); + expect(toolMessage.type).toBe("text"); + if (toolMessage.type === "text") { + expect(toolMessage.text).toContain("Elicitation response:"); + expect(toolMessage.text).toContain("accept"); + expect(toolMessage.text).toContain("Test User"); + } + + // Verify the pending elicitation was removed + const pendingElicitations = client.getPendingElicitations(); + expect(pendingElicitations.length).toBe(0); + }); + + it("should handle URL-based elicitation requests from server and respond", async () => { + // Create a test server with the collectUrlElicitation tool + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createCollectUrlElicitationTool()], + serverType: "streamable-http", + }); + + await server.start(); + + // Create client with elicitation enabled + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + elicit: { url: true }, // Enable elicitation capability + }, + ); + + await client.connect(); + + // Set up Promise to wait for elicitation request event + const elicitationRequestPromise = new Promise( + (resolve) => { + client.addEventListener( + "newPendingElicitation", + (event) => { + resolve(event.detail); + }, + { once: true }, + ); + }, + ); + + // Start the tool call (don't await yet - it will block until elicitation is responded to) + const toolResultPromise = client.callTool("collectUrlElicitation", { + message: "Please visit the URL to complete authentication", + url: "https://example.com/auth", + elicitationId: "test-url-elicitation-123", + }); + + // Wait for the elicitation request to arrive via event + const pendingElicitation = await elicitationRequestPromise; + + // Verify we received a URL-based elicitation request + expect(pendingElicitation.request.method).toBe("elicitation/create"); + expect(pendingElicitation.request.params.message).toBe( + "Please visit the URL to complete authentication", + ); + expect(pendingElicitation.request.params.mode).toBe("url"); + if (pendingElicitation.request.params.mode === "url") { + expect(pendingElicitation.request.params.url).toBe( + "https://example.com/auth", + ); + expect(pendingElicitation.request.params.elicitationId).toBe( + "test-url-elicitation-123", + ); + } + + // Respond to the URL-based elicitation request + const elicitationResponse: ElicitResult = { + action: "accept", + content: { + // URL-based elicitation typically doesn't have form data, but we can include metadata + completed: true, + }, + }; + + await pendingElicitation.respond(elicitationResponse); + + // Now await the tool result (it should complete now that we've responded) + const toolResult = await toolResultPromise; + + // Verify the tool result contains the elicitation response + expect(toolResult).toBeDefined(); + expect(toolResult.success).toBe(true); + expect(toolResult.result).toBeDefined(); + expect(toolResult.result!.content).toBeDefined(); + expect(Array.isArray(toolResult.result!.content)).toBe(true); + const toolContent = toolResult.result!.content as any[]; + expect(toolContent.length).toBeGreaterThan(0); + const toolMessage = toolContent[0]; + expect(toolMessage).toBeDefined(); + expect(toolMessage.type).toBe("text"); + if (toolMessage.type === "text") { + expect(toolMessage.text).toContain("URL elicitation response:"); + expect(toolMessage.text).toContain("accept"); + } + + // Verify the pending elicitation was removed + const pendingElicitations = client.getPendingElicitations(); + expect(pendingElicitations.length).toBe(0); + }); + }); + + describe("Roots Support", () => { + it("should handle roots/list request from server and return roots", async () => { + // Create a test server with the listRoots tool + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createListRootsTool()], + serverType: "streamable-http", + }); + + await server.start(); + + // Create client with roots enabled + const initialRoots = [ + { uri: "file:///test1", name: "Test Root 1" }, + { uri: "file:///test2", name: "Test Root 2" }, + ]; + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + roots: initialRoots, // Enable roots capability + }, + ); + + await client.connect(); + + // Call the listRoots tool - it will call roots/list on the client + const toolResult = await client.callTool("listRoots", {}); + + // Verify the tool result contains the roots + expect(toolResult).toBeDefined(); + expect(toolResult.success).toBe(true); + expect(toolResult.result).toBeDefined(); + expect(toolResult.result!.content).toBeDefined(); + expect(Array.isArray(toolResult.result!.content)).toBe(true); + const toolContent = toolResult.result!.content as any[]; + expect(toolContent.length).toBeGreaterThan(0); + const toolMessage = toolContent[0]; + expect(toolMessage).toBeDefined(); + expect(toolMessage.type).toBe("text"); + if (toolMessage.type === "text") { + expect(toolMessage.text).toContain("Roots:"); + expect(toolMessage.text).toContain("file:///test1"); + expect(toolMessage.text).toContain("file:///test2"); + } + + // Verify getRoots() returns the roots + const roots = client.getRoots(); + expect(roots).toEqual(initialRoots); + + await client.disconnect(); + await server.stop(); + }); + + it("should send roots/list_changed notification when roots are updated", async () => { + // Create a test server - clients can send roots/list_changed notifications to any server + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + serverType: "streamable-http", + }); + + await server.start(); + + // Create client with roots enabled + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + roots: [], // Enable roots capability with empty array + }, + ); + + await client.connect(); + + // Clear any recorded requests from connection + server.clearRecordings(); + + // Update roots + const newRoots = [ + { uri: "file:///new1", name: "New Root 1" }, + { uri: "file:///new2", name: "New Root 2" }, + ]; + await client.setRoots(newRoots); + + const rootsChangedNotification = await server.waitUntilRecorded( + (req) => req.method === "notifications/roots/list_changed", + { timeout: 5000, interval: 10 }, + ); + + expect(rootsChangedNotification.method).toBe( + "notifications/roots/list_changed", + ); + + // Verify getRoots() returns the new roots + const roots = client.getRoots(); + expect(roots).toEqual(newRoots); + + // Verify rootsChange event was dispatched + const rootsChangePromise = new Promise((resolve) => { + client.addEventListener( + "rootsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + await client.setRoots([{ uri: "file:///updated", name: "Updated" }]); + + const rootsChangeEvent = await rootsChangePromise; + expect(rootsChangeEvent.detail).toEqual([ + { uri: "file:///updated", name: "Updated" }, + ]); + + // Verify another notification was sent + const updatedRequests = server.getRecordedRequests(); + const secondNotification = updatedRequests.filter( + (req) => req.method === "notifications/roots/list_changed", + ); + expect(secondNotification.length).toBeGreaterThanOrEqual(1); + + await client.disconnect(); + await server.stop(); + }); + }); + + describe("Completions", () => { + it("should get completions for resource template variable", async () => { + // Create a test server with a resource template that has completion support + const completionCallback = (argName: string, value: string): string[] => { + if (argName === "path") { + const files = ["file1.txt", "file2.txt", "file3.txt"]; + return files.filter((f) => f.startsWith(value)); + } + return []; + }; + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [createFileResourceTemplate(completionCallback)], + }); + + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Request completions for "file" variable with partial value "file1" + const result = await client.getCompletions( + { type: "ref/resource", uri: "file:///{path}" }, + "path", + "file1", + ); + + expect(result.values).toContain("file1.txt"); + expect(result.values.length).toBeGreaterThan(0); + + await client.disconnect(); + await server.stop(); + }); + + it("should get completions for prompt argument", async () => { + // Create a test server with a prompt that has completion support + const cityCompletions = ( + value: string, + _context?: Record, + ): string[] => { + const cities = ["New York", "Los Angeles", "Chicago", "Houston"]; + return cities.filter((c) => + c.toLowerCase().startsWith(value.toLowerCase()), + ); + }; + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [ + createArgsPrompt({ + city: cityCompletions, + }), + ], + }); + + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Request completions for "city" argument with partial value "New" + const result = await client.getCompletions( + { type: "ref/prompt", name: "args-prompt" }, + "city", + "New", + ); + + expect(result.values).toContain("New York"); + expect(result.values.length).toBeGreaterThan(0); + + await client.disconnect(); + await server.stop(); + }); + + it("should return empty array when server does not support completions", async () => { + // Create a test server without completion support + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [createFileResourceTemplate()], // No completion callback + }); + + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Request completions - should return empty array (MethodNotFound handled gracefully) + const result = await client.getCompletions( + { type: "ref/resource", uri: "file:///{path}" }, + "path", + "file", + ); + + expect(result.values).toEqual([]); + + await client.disconnect(); + await server.stop(); + }); + + it("should get completions with context (other arguments)", async () => { + // Create a test server with a prompt that uses context + const stateCompletions = ( + value: string, + context?: Record, + ): string[] => { + const statesByCity: Record = { + "New York": ["NY", "New York State"], + "Los Angeles": ["CA", "California"], + }; + + const city = context?.city; + if (city && statesByCity[city]) { + return statesByCity[city].filter((s) => + s.toLowerCase().startsWith(value.toLowerCase()), + ); + } + return ["NY", "CA", "TX", "FL"].filter((s) => + s.toLowerCase().startsWith(value.toLowerCase()), + ); + }; + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [ + createArgsPrompt({ + state: stateCompletions, + }), + ], + }); + + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Request completions for "state" with context (city="New York") + const result = await client.getCompletions( + { type: "ref/prompt", name: "args-prompt" }, + "state", + "N", + { city: "New York" }, + ); + + expect(result.values).toContain("NY"); + expect(result.values).toContain("New York State"); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle async completion callbacks", async () => { + // Create a test server with async completion callback + const asyncCompletionCallback = async ( + argName: string, + value: string, + ): Promise => { + // Simulate async I/O in completion callback; fixture behavior, not a test wait. + await new Promise((resolve) => setTimeout(resolve, 10)); + const files = ["async1.txt", "async2.txt", "async3.txt"]; + return files.filter((f) => f.startsWith(value)); + }; + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [ + createFileResourceTemplate(asyncCompletionCallback), + ], + }); + + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const result = await client.getCompletions( + { type: "ref/resource", uri: "file:///{path}" }, + "path", + "async1", + ); + + expect(result.values).toContain("async1.txt"); + + await client.disconnect(); + await server.stop(); + }); + }); + + describe("ContentCache integration", () => { + it("should expose cache property that returns null for all getters initially", async () => { + const client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + // Cache should be accessible + expect(client.cache).toBeDefined(); + + // All getters should return null initially + expect(client.cache.getResource("file:///test.txt")).toBeNull(); + expect(client.cache.getResourceTemplate("file:///{path}")).toBeNull(); + expect(client.cache.getPrompt("testPrompt")).toBeNull(); + expect(client.cache.getToolCallResult("testTool")).toBeNull(); + + await client.disconnect(); + }); + + it("should clear cache when disconnect() is called", async () => { + const client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + // Verify cache is accessible + expect(client.cache).toBeDefined(); + + // Populate cache by calling fetch methods + const resources = await client.listAllResources(); + let resourceUri: string | undefined; + if (resources.length > 0 && resources[0]) { + resourceUri = resources[0].uri; + await client.readResource(resourceUri); + expect(client.cache.getResource(resourceUri)).not.toBeNull(); + } + + const tools = await client.listAllTools(); + let toolName: string | undefined; + if (tools.length > 0 && tools[0]) { + toolName = tools[0].name; + await client.callTool(toolName, {}); + expect(client.cache.getToolCallResult(toolName)).not.toBeNull(); + } + + const prompts = await client.listAllPrompts(); + let promptName: string | undefined; + if (prompts.length > 0 && prompts[0]) { + promptName = prompts[0].name; + await client.getPrompt(promptName); + expect(client.cache.getPrompt(promptName)).not.toBeNull(); + } + + // Disconnect should clear cache + await client.disconnect(); + + // After disconnect, cache should be cleared + if (resourceUri) { + expect(client.cache.getResource(resourceUri)).toBeNull(); + } + if (toolName) { + expect(client.cache.getToolCallResult(toolName)).toBeNull(); + } + if (promptName) { + expect(client.cache.getPrompt(promptName)).toBeNull(); + } + }); + + it("should not break existing API", async () => { + const client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + // Verify existing properties and methods still work + expect(client.getStatus()).toBe("disconnected"); + expect(client.getTools()).toEqual([]); + expect(client.getResources()).toEqual([]); + expect(client.getPrompts()).toEqual([]); + + await client.connect(); + expect(client.getStatus()).toBe("connected"); + + await client.disconnect(); + expect(client.getStatus()).toBe("disconnected"); + }); + + it("should cache resource content and dispatch event when readResource is called", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + const uri = "file:///test.txt"; + let eventReceived = false; + let eventDetail: any = null; + + client.addEventListener( + "resourceContentChange", + (event) => { + eventReceived = true; + eventDetail = event.detail; + }, + { once: true }, + ); + + const invocation = await client.readResource(uri); + + // Verify cache + const cached = client.cache.getResource(uri); + expect(cached).not.toBeNull(); + expect(cached).toBe(invocation); // Object identity preserved + + // Verify event was dispatched + expect(eventReceived).toBe(true); + expect(eventDetail.uri).toBe(uri); + expect(eventDetail.content).toBe(invocation); + expect(eventDetail.timestamp).toBeInstanceOf(Date); + + await client.disconnect(); + }); + + it("should cache resource template content and dispatch event when readResourceFromTemplate is called", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, // Auto-fetch to populate templates + }, + ); + await client.connect(); + + const template = client.getResourceTemplates()[0]; + if (!template) { + throw new Error("No resource templates available"); + } + + const params = { path: "test.txt" }; + let eventReceived = false; + let eventDetail: any = null; + + client.addEventListener( + "resourceTemplateContentChange", + (event) => { + eventReceived = true; + eventDetail = event.detail; + }, + { once: true }, + ); + + const invocation = await client.readResourceFromTemplate( + template.uriTemplate, + params, + ); + + // Verify cache + const cached = client.cache.getResourceTemplate(template.uriTemplate); + expect(cached).not.toBeNull(); + expect(cached).toBe(invocation); // Object identity preserved + + // Verify event was dispatched + expect(eventReceived).toBe(true); + expect(eventDetail.uriTemplate).toBe(template.uriTemplate); + expect(eventDetail.content).toBe(invocation); + expect(eventDetail.params).toEqual(params); + expect(eventDetail.timestamp).toBeInstanceOf(Date); + + await client.disconnect(); + }); + + it("should cache prompt content and dispatch event when getPrompt is called", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, // Auto-fetch to populate prompts + }, + ); + await client.connect(); + + const prompt = client.getPrompts()[0]; + if (!prompt) { + throw new Error("No prompts available"); + } + + let eventReceived = false; + let eventDetail: any = null; + + client.addEventListener( + "promptContentChange", + (event) => { + eventReceived = true; + eventDetail = event.detail; + }, + { once: true }, + ); + + const invocation = await client.getPrompt(prompt.name); + + // Verify cache + const cached = client.cache.getPrompt(prompt.name); + expect(cached).not.toBeNull(); + expect(cached).toBe(invocation); // Object identity preserved + + // Verify event was dispatched + expect(eventReceived).toBe(true); + expect(eventDetail.name).toBe(prompt.name); + expect(eventDetail.content).toBe(invocation); + expect(eventDetail.timestamp).toBeInstanceOf(Date); + + await client.disconnect(); + }); + + it("should cache successful tool call result and dispatch event", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, // Auto-fetch to populate tools + }, + ); + await client.connect(); + + const tool = client.getTools().find((t) => t.name === "echo"); + if (!tool) { + throw new Error("Echo tool not available"); + } + + let eventReceived = false; + let eventDetail: any = null; + + client.addEventListener( + "toolCallResultChange", + (event) => { + eventReceived = true; + eventDetail = event.detail; + }, + { once: true }, + ); + + const invocation = await client.callTool("echo", { message: "test" }); + + // Verify cache + const cached = client.cache.getToolCallResult("echo"); + expect(cached).not.toBeNull(); + expect(cached).toBe(invocation); // Object identity preserved + expect(cached?.success).toBe(true); + + // Verify event was dispatched + expect(eventReceived).toBe(true); + expect(eventDetail.toolName).toBe("echo"); + expect(eventDetail.success).toBe(true); + expect(eventDetail.result).not.toBeNull(); + expect(eventDetail.timestamp).toBeInstanceOf(Date); + + await client.disconnect(); + }); + + it("should cache failed tool call result and dispatch event", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + let eventReceived = false; + let eventDetail: any = null; + + client.addEventListener( + "toolCallResultChange", + (event) => { + eventReceived = true; + eventDetail = event.detail; + }, + { once: true }, + ); + + const invocation = await client.callTool("nonexistent-tool", {}); + + // Verify cache + const cached = client.cache.getToolCallResult("nonexistent-tool"); + expect(cached).not.toBeNull(); + expect(cached).toBe(invocation); // Object identity preserved + // Note: The tool call might succeed if the server has a catch-all handler + // So we just verify the cache stores the result correctly + expect(cached?.toolName).toBe("nonexistent-tool"); + expect(cached?.params).toEqual({}); + + // Verify event was dispatched + expect(eventReceived).toBe(true); + expect(eventDetail.toolName).toBe("nonexistent-tool"); + expect(eventDetail.params).toEqual({}); + expect(eventDetail.timestamp).toBeInstanceOf(Date); + // Note: success/error depends on server behavior + + await client.disconnect(); + }); + + it("should replace cache entry on subsequent calls", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + const uri = "file:///test.txt"; + + // First call + const invocation1 = await client.readResource(uri); + const cached1 = client.cache.getResource(uri); + expect(cached1).toBe(invocation1); + + // Advance clock so second readResource gets a strictly newer timestamp; no event/API to wait on. + await new Promise((resolve) => setTimeout(resolve, 10)); + + // Second call should replace cache + const invocation2 = await client.readResource(uri); + const cached2 = client.cache.getResource(uri); + expect(cached2).toBe(invocation2); + expect(cached2).not.toBe(invocation1); // Different object + expect(cached2?.timestamp.getTime()).toBeGreaterThan( + invocation1.timestamp.getTime(), + ); + + await client.disconnect(); + }); + + it("should persist cache across multiple calls", async () => { + client = new InspectorClient( + { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + const uri = "file:///test.txt"; + + // First call + const invocation1 = await client.readResource(uri); + const cached1 = client.cache.getResource(uri); + expect(cached1).toBe(invocation1); + + // Second call to same resource + const invocation2 = await client.readResource(uri); + const cached2 = client.cache.getResource(uri); + expect(cached2).toBe(invocation2); + + // Cache should still be accessible + const cached3 = client.cache.getResource(uri); + expect(cached3).toBe(invocation2); + + await client.disconnect(); + }); + }); + + describe("Resource Subscriptions", () => { + it("should initialize subscribedResources as empty Set", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + expect(client.getSubscribedResources()).toEqual([]); + expect(client.isSubscribedToResource("test://uri")).toBe(false); + + await client.disconnect(); + await server.stop(); + }); + + it("should clear subscriptions on disconnect", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Manually add a subscription (Phase 3 will add proper methods) + (client as any).subscribedResources.add("test://uri1"); + (client as any).subscribedResources.add("test://uri2"); + + expect(client.getSubscribedResources()).toHaveLength(2); + + await client.disconnect(); + + // Subscriptions should be cleared + expect(client.getSubscribedResources()).toEqual([]); + + await server.stop(); + }); + + it("should check server capability for resource subscriptions support", async () => { + // Server without resource subscriptions + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Server doesn't support resource subscriptions + expect(client.supportsResourceSubscriptions()).toBe(false); + + await client.disconnect(); + await server.stop(); + + // Server with resource subscriptions (we'll need to add this capability in test server) + // For now, just test that the method exists and checks capabilities + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + // Note: We'd need to add subscribe capability to test server config + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Still false because test server doesn't advertise subscribe capability + expect(client.supportsResourceSubscriptions()).toBe(false); + + await client.disconnect(); + await server.stop(); + }); + }); + + describe("ListChanged Notifications", () => { + it("should initialize listChangedNotifications config with defaults (all enabled)", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + // Defaults should be all enabled + expect((client as any).listChangedNotifications).toEqual({ + tools: true, + resources: true, + prompts: true, + }); + + await client.disconnect(); + await server.stop(); + }); + + it("should respect listChangedNotifications config options", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + listChangedNotifications: { + tools: false, + resources: true, + prompts: false, + }, + }, + ); + + expect((client as any).listChangedNotifications).toEqual({ + tools: false, + resources: true, + prompts: false, + }); + + await client.disconnect(); + await server.stop(); + }); + + it("should update state and dispatch event when listAllTools() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Clear initial state + expect(client.getTools()).toEqual([]); + + // Wait for toolsChange event + const toolsChangePromise = new Promise((resolve) => { + client.addEventListener( + "toolsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + const tools = await client.listAllTools(); + const event = await toolsChangePromise; + + expect(tools.length).toBeGreaterThan(0); + expect(client.getTools()).toEqual(tools); + expect(event.detail).toEqual(tools); + + await client.disconnect(); + await server.stop(); + }); + + it("should update state, clean cache, and dispatch event when listResources() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Load a resource to populate cache (before listing) + const uri = "demo://resource/static/document/architecture.md"; + await client.readResource(uri); + expect(client.cache.getResource(uri)).not.toBeNull(); + + // Wait for resourcesChange event + const resourcesChangePromise = new Promise((resolve) => { + client.addEventListener( + "resourcesChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // listAllResources will reset and reload all resources + const resources = await client.listAllResources(); + const event = await resourcesChangePromise; + + expect(resources.length).toBeGreaterThan(0); + expect(client.getResources()).toEqual(resources); + expect(event.detail).toEqual(resources); + // Cache should be preserved for existing resource + expect(client.cache.getResource(uri)).not.toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should clean up cache for removed resources when listResources() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource(), createTestCwdResource()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First list resources to populate the list + await client.listResources(); + + // Load both resources to populate cache + const uri1 = "demo://resource/static/document/architecture.md"; + const uri2 = "test://cwd"; + await client.readResource(uri1); + await client.readResource(uri2); + expect(client.cache.getResource(uri1)).not.toBeNull(); + expect(client.cache.getResource(uri2)).not.toBeNull(); + + // Now remove one resource from server + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], // Only keep uri1 + }); + await server.stop(); + await server.start(); + + // Reconnect and list resources + await client.disconnect(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + // Load the remaining resource to populate cache + await client.readResource(uri1); + + // listAllResources clears cache for removed resources + await client.listAllResources(); + + // Cache for uri1 should be preserved, uri2 should be cleared + expect(client.cache.getResource(uri1)).not.toBeNull(); + expect(client.cache.getResource(uri2)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should update state, clean cache, and dispatch event when listAllResourceTemplates() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [createFileResourceTemplate()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First list resource templates to populate the list + await client.listAllResourceTemplates(); + + // Load a resource template to populate cache + const uriTemplate = "file:///{path}"; + await client.readResourceFromTemplate(uriTemplate, { path: "test.txt" }); + expect(client.cache.getResourceTemplate(uriTemplate)).not.toBeNull(); + + // Wait for resourceTemplatesChange event + const resourceTemplatesChangePromise = new Promise( + (resolve) => { + client.addEventListener( + "resourceTemplatesChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }, + ); + + const templates = await client.listAllResourceTemplates(); + const event = await resourceTemplatesChangePromise; + + expect(templates.length).toBeGreaterThan(0); + expect(client.getResourceTemplates()).toEqual(templates); + expect(event.detail).toEqual(templates); + // Cache should be preserved for existing template + expect(client.cache.getResourceTemplate(uriTemplate)).not.toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should update state, clean cache, and dispatch event when listAllPrompts() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [createSimplePrompt()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First list prompts to populate the list + await client.listAllPrompts(); + + // Load a prompt to populate cache + const promptName = "simple-prompt"; + await client.getPrompt(promptName); + expect(client.cache.getPrompt(promptName)).not.toBeNull(); + + // Wait for promptsChange event + const promptsChangePromise = new Promise((resolve) => { + client.addEventListener( + "promptsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + const prompts = await client.listAllPrompts(); + const event = await promptsChangePromise; + + expect(prompts.length).toBeGreaterThan(0); + expect(client.getPrompts()).toEqual(prompts); + expect(event.detail).toEqual(prompts); + // Cache should be preserved for existing prompt + expect(client.cache.getPrompt(promptName)).not.toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle tools/list_changed notification and reload tools", async () => { + const { createAddToolTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool(), createAddToolTool()], + listChanged: { tools: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, // Auto-fetch to populate initial state + }, + ); + + await client.connect(); + + const initialTools = client.getTools(); + expect(initialTools.length).toBeGreaterThan(0); + + // Wait for toolsChange event after notification + const toolsChangePromise = new Promise((resolve) => { + client.addEventListener( + "toolsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Add a new tool (this will send list_changed notification) + await client.callTool("addTool", { + name: "newTool", + description: "A new test tool", + }); + const event = await toolsChangePromise; + + // Tools should be reloaded + const updatedTools = client.getTools(); + expect(Array.isArray(updatedTools)).toBe(true); + // Should have the new tool + expect(updatedTools.find((t) => t.name === "newTool")).toBeDefined(); + // Event detail should match current tools exactly + // (callTool() uses listToolsInternal() so it doesn't dispatch events, + // so this event comes only from the notification handler) + expect(event.detail).toEqual(updatedTools); + + await client.disconnect(); + await server.stop(); + }); + + it("should fire toolsListChanged event when server sends tools/list_changed notification", async () => { + const { createAddToolTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool(), createAddToolTool()], + listChanged: { tools: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, // Don't auto-reload + }, + ); + + await client.connect(); + + // Wait for toolsListChanged event + const toolsListChangedPromise = new Promise((resolve) => { + client.addEventListener( + "toolsListChanged", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Add a new tool (this will send list_changed notification) + await client.callTool("addTool", { + name: "newTool", + description: "A new test tool", + }); + await toolsListChangedPromise; + + // Event should have fired (notification received) + // But tools should NOT be reloaded since autoSyncLists is false + const tools = client.getTools(); + expect(tools.find((t) => t.name === "newTool")).toBeUndefined(); + + await client.disconnect(); + await server.stop(); + }); + + it("should reload tools when autoSyncLists is true and toolsListChanged fires", async () => { + const { createAddToolTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool(), createAddToolTool()], + listChanged: { tools: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, // Auto-reload enabled + }, + ); + + await client.connect(); + + const events: CustomEvent[] = []; + client.addEventListener("toolsListChanged", (event) => { + events.push(event); + }); + client.addEventListener("toolsChange", (event) => { + events.push(event); + }); + + // Add a new tool (this will send list_changed notification) + await client.callTool("addTool", { + name: "newTool", + description: "A new test tool", + }); + + // Wait a bit for events to fire + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Should have received both events + expect(events.length).toBeGreaterThanOrEqual(2); + expect(events.some((e) => e.type === "toolsListChanged")).toBe(true); + expect(events.some((e) => e.type === "toolsChange")).toBe(true); + + // Tools should be reloaded + const tools = client.getTools(); + expect(tools.find((t) => t.name === "newTool")).toBeDefined(); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle resources/list_changed notification and reload resources and templates", async () => { + const { createAddResourceTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + resourceTemplates: [createFileResourceTemplate()], + tools: [createAddResourceTool()], + listChanged: { resources: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + const initialResources = client.getResources(); + const initialTemplates = client.getResourceTemplates(); + expect(initialResources.length).toBeGreaterThan(0); + expect(initialTemplates.length).toBeGreaterThan(0); + + // Wait for both change events + const resourcesChangePromise = new Promise((resolve) => { + client.addEventListener( + "resourcesChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + const resourceTemplatesChangePromise = new Promise( + (resolve) => { + client.addEventListener( + "resourceTemplatesChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }, + ); + + // Add a new resource (this will send list_changed notification) + await client.callTool("addResource", { + uri: "test://new-resource", + name: "newResource", + text: "New resource content", + }); + const resourcesEvent = await resourcesChangePromise; + const templatesEvent = await resourceTemplatesChangePromise; + + // Both should be reloaded + expect(client.getResources()).toEqual(resourcesEvent.detail); + expect(client.getResourceTemplates()).toEqual(templatesEvent.detail); + // Should have the new resource + expect( + client.getResources().find((r) => r.uri === "test://new-resource"), + ).toBeDefined(); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle prompts/list_changed notification and reload prompts", async () => { + const { createAddPromptTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [createSimplePrompt()], + tools: [createAddPromptTool()], + listChanged: { prompts: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + const initialPrompts = client.getPrompts(); + expect(initialPrompts.length).toBeGreaterThan(0); + + // Wait for promptsChange event after notification + const promptsChangePromise = new Promise((resolve) => { + client.addEventListener( + "promptsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Add a new prompt (this will send list_changed notification) + await client.callTool("addPrompt", { + name: "newPrompt", + promptString: "This is a new prompt", + }); + const event = await promptsChangePromise; + + // Prompts should be reloaded + expect(client.getPrompts()).toEqual(event.detail); + // Should have the new prompt + expect( + client.getPrompts().find((p) => p.name === "newPrompt"), + ).toBeDefined(); + + await client.disconnect(); + await server.stop(); + }); + + it("should respect listChangedNotifications config (disabled handlers)", async () => { + const { createAddToolTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool(), createAddToolTool()], + listChanged: { tools: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + listChangedNotifications: { + tools: false, // Disable tools listChanged handler + resources: true, + prompts: true, + }, + }, + ); + + await client.connect(); + + const initialTools = client.getTools(); + const initialToolCount = initialTools.length; + + // Set up event listener to detect if notification handler runs + // callTool() uses listToolsInternal() which doesn't dispatch events, + // so any toolsChange event must come from the notification handler + let eventReceived = false; + const testEventListener = () => { + eventReceived = true; + }; + client.addEventListener("toolsChange", testEventListener, { once: true }); + + // Add a new tool (this will send list_changed notification from server) + // callTool() uses listToolsInternal() which doesn't dispatch events + // If handler is enabled, it will call listTools() which dispatches toolsChange + // Since handler is disabled, no event should be received + await client.callTool("addTool", { + name: "testTool", + description: "Test tool", + }); + + // Observation window: we assert no toolsChange from notification handler; can't wait for a non-event. + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Remove listener + client.removeEventListener("toolsChange", testEventListener); + + // Event should NOT be received because handler is disabled + expect(eventReceived).toBe(false); + + // Tools should not have changed (handler didn't run, so listTools() wasn't called) + // The server has the new tool, but the client's internal state hasn't been updated + const finalTools = client.getTools(); + expect(finalTools.length).toBe(initialToolCount); + expect(finalTools).toEqual(initialTools); + + // Verify the tool was actually added to the server by manually calling listAllTools() + // This proves the server received the addTool call and the notification was sent + const serverTools = await client.listAllTools(); + expect(serverTools.length).toBeGreaterThan(initialToolCount); + expect(serverTools.find((t) => t.name === "testTool")).toBeDefined(); + + await client.disconnect(); + await server.stop(); + }); + + it("should only register handlers when server supports listChanged capability", async () => { + // Create a server that doesn't advertise listChanged capability + // (we can't easily do this with our test server, but we can test the logic) + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + // Check that capabilities are set + const capabilities = (client as any).capabilities; + // If server doesn't advertise listChanged, handlers won't be registered + // This is tested implicitly - if handlers were registered incorrectly, tests would fail + + await client.disconnect(); + await server.stop(); + }); + + it("should handle tools/list_changed notification on removal and clear tool call cache", async () => { + const { createRemoveToolTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool(), createRemoveToolTool()], + listChanged: { tools: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + // Call echo tool to populate cache + const toolName = "echo"; + await client.callTool(toolName, { message: "test" }); + expect(client.cache.getToolCallResult(toolName)).not.toBeNull(); + + // Wait for toolsChange event after notification + const toolsChangePromise = new Promise((resolve) => { + client.addEventListener( + "toolsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Remove the tool (this will send list_changed notification) + await client.callTool("removeTool", { name: toolName }); + const event = await toolsChangePromise; + + // Tools should be reloaded + const updatedTools = client.getTools(); + expect(updatedTools.find((t) => t.name === toolName)).toBeUndefined(); + expect(event.detail).toEqual(updatedTools); + + // Cache should be cleared for removed tool + expect(client.cache.getToolCallResult(toolName)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle resources/list_changed notification on removal and clear resource cache", async () => { + const { createRemoveResourceTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + tools: [createRemoveResourceTool()], + listChanged: { resources: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + // Load resource to populate cache + const uri = "demo://resource/static/document/architecture.md"; + await client.readResource(uri); + expect(client.cache.getResource(uri)).not.toBeNull(); + + // Wait for resourcesChange event after notification + const resourcesChangePromise = new Promise((resolve) => { + client.addEventListener( + "resourcesChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Remove the resource (this will send list_changed notification) + await client.callTool("removeResource", { uri }); + const event = await resourcesChangePromise; + + // Resources should be reloaded + const updatedResources = client.getResources(); + expect(updatedResources.find((r) => r.uri === uri)).toBeUndefined(); + expect(event.detail).toEqual(updatedResources); + + // Cache should be cleared for removed resource + expect(client.cache.getResource(uri)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should handle prompts/list_changed notification on removal and clear prompt cache", async () => { + const { createRemovePromptTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [createSimplePrompt()], + tools: [createRemovePromptTool()], + listChanged: { prompts: true }, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: true, + }, + ); + + await client.connect(); + + // Load prompt to populate cache + const promptName = "simple-prompt"; + await client.getPrompt(promptName); + expect(client.cache.getPrompt(promptName)).not.toBeNull(); + + // Wait for promptsChange event after notification + const promptsChangePromise = new Promise((resolve) => { + client.addEventListener( + "promptsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Remove the prompt (this will send list_changed notification) + await client.callTool("removePrompt", { name: promptName }); + const event = await promptsChangePromise; + + // Prompts should be reloaded + const updatedPrompts = client.getPrompts(); + expect(updatedPrompts.find((p) => p.name === promptName)).toBeUndefined(); + expect(event.detail).toEqual(updatedPrompts); + + // Cache should be cleared for removed prompt + expect(client.cache.getPrompt(promptName)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should clean up cache for removed resource templates when listResourceTemplates() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [ + createFileResourceTemplate(), + createUserResourceTemplate(), + ], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First list resource templates to populate the list + await client.listAllResourceTemplates(); + + // Load both templates to populate cache + const uriTemplate1 = "file:///{path}"; + const uriTemplate2 = "user://{userId}"; + await client.readResourceFromTemplate(uriTemplate1, { path: "test.txt" }); + await client.readResourceFromTemplate(uriTemplate2, { userId: "123" }); + expect(client.cache.getResourceTemplate(uriTemplate1)).not.toBeNull(); + expect(client.cache.getResourceTemplate(uriTemplate2)).not.toBeNull(); + + // Now remove one template from server + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resourceTemplates: [createFileResourceTemplate()], // Only keep uriTemplate1 + }); + await server.stop(); + await server.start(); + + // Reconnect and list resource templates + await client.disconnect(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + // First list resource templates to populate the list + await client.listAllResourceTemplates(); + + // Load uriTemplate1 again to populate cache + await client.readResourceFromTemplate(uriTemplate1, { path: "test.txt" }); + + // List resource templates (should only have uriTemplate1 now) + await client.listAllResourceTemplates(); + + // Cache for uriTemplate1 should be preserved, uriTemplate2 should be cleared + expect(client.cache.getResourceTemplate(uriTemplate1)).not.toBeNull(); + expect(client.cache.getResourceTemplate(uriTemplate2)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should clean up cache for removed prompts when listPrompts() is called", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [createSimplePrompt(), createArgsPrompt()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // First list prompts to populate the list + await client.listAllPrompts(); + + // Load both prompts to populate cache + const promptName1 = "simple-prompt"; + const promptName2 = "args-prompt"; + await client.getPrompt(promptName1); + await client.getPrompt(promptName2, { city: "New York", state: "NY" }); + expect(client.cache.getPrompt(promptName1)).not.toBeNull(); + expect(client.cache.getPrompt(promptName2)).not.toBeNull(); + + // Now remove one prompt from server + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + prompts: [createSimplePrompt()], // Only keep promptName1 + }); + await server.stop(); + await server.start(); + + // Reconnect and list prompts + await client.disconnect(); + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + // First list prompts to populate the list + await client.listAllPrompts(); + + // Load promptName1 again to populate cache + await client.getPrompt(promptName1); + + // List prompts (should only have promptName1 now) + await client.listAllPrompts(); + + // Cache for promptName1 should be preserved, promptName2 should be cleared + expect(client.cache.getPrompt(promptName1)).not.toBeNull(); + expect(client.cache.getPrompt(promptName2)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + }); + + describe("Resource Subscriptions", () => { + it("should subscribe to a resource and track subscription state", async () => { + // Test server without subscriptions + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Server doesn't support subscriptions + expect(client.supportsResourceSubscriptions()).toBe(false); + + // Should throw error when trying to subscribe + await expect( + client.subscribeToResource( + "demo://resource/static/document/architecture.md", + ), + ).rejects.toThrow("Server does not support resource subscriptions"); + + await client.disconnect(); + await server.stop(); + }); + + it("should subscribe to a resource when server supports subscriptions", async () => { + const { createUpdateResourceTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + tools: [createUpdateResourceTool()], + subscriptions: true, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + // Server supports subscriptions + expect(client.supportsResourceSubscriptions()).toBe(true); + + const uri = "demo://resource/static/document/architecture.md"; + + // Wait for resourceSubscriptionsChange event + const eventPromise = new Promise((resolve) => { + client.addEventListener( + "resourceSubscriptionsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Subscribe to resource + await client.subscribeToResource(uri); + const event = await eventPromise; + + // Verify subscription state + expect(client.isSubscribedToResource(uri)).toBe(true); + expect(client.getSubscribedResources()).toContain(uri); + expect(event.detail).toContain(uri); + + await client.disconnect(); + await server.stop(); + }); + + it("should unsubscribe from a resource", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + subscriptions: true, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const uri = "demo://resource/static/document/architecture.md"; + + // Subscribe first + await client.subscribeToResource(uri); + expect(client.isSubscribedToResource(uri)).toBe(true); + + // Wait for resourceSubscriptionsChange event + const eventPromise = new Promise((resolve) => { + client.addEventListener( + "resourceSubscriptionsChange", + (event) => { + resolve(event); + }, + { once: true }, + ); + }); + + // Unsubscribe + await client.unsubscribeFromResource(uri); + const event = await eventPromise; + + // Verify unsubscribed + expect(client.isSubscribedToResource(uri)).toBe(false); + expect(client.getSubscribedResources()).not.toContain(uri); + expect(event.detail).not.toContain(uri); + + await client.disconnect(); + await server.stop(); + }); + + it("should throw error when unsubscribe called while not connected", async () => { + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + await client.disconnect(); + + await expect( + client.unsubscribeFromResource( + "demo://resource/static/document/architecture.md", + ), + ).rejects.toThrow(); + + await server.stop(); + }); + + it("should handle resource updated notification and clear cache for subscribed resource", async () => { + const { createUpdateResourceTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + tools: [createUpdateResourceTool()], + subscriptions: true, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const uri = "demo://resource/static/document/architecture.md"; + + // Load resource to populate cache + await client.readResource(uri); + expect(client.cache.getResource(uri)).not.toBeNull(); + + // Subscribe to resource + await client.subscribeToResource(uri); + expect(client.isSubscribedToResource(uri)).toBe(true); + + // Wait for resourceUpdated event + const eventPromise = new Promise((resolve) => { + client.addEventListener( + "resourceUpdated", + ((event: CustomEvent) => { + resolve(event); + }) as EventListener, + { once: true }, + ); + }); + + // Update the resource (this will send resource updated notification) + await client.callTool("updateResource", { + uri, + text: "Updated content", + }); + + const event = await eventPromise; + expect(event.detail.uri).toBe(uri); + + // Cache should be cleared + expect(client.cache.getResource(uri)).toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + + it("should ignore resource updated notification for unsubscribed resources", async () => { + const { createUpdateResourceTool } = + await import("../test/test-server-fixtures.js"); + + server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + resources: [createArchitectureResource()], + tools: [createUpdateResourceTool()], + subscriptions: true, + }); + await server.start(); + + client = new InspectorClient( + { + type: "streamable-http", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + + await client.connect(); + + const uri = "demo://resource/static/document/architecture.md"; + + // Load resource to populate cache + await client.readResource(uri); + expect(client.cache.getResource(uri)).not.toBeNull(); + + // Don't subscribe - resource should NOT be in subscribedResources + expect(client.isSubscribedToResource(uri)).toBe(false); + + // Set up event listener (should not receive event) + let eventReceived = false; + const testEventListener = () => { + eventReceived = true; + }; + client.addEventListener("resourceUpdated", testEventListener, { + once: true, + }); + + // Update the resource (this will send resource updated notification) + await client.callTool("updateResource", { + uri, + text: "Updated content", + }); + + // Observation window: we assert no resourceUpdated for unsubscribed resource; can't wait for a non-event. + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Remove listener + client.removeEventListener("resourceUpdated", testEventListener); + + // Event should NOT be received because resource is not subscribed + expect(eventReceived).toBe(false); + + // Cache should still be present (not cleared) + expect(client.cache.getResource(uri)).not.toBeNull(); + + await client.disconnect(); + await server.stop(); + }); + }); + + describe("Task Support", () => { + beforeEach(async () => { + // Create server with task support + const taskConfig = { + ...getTaskServerConfig(), + serverType: "sse" as const, + }; + server = createTestServerHttp(taskConfig); + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + }); + + it("should detect task capabilities", () => { + const capabilities = client.getTaskCapabilities(); + expect(capabilities).toBeDefined(); + expect(capabilities?.list).toBe(true); + expect(capabilities?.cancel).toBe(true); + }); + + it("should list tasks (empty initially)", async () => { + const result = await client.listTasks(); + expect(result).toHaveProperty("tasks"); + expect(Array.isArray(result.tasks)).toBe(true); + }); + + it("should call tool with task support using callToolStream", async () => { + const taskCreatedEvents: Array<{ taskId: string; task: Task }> = []; + const taskStatusEvents: Array<{ taskId: string; task: Task }> = []; + const taskCompletedEvents: Array<{ + taskId: string; + result: CallToolResult; + }> = []; + const toolCallResultEvents: Array<{ + toolName: string; + params: Record; + result: any; + timestamp: Date; + success: boolean; + error?: string; + metadata?: Record; + }> = []; + + client.addEventListener( + "taskCreated", + (event: TypedEvent<"taskCreated">) => { + taskCreatedEvents.push(event.detail); + }, + ); + client.addEventListener( + "taskStatusChange", + (event: TypedEvent<"taskStatusChange">) => { + taskStatusEvents.push(event.detail); + }, + ); + client.addEventListener( + "taskCompleted", + (event: TypedEvent<"taskCompleted">) => { + taskCompletedEvents.push(event.detail); + }, + ); + client.addEventListener( + "toolCallResultChange", + (event: TypedEvent<"toolCallResultChange">) => { + toolCallResultEvents.push(event.detail); + }, + ); + + const result = await client.callToolStream("simpleTask", { + message: "test task", + }); + + // Validate final result + expect(result.success).toBe(true); + expect(result.result).toBeDefined(); + expect(result.result).not.toBeNull(); + expect(result.result).toHaveProperty("content"); + + // Validate result content structure + const toolResult = result.result!; + expect(toolResult.content).toBeDefined(); + expect(Array.isArray(toolResult.content)).toBe(true); + expect(toolResult.content.length).toBe(1); + + const firstContent = toolResult.content[0]; + expect(firstContent).toBeDefined(); + expect(firstContent).not.toBeUndefined(); + expect(firstContent!.type).toBe("text"); + + // Validate result content value + if (firstContent && firstContent.type === "text") { + expect(firstContent.text).toBeDefined(); + const resultText = JSON.parse(firstContent.text); + expect(resultText.message).toBe("Task completed: test task"); + expect(resultText.taskId).toBeDefined(); + expect(typeof resultText.taskId).toBe("string"); + } else { + expect(firstContent?.type).toBe("text"); + } + + // Validate taskCreated event + expect(taskCreatedEvents.length).toBe(1); + const createdEvent = taskCreatedEvents[0]!; + expect(createdEvent.taskId).toBeDefined(); + expect(typeof createdEvent.taskId).toBe("string"); + expect(createdEvent.task).toBeDefined(); + expect(createdEvent.task.taskId).toBe(createdEvent.taskId); + expect(createdEvent.task.status).toBe("working"); + expect(createdEvent.task).toHaveProperty("ttl"); + expect(createdEvent.task).toHaveProperty("lastUpdatedAt"); + + const taskId = createdEvent.taskId; + + // Validate taskStatusChange events - simpleTask flow: + // The SDK may send multiple status updates. For simpleTask, we expect: + // 1. taskCreated (status: "working") - from SDK when task is created + // 2. taskStatusChange events - SDK may send status updates during execution + // - At minimum: one with status "completed" when task finishes + // - May also include: one with status "working" (initial status update) + // 3. taskCompleted - when result is available + + // Verify we got at least one status change + expect(taskStatusEvents.length).toBeGreaterThanOrEqual(1); + + // Verify all status events are for the same task and have valid structure + const statuses = taskStatusEvents.map((event) => { + expect(event.taskId).toBe(taskId); + expect(event.task.taskId).toBe(taskId); + expect(event.task).toHaveProperty("status"); + expect(event.task).toHaveProperty("ttl"); + expect(event.task).toHaveProperty("lastUpdatedAt"); + // Verify lastUpdatedAt is a valid ISO string if present + if (event.task.lastUpdatedAt) { + expect(typeof event.task.lastUpdatedAt).toBe("string"); + expect(() => new Date(event.task.lastUpdatedAt!)).not.toThrow(); + } + return event.task.status; + }); + + // The last status change must be "completed" + expect(statuses[statuses.length - 1]).toBe("completed"); + + // All statuses should be either "working" or "completed" (no input_required, failed, cancelled) + statuses.forEach((status) => { + expect(["working", "completed"]).toContain(status); + }); + + // If we have multiple events, they should be in order: working -> completed + if (taskStatusEvents.length > 1) { + // First status should be "working" + expect(statuses[0]).toBe("working"); + // Last status should be "completed" + expect(statuses[statuses.length - 1]).toBe("completed"); + } else { + // If only one event, it must be "completed" + expect(statuses[0]).toBe("completed"); + } + + // Validate taskCompleted event + expect(taskCompletedEvents.length).toBe(1); + const completedEvent = taskCompletedEvents[0]!; + expect(completedEvent.taskId).toBe(taskId); + expect(completedEvent.result).toBeDefined(); + expect(completedEvent.result).toEqual(toolResult); + + // Validate toolCallResultChange event + expect(toolCallResultEvents.length).toBe(1); + const toolCallEvent = toolCallResultEvents[0]!; + expect(toolCallEvent.toolName).toBe("simpleTask"); + expect(toolCallEvent.params).toEqual({ message: "test task" }); + expect(toolCallEvent.success).toBe(true); + expect(toolCallEvent.result).toEqual(toolResult); + expect(toolCallEvent.timestamp).toBeInstanceOf(Date); + + // Validate task in clientTasks + const clientTasks = client.getClientTasks(); + const cachedTask = clientTasks.find((t) => t.taskId === taskId); + expect(cachedTask).toBeDefined(); + expect(cachedTask!.taskId).toBe(taskId); + expect(cachedTask!.status).toBe("completed"); + expect(cachedTask!).toHaveProperty("ttl"); + expect(cachedTask!).toHaveProperty("lastUpdatedAt"); + + // Validate consistency: taskId from all sources matches + expect(createdEvent.taskId).toBe(taskId); + expect(completedEvent.taskId).toBe(taskId); + expect(cachedTask!.taskId).toBe(taskId); + if (firstContent && firstContent.type === "text") { + const resultText = JSON.parse(firstContent.text); + expect(resultText.taskId).toBe(taskId); + } + }); + + it("should get task by taskId", async () => { + // First create a task + const result = await client.callToolStream("simpleTask", { + message: "test", + }); + expect(result.success).toBe(true); + + // Get the taskId from active tasks + const activeTasks = client.getClientTasks(); + expect(activeTasks.length).toBeGreaterThan(0); + const activeTask = activeTasks[0]; + expect(activeTask).toBeDefined(); + const taskId = activeTask!.taskId; + + // Get the task + const task = await client.getTask(taskId); + expect(task).toBeDefined(); + expect(task.taskId).toBe(taskId); + expect(task.status).toBe("completed"); + }); + + it("should get task result", async () => { + // First create a task + const result = await client.callToolStream("simpleTask", { + message: "test result", + }); + expect(result.success).toBe(true); + expect(result.result).toBeDefined(); + expect(result.result).not.toBeNull(); + + // Get the taskId from client tasks + const clientTasks = client.getClientTasks(); + expect(clientTasks.length).toBeGreaterThan(0); + const task = clientTasks.find((t) => t.status === "completed"); + expect(task).toBeDefined(); + const taskId = task!.taskId; + + // Get the task result + const taskResult = await client.getTaskResult(taskId); + + // Validate result structure + expect(taskResult).toBeDefined(); + expect(taskResult).toHaveProperty("content"); + expect(Array.isArray(taskResult.content)).toBe(true); + expect(taskResult.content.length).toBe(1); + + // Validate content structure + const firstContent = taskResult.content[0]; + expect(firstContent).toBeDefined(); + expect(firstContent).not.toBeUndefined(); + expect(firstContent!.type).toBe("text"); + + // Validate content value + if (firstContent && firstContent.type === "text") { + expect(firstContent.text).toBeDefined(); + const resultText = JSON.parse(firstContent.text); + expect(resultText.message).toBe("Task completed: test result"); + expect(resultText.taskId).toBe(taskId); + } else { + expect(firstContent?.type).toBe("text"); + } + + // Validate that getTaskResult returns the same result as callToolStream + expect(taskResult).toEqual(result.result); + }); + + it("should throw error when calling callTool on task-required tool", async () => { + await expect( + client.callTool("simpleTask", { message: "test" }), + ).rejects.toThrow("requires task support"); + }); + + it("should clear tasks on disconnect", async () => { + // Create a task + await client.callToolStream("simpleTask", { message: "test" }); + expect(client.getClientTasks().length).toBeGreaterThan(0); + + // Disconnect + await client.disconnect(); + + // Tasks should be cleared + expect(client.getClientTasks().length).toBe(0); + }); + + it("should call tool with taskSupport: forbidden (immediate result, no task)", async () => { + // forbiddenTask should return immediately without creating a task + const result = await client.callToolStream("forbiddenTask", { + message: "test", + }); + + expect(result.success).toBe(true); + expect(result.result).toHaveProperty("content"); + // No task should be created + expect(client.getClientTasks().length).toBe(0); + }); + + it("should call tool with taskSupport: optional (may or may not create task)", async () => { + // optionalTask may create a task or return immediately + const result = await client.callToolStream("optionalTask", { + message: "test", + }); + + expect(result.success).toBe(true); + expect(result.result).toHaveProperty("content"); + // Task may or may not be created - both are valid + }); + + it("should handle task failure and dispatch taskFailed event", async () => { + await client.disconnect(); + await server?.stop(); + + // Create a task tool that will fail after a short delay + const failingTask = createFlexibleTaskTool({ + name: "failingTask", + taskSupport: "required", + delayMs: 100, + failAfterDelay: 50, // Fail after 50ms + }); + + const taskConfig = getTaskServerConfig(); + const failConfig = { + ...taskConfig, + serverType: "sse" as const, + tools: [failingTask, ...(taskConfig.tools || [])], + }; + server = createTestServerHttp(failConfig); + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + const failedPromise = expect( + client.callToolStream("failingTask", { message: "test" }), + ).rejects.toThrow(); + + const taskFailedDetail = await waitForEvent<{ + taskId: string; + error: Error; + }>(client, "taskFailed", { timeout: 2000 }); + expect(taskFailedDetail.taskId).toBeDefined(); + expect(taskFailedDetail.error).toBeDefined(); + + await failedPromise; + }); + + it("should cancel a running task", async () => { + await client.disconnect(); + await server?.stop(); + + // Create a longer-running task tool + const longRunningTask = createFlexibleTaskTool({ + name: "longRunningTask", + taskSupport: "required", + delayMs: 2000, // 2 seconds + }); + + const taskConfig = getTaskServerConfig(); + const cancelConfig = { + ...taskConfig, + serverType: "sse" as const, + tools: [longRunningTask, ...(taskConfig.tools || [])], + }; + server = createTestServerHttp(cancelConfig); + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + }, + ); + await client.connect(); + + const taskPromise = client.callToolStream("longRunningTask", { + message: "test", + }); + + const taskCreatedDetail = await waitForEvent<{ taskId: string }>( + client, + "taskCreated", + { timeout: 3000 }, + ); + const taskId = taskCreatedDetail.taskId; + expect(taskId).toBeDefined(); + + const cancelledPromise = waitForEvent<{ taskId: string }>( + client, + "taskCancelled", + { timeout: 3000 }, + ); + await client.cancelTask(taskId); + + const [cancelledResult, taskResult] = await Promise.allSettled([ + cancelledPromise, + taskPromise, + ]); + expect(cancelledResult.status).toBe("fulfilled"); + const cancelledDetail = ( + cancelledResult as PromiseFulfilledResult<{ taskId: string }> + ).value; + expect(cancelledDetail.taskId).toBe(taskId); + expect(taskResult.status).toBe("rejected"); + + const task = await client.getTask(taskId); + expect(task.status).toBe("cancelled"); + }); + + it("should handle elicitation with task (input_required flow)", async () => { + await client.disconnect(); + await server?.stop(); + + const elicitationConfig = { + ...getTaskServerConfig(), + serverType: "sse" as const, + tools: [ + createElicitationTaskTool("taskWithElicitation"), + ...(getTaskServerConfig().tools || []), + ], + }; + server = createTestServerHttp(elicitationConfig); + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + elicit: true, + }, + ); + await client.connect(); + + const elicitationPromise = waitForEvent( + client, + "newPendingElicitation", + { timeout: 2000 }, + ); + const taskPromise = client.callToolStream("taskWithElicitation", { + message: "test", + }); + + const elicitation = await elicitationPromise; + + // Verify elicitation was received + expect(elicitation).toBeDefined(); + + // Verify task status is input_required (if taskId was extracted) + if (elicitation.taskId) { + const activeTasks = client.getClientTasks(); + const task = activeTasks.find((t) => t.taskId === elicitation.taskId); + if (task) { + expect(task.status).toBe("input_required"); + } + } + + // Respond to elicitation with correct format + await elicitation.respond({ + action: "accept", + content: { + input: "test input", + }, + }); + + // Wait for task to complete + const result = await taskPromise; + expect(result.success).toBe(true); + }); + + it("should handle sampling with task (input_required flow)", async () => { + await client.disconnect(); + await server?.stop(); + + const samplingConfig = { + ...getTaskServerConfig(), + serverType: "sse" as const, + tools: [ + createSamplingTaskTool("taskWithSampling"), + ...(getTaskServerConfig().tools || []), + ], + }; + server = createTestServerHttp(samplingConfig); + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + sample: true, + }, + ); + await client.connect(); + + const samplingPromise = waitForEvent( + client, + "newPendingSample", + { timeout: 3000 }, + ); + const taskCreatedPromise = waitForEvent<{ taskId: string }>( + client, + "taskCreated", + { timeout: 3000 }, + ); + const taskPromise = client.callToolStream("taskWithSampling", { + message: "test", + }); + + const sample = await samplingPromise; + expect(sample).toBeDefined(); + + const taskCreatedDetail = await taskCreatedPromise; + const task = await client.getTask(taskCreatedDetail.taskId); + expect(task).toBeDefined(); + expect(task!.status).toBe("input_required"); + + // Respond to sampling with correct format + await sample.respond({ + model: "test-model", + role: "assistant", + stopReason: "endTurn", + content: { + type: "text", + text: "Sampling response", + }, + }); + + // Wait for task to complete + const result = await taskPromise; + expect(result.success).toBe(true); + }); + + it("should handle progress notifications linked to tasks", async () => { + await client.disconnect(); + await server?.stop(); + + // createProgressTaskTool defaults to 5 progress units with 2000ms delay + // Progress notifications are sent at delayMs / progressUnits intervals (400ms each) + const progressConfig = { + ...getTaskServerConfig(), + serverType: "sse" as const, + tools: [ + createProgressTaskTool("taskWithProgress", 2000, 5), + ...(getTaskServerConfig().tools || []), + ], + }; + server = createTestServerHttp(progressConfig); + await server.start(); + client = new InspectorClient( + { + type: "sse", + url: server.url, + }, + { + environment: { transport: createTransportNode }, + autoSyncLists: false, + progress: true, + }, + ); + await client.connect(); + + const progressToken = Math.random().toString(); + + const taskCreatedPromise = waitForEvent<{ taskId: string }>( + client, + "taskCreated", + { timeout: 5000 }, + ); + const progressPromise = waitForProgressCount(client, 5, { + timeout: 5000, + }); + const taskCompletedPromise = waitForEvent<{ + taskId: string; + result: unknown; + }>(client, "taskCompleted", { timeout: 5000 }); + const resultPromise = client.callToolStream( + "taskWithProgress", + { message: "test" }, + undefined, + { progressToken }, + ); + + const taskCreatedDetail = await taskCreatedPromise; + const taskId = taskCreatedDetail.taskId; + expect(taskId).toBeDefined(); + + const progressEvents = await progressPromise; + const result = await resultPromise; + const taskCompletedDetail = await taskCompletedPromise; + + // Verify task completed successfully + expect(result.success).toBe(true); + expect(result.result).toBeDefined(); + expect(result.result).not.toBeNull(); + expect(result.result).toHaveProperty("content"); + + // Validate the actual tool call response content + const toolResult = result.result!; + expect(toolResult.content).toBeDefined(); + expect(Array.isArray(toolResult.content)).toBe(true); + expect(toolResult.content.length).toBe(1); + + const firstContent = toolResult.content[0]; + expect(firstContent).toBeDefined(); + expect(firstContent).not.toBeUndefined(); + expect(firstContent!.type).toBe("text"); + + // Assert it's a text content block (for TypeScript narrowing) + expect(firstContent!.type === "text").toBe(true); + + // TypeScript type narrowing - we've already asserted it's text + if (firstContent && firstContent.type === "text") { + expect(firstContent.text).toBeDefined(); + // Parse and validate the JSON text content + const resultText = JSON.parse(firstContent.text); + expect(resultText.message).toBe("Task completed: test"); + expect(resultText.taskId).toBe(taskId); + } else { + // This should never happen due to the assertion above, but TypeScript needs it + expect(firstContent?.type).toBe("text"); + } + + expect(taskCompletedDetail.taskId).toBe(taskId); + expect(taskCompletedDetail.result).toBeDefined(); + expect(taskCompletedDetail.result).toEqual(toolResult); + + expect(progressEvents.length).toBe(5); + progressEvents.forEach((evt: unknown, index: number) => { + const event = evt as { + progressToken: string; + progress: number; + total: number; + message: string; + _meta?: Record; + }; + expect(event.progressToken).toBe(progressToken); + expect(event.progress).toBe(index + 1); + expect(event.total).toBe(5); + expect(event.message).toBe(`Processing... ${index + 1}/5`); + expect(event._meta).toBeDefined(); + expect(event._meta?.[RELATED_TASK_META_KEY]).toBeDefined(); + const relatedTask = event._meta?.[RELATED_TASK_META_KEY] as { + taskId: string; + }; + expect(relatedTask.taskId).toBe(taskId); + }); + + // Verify task is in completed state + const activeTasks = client.getClientTasks(); + const completedTask = activeTasks.find((t) => t.taskId === taskId); + expect(completedTask).toBeDefined(); + expect(completedTask!.status).toBe("completed"); + }); + + it("should handle listTasks pagination", async () => { + await client.callToolStream("simpleTask", { message: "task1" }); + await client.callToolStream("simpleTask", { message: "task2" }); + await client.callToolStream("simpleTask", { message: "task3" }); + const result = await client.listTasks(); + expect(result.tasks.length).toBeGreaterThan(0); + + // If there's a nextCursor, test pagination + if (result.nextCursor) { + const nextPage = await client.listTasks(result.nextCursor); + expect(nextPage.tasks).toBeDefined(); + expect(Array.isArray(nextPage.tasks)).toBe(true); + } + }); + }); +}); diff --git a/shared/__tests__/jsonUtils.test.ts b/shared/__tests__/jsonUtils.test.ts new file mode 100644 index 000000000..ea5050c66 --- /dev/null +++ b/shared/__tests__/jsonUtils.test.ts @@ -0,0 +1,124 @@ +import { describe, it, expect } from "vitest"; +import { + convertParameterValue, + convertToolParameters, + convertPromptArguments, +} from "../json/jsonUtils.js"; +import type { Tool } from "@modelcontextprotocol/sdk/types.js"; + +describe("JSON Utils", () => { + describe("convertParameterValue", () => { + it("should convert string to string", () => { + expect(convertParameterValue("hello", { type: "string" })).toBe("hello"); + }); + + it("should convert string to number", () => { + expect(convertParameterValue("42", { type: "number" })).toBe(42); + expect(convertParameterValue("3.14", { type: "number" })).toBe(3.14); + }); + + it("should convert string to boolean", () => { + expect(convertParameterValue("true", { type: "boolean" })).toBe(true); + expect(convertParameterValue("false", { type: "boolean" })).toBe(false); + }); + + it("should parse JSON strings", () => { + expect( + convertParameterValue('{"key":"value"}', { type: "object" }), + ).toEqual({ + key: "value", + }); + expect(convertParameterValue("[1,2,3]", { type: "array" })).toEqual([ + 1, 2, 3, + ]); + }); + + it("should return string for unknown types", () => { + expect(convertParameterValue("hello", { type: "unknown" })).toBe("hello"); + }); + }); + + describe("convertToolParameters", () => { + const tool: Tool = { + name: "test-tool", + description: "Test tool", + inputSchema: { + type: "object", + properties: { + message: { type: "string" }, + count: { type: "number" }, + enabled: { type: "boolean" }, + }, + }, + }; + + it("should convert string parameters", () => { + const result = convertToolParameters(tool, { + message: "hello", + count: "42", + enabled: "true", + }); + + expect(result.message).toBe("hello"); + expect(result.count).toBe(42); + expect(result.enabled).toBe(true); + }); + + it("should preserve non-string values", () => { + const result = convertToolParameters(tool, { + message: "hello", + count: "42", // Still pass as string, conversion will handle it + enabled: "true", // Still pass as string, conversion will handle it + }); + + expect(result.message).toBe("hello"); + expect(result.count).toBe(42); + expect(result.enabled).toBe(true); + }); + + it("should handle missing schema", () => { + const toolWithoutSchema: Tool = { + name: "test-tool", + description: "Test tool", + inputSchema: { + type: "object", + properties: {}, + }, + }; + + const result = convertToolParameters(toolWithoutSchema, { + message: "hello", + }); + + expect(result.message).toBe("hello"); + }); + }); + + describe("convertPromptArguments", () => { + it("should convert values to strings", () => { + const result = convertPromptArguments({ + name: "John", + age: 42, + active: true, + data: { key: "value" }, + items: [1, 2, 3], + }); + + expect(result.name).toBe("John"); + expect(result.age).toBe("42"); + expect(result.active).toBe("true"); + expect(result.data).toBe('{"key":"value"}'); + expect(result.items).toBe("[1,2,3]"); + }); + + it("should handle null and undefined", () => { + const result = convertPromptArguments({ + value: null, + missing: undefined, + }); + + expect(result.value).toBe("null"); + expect(result.missing).toBe("undefined"); + }); + }); +}); diff --git a/shared/__tests__/remote-transport.test.ts b/shared/__tests__/remote-transport.test.ts new file mode 100644 index 000000000..7f7fbfe94 --- /dev/null +++ b/shared/__tests__/remote-transport.test.ts @@ -0,0 +1,934 @@ +/** + * E2E tests for remote transport (stdio, SSE, streamable-http). + * Verifies connection, tools, fetch tracking, stderr logging, and remote logging over the remote. + */ + +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { serve } from "@hono/node-server"; +import type { ServerType } from "@hono/node-server"; +import pino from "pino"; +import { InspectorClient } from "../mcp/inspectorClient.js"; +import { createRemoteTransport } from "../mcp/remote/createRemoteTransport.js"; +import { createRemoteLogger } from "../mcp/remote/createRemoteLogger.js"; +import { createRemoteApp } from "../mcp/remote/node/server.js"; +import { createTestServerHttp } from "../test/test-server-http.js"; +import { getTestMcpServerCommand } from "../test/test-server-stdio.js"; +import { + createEchoTool, + createTestServerInfo, +} from "../test/test-server-fixtures.js"; +import type { MCPServerConfig } from "../mcp/types.js"; + +interface StartRemoteServerOptions { + logger?: pino.Logger; + storageDir?: string; + allowedOrigins?: string[]; +} + +async function startRemoteServer( + port: number, + options: StartRemoteServerOptions = {}, +): Promise<{ + baseUrl: string; + server: ServerType; + authToken: string; +}> { + const { app, authToken } = createRemoteApp({ + logger: options.logger, + storageDir: options.storageDir, + allowedOrigins: options.allowedOrigins, + }); + return new Promise((resolve, reject) => { + const server = serve( + { fetch: app.fetch, port, hostname: "127.0.0.1" }, + (info) => { + const actualPort = + info && typeof info === "object" && "port" in info + ? (info as { port: number }).port + : port; + resolve({ + baseUrl: `http://127.0.0.1:${actualPort}`, + server, + authToken, + }); + }, + ); + server.on("error", reject); + }); +} + +describe("Remote transport e2e", () => { + let remoteServer: ServerType | null; + let mcpHttpServer: Awaited> | null; + + beforeEach(() => { + remoteServer = null; + mcpHttpServer = null; + }); + + afterEach(async () => { + if (remoteServer) { + await new Promise((resolve, reject) => { + remoteServer!.close((err) => (err ? reject(err) : resolve())); + }); + remoteServer = null; + } + if (mcpHttpServer) { + try { + await mcpHttpServer.stop(); + } catch { + // Ignore stop errors + } + mcpHttpServer = null; + } + }); + + async function setupRemoteAndConnect( + config: MCPServerConfig, + ): Promise { + const { baseUrl, server, authToken } = await startRemoteServer(0); + remoteServer = server; + + const createTransport = createRemoteTransport({ baseUrl, authToken }); + const client = new InspectorClient(config, { + environment: { + transport: createTransport, + }, + autoSyncLists: false, + maxMessages: 100, + maxFetchRequests: 100, + maxStderrLogEvents: 100, + pipeStderr: true, + }); + + await client.connect(); + + return client; + } + + it("smoke: remote server accepts connect and returns sessionId for SSE", async () => { + mcpHttpServer = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "sse", + }); + await mcpHttpServer.start(); + + const { baseUrl, server, authToken } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: mcpHttpServer!.url }, + }), + }); + + const json = (await res.json()) as { sessionId?: string; error?: string }; + if (!res.ok) { + throw new Error( + `Connect failed: ${res.status} ${json.error ?? (await res.text())}`, + ); + } + expect(json.sessionId).toBeDefined(); + expect(typeof json.sessionId).toBe("string"); + }); + + describe("stdio", () => { + it("connects, lists tools, and forwards stderr over remote", async () => { + const serverCommand = getTestMcpServerCommand(); + const config: MCPServerConfig = { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }; + + const client = await setupRemoteAndConnect(config); + + try { + expect(client.getStatus()).toBe("connected"); + + const tools = await client.listTools(); + expect(tools.tools.length).toBeGreaterThan(0); + expect(tools.tools.some((t) => t.name === "echo")).toBe(true); + + // Stdio server may emit stderr (e.g. from MCP logging). We verify the + // mechanism works; some servers may not produce stderr. + const stderrLogs = client.getStderrLogs(); + expect(Array.isArray(stderrLogs)).toBe(true); + } finally { + await client.disconnect(); + } + }); + + it("validates stderr content over remote stdio", async () => { + const serverCommand = getTestMcpServerCommand(); + const config: MCPServerConfig = { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }; + + const client = await setupRemoteAndConnect(config); + + try { + const testMessage = `stderr-remote-${Date.now()}`; + await client.callTool("writeToStderr", { message: testMessage }); + + const stderrLogs = client.getStderrLogs(); + expect(Array.isArray(stderrLogs)).toBe(true); + const matching = stderrLogs.filter((l) => + l.message.includes(testMessage), + ); + expect(matching.length).toBeGreaterThan(0); + expect(matching[0]!.message).toContain(testMessage); + } finally { + await client.disconnect(); + } + }); + + it("calls a tool over remote stdio", async () => { + const serverCommand = getTestMcpServerCommand(); + const config: MCPServerConfig = { + type: "stdio", + command: serverCommand.command, + args: serverCommand.args, + }; + + const client = await setupRemoteAndConnect(config); + + try { + const invocation = await client.callTool("echo", { + message: "hello-remote", + }); + expect(invocation.result?.content).toBeDefined(); + const textContent = invocation.result?.content?.find( + (c: { type: string }) => c.type === "text", + ); + expect(textContent).toBeDefined(); + expect((textContent as { type: "text"; text: string }).text).toContain( + "Echo: hello-remote", + ); + } finally { + await client.disconnect(); + } + }); + }); + + describe("SSE", () => { + it("connects, lists tools, and receives fetch_request events over remote", async () => { + mcpHttpServer = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "sse", + }); + await mcpHttpServer.start(); + + const config: MCPServerConfig = { + type: "sse", + url: mcpHttpServer.url, + }; + + const client = await setupRemoteAndConnect(config); + + try { + expect(client.getStatus()).toBe("connected"); + + await client.listTools(); + + // Fetch tracking: remote server applies createFetchTracker when creating + // the transport; it emits fetch_request events over SSE to the client. + const fetchRequests = client.getFetchRequests(); + expect(fetchRequests.length).toBeGreaterThan(0); + const getRequest = fetchRequests.find((r) => r.method === "GET"); + expect(getRequest).toBeDefined(); + if (getRequest) { + expect(getRequest.url).toContain("/sse"); + expect(getRequest.requestHeaders).toBeDefined(); + expect(getRequest.responseStatus).toBeDefined(); + } + } finally { + await client.disconnect(); + } + }); + + it("calls a tool over remote SSE", async () => { + mcpHttpServer = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "sse", + }); + await mcpHttpServer.start(); + + const config: MCPServerConfig = { + type: "sse", + url: mcpHttpServer.url, + }; + + const client = await setupRemoteAndConnect(config); + + try { + const invocation = await client.callTool("echo", { + message: "sse-test", + }); + expect(invocation.result?.content).toBeDefined(); + const textContent = invocation.result?.content?.find( + (c: { type: string }) => c.type === "text", + ); + expect((textContent as { type: "text"; text: string }).text).toContain( + "Echo: sse-test", + ); + } finally { + await client.disconnect(); + } + }); + }); + + describe("streamable-http", () => { + it("connects, lists tools, and receives fetch_request events over remote", async () => { + mcpHttpServer = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "streamable-http", + }); + await mcpHttpServer.start(); + + const config: MCPServerConfig = { + type: "streamable-http", + url: mcpHttpServer.url, + }; + + const client = await setupRemoteAndConnect(config); + + try { + expect(client.getStatus()).toBe("connected"); + + await client.listTools(); + + const fetchRequests = client.getFetchRequests(); + expect(fetchRequests.length).toBeGreaterThan(0); + const postRequest = fetchRequests.find((r) => r.method === "POST"); + expect(postRequest).toBeDefined(); + if (postRequest) { + expect(postRequest.url).toContain("/mcp"); + expect(postRequest.requestHeaders).toBeDefined(); + expect(postRequest.responseStatus).toBeDefined(); + expect(postRequest.responseHeaders).toBeDefined(); + expect(postRequest.duration).toBeDefined(); + } + } finally { + await client.disconnect(); + } + }); + + it("calls a tool over remote streamable-http", async () => { + mcpHttpServer = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "streamable-http", + }); + await mcpHttpServer.start(); + + const config: MCPServerConfig = { + type: "streamable-http", + url: mcpHttpServer.url, + }; + + const client = await setupRemoteAndConnect(config); + + try { + const invocation = await client.callTool("echo", { + message: "streamable-http-test", + }); + expect(invocation.result?.content).toBeDefined(); + const textContent = invocation.result?.content?.find( + (c: { type: string }) => c.type === "text", + ); + expect((textContent as { type: "text"; text: string }).text).toContain( + "Echo: streamable-http-test", + ); + } finally { + await client.disconnect(); + } + }); + }); + + describe("authentication", () => { + it("rejects requests without auth token", async () => { + const { baseUrl, server } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + expect(json.message).toContain("x-mcp-remote-auth"); + }); + + it("rejects requests with incorrect auth token", async () => { + const { baseUrl, server, authToken } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer wrong-token-${authToken}`, + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + + it("rejects requests without Bearer prefix", async () => { + const { baseUrl, server, authToken } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": authToken, // Missing "Bearer " prefix + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + + it("rejects requests to /api/fetch without auth token", async () => { + const { baseUrl, server } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/fetch`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ url: "http://example.com" }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + + it("rejects requests to /api/log without auth token", async () => { + const { baseUrl, server } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/log`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ level: { label: "info" }, messages: ["test"] }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + + it("rejects requests to /api/mcp/send without auth token", async () => { + const { baseUrl, server } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/send`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + sessionId: "test-session", + message: { jsonrpc: "2.0", method: "test", id: 1 }, + }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + + it("rejects requests to /api/mcp/events without auth token", async () => { + const { baseUrl, server } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/events?sessionId=test`, { + method: "GET", + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + + it("rejects requests to /api/mcp/disconnect without auth token", async () => { + const { baseUrl, server } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/disconnect`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ sessionId: "test-session" }), + }); + + expect(res.status).toBe(401); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Unauthorized"); + }); + }); + + describe("remote logging", () => { + let tempDir: string | null = null; + + afterEach(() => { + if (tempDir) { + try { + rmSync(tempDir, { recursive: true }); + } catch { + // Ignore cleanup errors + } + tempDir = null; + } + }); + + it("writes InspectorClient logs to file via createRemoteLogger over remote transport", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-log-test-")); + const logPath = join(tempDir!, "remote.log"); + const fileLogger = pino( + { level: "info" }, + pino.destination({ dest: logPath, append: true, mkdir: true }), + ); + + mcpHttpServer = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "sse", + }); + await mcpHttpServer.start(); + + const { baseUrl, server, authToken } = await startRemoteServer(0, { + logger: fileLogger, + }); + remoteServer = server; + + const createTransport = createRemoteTransport({ + baseUrl, + authToken, + }); + const remoteLogger = createRemoteLogger({ + baseUrl, + authToken, + fetchFn: fetch, + }); + const client = new InspectorClient( + { type: "sse", url: mcpHttpServer!.url }, + { + environment: { + transport: createTransport, + logger: remoteLogger, + }, + autoSyncLists: false, + maxMessages: 100, + maxFetchRequests: 100, + maxStderrLogEvents: 100, + pipeStderr: true, + }, + ); + + await client.connect(); + await client.listTools(); + + // Wait for async log POSTs to complete and file logger to flush + await new Promise((resolve) => { + fileLogger.flush(() => resolve()); + }); + await new Promise((r) => setTimeout(r, 300)); + + const logContent = readFileSync(logPath, "utf-8"); + expect(logContent).toContain("transport fetch"); + expect(logContent).toContain("InspectorClient"); + expect(logContent).toContain("component"); + expect(logContent).toContain("category"); + + await client.disconnect(); + }); + }); + + describe("storage", () => { + let tempDir: string | null = null; + + beforeEach(() => { + tempDir = null; + }); + + afterEach(async () => { + if (tempDir) { + try { + rmSync(tempDir, { recursive: true }); + } catch { + // Ignore cleanup errors + } + tempDir = null; + } + }); + + it("returns empty object for non-existent store", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + + expect(res.status).toBe(200); + const json = await res.json(); + expect(json).toEqual({}); + }); + + it("reads and writes store data", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const testData = { key1: "value1", key2: { nested: "value" } }; + + // Write store + const writeRes = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + body: JSON.stringify(testData), + }); + + expect(writeRes.status).toBe(200); + const writeJson = await writeRes.json(); + expect(writeJson).toEqual({ ok: true }); + + // Read store + const readRes = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + + expect(readRes.status).toBe(200); + const readJson = await readRes.json(); + expect(readJson).toEqual(testData); + }); + + it("overwrites store on POST", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const initialData = { key1: "value1" }; + const updatedData = { key2: "value2" }; + + // Write initial data + await fetch(`${baseUrl}/api/storage/test-store`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + body: JSON.stringify(initialData), + }); + + // Overwrite with new data + await fetch(`${baseUrl}/api/storage/test-store`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + body: JSON.stringify(updatedData), + }); + + // Read and verify overwrite + const readRes = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + + expect(readRes.status).toBe(200); + const readJson = await readRes.json(); + expect(readJson).toEqual(updatedData); + expect(readJson).not.toEqual(initialData); + }); + + it("rejects invalid storeId", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + // Test invalid characters (not alphanumeric, hyphen, underscore) + const res = await fetch(`${baseUrl}/api/storage/invalid.store.id`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + + expect(res.status).toBe(400); + const json = await res.json(); + expect(json.error).toBe("Invalid storeId"); + }); + + it("rejects requests without auth token", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + }); + + expect(res.status).toBe(401); + const json = await res.json(); + expect(json.error).toBe("Unauthorized"); + }); + + it("deletes store with DELETE endpoint", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const testData = { key1: "value1" }; + + // Write store + await fetch(`${baseUrl}/api/storage/test-store`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + body: JSON.stringify(testData), + }); + + // Verify it exists + const readRes = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(readRes.status).toBe(200); + const readJson = await readRes.json(); + expect(readJson).toEqual(testData); + + // Delete store + const deleteRes = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "DELETE", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(deleteRes.status).toBe(200); + const deleteJson = await deleteRes.json(); + expect(deleteJson).toEqual({ ok: true }); + + // Verify it's gone (returns empty object) + const readAfterDelete = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(readAfterDelete.status).toBe(200); + const readAfterDeleteJson = await readAfterDelete.json(); + expect(readAfterDeleteJson).toEqual({}); + }); + + it("DELETE returns success for non-existent store", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const deleteRes = await fetch(`${baseUrl}/api/storage/non-existent`, { + method: "DELETE", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(deleteRes.status).toBe(200); + const deleteJson = await deleteRes.json(); + expect(deleteJson).toEqual({ ok: true }); + }); + }); + + describe("Origin validation", () => { + it("allows requests with valid origin", async () => { + const { baseUrl, server, authToken } = await startRemoteServer(0, { + allowedOrigins: ["http://localhost:3000"], + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + Origin: "http://localhost:3000", + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + // Should not be blocked by origin validation (may fail for other reasons) + expect(res.status).not.toBe(403); + const json = (await res.json()) as { error?: string }; + // Should not be "Forbidden" due to origin + expect(json.error).not.toBe("Forbidden"); + }); + + it("blocks requests with invalid origin", async () => { + const { baseUrl, server, authToken } = await startRemoteServer(0, { + allowedOrigins: ["http://localhost:3000"], + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + Origin: "http://evil.com", + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + expect(res.status).toBe(403); + const json = (await res.json()) as { error?: string; message?: string }; + expect(json.error).toBe("Forbidden"); + expect(json.message).toContain("Invalid origin"); + }); + + it("allows requests without origin header (same-origin or non-browser)", async () => { + const { baseUrl, server, authToken } = await startRemoteServer(0, { + allowedOrigins: ["http://localhost:3000"], + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + // No Origin header + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + // Should not be blocked by origin validation + expect(res.status).not.toBe(403); + }); + + it("handles CORS preflight requests with valid origin", async () => { + const { baseUrl, server } = await startRemoteServer(0, { + allowedOrigins: ["http://localhost:3000"], + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "OPTIONS", + headers: { + Origin: "http://localhost:3000", + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type,x-mcp-remote-auth", + }, + }); + + expect(res.status).toBe(204); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe( + "http://localhost:3000", + ); + expect(res.headers.get("Access-Control-Allow-Methods")).toContain("POST"); + }); + + it("blocks CORS preflight requests with invalid origin", async () => { + const { baseUrl, server } = await startRemoteServer(0, { + allowedOrigins: ["http://localhost:3000"], + }); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "OPTIONS", + headers: { + Origin: "http://evil.com", + "Access-Control-Request-Method": "POST", + }, + }); + + expect(res.status).toBe(403); + const json = (await res.json()) as { error?: string }; + expect(json.error).toBe("Forbidden"); + }); + + it("allows all origins when allowedOrigins is not configured", async () => { + const { baseUrl, server, authToken } = await startRemoteServer(0); + remoteServer = server; + + const res = await fetch(`${baseUrl}/api/mcp/connect`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-mcp-remote-auth": `Bearer ${authToken}`, + Origin: "http://any-origin.com", + }, + body: JSON.stringify({ + config: { type: "sse" as const, url: "http://localhost:3000" }, + }), + }); + + // Should not be blocked by origin validation + expect(res.status).not.toBe(403); + }); + }); +}); diff --git a/shared/__tests__/storage-adapters.test.ts b/shared/__tests__/storage-adapters.test.ts new file mode 100644 index 000000000..7826b7abe --- /dev/null +++ b/shared/__tests__/storage-adapters.test.ts @@ -0,0 +1,290 @@ +/** + * Tests for storage adapters (file, remote). + */ + +import { describe, it, expect, beforeEach, afterEach } from "vitest"; +import { mkdtempSync, readFileSync, rmSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { serve } from "@hono/node-server"; +import type { ServerType } from "@hono/node-server"; +import { createFileStorageAdapter } from "../storage/adapters/file-storage.js"; +import { createRemoteStorageAdapter } from "../storage/adapters/remote-storage.js"; +import { createOAuthStore } from "../auth/store.js"; +import { createRemoteApp } from "../mcp/remote/node/server.js"; + +interface StartRemoteServerOptions { + storageDir?: string; +} + +async function startRemoteServer( + port: number, + options: StartRemoteServerOptions = {}, +): Promise<{ + baseUrl: string; + server: ServerType; + authToken: string; +}> { + const { app, authToken } = createRemoteApp({ + storageDir: options.storageDir, + }); + return new Promise((resolve, reject) => { + const server = serve( + { fetch: app.fetch, port, hostname: "127.0.0.1" }, + (info) => { + const actualPort = + info && typeof info === "object" && "port" in info + ? (info as { port: number }).port + : port; + resolve({ + baseUrl: `http://127.0.0.1:${actualPort}`, + server, + authToken, + }); + }, + ); + server.on("error", reject); + }); +} + +describe("Storage adapters", () => { + describe("FileStorageAdapter", () => { + let tempDir: string | null = null; + + afterEach(() => { + if (tempDir) { + try { + rmSync(tempDir, { recursive: true }); + } catch { + // Ignore cleanup errors + } + tempDir = null; + } + }); + + it("creates store and persists state", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const filePath = join(tempDir!, "test-store.json"); + const storage = createFileStorageAdapter({ filePath }); + const store = createOAuthStore(storage); + + // Set some state + store.getState().setServerState("https://example.com", { + tokens: { access_token: "test-token", token_type: "Bearer" }, + }); + + // Wait for persistence + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify file exists and contains state + expect(existsSync(filePath)).toBe(true); + const fileContent = readFileSync(filePath, "utf-8"); + const parsed = JSON.parse(fileContent); + expect(parsed.state.servers["https://example.com"].tokens).toEqual({ + access_token: "test-token", + token_type: "Bearer", + }); + }); + + it("loads persisted state on initialization", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const filePath = join( + tmpdir(), + "inspector-storage-test-", + "test-store.json", + ); + + // Create initial store and persist + const storage1 = createFileStorageAdapter({ filePath }); + const store1 = createOAuthStore(storage1); + store1.getState().setServerState("https://example.com", { + tokens: { access_token: "initial-token", token_type: "Bearer" }, + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Create new store instance (should load persisted state) + const storage2 = createFileStorageAdapter({ filePath }); + const store2 = createOAuthStore(storage2); + await new Promise((resolve) => setTimeout(resolve, 100)); + + const state = store2.getState().getServerState("https://example.com"); + expect(state.tokens).toEqual({ + access_token: "initial-token", + token_type: "Bearer", + }); + }); + + it("handles empty state after clear", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const filePath = join(tempDir!, "test-store.json"); + const storage = createFileStorageAdapter({ filePath }); + const store = createOAuthStore(storage); + + // Set state and persist + store.getState().setServerState("https://example.com", { + tokens: { access_token: "test-token", token_type: "Bearer" }, + }); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(existsSync(filePath)).toBe(true); + + // Clear all servers (this will persist empty state) + const state = store.getState(); + const urls = Object.keys(state.servers); + for (const url of urls) { + state.clearServerState(url); + } + await new Promise((resolve) => setTimeout(resolve, 100)); + + // Verify file still exists but with empty servers + expect(existsSync(filePath)).toBe(true); + const fileContent = readFileSync(filePath, "utf-8"); + const parsed = JSON.parse(fileContent); + expect(Object.keys(parsed.state.servers).length).toBe(0); + }); + }); + + describe("RemoteStorageAdapter", () => { + let remoteServer: ServerType | null = null; + let tempDir: string | null = null; + + afterEach(async () => { + if (remoteServer) { + await new Promise((resolve, reject) => { + remoteServer!.close((err) => (err ? reject(err) : resolve())); + }); + remoteServer = null; + } + if (tempDir) { + try { + rmSync(tempDir, { recursive: true }); + } catch { + // Ignore cleanup errors + } + tempDir = null; + } + }); + + it("creates store and persists state via HTTP", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const storage = createRemoteStorageAdapter({ + baseUrl, + storeId: "test-store", + authToken, + }); + const store = createOAuthStore(storage); + + // Set some state + store.getState().setServerState("https://example.com", { + tokens: { access_token: "test-token", token_type: "Bearer" }, + }); + + // Wait for persistence + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Verify via API + const res = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(res.status).toBe(200); + const storeData = await res.json(); + expect(storeData.state.servers["https://example.com"].tokens).toEqual({ + access_token: "test-token", + token_type: "Bearer", + }); + }); + + it("loads persisted state on initialization", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + // Create initial store and persist + const storage1 = createRemoteStorageAdapter({ + baseUrl, + storeId: "test-store", + authToken, + }); + const store1 = createOAuthStore(storage1); + store1.getState().setServerState("https://example.com", { + tokens: { access_token: "initial-token", token_type: "Bearer" }, + }); + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Create new store instance (should load persisted state) + const storage2 = createRemoteStorageAdapter({ + baseUrl, + storeId: "test-store", + authToken, + }); + const store2 = createOAuthStore(storage2); + await new Promise((resolve) => setTimeout(resolve, 200)); + + const state = store2.getState().getServerState("https://example.com"); + expect(state.tokens).toEqual({ + access_token: "initial-token", + token_type: "Bearer", + }); + }); + + it("handles empty state after clear", async () => { + tempDir = mkdtempSync(join(tmpdir(), "inspector-storage-test-")); + const { baseUrl, server, authToken } = await startRemoteServer(0, { + storageDir: tempDir, + }); + remoteServer = server; + + const storage = createRemoteStorageAdapter({ + baseUrl, + storeId: "test-store", + authToken, + }); + const store = createOAuthStore(storage); + + // Set state and persist + store.getState().setServerState("https://example.com", { + tokens: { access_token: "test-token", token_type: "Bearer" }, + }); + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Verify it exists + let res = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(res.status).toBe(200); + const storeData = await res.json(); + expect(Object.keys(storeData.state.servers).length).toBeGreaterThan(0); + + // Clear all servers (this will persist empty state) + const state = store.getState(); + const urls = Object.keys(state.servers); + for (const url of urls) { + state.clearServerState(url); + } + await new Promise((resolve) => setTimeout(resolve, 200)); + + // Verify it's empty + res = await fetch(`${baseUrl}/api/storage/test-store`, { + method: "GET", + headers: { + "x-mcp-remote-auth": `Bearer ${authToken}`, + }, + }); + expect(res.status).toBe(200); + const emptyStore = await res.json(); + expect(Object.keys(emptyStore.state.servers).length).toBe(0); + }); + }); +}); diff --git a/shared/__tests__/transport.test.ts b/shared/__tests__/transport.test.ts new file mode 100644 index 000000000..0d65d9e5b --- /dev/null +++ b/shared/__tests__/transport.test.ts @@ -0,0 +1,192 @@ +import { describe, it, expect } from "vitest"; +import { getServerType } from "../mcp/config.js"; +import { createTransportNode } from "../mcp/node/transport.js"; +import type { MCPServerConfig } from "../mcp/types.js"; +import { createTestServerHttp } from "../test/test-server-http.js"; +import { + createEchoTool, + createTestServerInfo, +} from "../test/test-server-fixtures.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; + +describe("Transport", () => { + describe("getServerType", () => { + it("should return stdio for stdio config", () => { + const config: MCPServerConfig = { + type: "stdio", + command: "echo", + args: ["hello"], + }; + expect(getServerType(config)).toBe("stdio"); + }); + + it("should return sse for sse config", () => { + const config: MCPServerConfig = { + type: "sse", + url: "http://localhost:3000/sse", + }; + expect(getServerType(config)).toBe("sse"); + }); + + it("should return streamable-http for streamable-http config", () => { + const config: MCPServerConfig = { + type: "streamable-http", + url: "http://localhost:3000/mcp", + }; + expect(getServerType(config)).toBe("streamable-http"); + }); + + it("should default to stdio when type is not present", () => { + const config: MCPServerConfig = { + command: "echo", + args: ["hello"], + }; + expect(getServerType(config)).toBe("stdio"); + }); + + it("should throw error for invalid type", () => { + const config = { + type: "invalid", + command: "echo", + } as unknown as MCPServerConfig; + expect(() => getServerType(config)).toThrow(); + }); + }); + + describe("createTransport", () => { + it("should create stdio transport", () => { + const config: MCPServerConfig = { + type: "stdio", + command: "echo", + args: ["hello"], + }; + const result = createTransportNode(config); + expect(result.transport).toBeDefined(); + }); + + it("should create SSE transport", () => { + const config: MCPServerConfig = { + type: "sse", + url: "http://localhost:3000/sse", + }; + const result = createTransportNode(config); + expect(result.transport).toBeDefined(); + }); + + it("should create streamable-http transport", () => { + const config: MCPServerConfig = { + type: "streamable-http", + url: "http://localhost:3000/mcp", + }; + const result = createTransportNode(config); + expect(result.transport).toBeDefined(); + }); + + it("should call onFetchRequest callback for SSE transport", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "sse", + }); + + try { + await server.start(); + + const config: MCPServerConfig = { + type: "sse", + url: server.url, + }; + + const fetchRequests: any[] = []; + const result = createTransportNode(config, { + onFetchRequest: (entry) => { + fetchRequests.push(entry); + }, + }); + + expect(result.transport).toBeDefined(); + + // Actually connect and make a request to verify fetch tracking works + const client = new Client( + { + name: "test-client", + version: "1.0.0", + }, + { + capabilities: {}, + }, + ); + + await client.connect(result.transport); + await client.listTools(); + await client.close(); + + // Verify fetch requests were tracked + expect(fetchRequests.length).toBeGreaterThan(0); + // SSE uses GET for the initial connection + const getRequest = fetchRequests.find((r) => r.method === "GET"); + expect(getRequest).toBeDefined(); + if (getRequest) { + expect(getRequest.url).toContain("/sse"); + expect(getRequest.requestHeaders).toBeDefined(); + } + } finally { + await server.stop(); + } + }); + + it("should call onFetchRequest callback for streamable-http transport", async () => { + const server = createTestServerHttp({ + serverInfo: createTestServerInfo(), + tools: [createEchoTool()], + serverType: "streamable-http", + }); + + try { + await server.start(); + + const config: MCPServerConfig = { + type: "streamable-http", + url: server.url, + }; + + const fetchRequests: any[] = []; + const result = createTransportNode(config, { + onFetchRequest: (entry) => { + fetchRequests.push(entry); + }, + }); + + expect(result.transport).toBeDefined(); + + // Actually connect and make a request to verify fetch tracking works + const client = new Client( + { + name: "test-client", + version: "1.0.0", + }, + { + capabilities: {}, + }, + ); + + await client.connect(result.transport); + await client.listTools(); + await client.close(); + + // Verify fetch requests were tracked + expect(fetchRequests.length).toBeGreaterThan(0); + const request = fetchRequests[0]; + expect(request).toBeDefined(); + expect(request.url).toContain("/mcp"); + expect(request.method).toBe("POST"); + expect(request.requestHeaders).toBeDefined(); + expect(request.responseStatus).toBeDefined(); + expect(request.responseHeaders).toBeDefined(); + expect(request.duration).toBeDefined(); + } finally { + await server.stop(); + } + }); + }); +}); diff --git a/shared/auth/browser/index.ts b/shared/auth/browser/index.ts new file mode 100644 index 000000000..e0fd34111 --- /dev/null +++ b/shared/auth/browser/index.ts @@ -0,0 +1,3 @@ +export { BrowserOAuthStorage } from "./storage.js"; +export { BrowserNavigation, BrowserOAuthClientProvider } from "./providers.js"; +export type { OAuthNavigationCallback } from "./providers.js"; diff --git a/shared/auth/browser/providers.ts b/shared/auth/browser/providers.ts new file mode 100644 index 000000000..75ab1f2d6 --- /dev/null +++ b/shared/auth/browser/providers.ts @@ -0,0 +1,47 @@ +import type { + RedirectUrlProvider, + OAuthNavigationCallback, +} from "../providers.js"; +import { CallbackNavigation, BaseOAuthClientProvider } from "../providers.js"; +import { BrowserOAuthStorage } from "./storage.js"; + +export type { OAuthNavigationCallback } from "../providers.js"; + +/** + * Browser navigation handler + * Redirects the browser window to the authorization URL, optionally invokes an + * extra callback. + */ +export class BrowserNavigation extends CallbackNavigation { + constructor(callback?: OAuthNavigationCallback) { + super((url) => { + if (typeof window === "undefined") { + throw new Error("BrowserNavigation requires browser environment"); + } + window.location.href = url.href; + return callback?.(url); + }); + } +} + +/** + * Browser OAuth client provider + * Uses sessionStorage directly (for web client reference) + */ +export class BrowserOAuthClientProvider extends BaseOAuthClientProvider { + constructor(serverUrl: string) { + if (typeof window === "undefined") { + throw new Error( + "BrowserOAuthClientProvider requires browser environment", + ); + } + const storage = new BrowserOAuthStorage(); + const redirectUrlProvider: RedirectUrlProvider = { + getRedirectUrl: (_mode: "normal" | "guided") => + `${window.location.origin}/oauth/callback`, + }; + const navigation = new BrowserNavigation(); + + super(serverUrl, { storage, redirectUrlProvider, navigation }, "normal"); + } +} diff --git a/shared/auth/browser/storage.ts b/shared/auth/browser/storage.ts new file mode 100644 index 000000000..3d546c5a4 --- /dev/null +++ b/shared/auth/browser/storage.ts @@ -0,0 +1,145 @@ +import { createJSONStorage } from "zustand/middleware"; +import type { OAuthStorage } from "../storage.js"; +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { + OAuthClientInformationSchema, + OAuthTokensSchema, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { createOAuthStore, type ServerOAuthState } from "../store.js"; + +/** + * Browser storage implementation using Zustand with sessionStorage. + * For web client (can be used by InspectorClient in browser). + */ +export class BrowserOAuthStorage implements OAuthStorage { + private store: ReturnType; + + constructor() { + // Use Zustand's built-in sessionStorage adapter + // The `name` option in persist() ("mcp-inspector-oauth") becomes the sessionStorage key + const storage = createJSONStorage(() => sessionStorage); + this.store = createOAuthStore(storage); + } + async getClientInformation( + serverUrl: string, + isPreregistered?: boolean, + ): Promise { + const state = this.store.getState().getServerState(serverUrl); + const clientInfo = isPreregistered + ? state.preregisteredClientInformation + : state.clientInformation; + + if (!clientInfo) { + return undefined; + } + + return await OAuthClientInformationSchema.parseAsync(clientInfo); + } + + async saveClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise { + this.store.getState().setServerState(serverUrl, { + clientInformation, + }); + } + + async savePreregisteredClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise { + this.store.getState().setServerState(serverUrl, { + preregisteredClientInformation: clientInformation, + }); + } + + clearClientInformation(serverUrl: string, isPreregistered?: boolean): void { + const state = this.store.getState().getServerState(serverUrl); + const updates: Partial = {}; + + if (isPreregistered) { + updates.preregisteredClientInformation = undefined; + } else { + updates.clientInformation = undefined; + } + + this.store.getState().setServerState(serverUrl, updates); + } + + async getTokens(serverUrl: string): Promise { + const state = this.store.getState().getServerState(serverUrl); + if (!state.tokens) { + return undefined; + } + + return await OAuthTokensSchema.parseAsync(state.tokens); + } + + async saveTokens(serverUrl: string, tokens: OAuthTokens): Promise { + this.store.getState().setServerState(serverUrl, { tokens }); + } + + clearTokens(serverUrl: string): void { + this.store.getState().setServerState(serverUrl, { tokens: undefined }); + } + + getCodeVerifier(serverUrl: string): string | undefined { + const state = this.store.getState().getServerState(serverUrl); + return state.codeVerifier; + } + + async saveCodeVerifier( + serverUrl: string, + codeVerifier: string, + ): Promise { + this.store.getState().setServerState(serverUrl, { codeVerifier }); + } + + clearCodeVerifier(serverUrl: string): void { + this.store + .getState() + .setServerState(serverUrl, { codeVerifier: undefined }); + } + + getScope(serverUrl: string): string | undefined { + const state = this.store.getState().getServerState(serverUrl); + return state.scope; + } + + async saveScope(serverUrl: string, scope: string | undefined): Promise { + this.store.getState().setServerState(serverUrl, { scope }); + } + + clearScope(serverUrl: string): void { + this.store.getState().setServerState(serverUrl, { scope: undefined }); + } + + getServerMetadata(serverUrl: string): OAuthMetadata | null { + const state = this.store.getState().getServerState(serverUrl); + return state.serverMetadata || null; + } + + async saveServerMetadata( + serverUrl: string, + metadata: OAuthMetadata, + ): Promise { + this.store + .getState() + .setServerState(serverUrl, { serverMetadata: metadata }); + } + + clearServerMetadata(serverUrl: string): void { + this.store + .getState() + .setServerState(serverUrl, { serverMetadata: undefined }); + } + + clear(serverUrl: string): void { + this.store.getState().clearServerState(serverUrl); + } +} diff --git a/shared/auth/discovery.ts b/shared/auth/discovery.ts new file mode 100644 index 000000000..1bf25de1c --- /dev/null +++ b/shared/auth/discovery.ts @@ -0,0 +1,37 @@ +import { discoverAuthorizationServerMetadata } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { OAuthProtectedResourceMetadata } from "@modelcontextprotocol/sdk/shared/auth.js"; + +/** + * Discovers OAuth scopes from server metadata, with preference for resource metadata scopes + * @param serverUrl - The MCP server URL + * @param resourceMetadata - Optional resource metadata containing preferred scopes + * @param fetchFn - Optional fetch function for HTTP requests (e.g. proxy fetch in browser) + * @returns Promise resolving to space-separated scope string or undefined + */ +export const discoverScopes = async ( + serverUrl: string, + resourceMetadata?: OAuthProtectedResourceMetadata, + fetchFn?: typeof fetch, +): Promise => { + try { + const metadata = await discoverAuthorizationServerMetadata( + new URL("/", serverUrl), + { fetchFn }, + ); + + // Prefer resource metadata scopes, but fall back to OAuth metadata if empty + const resourceScopes = resourceMetadata?.scopes_supported; + const oauthScopes = metadata?.scopes_supported; + + const scopesSupported = + resourceScopes && resourceScopes.length > 0 + ? resourceScopes + : oauthScopes; + + return scopesSupported && scopesSupported.length > 0 + ? scopesSupported.join(" ") + : undefined; + } catch (error) { + return undefined; + } +}; diff --git a/shared/auth/index.ts b/shared/auth/index.ts new file mode 100644 index 000000000..01befea1e --- /dev/null +++ b/shared/auth/index.ts @@ -0,0 +1,48 @@ +// Types +export type { + OAuthStep, + OAuthAuthType, + MessageType, + StatusMessage, + AuthGuidedState, + CallbackParams, +} from "./types.js"; +export { EMPTY_GUIDED_STATE } from "./types.js"; + +// Storage +export type { OAuthStorage } from "./storage.js"; +export { getServerSpecificKey, OAUTH_STORAGE_KEYS } from "./storage.js"; + +// Providers +export type { + OAuthProviderConfig, + RedirectUrlProvider, + OAuthNavigation, + OAuthNavigationCallback, +} from "./providers.js"; +export { + MutableRedirectUrlProvider, + ConsoleNavigation, + CallbackNavigation, + BaseOAuthClientProvider, +} from "./providers.js"; + +// Utilities +export { + parseOAuthCallbackParams, + generateOAuthState, + generateOAuthStateWithMode, + parseOAuthState, + generateOAuthErrorDescription, +} from "./utils.js"; +export type { OAuthStateMode } from "./utils.js"; + +// Discovery +export { discoverScopes } from "./discovery.js"; + +// Logging +export type { InspectorClientLogger } from "./logger.js"; +export { silentLogger } from "./logger.js"; +// State Machine +export type { StateMachineContext, StateTransition } from "./state-machine.js"; +export { oauthTransitions, OAuthStateMachine } from "./state-machine.js"; diff --git a/shared/auth/logger.ts b/shared/auth/logger.ts new file mode 100644 index 000000000..d253aef0c --- /dev/null +++ b/shared/auth/logger.ts @@ -0,0 +1,13 @@ +import pino from "pino"; + +/** + * Logger type for InspectorClient. Both sides use pino.Logger directly. + * @deprecated Use pino.Logger directly; kept for backward compatibility. + */ +export type InspectorClientLogger = pino.Logger; + +/** + * Silent logger for use when no logger is injected. Satisfies pino.Logger, + * does not output anything. InspectorClient uses this as the default. + */ +export const silentLogger = pino({ level: "silent" }); diff --git a/shared/auth/node/index.ts b/shared/auth/node/index.ts new file mode 100644 index 000000000..cbd8476b4 --- /dev/null +++ b/shared/auth/node/index.ts @@ -0,0 +1,16 @@ +export { + NodeOAuthStorage, + getOAuthStore, + getStateFilePath, + clearAllOAuthClientState, +} from "./storage-node.js"; +export { + createOAuthCallbackServer, + OAuthCallbackServer, +} from "./oauth-callback-server.js"; +export type { + OAuthCallbackHandler, + OAuthErrorHandler, + OAuthCallbackServerStartOptions, + OAuthCallbackServerStartResult, +} from "./oauth-callback-server.js"; diff --git a/shared/auth/node/oauth-callback-server.ts b/shared/auth/node/oauth-callback-server.ts new file mode 100644 index 000000000..8ee48d7d9 --- /dev/null +++ b/shared/auth/node/oauth-callback-server.ts @@ -0,0 +1,216 @@ +import { createServer, type Server } from "node:http"; +import { parseOAuthCallbackParams } from "../utils.js"; +import { generateOAuthErrorDescription } from "../utils.js"; + +const DEFAULT_HOSTNAME = "127.0.0.1"; +const DEFAULT_CALLBACK_PATH = "/oauth/callback"; + +const SUCCESS_HTML = ` + +OAuth complete +

OAuth complete. You can close this window.

+`; + +function errorHtml(message: string): string { + return ` + +OAuth error +

OAuth failed: ${escapeHtml(message)}

+`; +} + +function escapeHtml(s: string): string { + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +export type OAuthCallbackHandler = (params: { + code: string; + state?: string; +}) => Promise; + +export type OAuthErrorHandler = (params: { + error: string; + error_description?: string | null; +}) => void; + +export interface OAuthCallbackServerStartOptions { + port?: number; + hostname?: string; + path?: string; + onCallback?: OAuthCallbackHandler; + onError?: OAuthErrorHandler; +} + +export interface OAuthCallbackServerStartResult { + port: number; + redirectUrl: string; +} + +/** + * Minimal HTTP server that receives OAuth 2.1 redirects at GET /oauth/callback. + * Used by TUI/CLI to complete the authorization code flow (both normal and guided). + * Caller provides onCallback/onError; typically onCallback calls + * InspectorClient.completeOAuthFlow(code) then stops the server. + */ +export class OAuthCallbackServer { + private server: Server | null = null; + private port: number = 0; + private hostname: string = DEFAULT_HOSTNAME; + private callbackPath: string = DEFAULT_CALLBACK_PATH; + private handled = false; + private onCallback?: OAuthCallbackHandler; + private onError?: OAuthErrorHandler; + + /** + * Start the server. Listens on the given port (default 0 = random). + * Returns port and redirectUrl for use as oauth.redirectUrl. + */ + async start( + options: OAuthCallbackServerStartOptions = {}, + ): Promise { + const { + port = 0, + hostname = DEFAULT_HOSTNAME, + path = DEFAULT_CALLBACK_PATH, + onCallback, + onError, + } = options; + if (!path.startsWith("/")) { + return Promise.reject( + new Error("Callback path must start with '/' (absolute path)"), + ); + } + this.onCallback = onCallback; + this.onError = onError; + this.handled = false; + this.hostname = hostname; + this.callbackPath = path; + + return new Promise((resolve, reject) => { + this.server = createServer((req, res) => this.handleRequest(req, res)); + this.server.on("error", reject); + this.server.listen(port, hostname, () => { + const a = this.server!.address(); + if (!a || typeof a === "string") { + reject(new Error("Failed to get server address")); + return; + } + this.port = a.port; + resolve({ + port: this.port, + redirectUrl: buildRedirectUrl(hostname, this.port, path), + }); + }); + }); + } + + /** + * Stop the server. Idempotent. + */ + async stop(): Promise { + if (!this.server) return; + await new Promise((resolve) => { + this.server!.close(() => resolve()); + }); + this.server = null; + } + + private handleRequest( + req: import("node:http").IncomingMessage, + res: import("node:http").ServerResponse< + import("node:http").IncomingMessage + >, + ): void { + const needJson = req.headers["accept"]?.includes("application/json"); + + const send = ( + status: number, + body: string, + contentType = "text/html; charset=utf-8", + ) => { + res.writeHead(status, { "Content-Type": contentType }); + res.end(body); + }; + + if (req.method !== "GET") { + send(405, needJson ? '{"error":"Method Not Allowed"}' : SUCCESS_HTML); + return; + } + + let pathname: string; + let search: string; + let state: string | undefined; + try { + const u = new URL(req.url ?? "", "http://placeholder"); + pathname = u.pathname; + search = u.search; + state = u.searchParams.get("state") ?? undefined; + } catch { + send(400, needJson ? '{"error":"Bad Request"}' : SUCCESS_HTML); + return; + } + + if (pathname !== this.callbackPath) { + send(404, needJson ? '{"error":"Not Found"}' : SUCCESS_HTML); + return; + } + + if (this.handled) { + send( + 409, + needJson ? '{"error":"Callback already handled"}' : SUCCESS_HTML, + ); + return; + } + + const params = parseOAuthCallbackParams(search); + + if (params.successful) { + this.handled = true; + const cb = this.onCallback; + if (cb) { + cb({ code: params.code, state }) + .then(() => { + send(200, SUCCESS_HTML); + void this.stop(); + }) + .catch((err) => { + const msg = err instanceof Error ? err.message : String(err); + this.onError?.({ error: "callback_error", error_description: msg }); + send(500, errorHtml(msg)); + void this.stop(); + }); + } else { + send(200, SUCCESS_HTML); + void this.stop(); + } + return; + } + + this.handled = true; + const msg = generateOAuthErrorDescription(params); + this.onError?.({ + error: params.error, + error_description: params.error_description ?? undefined, + }); + send(400, errorHtml(msg)); + } +} + +/** + * Create an OAuth callback server instance. + * Use start() then stop() when the OAuth flow is done. + */ +export function createOAuthCallbackServer(): OAuthCallbackServer { + return new OAuthCallbackServer(); +} + +function buildRedirectUrl(host: string, port: number, path: string): string { + const needsBrackets = host.includes(":") && !host.startsWith("["); + const formattedHost = needsBrackets ? `[${host}]` : host; + return `http://${formattedHost}:${port}${path}`; +} diff --git a/shared/auth/node/storage-node.ts b/shared/auth/node/storage-node.ts new file mode 100644 index 000000000..f91607d6c --- /dev/null +++ b/shared/auth/node/storage-node.ts @@ -0,0 +1,192 @@ +import type { OAuthStorage } from "../storage.js"; +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { + OAuthClientInformationSchema, + OAuthTokensSchema, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import * as path from "node:path"; +import { createOAuthStore, type ServerOAuthState } from "../store.js"; +import { createFileStorageAdapter } from "../../storage/adapters/file-storage.js"; + +const DEFAULT_STATE_PATH = (() => { + const homeDir = process.env.HOME || process.env.USERPROFILE || "."; + return path.join(homeDir, ".mcp-inspector", "oauth", "state.json"); +})(); + +/** + * Get path to state.json file. + * @param customPath - Optional custom path (full path to state file). Default: ~/.mcp-inspector/oauth/state.json + */ +export function getStateFilePath(customPath?: string): string { + return customPath ?? DEFAULT_STATE_PATH; +} + +const storeCache = new Map>(); + +/** + * Get or create the OAuth store instance for the given path. + * @param stateFilePath - Optional custom path to state file. Default: ~/.mcp-inspector/oauth/state.json + */ +export function getOAuthStore(stateFilePath?: string) { + const key = getStateFilePath(stateFilePath); + let store = storeCache.get(key); + if (!store) { + const filePath = getStateFilePath(stateFilePath); + const storage = createFileStorageAdapter({ filePath }); + store = createOAuthStore(storage); + storeCache.set(key, store); + } + return store; +} + +/** + * Clear all OAuth client state (all servers) in the default store. + * Useful for test isolation in E2E OAuth tests. + * Use a custom-path store and clear per serverUrl if you need to clear non-default storage. + */ +export function clearAllOAuthClientState(): void { + const store = getOAuthStore(); + const state = store.getState(); + const urls = Object.keys(state.servers ?? {}); + for (const url of urls) { + state.clearServerState(url); + } +} + +/** + * Node.js storage implementation using Zustand with file-based persistence + * For InspectorClient, CLI, and TUI + */ +export class NodeOAuthStorage implements OAuthStorage { + private store: ReturnType; + + /** + * @param storagePath - Optional path to state file. Default: ~/.mcp-inspector/oauth/state.json + */ + constructor(storagePath?: string) { + this.store = getOAuthStore(storagePath); + } + + async getClientInformation( + serverUrl: string, + isPreregistered?: boolean, + ): Promise { + const state = this.store.getState().getServerState(serverUrl); + const clientInfo = isPreregistered + ? state.preregisteredClientInformation + : state.clientInformation; + + if (!clientInfo) { + return undefined; + } + + return await OAuthClientInformationSchema.parseAsync(clientInfo); + } + + async saveClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise { + this.store.getState().setServerState(serverUrl, { + clientInformation, + }); + } + + async savePreregisteredClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise { + this.store.getState().setServerState(serverUrl, { + preregisteredClientInformation: clientInformation, + }); + } + + clearClientInformation(serverUrl: string, isPreregistered?: boolean): void { + const state = this.store.getState().getServerState(serverUrl); + const updates: Partial = {}; + + if (isPreregistered) { + updates.preregisteredClientInformation = undefined; + } else { + updates.clientInformation = undefined; + } + + this.store.getState().setServerState(serverUrl, updates); + } + + async getTokens(serverUrl: string): Promise { + const state = this.store.getState().getServerState(serverUrl); + if (!state.tokens) { + return undefined; + } + + return await OAuthTokensSchema.parseAsync(state.tokens); + } + + async saveTokens(serverUrl: string, tokens: OAuthTokens): Promise { + this.store.getState().setServerState(serverUrl, { tokens }); + } + + clearTokens(serverUrl: string): void { + this.store.getState().setServerState(serverUrl, { tokens: undefined }); + } + + getCodeVerifier(serverUrl: string): string | undefined { + const state = this.store.getState().getServerState(serverUrl); + return state.codeVerifier; + } + + async saveCodeVerifier( + serverUrl: string, + codeVerifier: string, + ): Promise { + this.store.getState().setServerState(serverUrl, { codeVerifier }); + } + + clearCodeVerifier(serverUrl: string): void { + this.store + .getState() + .setServerState(serverUrl, { codeVerifier: undefined }); + } + + getScope(serverUrl: string): string | undefined { + const state = this.store.getState().getServerState(serverUrl); + return state.scope; + } + + async saveScope(serverUrl: string, scope: string | undefined): Promise { + this.store.getState().setServerState(serverUrl, { scope }); + } + + clearScope(serverUrl: string): void { + this.store.getState().setServerState(serverUrl, { scope: undefined }); + } + + getServerMetadata(serverUrl: string): OAuthMetadata | null { + const state = this.store.getState().getServerState(serverUrl); + return state.serverMetadata || null; + } + + async saveServerMetadata( + serverUrl: string, + metadata: OAuthMetadata, + ): Promise { + this.store + .getState() + .setServerState(serverUrl, { serverMetadata: metadata }); + } + + clearServerMetadata(serverUrl: string): void { + this.store + .getState() + .setServerState(serverUrl, { serverMetadata: undefined }); + } + + clear(serverUrl: string): void { + this.store.getState().clearServerState(serverUrl); + } +} diff --git a/shared/auth/providers.ts b/shared/auth/providers.ts new file mode 100644 index 000000000..56efa576d --- /dev/null +++ b/shared/auth/providers.ts @@ -0,0 +1,255 @@ +import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { + OAuthClientInformation, + OAuthClientMetadata, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import type { OAuthStorage } from "./storage.js"; +import { generateOAuthStateWithMode } from "./utils.js"; + +/** + * Redirect URL provider. Returns the redirect URL for the requested mode. + * Caller populates the URLs before authenticate() (e.g. from callback server). + */ +export interface RedirectUrlProvider { + getRedirectUrl(mode: "normal" | "guided"): string; +} + +/** + * Mutable redirect URL provider for TUI/CLI. Caller sets redirectUrl + * before authenticate(); same URL is used for both normal and guided flows. + */ +export class MutableRedirectUrlProvider implements RedirectUrlProvider { + redirectUrl = ""; + + getRedirectUrl(_mode: "normal" | "guided"): string { + return this.redirectUrl; + } +} + +/** + * Navigation handler interface + * Handles navigation to authorization URLs + */ +export interface OAuthNavigation { + /** + * Navigate to the authorization URL + * @param authorizationUrl - The OAuth authorization URL + */ + navigateToAuthorization(authorizationUrl: URL): void; +} + +export type OAuthNavigationCallback = ( + authorizationUrl: URL, +) => void | Promise; + +/** + * Callback navigation handler + * Invokes the provided callback when navigation is requested. + * The caller always handles navigation. + */ +export class CallbackNavigation implements OAuthNavigation { + private authorizationUrl: URL | null = null; + + constructor(private callback: OAuthNavigationCallback) {} + + navigateToAuthorization(authorizationUrl: URL): void { + this.authorizationUrl = authorizationUrl; + const result = this.callback(authorizationUrl); + if (result instanceof Promise) { + void result; + } + } + + getAuthorizationUrl(): URL | null { + return this.authorizationUrl; + } +} + +/** + * Console navigation handler + * Prints the authorization URL to console, optionally invokes an extra callback. + */ +export class ConsoleNavigation extends CallbackNavigation { + constructor(callback?: OAuthNavigationCallback) { + super((url) => { + console.log(`Please navigate to: ${url.href}`); + return callback?.(url); + }); + } +} + +/** + * Config passed to BaseOAuthClientProvider. Provider assigns to members and + * accesses as needed. + */ +export type OAuthProviderConfig = { + storage: OAuthStorage; + redirectUrlProvider: RedirectUrlProvider; + navigation: OAuthNavigation; + clientMetadataUrl?: string; +}; + +/** + * Base OAuth client provider + * Implements common OAuth provider functionality. + * Use with injected storage, redirect URL provider, and navigation. + */ +export class BaseOAuthClientProvider implements OAuthClientProvider { + private capturedAuthUrl: URL | null = null; + private eventTarget: EventTarget | null = null; + + protected storage: OAuthStorage; + protected redirectUrlProvider: RedirectUrlProvider; + protected navigation: OAuthNavigation; + public clientMetadataUrl?: string; + protected mode: "normal" | "guided"; + + constructor( + protected serverUrl: string, + oauthConfig: OAuthProviderConfig, + mode: "normal" | "guided" = "normal", + ) { + this.storage = oauthConfig.storage; + this.redirectUrlProvider = oauthConfig.redirectUrlProvider; + this.navigation = oauthConfig.navigation; + this.clientMetadataUrl = oauthConfig.clientMetadataUrl; + this.mode = mode; + } + + /** + * Set the event target for dispatching oauthAuthorizationRequired events + */ + setEventTarget(eventTarget: EventTarget): void { + this.eventTarget = eventTarget; + } + + /** + * Get the captured authorization URL (for return value) + */ + getCapturedAuthUrl(): URL | null { + return this.capturedAuthUrl; + } + + /** + * Clear the captured authorization URL + */ + clearCapturedAuthUrl(): void { + this.capturedAuthUrl = null; + } + + get scope(): string | undefined { + return this.storage.getScope(this.serverUrl); + } + + /** Redirect URL for the current flow (normal or guided). */ + get redirectUrl(): string { + return this.redirectUrlProvider.getRedirectUrl(this.mode); + } + + get redirect_uris(): string[] { + return [this.redirectUrlProvider.getRedirectUrl("normal")]; + } + + get clientMetadata(): OAuthClientMetadata { + const metadata: OAuthClientMetadata = { + redirect_uris: this.redirect_uris, + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + client_name: "MCP Inspector", + client_uri: "https://github.com/modelcontextprotocol/inspector", + scope: this.scope ?? "", + }; + + // Note: clientMetadataUrl for CIMD mode is passed to registerClient() directly, + // not as part of clientMetadata. The SDK handles CIMD separately. + + return metadata; + } + + state(): string | Promise { + return generateOAuthStateWithMode(this.mode); + } + + async clientInformation(): Promise { + // Try preregistered first, then dynamically registered + const preregistered = await this.storage.getClientInformation( + this.serverUrl, + true, + ); + if (preregistered) { + return preregistered; + } + return await this.storage.getClientInformation(this.serverUrl, false); + } + + async saveClientInformation( + clientInformation: OAuthClientInformation, + ): Promise { + await this.storage.saveClientInformation(this.serverUrl, clientInformation); + } + + async saveScope(scope: string | undefined): Promise { + await this.storage.saveScope(this.serverUrl, scope); + } + + async savePreregisteredClientInformation( + clientInformation: OAuthClientInformation, + ): Promise { + await this.storage.savePreregisteredClientInformation( + this.serverUrl, + clientInformation, + ); + } + + async tokens(): Promise { + return await this.storage.getTokens(this.serverUrl); + } + + async saveTokens(tokens: OAuthTokens): Promise { + await this.storage.saveTokens(this.serverUrl, tokens); + } + + redirectToAuthorization(authorizationUrl: URL): void { + // Capture URL for return value + this.capturedAuthUrl = authorizationUrl; + + // Dispatch event if event target is set + if (this.eventTarget) { + this.eventTarget.dispatchEvent( + new CustomEvent("oauthAuthorizationRequired", { + detail: { url: authorizationUrl }, + }), + ); + } + + // Original navigation behavior + this.navigation.navigateToAuthorization(authorizationUrl); + } + + async saveCodeVerifier(codeVerifier: string): Promise { + await this.storage.saveCodeVerifier(this.serverUrl, codeVerifier); + } + + codeVerifier(): string { + const verifier = this.storage.getCodeVerifier(this.serverUrl); + if (!verifier) { + throw new Error("No code verifier saved for session"); + } + return verifier; + } + + clear(): void { + this.storage.clear(this.serverUrl); + } + + getServerMetadata(): OAuthMetadata | null { + return this.storage.getServerMetadata(this.serverUrl); + } + + async saveServerMetadata(metadata: OAuthMetadata): Promise { + await this.storage.saveServerMetadata(this.serverUrl, metadata); + } +} diff --git a/shared/auth/remote/index.ts b/shared/auth/remote/index.ts new file mode 100644 index 000000000..8f3272956 --- /dev/null +++ b/shared/auth/remote/index.ts @@ -0,0 +1,6 @@ +/** + * Remote HTTP storage for OAuth state. + */ + +export { RemoteOAuthStorage } from "./storage-remote.js"; +export type { RemoteOAuthStorageOptions } from "./storage-remote.js"; diff --git a/shared/auth/remote/storage-remote.ts b/shared/auth/remote/storage-remote.ts new file mode 100644 index 000000000..b03c34f5a --- /dev/null +++ b/shared/auth/remote/storage-remote.ts @@ -0,0 +1,167 @@ +/** + * Remote HTTP storage implementation for OAuth state. + * Uses Zustand with remote storage adapter (HTTP API). + * For web clients that need to share state with Node apps. + */ + +import type { OAuthStorage } from "../storage.js"; +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { + OAuthClientInformationSchema, + OAuthTokensSchema, +} from "@modelcontextprotocol/sdk/shared/auth.js"; +import { createOAuthStore, type ServerOAuthState } from "../store.js"; +import { createRemoteStorageAdapter } from "../../storage/adapters/remote-storage.js"; + +export interface RemoteOAuthStorageOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + /** Store ID (default: "oauth") */ + storeId?: string; + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + /** Fetch function to use (default: globalThis.fetch) */ + fetchFn?: typeof fetch; +} + +/** + * Remote HTTP storage implementation using Zustand with remote storage adapter. + * Stores OAuth state via HTTP API (GET/POST/DELETE /api/storage/:storeId). + * For web clients that need to share state with Node apps (TUI, CLI). + */ +export class RemoteOAuthStorage implements OAuthStorage { + private store: ReturnType; + + constructor(options: RemoteOAuthStorageOptions) { + const storage = createRemoteStorageAdapter({ + baseUrl: options.baseUrl, + storeId: options.storeId ?? "oauth", + authToken: options.authToken, + fetchFn: options.fetchFn, + }); + this.store = createOAuthStore(storage); + } + + async getClientInformation( + serverUrl: string, + isPreregistered?: boolean, + ): Promise { + const state = this.store.getState().getServerState(serverUrl); + const clientInfo = isPreregistered + ? state.preregisteredClientInformation + : state.clientInformation; + + if (!clientInfo) { + return undefined; + } + + return await OAuthClientInformationSchema.parseAsync(clientInfo); + } + + async saveClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise { + this.store.getState().setServerState(serverUrl, { + clientInformation, + }); + } + + async savePreregisteredClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise { + this.store.getState().setServerState(serverUrl, { + preregisteredClientInformation: clientInformation, + }); + } + + clearClientInformation(serverUrl: string, isPreregistered?: boolean): void { + const state = this.store.getState().getServerState(serverUrl); + const updates: Partial = {}; + + if (isPreregistered) { + updates.preregisteredClientInformation = undefined; + } else { + updates.clientInformation = undefined; + } + + this.store.getState().setServerState(serverUrl, updates); + } + + async getTokens(serverUrl: string): Promise { + const state = this.store.getState().getServerState(serverUrl); + if (!state.tokens) { + return undefined; + } + + return await OAuthTokensSchema.parseAsync(state.tokens); + } + + async saveTokens(serverUrl: string, tokens: OAuthTokens): Promise { + this.store.getState().setServerState(serverUrl, { tokens }); + } + + clearTokens(serverUrl: string): void { + this.store.getState().setServerState(serverUrl, { tokens: undefined }); + } + + getCodeVerifier(serverUrl: string): string | undefined { + const state = this.store.getState().getServerState(serverUrl); + return state.codeVerifier; + } + + async saveCodeVerifier( + serverUrl: string, + codeVerifier: string, + ): Promise { + this.store.getState().setServerState(serverUrl, { codeVerifier }); + } + + clearCodeVerifier(serverUrl: string): void { + this.store + .getState() + .setServerState(serverUrl, { codeVerifier: undefined }); + } + + getScope(serverUrl: string): string | undefined { + const state = this.store.getState().getServerState(serverUrl); + return state.scope; + } + + async saveScope(serverUrl: string, scope: string | undefined): Promise { + this.store.getState().setServerState(serverUrl, { scope }); + } + + clearScope(serverUrl: string): void { + this.store.getState().setServerState(serverUrl, { scope: undefined }); + } + + getServerMetadata(serverUrl: string): OAuthMetadata | null { + const state = this.store.getState().getServerState(serverUrl); + return state.serverMetadata || null; + } + + async saveServerMetadata( + serverUrl: string, + metadata: OAuthMetadata, + ): Promise { + this.store + .getState() + .setServerState(serverUrl, { serverMetadata: metadata }); + } + + clearServerMetadata(serverUrl: string): void { + this.store + .getState() + .setServerState(serverUrl, { serverMetadata: undefined }); + } + + clear(serverUrl: string): void { + this.store.getState().clearServerState(serverUrl); + } +} diff --git a/shared/auth/state-machine.ts b/shared/auth/state-machine.ts new file mode 100644 index 000000000..49f950718 --- /dev/null +++ b/shared/auth/state-machine.ts @@ -0,0 +1,285 @@ +import type { OAuthStep, AuthGuidedState } from "./types.js"; +import type { BaseOAuthClientProvider } from "./providers.js"; +import { discoverScopes } from "./discovery.js"; +import { + discoverAuthorizationServerMetadata, + registerClient, + startAuthorization, + exchangeAuthorization, + discoverOAuthProtectedResourceMetadata, + selectResourceURL, +} from "@modelcontextprotocol/sdk/client/auth.js"; +import { + OAuthMetadataSchema, + type OAuthProtectedResourceMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; + +export interface StateMachineContext { + state: AuthGuidedState; + serverUrl: string; + provider: BaseOAuthClientProvider; + updateState: (updates: Partial) => void; + fetchFn?: typeof fetch; +} + +export interface StateTransition { + canTransition: (context: StateMachineContext) => Promise; + execute: (context: StateMachineContext) => Promise; +} + +// State machine transitions +export const oauthTransitions: Record = { + metadata_discovery: { + canTransition: async () => true, + execute: async (context) => { + // Default to discovering from the server's URL + let authServerUrl: URL = new URL("/", context.serverUrl); + let resourceMetadata: OAuthProtectedResourceMetadata | null = null; + let resourceMetadataError: Error | null = null; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata( + context.serverUrl as string | URL, + ); + if (resourceMetadata?.authorization_servers?.length) { + const firstServer = resourceMetadata.authorization_servers[0]; + if (firstServer) { + authServerUrl = new URL(firstServer); + } + } + } catch (e) { + if (e instanceof Error) { + resourceMetadataError = e; + } else { + resourceMetadataError = new Error(String(e)); + } + } + + const resource: URL | undefined = resourceMetadata + ? await selectResourceURL( + context.serverUrl, + context.provider, + resourceMetadata, + ) + : undefined; + + const metadata = await discoverAuthorizationServerMetadata( + authServerUrl, + { + ...(context.fetchFn && { fetchFn: context.fetchFn }), + }, + ); + if (!metadata) { + throw new Error("Failed to discover OAuth metadata"); + } + const parsedMetadata = await OAuthMetadataSchema.parseAsync(metadata); + + await context.provider.saveServerMetadata(parsedMetadata); + + context.updateState({ + resourceMetadata, + resource, + resourceMetadataError, + authServerUrl, + oauthMetadata: parsedMetadata, + oauthStep: "client_registration", + }); + }, + }, + + client_registration: { + canTransition: async (context) => !!context.state.oauthMetadata, + execute: async (context) => { + const metadata = context.state.oauthMetadata!; + const clientMetadata = context.provider.clientMetadata; + + // Priority: user-provided scope > discovered scopes + if (!context.provider.scope || context.provider.scope.trim() === "") { + // Prefer scopes from resource metadata if available + const scopesSupported = + context.state.resourceMetadata?.scopes_supported || + metadata.scopes_supported; + // Add all supported scopes to client registration + if (scopesSupported) { + clientMetadata.scope = scopesSupported.join(" "); + } + } + + // Use pre-set client info from state (static client) when present; otherwise provider lookup → CIMD → DCR + let fullInformation = + context.state.oauthClientInfo ?? + (await context.provider.clientInformation()); + if (!fullInformation) { + // Check if provider has clientMetadataUrl (CIMD mode) + const clientMetadataUrl = + "clientMetadataUrl" in context.provider && + context.provider.clientMetadataUrl + ? context.provider.clientMetadataUrl + : undefined; + + // Check for CIMD support (SDK handles this in authInternal - we replicate it here) + const supportsUrlBasedClientId = + metadata?.client_id_metadata_document_supported === true; + const shouldUseUrlBasedClientId = + supportsUrlBasedClientId && clientMetadataUrl; + + if (shouldUseUrlBasedClientId) { + // SEP-991: URL-based Client IDs (CIMD) + // SDK creates { client_id: clientMetadataUrl } directly - no registration needed + fullInformation = { + client_id: clientMetadataUrl, + }; + } else { + // Fallback to DCR registration + fullInformation = await registerClient(context.serverUrl, { + metadata, + clientMetadata, + ...(context.fetchFn && { fetchFn: context.fetchFn }), + }); + } + await context.provider.saveClientInformation(fullInformation); + } + + context.updateState({ + oauthClientInfo: fullInformation, + oauthStep: "authorization_redirect", + }); + }, + }, + + authorization_redirect: { + canTransition: async (context) => + !!context.state.oauthMetadata && !!context.state.oauthClientInfo, + execute: async (context) => { + const metadata = context.state.oauthMetadata!; + const clientInformation = context.state.oauthClientInfo!; + + // Priority: user-provided scope > discovered scopes + let scope = context.provider.scope; + if (!scope || scope.trim() === "") { + scope = await discoverScopes( + context.serverUrl, + context.state.resourceMetadata ?? undefined, + context.fetchFn, + ); + } + + const providerState = context.provider.state(); + const state = await Promise.resolve(providerState); + const { authorizationUrl, codeVerifier } = await startAuthorization( + context.serverUrl, + { + metadata, + clientInformation, + redirectUrl: context.provider.redirectUrl, + scope, + state, + resource: context.state.resource ?? undefined, + }, + ); + + await context.provider.saveCodeVerifier(codeVerifier); + context.updateState({ + authorizationUrl: authorizationUrl, + oauthStep: "authorization_code", + }); + }, + }, + + authorization_code: { + canTransition: async () => true, + execute: async (context) => { + if ( + !context.state.authorizationCode || + context.state.authorizationCode.trim() === "" + ) { + context.updateState({ + validationError: "You need to provide an authorization code", + }); + // Don't advance if no code + throw new Error("Authorization code required"); + } + context.updateState({ + validationError: null, + oauthStep: "token_request", + }); + }, + }, + + token_request: { + canTransition: async (context) => { + const hasMetadata = !!context.provider.getServerMetadata(); + const clientInfo = + context.state.oauthClientInfo ?? + (await context.provider.clientInformation()); + return !!context.state.authorizationCode && hasMetadata && !!clientInfo; + }, + execute: async (context) => { + const codeVerifier = context.provider.codeVerifier(); + const metadata = context.provider.getServerMetadata(); + + if (!metadata) { + throw new Error("OAuth metadata not available"); + } + + const clientInformation = + context.state.oauthClientInfo ?? + (await context.provider.clientInformation()); + if (!clientInformation) { + throw new Error("Client information not available for token exchange"); + } + + const tokens = await exchangeAuthorization(context.serverUrl, { + metadata, + clientInformation, + authorizationCode: context.state.authorizationCode, + codeVerifier, + redirectUri: context.provider.redirectUrl, + resource: context.state.resource + ? context.state.resource instanceof URL + ? context.state.resource + : new URL(context.state.resource) + : undefined, + ...(context.fetchFn && { fetchFn: context.fetchFn }), + }); + + await context.provider.saveTokens(tokens); + context.updateState({ + oauthTokens: tokens, + oauthStep: "complete", + }); + }, + }, + + complete: { + canTransition: async () => false, + execute: async () => { + // No-op for complete state + }, + }, +}; + +export class OAuthStateMachine { + constructor( + private serverUrl: string, + private provider: BaseOAuthClientProvider, + private updateState: (updates: Partial) => void, + private fetchFn?: typeof fetch, + ) {} + + async executeStep(state: AuthGuidedState): Promise { + const context: StateMachineContext = { + state, + serverUrl: this.serverUrl, + provider: this.provider, + updateState: this.updateState, + ...(this.fetchFn && { fetchFn: this.fetchFn }), + }; + + const transition = oauthTransitions[state.oauthStep]; + if (!(await transition.canTransition(context))) { + throw new Error(`Cannot transition from ${state.oauthStep}`); + } + + await transition.execute(context); + } +} diff --git a/shared/auth/storage.ts b/shared/auth/storage.ts new file mode 100644 index 000000000..6cbe13b5b --- /dev/null +++ b/shared/auth/storage.ts @@ -0,0 +1,127 @@ +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; + +/** + * Abstract storage interface for OAuth state + * Supports both browser (sessionStorage) and Node.js (Zustand) environments + */ +export interface OAuthStorage { + /** + * Get client information (preregistered or dynamically registered) + */ + getClientInformation( + serverUrl: string, + isPreregistered?: boolean, + ): Promise; + + /** + * Save client information (dynamically registered) + */ + saveClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise; + + /** + * Save preregistered client information (static client from config) + */ + savePreregisteredClientInformation( + serverUrl: string, + clientInformation: OAuthClientInformation, + ): Promise; + + /** + * Clear client information + */ + clearClientInformation(serverUrl: string, isPreregistered?: boolean): void; + + /** + * Get OAuth tokens + */ + getTokens(serverUrl: string): Promise; + + /** + * Save OAuth tokens + */ + saveTokens(serverUrl: string, tokens: OAuthTokens): Promise; + + /** + * Clear OAuth tokens + */ + clearTokens(serverUrl: string): void; + + /** + * Get code verifier (for PKCE) + */ + getCodeVerifier(serverUrl: string): string | undefined; + + /** + * Save code verifier (for PKCE) + */ + saveCodeVerifier(serverUrl: string, codeVerifier: string): Promise; + + /** + * Clear code verifier + */ + clearCodeVerifier(serverUrl: string): void; + + /** + * Get scope + */ + getScope(serverUrl: string): string | undefined; + + /** + * Save scope + */ + saveScope(serverUrl: string, scope: string | undefined): Promise; + + /** + * Clear scope + */ + clearScope(serverUrl: string): void; + + /** + * Get server metadata (for guided mode) + */ + getServerMetadata(serverUrl: string): OAuthMetadata | null; + + /** + * Save server metadata (for guided mode) + */ + saveServerMetadata(serverUrl: string, metadata: OAuthMetadata): Promise; + + /** + * Clear server metadata + */ + clearServerMetadata(serverUrl: string): void; + + /** + * Clear all OAuth data for a server + */ + clear(serverUrl: string): void; +} + +/** + * Generate server-specific storage key + */ +export function getServerSpecificKey( + baseKey: string, + serverUrl: string, +): string { + return `[${serverUrl}] ${baseKey}`; +} + +/** + * Base storage keys for OAuth data + */ +export const OAUTH_STORAGE_KEYS = { + CODE_VERIFIER: "mcp_code_verifier", + TOKENS: "mcp_tokens", + CLIENT_INFORMATION: "mcp_client_information", + PREREGISTERED_CLIENT_INFORMATION: "mcp_preregistered_client_information", + SERVER_METADATA: "mcp_server_metadata", + SCOPE: "mcp_scope", +} as const; diff --git a/shared/auth/store.ts b/shared/auth/store.ts new file mode 100644 index 000000000..6caf66d49 --- /dev/null +++ b/shared/auth/store.ts @@ -0,0 +1,80 @@ +/** + * OAuth store factory using Zustand. + * Creates a store with any storage adapter (file, remote, sessionStorage). + */ + +import { createStore } from "zustand/vanilla"; +import { persist, createJSONStorage } from "zustand/middleware"; +import type { + OAuthClientInformation, + OAuthTokens, + OAuthMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; + +/** + * OAuth state for a single server + */ +export interface ServerOAuthState { + clientInformation?: OAuthClientInformation; + preregisteredClientInformation?: OAuthClientInformation; + tokens?: OAuthTokens; + codeVerifier?: string; + scope?: string; + serverMetadata?: OAuthMetadata; +} + +/** + * Zustand store state (all servers) + */ +export interface OAuthStoreState { + servers: Record; + getServerState: (serverUrl: string) => ServerOAuthState; + setServerState: (serverUrl: string, state: Partial) => void; + clearServerState: (serverUrl: string) => void; +} + +/** + * Creates a Zustand store for OAuth state with the given storage adapter. + * The storage adapter handles persistence (file, remote HTTP, sessionStorage, etc.). + * + * @param storage - Zustand storage adapter (from createJSONStorage) + * @returns Zustand store instance + */ +export function createOAuthStore( + storage: ReturnType, +) { + return createStore()( + persist( + (set, get) => ({ + servers: {}, + getServerState: (serverUrl: string) => { + return get().servers[serverUrl] || {}; + }, + setServerState: ( + serverUrl: string, + updates: Partial, + ) => { + set((state) => ({ + servers: { + ...state.servers, + [serverUrl]: { + ...state.servers[serverUrl], + ...updates, + }, + }, + })); + }, + clearServerState: (serverUrl: string) => { + set((state) => { + const { [serverUrl]: _, ...rest } = state.servers; + return { servers: rest }; + }); + }, + }), + { + name: "mcp-inspector-oauth", + storage, + }, + ), + ); +} diff --git a/shared/auth/types.ts b/shared/auth/types.ts new file mode 100644 index 000000000..77f4a5557 --- /dev/null +++ b/shared/auth/types.ts @@ -0,0 +1,94 @@ +import type { + OAuthMetadata, + OAuthClientInformation, + OAuthClientInformationFull, + OAuthTokens, + OAuthProtectedResourceMetadata, +} from "@modelcontextprotocol/sdk/shared/auth.js"; + +// OAuth flow steps +export type OAuthStep = + | "metadata_discovery" + | "client_registration" + | "authorization_redirect" + | "authorization_code" + | "token_request" + | "complete"; + +// Message types for inline feedback +export type MessageType = "success" | "error" | "info"; + +export interface StatusMessage { + type: MessageType; + message: string; +} + +// How the current auth flow was started (guided = state machine with step events; normal = SDK auth()) +export type OAuthAuthType = "guided" | "normal"; + +// Single state interface for OAuth state +export interface AuthGuidedState { + /** How this auth flow was started; determines which fields are populated. */ + authType: OAuthAuthType; + /** When auth reached step "complete" (ms since epoch), if applicable. */ + completedAt: number | null; + isInitiatingAuth: boolean; + oauthTokens: OAuthTokens | null; + oauthStep: OAuthStep; + resourceMetadata: OAuthProtectedResourceMetadata | null; + resourceMetadataError: Error | null; + resource: URL | null; + authServerUrl: URL | null; + oauthMetadata: OAuthMetadata | null; + oauthClientInfo: OAuthClientInformationFull | OAuthClientInformation | null; + authorizationUrl: URL | null; + authorizationCode: string; + latestError: Error | null; + statusMessage: StatusMessage | null; + validationError: string | null; +} + +export const EMPTY_GUIDED_STATE: AuthGuidedState = { + authType: "guided", + completedAt: null, + isInitiatingAuth: false, + oauthTokens: null, + oauthStep: "metadata_discovery", + oauthMetadata: null, + resourceMetadata: null, + resourceMetadataError: null, + resource: null, + authServerUrl: null, + oauthClientInfo: null, + authorizationUrl: null, + authorizationCode: "", + latestError: null, + statusMessage: null, + validationError: null, +}; + +// The parsed query parameters returned by the Authorization Server +// representing either a valid authorization_code or an error +// ref: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-12#section-4.1.2 +export type CallbackParams = + | { + successful: true; + // The authorization code is generated by the authorization server. + code: string; + } + | { + successful: false; + // The OAuth 2.1 Error Code. + // Usually one of: + // ``` + // invalid_request, unauthorized_client, access_denied, unsupported_response_type, + // invalid_scope, server_error, temporarily_unavailable + // ``` + error: string; + // Human-readable ASCII text providing additional information, used to assist the + // developer in understanding the error that occurred. + error_description: string | null; + // A URI identifying a human-readable web page with information about the error, + // used to provide the client developer with additional information about the error. + error_uri: string | null; + }; diff --git a/shared/auth/utils.ts b/shared/auth/utils.ts new file mode 100644 index 000000000..5b6799f9c --- /dev/null +++ b/shared/auth/utils.ts @@ -0,0 +1,111 @@ +import type { CallbackParams } from "./types.js"; + +/** + * Parses OAuth 2.1 callback parameters from a URL search string + * @param location The URL search string (e.g., "?code=abc123" or "?error=access_denied") + * @returns Parsed callback parameters with success/error information + */ +export const parseOAuthCallbackParams = (location: string): CallbackParams => { + const params = new URLSearchParams(location); + + const code = params.get("code"); + if (code) { + return { successful: true, code }; + } + + const error = params.get("error"); + const error_description = params.get("error_description"); + const error_uri = params.get("error_uri"); + + if (error) { + return { successful: false, error, error_description, error_uri }; + } + + return { + successful: false, + error: "invalid_request", + error_description: "Missing code or error in response", + error_uri: null, + }; +}; + +/** + * Generate a random state for the OAuth 2.0 flow. + * Works in both browser and Node.js environments. + * + * @returns A random state for the OAuth 2.0 flow. + */ +export const generateOAuthState = (): string => { + // Generate a random state + const array = new Uint8Array(32); + + // Use crypto.getRandomValues (available in both browser and Node.js) + if (typeof crypto !== "undefined" && crypto.getRandomValues) { + crypto.getRandomValues(array); + } else { + // Fallback for environments without crypto.getRandomValues + // This should not happen in modern environments + for (let i = 0; i < array.length; i++) { + array[i] = Math.floor(Math.random() * 256); + } + } + + return Array.from(array, (byte) => byte.toString(16).padStart(2, "0")).join( + "", + ); +}; + +export type OAuthStateMode = "normal" | "guided"; + +/** + * Generate OAuth state with mode prefix for single-redirect-URL flow. + * Format: {mode}:{authId} (e.g. "guided:a1b2c3..."). + * The authId part is 64 hex chars for CSRF protection and serves as session identifier. + */ +export const generateOAuthStateWithMode = (mode: OAuthStateMode): string => { + const authId = generateOAuthState(); + return `${mode}:${authId}`; +}; + +/** + * Parse OAuth state to extract mode and authId part. + * Returns null if invalid. + * Legacy state (plain 64-char hex, no prefix) is treated as mode "normal". + */ +export const parseOAuthState = ( + state: string, +): { mode: OAuthStateMode; authId: string } | null => { + if (!state || typeof state !== "string") return null; + if (state.startsWith("normal:")) { + return { mode: "normal", authId: state.slice(7) }; + } + if (state.startsWith("guided:")) { + return { mode: "guided", authId: state.slice(7) }; + } + // Legacy: plain 64-char hex + if (/^[a-f0-9]{64}$/i.test(state)) { + return { mode: "normal", authId: state }; + } + return null; +}; + +/** + * Generates a human-readable error description from OAuth callback error parameters + * @param params OAuth error callback parameters containing error details + * @returns Formatted multiline error message with error code, description, and optional URI + */ +export const generateOAuthErrorDescription = ( + params: Extract, +): string => { + const error = params.error; + const errorDescription = params.error_description; + const errorUri = params.error_uri; + + return [ + `Error: ${error}.`, + errorDescription ? `Details: ${errorDescription}.` : "", + errorUri ? `More info: ${errorUri}.` : "", + ] + .filter(Boolean) + .join("\n"); +}; diff --git a/shared/json/jsonUtils.ts b/shared/json/jsonUtils.ts new file mode 100644 index 000000000..2fdd0853a --- /dev/null +++ b/shared/json/jsonUtils.ts @@ -0,0 +1,101 @@ +import type { Tool } from "@modelcontextprotocol/sdk/types.js"; + +/** + * JSON value type used across the inspector project + */ +export type JsonValue = + | string + | number + | boolean + | null + | undefined + | JsonValue[] + | { [key: string]: JsonValue }; + +/** + * Simple schema type for parameter conversion + */ +type ParameterSchema = { + type?: string; +}; + +/** + * Convert a string parameter value to the appropriate JSON type based on schema + * @param value String value to convert + * @param schema Schema type information + * @returns Converted JSON value + */ +export function convertParameterValue( + value: string, + schema: ParameterSchema, +): JsonValue { + if (!value) { + return value; + } + + if (schema.type === "number" || schema.type === "integer") { + return Number(value); + } + + if (schema.type === "boolean") { + return value.toLowerCase() === "true"; + } + + if (schema.type === "object" || schema.type === "array") { + try { + return JSON.parse(value) as JsonValue; + } catch (error) { + return value; + } + } + + return value; +} + +/** + * Convert string parameters to JSON values based on tool schema + * @param tool Tool definition with input schema + * @param params String parameters to convert + * @returns Converted parameters as JSON values + */ +export function convertToolParameters( + tool: Tool, + params: Record, +): Record { + const result: Record = {}; + const properties = tool.inputSchema?.properties || {}; + + for (const [key, value] of Object.entries(params)) { + const paramSchema = properties[key] as ParameterSchema | undefined; + + if (paramSchema) { + result[key] = convertParameterValue(value, paramSchema); + } else { + // If no schema is found for this parameter, keep it as string + result[key] = value; + } + } + + return result; +} + +/** + * Convert prompt arguments (JsonValue) to strings for prompt API + * @param args Prompt arguments as JsonValue + * @returns String arguments for prompt API + */ +export function convertPromptArguments( + args: Record, +): Record { + const stringArgs: Record = {}; + for (const [key, value] of Object.entries(args)) { + if (typeof value === "string") { + stringArgs[key] = value; + } else if (value === null || value === undefined) { + stringArgs[key] = String(value); + } else { + stringArgs[key] = JSON.stringify(value); + } + } + return stringArgs; +} diff --git a/shared/mcp/config.ts b/shared/mcp/config.ts new file mode 100644 index 000000000..1d1e034b4 --- /dev/null +++ b/shared/mcp/config.ts @@ -0,0 +1,24 @@ +import type { MCPServerConfig, ServerType } from "./types.js"; + +/** + * Returns the transport type for an MCP server configuration. + * If type is omitted, defaults to "stdio". Throws if type is invalid. + */ +export function getServerType(config: MCPServerConfig): ServerType { + if (!("type" in config) || config.type === undefined) { + return "stdio"; + } + const type = config.type; + if (type === "stdio") { + return "stdio"; + } + if (type === "sse") { + return "sse"; + } + if (type === "streamable-http") { + return "streamable-http"; + } + throw new Error( + `Invalid server type: ${type}. Valid types are: stdio, sse, streamable-http`, + ); +} diff --git a/shared/mcp/contentCache.ts b/shared/mcp/contentCache.ts new file mode 100644 index 000000000..6d7480983 --- /dev/null +++ b/shared/mcp/contentCache.ts @@ -0,0 +1,217 @@ +import type { + ResourceReadInvocation, + ResourceTemplateReadInvocation, + PromptGetInvocation, + ToolCallInvocation, +} from "./types.js"; + +/** + * Read-only interface for accessing cached content. + * This interface is exposed to users of InspectorClient. + */ +export interface ReadOnlyContentCache { + /** + * Get cached resource content by URI + * @param uri - The URI of the resource + * @returns The cached invocation object or null if not cached + */ + getResource(uri: string): ResourceReadInvocation | null; + + /** + * Get cached resource template content by URI template + * @param uriTemplate - The URI template string (unique identifier) + * @returns The cached invocation object or null if not cached + */ + getResourceTemplate( + uriTemplate: string, + ): ResourceTemplateReadInvocation | null; + + /** + * Get cached prompt content by name + * @param name - The prompt name + * @returns The cached invocation object or null if not cached + */ + getPrompt(name: string): PromptGetInvocation | null; + + /** + * Get cached tool call result by tool name + * @param toolName - The tool name + * @returns The cached invocation object or null if not cached + */ + getToolCallResult(toolName: string): ToolCallInvocation | null; + + /** + * Clear cached content for a specific resource + * @param uri - The URI of the resource to clear + */ + clearResource(uri: string): void; + + /** + * Clear all cached content for a given URI. + * This clears both regular resources cached by URI and resource templates + * that have a matching expandedUri. + * @param uri - The URI to clear from all caches + */ + clearResourceAndResourceTemplate(uri: string): void; + + /** + * Clear cached content for a specific resource template + * @param uriTemplate - The URI template string to clear + */ + clearResourceTemplate(uriTemplate: string): void; + + /** + * Clear cached content for a specific prompt + * @param name - The prompt name to clear + */ + clearPrompt(name: string): void; + + /** + * Clear cached tool call result for a specific tool + * @param toolName - The tool name to clear + */ + clearToolCallResult(toolName: string): void; + + /** + * Clear all cached content + */ + clearAll(): void; +} + +/** + * Read-write interface for accessing and modifying cached content. + * This interface is used internally by InspectorClient. + */ +export interface ReadWriteContentCache extends ReadOnlyContentCache { + /** + * Store resource content in cache + * @param uri - The URI of the resource + * @param invocation - The invocation object to cache + */ + setResource(uri: string, invocation: ResourceReadInvocation): void; + + /** + * Store resource template content in cache + * @param uriTemplate - The URI template string (unique identifier) + * @param invocation - The invocation object to cache + */ + setResourceTemplate( + uriTemplate: string, + invocation: ResourceTemplateReadInvocation, + ): void; + + /** + * Store prompt content in cache + * @param name - The prompt name + * @param invocation - The invocation object to cache + */ + setPrompt(name: string, invocation: PromptGetInvocation): void; + + /** + * Store tool call result in cache + * @param toolName - The tool name + * @param invocation - The invocation object to cache + */ + setToolCallResult(toolName: string, invocation: ToolCallInvocation): void; +} + +/** + * ContentCache manages cached content for resources, resource templates, prompts, and tool calls. + * This class implements ReadWriteContentCache and can be exposed as ReadOnlyContentCache to users. + */ +export class ContentCache implements ReadWriteContentCache { + // Internal storage - all cached content managed by this single object + private resourceContentCache: Map = new Map(); // Keyed by URI + private resourceTemplateContentCache: Map< + string, + ResourceTemplateReadInvocation + > = new Map(); // Keyed by uriTemplate + private promptContentCache: Map = new Map(); + private toolCallResultCache: Map = new Map(); + + // Read-only getter methods + + getResource(uri: string): ResourceReadInvocation | null { + return this.resourceContentCache.get(uri) ?? null; + } + + getResourceTemplate( + uriTemplate: string, + ): ResourceTemplateReadInvocation | null { + return this.resourceTemplateContentCache.get(uriTemplate) ?? null; + } + + getPrompt(name: string): PromptGetInvocation | null { + return this.promptContentCache.get(name) ?? null; + } + + getToolCallResult(toolName: string): ToolCallInvocation | null { + return this.toolCallResultCache.get(toolName) ?? null; + } + + // Clear methods + + clearResource(uri: string): void { + this.resourceContentCache.delete(uri); + } + + /** + * Clear all cached content for a given URI. + * This clears both regular resources cached by URI and resource templates + * that have a matching expandedUri. + * @param uri - The URI to clear from all caches + */ + clearResourceAndResourceTemplate(uri: string): void { + // Clear regular resource cache + this.resourceContentCache.delete(uri); + // Clear any resource templates with matching expandedUri + for (const [ + uriTemplate, + invocation, + ] of this.resourceTemplateContentCache.entries()) { + if (invocation.expandedUri === uri) { + this.resourceTemplateContentCache.delete(uriTemplate); + } + } + } + + clearResourceTemplate(uriTemplate: string): void { + this.resourceTemplateContentCache.delete(uriTemplate); + } + + clearPrompt(name: string): void { + this.promptContentCache.delete(name); + } + + clearToolCallResult(toolName: string): void { + this.toolCallResultCache.delete(toolName); + } + + clearAll(): void { + this.resourceContentCache.clear(); + this.resourceTemplateContentCache.clear(); + this.promptContentCache.clear(); + this.toolCallResultCache.clear(); + } + + // Write methods (for internal use by InspectorClient) + + setResource(uri: string, invocation: ResourceReadInvocation): void { + this.resourceContentCache.set(uri, invocation); + } + + setResourceTemplate( + uriTemplate: string, + invocation: ResourceTemplateReadInvocation, + ): void { + this.resourceTemplateContentCache.set(uriTemplate, invocation); + } + + setPrompt(name: string, invocation: PromptGetInvocation): void { + this.promptContentCache.set(name, invocation); + } + + setToolCallResult(toolName: string, invocation: ToolCallInvocation): void { + this.toolCallResultCache.set(toolName, invocation); + } +} diff --git a/shared/mcp/elicitationCreateMessage.ts b/shared/mcp/elicitationCreateMessage.ts new file mode 100644 index 000000000..725a99812 --- /dev/null +++ b/shared/mcp/elicitationCreateMessage.ts @@ -0,0 +1,50 @@ +import type { + ElicitRequest, + ElicitResult, +} from "@modelcontextprotocol/sdk/types.js"; +import { RELATED_TASK_META_KEY } from "@modelcontextprotocol/sdk/types.js"; + +/** + * Represents a pending elicitation request from the server + */ +export class ElicitationCreateMessage { + public readonly id: string; + public readonly timestamp: Date; + public readonly request: ElicitRequest; + public readonly taskId?: string; + private resolvePromise?: (result: ElicitResult) => void; + + constructor( + request: ElicitRequest, + resolve: (result: ElicitResult) => void, + private onRemove: (id: string) => void, + ) { + this.id = `elicitation-${Date.now()}-${Math.random()}`; + this.timestamp = new Date(); + this.request = request; + // Extract taskId from request params metadata if present + const relatedTask = request.params?._meta?.[RELATED_TASK_META_KEY]; + this.taskId = relatedTask?.taskId; + this.resolvePromise = resolve; + } + + /** + * Respond to the elicitation request with a result + */ + async respond(result: ElicitResult): Promise { + if (!this.resolvePromise) { + throw new Error("Request already resolved"); + } + this.resolvePromise(result); + this.resolvePromise = undefined; + // Remove from pending list after responding + this.remove(); + } + + /** + * Remove this pending elicitation from the list + */ + remove(): void { + this.onRemove(this.id); + } +} diff --git a/shared/mcp/fetchTracking.ts b/shared/mcp/fetchTracking.ts new file mode 100644 index 000000000..916427b2c --- /dev/null +++ b/shared/mcp/fetchTracking.ts @@ -0,0 +1,151 @@ +import type { FetchRequestEntryBase } from "./types.js"; + +export interface FetchTrackingCallbacks { + trackRequest?: (entry: FetchRequestEntryBase) => void; +} + +/** + * Creates a fetch wrapper that tracks HTTP requests and responses + */ +export function createFetchTracker( + baseFetch: typeof fetch, + callbacks: FetchTrackingCallbacks, +): typeof fetch { + return async ( + input: RequestInfo | URL, + init?: RequestInit, + ): Promise => { + const startTime = Date.now(); + const timestamp = new Date(); + const id = `${timestamp.getTime()}-${Math.random().toString(36).substr(2, 9)}`; + + // Extract request information + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + const method = init?.method || "GET"; + + // Extract headers + const requestHeaders: Record = {}; + if (input instanceof Request) { + input.headers.forEach((value, key) => { + requestHeaders[key] = value; + }); + } + if (init?.headers) { + const headers = new Headers(init.headers); + headers.forEach((value, key) => { + requestHeaders[key] = value; + }); + } + + // Extract body (if present and readable) + let requestBody: string | undefined; + if (init?.body) { + if (typeof init.body === "string") { + requestBody = init.body; + } else { + // Try to convert to string, but skip if it fails (e.g., ReadableStream) + try { + requestBody = String(init.body); + } catch { + requestBody = undefined; + } + } + } else if (input instanceof Request && input.body) { + // Try to clone and read the request body + // Clone protects the original body from being consumed + try { + const cloned = input.clone(); + requestBody = await cloned.text(); + } catch { + // Can't read body (might be consumed, not readable, or other issue) + requestBody = undefined; + } + } + + // Make the actual fetch request + let response: Response; + let error: string | undefined; + try { + response = await baseFetch(input, init); + } catch (err) { + error = err instanceof Error ? err.message : String(err); + // Create a minimal error entry + const entry: FetchRequestEntryBase = { + id, + timestamp, + method, + url, + requestHeaders, + requestBody, + error, + duration: Date.now() - startTime, + }; + callbacks.trackRequest?.(entry); + throw err; + } + + // Extract response information + const responseStatus = response.status; + const responseStatusText = response.statusText; + + // Extract response headers + const responseHeaders: Record = {}; + response.headers.forEach((value, key) => { + responseHeaders[key] = value; + }); + + // Check if this is a streaming response - if so, skip body reading entirely + // For streamable-http POST requests to /mcp, the response is always a stream + // that the transport needs to consume, so we should never try to read it + const contentType = response.headers.get("content-type"); + const isStream = + contentType?.includes("text/event-stream") || + contentType?.includes("application/x-ndjson") || + (method === "POST" && url.includes("/mcp")); + + let responseBody: string | undefined; + let duration: number; + + if (isStream) { + // For streams, don't try to read the body - just record metadata and return immediately + // The transport needs to consume the stream, so we can't clone/read it + duration = Date.now() - startTime; + } else { + // For regular responses, try to read the body (clone so we don't consume it) + if (response.body && !response.bodyUsed) { + try { + const cloned = response.clone(); + responseBody = await cloned.text(); + } catch { + // Can't read body (might be consumed, not readable, or other issue) + responseBody = undefined; + } + } + duration = Date.now() - startTime; + } + + // Create entry and track it + const entry: FetchRequestEntryBase = { + id, + timestamp, + method, + url, + requestHeaders, + requestBody, + responseStatus, + responseStatusText, + responseHeaders, + responseBody, + duration, + }; + + callbacks.trackRequest?.(entry); + + return response; + }; +} diff --git a/shared/mcp/index.ts b/shared/mcp/index.ts new file mode 100644 index 000000000..33bc106d6 --- /dev/null +++ b/shared/mcp/index.ts @@ -0,0 +1,59 @@ +// Main MCP client module +// Re-exports the primary API for MCP client/server interaction + +export { InspectorClient } from "./inspectorClient.js"; +export type { + InspectorClientOptions, + InspectorClientEnvironment, +} from "./inspectorClient.js"; + +// Re-export type-safe event target types for consumers +export type { InspectorClientEventMap } from "./inspectorClientEventTarget.js"; + +export { getServerType } from "./config.js"; + +// Re-export ContentCache +export { + ContentCache, + type ReadOnlyContentCache, + type ReadWriteContentCache, +} from "./contentCache.js"; + +// Re-export types used by consumers +export type { + // Transport factory types (required by InspectorClient) + CreateTransport, + CreateTransportOptions, + CreateTransportResult, + // Config types + MCPConfig, + MCPServerConfig, + ServerType, + // Connection and state types (used by components and hooks) + ConnectionStatus, + StderrLogEntry, + MessageEntry, + FetchRequestEntry, + FetchRequestEntryBase, + FetchRequestCategory, + ServerState, + // Invocation types (returned from InspectorClient methods) + ResourceReadInvocation, + ResourceTemplateReadInvocation, + PromptGetInvocation, + ToolCallInvocation, +} from "./types.js"; + +// Re-export JSON utilities +export type { JsonValue } from "../json/jsonUtils.js"; +export { + convertParameterValue, + convertToolParameters, + convertPromptArguments, +} from "../json/jsonUtils.js"; + +// Re-export session storage types +export type { + InspectorClientStorage, + InspectorClientSessionState, +} from "./sessionStorage.js"; diff --git a/shared/mcp/inspectorClient.ts b/shared/mcp/inspectorClient.ts new file mode 100644 index 000000000..ccee6bd5a --- /dev/null +++ b/shared/mcp/inspectorClient.ts @@ -0,0 +1,3059 @@ +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import type { + MCPServerConfig, + StderrLogEntry, + ConnectionStatus, + MessageEntry, + FetchRequestEntry, + FetchRequestEntryBase, + ResourceReadInvocation, + ResourceTemplateReadInvocation, + PromptGetInvocation, + ToolCallInvocation, +} from "./types.js"; +import { getServerType as getServerTypeFromConfig } from "./config.js"; +import type { + CreateTransport, + CreateTransportOptions, + ServerType, +} from "./types.js"; +import { + MessageTrackingTransport, + type MessageTrackingCallbacks, +} from "./messageTrackingTransport.js"; +import type { + JSONRPCRequest, + JSONRPCNotification, + JSONRPCResultResponse, + JSONRPCErrorResponse, + ServerCapabilities, + ClientCapabilities, + Implementation, + LoggingLevel, + Tool, + Resource, + ResourceTemplate, + Prompt, + Root, + CreateMessageResult, + ElicitResult, + CallToolResult, + Task, + Progress, + ProgressToken, +} from "@modelcontextprotocol/sdk/types.js"; +import type { + RequestOptions, + ProgressCallback, +} from "@modelcontextprotocol/sdk/shared/protocol.js"; +import { + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, + RootsListChangedNotificationSchema, + ToolListChangedNotificationSchema, + ResourceListChangedNotificationSchema, + PromptListChangedNotificationSchema, + ResourceUpdatedNotificationSchema, + CallToolResultSchema, + McpError, + ErrorCode, +} from "@modelcontextprotocol/sdk/types.js"; +import { + type JsonValue, + convertToolParameters, + convertPromptArguments, +} from "../json/jsonUtils.js"; +import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js"; +import { ContentCache, type ReadOnlyContentCache } from "./contentCache.js"; +import { InspectorClientEventTarget } from "./inspectorClientEventTarget.js"; +import { SamplingCreateMessage } from "./samplingCreateMessage.js"; +import { ElicitationCreateMessage } from "./elicitationCreateMessage.js"; +import type { + OAuthNavigation, + RedirectUrlProvider, +} from "../auth/providers.js"; +import { BaseOAuthClientProvider } from "../auth/providers.js"; +import type { OAuthStorage } from "../auth/storage.js"; +import type { AuthGuidedState, OAuthStep } from "../auth/types.js"; +import { EMPTY_GUIDED_STATE } from "../auth/types.js"; +import { OAuthStateMachine } from "../auth/state-machine.js"; +import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { auth } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { OAuthClientInformation } from "@modelcontextprotocol/sdk/shared/auth.js"; +import type pino from "pino"; +import { silentLogger } from "../auth/logger.js"; +import { createFetchTracker } from "./fetchTracking.js"; +import type { + InspectorClientStorage, + InspectorClientSessionState, +} from "./sessionStorage.js"; +import { parseOAuthState } from "../auth/utils.js"; + +/** + * Consolidated environment interface that defines all environment-specific seams. + * Each environment (Node, browser, tests) provides a complete implementation bundle. + */ +export interface InspectorClientEnvironment { + /** + * Factory that creates a client transport for the given server config. + * Required. Environment provides the implementation: + * - Node: createTransportNode + * - Browser: createRemoteTransport + */ + transport: CreateTransport; + + /** + * Optional fetch function for HTTP requests (OAuth discovery/token exchange and + * MCP transport). When provided, used for both auth and transport to bypass CORS. + * - Node: undefined (uses global fetch) + * - Browser: createRemoteFetch + */ + fetch?: typeof fetch; + + /** + * Optional logger for InspectorClient events (transport, OAuth, etc.). + * - Node: pino file logger + * - Browser: createRemoteLogger + */ + logger?: pino.Logger; + + /** + * OAuth environment components + */ + oauth?: { + /** + * OAuth storage implementation + * - Node: NodeOAuthStorage (file-based) + * - Browser: BrowserOAuthStorage (sessionStorage) or RemoteOAuthStorage (shared state) + */ + storage?: OAuthStorage; + + /** + * Navigation handler for redirecting users to authorization URLs + * - Node: ConsoleNavigation + * - Browser: BrowserNavigation + */ + navigation?: OAuthNavigation; + + /** + * Redirect URL provider + * - Node: from OAuth callback server + * - Browser: from window.location or callback route + */ + redirectUrlProvider?: RedirectUrlProvider; + }; +} + +export interface InspectorClientOptions { + /** + * Environment-specific implementations (transport, fetch, logger, OAuth components) + */ + environment: InspectorClientEnvironment; + + /** + * Client identity (name and version) + */ + clientIdentity?: { + name: string; + version: string; + }; + /** + * Maximum number of messages to store (0 = unlimited, but not recommended) + */ + maxMessages?: number; + + /** + * Maximum number of stderr log entries to store (0 = unlimited, but not recommended) + */ + maxStderrLogEvents?: number; + + /** + * Maximum number of fetch requests to store (0 = unlimited, but not recommended) + * Only applies to HTTP-based transports (SSE, streamable-http) + */ + maxFetchRequests?: number; + + /** + * Whether to pipe stderr for stdio transports (default: true for TUI, false for CLI) + */ + pipeStderr?: boolean; + + /** + * Whether to automatically sync lists (tools, resources, prompts) on connect and when + * list_changed notifications are received (default: true) + * If false, lists must be loaded manually via listTools(), listResources(), etc. + * Note: This only controls reloading; listChangedNotifications controls subscription. + */ + autoSyncLists?: boolean; + + /** + * Initial logging level to set after connection (if server supports logging) + * If not provided, logging level will not be set automatically + */ + initialLoggingLevel?: LoggingLevel; + + /** + * Whether to advertise sampling capability (default: true) + */ + sample?: boolean; + + /** + * Elicitation capability configuration + * - `true` - support form-based elicitation only (default, for backward compatibility) + * - `{ form: true }` - support form-based elicitation only + * - `{ url: true }` - support URL-based elicitation only + * - `{ form: true, url: true }` - support both form and URL-based elicitation + * - `false` or `undefined` - no elicitation support + */ + elicit?: + | boolean + | { + form?: boolean; + url?: boolean; + }; + + /** + * Initial roots to configure. If provided (even if empty array), the client will + * advertise roots capability and handle roots/list requests from the server. + */ + roots?: Root[]; + + /** + * Whether to enable listChanged notification handlers (default: true) + * If enabled, InspectorClient will subscribe to list_changed notifications and fire + * corresponding events (toolsListChanged, resourcesListChanged, promptsListChanged). + * If autoSyncLists is also true, lists will be automatically reloaded when notifications arrive. + */ + listChangedNotifications?: { + tools?: boolean; // default: true + resources?: boolean; // default: true + prompts?: boolean; // default: true + }; + + /** + * Whether to enable progress notification handling (default: true) + * If enabled, InspectorClient will register a handler for progress notifications and dispatch progressNotification events + */ + progress?: boolean; // default: true + + /** + * If true, receiving a progress notification resets the request timeout (default: true). + * Only applies to requests that can receive progress. Set to false for strict timeout caps. + */ + resetTimeoutOnProgress?: boolean; + + /** + * Per-request timeout in milliseconds. If not set, the SDK default (60_000) is used. + */ + timeout?: number; + + /** + * OAuth configuration (client credentials, scope, etc.) + * Note: OAuth environment components (storage, navigation, redirectUrlProvider) + * are in environment.oauth, but clientId/clientSecret/scope are config. + */ + oauth?: { + /** + * Preregistered client ID (optional, will use DCR if not provided) + * If clientMetadataUrl is provided, this is ignored (CIMD mode) + */ + clientId?: string; + + /** + * Preregistered client secret (optional, only if client requires secret) + * If clientMetadataUrl is provided, this is ignored (CIMD mode) + */ + clientSecret?: string; + + /** + * Client metadata URL for CIMD (Client ID Metadata Documents) mode + * If provided, enables URL-based client IDs (SEP-991) + * The URL becomes the client_id, and the authorization server fetches it to discover client metadata + */ + clientMetadataUrl?: string; + + /** + * OAuth scope (optional, will be discovered if not provided) + */ + scope?: string; + }; + + /** + * Optional storage for persisting session state across page navigations. + * When provided, InspectorClient will save/restore fetch requests, etc. + * during OAuth flows. + */ + sessionStorage?: InspectorClientStorage; + + /** + * Optional session ID. If not provided, will be extracted from OAuth state + * when OAuth flow starts. Used as key for sessionStorage. + */ + sessionId?: string; +} + +/** + * InspectorClient wraps an MCP Client and provides: + * - Message tracking and storage + * - Stderr log tracking and storage (for stdio transports) + * - EventTarget interface for React hooks (cross-platform: works in browser and Node.js) + * - Access to client functionality (prompts, resources, tools) + */ +// Maximum number of pages to fetch when paginating through lists +const MAX_PAGES = 100; + +export class InspectorClient extends InspectorClientEventTarget { + private client: Client | null = null; + private transport: any = null; + private baseTransport: any = null; + private messages: MessageEntry[] = []; + private stderrLogs: StderrLogEntry[] = []; + private fetchRequests: FetchRequestEntry[] = []; + private maxMessages: number; + private maxStderrLogEvents: number; + private maxFetchRequests: number; + private pipeStderr: boolean; + private autoSyncLists: boolean; + private initialLoggingLevel?: LoggingLevel; + private sample: boolean; + private elicit: boolean | { form?: boolean; url?: boolean }; + private progress: boolean; + private resetTimeoutOnProgress: boolean; + private requestTimeout: number | undefined; + private status: ConnectionStatus = "disconnected"; + // Server data + private tools: Tool[] = []; + private resources: Resource[] = []; + private resourceTemplates: ResourceTemplate[] = []; + private prompts: Prompt[] = []; + private capabilities?: ServerCapabilities; + private serverInfo?: Implementation; + private instructions?: string; + // Sampling requests + private pendingSamples: SamplingCreateMessage[] = []; + // Elicitation requests + private pendingElicitations: ElicitationCreateMessage[] = []; + // Roots (undefined means roots capability not enabled, empty array means enabled but no roots) + private roots: Root[] | undefined; + // Content cache + private cacheInternal: ContentCache; + public readonly cache: ReadOnlyContentCache; + // ListChanged notification configuration + private listChangedNotifications: { + tools: boolean; + resources: boolean; + prompts: boolean; + }; + // Resource subscriptions + private subscribedResources: Set = new Set(); + // Task tracking + private clientTasks: Map = new Map(); + // OAuth support + private oauthConfig?: InspectorClientOptions["oauth"] & + NonNullable; + private oauthStateMachine: OAuthStateMachine | null = null; + private oauthState: AuthGuidedState | null = null; + private logger: pino.Logger; + private transportClientFactory: CreateTransport; + private fetchFn?: typeof fetch; + private effectiveAuthFetch: typeof fetch; + // Session storage support + private sessionStorage?: InspectorClientOptions["sessionStorage"]; + private sessionId?: string; + + constructor( + private transportConfig: MCPServerConfig, + options: InspectorClientOptions, + ) { + super(); + // Extract environment components + this.transportClientFactory = options.environment.transport; + this.fetchFn = options.environment.fetch; + this.logger = options.environment.logger ?? silentLogger; + + // Initialize content cache + this.cacheInternal = new ContentCache(); + this.cache = this.cacheInternal; + this.maxMessages = options.maxMessages ?? 1000; + this.maxStderrLogEvents = options.maxStderrLogEvents ?? 1000; + this.maxFetchRequests = options.maxFetchRequests ?? 1000; + this.pipeStderr = options.pipeStderr ?? false; + this.autoSyncLists = options.autoSyncLists ?? true; + this.initialLoggingLevel = options.initialLoggingLevel; + this.sample = options.sample ?? true; + this.elicit = options.elicit ?? true; + this.progress = options.progress ?? true; + this.resetTimeoutOnProgress = options.resetTimeoutOnProgress ?? true; + this.requestTimeout = options.timeout; + // Only set roots if explicitly provided (even if empty array) - this enables roots capability + this.roots = options.roots; + // Initialize listChangedNotifications config (default: all enabled) + this.listChangedNotifications = { + tools: options.listChangedNotifications?.tools ?? true, + resources: options.listChangedNotifications?.resources ?? true, + prompts: options.listChangedNotifications?.prompts ?? true, + }; + + // Effective auth fetch: base fetch + tracking with category 'auth' + this.effectiveAuthFetch = this.buildEffectiveAuthFetch(); + + // Session storage support + this.sessionStorage = options.sessionStorage; + this.sessionId = options.sessionId; + + // Restore session if sessionId provided + if (this.sessionId && this.sessionStorage) { + this.restoreSession().catch((error) => { + this.logger.warn( + { + sessionId: this.sessionId, + error: error instanceof Error ? error.message : String(error), + }, + "Failed to restore session", + ); + }); + } + + // Merge OAuth config with environment components + if (options.oauth || options.environment.oauth) { + this.oauthConfig = { + // Environment components (storage, navigation, redirectUrlProvider) + ...options.environment.oauth, + // Config values (clientId, clientSecret, clientMetadataUrl, scope) + ...options.oauth, + }; + } + + // Transport is created in connect() (single place for create / wrap / attach). + + // Build client capabilities + const clientOptions: { capabilities?: ClientCapabilities } = {}; + const capabilities: ClientCapabilities = {}; + if (this.sample) { + capabilities.sampling = {}; + } + // Handle elicitation capability with mode support + if (this.elicit) { + const elicitationCap: NonNullable = {}; + + if (this.elicit === true) { + // Backward compatibility: `elicit: true` means form support only + elicitationCap.form = {}; + } else { + // Explicit mode configuration + if (this.elicit.form) { + elicitationCap.form = {}; + } + if (this.elicit.url) { + elicitationCap.url = {}; + } + } + + // Only add elicitation capability if at least one mode is enabled + if (Object.keys(elicitationCap).length > 0) { + capabilities.elicitation = elicitationCap; + } + } + // Advertise roots capability if roots option was provided (even if empty array) + if (this.roots !== undefined) { + capabilities.roots = { listChanged: true }; + } + if (Object.keys(capabilities).length > 0) { + clientOptions.capabilities = capabilities; + } + + this.client = new Client( + options.clientIdentity ?? { + name: "@modelcontextprotocol/inspector", + version: "0.18.0", + }, + Object.keys(clientOptions).length > 0 ? clientOptions : undefined, + ); + } + + private buildEffectiveAuthFetch(): typeof fetch { + const base = this.fetchFn ?? fetch; + return createFetchTracker(base, { + trackRequest: (entry) => + this.addFetchRequest({ ...entry, category: "auth" }), + }); + } + + private createMessageTrackingCallbacks(): MessageTrackingCallbacks { + return { + trackRequest: (message: JSONRPCRequest) => { + const entry: MessageEntry = { + id: `${Date.now()}-${Math.random()}`, + timestamp: new Date(), + direction: "request", + message, + }; + this.addMessage(entry); + }, + trackResponse: ( + message: JSONRPCResultResponse | JSONRPCErrorResponse, + ) => { + const messageId = message.id; + const requestEntry = this.messages.find( + (e) => + e.direction === "request" && + "id" in e.message && + e.message.id === messageId, + ); + if (requestEntry) { + this.updateMessageResponse(requestEntry, message); + } else { + const entry: MessageEntry = { + id: `${Date.now()}-${Math.random()}`, + timestamp: new Date(), + direction: "response", + message, + }; + this.addMessage(entry); + } + }, + trackNotification: (message: JSONRPCNotification) => { + const entry: MessageEntry = { + id: `${Date.now()}-${Math.random()}`, + timestamp: new Date(), + direction: "notification", + message, + }; + this.addMessage(entry); + }, + }; + } + + private attachTransportListeners(baseTransport: any): void { + baseTransport.onclose = () => { + if (this.status !== "disconnected") { + this.status = "disconnected"; + this.dispatchTypedEvent("statusChange", this.status); + this.dispatchTypedEvent("disconnect"); + } + }; + baseTransport.onerror = (error: Error) => { + this.status = "error"; + this.dispatchTypedEvent("statusChange", this.status); + this.dispatchTypedEvent("error", error); + }; + } + + /** + * Build RequestOptions for SDK client calls (timeout, resetTimeoutOnProgress, onprogress). + * When timeout is unset, SDK uses DEFAULT_REQUEST_TIMEOUT_MSEC (60s). + * + * When progress is enabled, we pass a per-request onprogress so the SDK routes progress and + * runs timeout reset. The SDK injects progressToken: messageId; we do not expose the caller's + * token to the server. We collect it from metadata and inject it into dispatched progressNotification + * events only, so listeners can correlate progress with the request that triggered it. + * + * @param progressToken Optional token from request metadata; injected into progressNotification + * events when provided (not sent to server). + */ + private getRequestOptions(progressToken?: ProgressToken): RequestOptions { + const opts: RequestOptions = { + resetTimeoutOnProgress: this.resetTimeoutOnProgress, + }; + if (this.requestTimeout !== undefined) { + opts.timeout = this.requestTimeout; + } + if (this.progress) { + const token = progressToken; + const onprogress: ProgressCallback = (progress: Progress) => { + const payload: Progress & { progressToken?: ProgressToken } = { + ...progress, + ...(token != null && { progressToken: token }), + }; + this.dispatchTypedEvent("progressNotification", payload); + }; + opts.onprogress = onprogress; + } + return opts; + } + + private isHttpOAuthConfig(): boolean { + const serverType = getServerTypeFromConfig(this.transportConfig); + return ( + (serverType === "sse" || serverType === "streamable-http") && + !!this.oauthConfig + ); + } + + /** + * Connect to the MCP server + */ + async connect(): Promise { + if (!this.client) { + throw new Error("Client not initialized"); + } + if (this.status === "connected") { + return; + } + + // Create transport (single place for create / wrap / attach). + if (!this.baseTransport) { + const transportOptions: CreateTransportOptions = { + fetchFn: this.fetchFn, + pipeStderr: this.pipeStderr, + onStderr: (entry: StderrLogEntry) => { + this.addStderrLog(entry); + }, + onFetchRequest: (entry: FetchRequestEntryBase) => { + this.addFetchRequest({ ...entry, category: "transport" }); + }, + }; + if (this.isHttpOAuthConfig()) { + const provider = await this.createOAuthProvider("normal"); + transportOptions.authProvider = provider; + } + const { transport: baseTransport } = this.transportClientFactory( + this.transportConfig, + transportOptions, + ); + this.baseTransport = baseTransport; + const messageTracking = this.createMessageTrackingCallbacks(); + this.transport = + this.maxMessages > 0 + ? new MessageTrackingTransport(baseTransport, messageTracking) + : baseTransport; + this.attachTransportListeners(this.baseTransport); + } + + if (!this.transport) { + throw new Error("Transport not initialized"); + } + + try { + this.status = "connecting"; + this.dispatchTypedEvent("statusChange", this.status); + + // Clear message history on connect (start fresh for new session) + // Don't clear stderrLogs - they persist across reconnects + this.messages = []; + this.dispatchTypedEvent("messagesChange"); + + await this.client.connect(this.transport); + this.status = "connected"; + this.dispatchTypedEvent("statusChange", this.status); + this.dispatchTypedEvent("connect"); + + // Always fetch server info (capabilities, serverInfo, instructions) - this is just cached data from initialize + await this.fetchServerInfo(); + + // Set initial logging level if configured and server supports it + if (this.initialLoggingLevel && this.capabilities?.logging) { + await this.client.setLoggingLevel( + this.initialLoggingLevel, + this.getRequestOptions(), + ); + } + + // Auto-fetch server contents (tools, resources, prompts) if enabled + if (this.autoSyncLists) { + await this.loadAllLists(); + } + + // Set up sampling request handler if sampling capability is enabled + if (this.sample && this.client) { + this.client.setRequestHandler(CreateMessageRequestSchema, (request) => { + return new Promise((resolve, reject) => { + const samplingRequest = new SamplingCreateMessage( + request, + (result) => { + resolve(result); + }, + (error) => { + reject(error); + }, + (id) => this.removePendingSample(id), + ); + this.addPendingSample(samplingRequest); + }); + }); + } + + // Set up elicitation request handler if elicitation capability is enabled + if (this.elicit && this.client) { + this.client.setRequestHandler(ElicitRequestSchema, (request) => { + return new Promise((resolve) => { + const elicitationRequest = new ElicitationCreateMessage( + request, + (result) => { + resolve(result); + }, + (id) => this.removePendingElicitation(id), + ); + this.addPendingElicitation(elicitationRequest); + }); + }); + } + + // Set up roots/list request handler if roots capability is enabled + if (this.roots !== undefined && this.client) { + this.client.setRequestHandler(ListRootsRequestSchema, async () => { + return { roots: this.roots ?? [] }; + }); + } + + // Set up notification handler for roots/list_changed from server + if (this.client) { + this.client.setNotificationHandler( + RootsListChangedNotificationSchema, + async () => { + // Dispatch event to notify UI that server's roots may have changed + // Note: rootsChange is a CustomEvent with Root[] payload, not a signal event + // We'll reload roots when the UI requests them, so we don't need to pass data here + // For now, we'll just dispatch an empty array as a signal to reload + this.dispatchTypedEvent("rootsChange", this.roots || []); + }, + ); + } + + // Set up listChanged notification handlers based on config + if (this.client) { + // Tools listChanged handler + // Only register if both client config and server capability are enabled + if ( + this.listChangedNotifications.tools && + this.capabilities?.tools?.listChanged + ) { + this.client.setNotificationHandler( + ToolListChangedNotificationSchema, + async () => { + // Always fire notification event (for tracking) + this.dispatchTypedEvent("toolsListChanged"); + // Only reload if autoSyncLists is enabled + if (this.autoSyncLists) { + await this.listAllTools(); + } + }, + ); + } + // Note: If handler should not be registered, we don't set it + // The SDK client will ignore notifications for which no handler is registered + + // Resources listChanged handler (reloads both resources and resource templates) + if ( + this.listChangedNotifications.resources && + this.capabilities?.resources?.listChanged + ) { + this.client.setNotificationHandler( + ResourceListChangedNotificationSchema, + async () => { + // Always fire notification event (for tracking) + this.dispatchTypedEvent("resourcesListChanged"); + // Only reload if autoSyncLists is enabled + if (this.autoSyncLists) { + // Resource templates are part of the resources capability + await this.listAllResources(); + await this.listAllResourceTemplates(); + } + }, + ); + } + + // Prompts listChanged handler + if ( + this.listChangedNotifications.prompts && + this.capabilities?.prompts?.listChanged + ) { + this.client.setNotificationHandler( + PromptListChangedNotificationSchema, + async () => { + // Always fire notification event (for tracking) + this.dispatchTypedEvent("promptsListChanged"); + // Only reload if autoSyncLists is enabled + if (this.autoSyncLists) { + await this.listAllPrompts(); + } + }, + ); + } + + // Resource updated notification handler (only if server supports subscriptions) + if (this.capabilities?.resources?.subscribe === true) { + this.client.setNotificationHandler( + ResourceUpdatedNotificationSchema, + async (notification) => { + const uri = notification.params.uri; + // Only process if we're subscribed to this resource + if (this.subscribedResources.has(uri)) { + // Clear cache for this resource (handles both regular resources and resource templates) + this.cacheInternal.clearResourceAndResourceTemplate(uri); + // Dispatch event to notify UI + this.dispatchTypedEvent("resourceUpdated", { uri }); + } + }, + ); + } + + // Progress: we use per-request onprogress (see getRequestOptions). We do not register + // a progress notification handler so the Protocol's _onprogress stays; timeout reset + // and routing work, and we inject the caller's progressToken into dispatched events. + } + } catch (error) { + this.status = "error"; + this.dispatchTypedEvent("statusChange", this.status); + this.dispatchTypedEvent( + "error", + error instanceof Error ? error : new Error(String(error)), + ); + throw error; + } + } + + /** + * Disconnect from the MCP server + */ + async disconnect(): Promise { + if (this.client) { + try { + await this.client.close(); + } catch (error) { + // Ignore errors on close + } + } + // Null out transport so next connect() creates a fresh one. + this.baseTransport = null; + this.transport = null; + // Update status - transport onclose handler will also fire and clear state + // But we also do it here in case disconnect() is called directly + if (this.status !== "disconnected") { + this.status = "disconnected"; + this.dispatchTypedEvent("statusChange", this.status); + this.dispatchTypedEvent("disconnect"); + } + + // Clear server state (tools, resources, resource templates, prompts) on disconnect + // These are only valid when connected + this.tools = []; + this.resources = []; + this.resourceTemplates = []; + this.prompts = []; + this.pendingSamples = []; + this.pendingElicitations = []; + // Clear all cached content on disconnect + this.cacheInternal.clearAll(); + // Clear resource subscriptions on disconnect + this.subscribedResources.clear(); + // Clear active tasks on disconnect + this.clientTasks.clear(); + this.capabilities = undefined; + this.serverInfo = undefined; + this.instructions = undefined; + this.dispatchTypedEvent("toolsChange", this.tools); + this.dispatchTypedEvent("resourcesChange", this.resources); + this.dispatchTypedEvent("pendingSamplesChange", this.pendingSamples); + this.dispatchTypedEvent("promptsChange", this.prompts); + this.dispatchTypedEvent("capabilitiesChange", this.capabilities); + this.dispatchTypedEvent("serverInfoChange", this.serverInfo); + this.dispatchTypedEvent("instructionsChange", this.instructions); + } + + /** + * Get the underlying MCP Client + */ + getClient(): Client { + if (!this.client) { + throw new Error("Client not initialized"); + } + return this.client; + } + + /** + * Get all messages + */ + getMessages(): MessageEntry[] { + return [...this.messages]; + } + + /** + * Get all stderr logs + */ + getStderrLogs(): StderrLogEntry[] { + return [...this.stderrLogs]; + } + + /** + * Get the current connection status + */ + getStatus(): ConnectionStatus { + return this.status; + } + + /** + * Get the MCP server configuration used to create this client + */ + getTransportConfig(): MCPServerConfig { + return this.transportConfig; + } + + /** + * Get the server type (stdio, sse, or streamable-http) + */ + getServerType(): ServerType { + return getServerTypeFromConfig(this.transportConfig); + } + + /** + * Get all tools + */ + getTools(): Tool[] { + return [...this.tools]; + } + + /** + * Get all resources + */ + getResources(): Resource[] { + return [...this.resources]; + } + + /** + * Get resource templates + * @returns Array of resource templates + */ + getResourceTemplates(): ResourceTemplate[] { + return [...this.resourceTemplates]; + } + + /** + * Get all prompts + */ + getPrompts(): Prompt[] { + return [...this.prompts]; + } + + /** + * Clear all tools and dispatch change event + */ + clearTools(): void { + this.tools = []; + this.dispatchTypedEvent("toolsChange", this.tools); + } + + /** + * Clear all resources and dispatch change event + */ + clearResources(): void { + this.resources = []; + this.dispatchTypedEvent("resourcesChange", this.resources); + } + + /** + * Clear all resource templates and dispatch change event + */ + clearResourceTemplates(): void { + this.resourceTemplates = []; + this.dispatchTypedEvent("resourceTemplatesChange", this.resourceTemplates); + } + + /** + * Clear all prompts and dispatch change event + */ + clearPrompts(): void { + this.prompts = []; + this.dispatchTypedEvent("promptsChange", this.prompts); + } + + /** + * Get all active tasks + */ + getClientTasks(): Task[] { + return Array.from(this.clientTasks.values()); + } + + /** + * Get task capabilities from server + * @returns Task capabilities or undefined if not supported + */ + getTaskCapabilities(): { list: boolean; cancel: boolean } | undefined { + if (!this.capabilities?.tasks) { + return undefined; + } + return { + list: !!this.capabilities.tasks.list, + cancel: !!this.capabilities.tasks.cancel, + }; + } + + /** + * Update task cache (internal helper) + */ + private updateClientTask(task: Task): void { + this.clientTasks.set(task.taskId, task); + } + + /** + * Get task status by taskId + * @param taskId Task identifier + * @returns Task status (GetTaskResult is the task itself) + */ + async getTask(taskId: string): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + const result = await this.client.experimental.tasks.getTask( + taskId, + this.getRequestOptions(), + ); + // GetTaskResult is the task itself (taskId, status, ttl, etc.) + // Update task cache with result + this.updateClientTask(result); + // Dispatch event + this.dispatchTypedEvent("taskStatusChange", { + taskId: result.taskId, + task: result, + }); + return result; + } + + /** + * Get task result by taskId + * @param taskId Task identifier + * @returns Task result + */ + async getTaskResult(taskId: string): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + // Use CallToolResultSchema for validation + return await this.client.experimental.tasks.getTaskResult( + taskId, + CallToolResultSchema, + this.getRequestOptions(), + ); + } + + /** + * Cancel a running task + * @param taskId Task identifier + * @returns Cancel result + */ + async cancelTask(taskId: string): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + await this.client.experimental.tasks.cancelTask( + taskId, + this.getRequestOptions(), + ); + // Update task cache if we have it + const task = this.clientTasks.get(taskId); + if (task) { + const cancelledTask: Task = { + ...task, + status: "cancelled", + lastUpdatedAt: new Date().toISOString(), + }; + this.updateClientTask(cancelledTask); + } + // Dispatch event + this.dispatchTypedEvent("taskCancelled", { taskId }); + } + + /** + * List all tasks with optional pagination + * @param cursor Optional pagination cursor + * @returns List of tasks with optional next cursor + */ + async listTasks( + cursor?: string, + ): Promise<{ tasks: Task[]; nextCursor?: string }> { + if (!this.client) { + throw new Error("Client is not connected"); + } + const result = await this.client.experimental.tasks.listTasks( + cursor, + this.getRequestOptions(), + ); + // Update task cache with all returned tasks + for (const task of result.tasks) { + this.updateClientTask(task); + } + // Dispatch event with all tasks + this.dispatchTypedEvent("tasksChange", result.tasks); + return result; + } + + /** + * Get all pending sampling requests + */ + getPendingSamples(): SamplingCreateMessage[] { + return [...this.pendingSamples]; + } + + /** + * Add a pending sampling request + */ + private addPendingSample(sample: SamplingCreateMessage): void { + this.pendingSamples.push(sample); + this.dispatchTypedEvent("pendingSamplesChange", this.pendingSamples); + this.dispatchTypedEvent("newPendingSample", sample); + } + + /** + * Remove a pending sampling request by ID + */ + removePendingSample(id: string): void { + const index = this.pendingSamples.findIndex((s) => s.id === id); + if (index !== -1) { + this.pendingSamples.splice(index, 1); + this.dispatchTypedEvent("pendingSamplesChange", this.pendingSamples); + } + } + + /** + * Get all pending elicitation requests + */ + getPendingElicitations(): ElicitationCreateMessage[] { + return [...this.pendingElicitations]; + } + + /** + * Add a pending elicitation request + */ + private addPendingElicitation(elicitation: ElicitationCreateMessage): void { + this.pendingElicitations.push(elicitation); + this.dispatchTypedEvent( + "pendingElicitationsChange", + this.pendingElicitations, + ); + this.dispatchTypedEvent("newPendingElicitation", elicitation); + } + + /** + * Remove a pending elicitation request by ID + */ + removePendingElicitation(id: string): void { + const index = this.pendingElicitations.findIndex((e) => e.id === id); + if (index !== -1) { + this.pendingElicitations.splice(index, 1); + this.dispatchTypedEvent( + "pendingElicitationsChange", + this.pendingElicitations, + ); + } + } + + /** + * Get server capabilities + */ + getCapabilities(): ServerCapabilities | undefined { + return this.capabilities; + } + + /** + * Get server info (name, version) + */ + getServerInfo(): Implementation | undefined { + return this.serverInfo; + } + + /** + * Get server instructions + */ + getInstructions(): string | undefined { + return this.instructions; + } + + /** + * Set the logging level for the MCP server + * @param level Logging level to set + * @throws Error if client is not connected or server doesn't support logging + */ + async setLoggingLevel(level: LoggingLevel): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + if (!this.capabilities?.logging) { + throw new Error("Server does not support logging"); + } + await this.client.setLoggingLevel(level, this.getRequestOptions()); + } + + /** + * Fetch a specific tool by name without side effects (no state updates, no events) + * First checks if the tool is already loaded, then fetches pages until found or exhausted + * Used by callTool/callToolStream to check tool schema before calling + * @param name Tool name to fetch + * @param metadata Optional metadata to include in the request + * @returns The tool if found, undefined otherwise + */ + private async fetchTool( + name: string, + metadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + + // First check if tool is already loaded + const existingTool = this.tools.find((t) => t.name === name); + if (existingTool) { + return existingTool; + } + + // Tool not found, fetch pages until we find it + // Use client directly to avoid modifying this.tools + let cursor: string | undefined; + let pageCount = 0; + + try { + do { + const params: any = + metadata && Object.keys(metadata).length > 0 + ? { _meta: metadata } + : {}; + if (cursor) { + params.cursor = cursor; + } + const response = await this.client.listTools( + params, + this.getRequestOptions(metadata?.progressToken), + ); + const tools = response.tools || []; + + // Check if we found the tool + const tool = tools.find((t) => t.name === name); + if (tool) { + return tool; // Found it, return early + } + + cursor = response.nextCursor; + pageCount++; + if (pageCount >= MAX_PAGES) { + throw new Error( + `Maximum pagination limit (${MAX_PAGES} pages) reached while searching for tool "${name}"`, + ); + } + } while (cursor); + + // Tool not found after searching all pages + return undefined; + } catch (error) { + throw new Error( + `Failed to fetch tool "${name}": ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * List available tools with pagination support + * @param cursor Optional cursor for pagination. If not provided, clears existing tools and starts fresh. + * @param metadata Optional metadata to include in the request + * @param suppressEvents If true, does not dispatch toolsChange event (default: false) + * @returns Object containing tools array and optional nextCursor + */ + async listTools( + cursor?: string, + metadata?: Record, + suppressEvents: boolean = false, + ): Promise<{ tools: Tool[]; nextCursor?: string }> { + if (!this.client) { + throw new Error("Client is not connected"); + } + const params: any = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + if (cursor) { + params.cursor = cursor; + } + const response = await this.client.listTools( + params, + this.getRequestOptions(metadata?.progressToken), + ); + const tools = response.tools || []; + + // Update internal state: reset if no cursor, append if cursor provided + if (cursor) { + // Append to existing tools + this.tools.push(...tools); + } else { + // Clear and start fresh + this.tools = tools; + } + + // Dispatch change event unless suppressed + if (!suppressEvents) { + this.dispatchTypedEvent("toolsChange", this.tools); + } + + return { + tools, + nextCursor: response.nextCursor, + }; + } + + /** + * List all available tools (fetches all pages) + * @param metadata Optional metadata to include in the request + * @returns Array of all tools + */ + async listAllTools(metadata?: Record): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + // Store current tool names before fetching + const currentNames = new Set(this.tools.map((t) => t.name)); + + // Fetch all pages (suppress events during pagination) + let cursor: string | undefined; + let pageCount = 0; + + do { + const result = await this.listTools(cursor, metadata, true); + cursor = result.nextCursor; + pageCount++; + if (pageCount >= MAX_PAGES) { + throw new Error( + `Maximum pagination limit (${MAX_PAGES} pages) reached while listing tools`, + ); + } + } while (cursor); + + // Find removed tool names by comparing with current tools + const newNames = new Set(this.tools.map((t) => t.name)); + // Clear cache for removed tools + for (const name of currentNames) { + if (!newNames.has(name)) { + this.cacheInternal.clearToolCallResult(name); + } + } + + // Dispatch final change event (listTools calls were suppressed) + this.dispatchTypedEvent("toolsChange", this.tools); + return this.tools; + } catch (error) { + throw new Error( + `Failed to list all tools: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * Call a tool by name + * @param name Tool name + * @param args Tool arguments + * @param generalMetadata Optional general metadata + * @param toolSpecificMetadata Optional tool-specific metadata (takes precedence over general) + * @returns Tool call response + */ + async callTool( + name: string, + args: Record, + generalMetadata?: Record, + toolSpecificMetadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + + // Check if tool requires task support BEFORE try block + // This ensures the error is thrown and not caught + const tool = await this.fetchTool(name, generalMetadata); + if (tool?.execution?.taskSupport === "required") { + throw new Error( + `Tool "${name}" requires task support. Use callToolStream() instead of callTool().`, + ); + } + + try { + let convertedArgs: Record = args; + + if (tool) { + // Convert parameters based on the tool's schema, but only for string values + // since we now accept pre-parsed values from the CLI + const stringArgs: Record = {}; + for (const [key, value] of Object.entries(args)) { + if (typeof value === "string") { + stringArgs[key] = value; + } + } + + if (Object.keys(stringArgs).length > 0) { + const convertedStringArgs = convertToolParameters(tool, stringArgs); + convertedArgs = { ...args, ...convertedStringArgs }; + } + } + + // Merge general metadata with tool-specific metadata + // Tool-specific metadata takes precedence over general metadata + let mergedMetadata: Record | undefined; + if (generalMetadata || toolSpecificMetadata) { + mergedMetadata = { + ...(generalMetadata || {}), + ...(toolSpecificMetadata || {}), + }; + } + + const timestamp = new Date(); + const metadata = + mergedMetadata && Object.keys(mergedMetadata).length > 0 + ? mergedMetadata + : undefined; + + const result = await this.client.callTool( + { + name: name, + arguments: convertedArgs, + _meta: metadata, + }, + undefined, + this.getRequestOptions(metadata?.progressToken), + ); + + const invocation: ToolCallInvocation = { + toolName: name, + params: args, + result: result as CallToolResult, + timestamp, + success: true, + metadata, + }; + + // Store in cache + this.cacheInternal.setToolCallResult(name, invocation); + // Dispatch event + this.dispatchTypedEvent("toolCallResultChange", { + toolName: name, + params: args, + result: invocation.result, + timestamp, + success: true, + metadata, + }); + + return invocation; + } catch (error) { + // Merge general metadata with tool-specific metadata for error case + let mergedMetadata: Record | undefined; + if (generalMetadata || toolSpecificMetadata) { + mergedMetadata = { + ...(generalMetadata || {}), + ...(toolSpecificMetadata || {}), + }; + } + + const timestamp = new Date(); + const metadata = + mergedMetadata && Object.keys(mergedMetadata).length > 0 + ? mergedMetadata + : undefined; + + const invocation: ToolCallInvocation = { + toolName: name, + params: args, + result: null, + timestamp, + success: false, + error: error instanceof Error ? error.message : String(error), + metadata, + }; + + // Store in cache (even on error) + this.cacheInternal.setToolCallResult(name, invocation); + // Dispatch event + this.dispatchTypedEvent("toolCallResultChange", { + toolName: name, + params: args, + result: null, + timestamp, + success: false, + error: invocation.error, + metadata, + }); + + throw error; + } + } + + /** + * Call a tool with task support (streaming) + * This method supports tools with taskSupport: "required", "optional", or "forbidden" + * @param name Tool name + * @param args Tool arguments + * @param generalMetadata Optional general metadata + * @param toolSpecificMetadata Optional tool-specific metadata (takes precedence over general) + * @returns Tool call response + */ + async callToolStream( + name: string, + args: Record, + generalMetadata?: Record, + toolSpecificMetadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + const tool = await this.fetchTool(name, generalMetadata); + + let convertedArgs: Record = args; + + if (tool) { + // Convert parameters based on the tool's schema, but only for string values + const stringArgs: Record = {}; + for (const [key, value] of Object.entries(args)) { + if (typeof value === "string") { + stringArgs[key] = value; + } + } + + if (Object.keys(stringArgs).length > 0) { + const convertedStringArgs = convertToolParameters(tool, stringArgs); + convertedArgs = { ...args, ...convertedStringArgs }; + } + } + + // Merge general metadata with tool-specific metadata + let mergedMetadata: Record | undefined; + if (generalMetadata || toolSpecificMetadata) { + mergedMetadata = { + ...(generalMetadata || {}), + ...(toolSpecificMetadata || {}), + }; + } + + const timestamp = new Date(); + const metadata = + mergedMetadata && Object.keys(mergedMetadata).length > 0 + ? mergedMetadata + : undefined; + + // Call the streaming API + // Metadata should be in the params, not in options + const streamParams: any = { + name: name, + arguments: convertedArgs, + }; + if (metadata) { + streamParams._meta = metadata; + } + const stream = this.client.experimental.tasks.callToolStream( + streamParams, + undefined, // Use default CallToolResultSchema + this.getRequestOptions(metadata?.progressToken), + ); + + let finalResult: CallToolResult | undefined; + let taskId: string | undefined; + let error: Error | undefined; + + // Iterate through the async generator + for await (const message of stream) { + switch (message.type) { + case "taskCreated": + // Task was created - update cache and dispatch event + this.updateClientTask(message.task); + taskId = message.task.taskId; + this.dispatchTypedEvent("taskCreated", { + taskId: message.task.taskId, + task: message.task, + }); + break; + + case "taskStatus": + // Task status updated - update cache and dispatch event + this.updateClientTask(message.task); + if (!taskId) { + taskId = message.task.taskId; + } + this.dispatchTypedEvent("taskStatusChange", { + taskId: message.task.taskId, + task: message.task, + }); + break; + + case "result": + // Task completed - update cache, dispatch event, and store result + // message.result is already CallToolResult from the stream + finalResult = message.result as CallToolResult; + if (taskId) { + // Update task status to completed if we have the task + const task = this.clientTasks.get(taskId); + if (task) { + const completedTask: Task = { + ...task, + status: "completed", + lastUpdatedAt: new Date().toISOString(), + }; + this.updateClientTask(completedTask); + this.dispatchTypedEvent("taskCompleted", { + taskId, + result: finalResult, + }); + } + } + break; + + case "error": + // Task failed - dispatch event and store error + error = new Error(message.error.message || "Task execution failed"); + if (taskId) { + // Update task status to failed if we have the task + const task = this.clientTasks.get(taskId); + if (task) { + const failedTask: Task = { + ...task, + status: "failed", + lastUpdatedAt: new Date().toISOString(), + statusMessage: message.error.message, + }; + this.updateClientTask(failedTask); + this.dispatchTypedEvent("taskFailed", { + taskId, + error: message.error, + }); + } + } + break; + } + } + + // If we got an error, throw it + if (error) { + throw error; + } + + // If we didn't get a result, something went wrong + // This can happen if the task completed but result wasn't in the stream + // Try to get it from the task result endpoint + if (!finalResult && taskId) { + try { + finalResult = await this.client.experimental.tasks.getTaskResult( + taskId, + undefined, + this.getRequestOptions(), // no metadata for fallback + ); + } catch (resultError) { + throw new Error( + `Tool call did not return a result: ${resultError instanceof Error ? resultError.message : String(resultError)}`, + ); + } + } + if (!finalResult) { + throw new Error("Tool call did not return a result"); + } + + const invocation: ToolCallInvocation = { + toolName: name, + params: args, + result: finalResult, + timestamp, + success: true, + metadata, + }; + + // Store in cache + this.cacheInternal.setToolCallResult(name, invocation); + // Dispatch event + this.dispatchTypedEvent("toolCallResultChange", { + toolName: name, + params: args, + result: invocation.result, + timestamp, + success: true, + metadata, + }); + + return invocation; + } catch (error) { + // Merge general metadata with tool-specific metadata for error case + let mergedMetadata: Record | undefined; + if (generalMetadata || toolSpecificMetadata) { + mergedMetadata = { + ...(generalMetadata || {}), + ...(toolSpecificMetadata || {}), + }; + } + + const timestamp = new Date(); + const metadata = + mergedMetadata && Object.keys(mergedMetadata).length > 0 + ? mergedMetadata + : undefined; + + const invocation: ToolCallInvocation = { + toolName: name, + params: args, + result: null, + timestamp, + success: false, + error: error instanceof Error ? error.message : String(error), + metadata, + }; + + // Store in cache + this.cacheInternal.setToolCallResult(name, invocation); + // Dispatch event + this.dispatchTypedEvent("toolCallResultChange", { + toolName: name, + params: args, + result: null, + timestamp, + success: false, + error: error instanceof Error ? error.message : String(error), + metadata, + }); + + // Re-throw error + throw error; + } + } + + /** + * List available resources with pagination support + * @param cursor Optional cursor for pagination. If not provided, clears existing resources and starts fresh. + * @param metadata Optional metadata to include in the request + * @param suppressEvents If true, does not dispatch resourcesChange event (default: false) + * @returns Object containing resources array and optional nextCursor + */ + async listResources( + cursor?: string, + metadata?: Record, + suppressEvents: boolean = false, + ): Promise<{ resources: Resource[]; nextCursor?: string }> { + if (!this.client) { + throw new Error("Client is not connected"); + } + const params: any = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + if (cursor) { + params.cursor = cursor; + } + const response = await this.client.listResources( + params, + this.getRequestOptions(metadata?.progressToken), + ); + const resources = response.resources || []; + + // Update internal state: reset if no cursor, append if cursor provided + if (cursor) { + // Append to existing resources + this.resources.push(...resources); + } else { + // Clear and start fresh + this.resources = resources; + } + + // Dispatch change event unless suppressed + if (!suppressEvents) { + this.dispatchTypedEvent("resourcesChange", this.resources); + } + + return { + resources, + nextCursor: response.nextCursor, + }; + } + + /** + * List all available resources (fetches all pages) + * @param metadata Optional metadata to include in the request + * @returns Array of all resources + */ + async listAllResources( + metadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + // Store current URIs before fetching (capture before first page resets the list) + const currentUris = new Set(this.resources.map((r) => r.uri)); + + // Fetch all pages (suppress events during pagination) + // First page resets the list, subsequent pages append + let cursor: string | undefined; + let pageCount = 0; + + do { + const result = await this.listResources(cursor, metadata, true); + cursor = result.nextCursor; + pageCount++; + if (pageCount >= MAX_PAGES) { + throw new Error( + `Maximum pagination limit (${MAX_PAGES} pages) reached while listing resources`, + ); + } + } while (cursor); + + // Find removed URIs by comparing previous state with new state + const newUris = new Set(this.resources.map((r) => r.uri)); + // Clear cache for removed resources (only if we had resources before) + if (currentUris.size > 0) { + for (const uri of currentUris) { + if (!newUris.has(uri)) { + this.cacheInternal.clearResource(uri); + } + } + } + + // Dispatch final change event (listResources calls were suppressed) + this.dispatchTypedEvent("resourcesChange", this.resources); + // Note: Cached content for existing resources is automatically preserved + return this.resources; + } catch (error) { + throw new Error( + `Failed to list all resources: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * Read a resource by URI + * @param uri Resource URI + * @param metadata Optional metadata to include in the request + * @returns Resource content + */ + async readResource( + uri: string, + metadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + const params: any = { uri }; + if (metadata && Object.keys(metadata).length > 0) { + params._meta = metadata; + } + const result = await this.client.readResource( + params, + this.getRequestOptions(metadata?.progressToken), + ); + const invocation: ResourceReadInvocation = { + result, + timestamp: new Date(), + uri, + metadata, + }; + // Store in cache + this.cacheInternal.setResource(uri, invocation); + // Dispatch event + this.dispatchTypedEvent("resourceContentChange", { + uri, + content: invocation, + timestamp: invocation.timestamp, + }); + return invocation; + } + + /** + * Read a resource from a template by expanding the template URI with parameters + * This encapsulates the business logic of template expansion and associates the + * loaded resource with its template in InspectorClient state + * @param templateName The name/ID of the resource template + * @param params Parameters to fill in the template variables + * @param metadata Optional metadata to include in the request + * @returns The resource content along with expanded URI and template name + * @throws Error if template is not found or URI expansion fails + */ + async readResourceFromTemplate( + uriTemplate: string, + params: Record, + metadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + + // Look up template in resourceTemplates by uriTemplate (the unique identifier) + const template = this.resourceTemplates.find( + (t) => t.uriTemplate === uriTemplate, + ); + + if (!template) { + throw new Error( + `Resource template with uriTemplate "${uriTemplate}" not found`, + ); + } + + if (!template.uriTemplate) { + throw new Error(`Resource template does not have a uriTemplate property`); + } + + // Get the uriTemplate string (the unique ID of the template) + const uriTemplateString = template.uriTemplate; + + // Expand the template's uriTemplate using the provided params + let expandedUri: string; + try { + const uriTemplate = new UriTemplate(uriTemplateString); + expandedUri = uriTemplate.expand(params); + } catch (error) { + throw new Error( + `Failed to expand URI template "${uriTemplate}": ${error instanceof Error ? error.message : String(error)}`, + ); + } + + // Always fetch fresh content: Call readResource with expanded URI + const readInvocation = await this.readResource(expandedUri, metadata); + + // Create the template invocation object + const invocation: ResourceTemplateReadInvocation = { + uriTemplate: uriTemplateString, + expandedUri, + result: readInvocation.result, + timestamp: readInvocation.timestamp, + params, + metadata, + }; + + // Store in cache + this.cacheInternal.setResourceTemplate(uriTemplateString, invocation); + // Dispatch event + this.dispatchTypedEvent("resourceTemplateContentChange", { + uriTemplate: uriTemplateString, + content: invocation, + params, + timestamp: invocation.timestamp, + }); + + return invocation; + } + + /** + * List resource templates with pagination support + * @param cursor Optional cursor for pagination. If not provided, clears existing resource templates and starts fresh. + * @param metadata Optional metadata to include in the request + * @param suppressEvents If true, does not dispatch resourceTemplatesChange event (default: false) + * @returns Object containing resourceTemplates array and optional nextCursor + */ + async listResourceTemplates( + cursor?: string, + metadata?: Record, + suppressEvents: boolean = false, + ): Promise<{ resourceTemplates: ResourceTemplate[]; nextCursor?: string }> { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + const params: any = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + if (cursor) { + params.cursor = cursor; + } + const response = await this.client.listResourceTemplates( + params, + this.getRequestOptions(metadata?.progressToken), + ); + const resourceTemplates = response.resourceTemplates || []; + + // Update internal state: reset if no cursor, append if cursor provided + if (cursor) { + // Append to existing resource templates + this.resourceTemplates.push(...resourceTemplates); + } else { + // Clear and start fresh + this.resourceTemplates = resourceTemplates; + } + + // Dispatch change event unless suppressed + if (!suppressEvents) { + this.dispatchTypedEvent( + "resourceTemplatesChange", + this.resourceTemplates, + ); + } + + return { + resourceTemplates, + nextCursor: response.nextCursor, + }; + } catch (error) { + throw new Error( + `Failed to list resource templates: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * List all resource templates (fetches all pages) + * @param metadata Optional metadata to include in the request + * @returns Array of all resource templates + */ + async listAllResourceTemplates( + metadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + // Store current uriTemplates before fetching + const currentUriTemplates = new Set( + this.resourceTemplates.map((t) => t.uriTemplate), + ); + + // Fetch all pages (suppress events during pagination) + let cursor: string | undefined; + let pageCount = 0; + + do { + const result = await this.listResourceTemplates(cursor, metadata, true); + cursor = result.nextCursor; + pageCount++; + if (pageCount >= MAX_PAGES) { + throw new Error( + `Maximum pagination limit (${MAX_PAGES} pages) reached while listing resource templates`, + ); + } + } while (cursor); + + // Find removed uriTemplates by comparing with current templates + const newUriTemplates = new Set( + this.resourceTemplates.map((t) => t.uriTemplate), + ); + // Clear cache for removed templates + for (const uriTemplate of currentUriTemplates) { + if (!newUriTemplates.has(uriTemplate)) { + this.cacheInternal.clearResourceTemplate(uriTemplate); + } + } + + // Dispatch final change event (listResourceTemplates calls were suppressed) + this.dispatchTypedEvent( + "resourceTemplatesChange", + this.resourceTemplates, + ); + // Note: Cached content for existing templates is automatically preserved + return this.resourceTemplates; + } catch (error) { + throw new Error( + `Failed to list all resource templates: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * List available prompts with pagination support + * @param cursor Optional cursor for pagination. If not provided, clears existing prompts and starts fresh. + * @param metadata Optional metadata to include in the request + * @param suppressEvents If true, does not dispatch promptsChange event (default: false) + * @returns Object containing prompts array and optional nextCursor + */ + async listPrompts( + cursor?: string, + metadata?: Record, + suppressEvents: boolean = false, + ): Promise<{ prompts: Prompt[]; nextCursor?: string }> { + if (!this.client) { + throw new Error("Client is not connected"); + } + const params: any = + metadata && Object.keys(metadata).length > 0 ? { _meta: metadata } : {}; + if (cursor) { + params.cursor = cursor; + } + const response = await this.client.listPrompts( + params, + this.getRequestOptions(metadata?.progressToken), + ); + const prompts = response.prompts || []; + + // Update internal state: reset if no cursor, append if cursor provided + if (cursor) { + // Append to existing prompts + this.prompts.push(...prompts); + } else { + // Clear and start fresh + this.prompts = prompts; + } + + // Dispatch change event unless suppressed + if (!suppressEvents) { + this.dispatchTypedEvent("promptsChange", this.prompts); + } + + return { + prompts, + nextCursor: response.nextCursor, + }; + } + + /** + * List all available prompts (fetches all pages) + * @param metadata Optional metadata to include in the request + * @returns Array of all prompts + */ + async listAllPrompts(metadata?: Record): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + // Store current prompt names before fetching + const currentNames = new Set(this.prompts.map((p) => p.name)); + + // Fetch all pages (suppress events during pagination) + let cursor: string | undefined; + let pageCount = 0; + + do { + const result = await this.listPrompts(cursor, metadata, true); + cursor = result.nextCursor; + pageCount++; + if (pageCount >= MAX_PAGES) { + throw new Error( + `Maximum pagination limit (${MAX_PAGES} pages) reached while listing prompts`, + ); + } + } while (cursor); + + // Find removed prompt names by comparing with current prompts + const newNames = new Set(this.prompts.map((p) => p.name)); + // Clear cache for removed prompts + for (const name of currentNames) { + if (!newNames.has(name)) { + this.cacheInternal.clearPrompt(name); + } + } + + // Dispatch final change event (listPrompts calls were suppressed) + this.dispatchTypedEvent("promptsChange", this.prompts); + // Note: Cached content for existing prompts is automatically preserved + return this.prompts; + } catch (error) { + throw new Error( + `Failed to list all prompts: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * Get a prompt by name + * @param name Prompt name + * @param args Optional prompt arguments + * @param metadata Optional metadata to include in the request + * @returns Prompt content + */ + async getPrompt( + name: string, + args?: Record, + metadata?: Record, + ): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + // Convert all arguments to strings for prompt arguments + const stringArgs = args ? convertPromptArguments(args) : {}; + + const params: any = { + name, + arguments: stringArgs, + }; + + if (metadata && Object.keys(metadata).length > 0) { + params._meta = metadata; + } + + const result = await this.client.getPrompt( + params, + this.getRequestOptions(metadata?.progressToken), + ); + + const invocation: PromptGetInvocation = { + result, + timestamp: new Date(), + name, + params: Object.keys(stringArgs).length > 0 ? stringArgs : undefined, + metadata, + }; + + // Store in cache + this.cacheInternal.setPrompt(name, invocation); + // Dispatch event + this.dispatchTypedEvent("promptContentChange", { + name, + content: invocation, + timestamp: invocation.timestamp, + }); + + return invocation; + } + + /** + * Request completions for a resource template variable or prompt argument + * @param ref Resource template reference or prompt reference + * @param argumentName Name of the argument/variable to complete + * @param argumentValue Current (partial) value of the argument + * @param context Optional context with other argument values + * @param metadata Optional metadata to include in the request + * @returns Completion result with values array + * @throws Error if client is not connected or request fails (except MethodNotFound) + */ + async getCompletions( + ref: + | { type: "ref/resource"; uri: string } + | { type: "ref/prompt"; name: string }, + argumentName: string, + argumentValue: string, + context?: Record, + metadata?: Record, + ): Promise<{ values: string[]; total?: number; hasMore?: boolean }> { + if (!this.client) { + return { values: [] }; + } + + try { + const params: any = { + ref, + argument: { + name: argumentName, + value: argumentValue, + }, + }; + + if (context) { + params.context = { + arguments: context, + }; + } + + if (metadata && Object.keys(metadata).length > 0) { + params._meta = metadata; + } + + const response = await this.client.complete( + params, + this.getRequestOptions(metadata?.progressToken), + ); + + return { + values: response.completion.values || [], + total: response.completion.total, + hasMore: response.completion.hasMore, + }; + } catch (error) { + // Handle MethodNotFound gracefully (server doesn't support completions) + if ( + (error instanceof McpError && + error.code === ErrorCode.MethodNotFound) || + (error instanceof Error && + (error.message.includes("Method not found") || + error.message.includes("does not support completions"))) + ) { + return { values: [] }; + } + + // Re-throw other errors + throw new Error( + `Failed to get completions: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * Fetch server info (capabilities, serverInfo, instructions) from cached initialize response + * This does not send any additional MCP requests - it just reads cached data + * Always called on connect + */ + private async fetchServerInfo(): Promise { + if (!this.client) { + return; + } + + try { + // Get server capabilities (cached from initialize response) + this.capabilities = this.client.getServerCapabilities(); + this.dispatchTypedEvent("capabilitiesChange", this.capabilities); + + // Get server info (name, version) and instructions (cached from initialize response) + this.serverInfo = this.client.getServerVersion(); + this.instructions = this.client.getInstructions(); + this.dispatchTypedEvent("serverInfoChange", this.serverInfo); + if (this.instructions !== undefined) { + this.dispatchTypedEvent("instructionsChange", this.instructions); + } + } catch (error) { + // Ignore errors in fetching server info + } + } + + /** + * Load all lists (tools, resources, prompts) by sending MCP requests. + * Only runs when autoSyncLists is enabled. + * listChanged auto-refresh is implemented via notification handlers in connect(). + */ + private async loadAllLists(): Promise { + if (!this.client) { + return; + } + + try { + // Query resources, prompts, and tools based on capabilities + // The list*() methods now handle state updates and event dispatching internally + if (this.capabilities?.resources) { + try { + await this.listAllResources(); + } catch (err) { + // Ignore errors, just leave empty + this.resources = []; + this.dispatchTypedEvent("resourcesChange", this.resources); + } + + // Also fetch resource templates + try { + await this.listAllResourceTemplates(); + } catch (err) { + // Ignore errors, just leave empty + this.resourceTemplates = []; + this.dispatchTypedEvent( + "resourceTemplatesChange", + this.resourceTemplates, + ); + } + } + + if (this.capabilities?.prompts) { + try { + await this.listAllPrompts(); + } catch (err) { + // Ignore errors, just leave empty + this.prompts = []; + this.dispatchTypedEvent("promptsChange", this.prompts); + } + } + + if (this.capabilities?.tools) { + try { + await this.listAllTools(); + } catch (err) { + // Ignore errors, just leave empty + this.tools = []; + this.dispatchTypedEvent("toolsChange", this.tools); + } + } + } catch (error) { + // Ignore errors in fetching server contents + } + } + + private addMessage(entry: MessageEntry): void { + if (this.maxMessages > 0 && this.messages.length >= this.maxMessages) { + // Remove oldest message + this.messages.shift(); + } + this.messages.push(entry); + this.dispatchTypedEvent("message", entry); + this.dispatchTypedEvent("messagesChange"); + } + + private updateMessageResponse( + requestEntry: MessageEntry, + response: JSONRPCResultResponse | JSONRPCErrorResponse, + ): void { + const duration = Date.now() - requestEntry.timestamp.getTime(); + // Update the entry in place (mutate the object directly) + requestEntry.response = response; + requestEntry.duration = duration; + this.dispatchTypedEvent("message", requestEntry); + this.dispatchTypedEvent("messagesChange"); + } + + private addStderrLog(entry: StderrLogEntry): void { + if ( + this.maxStderrLogEvents > 0 && + this.stderrLogs.length >= this.maxStderrLogEvents + ) { + // Remove oldest stderr log + this.stderrLogs.shift(); + } + this.stderrLogs.push(entry); + this.dispatchTypedEvent("stderrLog", entry); + this.dispatchTypedEvent("stderrLogsChange"); + } + + private addFetchRequest(entry: FetchRequestEntry): void { + this.logger.info( + { + component: "InspectorClient", + category: entry.category, + fetchRequest: { + url: entry.url, + method: entry.method, + headers: entry.requestHeaders, + body: entry.requestBody ?? "[no body]", + }, + fetchResponse: entry.error + ? { error: entry.error } + : { + status: entry.responseStatus, + statusText: entry.responseStatusText, + headers: entry.responseHeaders, + body: entry.responseBody, + }, + }, + `${entry.category} fetch`, + ); + if ( + this.maxFetchRequests > 0 && + this.fetchRequests.length >= this.maxFetchRequests + ) { + // Remove oldest fetch request + this.fetchRequests.shift(); + } + this.fetchRequests.push(entry); + this.dispatchTypedEvent("fetchRequest", entry); + this.dispatchTypedEvent("fetchRequestsChange"); + } + + /** + * Get all fetch requests + */ + getFetchRequests(): FetchRequestEntry[] { + return [...this.fetchRequests]; + } + + /** + * Get current session ID (from OAuth state authId) + */ + getSessionId(): string | undefined { + return this.sessionId; + } + + /** + * Set session ID (typically extracted from OAuth state) + */ + setSessionId(sessionId: string): void { + this.sessionId = sessionId; + } + + /** + * Save current session state to storage + */ + async saveSession(): Promise { + if (!this.sessionStorage || !this.sessionId) { + return; + } + + const state: InspectorClientSessionState = { + fetchRequests: [...this.fetchRequests], // Copy array, timestamps will be serialized by storage + createdAt: Date.now(), + updatedAt: Date.now(), + }; + + try { + await this.sessionStorage.saveSession(this.sessionId, state); + this.logger.debug( + { + sessionId: this.sessionId, + fetchRequestCount: this.fetchRequests.length, + }, + "Session state saved", + ); + } catch (error) { + this.logger.warn( + { + sessionId: this.sessionId, + error: error instanceof Error ? error.message : String(error), + }, + "Failed to save session state", + ); + } + } + + /** + * Restore session state from storage + */ + private async restoreSession(): Promise { + if (!this.sessionStorage || !this.sessionId) { + return; + } + + try { + const state = await this.sessionStorage.loadSession(this.sessionId); + if (!state) { + return; + } + + // Restore fetch requests (convert timestamp strings back to Date objects) + if (state.fetchRequests && state.fetchRequests.length > 0) { + this.fetchRequests = state.fetchRequests.map((req) => ({ + ...req, + timestamp: + req.timestamp instanceof Date + ? req.timestamp + : typeof req.timestamp === "string" + ? new Date(req.timestamp) + : new Date(req.timestamp as any), + })); + this.dispatchTypedEvent("fetchRequestsChange"); + this.logger.debug( + { + sessionId: this.sessionId, + fetchRequestCount: this.fetchRequests.length, + }, + "Session state restored", + ); + } + } catch (error) { + this.logger.warn( + { + sessionId: this.sessionId, + error: error instanceof Error ? error.message : String(error), + }, + "Failed to restore session state", + ); + } + } + + /** + * Get current roots + */ + getRoots(): Root[] { + return this.roots !== undefined ? [...this.roots] : []; + } + + /** + * Set roots and notify server if it supports roots/listChanged + * Note: This will enable roots capability if it wasn't already enabled + */ + async setRoots(roots: Root[]): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + + // Enable roots capability if not already enabled + if (this.roots === undefined) { + this.roots = []; + } + this.roots = [...roots]; + this.dispatchTypedEvent("rootsChange", this.roots); + + // Send notification to server - clients can send this notification to any server + // The server doesn't need to advertise support for it + try { + await this.client.notification({ + method: "notifications/roots/list_changed", + }); + } catch (error) { + // Log but don't throw - roots were updated locally even if notification failed + console.error("Failed to send roots/list_changed notification:", error); + } + } + + /** + * Get list of currently subscribed resource URIs + */ + getSubscribedResources(): string[] { + return Array.from(this.subscribedResources); + } + + /** + * Check if a resource is currently subscribed + */ + isSubscribedToResource(uri: string): boolean { + return this.subscribedResources.has(uri); + } + + /** + * Check if the server supports resource subscriptions + */ + supportsResourceSubscriptions(): boolean { + return this.capabilities?.resources?.subscribe === true; + } + + /** + * Subscribe to a resource to receive update notifications + * @param uri - The URI of the resource to subscribe to + * @throws Error if client is not connected or server doesn't support subscriptions + */ + async subscribeToResource(uri: string): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + if (!this.supportsResourceSubscriptions()) { + throw new Error("Server does not support resource subscriptions"); + } + try { + await this.client.subscribeResource({ uri }, this.getRequestOptions()); + this.subscribedResources.add(uri); + this.dispatchTypedEvent( + "resourceSubscriptionsChange", + Array.from(this.subscribedResources), + ); + } catch (error) { + throw new Error( + `Failed to subscribe to resource: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + /** + * Unsubscribe from a resource + * @param uri - The URI of the resource to unsubscribe from + * @throws Error if client is not connected + */ + async unsubscribeFromResource(uri: string): Promise { + if (!this.client) { + throw new Error("Client is not connected"); + } + try { + await this.client.unsubscribeResource({ uri }, this.getRequestOptions()); + this.subscribedResources.delete(uri); + this.dispatchTypedEvent( + "resourceSubscriptionsChange", + Array.from(this.subscribedResources), + ); + } catch (error) { + throw new Error( + `Failed to unsubscribe from resource: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + // ============================================================================ + // OAuth Support + // ============================================================================ + + /** + * Get server URL from transport config (full URL including path, for OAuth discovery) + */ + private getServerUrl(): string { + if ( + this.transportConfig.type === "sse" || + this.transportConfig.type === "streamable-http" + ) { + return this.transportConfig.url; + } + // Stdio transports don't have a URL - OAuth not applicable + throw new Error( + "OAuth is only supported for HTTP-based transports (SSE, streamable-http)", + ); + } + + /** + * Set OAuth configuration + */ + setOAuthConfig(config: { + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + scope?: string; + }): void { + if (!this.oauthConfig) { + throw new Error( + "OAuth config must be set at creation. Pass oauth in constructor.", + ); + } + this.oauthConfig = { + ...this.oauthConfig, + ...config, + } as NonNullable; + } + + /** + * Create and initialize an OAuth provider for the specified mode + */ + private async createOAuthProvider( + mode: "normal" | "guided", + ): Promise { + if (!this.oauthConfig) { + throw new Error("OAuth not configured. Call setOAuthConfig() first."); + } + + if ( + !this.oauthConfig.storage || + !this.oauthConfig.redirectUrlProvider || + !this.oauthConfig.navigation + ) { + throw new Error( + "OAuth environment components (storage, navigation, redirectUrlProvider) are required.", + ); + } + + const serverUrl = this.getServerUrl(); + const provider = new BaseOAuthClientProvider( + serverUrl, + { + storage: this.oauthConfig.storage, + redirectUrlProvider: this.oauthConfig.redirectUrlProvider, + navigation: this.oauthConfig.navigation, + clientMetadataUrl: this.oauthConfig.clientMetadataUrl, + }, + mode, + ); + + // Set event target for event dispatch + provider.setEventTarget(this); + + // Set scope if provided + if (this.oauthConfig.scope) { + await provider.saveScope(this.oauthConfig.scope); + } + + // Save preregistered client info if provided (static client from config) + if (this.oauthConfig.clientId) { + const clientInfo: OAuthClientInformation = { + client_id: this.oauthConfig.clientId, + ...(this.oauthConfig.clientSecret && { + client_secret: this.oauthConfig.clientSecret, + }), + }; + await provider.savePreregisteredClientInformation(clientInfo); + } + + return provider; + } + + /** + * Initiates OAuth flow using SDK's auth() function (normal mode) + * Can be called directly by user or automatically triggered by 401 errors + */ + async authenticate(): Promise { + if (!this.oauthConfig) { + throw new Error("OAuth not configured. Call setOAuthConfig() first."); + } + + const provider = await this.createOAuthProvider("normal"); + const serverUrl = this.getServerUrl(); + + // Clear any previously captured URL + provider.clearCapturedAuthUrl(); + + // Use SDK's auth() function - it handles client resolution, token refresh, etc. + const result = await auth(provider, { + serverUrl, + scope: provider.scope, + fetchFn: this.effectiveAuthFetch, + }); + + if (result === "AUTHORIZED") { + // Tokens were refreshed, no authorization URL needed + throw new Error( + "Unexpected: auth() returned AUTHORIZED without authorization code", + ); + } + + // Get the captured URL from the provider (set in redirectToAuthorization) + const capturedUrl = provider.getCapturedAuthUrl(); + if (!capturedUrl) { + throw new Error("Failed to capture authorization URL"); + } + + // Extract sessionId from OAuth state parameter in authorization URL + const stateParam = capturedUrl.searchParams.get("state"); + if (stateParam) { + const parsedState = parseOAuthState(stateParam); + if (parsedState?.authId) { + this.sessionId = parsedState.authId; + // Save session before navigation + await this.saveSession(); + } + } + + // Backfill oauthState so getOAuthState() returns consistent shape (normal flow) + const clientInfo = await provider.clientInformation(); + this.oauthState = { + ...EMPTY_GUIDED_STATE, + authType: "normal", + oauthStep: "authorization_code", + authorizationUrl: capturedUrl, + oauthClientInfo: clientInfo ?? null, + }; + return capturedUrl; + } + + /** + * Starts guided OAuth flow (step-by-step). Runs only the first step. + * Use proceedOAuthStep() to advance. When oauthStep is "authorization_code", + * set authorizationCode and call proceedOAuthStep() to complete. + */ + async beginGuidedAuth(): Promise { + if (!this.oauthConfig) { + throw new Error("OAuth not configured. Call setOAuthConfig() first."); + } + + const provider = await this.createOAuthProvider("guided"); + const serverUrl = this.getServerUrl(); + + this.oauthState = { ...EMPTY_GUIDED_STATE }; + if (this.oauthConfig.clientId) { + this.oauthState.oauthClientInfo = { + client_id: this.oauthConfig.clientId, + ...(this.oauthConfig.clientSecret && { + client_secret: this.oauthConfig.clientSecret, + }), + }; + } + this.oauthStateMachine = new OAuthStateMachine( + serverUrl, + provider, + (updates) => { + const state = this.oauthState; + if (!state) throw new Error("OAuth state not initialized"); + const previousStep = state.oauthStep; + this.oauthState = { ...state, ...updates }; + if (updates.oauthStep === "complete") { + this.oauthState.completedAt = Date.now(); + } + const step = updates.oauthStep ?? previousStep; + this.dispatchTypedEvent("oauthStepChange", { + step, + previousStep, + state: updates, + }); + }, + this.effectiveAuthFetch, + ); + + await this.oauthStateMachine.executeStep(this.oauthState); + } + + /** + * Runs guided OAuth flow to completion. If already started (via beginGuidedAuth), + * continues from current step. Otherwise initializes and runs from the start. + * Returns the authorization URL when user must authorize, or undefined if already complete. + */ + async runGuidedAuth(): Promise { + if (!this.oauthConfig) { + throw new Error("OAuth not configured. Call setOAuthConfig() first."); + } + + if (!this.oauthStateMachine || !this.oauthState) { + await this.beginGuidedAuth(); + } + + const machine = this.oauthStateMachine; + if (!machine) { + throw new Error("Guided auth failed to initialize state"); + } + + while (true) { + const state = this.oauthState; + if (!state) { + throw new Error("Guided auth failed to initialize state"); + } + if ( + state.oauthStep === "authorization_code" || + state.oauthStep === "complete" + ) { + break; + } + await machine.executeStep(state); + } + + const state = this.oauthState; + if (state?.oauthStep === "complete") { + return undefined; + } + if (!state?.authorizationUrl) { + throw new Error("Failed to generate authorization URL"); + } + + // Extract sessionId from OAuth state parameter in authorization URL + const stateParam = state.authorizationUrl.searchParams.get("state"); + if (stateParam) { + const parsedState = parseOAuthState(stateParam); + if (parsedState?.authId) { + this.sessionId = parsedState.authId; + // Save session before navigation + await this.saveSession(); + } + } + + this.dispatchTypedEvent("oauthAuthorizationRequired", { + url: state.authorizationUrl, + }); + + return state.authorizationUrl; + } + + /** + * Set authorization code for guided OAuth flow. + * Validates that the client is in guided OAuth mode (has active state machine). + * @param authorizationCode The authorization code from the OAuth callback + * @param completeFlow If true, automatically proceed through all remaining steps to completion. + * If false, only set the code and wait for manual progression via proceedOAuthStep(). + * Defaults to false for manual step-by-step control. + * @throws Error if not in guided OAuth flow or not at authorization_code step + */ + async setGuidedAuthorizationCode( + authorizationCode: string, + completeFlow: boolean = false, + ): Promise { + if (!this.oauthStateMachine || !this.oauthState) { + throw new Error( + "Not in guided OAuth flow. Call beginGuidedAuth() first.", + ); + } + const currentStep = this.oauthState.oauthStep; + if (currentStep !== "authorization_code") { + throw new Error( + `Cannot set authorization code at step ${currentStep}. Expected step: authorization_code`, + ); + } + + this.oauthState.authorizationCode = authorizationCode; + + if (completeFlow) { + // Execute current step (authorization_code -> token_request) + await this.oauthStateMachine.executeStep(this.oauthState); + // Continue through remaining steps until complete + // TypeScript doesn't track that executeStep mutates oauthState.oauthStep, + // so we use a type assertion to acknowledge the step changes dynamically + let step: OAuthStep = this.oauthState.oauthStep; + while (step !== "complete") { + await this.oauthStateMachine.executeStep(this.oauthState); + step = this.oauthState.oauthStep; + } + + if (!this.oauthState.oauthTokens) { + throw new Error("Failed to exchange authorization code for tokens"); + } + + this.dispatchTypedEvent("oauthComplete", { + tokens: this.oauthState.oauthTokens, + }); + } else { + // Manual mode: dispatch event to notify listeners that code was set + // (step transitions will happen when user calls proceedOAuthStep()) + this.dispatchTypedEvent("oauthStepChange", { + step: this.oauthState.oauthStep, + previousStep: this.oauthState.oauthStep, + state: { authorizationCode }, + }); + } + } + + /** + * Completes OAuth flow with authorization code. + * For guided mode, this calls setGuidedAuthorizationCode(code, true) internally. + * For normal mode, uses SDK auth() directly. + */ + async completeOAuthFlow(authorizationCode: string): Promise { + if (!this.oauthConfig) { + throw new Error("OAuth not configured. Call setOAuthConfig() first."); + } + + try { + if (this.oauthStateMachine && this.oauthState) { + // Guided mode - use setGuidedAuthorizationCode with completeFlow=true + await this.setGuidedAuthorizationCode(authorizationCode, true); + } else { + // Normal mode - use SDK auth() with authorization code + const provider = await this.createOAuthProvider("normal"); + const serverUrl = this.getServerUrl(); + + const result = await auth(provider, { + serverUrl, + authorizationCode, + fetchFn: this.effectiveAuthFetch, + }); + + if (result !== "AUTHORIZED") { + throw new Error( + `Expected AUTHORIZED after providing authorization code, got: ${result}`, + ); + } + + const tokens = await provider.tokens(); + if (!tokens) { + throw new Error("Failed to retrieve tokens after authorization"); + } + + const clientInfo = await provider.clientInformation(); + const completedAt = Date.now(); + this.oauthState = this.oauthState + ? { + ...this.oauthState, + oauthStep: "complete", + oauthTokens: tokens, + oauthClientInfo: clientInfo ?? null, + completedAt, + } + : { + ...EMPTY_GUIDED_STATE, + authType: "normal", + oauthStep: "complete", + oauthTokens: tokens, + oauthClientInfo: clientInfo ?? null, + completedAt, + }; + + this.dispatchTypedEvent("oauthComplete", { + tokens, + }); + } + } catch (error) { + this.dispatchTypedEvent("oauthError", { + error: error instanceof Error ? error : new Error(String(error)), + }); + throw error; + } + } + + /** + * Gets current OAuth tokens (if authorized) + */ + async getOAuthTokens(): Promise { + if (!this.oauthConfig) { + return undefined; + } + + // Return tokens from state machine if in guided mode + if (this.oauthState?.oauthTokens) { + return this.oauthState.oauthTokens; + } + + // Otherwise get from provider storage + const provider = await this.createOAuthProvider("normal"); + try { + return await provider.tokens(); + } catch { + return undefined; + } + } + + /** + * Clears OAuth tokens and client information + */ + clearOAuthTokens(): void { + if (!this.oauthConfig?.storage) { + return; + } + + const serverUrl = this.getServerUrl(); + this.oauthConfig.storage.clear(serverUrl); + + this.oauthState = null; + this.oauthStateMachine = null; + } + + /** + * Checks if client is currently OAuth authorized + */ + async isOAuthAuthorized(): Promise { + const tokens = await this.getOAuthTokens(); + return tokens !== undefined; + } + + /** + * Get current OAuth state machine state (for guided mode) + */ + getOAuthState(): AuthGuidedState | undefined { + return this.oauthState ? { ...this.oauthState } : undefined; + } + + /** + * Get current OAuth step (for guided mode) + */ + getOAuthStep(): OAuthStep | undefined { + return this.oauthState?.oauthStep; + } + + /** + * Manually progress to next step in guided OAuth flow + */ + async proceedOAuthStep(): Promise { + if (!this.oauthStateMachine || !this.oauthState) { + throw new Error( + "Not in guided OAuth flow. Call authenticateGuided() first.", + ); + } + + await this.oauthStateMachine.executeStep(this.oauthState); + } +} diff --git a/shared/mcp/inspectorClientEventTarget.ts b/shared/mcp/inspectorClientEventTarget.ts new file mode 100644 index 000000000..bc718b156 --- /dev/null +++ b/shared/mcp/inspectorClientEventTarget.ts @@ -0,0 +1,214 @@ +/** + * Type-safe EventTarget for InspectorClient events + * + * This module provides a base class with overloaded addEventListener/removeEventListener + * methods and a dispatchTypedEvent method that give compile-time type safety for event + * names and event detail types. + */ + +import type { + ConnectionStatus, + MessageEntry, + StderrLogEntry, + FetchRequestEntry, + PromptGetInvocation, + ResourceReadInvocation, + ResourceTemplateReadInvocation, +} from "./types.js"; +import type { + Tool, + Resource, + ResourceTemplate, + Prompt, + ServerCapabilities, + Implementation, + Root, + Progress, + ProgressToken, + Task, + CallToolResult, + McpError, +} from "@modelcontextprotocol/sdk/types.js"; +import type { SamplingCreateMessage } from "./samplingCreateMessage.js"; +import type { ElicitationCreateMessage } from "./elicitationCreateMessage.js"; +import type { AuthGuidedState, OAuthStep } from "../auth/types.js"; +import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"; + +/** + * Maps event names to their detail types for CustomEvents + */ +export interface InspectorClientEventMap { + statusChange: ConnectionStatus; + toolsChange: Tool[]; + resourcesChange: Resource[]; + resourceTemplatesChange: ResourceTemplate[]; + promptsChange: Prompt[]; + capabilitiesChange: ServerCapabilities | undefined; + serverInfoChange: Implementation | undefined; + instructionsChange: string | undefined; + message: MessageEntry; + stderrLog: StderrLogEntry; + fetchRequest: FetchRequestEntry; + error: Error; + resourceUpdated: { uri: string }; + progressNotification: Progress & { progressToken?: ProgressToken }; + toolCallResultChange: { + toolName: string; + params: Record; + result: any; + timestamp: Date; + success: boolean; + error?: string; + metadata?: Record; + }; + resourceContentChange: { + uri: string; + content: ResourceReadInvocation; + timestamp: Date; + }; + resourceTemplateContentChange: { + uriTemplate: string; + content: ResourceTemplateReadInvocation; + params: Record; + timestamp: Date; + }; + promptContentChange: { + name: string; + content: PromptGetInvocation; + timestamp: Date; + }; + pendingSamplesChange: SamplingCreateMessage[]; + newPendingSample: SamplingCreateMessage; + pendingElicitationsChange: ElicitationCreateMessage[]; + newPendingElicitation: ElicitationCreateMessage; + rootsChange: Root[]; + resourceSubscriptionsChange: string[]; + // Task events + taskCreated: { taskId: string; task: Task }; + taskStatusChange: { taskId: string; task: Task }; + taskCompleted: { taskId: string; result: CallToolResult }; + taskFailed: { taskId: string; error: McpError }; + taskCancelled: { taskId: string }; + tasksChange: Task[]; + // Signal events (no payload) + connect: void; + disconnect: void; + messagesChange: void; + stderrLogsChange: void; + fetchRequestsChange: void; + // List changed notification events (fired when server sends list_changed notifications) + toolsListChanged: void; + resourcesListChanged: void; + promptsListChanged: void; + // OAuth events + oauthAuthorizationRequired: { + url: URL; + }; + oauthComplete: { + tokens: OAuthTokens; + }; + oauthError: { + error: Error; + }; + oauthStepChange: { + step: OAuthStep; + previousStep: OAuthStep; + state: Partial; + }; +} + +/** + * Typed event class that extends CustomEvent with type-safe detail + */ +export class TypedEvent< + K extends keyof InspectorClientEventMap, +> extends CustomEvent { + constructor(type: K, detail: InspectorClientEventMap[K]) { + super(type, { detail }); + } +} + +/** + * Type-safe EventTarget for InspectorClient events + * + * Provides overloaded addEventListener/removeEventListener methods that + * give compile-time type safety for event names and event detail types. + * Extends the standard EventTarget, so all standard EventTarget functionality + * is still available. + */ +export class InspectorClientEventTarget extends EventTarget { + /** + * Dispatch a type-safe event + * For void events, no detail parameter is required (or allowed) + * For events with payloads, the detail parameter is required + */ + dispatchTypedEvent( + type: K, + ...args: InspectorClientEventMap[K] extends void + ? [] + : [detail: InspectorClientEventMap[K]] + ): void { + const detail = args[0] as InspectorClientEventMap[K]; + this.dispatchEvent(new TypedEvent(type, detail)); + } + + // Overload 1: All typed events + addEventListener( + type: K, + listener: (event: TypedEvent) => void, + options?: boolean | AddEventListenerOptions, + ): void; + + // Overload 2: Fallback for any string (for compatibility) + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ): void; + + // Implementation - must be compatible with all overloads + addEventListener( + type: string, + listener: + | ((event: TypedEvent) => void) + | EventListenerOrEventListenerObject + | null, + options?: boolean | AddEventListenerOptions, + ): void { + super.addEventListener( + type, + listener as EventListenerOrEventListenerObject | null, + options, + ); + } + + // Overload 1: All typed events + removeEventListener( + type: K, + listener: (event: TypedEvent) => void, + options?: boolean | EventListenerOptions, + ): void; + + // Overload 2: Fallback for any string (for compatibility) + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ): void; + + // Implementation - must be compatible with all overloads + removeEventListener( + type: string, + listener: + | ((event: TypedEvent) => void) + | EventListenerOrEventListenerObject + | null, + options?: boolean | EventListenerOptions, + ): void { + super.removeEventListener( + type, + listener as EventListenerOrEventListenerObject | null, + options, + ); + } +} diff --git a/shared/mcp/messageTrackingTransport.ts b/shared/mcp/messageTrackingTransport.ts new file mode 100644 index 000000000..8c42319b1 --- /dev/null +++ b/shared/mcp/messageTrackingTransport.ts @@ -0,0 +1,120 @@ +import type { + Transport, + TransportSendOptions, +} from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { + JSONRPCMessage, + MessageExtraInfo, +} from "@modelcontextprotocol/sdk/types.js"; +import type { + JSONRPCRequest, + JSONRPCNotification, + JSONRPCResultResponse, + JSONRPCErrorResponse, +} from "@modelcontextprotocol/sdk/types.js"; + +export interface MessageTrackingCallbacks { + trackRequest?: (message: JSONRPCRequest) => void; + trackResponse?: ( + message: JSONRPCResultResponse | JSONRPCErrorResponse, + ) => void; + trackNotification?: (message: JSONRPCNotification) => void; +} + +// Transport wrapper that intercepts all messages for tracking +export class MessageTrackingTransport implements Transport { + constructor( + private baseTransport: Transport, + private callbacks: MessageTrackingCallbacks, + ) {} + + async start(): Promise { + return this.baseTransport.start(); + } + + async send( + message: JSONRPCMessage, + options?: TransportSendOptions, + ): Promise { + // Track outgoing requests (only requests have a method and are sent by the client) + if ("method" in message && "id" in message) { + this.callbacks.trackRequest?.(message as JSONRPCRequest); + } + return this.baseTransport.send(message, options); + } + + async close(): Promise { + return this.baseTransport.close(); + } + + get onclose(): (() => void) | undefined { + return this.baseTransport.onclose; + } + + set onclose(handler: (() => void) | undefined) { + this.baseTransport.onclose = handler; + } + + get onerror(): ((error: Error) => void) | undefined { + return this.baseTransport.onerror; + } + + set onerror(handler: ((error: Error) => void) | undefined) { + this.baseTransport.onerror = handler; + } + + get onmessage(): + | ((message: T, extra?: MessageExtraInfo) => void) + | undefined { + return this.baseTransport.onmessage; + } + + set onmessage( + handler: + | (( + message: T, + extra?: MessageExtraInfo, + ) => void) + | undefined, + ) { + if (handler) { + // Wrap the handler to track incoming messages + this.baseTransport.onmessage = ( + message: T, + extra?: MessageExtraInfo, + ) => { + // Track incoming messages + if ( + "id" in message && + message.id !== null && + message.id !== undefined + ) { + // Check if it's a response (has 'result' or 'error' property) + if ("result" in message || "error" in message) { + this.callbacks.trackResponse?.( + message as JSONRPCResultResponse | JSONRPCErrorResponse, + ); + } else if ("method" in message) { + // This is a request coming from the server + this.callbacks.trackRequest?.(message as JSONRPCRequest); + } + } else if ("method" in message) { + // Notification (no ID, has method) + this.callbacks.trackNotification?.(message as JSONRPCNotification); + } + // Call the original handler + handler(message, extra); + }; + } else { + this.baseTransport.onmessage = undefined; + } + } + + get sessionId(): string | undefined { + return this.baseTransport.sessionId; + } + + get setProtocolVersion(): ((version: string) => void) | undefined { + return this.baseTransport.setProtocolVersion; + } +} diff --git a/shared/mcp/node/config.ts b/shared/mcp/node/config.ts new file mode 100644 index 000000000..b55ffdd93 --- /dev/null +++ b/shared/mcp/node/config.ts @@ -0,0 +1,149 @@ +import { readFileSync } from "fs"; +import { resolve } from "path"; +import type { + MCPConfig, + MCPServerConfig, + StdioServerConfig, + SseServerConfig, + StreamableHttpServerConfig, +} from "../types.js"; + +/** + * Loads and validates an MCP servers configuration file + * @param configPath - Path to the config file (relative to process.cwd() or absolute) + * @returns The parsed MCPConfig + * @throws Error if the file cannot be loaded, parsed, or is invalid + */ +export function loadMcpServersConfig(configPath: string): MCPConfig { + try { + const resolvedPath = resolve(process.cwd(), configPath); + const configContent = readFileSync(resolvedPath, "utf-8"); + const config = JSON.parse(configContent) as MCPConfig; + + if (!config.mcpServers) { + throw new Error("Configuration file must contain an mcpServers element"); + } + + return config; + } catch (error) { + if (error instanceof Error) { + throw new Error(`Error loading configuration: ${error.message}`); + } + throw new Error("Error loading configuration: Unknown error"); + } +} + +/** + * Converts CLI arguments to MCPServerConfig format. + * Handles all CLI-specific logic including: + * - Detecting if target is a URL or command + * - Validating transport/URL combinations + * - Auto-detecting transport type from URL path + * - Converting CLI's "http" transport to "streamable-http" + * + * @param args - CLI arguments object with target (URL or command), transport, and headers + * @returns MCPServerConfig suitable for creating an InspectorClient + * @throws Error if arguments are invalid (e.g., args with URLs, stdio with URLs, etc.) + */ +export function argsToMcpServerConfig(args: { + target: string[]; + transport?: "sse" | "stdio" | "http"; + headers?: Record; + env?: Record; +}): MCPServerConfig { + if (args.target.length === 0) { + throw new Error( + "Target is required. Specify a URL or a command to execute.", + ); + } + + const [firstTarget, ...targetArgs] = args.target; + + if (!firstTarget) { + throw new Error("Target is required."); + } + + const isUrl = + firstTarget.startsWith("http://") || firstTarget.startsWith("https://"); + + // Validation: URLs cannot have additional arguments + if (isUrl && targetArgs.length > 0) { + throw new Error("Arguments cannot be passed to a URL-based MCP server."); + } + + // Validation: Transport/URL combinations + if (args.transport) { + if (!isUrl && args.transport !== "stdio") { + throw new Error("Only stdio transport can be used with local commands."); + } + if (isUrl && args.transport === "stdio") { + throw new Error("stdio transport cannot be used with URLs."); + } + } + + // Handle URL-based transports (SSE or streamable-http) + if (isUrl) { + const url = new URL(firstTarget); + + // Determine transport type + let transportType: "sse" | "streamable-http"; + if (args.transport) { + // Convert CLI's "http" to "streamable-http" + if (args.transport === "http") { + transportType = "streamable-http"; + } else if (args.transport === "sse") { + transportType = "sse"; + } else { + // Should not happen due to validation above, but default to SSE + transportType = "sse"; + } + } else { + // Auto-detect from URL path + if (url.pathname.endsWith("/mcp")) { + transportType = "streamable-http"; + } else if (url.pathname.endsWith("/sse")) { + transportType = "sse"; + } else { + // Default to SSE if path doesn't match known patterns + transportType = "sse"; + } + } + + // Create SSE or streamable-http config + if (transportType === "sse") { + const config: SseServerConfig = { + type: "sse", + url: firstTarget, + }; + if (args.headers) { + config.headers = args.headers; + } + return config; + } else { + const config: StreamableHttpServerConfig = { + type: "streamable-http", + url: firstTarget, + }; + if (args.headers) { + config.headers = args.headers; + } + return config; + } + } + + // Handle stdio transport (command-based) + const config: StdioServerConfig = { + type: "stdio", + command: firstTarget, + }; + + if (targetArgs.length > 0) { + config.args = targetArgs; + } + + if (args.env && Object.keys(args.env).length > 0) { + config.env = args.env; + } + + return config; +} diff --git a/shared/mcp/node/index.ts b/shared/mcp/node/index.ts new file mode 100644 index 000000000..8e57d0d5e --- /dev/null +++ b/shared/mcp/node/index.ts @@ -0,0 +1,2 @@ +export { loadMcpServersConfig, argsToMcpServerConfig } from "./config.js"; +export { createTransportNode } from "./transport.js"; diff --git a/shared/mcp/node/transport.ts b/shared/mcp/node/transport.ts new file mode 100644 index 000000000..4d894e053 --- /dev/null +++ b/shared/mcp/node/transport.ts @@ -0,0 +1,112 @@ +import { getServerType } from "../config.js"; +import type { + MCPServerConfig, + StdioServerConfig, + SseServerConfig, + StreamableHttpServerConfig, + CreateTransportOptions, + CreateTransportResult, +} from "../types.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { createFetchTracker } from "../fetchTracking.js"; + +/** + * Creates the appropriate transport for an MCP server configuration. + */ +export function createTransportNode( + config: MCPServerConfig, + options: CreateTransportOptions = {}, +): CreateTransportResult { + const serverType = getServerType(config); + const { + fetchFn: optionsFetchFn, + onStderr, + pipeStderr = false, + onFetchRequest, + authProvider, + } = options; + + const baseFetch = optionsFetchFn ?? globalThis.fetch; + + if (serverType === "stdio") { + const stdioConfig = config as StdioServerConfig; + const transport = new StdioClientTransport({ + command: stdioConfig.command, + args: stdioConfig.args || [], + env: stdioConfig.env, + cwd: stdioConfig.cwd, + stderr: pipeStderr ? "pipe" : undefined, + }); + + // Set up stderr listener if requested + if (pipeStderr && transport.stderr && onStderr) { + transport.stderr.on("data", (data: Buffer) => { + const logEntry = data.toString().trim(); + if (logEntry) { + onStderr({ + timestamp: new Date(), + message: logEntry, + }); + } + }); + } + + return { transport: transport }; + } else if (serverType === "sse") { + const sseConfig = config as SseServerConfig; + const url = new URL(sseConfig.url); + + const sseFetch = + (sseConfig.eventSourceInit?.fetch as typeof fetch) || baseFetch; + const trackedFetch = onFetchRequest + ? createFetchTracker(sseFetch, { trackRequest: onFetchRequest }) + : sseFetch; + + const eventSourceInit: Record = { + ...sseConfig.eventSourceInit, + ...(sseConfig.headers && { headers: sseConfig.headers }), + fetch: trackedFetch, + }; + + const requestInit: RequestInit = { + ...sseConfig.requestInit, + ...(sseConfig.headers && { headers: sseConfig.headers }), + }; + + const postFetch = onFetchRequest + ? createFetchTracker(baseFetch, { trackRequest: onFetchRequest }) + : baseFetch; + + const transport = new SSEClientTransport(url, { + authProvider, + eventSourceInit, + requestInit, + fetch: postFetch, + }); + + return { transport }; + } else { + // streamable-http + const httpConfig = config as StreamableHttpServerConfig; + const url = new URL(httpConfig.url); + + const requestInit: RequestInit = { + ...httpConfig.requestInit, + ...(httpConfig.headers && { headers: httpConfig.headers }), + }; + + const transportFetch = onFetchRequest + ? createFetchTracker(baseFetch, { trackRequest: onFetchRequest }) + : baseFetch; + + const transport = new StreamableHTTPClientTransport(url, { + authProvider, + requestInit, + fetch: transportFetch, + }); + + return { transport }; + } +} diff --git a/shared/mcp/remote/constants.ts b/shared/mcp/remote/constants.ts new file mode 100644 index 000000000..36911415d --- /dev/null +++ b/shared/mcp/remote/constants.ts @@ -0,0 +1,11 @@ +/** + * Environment variable names for the remote server. + * This is shared between browser and Node.js code, so it's in the base remote directory. + */ +export const API_SERVER_ENV_VARS = { + /** + * Auth token for authenticating requests to the remote API server. + * Used by the x-mcp-remote-auth header (or Authorization header if changed). + */ + AUTH_TOKEN: "MCP_INSPECTOR_API_TOKEN", +} as const; diff --git a/shared/mcp/remote/createRemoteFetch.ts b/shared/mcp/remote/createRemoteFetch.ts new file mode 100644 index 000000000..2633cffe0 --- /dev/null +++ b/shared/mcp/remote/createRemoteFetch.ts @@ -0,0 +1,139 @@ +/** + * Creates a fetch implementation that POSTs requests to the remote /api/fetch endpoint. + * Use in the browser to bypass CORS for OAuth and MCP HTTP requests. + */ + +export interface RemoteFetchOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + + /** Base fetch to use for the POST to the remote (default: globalThis.fetch) */ + fetchFn?: typeof fetch; +} + +/** + * Serialize request for the remote. Handles URLSearchParams body for OAuth token exchange. + */ +async function serializeRequest( + input: RequestInfo | URL, + init?: RequestInit, +): Promise<{ + url: string; + method: string; + headers: Record; + body?: string; +}> { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : (input as Request).url; + const method = + init?.method ?? + (typeof input === "object" && "method" in input + ? (input as Request).method + : "GET"); + + const headers: Record = {}; + if (input instanceof Request) { + input.headers.forEach((v, k) => { + headers[k] = v; + }); + } + if (init?.headers) { + const h = new Headers(init.headers); + h.forEach((v, k) => { + headers[k] = v; + }); + } + + let body: string | undefined; + if (init?.body !== undefined && init?.body !== null) { + if (typeof init.body === "string") { + body = init.body; + } else if (init.body instanceof URLSearchParams) { + body = init.body.toString(); + } else if (init.body instanceof FormData) { + const params = new URLSearchParams(); + for (const [key, value] of init.body.entries()) { + if (typeof value === "string") { + params.set(key, value); + } + } + body = params.toString(); + } else { + body = String(init.body); + } + } else if (input instanceof Request && input.body) { + const cloned = input.clone(); + body = await cloned.text(); + } + + return { url, method, headers, body }; +} + +/** + * Deserialize remote response into a Response object. + */ +function deserializeResponse(data: { + ok: boolean; + status: number; + statusText: string; + headers: Record; + body?: string; +}): Response { + return new Response(data.body ?? null, { + status: data.status, + statusText: data.statusText, + headers: new Headers(data.headers ?? {}), + }); +} + +/** + * Returns a fetch function that forwards requests to the remote /api/fetch endpoint. + * The remote server performs the actual HTTP request in Node (no CORS). + */ +export function createRemoteFetch(options: RemoteFetchOptions): typeof fetch { + const baseUrl = options.baseUrl.replace(/\/$/, ""); + const fetchFn = options.fetchFn ?? globalThis.fetch; + + return async ( + input: RequestInfo | URL, + init?: RequestInit, + ): Promise => { + const { url, method, headers, body } = await serializeRequest(input, init); + + const reqHeaders: Record = { + "Content-Type": "application/json", + ...headers, + }; + if (options.authToken) { + reqHeaders["x-mcp-remote-auth"] = `Bearer ${options.authToken}`; + } + + const res = await fetchFn(`${baseUrl}/api/fetch`, { + method: "POST", + headers: reqHeaders, + body: JSON.stringify({ url, method, headers, body }), + }); + + if (!res.ok) { + const text = await res.text(); + throw new Error(`Remote fetch failed (${res.status}): ${text}`); + } + + const data = (await res.json()) as { + ok: boolean; + status: number; + statusText: string; + headers: Record; + body?: string; + }; + + return deserializeResponse(data); + }; +} diff --git a/shared/mcp/remote/createRemoteLogger.ts b/shared/mcp/remote/createRemoteLogger.ts new file mode 100644 index 000000000..e4aae396e --- /dev/null +++ b/shared/mcp/remote/createRemoteLogger.ts @@ -0,0 +1,62 @@ +/** + * Creates a pino logger that POSTs log events to the remote /api/log endpoint + * via browser.transmit. Use in the browser when InspectorClient needs logging— + * logs are written server-side to the same file logger as Node mode. + * + * Uses pino/browser so transmit works in both Node (tests) and browser. + */ + +// @ts-expect-error - pino/browser.js exists but TypeScript doesn't have types for the .js extension +// Node.js ESM requires explicit .js extension, and pino exports browser.js +import pino from "pino/browser.js"; +import type { Logger, LogEvent } from "pino"; + +export interface RemoteLoggerOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + + /** Fetch function to use (default: globalThis.fetch) */ + fetchFn?: typeof fetch; + + /** Minimum level to send (default: 'info') */ + level?: string; +} + +/** + * Creates a pino logger that transmits log events to the remote /api/log endpoint. + * Returns a real pino.Logger; suitable for InspectorClient's logger option. + */ +export function createRemoteLogger(options: RemoteLoggerOptions): Logger { + const baseUrl = options.baseUrl.replace(/\/$/, ""); + const fetchFn = options.fetchFn ?? globalThis.fetch; + const level = options.level ?? "info"; + + return pino({ + level, + browser: { + write: () => {}, + transmit: { + level, + send: (_level: unknown, logEvent: LogEvent) => { + const headers: Record = { + "Content-Type": "application/json", + }; + if (options.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`; + } + + fetchFn(`${baseUrl}/api/log`, { + method: "POST", + headers, + body: JSON.stringify(logEvent), + }).catch(() => { + // Silently ignore log delivery failures + }); + }, + }, + }, + }); +} diff --git a/shared/mcp/remote/createRemoteTransport.ts b/shared/mcp/remote/createRemoteTransport.ts new file mode 100644 index 000000000..13fe94123 --- /dev/null +++ b/shared/mcp/remote/createRemoteTransport.ts @@ -0,0 +1,67 @@ +/** + * Factory for createRemoteTransport - returns a CreateTransport that uses the remote server. + */ + +import type { + MCPServerConfig, + CreateTransport, + CreateTransportOptions, + CreateTransportResult, +} from "../types.js"; +import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; +import { RemoteClientTransport } from "./remoteClientTransport.js"; + +export interface RemoteTransportFactoryOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + + /** Optional fetch implementation (for proxy or testing) */ + fetchFn?: typeof fetch; +} + +/** + * Creates a CreateTransport that produces RemoteClientTransport instances + * connecting to the given remote server. + * + * @example + * import { API_SERVER_ENV_VARS } from '@modelcontextprotocol/inspector-shared/mcp/remote'; + * const createTransport = createRemoteTransport({ + * baseUrl: 'http://localhost:3000', + * authToken: process.env[API_SERVER_ENV_VARS.AUTH_TOKEN], + * }); + * const inspector = new InspectorClient(config, { + * environment: { + * transport: createTransport, + * }, + * ... + * }); + */ +export function createRemoteTransport( + options: RemoteTransportFactoryOptions, +): CreateTransport { + return ( + config: MCPServerConfig, + transportOptions: CreateTransportOptions = {}, + ): CreateTransportResult => { + // Use only the factory's fetchFn, not InspectorClient's. The transport's HTTP + // (connect, GET events, send, disconnect) must support streaming (GET /api/mcp/events + // is SSE). A remoted fetch (e.g. createRemoteFetch) buffers responses and cannot + // stream. So we ignore transportOptions.fetchFn here; auth can still use a + // remoted fetch via InspectorClient's fetchFn (effectiveAuthFetch). + const transport = new RemoteClientTransport( + { + baseUrl: options.baseUrl, + authToken: options.authToken, + fetchFn: options.fetchFn, + onStderr: transportOptions.onStderr, + onFetchRequest: transportOptions.onFetchRequest, + authProvider: transportOptions.authProvider, + }, + config, + ); + return { transport }; + }; +} diff --git a/shared/mcp/remote/index.ts b/shared/mcp/remote/index.ts new file mode 100644 index 000000000..7e7d72c18 --- /dev/null +++ b/shared/mcp/remote/index.ts @@ -0,0 +1,31 @@ +/** + * Remote transport client - pure TypeScript, runs in browser, Deno, or Node. + * Talks to the remote server for MCP connections when direct transport is not available. + */ + +export { + RemoteClientTransport, + type RemoteTransportOptions, +} from "./remoteClientTransport.js"; +export { + createRemoteTransport, + type RemoteTransportFactoryOptions, +} from "./createRemoteTransport.js"; +export { + createRemoteFetch, + type RemoteFetchOptions, +} from "./createRemoteFetch.js"; +export { + createRemoteLogger, + type RemoteLoggerOptions, +} from "./createRemoteLogger.js"; +export { + RemoteInspectorClientStorage, + type RemoteInspectorClientStorageOptions, +} from "./sessionStorage.js"; +export type { + RemoteConnectRequest, + RemoteConnectResponse, + RemoteEvent, +} from "./types.js"; +export { API_SERVER_ENV_VARS } from "./constants.js"; diff --git a/shared/mcp/remote/node/index.ts b/shared/mcp/remote/node/index.ts new file mode 100644 index 000000000..1c30e7361 --- /dev/null +++ b/shared/mcp/remote/node/index.ts @@ -0,0 +1,11 @@ +/** + * Remote server (Node) - Hono app for /api/mcp/*, /api/fetch, /api/log. + */ + +export { + createRemoteApp, + type RemoteServerOptions, + type CreateRemoteAppResult, +} from "./server.js"; +// Re-export constants from base remote directory (browser-safe) +export { API_SERVER_ENV_VARS } from "../constants.js"; diff --git a/shared/mcp/remote/node/remote-session.ts b/shared/mcp/remote/node/remote-session.ts new file mode 100644 index 000000000..227662568 --- /dev/null +++ b/shared/mcp/remote/node/remote-session.ts @@ -0,0 +1,107 @@ +/** + * Remote session - holds a transport and event queue for a remote client. + */ + +import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; +import type { FetchRequestEntryBase } from "../../types.js"; +import type { RemoteEvent } from "../types.js"; + +export interface SessionEvent { + type: RemoteEvent["type"]; + data: unknown; +} + +export class RemoteSession { + public readonly sessionId: string; + public transport!: Transport; + private eventQueue: SessionEvent[] = []; + private eventConsumer: ((event: SessionEvent) => void) | null = null; + private transportDead: boolean = false; + private transportError: string | null = null; + + constructor(sessionId: string) { + this.sessionId = sessionId; + } + + setTransport(transport: Transport): void { + this.transport = transport; + } + + setEventConsumer(consumer: (event: SessionEvent) => void): void { + this.eventConsumer = consumer; + // Flush queued events + while (this.eventQueue.length > 0) { + const ev = this.eventQueue.shift()!; + consumer(ev); + } + } + + clearEventConsumer(): boolean { + this.eventConsumer = null; + // If transport is dead and no client connected, signal to cleanup + return this.transportDead; + } + + markTransportDead(error: string): void { + this.transportDead = true; + this.transportError = error; + // Send error event if client is connected + if (this.eventConsumer) { + this.pushEvent({ + type: "transport_error", + data: { + error, + code: -32000, // MCP error code for connection closed + }, + }); + } + } + + isTransportDead(): boolean { + return this.transportDead; + } + + getTransportError(): string | null { + return this.transportError; + } + + hasEventConsumer(): boolean { + return this.eventConsumer !== null; + } + + pushEvent(event: SessionEvent): void { + if (this.eventConsumer) { + this.eventConsumer(event); + } else { + this.eventQueue.push(event); + } + } + + onMessage(message: JSONRPCMessage): void { + this.pushEvent({ type: "message", data: message }); + } + + onFetchRequest(entry: FetchRequestEntryBase): void { + this.pushEvent({ + type: "fetch_request", + data: { + ...entry, + timestamp: + entry.timestamp instanceof Date + ? entry.timestamp.toISOString() + : entry.timestamp, + }, + }); + } + + onStderr(entry: { timestamp: Date; message: string }): void { + this.pushEvent({ + type: "stdio_log", + data: { + timestamp: entry.timestamp.toISOString(), + message: entry.message, + }, + }); + } +} diff --git a/shared/mcp/remote/node/server.ts b/shared/mcp/remote/node/server.ts new file mode 100644 index 000000000..6e407dfa6 --- /dev/null +++ b/shared/mcp/remote/node/server.ts @@ -0,0 +1,705 @@ +/** + * Hono-based remote server for MCP transports. + * Hosts /api/config, /api/mcp/connect, send, events, disconnect, /api/fetch, /api/log, /api/storage/:storeId. + */ + +import { randomBytes, timingSafeEqual } from "node:crypto"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import type pino from "pino"; +import type { LogEvent } from "pino"; +import { Hono } from "hono"; +import type { Context, Next } from "hono"; +import { streamSSE } from "hono/streaming"; +import { createTransportNode } from "../../node/transport.js"; +import type { RemoteConnectRequest, RemoteSendRequest } from "../types.js"; +import type { MCPServerConfig } from "../../types.js"; +import { RemoteSession } from "./remote-session.js"; +import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { OAuthTokens } from "@modelcontextprotocol/sdk/shared/auth.js"; +import { API_SERVER_ENV_VARS } from "../constants.js"; + +export interface RemoteServerOptions { + /** Optional auth token. If not provided, uses API_SERVER_ENV_VARS.AUTH_TOKEN env var or generates one. */ + authToken?: string; + + /** Optional: validate Origin header against allowed origins (for CORS) */ + allowedOrigins?: string[]; + + /** Optional pino file logger. When set, /api/log forwards received events to it. */ + logger?: pino.Logger; + + /** Optional storage directory for /api/storage/:storeId. Default: ~/.mcp-inspector/storage */ + storageDir?: string; +} + +export interface CreateRemoteAppResult { + /** The Hono app */ + app: Hono; + /** The auth token (from options, env var, or generated). Returned so caller can embed in client. */ + authToken: string; +} + +function safeCompare(a: string, b: string): boolean { + if (a.length !== b.length) return false; + const bufA = Buffer.from(a, "utf8"); + const bufB = Buffer.from(b, "utf8"); + if (bufA.length !== bufB.length) return false; + return timingSafeEqual(bufA, bufB); +} + +/** + * Hono middleware for origin validation (CORS and DNS rebinding protection). + * Validates Origin header against allowedOrigins if provided. + */ +function createOriginMiddleware(allowedOrigins?: string[]) { + return async (c: Context, next: Next) => { + // If no allowedOrigins configured, skip validation (allow all) + if (!allowedOrigins || allowedOrigins.length === 0) { + await next(); + return; + } + + const origin = c.req.header("origin"); + + // Handle CORS preflight requests + if (c.req.method === "OPTIONS") { + if (origin && allowedOrigins.includes(origin)) { + c.header("Access-Control-Allow-Origin", origin); + c.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS"); + c.header( + "Access-Control-Allow-Headers", + "Content-Type, x-mcp-remote-auth", + ); + c.header("Access-Control-Max-Age", "86400"); // 24 hours + return c.body(null, 204); + } + // Invalid origin for preflight - return 403 + return c.json( + { + error: "Forbidden", + message: + "Invalid origin. Request blocked to prevent DNS rebinding attacks.", + }, + 403, + ); + } + + // For actual requests, validate origin if present + if (origin) { + if (!allowedOrigins.includes(origin)) { + return c.json( + { + error: "Forbidden", + message: + "Invalid origin. Request blocked to prevent DNS rebinding attacks. Configure allowed origins via allowedOrigins option.", + }, + 403, + ); + } + // Set CORS header for allowed origin + c.header("Access-Control-Allow-Origin", origin); + } + // If no origin header (same-origin or non-browser client), allow request + + await next(); + }; +} + +/** + * Hono middleware for auth token validation. + * Expects Bearer token format: x-mcp-remote-auth: Bearer + */ +function createAuthMiddleware(authToken: string) { + return async (c: Context, next: Next) => { + const authHeader = c.req.header("x-mcp-remote-auth"); + if (!authHeader || !authHeader.startsWith("Bearer ")) { + return c.json( + { + error: "Unauthorized", + message: + "Authentication required. Use the x-mcp-remote-auth header with Bearer token.", + }, + 401, + ); + } + + const providedToken = authHeader.substring(7); // Remove 'Bearer ' prefix + const expectedToken = authToken; + + // Convert to buffers for timing-safe comparison + const providedBuffer = Buffer.from(providedToken); + const expectedBuffer = Buffer.from(expectedToken); + + // Check length first to prevent timing attacks + if (providedBuffer.length !== expectedBuffer.length) { + return c.json( + { + error: "Unauthorized", + message: + "Authentication required. Use the x-mcp-remote-auth header with Bearer token.", + }, + 401, + ); + } + + // Perform timing-safe comparison + if (!timingSafeEqual(providedBuffer, expectedBuffer)) { + return c.json( + { + error: "Unauthorized", + message: + "Authentication required. Use the x-mcp-remote-auth header with Bearer token.", + }, + 401, + ); + } + + await next(); + }; +} + +/** + * Get default storage directory path. + */ +function getDefaultStorageDir(): string { + const homeDir = process.env.HOME || process.env.USERPROFILE || "."; + return path.join(homeDir, ".mcp-inspector", "storage"); +} + +/** + * Build initial config object from process.env for GET /api/config. + * Same shape as previously injected via __INITIAL_CONFIG__. + */ +function buildInitialConfigFromEnv(): { + defaultCommand?: string; + defaultArgs?: string[]; + defaultTransport?: string; + defaultServerUrl?: string; + defaultEnvironment: Record; +} { + const defaultEnvKeys = + process.platform === "win32" + ? [ + "APPDATA", + "HOMEDRIVE", + "HOMEPATH", + "LOCALAPPDATA", + "PATH", + "PROCESSOR_ARCHITECTURE", + "SYSTEMDRIVE", + "SYSTEMROOT", + "TEMP", + "USERNAME", + "USERPROFILE", + "PROGRAMFILES", + ] + : ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]; + + const defaultEnvironment: Record = {}; + for (const key of defaultEnvKeys) { + const value = process.env[key]; + if (value && !value.startsWith("()")) { + defaultEnvironment[key] = value; + } + } + if (process.env.MCP_ENV_VARS) { + try { + Object.assign( + defaultEnvironment, + JSON.parse(process.env.MCP_ENV_VARS) as Record, + ); + } catch { + // Ignore invalid MCP_ENV_VARS + } + } + + return { + ...(process.env.MCP_INITIAL_COMMAND + ? { defaultCommand: process.env.MCP_INITIAL_COMMAND } + : {}), + ...(process.env.MCP_INITIAL_ARGS + ? { defaultArgs: process.env.MCP_INITIAL_ARGS.split(" ") } + : {}), + ...(process.env.MCP_INITIAL_TRANSPORT + ? { defaultTransport: process.env.MCP_INITIAL_TRANSPORT } + : {}), + ...(process.env.MCP_INITIAL_SERVER_URL + ? { defaultServerUrl: process.env.MCP_INITIAL_SERVER_URL } + : {}), + defaultEnvironment, + }; +} + +/** + * Validate storeId to prevent path traversal attacks. + * Store IDs must be alphanumeric, hyphens, underscores only, and not empty. + */ +function validateStoreId(storeId: string): boolean { + return /^[a-zA-Z0-9_-]+$/.test(storeId) && storeId.length > 0; +} + +/** + * Get file path for a store ID. + */ +function getStoreFilePath(storageDir: string, storeId: string): string { + return path.join(storageDir, `${storeId}.json`); +} + +/** + * Simple OAuth client provider that just returns tokens. + * Used by remote server to inject Bearer tokens into transport requests. + */ +function createTokenAuthProvider( + tokens: RemoteConnectRequest["oauthTokens"], +): OAuthClientProvider | undefined { + if (!tokens) return undefined; + + return { + async tokens(): Promise { + return tokens as OAuthTokens; + }, + // Other methods not needed for transport Bearer token injection + async clientInformation() { + return undefined; + }, + async saveTokens() { + // No-op + }, + codeVerifier() { + return undefined; + }, + async saveCodeVerifier() { + // No-op + }, + clear() { + // No-op + }, + redirectToAuthorization() { + // No-op + }, + state() { + return ""; + }, + } as unknown as OAuthClientProvider; +} + +function forwardLogEvent( + logger: pino.Logger, + logEvent: Partial, +): void { + const levelLabel = (logEvent?.level?.label ?? "info").toLowerCase(); + const method = (logger as unknown as Record)[levelLabel]; + if (typeof method !== "function") return; + + const bindings = Object.assign( + {}, + ...(Array.isArray(logEvent.bindings) ? logEvent.bindings : []), + ); + const messages = Array.isArray(logEvent.messages) ? logEvent.messages : []; + + if (messages.length === 0) { + (method as (obj: object) => void).call(logger, bindings); + return; + } + + const first = messages[0]; + if (typeof first === "object" && first !== null && !Array.isArray(first)) { + const obj = { ...bindings, ...(first as Record) }; + const msg = messages[1]; + const args = messages.slice(2); + (method as (obj: object, msg?: unknown, ...args: unknown[]) => void).call( + logger, + obj, + msg, + ...args, + ); + } else { + const msg = messages[0]; + const args = messages.slice(1); + (method as (obj: object, msg?: unknown, ...args: unknown[]) => void).call( + logger, + bindings, + msg, + ...args, + ); + } +} + +export function createRemoteApp( + options: RemoteServerOptions = {}, +): CreateRemoteAppResult { + // Determine auth token: options > env var > generate + const authToken = + options.authToken || + process.env[API_SERVER_ENV_VARS.AUTH_TOKEN] || + randomBytes(32).toString("hex"); + + const app = new Hono(); + const sessions = new Map(); + const { logger: fileLogger, allowedOrigins } = options; + const storageDir = options.storageDir ?? getDefaultStorageDir(); + + // Apply origin validation middleware first (before auth) + // This prevents DNS rebinding attacks by validating Origin header + app.use("*", createOriginMiddleware(allowedOrigins)); + + // Apply auth middleware to all routes + // Auth is always enabled (token from options, env var, or generated) + app.use("*", createAuthMiddleware(authToken)); + + app.get("/api/config", (c) => { + const initialConfig = buildInitialConfigFromEnv(); + return c.json(initialConfig); + }); + + app.post("/api/mcp/connect", async (c) => { + let body: RemoteConnectRequest; + try { + body = (await c.req.json()) as RemoteConnectRequest; + } catch { + return c.json({ error: "Invalid JSON body" }, 400); + } + + const config = body.config as MCPServerConfig; + if (!config) { + return c.json({ error: "Missing config" }, 400); + } + + const sessionId = crypto.randomUUID(); + const session = new RemoteSession(sessionId); + + let transport: Awaited>["transport"]; + try { + // Create authProvider from tokens if provided + const authProvider = createTokenAuthProvider(body.oauthTokens); + + const result = createTransportNode(config, { + pipeStderr: true, + onStderr: (entry) => session.onStderr(entry), + onFetchRequest: (entry) => session.onFetchRequest(entry), + authProvider, + }); + transport = result.transport; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + return c.json({ error: `Failed to create transport: ${msg}` }, 500); + } + + session.setTransport(transport); + transport.onmessage = (msg) => session.onMessage(msg); + + // Track if transport closes/errors during start - this matches local behavior + // If transport.start() throws, we catch it. If it resolves but transport closes immediately, + // we detect that too (process failure after spawn). + let transportFailed = false; + let transportError: string | null = null; + + const originalOnclose = transport.onclose; + const originalOnerror = transport.onerror; + + // Set up error handlers BEFORE calling start() so we catch failures during start + transport.onerror = (err) => { + transportFailed = true; + transportError = err instanceof Error ? err.message : String(err); + originalOnerror?.(err); + }; + + transport.onclose = () => { + const session = sessions.get(sessionId); + if (session) { + // Mark transport as dead but don't delete session yet + // We'll notify client via SSE and cleanup when client disconnects + const errorMsg = + transportError || "Transport closed - process may have exited"; + session.markTransportDead(errorMsg); + // If no client connected, can cleanup immediately + if (!session.hasEventConsumer()) { + sessions.delete(sessionId); + } + } else { + // Session not created yet - failed during start + transportFailed = true; + transportError = + transportError || + "Transport closed during start - process may have failed"; + } + originalOnclose?.(); + }; + + try { + // transport.start() should throw if process fails to start + // If it resolves, the process should be running + await transport.start(); + + // Check if transport failed during start (onerror/onclose fired synchronously) + if (transportFailed) { + const errorMsg = transportError || "Transport failed during start"; + return c.json({ error: `Failed to start transport: ${errorMsg}` }, 500); + } + } catch (err) { + // transport.start() threw - this is the expected failure path + const msg = err instanceof Error ? err.message : String(err); + // Preserve 401 status if the underlying error is a 401 + const is401 = + (err as { code?: number }).code === 401 || + msg.includes("401") || + msg.includes("Unauthorized"); + return c.json( + { error: `Failed to start transport: ${msg}` }, + is401 ? 401 : 500, + ); + } + + // Transport started successfully - add to sessions + sessions.set(sessionId, session); + + return c.json({ sessionId }); + }); + + app.post("/api/mcp/send", async (c) => { + let body: RemoteSendRequest & { sessionId?: string }; + try { + body = (await c.req.json()) as RemoteSendRequest & { sessionId?: string }; + } catch { + return c.json({ error: "Invalid JSON body" }, 400); + } + + const { sessionId, message, relatedRequestId } = body; + if (!sessionId || !message) { + return c.json({ error: "Missing sessionId or message" }, 400); + } + + const session = sessions.get(sessionId); + if (!session) { + return c.json({ error: "Session not found" }, 404); + } + + // Check if transport is dead - return error immediately (matches local behavior) + if (session.isTransportDead()) { + const errorMsg = session.getTransportError() || "Transport closed"; + return c.json({ error: errorMsg }, 500); + } + + try { + await session.transport.send(message, { + relatedRequestId: relatedRequestId as string | number | undefined, + }); + return c.json({ ok: true }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + return c.json({ error: msg }, 500); + } + }); + + app.get("/api/mcp/events", async (c) => { + const sessionId = c.req.query("sessionId"); + if (!sessionId) { + return c.json({ error: "Missing sessionId query" }, 400); + } + + const session = sessions.get(sessionId); + if (!session) { + return c.json({ error: "Session not found" }, 404); + } + + return streamSSE(c, async (stream) => { + session.setEventConsumer((event) => { + const data = JSON.stringify(event); + void stream.writeSSE({ + event: event.type, + data, + }); + }); + + stream.onAbort(() => { + // Client disconnected - clear event consumer + const shouldCleanup = session.clearEventConsumer(); + stream.close(); + + // If transport is dead and no client connected, cleanup session + if (shouldCleanup || session.isTransportDead()) { + sessions.delete(sessionId); + } + }); + + // Keep the stream open until the client disconnects. Hono's streamSSE + // closes the stream when this callback returns, so we must not return + // until the connection is aborted. + await new Promise((resolve) => { + stream.onAbort(() => { + // Cleanup happens in onAbort handler above + resolve(); + }); + }); + }); + }); + + app.post("/api/mcp/disconnect", async (c) => { + let body: { sessionId?: string }; + try { + body = (await c.req.json()) as { sessionId?: string }; + } catch { + return c.json({ error: "Invalid JSON body" }, 400); + } + + const sessionId = body.sessionId; + if (!sessionId) { + return c.json({ error: "Missing sessionId" }, 400); + } + + const session = sessions.get(sessionId); + if (session) { + session.clearEventConsumer(); + await session.transport.close(); + sessions.delete(sessionId); + } + + return c.json({ ok: true }); + }); + + app.post("/api/fetch", async (c) => { + let body: { + url: string; + method?: string; + headers?: Record; + body?: string; + }; + try { + body = (await c.req.json()) as typeof body; + } catch { + return c.json({ error: "Invalid JSON body" }, 400); + } + + const { url, method = "GET", headers = {}, body: reqBody } = body; + if (!url) { + return c.json({ error: "Missing url" }, 400); + } + + try { + const res = await fetch(url, { + method, + headers: new Headers(headers), + body: reqBody, + }); + + const resHeaders: Record = {}; + res.headers.forEach((v, k) => { + resHeaders[k] = v; + }); + + const contentType = res.headers.get("content-type"); + const isStream = + contentType?.includes("text/event-stream") || + contentType?.includes("application/x-ndjson"); + let resBody: string | undefined; + if (!isStream && res.body) { + resBody = await res.text(); + } + + return c.json({ + ok: res.ok, + status: res.status, + statusText: res.statusText, + headers: resHeaders, + body: resBody, + }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + return c.json({ error: msg }, 500); + } + }); + + app.post("/api/log", async (c) => { + const body = (await c.req.json().catch(() => ({}))) as Partial; + if (fileLogger) { + forwardLogEvent(fileLogger, body); + } else { + console.log("[remote-log]", body); + } + return c.json({ ok: true }); + }); + + app.get("/api/storage/:storeId", async (c) => { + const storeId = c.req.param("storeId"); + if (!storeId || !validateStoreId(storeId)) { + return c.json({ error: "Invalid storeId" }, 400); + } + + const filePath = getStoreFilePath(storageDir, storeId); + + try { + const data = await fs.readFile(filePath, "utf-8"); + const store = JSON.parse(data); + return c.json(store); + } catch (error) { + const err = error as NodeJS.ErrnoException; + if (err.code === "ENOENT") { + return c.json({}, 200); // Return empty object if file doesn't exist + } + const msg = err instanceof Error ? err.message : String(err); + return c.json({ error: `Failed to read store: ${msg}` }, 500); + } + }); + + app.post("/api/storage/:storeId", async (c) => { + const storeId = c.req.param("storeId"); + if (!storeId || !validateStoreId(storeId)) { + return c.json({ error: "Invalid storeId" }, 400); + } + + let body: unknown; + try { + body = await c.req.json(); + } catch { + return c.json({ error: "Invalid JSON body" }, 400); + } + + const filePath = getStoreFilePath(storageDir, storeId); + + try { + // Ensure storage directory exists + await fs.mkdir(storageDir, { recursive: true }); + + // Write store as JSON + const jsonData = JSON.stringify(body, null, 2); + await fs.writeFile(filePath, jsonData, "utf-8"); + + // Set restrictive permissions (600) for security + try { + await fs.chmod(filePath, 0o600); + } catch { + // Ignore chmod errors (may fail on some systems) + } + + return c.json({ ok: true }); + } catch (error) { + const msg = error instanceof Error ? error.message : String(error); + return c.json({ error: `Failed to write store: ${msg}` }, 500); + } + }); + + app.delete("/api/storage/:storeId", async (c) => { + const storeId = c.req.param("storeId"); + if (!storeId || !validateStoreId(storeId)) { + return c.json({ error: "Invalid storeId" }, 400); + } + + const filePath = getStoreFilePath(storageDir, storeId); + + try { + await fs.unlink(filePath); + return c.json({ ok: true }); + } catch (error) { + const err = error as NodeJS.ErrnoException; + if (err.code === "ENOENT") { + // Already deleted, return success + return c.json({ ok: true }); + } + const msg = err instanceof Error ? err.message : String(err); + return c.json({ error: `Failed to delete store: ${msg}` }, 500); + } + }); + + return { app, authToken }; +} diff --git a/shared/mcp/remote/pino-browser.d.ts b/shared/mcp/remote/pino-browser.d.ts new file mode 100644 index 000000000..62d42a807 --- /dev/null +++ b/shared/mcp/remote/pino-browser.d.ts @@ -0,0 +1,9 @@ +/** + * Type declaration for pino/browser (has transmit support). + * The pino package provides a browser build at pino/browser. + */ +declare module "pino/browser" { + import type { Logger, LoggerOptions } from "pino"; + function pino(options?: LoggerOptions): Logger; + export = pino; +} diff --git a/shared/mcp/remote/remoteClientTransport.ts b/shared/mcp/remote/remoteClientTransport.ts new file mode 100644 index 000000000..e9feca62a --- /dev/null +++ b/shared/mcp/remote/remoteClientTransport.ts @@ -0,0 +1,330 @@ +/** + * RemoteClientTransport - Transport that talks to a remote server via HTTP. + * Pure TypeScript; works in browser, Deno, or Node. + */ + +import type { + Transport, + TransportSendOptions, +} from "@modelcontextprotocol/sdk/shared/transport.js"; +import type { + JSONRPCMessage, + MessageExtraInfo, +} from "@modelcontextprotocol/sdk/types.js"; +import type { StderrLogEntry } from "../types.js"; +import type { FetchRequestEntryBase } from "../types.js"; +import type { + RemoteConnectRequest, + RemoteConnectResponse, + RemoteEvent, +} from "./types.js"; + +export interface RemoteTransportOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + + /** Optional fetch implementation (for proxy or testing) */ + fetchFn?: typeof fetch; + + /** Callback for stderr from stdio transports (forwarded via remote) */ + onStderr?: (entry: StderrLogEntry) => void; + + /** Callback for fetch request tracking (forwarded via remote) */ + onFetchRequest?: (entry: FetchRequestEntryBase) => void; + + /** Optional OAuth client provider for Bearer authentication */ + authProvider?: import("@modelcontextprotocol/sdk/client/auth.js").OAuthClientProvider; +} + +/** + * Parse SSE stream from a ReadableStream. + * Yields { event, data } for each SSE message. + */ +async function* parseSSE( + reader: ReadableStreamDefaultReader, +): AsyncGenerator<{ event: string; data: string }> { + const decoder = new TextDecoder(); + let buffer = ""; + + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n"); + buffer = lines.pop() ?? ""; + + let currentEvent = "message"; + let currentData: string[] = []; + + for (const line of lines) { + if (line.startsWith("event:")) { + currentEvent = line.slice(6).trim(); + } else if (line.startsWith("data:")) { + currentData.push(line.slice(5).trimStart()); + } else if (line === "") { + if (currentData.length > 0) { + yield { event: currentEvent, data: currentData.join("\n") }; + } + currentEvent = "message"; + currentData = []; + } + } + } + + if (buffer.trim()) { + const lines = buffer.split("\n"); + let currentEvent = "message"; + const currentData: string[] = []; + for (const line of lines) { + if (line.startsWith("event:")) currentEvent = line.slice(6).trim(); + else if (line.startsWith("data:")) + currentData.push(line.slice(5).trimStart()); + } + if (currentData.length > 0) { + yield { event: currentEvent, data: currentData.join("\n") }; + } + } +} + +/** + * Transport that forwards JSON-RPC to a remote server and receives responses via SSE. + */ +export class RemoteClientTransport implements Transport { + private _sessionId: string | undefined = undefined; + private eventStreamReader: ReadableStreamDefaultReader | null = + null; + private eventStreamAbort: AbortController | null = null; + private closed = false; + + /** + * Intentionally returns undefined. The MCP Client checks transport.sessionId to detect + * reconnects and skip initialize. Our _sessionId is the remote server's session ID, not + * the MCP protocol's initialization state. Exposing it would cause the MCP Client to + * skip initialize and send tools/list first, which fails on streamable-http (and any + * transport requiring initialize before other requests). + */ + get sessionId(): string | undefined { + return undefined; + } + + constructor( + private readonly options: RemoteTransportOptions, + private readonly config: import("../types.js").MCPServerConfig, + ) {} + + private get fetchFn(): typeof fetch { + return this.options.fetchFn ?? globalThis.fetch; + } + + private get baseUrl(): string { + return this.options.baseUrl.replace(/\/$/, ""); + } + + private get headers(): Record { + const h: Record = { + "Content-Type": "application/json", + }; + if (this.options.authToken) { + h["x-mcp-remote-auth"] = `Bearer ${this.options.authToken}`; + } + return h; + } + + async start(): Promise { + if (this.sessionId) return; + if (this.closed) throw new Error("Transport is closed"); + + // Extract OAuth tokens from authProvider if available + let oauthTokens: RemoteConnectRequest["oauthTokens"] | undefined; + if (this.options.authProvider) { + const tokens = await this.options.authProvider.tokens(); + if (tokens) { + oauthTokens = { + access_token: tokens.access_token, + token_type: tokens.token_type, + expires_in: tokens.expires_in, + refresh_token: tokens.refresh_token, + }; + } + } + + const body: RemoteConnectRequest = { + config: this.config, + oauthTokens, + }; + + const res = await this.fetchFn(`${this.baseUrl}/api/mcp/connect`, { + method: "POST", + headers: this.headers, + body: JSON.stringify(body), + }); + + if (!res.ok) { + const text = await res.text(); + // Preserve the status code in the error so callers can detect 401 + const error = new Error(`Remote connect failed (${res.status}): ${text}`); + (error as { status?: number }).status = res.status; + throw error; + } + + const json = (await res.json()) as RemoteConnectResponse; + this._sessionId = json.sessionId; + + if (!this._sessionId) { + throw new Error("Remote did not return sessionId"); + } + + // Open SSE event stream + this.eventStreamAbort = new AbortController(); + const eventRes = await this.fetchFn( + `${this.baseUrl}/api/mcp/events?sessionId=${encodeURIComponent(this._sessionId!)}`, + { + headers: this.options.authToken + ? { "x-mcp-remote-auth": `Bearer ${this.options.authToken}` } + : {}, + signal: this.eventStreamAbort.signal, + }, + ); + + if (!eventRes.ok) { + this._sessionId = undefined; + throw new Error( + `Remote events stream failed (${eventRes.status}): ${await eventRes.text()}`, + ); + } + + const bodyStream = eventRes.body; + if (!bodyStream) { + throw new Error("Remote events stream has no body"); + } + + this.eventStreamReader = bodyStream.getReader(); + this.consumeEventStream(); + } + + private async consumeEventStream(): Promise { + if (!this.eventStreamReader) return; + + try { + for await (const { event, data } of parseSSE(this.eventStreamReader)) { + if (this.closed) break; + + try { + const parsed = JSON.parse(data) as RemoteEvent; + + if (parsed.type === "message") { + this.onmessage?.(parsed.data as JSONRPCMessage, undefined); + } else if ( + parsed.type === "fetch_request" && + this.options.onFetchRequest + ) { + const entry = parsed.data; + this.options.onFetchRequest({ + ...entry, + timestamp: + typeof entry.timestamp === "string" + ? new Date(entry.timestamp) + : entry.timestamp, + }); + } else if (parsed.type === "stdio_log" && this.options.onStderr) { + this.options.onStderr({ + timestamp: new Date(parsed.data.timestamp), + message: parsed.data.message, + }); + } else if (parsed.type === "transport_error") { + // Transport died - notify client and close (matches local behavior) + const error = new Error(parsed.data.error); + if (parsed.data.code !== undefined) { + (error as { code?: number | string }).code = parsed.data.code; + } + this.onerror?.(error); + // Also trigger onclose to match local transport behavior + if (!this.closed) { + this.closed = true; + this.onclose?.(); + } + } + } catch (err) { + // JSON parse error or other processing error - report but continue + this.onerror?.(err instanceof Error ? err : new Error(String(err))); + } + } + } catch (err) { + // Stream reading error (network issue, abort, etc.) + if (!this.closed && err instanceof Error && err.name !== "AbortError") { + this.onerror?.(err); + } + } finally { + this.eventStreamReader = null; + if (!this.closed) { + this.closed = true; + this.onclose?.(); + } + } + } + + async send( + message: JSONRPCMessage, + options?: TransportSendOptions, + ): Promise { + if (!this._sessionId) { + throw new Error("Transport not started"); + } + if (this.closed) { + throw new Error("Transport is closed"); + } + + const body = { + sessionId: this._sessionId, + message, + ...(options?.relatedRequestId != null && { + relatedRequestId: options.relatedRequestId, + }), + }; + + const res = await this.fetchFn(`${this.baseUrl}/api/mcp/send`, { + method: "POST", + headers: this.headers, + body: JSON.stringify(body), + }); + + if (!res.ok) { + const text = await res.text(); + throw new Error(`Remote send failed (${res.status}): ${text}`); + } + } + + async close(): Promise { + if (this.closed) return; + + this.closed = true; + this.eventStreamAbort?.abort(); + this.eventStreamReader = null; + + if (this._sessionId) { + try { + await this.fetchFn(`${this.baseUrl}/api/mcp/disconnect`, { + method: "POST", + headers: this.headers, + body: JSON.stringify({ sessionId: this._sessionId }), + }); + } catch { + // Ignore disconnect errors + } + this._sessionId = undefined; + } + + this.onclose?.(); + } + + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: ( + message: T, + extra?: MessageExtraInfo, + ) => void; +} diff --git a/shared/mcp/remote/sessionStorage.ts b/shared/mcp/remote/sessionStorage.ts new file mode 100644 index 000000000..593baf417 --- /dev/null +++ b/shared/mcp/remote/sessionStorage.ts @@ -0,0 +1,140 @@ +/** + * Remote HTTP storage implementation for InspectorClient session state. + * Uses the remote /api/storage/:storeId endpoint to persist session data + * across page navigations during OAuth flows. + */ + +import type { + InspectorClientStorage, + InspectorClientSessionState, +} from "../sessionStorage.js"; + +export interface RemoteInspectorClientStorageOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + /** Fetch function to use (default: globalThis.fetch) */ + fetchFn?: typeof fetch; +} + +/** + * Remote HTTP storage implementation for InspectorClient session state. + * Stores session data via HTTP API (GET/POST/DELETE /api/storage/:storeId). + * For web clients that need to persist session state across OAuth redirects. + */ +export class RemoteInspectorClientStorage implements InspectorClientStorage { + private baseUrl: string; + private authToken?: string; + private fetchFn: typeof fetch; + + constructor(options: RemoteInspectorClientStorageOptions) { + this.baseUrl = options.baseUrl.replace(/\/$/, ""); + this.authToken = options.authToken; + this.fetchFn = options.fetchFn ?? globalThis.fetch; + } + + private getStoreId(sessionId: string): string { + // Use a prefix to distinguish from OAuth storage + return `inspector-session-${sessionId}`; + } + + async saveSession( + sessionId: string, + state: InspectorClientSessionState, + ): Promise { + const storeId = this.getStoreId(sessionId); + const url = `${this.baseUrl}/api/storage/${encodeURIComponent(storeId)}`; + + const headers: Record = { + "Content-Type": "application/json", + }; + if (this.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${this.authToken}`; + } + + // Serialize state (convert Date objects to ISO strings for JSON) + const serializedState = { + ...state, + fetchRequests: state.fetchRequests.map((req) => ({ + ...req, + timestamp: + req.timestamp instanceof Date + ? req.timestamp.toISOString() + : req.timestamp, + })), + }; + + const res = await this.fetchFn(url, { + method: "POST", + headers, + body: JSON.stringify(serializedState), + }); + + if (!res.ok) { + const text = await res.text(); + throw new Error(`Failed to save session: ${res.status} ${text}`); + } + } + + async loadSession( + sessionId: string, + ): Promise { + const storeId = this.getStoreId(sessionId); + const url = `${this.baseUrl}/api/storage/${encodeURIComponent(storeId)}`; + + const headers: Record = {}; + if (this.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${this.authToken}`; + } + + const res = await this.fetchFn(url, { + method: "GET", + headers, + }); + + if (!res.ok) { + if (res.status === 404) { + return undefined; + } + const text = await res.text(); + throw new Error(`Failed to load session: ${res.status} ${text}`); + } + + const data = (await res.json()) as InspectorClientSessionState; + + // Deserialize state (convert ISO strings back to Date objects) + return { + ...data, + fetchRequests: data.fetchRequests.map((req) => ({ + ...req, + timestamp: + typeof req.timestamp === "string" + ? new Date(req.timestamp) + : req.timestamp instanceof Date + ? req.timestamp + : new Date(req.timestamp), + })), + }; + } + + async deleteSession(sessionId: string): Promise { + const storeId = this.getStoreId(sessionId); + const url = `${this.baseUrl}/api/storage/${encodeURIComponent(storeId)}`; + + const headers: Record = {}; + if (this.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${this.authToken}`; + } + + const res = await this.fetchFn(url, { + method: "DELETE", + headers, + }); + + if (!res.ok && res.status !== 404) { + const text = await res.text(); + throw new Error(`Failed to delete session: ${res.status} ${text}`); + } + } +} diff --git a/shared/mcp/remote/types.ts b/shared/mcp/remote/types.ts new file mode 100644 index 000000000..34331e232 --- /dev/null +++ b/shared/mcp/remote/types.ts @@ -0,0 +1,63 @@ +/** + * Types for the remote transport protocol. + */ + +import type { MCPServerConfig, FetchRequestEntryBase } from "../types.js"; +import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; + +export interface RemoteConnectRequest { + /** MCP server config (stdio, sse, or streamable-http) */ + config: MCPServerConfig; + /** Optional OAuth tokens for Bearer authentication (for HTTP transports) */ + oauthTokens?: { + access_token: string; + token_type: string; + expires_in?: number; + refresh_token?: string; + }; +} + +export interface RemoteConnectResponse { + sessionId: string; +} + +export interface RemoteSendRequest { + message: JSONRPCMessage; + /** Optional, for associating response with request (e.g. streamable-http) */ + relatedRequestId?: string | number; +} + +export type RemoteEventType = + | "message" + | "fetch_request" + | "stdio_log" + | "transport_error"; + +export interface RemoteEventMessage { + type: "message"; + data: unknown; +} + +export interface RemoteEventFetchRequest { + type: "fetch_request"; + data: FetchRequestEntryBase; +} + +export interface RemoteEventStdioLog { + type: "stdio_log"; + data: { timestamp: string; message: string }; +} + +export interface RemoteEventTransportError { + type: "transport_error"; + data: { + error: string; + code?: string | number; + }; +} + +export type RemoteEvent = + | RemoteEventMessage + | RemoteEventFetchRequest + | RemoteEventStdioLog + | RemoteEventTransportError; diff --git a/shared/mcp/samplingCreateMessage.ts b/shared/mcp/samplingCreateMessage.ts new file mode 100644 index 000000000..c386cce1c --- /dev/null +++ b/shared/mcp/samplingCreateMessage.ts @@ -0,0 +1,68 @@ +import type { + CreateMessageRequest, + CreateMessageResult, +} from "@modelcontextprotocol/sdk/types.js"; +import { RELATED_TASK_META_KEY } from "@modelcontextprotocol/sdk/types.js"; + +/** + * Represents a pending sampling request from the server + */ +export class SamplingCreateMessage { + public readonly id: string; + public readonly timestamp: Date; + public readonly request: CreateMessageRequest; + public readonly taskId?: string; + private resolvePromise?: (result: CreateMessageResult) => void; + private rejectPromise?: (error: Error) => void; + + constructor( + request: CreateMessageRequest, + resolve: (result: CreateMessageResult) => void, + reject: (error: Error) => void, + private onRemove: (id: string) => void, + ) { + this.id = `sampling-${Date.now()}-${Math.random()}`; + this.timestamp = new Date(); + this.request = request; + // Extract taskId from request params metadata if present + const relatedTask = request.params?._meta?.[RELATED_TASK_META_KEY]; + this.taskId = relatedTask?.taskId; + this.resolvePromise = resolve; + this.rejectPromise = reject; + } + + /** + * Respond to the sampling request with a result + */ + async respond(result: CreateMessageResult): Promise { + if (!this.resolvePromise) { + throw new Error("Request already resolved or rejected"); + } + this.resolvePromise(result); + this.resolvePromise = undefined; + this.rejectPromise = undefined; + // Remove from pending list after responding + this.remove(); + } + + /** + * Reject the sampling request with an error + */ + async reject(error: Error): Promise { + if (!this.rejectPromise) { + throw new Error("Request already resolved or rejected"); + } + this.rejectPromise(error); + this.resolvePromise = undefined; + this.rejectPromise = undefined; + // Remove from pending list after rejecting + this.remove(); + } + + /** + * Remove this pending sample from the list + */ + remove(): void { + this.onRemove(this.id); + } +} diff --git a/shared/mcp/sessionStorage.ts b/shared/mcp/sessionStorage.ts new file mode 100644 index 000000000..ddd582c7a --- /dev/null +++ b/shared/mcp/sessionStorage.ts @@ -0,0 +1,46 @@ +import type { FetchRequestEntry } from "./types.js"; + +/** + * Serialized session state for InspectorClient. + * Contains data that should persist across page navigations (e.g., OAuth redirects). + */ +export interface InspectorClientSessionState { + /** Fetch requests tracked during the session */ + fetchRequests: FetchRequestEntry[]; + /** Timestamp when session was created */ + createdAt: number; + /** Timestamp when session was last updated */ + updatedAt: number; +} + +/** + * Storage interface for persisting InspectorClient session state. + * Used to maintain session data (e.g., fetch requests) across page navigations + * during OAuth flows. + */ +export interface InspectorClientStorage { + /** + * Save InspectorClient session state. + * @param sessionId - Unique session identifier (typically from OAuth state authId) + * @param state - Serialized InspectorClient state + */ + saveSession( + sessionId: string, + state: InspectorClientSessionState, + ): Promise; + + /** + * Load InspectorClient session state. + * @param sessionId - Unique session identifier + * @returns Session state or undefined if not found + */ + loadSession( + sessionId: string, + ): Promise; + + /** + * Delete session state (cleanup). + * @param sessionId - Unique session identifier + */ + deleteSession(sessionId: string): Promise; +} diff --git a/shared/mcp/types.ts b/shared/mcp/types.ts new file mode 100644 index 000000000..37ae649be --- /dev/null +++ b/shared/mcp/types.ts @@ -0,0 +1,211 @@ +// Stdio transport config +export interface StdioServerConfig { + type?: "stdio"; + command: string; + args?: string[]; + env?: Record; + cwd?: string; +} + +// SSE transport config +export interface SseServerConfig { + type: "sse"; + url: string; + headers?: Record; + eventSourceInit?: Record; + requestInit?: Record; +} + +// StreamableHTTP transport config +export interface StreamableHttpServerConfig { + type: "streamable-http"; + url: string; + headers?: Record; + requestInit?: Record; +} + +export type MCPServerConfig = + | StdioServerConfig + | SseServerConfig + | StreamableHttpServerConfig; + +export type ServerType = "stdio" | "sse" | "streamable-http"; + +export interface MCPConfig { + mcpServers: Record; +} + +export type ConnectionStatus = + | "disconnected" + | "connecting" + | "connected" + | "error"; + +export interface StderrLogEntry { + timestamp: Date; + message: string; +} + +import type { + ServerCapabilities, + Implementation, + JSONRPCRequest, + JSONRPCNotification, + JSONRPCResultResponse, + JSONRPCErrorResponse, +} from "@modelcontextprotocol/sdk/types.js"; + +export interface MessageEntry { + id: string; + timestamp: Date; + direction: "request" | "response" | "notification"; + message: + | JSONRPCRequest + | JSONRPCNotification + | JSONRPCResultResponse + | JSONRPCErrorResponse; + response?: JSONRPCResultResponse | JSONRPCErrorResponse; + duration?: number; // Time between request and response in ms +} + +export type FetchRequestCategory = "auth" | "transport"; + +export interface FetchRequestEntry { + id: string; + timestamp: Date; + method: string; + url: string; + requestHeaders: Record; + requestBody?: string; + responseStatus?: number; + responseStatusText?: string; + responseHeaders?: Record; + responseBody?: string; + duration?: number; // Time between request and response in ms + error?: string; + /** Distinguishes OAuth/auth fetches from MCP transport fetches */ + category: FetchRequestCategory; +} + +/** Entry shape from createFetchTracker before category is added by the caller */ +export type FetchRequestEntryBase = Omit; + +import type { OAuthClientProvider } from "@modelcontextprotocol/sdk/client/auth.js"; +import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; + +export interface CreateTransportOptions { + /** + * Optional fetch function. When provided, used as the base for transport HTTP requests + * (SSE, streamable-http). Enables proxy fetch in browser (CORS bypass). + */ + fetchFn?: typeof fetch; + + /** + * Optional callback to handle stderr logs from stdio transports + */ + onStderr?: (entry: StderrLogEntry) => void; + + /** + * Whether to pipe stderr for stdio transports (default: true for TUI, false for CLI) + */ + pipeStderr?: boolean; + + /** + * Optional callback to track HTTP fetch requests (for SSE and streamable-http transports). + * Receives entries without category; caller adds category when storing. + */ + onFetchRequest?: (entry: FetchRequestEntryBase) => void; + + /** + * Optional OAuth client provider for Bearer authentication (SSE, streamable-http). + * When set, the SDK injects tokens and handles 401 via the provider. + */ + authProvider?: OAuthClientProvider; +} + +export interface CreateTransportResult { + transport: Transport; +} + +/** + * Factory that creates a client transport for an MCP server configuration. + * Required by InspectorClient; caller provides the implementation for their + * environment (e.g. createTransport for Node, RemoteClientTransport factory for browser). + */ +export type CreateTransport = ( + config: MCPServerConfig, + options: CreateTransportOptions, +) => CreateTransportResult; + +export interface ServerState { + status: ConnectionStatus; + error: string | null; + capabilities?: ServerCapabilities; + serverInfo?: Implementation; + instructions?: string; + resources: any[]; + prompts: any[]; + tools: any[]; + stderrLogs: StderrLogEntry[]; +} + +import type { + ReadResourceResult, + GetPromptResult, + CallToolResult, +} from "@modelcontextprotocol/sdk/types.js"; +import type { JsonValue } from "../json/jsonUtils.js"; + +/** + * Represents a complete resource read invocation, including request parameters, + * response, and metadata. This object is returned from InspectorClient.readResource() + * and cached for later retrieval. + */ +export interface ResourceReadInvocation { + result: ReadResourceResult; // The full SDK response object + timestamp: Date; // When the call was made + uri: string; // The URI that was read (request parameter) + metadata?: Record; // Optional metadata that was passed +} + +/** + * Represents a complete resource template read invocation, including request parameters, + * response, and metadata. This object is returned from InspectorClient.readResourceFromTemplate() + * and cached for later retrieval. + */ +export interface ResourceTemplateReadInvocation { + uriTemplate: string; // The URI template string (unique ID) + expandedUri: string; // The expanded URI after template expansion + result: ReadResourceResult; // The full SDK response object + timestamp: Date; // When the call was made + params: Record; // The parameters used to expand the template (request parameters) + metadata?: Record; // Optional metadata that was passed +} + +/** + * Represents a complete prompt get invocation, including request parameters, + * response, and metadata. This object is returned from InspectorClient.getPrompt() + * and cached for later retrieval. + */ +export interface PromptGetInvocation { + result: GetPromptResult; // The full SDK response object + timestamp: Date; // When the call was made + name: string; // The prompt name (request parameter) + params?: Record; // The parameters used when fetching the prompt (request parameters) + metadata?: Record; // Optional metadata that was passed +} + +/** + * Represents a complete tool call invocation, including request parameters, + * response, and metadata. This object is returned from InspectorClient.callTool() + * and cached for later retrieval. + */ +export interface ToolCallInvocation { + toolName: string; // The tool that was called (request parameter) + params: Record; // The arguments passed to the tool (request parameters) + result: CallToolResult | null; // The full SDK response object (null on error) + timestamp: Date; // When the call was made + success: boolean; // true if call succeeded, false if it threw + error?: string; // Error message if success === false + metadata?: Record; // Optional metadata that was passed +} diff --git a/shared/package.json b/shared/package.json new file mode 100644 index 000000000..d50010d78 --- /dev/null +++ b/shared/package.json @@ -0,0 +1,52 @@ +{ + "name": "@modelcontextprotocol/inspector-shared", + "version": "0.18.0", + "private": true, + "type": "module", + "main": "./build/mcp/index.js", + "types": "./build/mcp/index.d.ts", + "exports": { + ".": "./build/mcp/index.js", + "./mcp/*": "./build/mcp/*", + "./auth": "./build/auth/index.js", + "./auth/*": "./build/auth/*", + "./react/*": "./build/react/*", + "./test/*": "./build/test/*", + "./json/*": "./build/json/*", + "./auth/node": "./build/auth/node/index.js", + "./auth/node/*": "./build/auth/node/*", + "./mcp/node": "./build/mcp/node/index.js", + "./mcp/node/*": "./build/mcp/node/*", + "./auth/browser": "./build/auth/browser/index.js", + "./auth/browser/*": "./build/auth/browser/*", + "./mcp/remote": "./build/mcp/remote/index.js", + "./mcp/remote/*": "./build/mcp/remote/*", + "./mcp/remote/node": "./build/mcp/remote/node/index.js", + "./mcp/remote/node/*": "./build/mcp/remote/node/*" + }, + "files": [ + "build" + ], + "scripts": { + "build": "tsc", + "test": "vitest run", + "test:watch": "vitest" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.25.2", + "pino": "^9.6.0", + "react": "^18.3.1" + }, + "dependencies": { + "hono": "^4.6.0", + "zustand": "^5.0.10" + }, + "devDependencies": { + "@hono/node-server": "^1.19.0", + "@modelcontextprotocol/sdk": "^1.25.2", + "@types/react": "^18.3.23", + "pino": "^9.6.0", + "typescript": "^5.4.2", + "vitest": "^4.0.17" + } +} diff --git a/shared/react/useInspectorClient.ts b/shared/react/useInspectorClient.ts new file mode 100644 index 000000000..34149f220 --- /dev/null +++ b/shared/react/useInspectorClient.ts @@ -0,0 +1,273 @@ +import { useState, useEffect, useCallback, useRef } from "react"; +import { InspectorClient } from "../mcp/index.js"; +import type { TypedEvent } from "../mcp/inspectorClientEventTarget.js"; +import type { + ConnectionStatus, + StderrLogEntry, + MessageEntry, + FetchRequestEntry, +} from "../mcp/index.js"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import type { + ServerCapabilities, + Implementation, + Tool, + ResourceReference, + PromptReference, +} from "@modelcontextprotocol/sdk/types.js"; + +export interface UseInspectorClientResult { + status: ConnectionStatus; + messages: MessageEntry[]; + stderrLogs: StderrLogEntry[]; + fetchRequests: FetchRequestEntry[]; + tools: any[]; + resources: any[]; + resourceTemplates: any[]; + prompts: any[]; + capabilities?: ServerCapabilities; + serverInfo?: Implementation; + instructions?: string; + client: Client | null; + connect: () => Promise; + disconnect: () => Promise; +} + +/** + * React hook that subscribes to InspectorClient events and provides reactive state + */ +export function useInspectorClient( + inspectorClient: InspectorClient | null, +): UseInspectorClientResult { + const [status, setStatus] = useState( + inspectorClient?.getStatus() ?? "disconnected", + ); + const [messages, setMessages] = useState( + inspectorClient?.getMessages() ?? [], + ); + const [stderrLogs, setStderrLogs] = useState( + inspectorClient?.getStderrLogs() ?? [], + ); + const [fetchRequests, setFetchRequests] = useState( + inspectorClient?.getFetchRequests() ?? [], + ); + const [tools, setTools] = useState(inspectorClient?.getTools() ?? []); + const [resources, setResources] = useState( + inspectorClient?.getResources() ?? [], + ); + const [resourceTemplates, setResourceTemplates] = useState( + inspectorClient?.getResourceTemplates() ?? [], + ); + const [prompts, setPrompts] = useState( + inspectorClient?.getPrompts() ?? [], + ); + const [capabilities, setCapabilities] = useState< + ServerCapabilities | undefined + >(inspectorClient?.getCapabilities()); + const [serverInfo, setServerInfo] = useState( + inspectorClient?.getServerInfo(), + ); + const [instructions, setInstructions] = useState( + inspectorClient?.getInstructions(), + ); + + // Use refs to track previous serialized values to prevent infinite loops + // InspectorClient.getMessages()/getStderrLogs()/getFetchRequests() return new arrays + // each time, so we need to compare content, not references + const previousMessagesRef = useRef("[]"); + const previousStderrLogsRef = useRef("[]"); + const previousFetchRequestsRef = useRef("[]"); + + // Subscribe to all InspectorClient events + useEffect(() => { + if (!inspectorClient) { + setStatus("disconnected"); + setMessages([]); + setStderrLogs([]); + setFetchRequests([]); + setTools([]); + setResources([]); + setResourceTemplates([]); + setPrompts([]); + setCapabilities(undefined); + setServerInfo(undefined); + setInstructions(undefined); + previousMessagesRef.current = "[]"; + previousStderrLogsRef.current = "[]"; + previousFetchRequestsRef.current = "[]"; + return; + } + + // Initial state + setStatus(inspectorClient.getStatus()); + const initialMessages = inspectorClient.getMessages(); + const initialStderrLogs = inspectorClient.getStderrLogs(); + const initialFetchRequests = inspectorClient.getFetchRequests(); + setMessages(initialMessages); + setStderrLogs(initialStderrLogs); + setFetchRequests(initialFetchRequests); + previousMessagesRef.current = JSON.stringify(initialMessages); + previousStderrLogsRef.current = JSON.stringify(initialStderrLogs); + previousFetchRequestsRef.current = JSON.stringify(initialFetchRequests); + setTools(inspectorClient.getTools()); + setResources(inspectorClient.getResources()); + setResourceTemplates(inspectorClient.getResourceTemplates()); + setPrompts(inspectorClient.getPrompts()); + setCapabilities(inspectorClient.getCapabilities()); + setServerInfo(inspectorClient.getServerInfo()); + setInstructions(inspectorClient.getInstructions()); + + // Event handlers - using type-safe event listeners + const onStatusChange = (event: TypedEvent<"statusChange">) => { + setStatus(event.detail); + }; + + const onMessagesChange = () => { + // messagesChange is a void event, so we fetch + // Compare by serializing to avoid infinite loops from reference changes + const newMessages = inspectorClient.getMessages(); + const serialized = JSON.stringify(newMessages); + if (serialized !== previousMessagesRef.current) { + setMessages(newMessages); + previousMessagesRef.current = serialized; + } + }; + + const onStderrLogsChange = () => { + // stderrLogsChange is a void event, so we fetch + // Compare by serializing to avoid infinite loops from reference changes + const newStderrLogs = inspectorClient.getStderrLogs(); + const serialized = JSON.stringify(newStderrLogs); + if (serialized !== previousStderrLogsRef.current) { + setStderrLogs(newStderrLogs); + previousStderrLogsRef.current = serialized; + } + }; + + const onFetchRequestsChange = () => { + // fetchRequestsChange is a void event, so we fetch + // Compare by serializing to avoid infinite loops from reference changes + const newFetchRequests = inspectorClient.getFetchRequests(); + const serialized = JSON.stringify(newFetchRequests); + if (serialized !== previousFetchRequestsRef.current) { + setFetchRequests(newFetchRequests); + previousFetchRequestsRef.current = serialized; + } + }; + + const onToolsChange = (event: TypedEvent<"toolsChange">) => { + setTools(event.detail); + }; + + const onResourcesChange = (event: TypedEvent<"resourcesChange">) => { + setResources(event.detail); + }; + + const onResourceTemplatesChange = ( + event: TypedEvent<"resourceTemplatesChange">, + ) => { + setResourceTemplates(event.detail); + }; + + const onPromptsChange = (event: TypedEvent<"promptsChange">) => { + setPrompts(event.detail); + }; + + const onCapabilitiesChange = (event: TypedEvent<"capabilitiesChange">) => { + setCapabilities(event.detail); + }; + + const onServerInfoChange = (event: TypedEvent<"serverInfoChange">) => { + setServerInfo(event.detail); + }; + + const onInstructionsChange = (event: TypedEvent<"instructionsChange">) => { + setInstructions(event.detail); + }; + + // Subscribe to events + inspectorClient.addEventListener("statusChange", onStatusChange); + inspectorClient.addEventListener("messagesChange", onMessagesChange); + inspectorClient.addEventListener("stderrLogsChange", onStderrLogsChange); + inspectorClient.addEventListener( + "fetchRequestsChange", + onFetchRequestsChange, + ); + inspectorClient.addEventListener("toolsChange", onToolsChange); + inspectorClient.addEventListener("resourcesChange", onResourcesChange); + inspectorClient.addEventListener( + "resourceTemplatesChange", + onResourceTemplatesChange, + ); + inspectorClient.addEventListener("promptsChange", onPromptsChange); + inspectorClient.addEventListener( + "capabilitiesChange", + onCapabilitiesChange, + ); + inspectorClient.addEventListener("serverInfoChange", onServerInfoChange); + inspectorClient.addEventListener( + "instructionsChange", + onInstructionsChange, + ); + + // Cleanup + return () => { + inspectorClient.removeEventListener("statusChange", onStatusChange); + inspectorClient.removeEventListener("messagesChange", onMessagesChange); + inspectorClient.removeEventListener( + "stderrLogsChange", + onStderrLogsChange, + ); + inspectorClient.removeEventListener( + "fetchRequestsChange", + onFetchRequestsChange, + ); + inspectorClient.removeEventListener("toolsChange", onToolsChange); + inspectorClient.removeEventListener("resourcesChange", onResourcesChange); + inspectorClient.removeEventListener( + "resourceTemplatesChange", + onResourceTemplatesChange, + ); + inspectorClient.removeEventListener("promptsChange", onPromptsChange); + inspectorClient.removeEventListener( + "capabilitiesChange", + onCapabilitiesChange, + ); + inspectorClient.removeEventListener( + "serverInfoChange", + onServerInfoChange, + ); + inspectorClient.removeEventListener( + "instructionsChange", + onInstructionsChange, + ); + }; + }, [inspectorClient]); + + const connect = useCallback(async () => { + if (!inspectorClient) return; + await inspectorClient.connect(); + }, [inspectorClient]); + + const disconnect = useCallback(async () => { + if (!inspectorClient) return; + await inspectorClient.disconnect(); + }, [inspectorClient]); + + return { + status, + messages, + stderrLogs, + fetchRequests, + tools, + resources, + resourceTemplates, + prompts, + capabilities, + serverInfo, + instructions, + client: inspectorClient?.getClient() ?? null, + connect, + disconnect, + }; +} diff --git a/shared/storage/adapters/file-storage.ts b/shared/storage/adapters/file-storage.ts new file mode 100644 index 000000000..94179cbae --- /dev/null +++ b/shared/storage/adapters/file-storage.ts @@ -0,0 +1,56 @@ +/** + * File-based storage adapter for Zustand persist middleware. + * Stores entire store state as JSON in a single file. + */ + +import { createJSONStorage } from "zustand/middleware"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; + +export interface FileStorageAdapterOptions { + /** Full path to the storage file */ + filePath: string; +} + +/** + * Creates a Zustand storage adapter that reads/writes from a file. + * Conforms to Zustand's StateStorage interface. + */ +export function createFileStorageAdapter( + options: FileStorageAdapterOptions, +): ReturnType { + return createJSONStorage(() => ({ + getItem: async (name: string) => { + try { + const data = await fs.readFile(options.filePath, "utf-8"); + return data; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + return null; + } + throw error; + } + }, + setItem: async (name: string, value: string) => { + // Ensure directory exists + const dir = path.dirname(options.filePath); + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(options.filePath, value, "utf-8"); + // Set restrictive permissions (600) for security + try { + await fs.chmod(options.filePath, 0o600); + } catch { + // Ignore chmod errors (may fail on some systems) + } + }, + removeItem: async (name: string) => { + try { + await fs.unlink(options.filePath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw error; + } + } + }, + })); +} diff --git a/shared/storage/adapters/index.ts b/shared/storage/adapters/index.ts new file mode 100644 index 000000000..214ba563d --- /dev/null +++ b/shared/storage/adapters/index.ts @@ -0,0 +1,10 @@ +/** + * Storage adapters for Zustand persist middleware. + * Provides adapters for file, remote HTTP, and browser storage. + */ + +export { createFileStorageAdapter } from "./file-storage.js"; +export type { FileStorageAdapterOptions } from "./file-storage.js"; + +export { createRemoteStorageAdapter } from "./remote-storage.js"; +export type { RemoteStorageAdapterOptions } from "./remote-storage.js"; diff --git a/shared/storage/adapters/remote-storage.ts b/shared/storage/adapters/remote-storage.ts new file mode 100644 index 000000000..222f5ccb1 --- /dev/null +++ b/shared/storage/adapters/remote-storage.ts @@ -0,0 +1,94 @@ +/** + * Remote HTTP storage adapter for Zustand persist middleware. + * Stores entire store state via HTTP API (GET/POST/DELETE /api/storage/:storeId). + */ + +import { createJSONStorage } from "zustand/middleware"; + +export interface RemoteStorageAdapterOptions { + /** Base URL of the remote server (e.g. http://localhost:3000) */ + baseUrl: string; + /** Store ID (e.g. "oauth", "inspector-settings") */ + storeId: string; + /** Optional auth token for x-mcp-remote-auth header */ + authToken?: string; + /** Fetch function to use (default: globalThis.fetch) */ + fetchFn?: typeof fetch; +} + +/** + * Creates a Zustand storage adapter that reads/writes via HTTP API. + * Conforms to Zustand's StateStorage interface. + */ +export function createRemoteStorageAdapter( + options: RemoteStorageAdapterOptions, +): ReturnType { + const baseUrl = options.baseUrl.replace(/\/$/, ""); + const fetchFn = options.fetchFn ?? globalThis.fetch; + + return createJSONStorage(() => ({ + getItem: async (name: string) => { + const headers: Record = {}; + if (options.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`; + } + + const res = await fetchFn(`${baseUrl}/api/storage/${options.storeId}`, { + method: "GET", + headers, + }); + + if (!res.ok) { + if (res.status === 404) { + return null; + } + throw new Error(`Failed to read store: ${res.status}`); + } + + const store = await res.json(); + // Zustand stores: { state: {...}, version: number } + // API returns the stored blob. If empty, Zustand hasn't initialized yet. + if (Object.keys(store).length === 0) { + return null; // Empty store means not initialized yet + } + // Return the stored Zustand format as string + return JSON.stringify(store); + }, + setItem: async (name: string, value: string) => { + const headers: Record = { + "Content-Type": "application/json", + }; + if (options.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`; + } + + // Zustand gives us the full persisted format as a string + // Store it as-is (the API treats it as an opaque blob) + const res = await fetchFn(`${baseUrl}/api/storage/${options.storeId}`, { + method: "POST", + headers, + body: value, // Already a JSON string from Zustand + }); + + if (!res.ok) { + throw new Error(`Failed to write store: ${res.status}`); + } + }, + removeItem: async (name: string) => { + const headers: Record = {}; + if (options.authToken) { + headers["x-mcp-remote-auth"] = `Bearer ${options.authToken}`; + } + + const res = await fetchFn(`${baseUrl}/api/storage/${options.storeId}`, { + method: "DELETE", + headers, + }); + + // 404 is fine (already deleted), but other errors should propagate + if (!res.ok && res.status !== 404) { + throw new Error(`Failed to delete store: ${res.status}`); + } + }, + })); +} diff --git a/shared/test/composable-test-server.ts b/shared/test/composable-test-server.ts new file mode 100644 index 000000000..5f4fad642 --- /dev/null +++ b/shared/test/composable-test-server.ts @@ -0,0 +1,949 @@ +/** + * Composable Test Server + * + * Provides types and functions for creating MCP test servers from configuration. + * This allows composing MCP test servers with different capabilities, tools, resources, and prompts. + */ + +import { + McpServer, + ResourceTemplate as SdkResourceTemplate, +} from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + Implementation, + Tool, + Resource, + ResourceTemplate, + Prompt, +} from "@modelcontextprotocol/sdk/types.js"; +import { + InMemoryTaskStore, + InMemoryTaskMessageQueue, +} from "@modelcontextprotocol/sdk/experimental/tasks/stores/in-memory.js"; +import type { + TaskStore, + TaskMessageQueue, + ToolTaskHandler, +} from "@modelcontextprotocol/sdk/experimental/tasks/interfaces.js"; +import type { + RegisteredTool, + RegisteredResource, + RegisteredPrompt, + RegisteredResourceTemplate, +} from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js"; +import type { + ServerRequest, + ServerNotification, +} from "@modelcontextprotocol/sdk/types.js"; +import { + SetLevelRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + ListToolsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ListPromptsRequestSchema, + type ListToolsResult, + type ListResourcesResult, + type ListResourceTemplatesResult, + type ListPromptsResult, +} from "@modelcontextprotocol/sdk/types.js"; +import { + ZodRawShapeCompat, + getObjectShape, + getSchemaDescription, + isSchemaOptional, + normalizeObjectSchema, +} from "@modelcontextprotocol/sdk/server/zod-compat.js"; +import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js"; +import { + completable, + isCompletable, +} from "@modelcontextprotocol/sdk/server/completable.js"; +import type { PromptArgument } from "@modelcontextprotocol/sdk/types.js"; + +// Empty object JSON schema constant (from SDK's mcp.js) +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {}, +} as const; + +type ToolInputSchema = ZodRawShapeCompat; +type PromptArgsSchema = ZodRawShapeCompat; + +interface ServerState { + registeredTools: Map; // Keyed by name + registeredResources: Map; // Keyed by URI + registeredPrompts: Map; // Keyed by name + registeredResourceTemplates: Map; // Keyed by uriTemplate + listChangedConfig: { + tools?: boolean; + resources?: boolean; + prompts?: boolean; + }; + resourceSubscriptions: Set; // Set of subscribed resource URIs +} + +/** + * Context object passed to tool handlers containing both server and state + */ +export interface TestServerContext { + server: McpServer; + state: ServerState; + serverControl?: { isClosing(): boolean }; +} + +export interface ToolDefinition { + name: string; + description: string; + inputSchema?: ToolInputSchema; + handler: ( + params: Record, + context?: TestServerContext, + extra?: RequestHandlerExtra, + ) => Promise; +} + +export interface TaskToolDefinition { + name: string; + description: string; + inputSchema?: ToolInputSchema; + execution?: { taskSupport: "required" | "optional" }; + handler: ToolTaskHandler; +} + +export interface ResourceDefinition { + uri: string; + name: string; + description?: string; + mimeType?: string; + text?: string; +} + +export interface PromptDefinition { + name: string; + description?: string; + promptString: string; // The prompt text with optional {argName} placeholders + argsSchema?: PromptArgsSchema; // Can include completable() schemas + // Optional completion callbacks keyed by argument name + // This is a convenience - users can also use completable() directly in argsSchema + completions?: Record< + string, + ( + argumentValue: string, + context?: Record, + ) => Promise | string[] + >; +} + +export interface ResourceTemplateDefinition { + name: string; + uriTemplate: string; // URI template with {variable} placeholders (RFC 6570) + description?: string; + inputSchema?: ZodRawShapeCompat; // Schema for template variables + handler: ( + uri: URL, + params: Record, + context?: TestServerContext, + extra?: RequestHandlerExtra, + ) => Promise<{ + contents: Array<{ uri: string; mimeType?: string; text: string }>; + }>; + // Optional callbacks for resource template operations + // list: Can return either: + // - string[] (convenience - will be converted to ListResourcesResult with uri and name) + // - ListResourcesResult (full control - includes uri, name, description, mimeType, etc.) + list?: + | (() => Promise | string[]) + | (() => Promise | ListResourcesResult); + // complete: Map of variable names to completion callbacks + // OR a single callback function that will be used for all variables + complete?: + | Record< + string, + ( + value: string, + context?: Record, + ) => Promise | string[] + > + | (( + argumentName: string, + argumentValue: string, + context?: Record, + ) => Promise | string[]); +} + +/** + * Configuration for composing an MCP server + */ +export interface ServerConfig { + serverInfo: Implementation; // Server metadata (name, version, etc.) - required + tools?: (ToolDefinition | TaskToolDefinition)[]; // Tools to register (optional, empty array means no tools, but tools capability is still advertised) + resources?: ResourceDefinition[]; // Resources to register (optional, empty array means no resources, but resources capability is still advertised) + resourceTemplates?: ResourceTemplateDefinition[]; // Resource templates to register (optional, empty array means no templates, but resources capability is still advertised) + prompts?: PromptDefinition[]; // Prompts to register (optional, empty array means no prompts, but prompts capability is still advertised) + logging?: boolean; // Whether to advertise logging capability (default: false) + onLogLevelSet?: (level: string) => void; // Optional callback when log level is set (for testing) + onRegisterResource?: (resource: ResourceDefinition) => + | (() => Promise<{ + contents: Array<{ uri: string; mimeType?: string; text: string }>; + }>) + | undefined; // Optional callback to customize resource handler during registration + serverType?: "sse" | "streamable-http"; // Transport type (default: "streamable-http") + port?: number; // Port to use (optional, will find available port if not specified) + /** + * Whether to advertise listChanged capability for each list type + * If enabled, modification tools will send list_changed notifications + */ + listChanged?: { + tools?: boolean; // default: false + resources?: boolean; // default: false + prompts?: boolean; // default: false + }; + /** + * Whether to advertise resource subscriptions capability + * If enabled, server will advertise resources.subscribe capability + */ + subscriptions?: boolean; // default: false + /** + * Maximum page size for pagination (optional, undefined means no pagination) + * When set, custom list handlers will paginate results using this page size + */ + maxPageSize?: { + tools?: number; + resources?: number; + resourceTemplates?: number; + prompts?: number; + }; + /** + * Whether to advertise tasks capability + * If enabled, server will advertise tasks capability with list and cancel support + */ + tasks?: { + list?: boolean; // default: true + cancel?: boolean; // default: true + }; + /** + * Task store implementation (optional, defaults to InMemoryTaskStore) + * Only used if tasks capability is enabled + */ + taskStore?: TaskStore; + /** + * Task message queue implementation (optional, defaults to InMemoryTaskMessageQueue) + * Only used if tasks capability is enabled + */ + taskMessageQueue?: TaskMessageQueue; + /** + * OAuth 2.1 configuration for test server + * If enabled, server will act as an OAuth authorization server + */ + oauth?: { + /** + * Whether OAuth is enabled for this test server + */ + enabled: boolean; + + /** + * OAuth authorization server issuer URL + * Used for metadata endpoints and token issuance + * If not provided, defaults to the test server's base URL + */ + issuerUrl?: URL; + + /** + * List of scopes supported by this authorization server + * Defaults to ["mcp"] if not provided + */ + scopesSupported?: string[]; + + /** + * If true, MCP endpoints require valid Bearer token + * Returns 401 Unauthorized if token is missing or invalid + */ + requireAuth?: boolean; + + /** + * Static/preregistered clients for testing + * These clients are pre-configured and don't require DCR + */ + staticClients?: Array<{ + clientId: string; + clientSecret?: string; + redirectUris?: string[]; + }>; + + /** + * Whether to support Dynamic Client Registration (DCR) + * If true, exposes /register endpoint for client registration + */ + supportDCR?: boolean; + + /** + * Whether to support CIMD (Client ID Metadata Documents) + * If true, server will fetch client metadata from clientMetadataUrl + */ + supportCIMD?: boolean; + + /** + * Token expiration time in seconds (default: 3600) + */ + tokenExpirationSeconds?: number; + + /** + * Whether to support refresh tokens (default: true) + */ + supportRefreshTokens?: boolean; + }; + /** + * Optional server control for orderly shutdown (test HTTP server). + * When present, progress-sending tools check isClosing() before sending and skip/break if closing. + */ + serverControl?: { isClosing(): boolean }; +} + +/** + * Create and configure an McpServer instance from ServerConfig + * This centralizes the setup logic shared between HTTP and stdio test servers + */ +export function createMcpServer(config: ServerConfig): McpServer { + // Build capabilities based on config + const capabilities: { + tools?: {}; + resources?: { subscribe?: boolean }; + prompts?: {}; + logging?: {}; + tasks?: { + list?: {}; + cancel?: {}; + requests?: { tools?: { call?: {} } }; + }; + } = {}; + + if (config.tools !== undefined) { + capabilities.tools = {}; + } + if ( + config.resources !== undefined || + config.resourceTemplates !== undefined + ) { + capabilities.resources = {}; + // Add subscribe capability if subscriptions are enabled + if (config.subscriptions === true) { + capabilities.resources.subscribe = true; + } + } + if (config.prompts !== undefined) { + capabilities.prompts = {}; + } + if (config.logging === true) { + capabilities.logging = {}; + } + if (config.tasks !== undefined) { + capabilities.tasks = { + list: config.tasks.list !== false ? {} : undefined, + cancel: config.tasks.cancel !== false ? {} : undefined, + requests: { tools: { call: {} } }, + }; + // Remove undefined values + if (capabilities.tasks.list === undefined) { + delete capabilities.tasks.list; + } + if (capabilities.tasks.cancel === undefined) { + delete capabilities.tasks.cancel; + } + } + + // Create task store and message queue if tasks are enabled + const taskStore = + config.tasks !== undefined + ? config.taskStore || new InMemoryTaskStore() + : undefined; + const taskMessageQueue = + config.tasks !== undefined + ? config.taskMessageQueue || new InMemoryTaskMessageQueue() + : undefined; + + // Create the server with capabilities and task stores + const mcpServer = new McpServer(config.serverInfo, { + capabilities, + taskStore, + taskMessageQueue, + }); + + // Create state (this is really session state, which is what we'll call it if we implement sessions at some point) + const state: ServerState = { + registeredTools: new Map(), // Keyed by name + registeredResources: new Map(), // Keyed by URI + registeredPrompts: new Map(), // Keyed by name + registeredResourceTemplates: new Map(), // Keyed by uriTemplate + listChangedConfig: config.listChanged || {}, + resourceSubscriptions: new Set(), // Track subscribed resource URIs + }; + + // Create context object + const context: TestServerContext = { + server: mcpServer, + state, + ...(config.serverControl && { serverControl: config.serverControl }), + }; + + // Set up logging handler if logging is enabled + if (config.logging === true) { + mcpServer.server.setRequestHandler( + SetLevelRequestSchema, + async (request) => { + // Call optional callback if provided (for testing) + if (config.onLogLevelSet) { + config.onLogLevelSet(request.params.level); + } + // Return empty result as per MCP spec + return {}; + }, + ); + } + + // Set up resource subscription handlers if subscriptions are enabled + if (config.subscriptions === true) { + mcpServer.server.setRequestHandler( + SubscribeRequestSchema, + async (request) => { + // Track subscription in state (accessible via closure) + const uri = request.params.uri; + state.resourceSubscriptions.add(uri); + return {}; + }, + ); + + mcpServer.server.setRequestHandler( + UnsubscribeRequestSchema, + async (request) => { + // Remove subscription from state (accessible via closure) + const uri = request.params.uri; + state.resourceSubscriptions.delete(uri); + return {}; + }, + ); + } + + // Type guard to check if a tool is a task tool + function isTaskTool( + tool: ToolDefinition | TaskToolDefinition, + ): tool is TaskToolDefinition { + return ( + "handler" in tool && + typeof tool.handler === "object" && + tool.handler !== null && + "createTask" in tool.handler + ); + } + + // Set up tools + if (config.tools && config.tools.length > 0) { + for (const tool of config.tools) { + if (isTaskTool(tool)) { + // Register task-based tool + // registerToolTask has two overloads: one with inputSchema (required) and one without + const registered = tool.inputSchema + ? mcpServer.experimental.tasks.registerToolTask( + tool.name, + { + description: tool.description, + inputSchema: tool.inputSchema, + execution: tool.execution, + }, + tool.handler, + ) + : mcpServer.experimental.tasks.registerToolTask( + tool.name, + { + description: tool.description, + execution: tool.execution, + }, + tool.handler, + ); + state.registeredTools.set(tool.name, registered); + } else { + // Register regular tool + const registered = mcpServer.registerTool( + tool.name, + { + description: tool.description, + inputSchema: tool.inputSchema, + }, + async (args, extra) => { + const result = await tool.handler( + args as Record, + context, + extra, + ); + // Handle different return types from tool handlers + // If handler returns content array directly (like get-annotated-message), use it + if (result && Array.isArray(result.content)) { + return { content: result.content }; + } + // If handler returns message (like echo), format it + if (result && typeof result.message === "string") { + return { + content: [ + { + type: "text", + text: result.message, + }, + ], + }; + } + // Otherwise, stringify the result + return { + content: [ + { + type: "text", + text: JSON.stringify(result), + }, + ], + }; + }, + ); + state.registeredTools.set(tool.name, registered); + } + } + } + + // Set up resources + if (config.resources && config.resources.length > 0) { + for (const resource of config.resources) { + // Check if there's a custom handler from the callback + const customHandler = config.onRegisterResource + ? config.onRegisterResource(resource) + : undefined; + + const registered = mcpServer.registerResource( + resource.name, + resource.uri, + { + description: resource.description, + mimeType: resource.mimeType, + }, + customHandler || + (async () => { + return { + contents: [ + { + uri: resource.uri, + mimeType: resource.mimeType || "text/plain", + text: resource.text ?? "", + }, + ], + }; + }), + ); + state.registeredResources.set(resource.uri, registered); + } + } + + // Set up resource templates + if (config.resourceTemplates && config.resourceTemplates.length > 0) { + for (const template of config.resourceTemplates) { + // ResourceTemplate is a class - create an instance with the URI template string and callbacks + // Convert list callback: SDK expects ListResourcesResult + // We support both string[] (convenience) and ListResourcesResult (full control) + const listCallback = template.list + ? async () => { + const result = template.list!(); + const resolved = await result; + // Check if it's already a ListResourcesResult (has resources array) + if ( + resolved && + typeof resolved === "object" && + "resources" in resolved + ) { + return resolved as ListResourcesResult; + } + // Otherwise, it's string[] - convert to ListResourcesResult + const uriArray = resolved as string[]; + return { + resources: uriArray.map((uri) => ({ + uri, + name: uri, // Use URI as name if not provided + })), + }; + } + : undefined; + + // Convert complete callback: SDK expects {[variable: string]: callback} + // We support either a map or a single function + let completeCallbacks: + | { + [variable: string]: ( + value: string, + context?: { arguments?: Record }, + ) => Promise | string[]; + } + | undefined = undefined; + + if (template.complete) { + if (typeof template.complete === "function") { + // Single function - extract variable names from URI template and use for all + // Parse URI template to find variables (e.g., {file} from "file://{file}") + const variableMatches = template.uriTemplate.match(/\{([^}]+)\}/g); + if (variableMatches) { + completeCallbacks = {}; + const completeFn = template.complete; + for (const match of variableMatches) { + const variableName = match.slice(1, -1); // Remove { and } + completeCallbacks[variableName] = async ( + value: string, + context?: { arguments?: Record }, + ) => { + const result = completeFn( + variableName, + value, + context?.arguments, + ); + return Array.isArray(result) ? result : await result; + }; + } + } + } else { + // Map of variable names to callbacks + completeCallbacks = {}; + for (const [variableName, callback] of Object.entries( + template.complete, + )) { + completeCallbacks[variableName] = async ( + value: string, + context?: { arguments?: Record }, + ) => { + const result = callback(value, context?.arguments); + return Array.isArray(result) ? result : await result; + }; + } + } + } + + const resourceTemplate = new SdkResourceTemplate(template.uriTemplate, { + list: listCallback, + complete: completeCallbacks, + }); + + const registered = mcpServer.registerResource( + template.name, + resourceTemplate, + { + description: template.description, + }, + async (uri: URL, variables: Record, extra) => { + const result = await template.handler(uri, variables, context, extra); + return result; + }, + ); + state.registeredResourceTemplates.set(template.uriTemplate, registered); + } + } + + // Set up prompts + if (config.prompts && config.prompts.length > 0) { + for (const prompt of config.prompts) { + // Build argsSchema with completion support if provided + let argsSchema = prompt.argsSchema; + + // If completions callbacks are provided, wrap the corresponding schemas + if (prompt.completions && argsSchema) { + const enhancedSchema: Record = { ...argsSchema }; + for (const [argName, completeCallback] of Object.entries( + prompt.completions, + )) { + if (enhancedSchema[argName]) { + // Wrap with completable only if not already wrapped (avoids "Cannot redefine property" when createMcpServer is called multiple times with shared config) + if (!isCompletable(enhancedSchema[argName])) { + enhancedSchema[argName] = completable( + enhancedSchema[argName], + async ( + value: any, + context?: { arguments?: Record }, + ) => { + const result = completeCallback( + String(value), + context?.arguments, + ); + return Array.isArray(result) ? result : await result; + }, + ); + } + } + } + argsSchema = enhancedSchema; + } + + const registered = mcpServer.registerPrompt( + prompt.name, + { + description: prompt.description, + argsSchema: argsSchema, + }, + async (args) => { + let text = prompt.promptString; + + // If args are provided, substitute them into the prompt string + // Replace {argName} with the actual value + if (args && typeof args === "object") { + for (const [key, value] of Object.entries(args)) { + const placeholder = `{${key}}`; + text = text.replace( + new RegExp(placeholder.replace(/[{}]/g, "\\$&"), "g"), + String(value), + ); + } + } + + return { + messages: [ + { + role: "user", + content: { + type: "text", + text, + }, + }, + ], + }; + }, + ); + state.registeredPrompts.set(prompt.name, registered); + } + } + + // Set up pagination handlers if maxPageSize is configured + const maxPageSize = config.maxPageSize || {}; + + // Tools pagination + if (capabilities.tools && maxPageSize.tools !== undefined) { + mcpServer.server.setRequestHandler( + ListToolsRequestSchema, + async (request) => { + const cursor = request.params?.cursor; + const pageSize = maxPageSize.tools!; + + // Convert registered tools to Tool format using the same logic as the SDK (mcp.js lines 67-95) + const allTools: Tool[] = []; + for (const [name, registered] of state.registeredTools.entries()) { + if (registered.enabled) { + // Match SDK's approach exactly (mcp.js lines 71-95) + const toolDefinition: any = { + name, + title: registered.title, + description: registered.description, + inputSchema: (() => { + const obj = normalizeObjectSchema(registered.inputSchema); + return obj + ? toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: "input", + }) + : EMPTY_OBJECT_JSON_SCHEMA; + })(), + annotations: registered.annotations, + execution: registered.execution, + _meta: registered._meta, + }; + + if (registered.outputSchema) { + const obj = normalizeObjectSchema(registered.outputSchema); + if (obj) { + toolDefinition.outputSchema = toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: "output", + }); + } + } + + allTools.push(toolDefinition as Tool); + } + } + + const startIndex = cursor ? parseInt(cursor, 10) : 0; + const endIndex = startIndex + pageSize; + const page = allTools.slice(startIndex, endIndex); + const nextCursor = + endIndex < allTools.length ? endIndex.toString() : undefined; + + return { + tools: page, + nextCursor, + } as ListToolsResult; + }, + ); + } + + // Resources pagination + if (capabilities.resources && maxPageSize.resources !== undefined) { + mcpServer.server.setRequestHandler( + ListResourcesRequestSchema, + async (request, extra) => { + const cursor = request.params?.cursor; + const pageSize = maxPageSize.resources!; + + // Collect all resources (static + from templates) + const allResources: Resource[] = []; + + // Add static resources from registered resources + for (const [uri, registered] of state.registeredResources.entries()) { + if (registered.enabled) { + allResources.push({ + uri, + name: registered.name, + title: registered.title, + description: registered.metadata?.description, + mimeType: registered.metadata?.mimeType, + icons: registered.metadata?.icons, + } as Resource); + } + } + + // Add resources from templates (if list callback exists) + for (const template of state.registeredResourceTemplates.values()) { + if (template.enabled && template.resourceTemplate.listCallback) { + try { + const result = + await template.resourceTemplate.listCallback(extra); + for (const resource of result.resources) { + allResources.push({ + ...resource, + // Merge template metadata if resource doesn't have it + name: resource.name, + description: + resource.description || template.metadata?.description, + mimeType: resource.mimeType || template.metadata?.mimeType, + icons: resource.icons || template.metadata?.icons, + } as Resource); + } + } catch (error) { + // Ignore errors from list callbacks + } + } + } + + const startIndex = cursor ? parseInt(cursor, 10) : 0; + const endIndex = startIndex + pageSize; + const page = allResources.slice(startIndex, endIndex); + const nextCursor = + endIndex < allResources.length ? endIndex.toString() : undefined; + + return { + resources: page, + nextCursor, + } as ListResourcesResult; + }, + ); + } + + // Resource templates pagination + if (capabilities.resources && maxPageSize.resourceTemplates !== undefined) { + mcpServer.server.setRequestHandler( + ListResourceTemplatesRequestSchema, + async (request) => { + const cursor = request.params?.cursor; + const pageSize = maxPageSize.resourceTemplates!; + + // Convert registered resource templates to ResourceTemplate format + const allTemplates: Array<{ + uriTemplate: string; + name: string; + description?: string; + mimeType?: string; + icons?: Array<{ + src: string; + mimeType?: string; + sizes?: string[]; + theme?: "light" | "dark"; + }>; + title?: string; + }> = []; + for (const [ + uriTemplate, + registered, + ] of state.registeredResourceTemplates.entries()) { + if (registered.enabled) { + // Find the name from config by matching uriTemplate + const templateDef = config.resourceTemplates?.find( + (t) => t.uriTemplate === uriTemplate, + ); + allTemplates.push({ + uriTemplate: registered.resourceTemplate.uriTemplate.toString(), + name: templateDef?.name || uriTemplate, // Fallback to uriTemplate if name not found + title: registered.title, + description: + registered.metadata?.description || templateDef?.description, + mimeType: registered.metadata?.mimeType, + icons: registered.metadata?.icons, + }); + } + } + + const startIndex = cursor ? parseInt(cursor, 10) : 0; + const endIndex = startIndex + pageSize; + const page = allTemplates.slice(startIndex, endIndex); + const nextCursor = + endIndex < allTemplates.length ? endIndex.toString() : undefined; + + return { + resourceTemplates: page as ResourceTemplate[], + nextCursor, + } as ListResourceTemplatesResult; + }, + ); + } + + // Prompts pagination + if (capabilities.prompts && maxPageSize.prompts !== undefined) { + mcpServer.server.setRequestHandler( + ListPromptsRequestSchema, + async (request) => { + const cursor = request.params?.cursor; + const pageSize = maxPageSize.prompts!; + + // Convert registered prompts to Prompt format using the same logic as the SDK + const allPrompts: Prompt[] = []; + for (const [name, prompt] of state.registeredPrompts.entries()) { + if (prompt.enabled) { + // Use the same conversion logic the SDK uses (from mcp.js line 408-419) + const shape = prompt.argsSchema + ? getObjectShape(prompt.argsSchema) + : undefined; + const arguments_ = shape + ? Object.entries(shape).map(([argName, field]) => { + const description = getSchemaDescription(field); + const isOptional = isSchemaOptional(field); + return { + name: argName, + description, + required: !isOptional, + } as PromptArgument; + }) + : undefined; + + allPrompts.push({ + name, + title: prompt.title, + description: prompt.description, + arguments: arguments_, + } as Prompt); + } + } + + const startIndex = cursor ? parseInt(cursor, 10) : 0; + const endIndex = startIndex + pageSize; + const page = allPrompts.slice(startIndex, endIndex); + const nextCursor = + endIndex < allPrompts.length ? endIndex.toString() : undefined; + + return { + prompts: page, + nextCursor, + } as ListPromptsResult; + }, + ); + } + + return mcpServer; +} diff --git a/shared/test/test-helpers.ts b/shared/test/test-helpers.ts new file mode 100644 index 000000000..c54d8556f --- /dev/null +++ b/shared/test/test-helpers.ts @@ -0,0 +1,113 @@ +/** + * Test helpers for event-driven waits and polling. + * Use these instead of arbitrary setTimeout/setInterval in E2E tests. + */ + +import { vi } from "vitest"; +import * as fs from "node:fs/promises"; + +export interface WaitForEventOptions { + timeout?: number; +} + +/** + * Wait for a single event on an EventTarget. Resolves with the event detail, + * or rejects after `timeout` ms if the event never fires. + */ +export function waitForEvent( + target: EventTarget, + eventName: string, + options?: WaitForEventOptions, +): Promise { + const timeoutMs = options?.timeout ?? 5000; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + target.removeEventListener(eventName, handler); + reject( + new Error(`Timeout waiting for event '${eventName}' (${timeoutMs}ms)`), + ); + }, timeoutMs); + const handler = (e: Event) => { + clearTimeout(timer); + target.removeEventListener(eventName, handler); + resolve((e as CustomEvent).detail); + }; + target.addEventListener(eventName, handler); + }); +} + +export interface WaitForProgressCountOptions { + timeout?: number; +} + +/** + * Wait until `progressNotification` has been received `expectedCount` times. + * Returns the collected event details. Use for sendProgress and progress-linked-to-tasks tests. + */ +export function waitForProgressCount( + client: { + addEventListener: (type: string, fn: (e: Event) => void) => void; + removeEventListener: (type: string, fn: (e: Event) => void) => void; + }, + expectedCount: number, + options?: WaitForProgressCountOptions, +): Promise { + const timeoutMs = options?.timeout ?? 5000; + const events: unknown[] = []; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + client.removeEventListener("progressNotification", handler); + reject( + new Error( + `Timeout waiting for ${expectedCount} progressNotification events (got ${events.length}) after ${timeoutMs}ms`, + ), + ); + }, timeoutMs); + const handler = (e: Event) => { + events.push((e as CustomEvent).detail); + if (events.length >= expectedCount) { + clearTimeout(timer); + client.removeEventListener("progressNotification", handler); + resolve(events); + } + }; + client.addEventListener("progressNotification", handler); + }); +} + +export interface WaitForStateFileOptions { + timeout?: number; + interval?: number; +} + +/** + * Poll state file until `predicate(parsed)` returns true, then return the parsed value. + * Uses vi.waitFor under the hood. For use with Zustand persist state.json files. + */ +export async function waitForStateFile( + filePath: string, + predicate: (parsed: unknown) => boolean, + options?: WaitForStateFileOptions, +): Promise { + const { timeout = 2000, interval = 50 } = options ?? {}; + let result: T | undefined; + await vi.waitFor( + async () => { + const raw = await fs.readFile(filePath, "utf-8"); + let parsed: unknown; + try { + parsed = JSON.parse(raw) as unknown; + } catch { + // File may be mid-write or contain partial/corrupt JSON; retry + throw new Error("waitForStateFile predicate not met"); + } + if (!predicate(parsed)) { + throw new Error("waitForStateFile predicate not met"); + } + result = parsed as T; + return true; + }, + { timeout, interval }, + ); + return result!; +} diff --git a/shared/test/test-server-control.ts b/shared/test/test-server-control.ts new file mode 100644 index 000000000..955b09811 --- /dev/null +++ b/shared/test/test-server-control.ts @@ -0,0 +1,19 @@ +/** + * Test-only server control for orderly shutdown. + * HTTP test server sets this when starting and clears it when stopping. + * Progress-sending tools check isClosing() before sending and skip/break if closing. + */ + +export interface ServerControl { + isClosing(): boolean; +} + +let current: ServerControl | null = null; + +export function setTestServerControl(c: ServerControl | null): void { + current = c; +} + +export function getTestServerControl(): ServerControl | null { + return current; +} diff --git a/shared/test/test-server-fixtures.ts b/shared/test/test-server-fixtures.ts new file mode 100644 index 000000000..c31b402c5 --- /dev/null +++ b/shared/test/test-server-fixtures.ts @@ -0,0 +1,1888 @@ +/** + * Shared test fixtures for composable MCP test servers + * + * This module provides helper functions for creating test tools, prompts, and resources. + * For the core composable server types and createMcpServer function, see composable-test-server.ts + */ + +import * as z from "zod/v4"; +import type { Implementation } from "@modelcontextprotocol/sdk/types.js"; +import { + CreateMessageResultSchema, + ElicitResultSchema, + ListRootsResultSchema, +} from "@modelcontextprotocol/sdk/types.js"; +import type { + ToolDefinition, + TaskToolDefinition, + ResourceDefinition, + PromptDefinition, + ResourceTemplateDefinition, + ServerConfig, + TestServerContext, +} from "./composable-test-server.js"; +import { getTestServerControl } from "./test-server-control.js"; +import type { + ElicitRequestFormParams, + ElicitRequestURLParams, +} from "@modelcontextprotocol/sdk/types.js"; +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { + ToolTaskHandler, + TaskRequestHandlerExtra, + CreateTaskRequestHandlerExtra, +} from "@modelcontextprotocol/sdk/experimental/tasks/interfaces.js"; +import { RELATED_TASK_META_KEY } from "@modelcontextprotocol/sdk/types.js"; +import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js"; +import type { ShapeOutput } from "@modelcontextprotocol/sdk/server/zod-compat.js"; +import type { + GetTaskResult, + CallToolResult, +} from "@modelcontextprotocol/sdk/types.js"; + +// Re-export types and functions from composable-test-server for backward compatibility +export type { + ToolDefinition, + TaskToolDefinition, + ResourceDefinition, + PromptDefinition, + ResourceTemplateDefinition, + ServerConfig, +} from "./composable-test-server.js"; +export { createMcpServer } from "./composable-test-server.js"; + +/** + * Create multiple numbered tools for pagination testing + * @param count Number of tools to create + * @returns Array of tool definitions + */ +export function createNumberedTools(count: number): ToolDefinition[] { + const tools: ToolDefinition[] = []; + for (let i = 1; i <= count; i++) { + tools.push({ + name: `tool-${i}`, + description: `Test tool number ${i}`, + inputSchema: { + message: z.string().describe(`Message for tool ${i}`), + }, + handler: async (params: Record) => { + return { message: `Tool ${i}: ${params.message as string}` }; + }, + }); + } + return tools; +} + +/** + * Create multiple numbered resources for pagination testing + * @param count Number of resources to create + * @returns Array of resource definitions + */ +export function createNumberedResources(count: number): ResourceDefinition[] { + const resources: ResourceDefinition[] = []; + for (let i = 1; i <= count; i++) { + resources.push({ + name: `resource-${i}`, + uri: `test://resource-${i}`, + description: `Test resource number ${i}`, + mimeType: "text/plain", + text: `Content for resource ${i}`, + }); + } + return resources; +} + +/** + * Create multiple numbered resource templates for pagination testing + * @param count Number of resource templates to create + * @returns Array of resource template definitions + */ +export function createNumberedResourceTemplates( + count: number, +): ResourceTemplateDefinition[] { + const templates: ResourceTemplateDefinition[] = []; + for (let i = 1; i <= count; i++) { + templates.push({ + name: `template-${i}`, + uriTemplate: `test://template-${i}/{param}`, + description: `Test resource template number ${i}`, + handler: async (uri: URL, variables: Record) => { + return { + contents: [ + { + uri: uri.toString(), + mimeType: "text/plain", + text: `Content for template ${i} with param ${variables.param}`, + }, + ], + }; + }, + }); + } + return templates; +} + +/** + * Create multiple numbered prompts for pagination testing + * @param count Number of prompts to create + * @returns Array of prompt definitions + */ +export function createNumberedPrompts(count: number): PromptDefinition[] { + const prompts: PromptDefinition[] = []; + for (let i = 1; i <= count; i++) { + prompts.push({ + name: `prompt-${i}`, + description: `Test prompt number ${i}`, + promptString: `This is prompt ${i}`, + }); + } + return prompts; +} + +/** + * Create an "echo" tool that echoes back the input message + */ +export function createEchoTool(): ToolDefinition { + return { + name: "echo", + description: "Echo back the input message", + inputSchema: { + message: z.string().describe("Message to echo back"), + }, + handler: async (params: Record, _server?: any) => { + return { message: `Echo: ${params.message as string}` }; + }, + }; +} + +/** + * Create a tool that writes a message to stderr. Used to test stderr capture/piping. + */ +export function createWriteToStderrTool(): ToolDefinition { + return { + name: "writeToStderr", + description: "Write a message to stderr (for testing stderr capture)", + inputSchema: { + message: z.string().describe("Message to write to stderr"), + }, + handler: async (params: Record) => { + const msg = params.message as string; + process.stderr.write(`${msg}\n`); + return { message: `Wrote to stderr: ${msg}` }; + }, + }; +} + +/** + * Create an "add" tool that adds two numbers together + */ +export function createAddTool(): ToolDefinition { + return { + name: "add", + description: "Add two numbers together", + inputSchema: { + a: z.number().describe("First number"), + b: z.number().describe("Second number"), + }, + handler: async (params: Record, _server?: any) => { + const a = params.a as number; + const b = params.b as number; + return { result: a + b }; + }, + }; +} + +/** + * Create a "get-sum" tool that returns the sum of two numbers (alias for add) + */ +export function createGetSumTool(): ToolDefinition { + return { + name: "get-sum", + description: "Get the sum of two numbers", + inputSchema: { + a: z.number().describe("First number"), + b: z.number().describe("Second number"), + }, + handler: async (params: Record, _server?: any) => { + const a = params.a as number; + const b = params.b as number; + return { result: a + b }; + }, + }; +} + +/** + * Create a "collectSample" tool that sends a sampling request and returns the response + */ +export function createCollectSampleTool(): ToolDefinition { + return { + name: "collectSample", + description: + "Send a sampling request with the given text and return the response", + inputSchema: { + text: z.string().describe("Text to send in the sampling request"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ): Promise => { + if (!context) { + throw new Error("Server context not available"); + } + const server = context.server; + + const text = params.text as string; + + // Send a sampling/createMessage request to the client using the SDK's createMessage method + try { + const result = await server.server.createMessage({ + messages: [ + { + role: "user" as const, + content: { + type: "text" as const, + text: text, + }, + }, + ], + maxTokens: 100, // Required parameter + }); + + return { + message: `Sampling response: ${JSON.stringify(result)}`, + }; + } catch (error) { + console.error( + "[collectSample] Error sending/receiving sampling request:", + error, + ); + throw error; + } + }, + }; +} + +/** + * Create a "listRoots" tool that calls roots/list and returns the roots + */ +export function createListRootsTool(): ToolDefinition { + return { + name: "listRoots", + description: "List the current roots configured on the client", + inputSchema: {}, + handler: async ( + _params: Record, + context?: TestServerContext, + ): Promise => { + if (!context) { + throw new Error("Server context not available"); + } + const server = context.server; + + try { + // Call roots/list on the client using the SDK's listRoots method + const result = await server.server.listRoots(); + + return { + message: `Roots: ${JSON.stringify(result.roots, null, 2)}`, + roots: result.roots, + }; + } catch (error) { + return { + message: `Error listing roots: ${error instanceof Error ? error.message : String(error)}`, + error: true, + }; + } + }, + }; +} + +/** + * Create a "collectElicitation" tool that sends an elicitation request and returns the response + */ +export function createCollectFormElicitationTool(): ToolDefinition { + return { + name: "collectElicitation", + description: + "Send an elicitation request with the given message and schema and return the response", + inputSchema: { + message: z + .string() + .describe("Message to send in the elicitation request"), + schema: z.any().describe("JSON schema for the elicitation request"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ): Promise => { + if (!context) { + throw new Error("Server context not available"); + } + const server = context.server; + + // TODO: The fact that param attributes are "any" is not ideal + const message = params.message as string; + const schema = params.schema as any; // TODO: This is also not ideal + + // Send a form-based elicitation request using the SDK's elicitInput method + try { + const elicitationParams: ElicitRequestFormParams = { + message, + requestedSchema: schema, + }; + + const result = await server.server.elicitInput(elicitationParams); + + return { + message: `Elicitation response: ${JSON.stringify(result)}`, + }; + } catch (error) { + console.error( + "[collectElicitation] Error sending/receiving elicitation request:", + error, + ); + throw error; + } + }, + }; +} + +/** + * Create a "collectUrlElicitation" tool that sends a URL-based elicitation request + * to the client and returns the response + */ +export function createCollectUrlElicitationTool(): ToolDefinition { + return { + name: "collectUrlElicitation", + description: + "Send a URL-based elicitation request with the given message and URL and return the response", + inputSchema: { + message: z + .string() + .describe("Message to send in the elicitation request"), + url: z.string().url().describe("URL for the user to navigate to"), + elicitationId: z + .string() + .optional() + .describe("Optional elicitation ID (generated if not provided)"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ): Promise => { + if (!context) { + throw new Error("Server context not available"); + } + const server = context.server; + + const message = params.message as string; + const url = params.url as string; + const elicitationId = + (params.elicitationId as string) || + `url-elicitation-${Date.now()}-${Math.random()}`; + + // Send a URL-based elicitation request using the SDK's elicitInput method + try { + const elicitationParams: ElicitRequestURLParams = { + mode: "url", + message, + elicitationId, + url, + }; + + const result = await server.server.elicitInput(elicitationParams); + + return { + message: `URL elicitation response: ${JSON.stringify(result)}`, + }; + } catch (error) { + console.error( + "[collectUrlElicitation] Error sending/receiving URL elicitation request:", + error, + ); + throw error; + } + }, + }; +} + +/** + * Create a "sendNotification" tool that sends a notification message from the server + */ +export function createSendNotificationTool(): ToolDefinition { + return { + name: "sendNotification", + description: "Send a notification message from the server", + inputSchema: { + message: z.string().describe("Notification message to send"), + level: z + .enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency", + ]) + .optional() + .describe("Log level for the notification"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ): Promise => { + if (!context) { + throw new Error("Server context not available"); + } + const server = context.server; + + const message = params.message as string; + const level = (params.level as string) || "info"; + + // Send a notification from the server + // Notifications don't have an id and use the jsonrpc format + try { + await server.server.notification({ + method: "notifications/message", + params: { + level, + logger: "test-server", + data: { + message, + }, + }, + }); + + return { + message: `Notification sent: ${message}`, + }; + } catch (error) { + console.error("[sendNotification] Error sending notification:", error); + throw error; + } + }, + }; +} + +/** + * Create a "get-annotated-message" tool that returns a message with optional image + */ +export function createGetAnnotatedMessageTool(): ToolDefinition { + return { + name: "get-annotated-message", + description: "Get an annotated message", + inputSchema: { + messageType: z + .enum(["success", "error", "warning", "info"]) + .describe("Type of message"), + includeImage: z + .boolean() + .optional() + .describe("Whether to include an image"), + }, + handler: async (params: Record, _server?: any) => { + const messageType = params.messageType as string; + const includeImage = params.includeImage as boolean | undefined; + const message = `This is a ${messageType} message`; + const content: Array< + | { type: "text"; text: string } + | { type: "image"; data: string; mimeType: string } + > = [ + { + type: "text", + text: message, + }, + ]; + + if (includeImage) { + content.push({ + type: "image", + data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==", // 1x1 transparent PNG + mimeType: "image/png", + }); + } + + return { content }; + }, + }; +} + +/** + * Create a "simple-prompt" prompt definition + */ +export function createSimplePrompt(): PromptDefinition { + return { + name: "simple-prompt", + description: "A simple prompt for testing", + promptString: "This is a simple prompt for testing purposes.", + }; +} + +/** + * Create an "args-prompt" prompt that accepts arguments + */ +export function createArgsPrompt( + completions?: Record< + string, + ( + argumentValue: string, + context?: Record, + ) => Promise | string[] + >, +): PromptDefinition { + return { + name: "args-prompt", + description: "A prompt that accepts arguments for testing", + promptString: "This is a prompt with arguments: city={city}, state={state}", + argsSchema: { + city: z.string().describe("City name"), + state: z.string().describe("State name"), + }, + completions, + }; +} + +/** + * Create an "architecture" resource definition + */ +export function createArchitectureResource(): ResourceDefinition { + return { + name: "architecture", + uri: "demo://resource/static/document/architecture.md", + description: "Architecture documentation", + mimeType: "text/markdown", + text: `# Architecture Documentation + +This is a test resource for the MCP test server. + +## Overview + +This resource is used for testing resource reading functionality in the CLI. + +## Sections + +- Introduction +- Design +- Implementation +- Testing + +## Notes + +This is a static resource provided by the test MCP server. +`, + }; +} + +/** + * Create a "test-cwd" resource that exposes the current working directory (generally useful when testing with the stdio test server) + */ +export function createTestCwdResource(): ResourceDefinition { + return { + name: "test-cwd", + uri: "test://cwd", + description: "Current working directory of the test server", + mimeType: "text/plain", + text: process.cwd(), + }; +} + +/** + * Create a "test-env" resource that exposes environment variables (generally useful when testing with the stdio test server) + */ +export function createTestEnvResource(): ResourceDefinition { + return { + name: "test-env", + uri: "test://env", + description: "Environment variables available to the test server", + mimeType: "application/json", + text: JSON.stringify(process.env, null, 2), + }; +} + +/** + * Create a "test-argv" resource that exposes command-line arguments (generally useful when testing with the stdio test server) + */ +export function createTestArgvResource(): ResourceDefinition { + return { + name: "test-argv", + uri: "test://argv", + description: "Command-line arguments the test server was started with", + mimeType: "application/json", + text: JSON.stringify(process.argv, null, 2), + }; +} + +/** + * Create minimal server info for test servers + */ +export function createTestServerInfo( + name: string = "test-server", + version: string = "1.0.0", +): Implementation { + return { + name, + version, + }; +} + +/** + * Create a "file" resource template that reads files by path + */ +export function createFileResourceTemplate( + completionCallback?: ( + argumentName: string, + value: string, + context?: Record, + ) => Promise | string[], + listCallback?: () => Promise | string[], +): ResourceTemplateDefinition { + return { + name: "file", + uriTemplate: "file:///{path}", + description: "Read a file by path", + inputSchema: { + path: z.string().describe("File path to read"), + }, + handler: async (uri: URL, params: Record) => { + const path = params.path as string; + // For testing, return a mock file content + return { + contents: [ + { + uri: uri.toString(), + mimeType: "text/plain", + text: `Mock file content for: ${path}\nThis is a test resource template.`, + }, + ], + }; + }, + complete: completionCallback, + list: listCallback, + }; +} + +/** + * Create a "user" resource template that returns user data by ID + */ +export function createUserResourceTemplate( + completionCallback?: ( + argumentName: string, + value: string, + context?: Record, + ) => Promise | string[], + listCallback?: () => Promise | string[], +): ResourceTemplateDefinition { + return { + name: "user", + uriTemplate: "user://{userId}", + description: "Get user data by ID", + inputSchema: { + userId: z.string().describe("User ID"), + }, + handler: async (uri: URL, params: Record) => { + const userId = params.userId as string; + return { + contents: [ + { + uri: uri.toString(), + mimeType: "application/json", + text: JSON.stringify( + { + id: userId, + name: `User ${userId}`, + email: `user${userId}@example.com`, + role: "test-user", + }, + null, + 2, + ), + }, + ], + }; + }, + complete: completionCallback, + list: listCallback, + }; +} + +/** + * Create a tool that adds a resource to the server and sends list_changed notification + */ +export function createAddResourceTool(): ToolDefinition { + return { + name: "addResource", + description: + "Add a resource to the server and send list_changed notification", + inputSchema: { + uri: z.string().describe("Resource URI"), + name: z.string().describe("Resource name"), + description: z.string().optional().describe("Resource description"), + mimeType: z.string().optional().describe("Resource MIME type"), + text: z.string().optional().describe("Resource text content"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Register with SDK (returns RegisteredResource) + const registered = server.registerResource( + params.name as string, + params.uri as string, + { + description: params.description as string | undefined, + mimeType: params.mimeType as string | undefined, + }, + async () => { + return { + contents: params.text + ? [ + { + uri: params.uri as string, + mimeType: params.mimeType as string | undefined, + text: params.text as string, + }, + ] + : [], + }; + }, + ); + + // Track in state (keyed by URI) + state.registeredResources.set(params.uri as string, registered); + + // Send notification if capability enabled + if (state.listChangedConfig.resources) { + server.sendResourceListChanged(); + } + + return { + message: `Resource ${params.uri} added`, + uri: params.uri, + }; + }, + }; +} + +/** + * Create a tool that removes a resource from the server by URI and sends list_changed notification + */ +export function createRemoveResourceTool(): ToolDefinition { + return { + name: "removeResource", + description: + "Remove a resource from the server by URI and send list_changed notification", + inputSchema: { + uri: z.string().describe("Resource URI to remove"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Find registered resource by URI + const resource = state.registeredResources.get(params.uri as string); + if (!resource) { + throw new Error(`Resource with URI ${params.uri} not found`); + } + + // Remove from SDK registry + resource.remove(); + + // Remove from tracking + state.registeredResources.delete(params.uri as string); + + // Send notification if capability enabled + if (state.listChangedConfig.resources) { + server.sendResourceListChanged(); + } + + return { + message: `Resource ${params.uri} removed`, + uri: params.uri, + }; + }, + }; +} + +/** + * Create a tool that adds a tool to the server and sends list_changed notification + */ +export function createAddToolTool(): ToolDefinition { + return { + name: "addTool", + description: "Add a tool to the server and send list_changed notification", + inputSchema: { + name: z.string().describe("Tool name"), + description: z.string().describe("Tool description"), + inputSchema: z.any().optional().describe("Tool input schema"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Register with SDK (returns RegisteredTool) + const registered = server.registerTool( + params.name as string, + { + description: params.description as string, + inputSchema: params.inputSchema, + }, + async () => { + return { + content: [ + { + type: "text" as const, + text: `Tool ${params.name} executed`, + }, + ], + }; + }, + ); + + // Track in state (keyed by name) + state.registeredTools.set(params.name as string, registered); + + // Send notification if capability enabled + // Note: sendToolListChanged() is synchronous on McpServer but internally calls async Server method + // We don't await it, but the tool should be registered before sending the notification + if (state.listChangedConfig.tools) { + // Small delay to ensure tool is fully registered in SDK's internal state + await new Promise((resolve) => setTimeout(resolve, 10)); + server.sendToolListChanged(); + } + + return { + message: `Tool ${params.name} added`, + name: params.name, + }; + }, + }; +} + +/** + * Create a tool that removes a tool from the server by name and sends list_changed notification + */ +export function createRemoveToolTool(): ToolDefinition { + return { + name: "removeTool", + description: + "Remove a tool from the server by name and send list_changed notification", + inputSchema: { + name: z.string().describe("Tool name to remove"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Find registered tool by name + const tool = state.registeredTools.get(params.name as string); + if (!tool) { + throw new Error(`Tool ${params.name} not found`); + } + + // Remove from SDK registry + tool.remove(); + + // Remove from tracking + state.registeredTools.delete(params.name as string); + + // Send notification if capability enabled + if (state.listChangedConfig.tools) { + server.sendToolListChanged(); + } + + return { + message: `Tool ${params.name} removed`, + name: params.name, + }; + }, + }; +} + +/** + * Create a tool that adds a prompt to the server and sends list_changed notification + */ +export function createAddPromptTool(): ToolDefinition { + return { + name: "addPrompt", + description: + "Add a prompt to the server and send list_changed notification", + inputSchema: { + name: z.string().describe("Prompt name"), + description: z.string().optional().describe("Prompt description"), + promptString: z.string().describe("Prompt text"), + argsSchema: z.any().optional().describe("Prompt arguments schema"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Register with SDK (returns RegisteredPrompt) + const registered = server.registerPrompt( + params.name as string, + { + description: params.description as string | undefined, + argsSchema: params.argsSchema, + }, + async () => { + return { + messages: [ + { + role: "user" as const, + content: { + type: "text" as const, + text: params.promptString as string, + }, + }, + ], + }; + }, + ); + + // Track in state (keyed by name) + state.registeredPrompts.set(params.name as string, registered); + + // Send notification if capability enabled + if (state.listChangedConfig.prompts) { + server.sendPromptListChanged(); + } + + return { + message: `Prompt ${params.name} added`, + name: params.name, + }; + }, + }; +} + +/** + * Create a tool that updates an existing resource's content and sends resource updated notification + */ +export function createUpdateResourceTool(): ToolDefinition { + return { + name: "updateResource", + description: + "Update an existing resource's content and send resource updated notification", + inputSchema: { + uri: z.string().describe("Resource URI to update"), + text: z.string().describe("New resource text content"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Find registered resource by URI + const resource = state.registeredResources.get(params.uri as string); + if (!resource) { + throw new Error(`Resource with URI ${params.uri} not found`); + } + + // Get the current resource metadata to preserve mimeType + const currentResource = state.registeredResources.get( + params.uri as string, + ); + const mimeType = currentResource?.metadata?.mimeType || "text/plain"; + + // Update the resource's callback to return new content + resource.update({ + callback: async () => { + return { + contents: [ + { + uri: params.uri as string, + mimeType, + text: params.text as string, + }, + ], + }; + }, + }); + + // Send resource updated notification only if subscribed + const uri = params.uri as string; + if (state.resourceSubscriptions.has(uri)) { + await server.server.sendResourceUpdated({ + uri, + }); + } + + return { + message: `Resource ${params.uri} updated`, + uri: params.uri, + }; + }, + }; +} + +/** + * Create a tool that sends progress notifications during execution + * @param name Tool name (default: "sendProgress") + * @returns Tool definition + */ +export function createSendProgressTool( + name: string = "sendProgress", +): ToolDefinition { + return { + name, + description: + "Send progress notifications during tool execution, then return a result", + inputSchema: { + units: z + .number() + .int() + .positive() + .describe("Number of progress units to send"), + delayMs: z + .number() + .int() + .nonnegative() + .default(100) + .describe("Delay in milliseconds between progress notifications"), + total: z + .number() + .int() + .positive() + .optional() + .describe("Total number of units (for percentage calculation)"), + message: z + .string() + .optional() + .describe("Progress message to include in notifications"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + extra?: any, + ): Promise => { + if (!context) { + throw new Error("Server context not available"); + } + const server = context.server; + + const units = params.units as number; + const delayMs = (params.delayMs as number) || 100; + const total = params.total as number | undefined; + const message = (params.message as string) || "Processing..."; + + // Extract progressToken from metadata + const progressToken = extra?._meta?.progressToken; + + // Send progress notifications + let sent = 0; + for (let i = 1; i <= units; i++) { + if (context.serverControl?.isClosing()) { + break; + } + // Wait before sending notification (except for the first one) + if (i > 1 && delayMs > 0) { + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + if (context.serverControl?.isClosing()) { + break; + } + + if (progressToken !== undefined) { + const progressParams: { + progress: number; + total?: number; + message?: string; + progressToken: string | number; + } = { + progress: i, + message: `${message} (${i}/${units})`, + progressToken, + }; + if (total !== undefined) { + progressParams.total = total; + } + + try { + await server.server.notification( + { + method: "notifications/progress", + params: progressParams, + }, + { relatedRequestId: extra?.requestId }, + ); + sent = i; + } catch (error) { + console.error( + "[sendProgress] Error sending progress notification:", + error, + ); + break; + } + } + } + + return { + message: `Completed ${sent} progress notifications`, + units: sent, + total: total || units, + }; + }, + }; +} + +export function createRemovePromptTool(): ToolDefinition { + return { + name: "removePrompt", + description: + "Remove a prompt from the server by name and send list_changed notification", + inputSchema: { + name: z.string().describe("Prompt name to remove"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ) => { + if (!context) { + throw new Error("Server context not available"); + } + + const { server, state } = context; + + // Find registered prompt by name + const prompt = state.registeredPrompts.get(params.name as string); + if (!prompt) { + throw new Error(`Prompt ${params.name} not found`); + } + + // Remove from SDK registry + prompt.remove(); + + // Remove from tracking + state.registeredPrompts.delete(params.name as string); + + // Send notification if capability enabled + if (state.listChangedConfig.prompts) { + server.sendPromptListChanged(); + } + + return { + message: `Prompt ${params.name} removed`, + name: params.name, + }; + }, + }; +} + +/** + * Options for creating a flexible task tool fixture + */ +export interface FlexibleTaskToolOptions { + name?: string; // default: "flexibleTask" + taskSupport?: "required" | "optional" | "forbidden"; // default: "required" + immediateReturn?: boolean; // If true, tool returns immediately, no task created + delayMs?: number; // default: 1000 (time before task completes) + progressUnits?: number; // If provided, send progress notifications (default: 5 if progress enabled) + elicitationSchema?: z.ZodTypeAny; // If provided, require elicitation with this schema + samplingText?: string; // If provided, require sampling with this text + failAfterDelay?: number; // If set, task fails after this delay (ms) + cancelAfterDelay?: number; // If set, task cancels itself after this delay (ms) +} + +/** + * Create a flexible task tool that can be configured for various task scenarios + * Returns ToolDefinition if taskSupport is "forbidden" or immediateReturn is true + * Returns TaskToolDefinition otherwise + */ +export function createFlexibleTaskTool( + options: FlexibleTaskToolOptions = {}, +): ToolDefinition | TaskToolDefinition { + const { + name = "flexibleTask", + taskSupport = "required", + immediateReturn = false, + delayMs = 1000, + progressUnits, + elicitationSchema, + samplingText, + failAfterDelay, + cancelAfterDelay, + } = options; + + // If taskSupport is "forbidden" or immediateReturn is true, return a regular tool + if (taskSupport === "forbidden" || immediateReturn) { + return { + name, + description: `A flexible task tool (${taskSupport === "forbidden" ? "forbidden" : "immediate return"} mode)`, + inputSchema: { + message: z.string().optional().describe("Optional message parameter"), + }, + handler: async ( + params: Record, + context?: TestServerContext, + ): Promise => { + // Simulate some work + await new Promise((resolve) => setTimeout(resolve, delayMs)); + return { + message: `Task completed immediately: ${params.message || "no message"}`, + }; + }, + }; + } + + // Otherwise, return a task tool + // Note: inputSchema is for createTask handler only - getTask and getTaskResult don't use it + const taskTool: TaskToolDefinition = { + name, + description: `A flexible task tool supporting progress, elicitation, and sampling`, + inputSchema: { + message: z.string().optional().describe("Optional message parameter"), + }, + execution: { + taskSupport: taskSupport as "required" | "optional", + }, + handler: { + createTask: async (args, extra) => { + const message = (args as Record)?.message as + | string + | undefined; + const progressToken = extra._meta?.progressToken; + + // Create the task + const task = await extra.taskStore.createTask({}); + + // Start async task execution + (async () => { + try { + // Handle elicitation if schema provided + if (elicitationSchema) { + // Update task status to input_required + await extra.taskStore.updateTaskStatus( + task.taskId, + "input_required", + ); + + // Send elicitation request with related-task metadata + // Note: We use extra.sendRequest() here because task handlers don't have + // direct access to the server instance with elicitInput(). However, we + // construct properly typed params for consistency with elicitInput() usage. + try { + // Convert Zod schema to JSON schema + const jsonSchema = toJsonSchemaCompat( + elicitationSchema, + ) as ElicitRequestFormParams["requestedSchema"]; + const elicitationParams: ElicitRequestFormParams = { + message: `Please provide input for task ${task.taskId}`, + requestedSchema: jsonSchema, + _meta: { + [RELATED_TASK_META_KEY]: { + taskId: task.taskId, + }, + }, + }; + await extra.sendRequest( + { + method: "elicitation/create", + params: elicitationParams, + }, + ElicitResultSchema, + ); + // Once response received, continue task + await extra.taskStore.updateTaskStatus(task.taskId, "working"); + } catch (error) { + console.error("[flexibleTask] Elicitation error:", error); + await extra.taskStore.updateTaskStatus( + task.taskId, + "failed", + error instanceof Error ? error.message : String(error), + ); + return; + } + } + + // Handle sampling if text provided + if (samplingText) { + // Update task status to input_required + await extra.taskStore.updateTaskStatus( + task.taskId, + "input_required", + ); + + // Send sampling request with related-task metadata + try { + await extra.sendRequest( + { + method: "sampling/createMessage", + params: { + messages: [ + { + role: "user", + content: { + type: "text", + text: samplingText, + }, + }, + ], + maxTokens: 100, + _meta: { + [RELATED_TASK_META_KEY]: { + taskId: task.taskId, + }, + }, + }, + }, + CreateMessageResultSchema, + ); + // Once response received, continue task + await extra.taskStore.updateTaskStatus(task.taskId, "working"); + } catch (error) { + console.error("[flexibleTask] Sampling error:", error); + await extra.taskStore.updateTaskStatus( + task.taskId, + "failed", + error instanceof Error ? error.message : String(error), + ); + return; + } + } + + // Send progress notifications if enabled + if (progressUnits !== undefined && progressUnits > 0) { + const units = progressUnits; + if (progressToken !== undefined) { + for (let i = 1; i <= units; i++) { + if (getTestServerControl()?.isClosing()) { + break; + } + await new Promise((resolve) => + setTimeout(resolve, delayMs / units), + ); + if (getTestServerControl()?.isClosing()) { + break; + } + try { + await extra.sendNotification({ + method: "notifications/progress", + params: { + progress: i, + total: units, + message: `Processing... ${i}/${units}`, + progressToken, + _meta: { + [RELATED_TASK_META_KEY]: { + taskId: task.taskId, + }, + }, + }, + }); + } catch (error) { + console.error( + "[flexibleTask] Progress notification error:", + error, + ); + break; + } + } + } + } else { + // Wait for delay if no progress + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + + // Check for failure + if (failAfterDelay !== undefined) { + await new Promise((resolve) => + setTimeout(resolve, failAfterDelay), + ); + await extra.taskStore.updateTaskStatus( + task.taskId, + "failed", + "Task failed as configured", + ); + return; + } + + // Check for cancellation + if (cancelAfterDelay !== undefined) { + await new Promise((resolve) => + setTimeout(resolve, cancelAfterDelay), + ); + await extra.taskStore.updateTaskStatus(task.taskId, "cancelled"); + return; + } + + // Complete the task + // Store result BEFORE updating status to ensure it's available when SDK fetches it + const result = { + content: [ + { + type: "text", + text: JSON.stringify({ + message: `Task completed: ${message || "no message"}`, + taskId: task.taskId, + }), + }, + ], + }; + await extra.taskStore.storeTaskResult( + task.taskId, + "completed", + result, + ); + await extra.taskStore.updateTaskStatus(task.taskId, "completed"); + } catch (error) { + // Only update status if task is not already in a terminal state + try { + const currentTask = await extra.taskStore.getTask(task.taskId); + if ( + currentTask && + currentTask.status !== "completed" && + currentTask.status !== "failed" && + currentTask.status !== "cancelled" + ) { + await extra.taskStore.updateTaskStatus( + task.taskId, + "failed", + error instanceof Error ? error.message : String(error), + ); + } + } catch (statusError) { + // Ignore errors when checking/updating status + console.error( + "[flexibleTask] Error checking/updating task status:", + statusError, + ); + } + } + })(); + + return { + task, + }; + }, + getTask: async ( + _args: ShapeOutput<{ message?: z.ZodString }>, + extra: TaskRequestHandlerExtra, + ): Promise => { + // taskId is already in extra for TaskRequestHandlerExtra + // SDK extracts taskId from request and provides it in extra.taskId + // args parameter is present due to inputSchema but not used here + // GetTaskResult is the task object itself, not a wrapper + const task = await extra.taskStore.getTask(extra.taskId); + return task as GetTaskResult; + }, + getTaskResult: async ( + _args: ShapeOutput<{ message?: z.ZodString }>, + extra: TaskRequestHandlerExtra, + ): Promise => { + // taskId is already in extra for TaskRequestHandlerExtra + // SDK extracts taskId from request and provides it in extra.taskId + // args parameter is present due to inputSchema but not used here + // getTaskResult returns Result, but handler must return CallToolResult + const result = await extra.taskStore.getTaskResult(extra.taskId); + // Ensure result has content field (CallToolResult requirement) + if (!result.content) { + throw new Error("Task result does not have content field"); + } + return result as CallToolResult; + }, + }, + }; + + return taskTool; +} + +/** + * Create a simple task tool that completes after a delay + */ +export function createSimpleTaskTool( + name: string = "simpleTask", + delayMs: number = 1000, +): TaskToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "required", + delayMs, + }) as TaskToolDefinition; +} + +/** + * Create a task tool that sends progress notifications + */ +export function createProgressTaskTool( + name: string = "progressTask", + delayMs: number = 2000, + progressUnits: number = 5, +): TaskToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "required", + delayMs, + progressUnits, + }) as TaskToolDefinition; +} + +/** + * Create a task tool that requires elicitation input + */ +export function createElicitationTaskTool( + name: string = "elicitationTask", + elicitationSchema?: z.ZodTypeAny, +): TaskToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "required", + elicitationSchema: + elicitationSchema || + z.object({ + input: z.string().describe("User input required for task"), + }), + }) as TaskToolDefinition; +} + +/** + * Create a task tool that requires sampling input + */ +export function createSamplingTaskTool( + name: string = "samplingTask", + samplingText?: string, +): TaskToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "required", + samplingText: samplingText || "Please provide a response for this task", + }) as TaskToolDefinition; +} + +/** + * Create a task tool with optional task support + */ +export function createOptionalTaskTool( + name: string = "optionalTask", + delayMs: number = 500, +): TaskToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "optional", + delayMs, + }) as TaskToolDefinition; +} + +/** + * Create a task tool that is forbidden from using tasks (returns immediately) + */ +export function createForbiddenTaskTool( + name: string = "forbiddenTask", + delayMs: number = 100, +): ToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "forbidden", + delayMs, + }) as ToolDefinition; +} + +/** + * Create a task tool that returns immediately even if taskSupport is required + * (for testing callTool() with task-supporting tools) + */ +export function createImmediateReturnTaskTool( + name: string = "immediateReturnTask", + delayMs: number = 100, +): ToolDefinition { + return createFlexibleTaskTool({ + name, + taskSupport: "required", + immediateReturn: true, + delayMs, + }) as ToolDefinition; +} + +/** + * Get a server config with task support and task tools for testing + */ +export function getTaskServerConfig(): ServerConfig { + return { + serverInfo: createTestServerInfo("test-task-server", "1.0.0"), + tasks: { + list: true, + cancel: true, + }, + tools: [ + createSimpleTaskTool(), + createProgressTaskTool(), + createElicitationTaskTool(), + createSamplingTaskTool(), + createOptionalTaskTool(), + createForbiddenTaskTool(), + createImmediateReturnTaskTool(), + ], + logging: true, // Required for notifications/message and progress + }; +} + +/** + * Get default server config with common test tools, prompts, and resources + */ +export function getDefaultServerConfig(): ServerConfig { + return { + serverInfo: createTestServerInfo("test-mcp-server", "1.0.0"), + tools: [ + createEchoTool(), + createGetSumTool(), + createGetAnnotatedMessageTool(), + createSendNotificationTool(), + createWriteToStderrTool(), + ], + prompts: [createSimplePrompt(), createArgsPrompt()], + resources: [ + createArchitectureResource(), + createTestCwdResource(), + createTestEnvResource(), + createTestArgvResource(), + ], + resourceTemplates: [ + createFileResourceTemplate(), + createUserResourceTemplate(), + ], + logging: true, // Required for notifications/message + }; +} + +/** + * OAuth Test Fixtures + */ + +/** + * Creates a test server configuration with OAuth enabled + */ +export function createOAuthTestServerConfig(options: { + requireAuth?: boolean; + scopesSupported?: string[]; + staticClients?: Array<{ + clientId: string; + clientSecret?: string; + redirectUris?: string[]; + }>; + supportDCR?: boolean; + supportCIMD?: boolean; + tokenExpirationSeconds?: number; + supportRefreshTokens?: boolean; +}): Partial { + return { + oauth: { + enabled: true, + requireAuth: options.requireAuth ?? false, + scopesSupported: options.scopesSupported ?? ["mcp"], + staticClients: options.staticClients, + supportDCR: options.supportDCR ?? false, + supportCIMD: options.supportCIMD ?? false, + tokenExpirationSeconds: options.tokenExpirationSeconds ?? 3600, + supportRefreshTokens: options.supportRefreshTokens ?? true, + }, + }; +} + +import type { + OAuthNavigation, + RedirectUrlProvider, +} from "../auth/providers.js"; +import type { OAuthStorage } from "../auth/storage.js"; +import { ConsoleNavigation } from "../auth/providers.js"; +import { NodeOAuthStorage } from "../auth/node/storage-node.js"; + +/** Creates a static RedirectUrlProvider for tests. Single URL for both modes. */ +function createStaticRedirectUrlProvider( + redirectUrl: string, +): RedirectUrlProvider { + return { + getRedirectUrl: () => redirectUrl, + }; +} + +/** + * Creates OAuth configuration for InspectorClient tests + */ +export function createOAuthClientConfig(options: { + mode: "static" | "dcr" | "cimd"; + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + redirectUrl: string; + scope?: string; +}): { + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + redirectUrlProvider: RedirectUrlProvider; + scope?: string; + storage: OAuthStorage; + navigation: OAuthNavigation; +} { + const config: { + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + redirectUrlProvider: RedirectUrlProvider; + scope?: string; + storage: OAuthStorage; + navigation: OAuthNavigation; + } = { + redirectUrlProvider: createStaticRedirectUrlProvider(options.redirectUrl), + storage: new NodeOAuthStorage(), + navigation: new ConsoleNavigation(), + }; + + if (options.mode === "static") { + if (!options.clientId) { + throw new Error("clientId is required for static mode"); + } + config.clientId = options.clientId; + if (options.clientSecret) { + config.clientSecret = options.clientSecret; + } + } else if (options.mode === "dcr") { + // DCR mode - no clientId needed, will be registered + // But we can optionally provide one for testing + if (options.clientId) { + config.clientId = options.clientId; + } + } else if (options.mode === "cimd") { + if (!options.clientMetadataUrl) { + throw new Error("clientMetadataUrl is required for CIMD mode"); + } + config.clientMetadataUrl = options.clientMetadataUrl; + } + + if (options.scope) { + config.scope = options.scope; + } + + return config; +} + +/** + * Client metadata document for CIMD testing + */ +export interface ClientMetadataDocument { + redirect_uris: string[]; + token_endpoint_auth_method?: string; + grant_types?: string[]; + response_types?: string[]; + client_name?: string; + client_uri?: string; + scope?: string; +} + +/** + * Creates an Express server that serves a client metadata document for CIMD testing + * The server runs on a different port and serves the metadata at the root path + * + * @param metadata - The client metadata document to serve + * @returns Object with server URL and cleanup function + */ +export async function createClientMetadataServer( + metadata: ClientMetadataDocument, +): Promise<{ url: string; stop: () => Promise }> { + const express = await import("express"); + const app = express.default(); + + // Serve metadata document at root path + app.get("/", (req, res) => { + res.json(metadata); + }); + + // Start server on a random available port + return new Promise((resolve, reject) => { + const server = app.listen(0, () => { + const address = server.address(); + if (!address || typeof address === "string") { + reject(new Error("Failed to get server address")); + return; + } + const port = address.port; + const url = `http://localhost:${port}`; + + resolve({ + url, + stop: async () => { + return new Promise((resolveStop) => { + server.close(() => { + resolveStop(); + }); + }); + }, + }); + }); + + server.on("error", reject); + }); +} + +/** + * Helper function to programmatically complete OAuth authorization + * Makes HTTP GET request to authorization URL and extracts authorization code + * The test server's authorization endpoint auto-approves and redirects with code + * + * @param authorizationUrl - The authorization URL from oauthAuthorizationRequired event + * @returns Authorization code extracted from redirect URL + */ +export async function completeOAuthAuthorization( + authorizationUrl: URL, +): Promise { + // Make GET request to authorization URL (test server auto-approves) + const response = await fetch(authorizationUrl.toString(), { + redirect: "manual", // Don't follow redirect automatically + }); + + if (response.status !== 302 && response.status !== 301) { + throw new Error( + `Expected redirect (302/301), got ${response.status}: ${await response.text()}`, + ); + } + + // Extract redirect URL from Location header + const redirectUrl = response.headers.get("location"); + if (!redirectUrl) { + throw new Error("No Location header in redirect response"); + } + + // Parse authorization code from redirect URL + const redirectUrlObj = new URL(redirectUrl); + const code = redirectUrlObj.searchParams.get("code"); + if (!code) { + throw new Error(`No authorization code in redirect URL: ${redirectUrl}`); + } + + return code; +} diff --git a/shared/test/test-server-http.ts b/shared/test/test-server-http.ts new file mode 100644 index 000000000..424b2b3d3 --- /dev/null +++ b/shared/test/test-server-http.ts @@ -0,0 +1,509 @@ +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { createMcpServer } from "./test-server-fixtures.js"; +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; +import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; +import type { Request, Response } from "express"; +import express from "express"; +import { createServer as createHttpServer, Server as HttpServer } from "http"; +import { createServer as createNetServer } from "net"; +import * as z from "zod/v4"; +import * as crypto from "node:crypto"; +import type { ServerConfig } from "./test-server-fixtures.js"; +import { + setupOAuthRoutes, + createBearerTokenMiddleware, +} from "./test-server-oauth.js"; +import { + setTestServerControl, + type ServerControl, +} from "./test-server-control.js"; + +export interface RecordedRequest { + method: string; + params?: any; + headers?: Record; + metadata?: Record; + response: any; + timestamp: number; +} + +/** + * Find an available port starting from the given port + */ +async function findAvailablePort(startPort: number): Promise { + return new Promise((resolve, reject) => { + const server = createNetServer(); + server.listen(startPort, "127.0.0.1", () => { + const port = (server.address() as { port: number })?.port; + server.close(() => resolve(port || startPort)); + }); + server.on("error", (err: NodeJS.ErrnoException) => { + if (err.code === "EADDRINUSE") { + // Try next port + findAvailablePort(startPort + 1) + .then(resolve) + .catch(reject); + } else { + reject(err); + } + }); + }); +} + +/** + * Extract headers from Express request + */ +function extractHeaders(req: Request): Record { + const headers: Record = {}; + for (const [key, value] of Object.entries(req.headers)) { + if (typeof value === "string") { + headers[key] = value; + } else if (Array.isArray(value) && value.length > 0) { + const lastValue = value[value.length - 1]; + if (typeof lastValue === "string") { + headers[key] = lastValue; + } + } + } + return headers; +} + +// With this test server, your test can hold an instance and you can get the server's recorded message history at any time. +// +export class TestServerHttp { + private config: ServerConfig; + private readonly configWithCallback: ServerConfig; + private readonly serverControl: ServerControl; + private _closing = false; + private recordedRequests: RecordedRequest[] = []; + private httpServer?: HttpServer; + private transport?: StreamableHTTPServerTransport | SSEServerTransport; + private baseUrl?: string; + private currentRequestHeaders?: Record; + private currentLogLevel: string | null = null; + /** One McpServer per connection (SSE and streamable-http both use this; SDK allows only one transport per server) */ + private mcpServersBySession?: Map; + + constructor(config: ServerConfig) { + this.config = config; + this.serverControl = { + isClosing: () => this._closing, + }; + this.configWithCallback = { + ...config, + onLogLevelSet: (level: string) => { + this.currentLogLevel = level; + }, + serverControl: this.serverControl, + }; + } + + /** + * Set up message interception for a transport to record incoming messages + * This wraps the transport's onmessage handler to record requests/notifications + */ + private setupMessageInterception( + transport: StreamableHTTPServerTransport | SSEServerTransport, + ): void { + const originalOnMessage = transport.onmessage; + transport.onmessage = async (message) => { + const timestamp = Date.now(); + const method = + "method" in message && typeof message.method === "string" + ? message.method + : "unknown"; + const params = "params" in message ? message.params : undefined; + + // Extract metadata from params if present - it's probably not worth the effort + // to type it properly here - so we'll just pry the metadata out if exists. + const metadata = + params && typeof params === "object" && "_meta" in params + ? ((params as any)._meta as Record) + : undefined; + + try { + // Let the server handle the message + if (originalOnMessage) { + await originalOnMessage.call(transport, message); + } + + // Record successful request/notification + this.recordedRequests.push({ + method, + params, + headers: { ...this.currentRequestHeaders }, + metadata: metadata ? { ...metadata } : undefined, + response: { processed: true }, + timestamp, + }); + } catch (error) { + // Record error + this.recordedRequests.push({ + method, + params, + headers: { ...this.currentRequestHeaders }, + metadata: metadata ? { ...metadata } : undefined, + response: { + error: error instanceof Error ? error.message : String(error), + }, + timestamp, + }); + throw error; + } + }; + } + + /** + * Start the server using the configuration from ServerConfig + */ + async start(): Promise { + setTestServerControl(this.serverControl); + const serverType = this.config.serverType ?? "streamable-http"; + const requestedPort = this.config.port; + + // If a port is explicitly requested, find an available port starting from that value + // Otherwise, use 0 to let the OS assign an available port + const port = requestedPort ? await findAvailablePort(requestedPort) : 0; + + if (serverType === "streamable-http") { + return this.startHttp(port); + } else { + return this.startSse(port); + } + } + + private async startHttp(port: number): Promise { + const app = express(); + app.use(express.json()); + + // Create HTTP server + this.httpServer = createHttpServer(app); + + // Set up OAuth if enabled (BEFORE MCP routes) + if (this.config.oauth?.enabled) { + // We need baseUrl, but it's not set yet - we'll set it after server starts + // For now, use a placeholder that will be updated + const placeholderUrl = `http://localhost:${port}`; + setupOAuthRoutes(app, this.config.oauth, placeholderUrl); + } + + // Store transports and one McpServer per session (SDK allows only one transport per server) + const transports: Map = new Map(); + this.mcpServersBySession = new Map(); + + // Bearer token middleware for MCP routes if requireAuth + const mcpMiddleware: express.RequestHandler[] = []; + if (this.config.oauth?.enabled && this.config.oauth.requireAuth) { + mcpMiddleware.push(createBearerTokenMiddleware(this.config.oauth)); + } + + // Set up Express route to handle MCP requests + app.post("/mcp", ...mcpMiddleware, async (req: Request, res: Response) => { + // If middleware already sent a response (401), don't continue + if (res.headersSent) { + return; + } + // Capture headers for this request + this.currentRequestHeaders = extractHeaders(req); + + const sessionId = req.headers["mcp-session-id"] as string | undefined; + + if (sessionId) { + // Existing session - use the transport for this session + const transport = transports.get(sessionId); + if (!transport) { + res.status(404).json({ error: "Session not found" }); + return; + } + + try { + await transport.handleRequest(req, res, req.body); + } catch (error) { + // If response already sent (e.g., by OAuth middleware), don't send another + if (!res.headersSent) { + res.status(500).json({ + error: error instanceof Error ? error.message : String(error), + }); + } + } + } else { + // New session - create a new transport and a new McpServer (one server per connection) + const sessionMcpServer = createMcpServer(this.configWithCallback); + const newTransport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => crypto.randomUUID(), + onsessioninitialized: (sessionId: string) => { + transports.set(sessionId, newTransport); + this.mcpServersBySession!.set(sessionId, sessionMcpServer); + }, + onsessionclosed: async (sessionId: string) => { + const mcp = this.mcpServersBySession?.get(sessionId); + transports.delete(sessionId); + this.mcpServersBySession?.delete(sessionId); + if (mcp) await mcp.close(); + }, + }); + + // Set up message interception for this transport + this.setupMessageInterception(newTransport); + + // Connect this session's MCP server to this transport + await sessionMcpServer.connect(newTransport); + + try { + await newTransport.handleRequest(req, res, req.body); + } catch (error) { + // If response already sent (e.g., by OAuth middleware), don't send another + if (!res.headersSent) { + res.status(500).json({ + error: error instanceof Error ? error.message : String(error), + }); + } + } + } + }); + + // Handle GET requests for SSE stream - this enables server-initiated messages + app.get("/mcp", ...mcpMiddleware, async (req: Request, res: Response) => { + // Get session ID from header - required for streamable-http + const sessionId = req.headers["mcp-session-id"] as string | undefined; + if (!sessionId) { + res.status(400).json({ + error: "Bad Request: Mcp-Session-Id header is required", + }); + return; + } + + // Look up the transport for this session + const transport = transports.get(sessionId); + if (!transport) { + res.status(404).json({ + error: "Session not found", + }); + return; + } + + // Let the transport handle the GET request + this.currentRequestHeaders = extractHeaders(req); + try { + await transport.handleRequest(req, res); + } catch (error) { + if (!res.headersSent) { + res.status(500).json({ + error: error instanceof Error ? error.message : String(error), + }); + } + } + }); + + // Start listening on localhost only to avoid macOS firewall prompts + // Use port 0 to let the OS assign an available port if no port was specified + return new Promise((resolve, reject) => { + this.httpServer!.listen(port, "127.0.0.1", () => { + const address = this.httpServer!.address(); + const assignedPort = + typeof address === "object" && address !== null ? address.port : port; + this.baseUrl = `http://localhost:${assignedPort}`; + resolve(assignedPort); + }); + this.httpServer!.on("error", reject); + }); + } + + private async startSse(port: number): Promise { + const app = express(); + app.use(express.json()); + + // Create HTTP server + this.httpServer = createHttpServer(app); + + // Set up OAuth if enabled (BEFORE MCP routes) + // Note: We use port 0 to let OS assign port, so we can't know the actual port yet + // But the routes use relative paths, so they should work regardless + if (this.config.oauth?.enabled) { + // Use placeholder URL - actual baseUrl will be set after server starts + // The OAuth routes use relative paths, so they'll work with any base URL + const placeholderUrl = `http://localhost:${port}`; + setupOAuthRoutes(app, this.config.oauth, placeholderUrl); + } + + // Bearer token middleware for SSE routes if requireAuth + const sseMiddleware: express.RequestHandler[] = []; + if (this.config.oauth?.enabled && this.config.oauth.requireAuth) { + sseMiddleware.push(createBearerTokenMiddleware(this.config.oauth)); + } + + // One McpServer per connection (same pattern as streamable-http) + this.mcpServersBySession = new Map(); + const sseTransports: Map = new Map(); + + // GET handler for SSE connection (establishes the SSE stream) + app.get("/sse", ...sseMiddleware, async (req: Request, res: Response) => { + this.currentRequestHeaders = extractHeaders(req); + const sessionMcpServer = createMcpServer(this.configWithCallback); + const sseTransport = new SSEServerTransport("/sse", res); + + const sessionId = sseTransport.sessionId; + sseTransports.set(sessionId, sseTransport); + this.mcpServersBySession!.set(sessionId, sessionMcpServer); + + // Clean up on connection close + res.on("close", async () => { + const mcp = this.mcpServersBySession?.get(sessionId); + sseTransports.delete(sessionId); + this.mcpServersBySession?.delete(sessionId); + if (mcp) await mcp.close(); + }); + + // Intercept messages + this.setupMessageInterception(sseTransport); + + // Connect this connection's MCP server to this transport + await sessionMcpServer.connect(sseTransport); + }); + + // POST handler for SSE message sending (SSE uses GET for stream, POST for sending messages) + app.post("/sse", ...sseMiddleware, async (req: Request, res: Response) => { + this.currentRequestHeaders = extractHeaders(req); + const sessionId = req.query.sessionId as string | undefined; + + if (!sessionId) { + res.status(400).json({ error: "Missing sessionId query parameter" }); + return; + } + + const transport = sseTransports.get(sessionId); + if (!transport) { + res.status(404).json({ error: "No transport found for sessionId" }); + return; + } + + try { + await transport.handlePostMessage(req, res, req.body); + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : String(error); + res.status(500).json({ + error: errorMessage, + }); + } + }); + + // Start listening on localhost only to avoid macOS firewall prompts + // Use port 0 to let the OS assign an available port if no port was specified + return new Promise((resolve, reject) => { + this.httpServer!.listen(port, "127.0.0.1", () => { + const address = this.httpServer!.address(); + const assignedPort = + typeof address === "object" && address !== null ? address.port : port; + this.baseUrl = `http://localhost:${assignedPort}`; + resolve(assignedPort); + }); + this.httpServer!.on("error", reject); + }); + } + + /** + * Stop the server. Set closing before closing transport so in-flight tools can skip sending. + */ + async stop(): Promise { + this._closing = true; + // Close all per-connection McpServers (SSE and streamable-http both use the map) + if (this.mcpServersBySession) { + for (const mcp of this.mcpServersBySession.values()) { + await mcp.close(); + } + this.mcpServersBySession.clear(); + this.mcpServersBySession = undefined; + } + + if (this.transport) { + await this.transport.close(); + this.transport = undefined; + } + + if (this.httpServer) { + return new Promise((resolve) => { + // Force close all connections + this.httpServer!.closeAllConnections?.(); + this.httpServer!.close(() => { + this.httpServer = undefined; + setTestServerControl(null); + resolve(); + }); + }); + } else { + setTestServerControl(null); + } + } + + /** + * Get all recorded requests + */ + getRecordedRequests(): RecordedRequest[] { + return [...this.recordedRequests]; + } + + /** + * Clear recorded requests + */ + clearRecordings(): void { + this.recordedRequests = []; + } + + /** + * Wait until a recorded request matches the predicate, or reject after timeout. + * Use instead of polling getRecordedRequests() with manual delays. + */ + waitUntilRecorded( + predicate: (req: RecordedRequest) => boolean, + options?: { timeout?: number; interval?: number }, + ): Promise { + const { timeout = 5000, interval = 10 } = options ?? {}; + const start = Date.now(); + return new Promise((resolve, reject) => { + const check = () => { + const req = this.getRecordedRequests().find(predicate); + if (req) { + resolve(req); + return; + } + if (Date.now() - start >= timeout) { + reject( + new Error( + `Timeout (${timeout}ms) waiting for recorded request matching predicate`, + ), + ); + return; + } + setTimeout(check, interval); + }; + check(); + }); + } + + /** + * Get the server URL with the appropriate endpoint path + */ + get url(): string { + if (!this.baseUrl) { + throw new Error("Server not started"); + } + const serverType = this.config.serverType ?? "streamable-http"; + const endpoint = serverType === "sse" ? "/sse" : "/mcp"; + return `${this.baseUrl}${endpoint}`; + } + + /** + * Get the most recent log level that was set + */ + getCurrentLogLevel(): string | null { + return this.currentLogLevel; + } +} + +/** + * Create an HTTP/SSE MCP test server + */ +export function createTestServerHttp(config: ServerConfig): TestServerHttp { + return new TestServerHttp(config); +} diff --git a/shared/test/test-server-oauth.ts b/shared/test/test-server-oauth.ts new file mode 100644 index 000000000..0ec0fb9f8 --- /dev/null +++ b/shared/test/test-server-oauth.ts @@ -0,0 +1,675 @@ +/** + * OAuth Test Server Infrastructure + * + * Provides OAuth 2.1 authorization server functionality for test servers. + * Integrates with Express apps to add OAuth endpoints and Bearer token verification. + */ + +import type { Request, Response } from "express"; +import express from "express"; +import type { ServerConfig } from "./composable-test-server.js"; + +/** + * OAuth configuration from ServerConfig + */ +export type OAuthConfig = NonNullable; + +/** + * Set up OAuth routes on an Express application + * This adds all OAuth endpoints (authorization, token, metadata, etc.) + * + * @param app - Express application + * @param config - OAuth configuration + * @param baseUrl - Base URL of the test server (for constructing issuer URL) + */ +export function setupOAuthRoutes( + app: express.Application, + config: OAuthConfig, + baseUrl: string, +): void { + const issuerUrl = config.issuerUrl || new URL(baseUrl); + + // OAuth metadata endpoints (RFC 8414) + setupMetadataEndpoints(app, config, issuerUrl); + + // OAuth authorization endpoint + setupAuthorizationEndpoint(app, config, issuerUrl); + + // OAuth token endpoint + setupTokenEndpoint(app, config, issuerUrl); + + // Dynamic Client Registration endpoint (if enabled) + if (config.supportDCR) { + setupDCREndpoint(app, config, issuerUrl); + } +} + +/** + * Create Bearer token verification middleware + * Returns 401 if token is missing or invalid when requireAuth is true + * + * @param config - OAuth configuration + * @returns Express middleware function + */ +export function createBearerTokenMiddleware( + config: OAuthConfig, +): express.RequestHandler { + return async (req: Request, res: Response, next: express.NextFunction) => { + if (!config.requireAuth) { + return next(); + } + + const authHeader = req.headers.authorization; + if (!authHeader || !authHeader.startsWith("Bearer ")) { + // Return 401 - the SDK's transport should detect this and throw an error + // For streamable-http, the SDK checks response status and throws StreamableHTTPError with code 401 + res.status(401); + res.setHeader("Content-Type", "application/json"); + res.setHeader("WWW-Authenticate", "Bearer"); + // Return a JSON-RPC error response format that the SDK will recognize + res.json({ + jsonrpc: "2.0", + error: { + code: -32603, + message: "Unauthorized: Missing or invalid Bearer token (401)", + }, + id: null, + }); + return; + } + + const token = authHeader.substring(7); // Remove "Bearer " prefix + + // Verify token (simplified for test server - in production, use proper JWT verification) + if (!isValidToken(token, config)) { + // Return 401 - the SDK's transport should detect this and throw an error + res.status(401); + res.setHeader("Content-Type", "application/json"); + res.setHeader("WWW-Authenticate", "Bearer"); + // Return a JSON-RPC error response format that the SDK will recognize + res.json({ + jsonrpc: "2.0", + error: { + code: -32603, + message: "Unauthorized: Invalid or expired token (401)", + }, + id: null, + }); + return; + } + + // Attach token info to request for use in handlers + (req as any).oauthToken = token; + next(); + }; +} + +/** + * Set up OAuth metadata endpoints (RFC 8414) + */ +function setupMetadataEndpoints( + app: express.Application, + config: OAuthConfig, + issuerUrl: URL, +): void { + const scopes = config.scopesSupported || ["mcp"]; + + // OAuth Authorization Server Metadata + app.get( + "/.well-known/oauth-authorization-server", + (req: Request, res: Response) => { + // Use request's host to get actual server URL (since port is assigned dynamically) + const requestBaseUrl = `${req.protocol}://${req.get("host")}`; + const actualIssuerUrl = new URL(requestBaseUrl); + const metadata = { + issuer: actualIssuerUrl.href, + authorization_endpoint: new URL("/oauth/authorize", actualIssuerUrl) + .href, + token_endpoint: new URL("/oauth/token", actualIssuerUrl).href, + scopes_supported: scopes, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], // PKCE support + token_endpoint_auth_methods_supported: ["client_secret_basic", "none"], + ...(config.supportDCR && { + registration_endpoint: new URL("/oauth/register", actualIssuerUrl) + .href, + }), + ...(config.supportCIMD && { + client_id_metadata_document_supported: true, + }), + }; + + res.json(metadata); + }, + ); + + // OAuth Protected Resource Metadata + app.get( + "/.well-known/oauth-protected-resource", + (req: Request, res: Response) => { + // Use request's host so resource matches actual server URL (port 0 → assigned port) + const requestBaseUrl = `${req.protocol}://${req.get("host")}`; + const actualResourceUrl = new URL("/", requestBaseUrl).href; + const metadata = { + resource: actualResourceUrl, + authorization_servers: [actualResourceUrl], + scopes_supported: scopes, + }; + + res.json(metadata); + }, + ); +} + +/** + * Set up OAuth authorization endpoint + * For test servers, this auto-approves requests and redirects with authorization code + */ +function setupAuthorizationEndpoint( + app: express.Application, + config: OAuthConfig, + issuerUrl: URL, +): void { + app.get("/oauth/authorize", async (req: Request, res: Response) => { + const { + client_id, + redirect_uri, + response_type, + scope, + state, + code_challenge, + code_challenge_method, + } = req.query; + + // Validate required parameters + if (!client_id || !redirect_uri || !response_type) { + res.status(400).json({ + error: "invalid_request", + error_description: "Missing required parameters", + }); + return; + } + + if (response_type !== "code") { + res.status(400).json({ error: "unsupported_response_type" }); + return; + } + + // Validate client (check static clients, DCR, or CIMD) + const client = await findClient(client_id as string, config); + if (!client) { + res.status(400).json({ error: "invalid_client" }); + return; + } + + // Validate redirect_uri + if ( + client.redirectUris && + !client.redirectUris.includes(redirect_uri as string) + ) { + res.status(400).json({ + error: "invalid_request", + error_description: "Invalid redirect_uri", + }); + return; + } + + // Validate PKCE + if (code_challenge_method && code_challenge_method !== "S256") { + res.status(400).json({ + error: "invalid_request", + error_description: "Unsupported code_challenge_method", + }); + return; + } + + // For test servers, auto-approve and generate authorization code + const authCode = generateAuthorizationCode( + client_id as string, + code_challenge as string | undefined, + ); + + // Store authorization code temporarily (in production, use proper storage) + storeAuthorizationCode(authCode, { + clientId: client_id as string, + redirectUri: redirect_uri as string, + codeChallenge: code_challenge as string | undefined, + scope: scope as string | undefined, + }); + + // Redirect with authorization code + const redirectUrl = new URL(redirect_uri as string); + redirectUrl.searchParams.set("code", authCode); + if (state) { + redirectUrl.searchParams.set("state", state as string); + } + + res.redirect(redirectUrl.href); + }); +} + +/** + * Set up OAuth token endpoint + */ +function setupTokenEndpoint( + app: express.Application, + config: OAuthConfig, + issuerUrl: URL, +): void { + app.post( + "/oauth/token", + express.urlencoded({ extended: true }), + async (req: Request, res: Response) => { + const { + grant_type, + code, + redirect_uri, + client_id: bodyClientId, + code_verifier, + refresh_token, + } = req.body; + + // Extract client_id from either body (client_secret_post) or Authorization header (client_secret_basic) + let client_id = bodyClientId; + let client_secret: string | undefined; + + // Check Authorization header for client_secret_basic + const authHeader = req.headers.authorization; + if (authHeader && authHeader.startsWith("Basic ")) { + const credentials = Buffer.from(authHeader.slice(6), "base64").toString( + "utf-8", + ); + const [id, secret] = credentials.split(":", 2); + client_id = id; + client_secret = secret; + } + + if (grant_type === "authorization_code") { + // Authorization code flow + if (!code || !redirect_uri || !client_id) { + res.status(400).json({ + error: "invalid_request", + error_description: "Missing required parameters", + }); + return; + } + + const authCodeData = getAuthorizationCode(code); + if (!authCodeData) { + res.status(400).json({ + error: "invalid_grant", + error_description: "Invalid or expired authorization code", + }); + return; + } + + // Verify client + const client = await findClient(client_id, config); + if (!client || client.clientId !== authCodeData.clientId) { + res.status(400).json({ error: "invalid_client" }); + return; + } + + // Verify client secret if provided (for client_secret_basic) + if ( + client_secret && + client.clientSecret && + client.clientSecret !== client_secret + ) { + res.status(400).json({ error: "invalid_client" }); + return; + } + + // Verify redirect_uri + if (authCodeData.redirectUri !== redirect_uri) { + res.status(400).json({ + error: "invalid_grant", + error_description: "Redirect URI mismatch", + }); + return; + } + + // Verify PKCE code verifier + if (authCodeData.codeChallenge) { + if (!code_verifier) { + res.status(400).json({ + error: "invalid_request", + error_description: "code_verifier required", + }); + return; + } + // Proper PKCE verification: code_challenge should be base64url(SHA256(code_verifier)) + const crypto = require("node:crypto"); + const hash = crypto + .createHash("sha256") + .update(code_verifier) + .digest(); + // Convert to base64url (replace + with -, / with _, remove padding) + const expectedChallenge = hash + .toString("base64") + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=/g, ""); + if (authCodeData.codeChallenge !== expectedChallenge) { + res.status(400).json({ + error: "invalid_grant", + error_description: "Invalid code_verifier", + }); + return; + } + } + + // Generate access token + const accessToken = generateAccessToken(client_id, authCodeData.scope); + const tokenExpiration = config.tokenExpirationSeconds || 3600; + + const response: any = { + access_token: accessToken, + token_type: "Bearer", + expires_in: tokenExpiration, + scope: authCodeData.scope || config.scopesSupported?.[0] || "mcp", + }; + + // Add refresh token if supported + if (config.supportRefreshTokens !== false) { + const refreshToken = generateRefreshToken(client_id); + response.refresh_token = refreshToken; + storeRefreshToken(refreshToken, { + clientId: client_id, + scope: authCodeData.scope, + }); + } + + res.json(response); + } else if (grant_type === "refresh_token") { + // Refresh token flow + if (!refresh_token || !client_id) { + res.status(400).json({ error: "invalid_request" }); + return; + } + + const refreshTokenData = getRefreshToken(refresh_token); + if (!refreshTokenData || refreshTokenData.clientId !== client_id) { + res.status(400).json({ error: "invalid_grant" }); + return; + } + + const accessToken = generateAccessToken( + client_id, + refreshTokenData.scope, + ); + const tokenExpiration = config.tokenExpirationSeconds || 3600; + + res.json({ + access_token: accessToken, + token_type: "Bearer", + expires_in: tokenExpiration, + scope: refreshTokenData.scope || config.scopesSupported?.[0] || "mcp", + }); + } else { + res.status(400).json({ error: "unsupported_grant_type" }); + } + }, + ); +} + +/** + * Set up Dynamic Client Registration endpoint + */ +function setupDCREndpoint( + app: express.Application, + config: OAuthConfig, + issuerUrl: URL, +): void { + app.post("/oauth/register", express.json(), (req: Request, res: Response) => { + const { redirect_uris, client_name, scope } = req.body; + + if ( + !redirect_uris || + !Array.isArray(redirect_uris) || + redirect_uris.length === 0 + ) { + res.status(400).json({ error: "invalid_client_metadata" }); + return; + } + + dcrRequests.push({ redirect_uris: [...redirect_uris] }); + + // Generate client ID and secret + const clientId = generateClientId(); + const clientSecret = generateClientSecret(); + + // Store registered client + registerClient(clientId, { + clientSecret, + redirectUris: redirect_uris, + clientName: client_name, + scope, + }); + + res.status(201).json({ + client_id: clientId, + client_secret: clientSecret, + redirect_uris, + ...(client_name && { client_name }), + ...(scope && { scope }), + }); + }); +} + +// In-memory storage for test server (simplified - not production-ready) +interface AuthorizationCodeData { + clientId: string; + redirectUri: string; + codeChallenge?: string; + scope?: string; + expiresAt: number; +} + +interface RefreshTokenData { + clientId: string; + scope?: string; +} + +interface RegisteredClient { + clientSecret?: string; + redirectUris: string[]; + clientName?: string; + scope?: string; +} + +const authorizationCodes = new Map(); +const accessTokens = new Set(); +const refreshTokens = new Map(); +const registeredClients = new Map(); + +/** Recorded DCR request bodies (redirect_uris) for tests that verify both URLs are registered. */ +const dcrRequests: Array<{ redirect_uris: string[] }> = []; + +/** + * Check if a string is a valid URL + */ +function isUrl(str: string): boolean { + try { + new URL(str); + return true; + } catch { + return false; + } +} + +/** + * Fetch client metadata document from URL (for CIMD) + */ +async function fetchClientMetadata(metadataUrl: string): Promise<{ + redirect_uris: string[]; + token_endpoint_auth_method?: string; + grant_types?: string[]; + response_types?: string[]; + client_name?: string; + client_uri?: string; + scope?: string; +} | null> { + try { + const response = await fetch(metadataUrl); + if (!response.ok) { + return null; + } + const metadata = await response.json(); + return metadata; + } catch { + return null; + } +} + +async function findClient( + clientId: string, + config: OAuthConfig, +): Promise<{ + clientId: string; + clientSecret?: string; + redirectUris?: string[]; +} | null> { + // Check static clients first + if (config.staticClients) { + const staticClient = config.staticClients.find( + (c) => c.clientId === clientId, + ); + if (staticClient) { + return { + clientId: staticClient.clientId, + clientSecret: staticClient.clientSecret, + redirectUris: staticClient.redirectUris, + }; + } + } + + // Check registered clients (DCR) + if (registeredClients.has(clientId)) { + const client = registeredClients.get(clientId)!; + return { + clientId, + clientSecret: client.clientSecret, + redirectUris: client.redirectUris, + }; + } + + // Check CIMD: if client_id is a URL and CIMD is supported, fetch metadata + if (config.supportCIMD && isUrl(clientId)) { + const metadata = await fetchClientMetadata(clientId); + if ( + metadata && + metadata.redirect_uris && + Array.isArray(metadata.redirect_uris) + ) { + // For CIMD, the client_id is the URL itself, and there's no client_secret + // (CIMD uses token_endpoint_auth_method: "none" typically) + return { + clientId, // The URL is the client_id + clientSecret: undefined, // CIMD typically doesn't use secrets + redirectUris: metadata.redirect_uris, + }; + } + } + + return null; +} + +function generateAuthorizationCode( + clientId: string, + codeChallenge?: string, +): string { + return `test_auth_code_${Date.now()}_${Math.random().toString(36).substring(7)}`; +} + +function storeAuthorizationCode( + code: string, + data: Omit, +): void { + authorizationCodes.set(code, { + ...data, + expiresAt: Date.now() + 60000, // 1 minute expiration + }); +} + +function getAuthorizationCode(code: string): AuthorizationCodeData | null { + const data = authorizationCodes.get(code); + if (!data) { + return null; + } + + // Check expiration + if (Date.now() > data.expiresAt) { + authorizationCodes.delete(code); + return null; + } + + // Delete after use (authorization codes are single-use) + authorizationCodes.delete(code); + return data; +} + +function generateAccessToken(clientId: string, scope?: string): string { + const token = `test_access_token_${Date.now()}_${Math.random().toString(36).substring(7)}`; + accessTokens.add(token); + return token; +} + +function generateRefreshToken(clientId: string): string { + return `test_refresh_token_${Date.now()}_${Math.random().toString(36).substring(7)}`; +} + +function storeRefreshToken(token: string, data: RefreshTokenData): void { + refreshTokens.set(token, data); +} + +function getRefreshToken(token: string): RefreshTokenData | null { + return refreshTokens.get(token) || null; +} + +function generateClientId(): string { + return `test_client_${Date.now()}_${Math.random().toString(36).substring(7)}`; +} + +function generateClientSecret(): string { + return `test_secret_${Math.random().toString(36).substring(2, 15)}`; +} + +function registerClient(clientId: string, client: RegisteredClient): void { + registeredClients.set(clientId, client); +} + +function isValidToken(token: string, config: OAuthConfig): boolean { + // Simplified token validation for test server + // In production, verify JWT signature, expiration, etc. + return accessTokens.has(token); +} + +/** + * Clear all OAuth test data (useful for test cleanup) + */ +export function clearOAuthTestData(): void { + authorizationCodes.clear(); + accessTokens.clear(); + refreshTokens.clear(); + registeredClients.clear(); + dcrRequests.length = 0; +} + +/** + * Returns recorded DCR request bodies (redirect_uris) for tests that verify + * both normal and guided redirect URLs are registered. + */ +export function getDCRRequests(): Array<{ redirect_uris: string[] }> { + return dcrRequests; +} + +/** + * Invalidate a single access token (remove from valid set). + * Used by E2E tests to simulate expired/revoked access token while keeping + * refresh_token valid, so 401 → auth() → refresh → retry can be exercised. + */ +export function invalidateAccessToken(token: string): void { + accessTokens.delete(token); +} diff --git a/shared/test/test-server-stdio.ts b/shared/test/test-server-stdio.ts new file mode 100644 index 000000000..c3b593acd --- /dev/null +++ b/shared/test/test-server-stdio.ts @@ -0,0 +1,135 @@ +#!/usr/bin/env node + +/** + * Test MCP server for stdio transport testing + * Can be used programmatically or run as a standalone executable + */ + +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import * as z from "zod/v4"; +import path from "path"; +import { fileURLToPath } from "url"; +import { dirname } from "path"; +import type { + ServerConfig, + ResourceDefinition, +} from "./test-server-fixtures.js"; +import { + getDefaultServerConfig, + createMcpServer, +} from "./test-server-fixtures.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +export class TestServerStdio { + private mcpServer: McpServer; + private config: ServerConfig; + private transport?: StdioServerTransport; + + constructor(config: ServerConfig) { + // Provide callback to customize resource handlers for stdio-specific dynamic resources + const configWithCallback: ServerConfig = { + ...config, + onRegisterResource: (resource: ResourceDefinition) => { + // Only provide custom handler for dynamic resources + if ( + resource.name === "test-cwd" || + resource.name === "test-env" || + resource.name === "test-argv" + ) { + return async () => { + let text: string; + if (resource.name === "test-cwd") { + text = process.cwd(); + } else if (resource.name === "test-env") { + text = JSON.stringify(process.env, null, 2); + } else if (resource.name === "test-argv") { + text = JSON.stringify(process.argv, null, 2); + } else { + text = resource.text ?? ""; + } + + return { + contents: [ + { + uri: resource.uri, + mimeType: resource.mimeType || "text/plain", + text, + }, + ], + }; + }; + } + // Return undefined to use default handler + return undefined; + }, + }; + this.config = config; + this.mcpServer = createMcpServer(configWithCallback); + } + + /** + * Start the server with stdio transport + */ + async start(): Promise { + this.transport = new StdioServerTransport(); + await this.mcpServer.connect(this.transport); + } + + /** + * Stop the server + */ + async stop(): Promise { + await this.mcpServer.close(); + if (this.transport) { + await this.transport.close(); + this.transport = undefined; + } + } +} + +/** + * Create a stdio MCP test server + */ +export function createTestServerStdio(config: ServerConfig): TestServerStdio { + return new TestServerStdio(config); +} + +/** + * Get the path to the test MCP server script + */ +export function getTestMcpServerPath(): string { + return path.resolve(__dirname, "test-server-stdio.ts"); +} + +/** + * Get the command and args to run the test MCP server + */ +export function getTestMcpServerCommand(): { command: string; args: string[] } { + return { + command: "tsx", + args: [getTestMcpServerPath()], + }; +} + +// If run as a standalone script, start with default config +// Check if this file is being executed directly (not imported) +const isMainModule = + import.meta.url.endsWith(process.argv[1] || "") || + (process.argv[1]?.endsWith("test-server-stdio.ts") ?? false) || + (process.argv[1]?.endsWith("test-server-stdio.js") ?? false); + +if (isMainModule) { + const server = new TestServerStdio(getDefaultServerConfig()); + server + .start() + .then(() => { + // Server is now running and listening on stdio + // Keep the process alive + }) + .catch((error) => { + console.error("Failed to start test MCP server:", error); + process.exit(1); + }); +} diff --git a/shared/tsconfig.json b/shared/tsconfig.json new file mode 100644 index 000000000..aa7308259 --- /dev/null +++ b/shared/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "./build", + "rootDir": ".", + "composite": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "noUncheckedIndexedAccess": true + }, + "include": [ + "mcp/**/*.ts", + "react/**/*.ts", + "react/**/*.tsx", + "json/**/*.ts", + "test/**/*.ts", + "__tests__/**/*.ts", + "auth/**/*.ts", + "storage/**/*.ts" + ], + "exclude": ["node_modules", "build"] +} diff --git a/shared/vitest.config.ts b/shared/vitest.config.ts new file mode 100644 index 000000000..39dfc5005 --- /dev/null +++ b/shared/vitest.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + globals: true, + environment: "node", + include: ["**/__tests__/**/*.test.ts"], + testTimeout: 30000, // 30 seconds - e2e tests spawn servers + hookTimeout: 30000, // 30 seconds - before/after hooks may start/stop servers + }, +}); diff --git a/tui/package.json b/tui/package.json new file mode 100644 index 000000000..a0ef2975c --- /dev/null +++ b/tui/package.json @@ -0,0 +1,42 @@ +{ + "name": "@modelcontextprotocol/inspector-tui", + "version": "0.20.0", + "description": "Terminal User Interface (TUI) for the Model Context Protocol inspector", + "license": "MIT", + "author": { + "name": "Bob Dickinson (TeamSpark AI)", + "email": "bob@teamspark.ai" + }, + "homepage": "https://modelcontextprotocol.io", + "bugs": "https://github.com/modelcontextprotocol/inspector/issues", + "type": "module", + "main": "build/tui.js", + "bin": { + "mcp-inspector-tui": "./build/tui.js" + }, + "files": [ + "build" + ], + "scripts": { + "build": "tsc", + "dev": "NODE_PATH=../node_modules:./node_modules:$NODE_PATH tsx tui.tsx" + }, + "dependencies": { + "@modelcontextprotocol/inspector-shared": "*", + "pino": "^9.6.0", + "commander": "^13.1.0", + "@modelcontextprotocol/sdk": "^1.25.2", + "fullscreen-ink": "^0.1.0", + "ink": "^5.2.1", + "ink-form": "^2.0.1", + "ink-scroll-view": "^0.3.6", + "open": "^10.2.0", + "react": "^18.3.1" + }, + "devDependencies": { + "@types/node": "^25.0.3", + "@types/react": "^18.3.23", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/tui/src/App.tsx b/tui/src/App.tsx new file mode 100644 index 000000000..9798a6bc7 --- /dev/null +++ b/tui/src/App.tsx @@ -0,0 +1,1656 @@ +import React, { + useState, + useMemo, + useEffect, + useCallback, + useRef, +} from "react"; +import { Box, Text, useInput, useApp, type Key } from "ink"; +import { readFileSync } from "fs"; +import { fileURLToPath } from "url"; +import { dirname, join } from "path"; +import type { + MessageEntry, + FetchRequestEntry, + MCPServerConfig, + InspectorClientOptions, + InspectorClientEnvironment, +} from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { + loadMcpServersConfig, + createTransportNode, +} from "@modelcontextprotocol/inspector-shared/mcp/node/index.js"; +import { useInspectorClient } from "@modelcontextprotocol/inspector-shared/react/useInspectorClient.js"; +import { + CallbackNavigation, + MutableRedirectUrlProvider, +} from "@modelcontextprotocol/inspector-shared/auth"; +import { + createOAuthCallbackServer, + type OAuthCallbackServer, + NodeOAuthStorage, +} from "@modelcontextprotocol/inspector-shared/auth/node/index.js"; +import { tuiLogger } from "./logger.js"; +import { openUrl } from "./utils/openUrl.js"; +import { Tabs, type TabType, tabs as tabList } from "./components/Tabs.js"; +import { InfoTab } from "./components/InfoTab.js"; +import { AuthTab } from "./components/AuthTab.js"; +import { ResourcesTab } from "./components/ResourcesTab.js"; +import { PromptsTab } from "./components/PromptsTab.js"; +import { ToolsTab } from "./components/ToolsTab.js"; +import { NotificationsTab } from "./components/NotificationsTab.js"; +import { HistoryTab } from "./components/HistoryTab.js"; +import { RequestsTab } from "./components/RequestsTab.js"; +import { ToolTestModal } from "./components/ToolTestModal.js"; +import { ResourceTestModal } from "./components/ResourceTestModal.js"; +import { PromptTestModal } from "./components/PromptTestModal.js"; +import { DetailsModal } from "./components/DetailsModal.js"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = dirname(__filename); + +// Read package.json to get project info +// Strategy: Try multiple paths to handle both local dev and global install +// - Local dev (tsx): __dirname = src/, package.json is one level up +// - Global install: __dirname = dist/src/, package.json is two levels up +let packagePath: string; +let packageJson: { name: string; description: string; version: string }; + +try { + // Try two levels up first (global install case) + packagePath = join(__dirname, "..", "..", "package.json"); + packageJson = JSON.parse(readFileSync(packagePath, "utf-8")) as { + name: string; + description: string; + version: string; + }; +} catch { + // Fall back to one level up (local dev case) + packagePath = join(__dirname, "..", "package.json"); + packageJson = JSON.parse(readFileSync(packagePath, "utf-8")) as { + name: string; + description: string; + version: string; + }; +} + +// Focus management types +type FocusArea = + | "serverList" + | "tabs" + // Used by Resources/Prompts/Tools - list pane + | "tabContentList" + // Used by Resources/Prompts/Tools - details pane + | "tabContentDetails" + // Used only when activeTab === 'messages' + | "messagesList" + | "messagesDetail" + // Used only when activeTab === 'requests' + | "requestsList" + | "requestsDetail"; + +interface AppProps { + configFile: string; + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + callbackUrlConfig: { + hostname: string; + port: number; + pathname: string; + }; +} + +/** HTTP transports (SSE, streamable-http) can use OAuth. No config gate. */ +function isOAuthCapableServer(config: MCPServerConfig | null): boolean { + if (!config) return false; + const c = config as MCPServerConfig & { oauth?: unknown }; + return c.type === "sse" || c.type === "streamable-http"; +} + +function App({ + configFile, + clientId, + clientSecret, + clientMetadataUrl, + callbackUrlConfig, +}: AppProps) { + const { exit } = useApp(); + const callbackServerBaseOptions = useMemo( + () => ({ + port: callbackUrlConfig.port, + hostname: callbackUrlConfig.hostname, + path: callbackUrlConfig.pathname, + }), + [callbackUrlConfig], + ); + + useEffect(() => { + tuiLogger.info({ configFile }, "TUI started"); + }, [configFile]); + + const [selectedServer, setSelectedServer] = useState(null); + const [activeTab, setActiveTab] = useState("info"); + const [focus, setFocus] = useState("serverList"); + const [tabCounts, setTabCounts] = useState<{ + info?: number; + resources?: number; + prompts?: number; + tools?: number; + messages?: number; + requests?: number; + logging?: number; + }>({}); + const [oauthStatus, setOauthStatus] = useState< + "idle" | "authenticating" | "success" | "error" + >("idle"); + const [oauthMessage, setOauthMessage] = useState(null); + const oauthInProgressRef = useRef(false); + const [selectedAuthAction, setSelectedAuthAction] = useState< + "guided" | "quick" | "clear" + >("guided"); + + // Tool test modal state + const [toolTestModal, setToolTestModal] = useState<{ + tool: any; + inspectorClient: InspectorClient | null; + } | null>(null); + + // Resource test modal state + const [resourceTestModal, setResourceTestModal] = useState<{ + template: { + name: string; + uriTemplate: string; + description?: string; + }; + inspectorClient: InspectorClient | null; + } | null>(null); + + // Prompt test modal state + const [promptTestModal, setPromptTestModal] = useState<{ + prompt: { + name: string; + description?: string; + arguments?: any[]; + }; + inspectorClient: InspectorClient | null; + } | null>(null); + + // Details modal state + const [detailsModal, setDetailsModal] = useState<{ + title: string; + content: React.ReactNode; + } | null>(null); + + // InspectorClient instances for each server + const [inspectorClients, setInspectorClients] = useState< + Record + >({}); + const [dimensions, setDimensions] = useState({ + width: process.stdout.columns || 80, + height: process.stdout.rows || 24, + }); + + useEffect(() => { + const updateDimensions = () => { + setDimensions({ + width: process.stdout.columns || 80, + height: process.stdout.rows || 24, + }); + }; + + process.stdout.on("resize", updateDimensions); + return () => { + process.stdout.off("resize", updateDimensions); + }; + }, []); + + // Parse MCP configuration + const mcpConfig = useMemo(() => { + try { + return loadMcpServersConfig(configFile); + } catch (error) { + if (error instanceof Error) { + console.error(error.message); + } else { + console.error("Error loading configuration: Unknown error"); + } + process.exit(1); + } + }, [configFile]); + + const serverNames = Object.keys(mcpConfig.mcpServers); + const selectedServerConfig = selectedServer + ? mcpConfig.mcpServers[selectedServer] + : null; + + // Mutable redirect URL providers, keyed by server name (populated before authenticate) + const redirectUrlProvidersRef = useRef< + Record + >({}); + + // Create InspectorClient instances for each server on mount + useEffect(() => { + const newClients: Record = {}; + for (const serverName of serverNames) { + if (!(serverName in inspectorClients)) { + const serverConfig = mcpConfig.mcpServers[ + serverName + ] as MCPServerConfig & { + oauth?: Record; + }; + const environment: InspectorClientEnvironment = { + transport: createTransportNode, + logger: tuiLogger, + }; + const opts: InspectorClientOptions = { + environment, + maxMessages: 1000, + maxStderrLogEvents: 1000, + maxFetchRequests: 1000, + pipeStderr: true, + }; + if (isOAuthCapableServer(serverConfig)) { + const oauthFromConfig = serverConfig.oauth as + | { storagePath?: string } + | undefined; + const redirectUrlProvider = + redirectUrlProvidersRef.current[serverName] ?? + (redirectUrlProvidersRef.current[serverName] = + new MutableRedirectUrlProvider()); + environment.oauth = { + storage: new NodeOAuthStorage(oauthFromConfig?.storagePath), + navigation: new CallbackNavigation( + async (url) => await openUrl(url), + ), + redirectUrlProvider, + }; + opts.oauth = { + ...(serverConfig.oauth || {}), + ...(clientId && { clientId }), + ...(clientSecret && { clientSecret }), + ...(clientMetadataUrl && { clientMetadataUrl }), + }; + } + newClients[serverName] = new InspectorClient(serverConfig, opts); + } + } + if (Object.keys(newClients).length > 0) { + setInspectorClients((prev) => ({ ...prev, ...newClients })); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [clientId, clientSecret, clientMetadataUrl]); + + // Cleanup: disconnect all clients on unmount + useEffect(() => { + return () => { + Object.values(inspectorClients).forEach((client) => { + client.disconnect().catch(() => { + // Ignore errors during cleanup + }); + }); + }; + }, [inspectorClients]); + + // Preselect the first server on mount + useEffect(() => { + if (serverNames.length > 0 && selectedServer === null) { + setSelectedServer(serverNames[0]); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + // Clear OAuth status when switching servers + useEffect(() => { + setOauthStatus("idle"); + setOauthMessage(null); + }, [selectedServer]); + + // Switch away from Auth tab when server is not OAuth-capable + useEffect(() => { + if ( + activeTab === "auth" && + selectedServerConfig && + !isOAuthCapableServer(selectedServerConfig) + ) { + setActiveTab("info"); + } + }, [activeTab, selectedServerConfig]); + + // Get InspectorClient for selected server + const selectedInspectorClient = useMemo( + () => (selectedServer ? inspectorClients[selectedServer] : null), + [selectedServer, inspectorClients], + ); + + // Use the hook to get reactive state from InspectorClient + const { + status: inspectorStatus, + messages: inspectorMessages, + stderrLogs: inspectorStderrLogs, + fetchRequests: inspectorFetchRequests, + tools: inspectorTools, + resources: inspectorResources, + resourceTemplates: inspectorResourceTemplates, + prompts: inspectorPrompts, + capabilities: inspectorCapabilities, + serverInfo: inspectorServerInfo, + instructions: inspectorInstructions, + client: inspectorClient, + connect: connectInspector, + disconnect: disconnectInspector, + } = useInspectorClient(selectedInspectorClient); + + // Connect handler - InspectorClient now handles fetching server data automatically + const handleConnect = useCallback(async () => { + if (!selectedServer || !selectedInspectorClient) return; + + try { + await connectInspector(); + // InspectorClient automatically fetches server data (capabilities, tools, resources, resource templates, prompts, etc.) + // on connect, so we don't need to do anything here + } catch (error) { + // Error handling is done by InspectorClient and will be reflected in status + } + }, [selectedServer, selectedInspectorClient, connectInspector]); + + // Disconnect handler + const handleDisconnect = useCallback(async () => { + if (!selectedServer) return; + await disconnectInspector(); + // InspectorClient will update status automatically, and data is preserved + }, [selectedServer, disconnectInspector]); + + // Shared ref for OAuth callback server; stop before starting new (avoids EADDRINUSE when prior auth failed without redirect) + const callbackServerRef = useRef(null); + + // OAuth Quick Auth (normal mode; callback server + open URL) + const handleQuickAuth = useCallback(async () => { + if ( + !selectedServer || + !selectedInspectorClient || + !selectedServerConfig || + !isOAuthCapableServer(selectedServerConfig) + ) { + return; + } + if (oauthInProgressRef.current) return; + oauthInProgressRef.current = true; + setOauthStatus("authenticating"); + setOauthMessage(null); + tuiLogger.info( + { server: selectedServer }, + "OAuth authentication started (Quick Auth)", + ); + const existing = callbackServerRef.current; + if (existing) { + await existing.stop(); + callbackServerRef.current = null; + } + const callbackServer = createOAuthCallbackServer(); + callbackServerRef.current = callbackServer; + let flowResolve: () => void; + let flowReject: (err: Error) => void; + const flowDone = new Promise((resolve, reject) => { + flowResolve = resolve; + flowReject = reject; + }); + try { + const { redirectUrl } = await callbackServer.start({ + ...callbackServerBaseOptions, + onCallback: async (params) => { + try { + await selectedInspectorClient!.completeOAuthFlow(params.code); + flowResolve!(); + } catch (err) { + flowReject!(err instanceof Error ? err : new Error(String(err))); + } finally { + callbackServerRef.current = null; + } + }, + onError: (params) => { + flowReject!( + new Error( + params.error_description ?? params.error ?? "OAuth error", + ), + ); + void callbackServer.stop(); + callbackServerRef.current = null; + }, + }); + const redirectUrlProvider = + redirectUrlProvidersRef.current[selectedServer]; + if (redirectUrlProvider) { + redirectUrlProvider.redirectUrl = redirectUrl; + } + await selectedInspectorClient.authenticate(); + await flowDone; + setOauthStatus("success"); + setOauthMessage("OAuth complete. Press C to connect."); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + setOauthStatus("error"); + setOauthMessage(msg); + } finally { + oauthInProgressRef.current = false; + } + }, [selectedServer, selectedInspectorClient, selectedServerConfig]); + + // OAuth Guided Auth - step-by-step + const handleGuidedStart = useCallback(async () => { + if ( + !selectedServer || + !selectedInspectorClient || + !selectedServerConfig || + !isOAuthCapableServer(selectedServerConfig) + ) { + return; + } + if (oauthInProgressRef.current) return; + oauthInProgressRef.current = true; + setOauthStatus("authenticating"); + setOauthMessage(null); + tuiLogger.info( + { server: selectedServer }, + "OAuth authentication started (Guided Auth)", + ); + // Stop any previous callback server (e.g. from failed auth where AS never redirected) + const existing = callbackServerRef.current; + if (existing) { + await existing.stop(); + callbackServerRef.current = null; + } + const callbackServer = createOAuthCallbackServer(); + callbackServerRef.current = callbackServer; + try { + const { redirectUrl } = await callbackServer.start({ + ...callbackServerBaseOptions, + onCallback: async (params) => { + try { + await selectedInspectorClient!.completeOAuthFlow(params.code); + setOauthStatus("success"); + setOauthMessage("OAuth complete. Press C to connect."); + } catch (err) { + setOauthStatus("error"); + setOauthMessage(err instanceof Error ? err.message : String(err)); + } finally { + callbackServerRef.current = null; + } + }, + onError: (params) => { + setOauthStatus("error"); + setOauthMessage( + params.error_description ?? params.error ?? "OAuth error", + ); + void callbackServer.stop(); + callbackServerRef.current = null; + }, + }); + const redirectUrlProvider = + redirectUrlProvidersRef.current[selectedServer]; + if (redirectUrlProvider) { + redirectUrlProvider.redirectUrl = redirectUrl; + } + await selectedInspectorClient.beginGuidedAuth(); + setOauthStatus("idle"); + } catch (err) { + setOauthStatus("error"); + setOauthMessage(err instanceof Error ? err.message : String(err)); + } finally { + oauthInProgressRef.current = false; + } + }, [selectedServer, selectedInspectorClient, selectedServerConfig]); + + const handleGuidedAdvance = useCallback(async () => { + if (!selectedInspectorClient) return; + if (oauthInProgressRef.current) return; + oauthInProgressRef.current = true; + setOauthStatus("authenticating"); + setOauthMessage(null); + tuiLogger.info("OAuth authentication started (Guided Auth advance step)"); + try { + await selectedInspectorClient.proceedOAuthStep(); + const state = selectedInspectorClient.getOAuthState(); + if (state?.oauthStep === "authorization_code" && state.authorizationUrl) { + await openUrl(state.authorizationUrl); + } + setOauthStatus("idle"); + } catch (err) { + setOauthStatus("error"); + setOauthMessage(err instanceof Error ? err.message : String(err)); + } finally { + oauthInProgressRef.current = false; + } + }, [selectedInspectorClient]); + + const handleRunGuidedToCompletion = useCallback(async () => { + if ( + !selectedServer || + !selectedInspectorClient || + !selectedServerConfig || + !isOAuthCapableServer(selectedServerConfig) + ) { + return; + } + if (oauthInProgressRef.current) return; + oauthInProgressRef.current = true; + setOauthStatus("authenticating"); + setOauthMessage(null); + tuiLogger.info( + { server: selectedServer }, + "OAuth authentication started (Run Guided Auth to completion)", + ); + + const ensureCallbackServer = async () => { + if (callbackServerRef.current) return; + const callbackServer = createOAuthCallbackServer(); + callbackServerRef.current = callbackServer; + const { redirectUrl } = await callbackServer.start({ + ...callbackServerBaseOptions, + onCallback: async (params) => { + try { + await selectedInspectorClient!.completeOAuthFlow(params.code); + setOauthStatus("success"); + setOauthMessage("OAuth complete. Press C to connect."); + } catch (err) { + setOauthStatus("error"); + setOauthMessage(err instanceof Error ? err.message : String(err)); + } finally { + callbackServerRef.current = null; + } + }, + onError: (params) => { + setOauthStatus("error"); + setOauthMessage( + params.error_description ?? params.error ?? "OAuth error", + ); + void callbackServer.stop(); + callbackServerRef.current = null; + }, + }); + const redirectUrlProvider = + redirectUrlProvidersRef.current[selectedServer]; + if (redirectUrlProvider) { + redirectUrlProvider.redirectUrl = redirectUrl; + } + }; + + try { + await ensureCallbackServer(); + const authUrl = await selectedInspectorClient.runGuidedAuth(); + if (authUrl) { + await openUrl(authUrl); + } + setOauthStatus("idle"); + } catch (err) { + setOauthStatus("error"); + setOauthMessage(err instanceof Error ? err.message : String(err)); + } finally { + oauthInProgressRef.current = false; + } + }, [selectedServer, selectedInspectorClient, selectedServerConfig]); + + const handleClearOAuth = useCallback(() => { + if (selectedInspectorClient) { + selectedInspectorClient.clearOAuthTokens(); + setOauthStatus("idle"); + setOauthMessage(null); + } + }, [selectedInspectorClient]); + + // Build current server state from InspectorClient data + const currentServerState = useMemo(() => { + if (!selectedServer) return null; + return { + status: inspectorStatus, + error: null, // InspectorClient doesn't track error in state, only emits error events + capabilities: inspectorCapabilities, + serverInfo: inspectorServerInfo, + instructions: inspectorInstructions, + resources: inspectorResources, + resourceTemplates: inspectorResourceTemplates, + prompts: inspectorPrompts, + tools: inspectorTools, + stderrLogs: inspectorStderrLogs, // InspectorClient manages this + }; + }, [ + selectedServer, + inspectorStatus, + inspectorCapabilities, + inspectorServerInfo, + inspectorInstructions, + inspectorResources, + inspectorResourceTemplates, + inspectorPrompts, + inspectorTools, + inspectorStderrLogs, + ]); + + // 401 on connect → prompt to authenticate (HTTP servers). Hide during/after auth. + const show401AuthHint = useMemo(() => { + if (inspectorStatus !== "error") return false; + if (oauthStatus === "authenticating" || oauthStatus === "success") + return false; + if (!selectedServerConfig || !isOAuthCapableServer(selectedServerConfig)) + return false; + return inspectorFetchRequests.some((r) => r.responseStatus === 401); + }, [ + inspectorStatus, + oauthStatus, + selectedServerConfig, + inspectorFetchRequests, + ]); + + // Helper functions to render details modal content + const renderResourceDetails = (resource: any) => ( + <> + {resource.description && ( + <> + {resource.description.split("\n").map((line: string, idx: number) => ( + + {line} + + ))} + + )} + {resource.uri && ( + + URI: + + {resource.uri} + + + )} + {resource.mimeType && ( + + MIME Type: + + {resource.mimeType} + + + )} + + Full JSON: + + {JSON.stringify(resource, null, 2)} + + + + ); + + const renderPromptDetails = (prompt: any) => ( + <> + {prompt.description && ( + <> + {prompt.description.split("\n").map((line: string, idx: number) => ( + + {line} + + ))} + + )} + {prompt.arguments && prompt.arguments.length > 0 && ( + <> + + Arguments: + + {prompt.arguments.map((arg: any, idx: number) => ( + + + - {arg.name}: {arg.description || arg.type || "string"} + + + ))} + + )} + + Full JSON: + + {JSON.stringify(prompt, null, 2)} + + + + ); + + const renderToolDetails = (tool: any) => ( + <> + {tool.description && ( + <> + {tool.description.split("\n").map((line: string, idx: number) => ( + + {line} + + ))} + + )} + {tool.inputSchema && ( + + Input Schema: + + {JSON.stringify(tool.inputSchema, null, 2)} + + + )} + + Full JSON: + + {JSON.stringify(tool, null, 2)} + + + + ); + + const renderRequestDetails = (request: FetchRequestEntry) => ( + <> + + + {request.method} {request.url} + + + + + Category:{" "} + {request.category === "auth" ? "auth" : "transport"} + + + {request.responseStatus !== undefined ? ( + + + Status: {request.responseStatus} {request.responseStatusText || ""} + + + ) : request.error ? ( + + + Error: {request.error} + + + ) : null} + {request.duration !== undefined && ( + + + {request.timestamp.toLocaleTimeString()} ({request.duration}ms) + + + )} + + Request Headers: + {Object.entries(request.requestHeaders).map(([key, value]) => ( + + + {key}: {value} + + + ))} + + {request.requestBody && ( + <> + + Request Body: + + {(() => { + try { + const parsed = JSON.parse(request.requestBody); + return JSON.stringify(parsed, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + )); + } catch { + return ( + + {request.requestBody} + + ); + } + })()} + + )} + {request.responseHeaders && + Object.keys(request.responseHeaders).length > 0 && ( + <> + + Response Headers: + + {Object.entries(request.responseHeaders).map(([key, value]) => ( + + + {key}: {value} + + + ))} + + )} + {request.responseBody && ( + <> + + Response Body: + + {(() => { + try { + const parsed = JSON.parse(request.responseBody); + return JSON.stringify(parsed, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + )); + } catch { + return ( + + {request.responseBody} + + ); + } + })()} + + )} + + ); + + const renderMessageDetails = (message: MessageEntry) => ( + <> + + Direction: {message.direction} + + + + {message.timestamp.toLocaleTimeString()} + {message.duration !== undefined && ` (${message.duration}ms)`} + + + {message.direction === "request" ? ( + <> + + Request: + + {JSON.stringify(message.message, null, 2)} + + + {message.response && ( + + Response: + + + {JSON.stringify(message.response, null, 2)} + + + + )} + + ) : ( + + + {message.direction === "response" ? "Response:" : "Notification:"} + + + {JSON.stringify(message.message, null, 2)} + + + )} + + ); + + // Update tab counts when selected server changes or InspectorClient state changes + // Just reflect InspectorClient state - don't try to be clever + useEffect(() => { + if (!selectedServer) { + return; + } + + setTabCounts({ + resources: inspectorResources.length || 0, + prompts: inspectorPrompts.length || 0, + tools: inspectorTools.length || 0, + messages: inspectorMessages.length || 0, + requests: inspectorFetchRequests.length || 0, + logging: inspectorStderrLogs.length || 0, + }); + }, [ + selectedServer, + inspectorResources, + inspectorPrompts, + inspectorTools, + inspectorMessages, + inspectorFetchRequests, + inspectorStderrLogs, + ]); + + // Keep focus state consistent when switching tabs + useEffect(() => { + if (activeTab === "messages") { + if (focus === "tabContentList" || focus === "tabContentDetails") { + setFocus("messagesList"); + } + } else if (activeTab === "requests") { + if (focus === "tabContentList" || focus === "tabContentDetails") { + setFocus("requestsList"); + } + } else { + if ( + focus === "messagesList" || + focus === "messagesDetail" || + focus === "requestsList" || + focus === "requestsDetail" + ) { + setFocus("tabContentList"); + } + } + }, [activeTab]); // intentionally not depending on focus to avoid loops + + // Switch away from logging tab if server is not stdio + useEffect(() => { + if (activeTab === "logging" && selectedServer) { + const client = inspectorClients[selectedServer]; + if (client && client.getServerType() !== "stdio") { + setActiveTab("info"); + } + } + }, [selectedServer, activeTab, inspectorClients]); + + useInput((input: string, key: Key) => { + // Don't process input when modal is open + if (toolTestModal || resourceTestModal || promptTestModal || detailsModal) { + return; + } + + if (key.ctrl && input === "c") { + exit(); + } + + // Exit accelerators + if (key.escape) { + exit(); + } + + // G/Q/S: switch to Auth tab (if not already) and select Guided/Quick/Clear + const showAuthTabForAccel = + !!selectedServer && + !!selectedServerConfig && + isOAuthCapableServer(selectedServerConfig); + const lower = input.toLowerCase(); + if ( + showAuthTabForAccel && + (lower === "g" || lower === "q" || lower === "s") + ) { + setActiveTab("auth"); + setFocus("tabContentList"); + setSelectedAuthAction( + lower === "g" ? "guided" : lower === "q" ? "quick" : "clear", + ); + return; + } + + // Tab switching with accelerator keys (first character of tab name) + const showAuthTab = + !!selectedServer && + !!selectedServerConfig && + isOAuthCapableServer(selectedServerConfig); + const showLoggingTab = + !!selectedServer && + inspectorClients[selectedServer]?.getServerType() === "stdio"; + const showRequestsTab = + !!selectedServer && + (inspectorClients[selectedServer]?.getServerType() === "sse" || + inspectorClients[selectedServer]?.getServerType() === + "streamable-http"); + const tabAccelerators: Record = Object.fromEntries( + tabList + .filter((tab: { id: TabType }) => { + if (tab.id === "auth" && !showAuthTab) return false; + if (tab.id === "logging" && !showLoggingTab) return false; + if (tab.id === "requests" && !showRequestsTab) return false; + return true; + }) + .map((tab: { id: TabType; label: string; accelerator: string }) => [ + tab.accelerator, + tab.id, + ]), + ); + if (tabAccelerators[input.toLowerCase()]) { + setActiveTab(tabAccelerators[input.toLowerCase()]); + setFocus("tabs"); + } else if (key.tab && !key.shift) { + // Flat focus order: servers -> tabs -> list -> details -> wrap to servers + const focusOrder: FocusArea[] = + activeTab === "messages" + ? ["serverList", "tabs", "messagesList", "messagesDetail"] + : activeTab === "requests" + ? ["serverList", "tabs", "requestsList", "requestsDetail"] + : ["serverList", "tabs", "tabContentList", "tabContentDetails"]; + const currentIndex = focusOrder.indexOf(focus); + const nextIndex = (currentIndex + 1) % focusOrder.length; + setFocus(focusOrder[nextIndex]); + } else if (key.tab && key.shift) { + // Reverse order: servers <- tabs <- list <- details <- wrap to servers + const focusOrder: FocusArea[] = + activeTab === "messages" + ? ["serverList", "tabs", "messagesList", "messagesDetail"] + : activeTab === "requests" + ? ["serverList", "tabs", "requestsList", "requestsDetail"] + : ["serverList", "tabs", "tabContentList", "tabContentDetails"]; + const currentIndex = focusOrder.indexOf(focus); + const prevIndex = + currentIndex > 0 ? currentIndex - 1 : focusOrder.length - 1; + setFocus(focusOrder[prevIndex]); + } else if (key.upArrow || key.downArrow) { + // Arrow keys only work in the focused pane + if (focus === "serverList") { + // Arrow key navigation for server list + if (key.upArrow) { + if (selectedServer === null) { + setSelectedServer(serverNames[serverNames.length - 1] || null); + } else { + const currentIndex = serverNames.indexOf(selectedServer); + const newIndex = + currentIndex > 0 ? currentIndex - 1 : serverNames.length - 1; + setSelectedServer(serverNames[newIndex] || null); + } + } else if (key.downArrow) { + if (selectedServer === null) { + setSelectedServer(serverNames[0] || null); + } else { + const currentIndex = serverNames.indexOf(selectedServer); + const newIndex = + currentIndex < serverNames.length - 1 ? currentIndex + 1 : 0; + setSelectedServer(serverNames[newIndex] || null); + } + } + return; // Handled, don't let other handlers process + } + // If focus is on tabs, tabContentList, tabContentDetails, messagesList, or messagesDetail, + // arrow keys will be handled by those components - don't do anything here + } else if (focus === "tabs" && (key.leftArrow || key.rightArrow)) { + // Left/Right arrows switch tabs when tabs are focused + const showAuthTab = + !!selectedServer && + !!selectedServerConfig && + isOAuthCapableServer(selectedServerConfig); + const showLoggingTab = + !!selectedServer && + inspectorClients[selectedServer]?.getServerType() === "stdio"; + const showRequestsTab = + !!selectedServer && + (inspectorClients[selectedServer]?.getServerType() === "sse" || + inspectorClients[selectedServer]?.getServerType() === + "streamable-http"); + const allTabs: TabType[] = [ + "info", + "auth", + "resources", + "prompts", + "tools", + "messages", + "requests", + "logging", + ]; + const tabs = allTabs.filter((t) => { + if (t === "auth" && !showAuthTab) return false; + if (t === "logging" && !showLoggingTab) return false; + if (t === "requests" && !showRequestsTab) return false; + return true; + }); + const currentIndex = tabs.indexOf(activeTab); + if (key.leftArrow) { + const newIndex = currentIndex > 0 ? currentIndex - 1 : tabs.length - 1; + setActiveTab(tabs[newIndex]); + } else if (key.rightArrow) { + const newIndex = currentIndex < tabs.length - 1 ? currentIndex + 1 : 0; + setActiveTab(tabs[newIndex]); + } + } + + // Accelerator keys for connect/disconnect (work from anywhere) + // 'a' switches to Auth tab; use the Auth tab for Quick/Guided auth + if (selectedServer) { + if ( + input.toLowerCase() === "c" && + (inspectorStatus === "disconnected" || inspectorStatus === "error") + ) { + handleConnect(); + } else if ( + input.toLowerCase() === "d" && + (inspectorStatus === "connected" || inspectorStatus === "connecting") + ) { + handleDisconnect(); + } + } + }); + + // Calculate layout dimensions + const headerHeight = 1; + const tabsHeight = 1; + // Server details will be flexible - calculate remaining space for content + const availableHeight = dimensions.height - headerHeight - tabsHeight; + // Reserve space for server details (will grow as needed, but we'll use flexGrow) + const serverDetailsMinHeight = 3; + const contentHeight = availableHeight - serverDetailsMinHeight; + const serverListWidth = Math.floor(dimensions.width * 0.3); + const contentWidth = dimensions.width - serverListWidth; + + const getStatusColor = (status: string) => { + switch (status) { + case "connected": + return "green"; + case "connecting": + return "yellow"; + case "error": + return "red"; + default: + return "gray"; + } + }; + + const getStatusSymbol = (status: string) => { + switch (status) { + case "connected": + return "●"; + case "connecting": + return "◐"; + case "error": + return "✗"; + default: + return "○"; + } + }; + + return ( + + {/* Header row across the top */} + + + + {packageJson.name} + + - {packageJson.description} + + v{packageJson.version} + + + {/* Main content area */} + + {/* Left column - Server list */} + + + + MCP Servers + + + + {serverNames.map((serverName) => { + const isSelected = selectedServer === serverName; + return ( + + + {isSelected ? "▶ " : " "} + {serverName} + + + ); + })} + + + {/* Fixed footer */} + + + ESC to exit + + + + + {/* Right column - Server details, Tabs and content */} + + {/* Server Details - Flexible height */} + + + + + {selectedServer} + + + {currentServerState && ( + <> + + {getStatusSymbol(currentServerState.status)}{" "} + {currentServerState.status} + + + {(currentServerState?.status === "disconnected" || + currentServerState?.status === "error") && ( + + [Connect] + + )} + {(currentServerState?.status === "connected" || + currentServerState?.status === "connecting") && ( + + [Disconnect] + + )} + + )} + + + {show401AuthHint && ( + + + 401 Unauthorized. Press A to authenticate. + + + )} + {oauthStatus !== "idle" && ( + + {oauthStatus === "authenticating" && ( + OAuth: authenticating… + )} + {oauthStatus === "success" && oauthMessage && ( + {oauthMessage} + )} + {oauthStatus === "error" && oauthMessage && ( + OAuth: {oauthMessage} + )} + + )} + + + + {/* Tabs */} + { + const serverType = + inspectorClients[selectedServer].getServerType(); + return ( + serverType === "sse" || serverType === "streamable-http" + ); + })() + : false + } + /> + + {/* Tab Content */} + + {activeTab === "info" && ( + + )} + {activeTab === "auth" && + selectedServer && + selectedServerConfig && + isOAuthCapableServer(selectedServerConfig) ? ( + + ) : null} + {activeTab === "resources" && + currentServerState?.status === "connected" && + selectedInspectorClient ? ( + + setTabCounts((prev) => ({ ...prev, resources: count })) + } + focusedPane={ + focus === "tabContentDetails" + ? "details" + : focus === "tabContentList" + ? "list" + : null + } + onViewDetails={(resource) => + setDetailsModal({ + title: `Resource: ${resource.name || resource.uri || "Unknown"}`, + content: renderResourceDetails(resource), + }) + } + onFetchResource={(resource) => { + // Resource fetching is handled internally by ResourcesTab + // This callback is just for triggering the fetch + }} + onFetchTemplate={(template) => { + setResourceTestModal({ + template, + inspectorClient: selectedInspectorClient, + }); + }} + modalOpen={ + !!(toolTestModal || resourceTestModal || detailsModal) + } + /> + ) : activeTab === "prompts" && + currentServerState?.status === "connected" && + selectedInspectorClient ? ( + + setTabCounts((prev) => ({ ...prev, prompts: count })) + } + focusedPane={ + focus === "tabContentDetails" + ? "details" + : focus === "tabContentList" + ? "list" + : null + } + onViewDetails={(prompt) => + setDetailsModal({ + title: `Prompt: ${prompt.name || "Unknown"}`, + content: renderPromptDetails(prompt), + }) + } + onFetchPrompt={(prompt) => { + setPromptTestModal({ + prompt, + inspectorClient: selectedInspectorClient, + }); + }} + modalOpen={ + !!( + toolTestModal || + resourceTestModal || + promptTestModal || + detailsModal + ) + } + /> + ) : activeTab === "tools" && + currentServerState?.status === "connected" && + inspectorClient ? ( + + setTabCounts((prev) => ({ ...prev, tools: count })) + } + focusedPane={ + focus === "tabContentDetails" + ? "details" + : focus === "tabContentList" + ? "list" + : null + } + onTestTool={(tool) => + setToolTestModal({ + tool, + inspectorClient: selectedInspectorClient, + }) + } + onViewDetails={(tool) => + setDetailsModal({ + title: `Tool: ${tool.name || "Unknown"}`, + content: renderToolDetails(tool), + }) + } + modalOpen={!!(toolTestModal || detailsModal)} + /> + ) : activeTab === "messages" && selectedInspectorClient ? ( + + setTabCounts((prev) => ({ ...prev, messages: count })) + } + focusedPane={ + focus === "messagesDetail" + ? "details" + : focus === "messagesList" + ? "messages" + : null + } + modalOpen={!!(toolTestModal || detailsModal)} + onViewDetails={(message) => { + const label = + message.direction === "request" && + "method" in message.message + ? message.message.method + : message.direction === "response" + ? "Response" + : message.direction === "notification" && + "method" in message.message + ? message.message.method + : "Message"; + setDetailsModal({ + title: `Message: ${label}`, + content: renderMessageDetails(message), + }); + }} + /> + ) : activeTab === "requests" && + selectedInspectorClient && + (inspectorStatus === "connected" || + inspectorFetchRequests.length > 0) ? ( + + setTabCounts((prev) => ({ ...prev, requests: count })) + } + focusedPane={ + focus === "requestsDetail" + ? "details" + : focus === "requestsList" + ? "requests" + : null + } + modalOpen={!!(toolTestModal || detailsModal)} + onViewDetails={(request) => { + setDetailsModal({ + title: `Request: ${request.method} ${request.url}`, + content: renderRequestDetails(request), + }); + }} + /> + ) : activeTab === "logging" && selectedInspectorClient ? ( + + setTabCounts((prev) => ({ ...prev, logging: count })) + } + focused={ + focus === "tabContentList" || focus === "tabContentDetails" + } + /> + ) : null} + + + + + {/* Tool Test Modal - rendered at App level for full screen overlay */} + {toolTestModal && ( + setToolTestModal(null)} + /> + )} + + {/* Resource Test Modal - rendered at App level for full screen overlay */} + {resourceTestModal && ( + setResourceTestModal(null)} + /> + )} + + {promptTestModal && ( + setPromptTestModal(null)} + /> + )} + + {/* Details Modal - rendered at App level for full screen overlay */} + {detailsModal && ( + setDetailsModal(null)} + /> + )} + + ); +} + +export default App; diff --git a/tui/src/components/AuthTab.tsx b/tui/src/components/AuthTab.tsx new file mode 100644 index 000000000..164cef442 --- /dev/null +++ b/tui/src/components/AuthTab.tsx @@ -0,0 +1,428 @@ +import React, { useState, useEffect, useCallback, useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import { SelectableItem } from "./SelectableItem.js"; +import type { + MCPServerConfig, + InspectorClient, +} from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import type { + AuthGuidedState, + OAuthStep, +} from "@modelcontextprotocol/inspector-shared/auth"; + +const STEP_LABELS: Record = { + metadata_discovery: "Metadata Discovery", + client_registration: "Client Registration", + authorization_redirect: "Preparing Authorization", + authorization_code: "Request Authorization Code", + token_request: "Token Request", + complete: "Authentication Complete", +}; + +const STEP_ORDER: OAuthStep[] = [ + "metadata_discovery", + "client_registration", + "authorization_redirect", + "authorization_code", + "token_request", + "complete", +]; + +function stepIndex(step: OAuthStep): number { + const i = STEP_ORDER.indexOf(step); + return i >= 0 ? i : 0; +} + +interface AuthTabProps { + serverName: string | null; + serverConfig: MCPServerConfig | null; + inspectorClient: InspectorClient | null; + oauthStatus: "idle" | "authenticating" | "success" | "error"; + oauthMessage: string | null; + width: number; + height: number; + focused?: boolean; + selectedAction: "guided" | "quick" | "clear"; + onSelectedActionChange: (action: "guided" | "quick" | "clear") => void; + onQuickAuth: () => Promise; + onGuidedStart: () => Promise; + onGuidedAdvance: () => Promise; + onRunGuidedToCompletion: () => Promise; + onClearOAuth: () => void; + isOAuthCapable: boolean; +} + +export function AuthTab({ + serverName, + serverConfig, + inspectorClient, + oauthStatus, + oauthMessage, + width, + height, + focused = false, + selectedAction, + onSelectedActionChange, + onQuickAuth, + onGuidedStart, + onGuidedAdvance, + onRunGuidedToCompletion, + onClearOAuth, + isOAuthCapable, +}: AuthTabProps) { + const scrollViewRef = useRef(null); + const [oauthState, setOauthState] = useState( + undefined, + ); + const [guidedStarted, setGuidedStarted] = useState(false); + const [clearedConfirmation, setClearedConfirmation] = useState(false); + + // Sync oauthState from InspectorClient + useEffect(() => { + if (!inspectorClient) { + setOauthState(undefined); + setGuidedStarted(false); + return; + } + + const update = () => setOauthState(inspectorClient.getOAuthState()); + update(); + + const onStepChange = () => update(); + inspectorClient.addEventListener("oauthStepChange", onStepChange); + inspectorClient.addEventListener("oauthComplete", onStepChange); + return () => { + inspectorClient.removeEventListener("oauthStepChange", onStepChange); + inspectorClient.removeEventListener("oauthComplete", onStepChange); + }; + }, [inspectorClient]); + + // Reset guided state when switching servers + useEffect(() => { + setGuidedStarted(false); + }, [serverName]); + + // Clear confirmation when switching away from Clear menu item + useEffect(() => { + if (selectedAction !== "clear") { + setClearedConfirmation(false); + } + }, [selectedAction]); + + const guidedFlowStarted = !!oauthState?.oauthStep; + const currentStep = oauthState?.oauthStep ?? "metadata_discovery"; + const needsAuthCode = + currentStep === "authorization_code" && oauthState?.authorizationUrl; + const isComplete = currentStep === "complete"; + + const handleContinue = useCallback(async () => { + if (!guidedStarted) { + await onGuidedStart(); + setGuidedStarted(true); + } else if (!needsAuthCode && !isComplete) { + await onGuidedAdvance(); + } + }, [ + guidedStarted, + needsAuthCode, + isComplete, + onGuidedStart, + onGuidedAdvance, + ]); + + // Keyboard: G/Q/S select menu item (handled by App when not focused), + // left/right select, Enter run, up/down scroll + useInput( + (input: string, key: Key) => { + if (!focused || !isOAuthCapable) return; + + const lower = input.toLowerCase(); + if (lower === "g") { + onSelectedActionChange("guided"); + return; + } + if (lower === "q") { + onSelectedActionChange("quick"); + return; + } + if (lower === "s") { + onSelectedActionChange("clear"); + return; + } + + if (key.leftArrow) { + onSelectedActionChange( + selectedAction === "guided" + ? "clear" + : selectedAction === "quick" + ? "guided" + : "quick", + ); + } else if (key.rightArrow) { + onSelectedActionChange( + selectedAction === "guided" + ? "quick" + : selectedAction === "quick" + ? "clear" + : "guided", + ); + } else if (key.upArrow && scrollViewRef.current) { + scrollViewRef.current.scrollBy(-1); + } else if (key.downArrow && scrollViewRef.current) { + scrollViewRef.current.scrollBy(1); + } else if (key.pageUp && scrollViewRef.current) { + const h = scrollViewRef.current.getViewportHeight() || 1; + scrollViewRef.current.scrollBy(-h); + } else if (key.pageDown && scrollViewRef.current) { + const h = scrollViewRef.current.getViewportHeight() || 1; + scrollViewRef.current.scrollBy(h); + } else if (key.return) { + if (selectedAction === "guided") onRunGuidedToCompletion(); + else if (selectedAction === "quick") onQuickAuth(); + else if (selectedAction === "clear") { + onClearOAuth(); + setClearedConfirmation(true); + } + } else if (input === " " && selectedAction === "guided") { + handleContinue(); + } + }, + { + isActive: focused, + }, + ); + + if (!serverName || !isOAuthCapable) { + return ( + + + Select an OAuth-capable server (SSE or Streamable HTTP) to configure + authentication. + + + ); + } + + return ( + + + + Authentication + + + + {/* Action bar and hint - single container for tight spacing */} + + + + Guided Auth + + + Quick Auth + + + Clear OAuth State + + + + {selectedAction === "guided" && ( + <> + + Press [Space] to advance one step through guided auth. + + + Press [Enter] to run guided auth to completion. + + + )} + {selectedAction === "quick" && ( + Press [Enter] to run quick auth. + )} + {selectedAction === "clear" && ( + Press [Enter] to clear OAuth state. + )} + + + + {selectedAction === "guided" && ( + + Guided OAuth Flow Progress + {STEP_ORDER.map((step) => { + const stepIdx = stepIndex(step); + const currentIdx = stepIndex(currentStep); + const completed = + guidedFlowStarted && + (stepIdx < currentIdx || + (step === currentStep && isComplete)); + const inProgress = + guidedFlowStarted && step === currentStep && !isComplete; + const details = oauthState + ? getStepDetails(oauthState, step) + : null; + + const icon = completed ? "✓" : inProgress ? "→" : "○"; + const color = completed + ? "green" + : inProgress + ? "cyan" + : "gray"; + + return ( + + + {icon} {STEP_LABELS[step]} + {inProgress && " (in progress)"} + + {completed && details && ( + + {details} + + )} + {inProgress && details && ( + + {details} + + )} + + ); + })} + + {/* Waiting for auth - URL was opened when we reached this step */} + {oauthState && needsAuthCode && oauthState?.authorizationUrl && ( + + Authorization URL opened in browser + + + {oauthState.authorizationUrl.toString()} + + + + + Complete authorization in the browser. You will be + redirected and the flow will complete automatically. + + + + )} + + )} + + {selectedAction === "quick" && ( + + {oauthStatus === "authenticating" && ( + Authenticating... + )} + {oauthStatus === "error" && oauthMessage && ( + {oauthMessage} + )} + {oauthStatus === "success" && + oauthState && + oauthState.authType === "normal" && + (oauthState.oauthTokens || oauthState.oauthClientInfo) && ( + <> + Quick Auth Results + {oauthState.oauthClientInfo && ( + + + Client:{" "} + {JSON.stringify(oauthState.oauthClientInfo, null, 2)} + + + )} + {oauthState.oauthTokens && ( + + + Access Token:{" "} + {oauthState.oauthTokens.access_token?.slice(0, 20)}... + + + )} + + )} + + )} + + {selectedAction === "clear" && clearedConfirmation && ( + + OAuth state cleared. + + )} + + + + {focused && ( + + + ←/→ select, G/Q/S or Enter run, ↑/↓ scroll + + + )} + + ); +} + +function getStepDetails( + state: AuthGuidedState, + step: OAuthStep, +): string | null { + switch (step) { + case "metadata_discovery": + if (state.resourceMetadata || state.oauthMetadata) { + const parts: string[] = []; + if (state.resourceMetadata) { + parts.push( + `Resource: ${JSON.stringify(state.resourceMetadata, null, 2)}`, + ); + } + if (state.oauthMetadata) { + parts.push(`OAuth: ${JSON.stringify(state.oauthMetadata, null, 2)}`); + } + return parts.join("\n"); + } + return null; + case "client_registration": + if (state.oauthClientInfo) { + return JSON.stringify(state.oauthClientInfo, null, 2); + } + return null; + case "authorization_redirect": + if (state.authorizationUrl) { + return `URL: ${state.authorizationUrl.toString()}`; + } + return null; + case "authorization_code": + return state.authorizationCode + ? `Code received: ${state.authorizationCode.slice(0, 10)}...` + : null; + case "token_request": + return "Exchanging code for tokens..."; + case "complete": + if (state.oauthTokens) { + return `Tokens: access_token=${state.oauthTokens.access_token?.slice(0, 15)}...`; + } + return null; + default: + return null; + } +} diff --git a/tui/src/components/DetailsModal.tsx b/tui/src/components/DetailsModal.tsx new file mode 100644 index 000000000..36baa41bb --- /dev/null +++ b/tui/src/components/DetailsModal.tsx @@ -0,0 +1,101 @@ +import React, { useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; + +interface DetailsModalProps { + title: string; + content: React.ReactNode; + width: number; + height: number; + onClose: () => void; +} + +export function DetailsModal({ + title, + content, + width, + height, + onClose, +}: DetailsModalProps) { + const scrollViewRef = useRef(null); + + // Use full terminal dimensions + const [terminalDimensions, setTerminalDimensions] = React.useState({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + + React.useEffect(() => { + const updateDimensions = () => { + setTerminalDimensions({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + }; + process.stdout.on("resize", updateDimensions); + updateDimensions(); + return () => { + process.stdout.off("resize", updateDimensions); + }; + }, [width, height]); + + // Handle escape to close and scrolling + useInput( + (input: string, key: Key) => { + if (key.escape) { + onClose(); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.pageDown) { + const viewportHeight = scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } else if (key.pageUp) { + const viewportHeight = scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } + }, + { isActive: true }, + ); + + // Calculate modal dimensions - use almost full screen + const modalWidth = terminalDimensions.width - 2; + const modalHeight = terminalDimensions.height - 2; + + return ( + + {/* Modal Content */} + + {/* Header */} + + + {title} + + + (Press ESC to close) + + + {/* Content Area */} + + {content} + + + + ); +} diff --git a/tui/src/components/HistoryTab.tsx b/tui/src/components/HistoryTab.tsx new file mode 100644 index 000000000..8b6496163 --- /dev/null +++ b/tui/src/components/HistoryTab.tsx @@ -0,0 +1,322 @@ +import React, { useEffect, useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { MessageEntry } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { useSelectableList } from "../hooks/useSelectableList.js"; + +interface HistoryTabProps { + serverName: string | null; + messages: MessageEntry[]; + width: number; + height: number; + onCountChange?: (count: number) => void; + focusedPane?: "messages" | "details" | null; + onViewDetails?: (message: MessageEntry) => void; + modalOpen?: boolean; +} + +export function HistoryTab({ + serverName, + messages, + width, + height, + onCountChange, + focusedPane = null, + onViewDetails, + modalOpen = false, +}: HistoryTabProps) { + const visibleCount = Math.max(1, height - 7); + const { selectedIndex, firstVisible, setSelection } = useSelectableList( + messages.length, + visibleCount, + ); + const scrollViewRef = useRef(null); + const selectedMessage = messages[selectedIndex] || null; + + // Handle arrow key navigation and scrolling when focused + useInput( + (input: string, key: Key) => { + if (focusedPane === "messages") { + if (key.upArrow && selectedIndex > 0) { + setSelection(selectedIndex - 1); + } else if (key.downArrow && selectedIndex < messages.length - 1) { + setSelection(selectedIndex + 1); + } else if (key.pageUp) { + setSelection(Math.max(0, selectedIndex - visibleCount)); + } else if (key.pageDown) { + setSelection( + Math.min(messages.length - 1, selectedIndex + visibleCount), + ); + } + return; + } + + // details scrolling (only when details pane is focused) + if (focusedPane === "details") { + // Handle '+' key to view in full screen modal + if (input === "+" && selectedMessage && onViewDetails) { + onViewDetails(selectedMessage); + return; + } + + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { isActive: !modalOpen && focusedPane !== undefined }, + ); + + // Update count when messages change + React.useEffect(() => { + onCountChange?.(messages.length); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [messages.length]); + + // Reset details scroll when message selection changes + useEffect(() => { + scrollViewRef.current?.scrollTo(0); + }, [selectedIndex]); + + const listWidth = Math.floor(width * 0.4); + const detailWidth = width - listWidth; + + return ( + + {/* Left column - Messages list */} + + + + Messages ({messages.length}) + + + + {/* Messages list */} + {messages.length === 0 ? ( + + No messages + + ) : ( + + {messages + .slice(firstVisible, firstVisible + visibleCount) + .map((msg, i) => { + const index = firstVisible + i; + const isSelected = index === selectedIndex; + let label: string; + if (msg.direction === "request" && "method" in msg.message) { + label = msg.message.method; + } else if (msg.direction === "response") { + if ("result" in msg.message) { + label = "Response (result)"; + } else if ("error" in msg.message) { + label = `Response (error: ${msg.message.error.code})`; + } else { + label = "Response"; + } + } else if ( + msg.direction === "notification" && + "method" in msg.message + ) { + label = msg.message.method; + } else { + label = "Unknown"; + } + const direction = + msg.direction === "request" + ? "→" + : msg.direction === "response" + ? "←" + : "•"; + const hasResponse = msg.response !== undefined; + + return ( + + + {isSelected ? "▶ " : " "} + {direction} {label} + {hasResponse + ? " ✓" + : msg.direction === "request" + ? " ..." + : ""} + + + ); + })} + + )} + + + {/* Right column - Message details */} + + {selectedMessage ? ( + <> + {/* Fixed method caption only */} + + + {selectedMessage.direction === "request" && + "method" in selectedMessage.message + ? selectedMessage.message.method + : selectedMessage.direction === "response" + ? "Response" + : selectedMessage.direction === "notification" && + "method" in selectedMessage.message + ? selectedMessage.message.method + : "Message"} + + + + {/* Scrollable content area */} + + {/* Metadata */} + + Direction: {selectedMessage.direction} + + + {selectedMessage.timestamp.toLocaleTimeString()} + {selectedMessage.duration !== undefined && + ` (${selectedMessage.duration}ms)`} + + + + + {selectedMessage.direction === "request" ? ( + <> + {/* Request label */} + + Request: + + + {/* Request content */} + {JSON.stringify(selectedMessage.message, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + {/* Response section */} + {selectedMessage.response ? ( + <> + + Response: + + {JSON.stringify(selectedMessage.response, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + ) : ( + + + Waiting for response... + + + )} + + ) : ( + <> + {/* Response or notification label */} + + + {selectedMessage.direction === "response" + ? "Response:" + : "Notification:"} + + + + {/* Message content */} + {JSON.stringify(selectedMessage.message, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + )} + + + {/* Fixed footer - only show when details pane is focused */} + {focusedPane === "details" && ( + + + ↑/↓ to scroll, + to zoom + + + )} + + ) : ( + + Select a message to view details + + )} + + + ); +} diff --git a/tui/src/components/InfoTab.tsx b/tui/src/components/InfoTab.tsx new file mode 100644 index 000000000..37ec0551f --- /dev/null +++ b/tui/src/components/InfoTab.tsx @@ -0,0 +1,228 @@ +import React, { useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { + MCPServerConfig, + ServerState, +} from "@modelcontextprotocol/inspector-shared/mcp/index.js"; + +interface InfoTabProps { + serverName: string | null; + serverConfig: MCPServerConfig | null; + serverState: ServerState | null; + width: number; + height: number; + focused?: boolean; +} + +export function InfoTab({ + serverName, + serverConfig, + serverState, + width, + height, + focused = false, +}: InfoTabProps) { + const scrollViewRef = useRef(null); + + // Handle keyboard input for scrolling + useInput( + (input: string, key: Key) => { + if (focused) { + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { isActive: focused }, + ); + + return ( + + + + Info + + + + {serverName ? ( + <> + {/* Scrollable content area - takes remaining space */} + + + {/* Server Configuration */} + + Server Configuration + + {serverConfig ? ( + + {serverConfig.type === undefined || + serverConfig.type === "stdio" ? ( + <> + Type: stdio + + Command: {(serverConfig as any).command} + + {(serverConfig as any).args && + (serverConfig as any).args.length > 0 && ( + + Args: + {(serverConfig as any).args.map( + (arg: string, idx: number) => ( + + {arg} + + ), + )} + + )} + {(serverConfig as any).env && + Object.keys((serverConfig as any).env).length > 0 && ( + + + Env:{" "} + {Object.entries((serverConfig as any).env) + .map(([k, v]) => `${k}=${v}`) + .join(", ")} + + + )} + {(serverConfig as any).cwd && ( + + CWD: {(serverConfig as any).cwd} + + )} + + ) : serverConfig.type === "sse" ? ( + <> + Type: sse + URL: {(serverConfig as any).url} + {(serverConfig as any).headers && + Object.keys((serverConfig as any).headers).length > + 0 && ( + + + Headers:{" "} + {Object.entries((serverConfig as any).headers) + .map(([k, v]) => `${k}=${v}`) + .join(", ")} + + + )} + + ) : ( + <> + Type: streamable-http + URL: {(serverConfig as any).url} + {(serverConfig as any).headers && + Object.keys((serverConfig as any).headers).length > + 0 && ( + + + Headers:{" "} + {Object.entries((serverConfig as any).headers) + .map(([k, v]) => `${k}=${v}`) + .join(", ")} + + + )} + + )} + + ) : ( + + No configuration available + + )} + + {/* Server Info */} + {serverState && + serverState.status === "connected" && + serverState.serverInfo && ( + <> + + Server Information + + + {serverState.serverInfo.name && ( + + Name: {serverState.serverInfo.name} + + )} + {serverState.serverInfo.version && ( + + + Version: {serverState.serverInfo.version} + + + )} + {serverState.instructions && ( + + Instructions: + + {serverState.instructions} + + + )} + + + )} + + {serverState && serverState.status === "error" && ( + + + Error + + {serverState.error && ( + + {serverState.error} + + )} + + )} + + {serverState && serverState.status === "disconnected" && ( + + Server not connected + + )} + + + + {/* Fixed keyboard help footer at bottom - only show when focused */} + {focused && ( + + + ↑/↓ to scroll, + to zoom + + + )} + + ) : null} + + ); +} diff --git a/tui/src/components/NotificationsTab.tsx b/tui/src/components/NotificationsTab.tsx new file mode 100644 index 000000000..f25de1b24 --- /dev/null +++ b/tui/src/components/NotificationsTab.tsx @@ -0,0 +1,87 @@ +import React, { useEffect, useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import type { StderrLogEntry } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; + +interface NotificationsTabProps { + client: Client | null; + stderrLogs: StderrLogEntry[]; + width: number; + height: number; + onCountChange?: (count: number) => void; + focused?: boolean; +} + +export function NotificationsTab({ + client, + stderrLogs, + width, + height, + onCountChange, + focused = false, +}: NotificationsTabProps) { + const scrollViewRef = useRef(null); + const onCountChangeRef = useRef(onCountChange); + + // Update ref when callback changes + useEffect(() => { + onCountChangeRef.current = onCountChange; + }, [onCountChange]); + + useEffect(() => { + onCountChangeRef.current?.(stderrLogs.length); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [stderrLogs.length]); + + // Handle keyboard input for scrolling + useInput( + (input: string, key: Key) => { + if (focused) { + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { isActive: focused }, + ); + + return ( + + + + Logging ({stderrLogs.length}) + + + {stderrLogs.length === 0 ? ( + + No stderr output yet + + ) : ( + + {stderrLogs.map((log, index) => ( + + [{log.timestamp.toLocaleTimeString()}] + {log.message} + + ))} + + )} + + ); +} diff --git a/tui/src/components/PromptTestModal.tsx b/tui/src/components/PromptTestModal.tsx new file mode 100644 index 000000000..0d56d2984 --- /dev/null +++ b/tui/src/components/PromptTestModal.tsx @@ -0,0 +1,300 @@ +import React, { useState } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { Form } from "ink-form"; +import { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { promptArgsToForm } from "../utils/promptArgsToForm.js"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; + +// Helper to extract error message from various error types +function getErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + if (typeof error === "string") { + return error; + } + if (error && typeof error === "object" && "message" in error) { + return String(error.message); + } + return "Unknown error"; +} + +interface PromptTestModalProps { + prompt: { + name: string; + description?: string; + arguments?: any[]; + }; + inspectorClient: InspectorClient | null; + width: number; + height: number; + onClose: () => void; +} + +type ModalState = "form" | "loading" | "results"; + +interface PromptResult { + input: Record; + output: any; + error?: string; + errorDetails?: any; + duration: number; +} + +export function PromptTestModal({ + prompt, + inspectorClient, + width, + height, + onClose, +}: PromptTestModalProps) { + const [state, setState] = useState("form"); + const [result, setResult] = useState(null); + const scrollViewRef = React.useRef(null); + + // Use full terminal dimensions instead of passed dimensions + const [terminalDimensions, setTerminalDimensions] = React.useState({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + + React.useEffect(() => { + const updateDimensions = () => { + setTerminalDimensions({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + }; + process.stdout.on("resize", updateDimensions); + updateDimensions(); + return () => { + process.stdout.off("resize", updateDimensions); + }; + }, [width, height]); + + const formStructure = promptArgsToForm( + prompt.arguments || [], + prompt.name || "Unknown Prompt", + ); + + // Reset state when modal closes + React.useEffect(() => { + return () => { + // Cleanup: reset state when component unmounts + setState("form"); + setResult(null); + }; + }, []); + + // Handle all input when modal is open - prevents input from reaching underlying components + // When in form mode, only handle escape (form handles its own input) + // When in results mode, handle scrolling keys + useInput( + (input: string, key: Key) => { + // Always handle escape to close modal + if (key.escape) { + setState("form"); + setResult(null); + onClose(); + return; + } + + if (state === "form") { + // In form mode, let the form handle all other input + // Don't process anything else - this prevents input from reaching underlying components + return; + } + + if (state === "results") { + // Allow scrolling in results view + if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } + } + }, + { isActive: true }, + ); + + const handleFormSubmit = async (values: Record) => { + if (!inspectorClient || !prompt) return; + + setState("loading"); + const startTime = Date.now(); + + try { + // Get the prompt using the provided arguments + const invocation = await inspectorClient.getPrompt(prompt.name, values); + + const duration = Date.now() - startTime; + + setResult({ + input: values, + output: invocation.result, + duration, + }); + setState("results"); + } catch (error) { + const duration = Date.now() - startTime; + const errorMessage = getErrorMessage(error); + + // Extract detailed error information + const errorObj: any = { + message: errorMessage, + }; + if (error instanceof Error) { + errorObj.name = error.name; + errorObj.stack = error.stack; + } else if (error && typeof error === "object") { + // Try to extract more details from error object + Object.assign(errorObj, error); + } else { + errorObj.error = String(error); + } + + setResult({ + input: values, + output: null, + error: errorMessage, + errorDetails: errorObj, + duration, + }); + setState("results"); + } + }; + + // Calculate modal dimensions - use almost full screen + const modalWidth = terminalDimensions.width - 2; + const modalHeight = terminalDimensions.height - 2; + + return ( + + {/* Modal Content */} + + {/* Header */} + + + {formStructure.title} + + + (Press ESC to close) + + + {/* Content Area */} + + {state === "form" && ( + + {prompt.description && ( + + {prompt.description} + + )} +
+ handleFormSubmit(values as Record) + } + /> + + )} + + {state === "loading" && ( + + Getting prompt... + + )} + + {state === "results" && result && ( + + + {/* Timing */} + + + Duration: {result.duration}ms + + + + {/* Input */} + {Object.keys(result.input).length > 0 && ( + + + Arguments: + + + + {JSON.stringify(result.input, null, 2)} + + + + )} + + {/* Output or Error */} + {result.error ? ( + + + + Error: + + + + {result.error} + + {result.errorDetails && ( + <> + + + Error Details: + + + + + {JSON.stringify(result.errorDetails, null, 2)} + + + + )} + + ) : ( + + + Prompt Messages: + + + + {JSON.stringify(result.output, null, 2)} + + + + )} + + + )} + + + + ); +} diff --git a/tui/src/components/PromptsTab.tsx b/tui/src/components/PromptsTab.tsx new file mode 100644 index 000000000..c10493cff --- /dev/null +++ b/tui/src/components/PromptsTab.tsx @@ -0,0 +1,265 @@ +import React, { useState, useEffect, useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { useSelectableList } from "../hooks/useSelectableList.js"; + +interface PromptsTabProps { + prompts: any[]; + client: any; // SDK Client (from inspectorClient.getClient()) + inspectorClient: InspectorClient | null; // InspectorClient for getPrompt + width: number; + height: number; + onCountChange?: (count: number) => void; + focusedPane?: "list" | "details" | null; + onViewDetails?: (prompt: any) => void; + onFetchPrompt?: (prompt: any) => void; + modalOpen?: boolean; +} + +export function PromptsTab({ + prompts, + client, + inspectorClient, + width, + height, + onCountChange, + focusedPane = null, + onViewDetails, + onFetchPrompt, + modalOpen = false, +}: PromptsTabProps) { + const visibleCount = Math.max(1, height - 7); + const { selectedIndex, firstVisible, setSelection } = useSelectableList( + prompts.length, + visibleCount, + { resetWhen: [prompts] }, + ); + const [error, setError] = useState(null); + const scrollViewRef = useRef(null); + + // Handle arrow key navigation when focused + useInput( + (input: string, key: Key) => { + // Handle Enter key to fetch prompt (works from both list and details) + if (key.return && selectedPrompt && inspectorClient && onFetchPrompt) { + // If prompt has arguments, open modal to collect them + // Otherwise, fetch directly + if (selectedPrompt.arguments && selectedPrompt.arguments.length > 0) { + onFetchPrompt(selectedPrompt); + } else { + // No arguments, fetch directly + (async () => { + try { + const invocation = await inspectorClient.getPrompt( + selectedPrompt.name, + ); + // Show result in details modal + if (onViewDetails) { + onViewDetails({ + ...selectedPrompt, + result: invocation.result, + }); + } + } catch (error) { + setError( + error instanceof Error ? error.message : "Failed to get prompt", + ); + } + })(); + } + return; + } + + if (focusedPane === "list") { + if (key.upArrow && selectedIndex > 0) { + setSelection(selectedIndex - 1); + } else if (key.downArrow && selectedIndex < prompts.length - 1) { + setSelection(selectedIndex + 1); + } + return; + } + + if (focusedPane === "details") { + // Handle '+' key to view in full screen modal + if (input === "+" && selectedPrompt && onViewDetails) { + onViewDetails(selectedPrompt); + return; + } + + // Scroll the details pane using ink-scroll-view + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { + isActive: + !modalOpen && (focusedPane === "list" || focusedPane === "details"), + }, + ); + + // Reset scroll when selection changes + useEffect(() => { + scrollViewRef.current?.scrollTo(0); + }, [selectedIndex]); + + const selectedPrompt = prompts[selectedIndex] || null; + + const listWidth = Math.floor(width * 0.4); + const detailWidth = width - listWidth; + + return ( + + {/* Prompts List */} + + + + Prompts ({prompts.length}) + + + {error ? ( + + {error} + + ) : prompts.length === 0 ? ( + + No prompts available + + ) : ( + + {prompts + .slice(firstVisible, firstVisible + visibleCount) + .map((prompt, i) => { + const index = firstVisible + i; + const isSelected = index === selectedIndex; + return ( + + + {isSelected ? "▶ " : " "} + {prompt.name || `Prompt ${index + 1}`} + + + ); + })} + + )} + + + {/* Prompt Details */} + + {selectedPrompt ? ( + <> + {/* Fixed header */} + + + {selectedPrompt.name} + + + + {/* Scrollable content area - direct ScrollView with height prop like NotificationsTab */} + + {/* Description */} + {selectedPrompt.description && ( + <> + {selectedPrompt.description + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + )} + + {/* Arguments */} + {selectedPrompt.arguments && + selectedPrompt.arguments.length > 0 && ( + <> + + Arguments: + + {selectedPrompt.arguments.map((arg: any, idx: number) => ( + + + - {arg.name}:{" "} + {arg.description || arg.type || "string"} + + + ))} + + )} + + {/* Enter to Get Prompt message */} + + [Enter to Get Prompt] + + + + {/* Fixed footer - only show when details pane is focused */} + {focusedPane === "details" && ( + + + ↑/↓ to scroll, + to zoom + + + )} + + ) : ( + + Select a prompt to view details + + )} + + + ); +} diff --git a/tui/src/components/RequestsTab.tsx b/tui/src/components/RequestsTab.tsx new file mode 100644 index 000000000..860d52a46 --- /dev/null +++ b/tui/src/components/RequestsTab.tsx @@ -0,0 +1,366 @@ +import React, { useEffect, useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { FetchRequestEntry } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { useSelectableList } from "../hooks/useSelectableList.js"; + +interface RequestsTabProps { + serverName: string | null; + requests: FetchRequestEntry[]; + width: number; + height: number; + onCountChange?: (count: number) => void; + focusedPane?: "requests" | "details" | null; + onViewDetails?: (request: FetchRequestEntry) => void; + modalOpen?: boolean; +} + +export function RequestsTab({ + serverName, + requests, + width, + height, + onCountChange, + focusedPane = null, + onViewDetails, + modalOpen = false, +}: RequestsTabProps) { + const visibleCount = Math.max(1, height - 7); + const { selectedIndex, firstVisible, setSelection } = useSelectableList( + requests.length, + visibleCount, + ); + const scrollViewRef = useRef(null); + const selectedRequest = requests[selectedIndex] || null; + + // Handle arrow key navigation and scrolling when focused + useInput( + (input: string, key: Key) => { + if (focusedPane === "requests") { + if (key.upArrow && selectedIndex > 0) { + setSelection(selectedIndex - 1); + } else if (key.downArrow && selectedIndex < requests.length - 1) { + setSelection(selectedIndex + 1); + } else if (key.pageUp) { + setSelection(Math.max(0, selectedIndex - visibleCount)); + } else if (key.pageDown) { + setSelection( + Math.min(requests.length - 1, selectedIndex + visibleCount), + ); + } + return; + } + + // details scrolling (only when details pane is focused) + if (focusedPane === "details") { + // Handle '+' key to view in full screen modal + if (input === "+" && selectedRequest && onViewDetails) { + onViewDetails(selectedRequest); + return; + } + + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { isActive: !modalOpen && focusedPane !== undefined }, + ); + + // Update count when requests change + React.useEffect(() => { + onCountChange?.(requests.length); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [requests.length]); + + // Reset details scroll when request selection changes + useEffect(() => { + scrollViewRef.current?.scrollTo(0); + }, [selectedIndex]); + + const listWidth = Math.floor(width * 0.4); + const detailWidth = width - listWidth; + + const getStatusColor = (status?: number): string => { + if (!status) return "gray"; + if (status >= 200 && status < 300) return "green"; + if (status >= 300 && status < 400) return "yellow"; + if (status >= 400) return "red"; + return "gray"; + }; + + return ( + + {/* Left column - Requests list */} + + + + Requests ({requests.length}) + + + + {/* Requests list */} + {requests.length === 0 ? ( + + No requests + + ) : ( + + {requests + .slice(firstVisible, firstVisible + visibleCount) + .map((req, i) => { + const index = firstVisible + i; + const isSelected = index === selectedIndex; + const statusColor = getStatusColor(req.responseStatus); + const statusText = req.responseStatus + ? `${req.responseStatus}` + : req.error + ? "ERROR" + : "..."; + + const categoryLabel = req.category === "auth" ? "AUTH" : "MCP "; + const methodPadded = req.method === "GET" ? "GET " : req.method; + return ( + + + {isSelected ? "▶ " : " "} + {categoryLabel}{" "} + {methodPadded}{" "} + {statusText} + {req.duration !== undefined && ( + {req.duration}ms + )} + + + ); + })} + + )} + + + {/* Right column - Request details */} + + {selectedRequest ? ( + <> + {/* Fixed header */} + + + {selectedRequest.method} {selectedRequest.url} + + + + {/* Scrollable content area */} + + {/* Category */} + + + Category:{" "} + + {selectedRequest.category === "auth" ? "auth" : "transport"} + + + + + {/* Status */} + {selectedRequest.responseStatus !== undefined ? ( + + + Status:{" "} + + {selectedRequest.responseStatus}{" "} + {selectedRequest.responseStatusText || ""} + + + + ) : selectedRequest.error ? ( + + + Error: {selectedRequest.error} + + + ) : ( + + + Request in progress... + + + )} + + {/* Duration */} + {selectedRequest.duration !== undefined && ( + + + {selectedRequest.timestamp.toLocaleTimeString()} ( + {selectedRequest.duration}ms) + + + )} + + {/* Request Headers */} + + Request Headers: + + {Object.entries(selectedRequest.requestHeaders).map( + ([key, value]) => ( + + + {key}: {value} + + + ), + )} + + {/* Request Body */} + {selectedRequest.requestBody && ( + <> + + Request Body: + + {(() => { + try { + const parsed = JSON.parse(selectedRequest.requestBody); + return JSON.stringify(parsed, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + )); + } catch { + return ( + + {selectedRequest.requestBody} + + ); + } + })()} + + )} + + {/* Response Headers */} + {selectedRequest.responseHeaders && + Object.keys(selectedRequest.responseHeaders).length > 0 && ( + <> + + Response Headers: + + {Object.entries(selectedRequest.responseHeaders).map( + ([key, value]) => ( + + + {key}: {value} + + + ), + )} + + )} + + {/* Response Body */} + {selectedRequest.responseBody && ( + <> + + Response Body: + + {(() => { + try { + const parsed = JSON.parse(selectedRequest.responseBody); + return JSON.stringify(parsed, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + )); + } catch { + return ( + + {selectedRequest.responseBody} + + ); + } + })()} + + )} + + + {/* Fixed footer - only show when details pane is focused */} + {focusedPane === "details" && ( + + + ↑/↓ to scroll, + to zoom + + + )} + + ) : ( + + Select a request to view details + + )} + + + ); +} diff --git a/tui/src/components/ResourceTestModal.tsx b/tui/src/components/ResourceTestModal.tsx new file mode 100644 index 000000000..a50d6682f --- /dev/null +++ b/tui/src/components/ResourceTestModal.tsx @@ -0,0 +1,319 @@ +import React, { useState } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { Form } from "ink-form"; +import { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { uriTemplateToForm } from "../utils/uriTemplateToForm.js"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; + +// Helper to extract error message from various error types +function getErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } + if (typeof error === "string") { + return error; + } + if (error && typeof error === "object" && "message" in error) { + return String(error.message); + } + return "Unknown error"; +} + +interface ResourceTestModalProps { + template: { + name: string; + uriTemplate: string; + description?: string; + }; + inspectorClient: InspectorClient | null; + width: number; + height: number; + onClose: () => void; +} + +type ModalState = "form" | "loading" | "results"; + +interface ResourceResult { + input: Record; + output: any; + error?: string; + errorDetails?: any; + duration: number; + uri: string; +} + +export function ResourceTestModal({ + template, + inspectorClient, + width, + height, + onClose, +}: ResourceTestModalProps) { + const [state, setState] = useState("form"); + const [result, setResult] = useState(null); + const scrollViewRef = React.useRef(null); + + // Use full terminal dimensions instead of passed dimensions + const [terminalDimensions, setTerminalDimensions] = React.useState({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + + React.useEffect(() => { + const updateDimensions = () => { + setTerminalDimensions({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + }; + process.stdout.on("resize", updateDimensions); + updateDimensions(); + return () => { + process.stdout.off("resize", updateDimensions); + }; + }, [width, height]); + + const formStructure = uriTemplateToForm( + template.uriTemplate, + template.name || "Unknown Template", + ); + + // Reset state when modal closes + React.useEffect(() => { + return () => { + // Cleanup: reset state when component unmounts + setState("form"); + setResult(null); + }; + }, []); + + // Handle all input when modal is open - prevents input from reaching underlying components + // When in form mode, only handle escape (form handles its own input) + // When in results mode, handle scrolling keys + useInput( + (input: string, key: Key) => { + // Always handle escape to close modal + if (key.escape) { + setState("form"); + setResult(null); + onClose(); + return; + } + + if (state === "form") { + // In form mode, let the form handle all other input + // Don't process anything else - this prevents input from reaching underlying components + return; + } + + if (state === "results") { + // Allow scrolling in results view + if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } + } + }, + { isActive: true }, + ); + + const handleFormSubmit = async (values: Record) => { + if (!inspectorClient || !template) return; + + setState("loading"); + const startTime = Date.now(); + + try { + // Use InspectorClient's readResourceFromTemplate method which encapsulates template expansion and resource reading + const invocation = await inspectorClient.readResourceFromTemplate( + template.uriTemplate, + values, + ); + + const duration = Date.now() - startTime; + + setResult({ + input: values, + output: invocation.result, // Extract the SDK result from the invocation + duration, + uri: invocation.expandedUri, // Use expandedUri instead of uri + }); + setState("results"); + } catch (error) { + const duration = Date.now() - startTime; + const errorMessage = getErrorMessage(error); + + // Try to get expanded URI from error if available, otherwise use template + let uri = template.uriTemplate; + // If the error response contains uri, use it + if (error && typeof error === "object" && "uri" in error) { + uri = (error as any).uri; + } + + // Extract detailed error information + const errorObj: any = { + message: errorMessage, + }; + if (error instanceof Error) { + errorObj.name = error.name; + errorObj.stack = error.stack; + } else if (error && typeof error === "object") { + // Try to extract more details from error object + Object.assign(errorObj, error); + } else { + errorObj.error = String(error); + } + + setResult({ + input: values, + output: null, + error: errorMessage, + errorDetails: errorObj, + duration, + uri, + }); + setState("results"); + } + }; + + // Calculate modal dimensions - use almost full screen + const modalWidth = terminalDimensions.width - 2; + const modalHeight = terminalDimensions.height - 2; + + return ( + + {/* Modal Content */} + + {/* Header */} + + + {formStructure.title} + + + (Press ESC to close) + + + {/* Content Area */} + + {state === "form" && ( + + {template.description && ( + + {template.description} + + )} + + handleFormSubmit(values as Record) + } + /> + + )} + + {state === "loading" && ( + + Reading resource... + + )} + + {state === "results" && result && ( + + + {/* Timing */} + + + Duration: {result.duration}ms + + + + {/* URI */} + + + URI:{" "} + + {result.uri} + + + {/* Input */} + + + Template Values: + + + + {JSON.stringify(result.input, null, 2)} + + + + + {/* Output or Error */} + {result.error ? ( + + + + Error: + + + + {result.error} + + {result.errorDetails && ( + <> + + + Error Details: + + + + + {JSON.stringify(result.errorDetails, null, 2)} + + + + )} + + ) : ( + + + Resource Content: + + + + {JSON.stringify(result.output, null, 2)} + + + + )} + + + )} + + + + ); +} diff --git a/tui/src/components/ResourcesTab.tsx b/tui/src/components/ResourcesTab.tsx new file mode 100644 index 000000000..6c9ec7018 --- /dev/null +++ b/tui/src/components/ResourcesTab.tsx @@ -0,0 +1,413 @@ +import React, { useState, useEffect, useRef, useMemo } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { useSelectableList } from "../hooks/useSelectableList.js"; + +interface ResourceTemplate { + name: string; + uriTemplate: string; + description?: string; +} + +interface ResourcesTabProps { + resources: any[]; + resourceTemplates?: ResourceTemplate[]; + inspectorClient: InspectorClient | null; + width: number; + height: number; + onCountChange?: (count: number) => void; + focusedPane?: "list" | "details" | null; + onViewDetails?: (resource: any) => void; + onFetchResource?: (resource: any) => void; + onFetchTemplate?: (template: ResourceTemplate) => void; + modalOpen?: boolean; +} + +export function ResourcesTab({ + resources, + resourceTemplates = [], + inspectorClient, + width, + height, + onCountChange, + focusedPane = null, + onViewDetails, + onFetchResource, + onFetchTemplate, + modalOpen = false, +}: ResourcesTabProps) { + const [error, setError] = useState(null); + const [resourceContent, setResourceContent] = useState(null); + const [loading, setLoading] = useState(false); + const [shouldFetchResource, setShouldFetchResource] = useState( + null, + ); + const scrollViewRef = useRef(null); + + // Combined list: resources first, then templates - memoized to prevent unnecessary recalculations + const allItems = useMemo( + () => [ + ...resources.map((r) => ({ type: "resource" as const, data: r })), + ...resourceTemplates.map((t) => ({ type: "template" as const, data: t })), + ], + [resources, resourceTemplates], + ); + const totalCount = useMemo( + () => resources.length + resourceTemplates.length, + [resources.length, resourceTemplates.length], + ); + + const visibleCount = Math.max(1, height - 7); + const { selectedIndex, firstVisible, setSelection } = useSelectableList( + totalCount, + visibleCount, + { resetWhen: [resources] }, + ); + const selectedItem = useMemo( + () => allItems[selectedIndex] || null, + [allItems, selectedIndex], + ); + + // Handle arrow key navigation when focused + useInput( + (input: string, key: Key) => { + // Handle Enter key to fetch resource (works from both list and details) + if ( + key.return && + selectedItem && + inspectorClient && + (onFetchResource || onFetchTemplate) + ) { + if (selectedItem.type === "resource" && selectedItem.data.uri) { + // Trigger fetch for regular resource + setShouldFetchResource(selectedItem.data.uri); + if (onFetchResource) { + onFetchResource(selectedItem.data); + } + } else if (selectedItem.type === "template" && onFetchTemplate) { + // Open modal for template + onFetchTemplate(selectedItem.data); + } + return; + } + + if (focusedPane === "list") { + if (key.upArrow && selectedIndex > 0) { + setSelection(selectedIndex - 1); + } else if (key.downArrow && selectedIndex < totalCount - 1) { + setSelection(selectedIndex + 1); + } + return; + } + + if (focusedPane === "details") { + // Handle '+' key to view in full screen modal + if (input === "+" && resourceContent && onViewDetails) { + onViewDetails({ content: resourceContent }); + return; + } + + // Scroll the details pane using ink-scroll-view + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { + isActive: + !modalOpen && (focusedPane === "list" || focusedPane === "details"), + }, + ); + + // Reset scroll when selection changes + useEffect(() => { + scrollViewRef.current?.scrollTo(0); + }, [selectedIndex]); + + // Clear fetched content when resources change + const prevResourcesRef = useRef(resources); + useEffect(() => { + if (prevResourcesRef.current !== resources) { + setResourceContent(null); + setShouldFetchResource(null); + prevResourcesRef.current = resources; + } + }, [resources]); + + const isResource = selectedItem?.type === "resource"; + const isTemplate = selectedItem?.type === "template"; + const selectedResource = isResource ? selectedItem.data : null; + const selectedTemplate = isTemplate ? selectedItem.data : null; + + // Fetch resource content when shouldFetchResource is set + useEffect(() => { + if (!shouldFetchResource || !inspectorClient) return; + + const fetchContent = async () => { + setLoading(true); + setError(null); + try { + const invocation = + await inspectorClient.readResource(shouldFetchResource); + setResourceContent(invocation.result); + } catch (err) { + setError( + err instanceof Error ? err.message : "Failed to read resource", + ); + setResourceContent(null); + } finally { + setLoading(false); + setShouldFetchResource(null); + } + }; + + fetchContent(); + }, [shouldFetchResource, inspectorClient]); + + const listWidth = Math.floor(width * 0.4); + const detailWidth = width - listWidth; + + // Update count when items change - use ref to track previous count and only call when it actually changes + const prevCountRef = useRef(totalCount); + useEffect(() => { + if (prevCountRef.current !== totalCount) { + prevCountRef.current = totalCount; + onCountChange?.(totalCount); + } + }, [totalCount, onCountChange]); + + return ( + + {/* Resources and Templates List */} + + + + Resources ({totalCount}) + + + {error ? ( + + {error} + + ) : totalCount === 0 ? ( + + No resources available + + ) : ( + + {allItems + .slice(firstVisible, firstVisible + visibleCount) + .map((item, i) => { + const index = firstVisible + i; + const isSelected = index === selectedIndex; + const label = + item.type === "resource" + ? item.data.name || item.data.uri || `Resource ${index + 1}` + : item.data.name || + `Template ${index - resources.length + 1}`; + const key = + item.type === "resource" + ? item.data.uri || index + : item.data.uriTemplate || index; + return ( + + + {isSelected ? "▶ " : " "} + {label} + + + ); + })} + + )} + + + {/* Resource Details */} + + {selectedResource ? ( + <> + {/* Fixed header */} + + + {selectedResource.name || selectedResource.uri} + + + + {/* Scrollable content area */} + + {/* Description */} + {selectedResource.description && ( + <> + {selectedResource.description + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + )} + + {/* URI */} + {selectedResource.uri && ( + + URI: {selectedResource.uri} + + )} + + {/* MIME Type */} + {selectedResource.mimeType && ( + + MIME Type: {selectedResource.mimeType} + + )} + + {/* Resource Content */} + {loading && ( + + Loading resource content... + + )} + + {!loading && resourceContent && ( + <> + + Content: + + + + {JSON.stringify(resourceContent, null, 2)} + + + + )} + + {!loading && !resourceContent && selectedResource.uri && ( + + [Enter to Fetch Resource] + + )} + + + {/* Fixed footer - only show when details pane is focused */} + {focusedPane === "details" && ( + + + {resourceContent + ? "↑/↓ to scroll, + to zoom" + : "Enter to fetch, ↑/↓ to scroll"} + + + )} + + ) : selectedTemplate ? ( + <> + {/* Fixed header */} + + + {selectedTemplate.name} + + + + {/* Scrollable content area */} + + {/* Description */} + {selectedTemplate.description && ( + <> + {selectedTemplate.description + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + )} + + {/* URI Template */} + {selectedTemplate.uriTemplate && ( + + + URI Template: {selectedTemplate.uriTemplate} + + + )} + + + [Enter to Fetch Resource] + + + + {/* Fixed footer - only show when details pane is focused */} + {focusedPane === "details" && ( + + + Enter to fetch + + + )} + + ) : ( + + Select a resource or template to view details + + )} + + + ); +} diff --git a/tui/src/components/SelectableItem.tsx b/tui/src/components/SelectableItem.tsx new file mode 100644 index 000000000..a87315a34 --- /dev/null +++ b/tui/src/components/SelectableItem.tsx @@ -0,0 +1,22 @@ +import React from "react"; +import { Box, Text } from "ink"; + +/** Renders a selectable item: ▶ + space when selected, space + space when not. Fixed width to prevent layout shift. */ +export function SelectableItem({ + isSelected, + bold, + children, +}: { + isSelected: boolean; + bold?: boolean; + children: React.ReactNode; +}) { + return ( + + + {isSelected ? "▶ " : " "} + + {children} + + ); +} diff --git a/tui/src/components/Tabs.tsx b/tui/src/components/Tabs.tsx new file mode 100644 index 000000000..bbbdc500d --- /dev/null +++ b/tui/src/components/Tabs.tsx @@ -0,0 +1,106 @@ +import React from "react"; +import { Box, Text } from "ink"; + +export type TabType = + | "info" + | "auth" + | "resources" + | "prompts" + | "tools" + | "messages" + | "requests" + | "logging"; + +interface TabsProps { + activeTab: TabType; + onTabChange: (tab: TabType) => void; + width: number; + counts?: { + info?: number; + auth?: number; + resources?: number; + prompts?: number; + tools?: number; + messages?: number; + requests?: number; + logging?: number; + }; + focused?: boolean; + showAuth?: boolean; + showLogging?: boolean; + showRequests?: boolean; +} + +export const tabs: { id: TabType; label: string; accelerator: string }[] = [ + { id: "info", label: "Info", accelerator: "i" }, + { id: "auth", label: "Auth", accelerator: "a" }, + { id: "resources", label: "Resources", accelerator: "r" }, + { id: "prompts", label: "Prompts", accelerator: "p" }, + { id: "tools", label: "Tools", accelerator: "t" }, + { id: "messages", label: "Messages", accelerator: "m" }, + { id: "requests", label: "HTTP Requests", accelerator: "h" }, + { id: "logging", label: "Logging", accelerator: "l" }, +]; + +export function Tabs({ + activeTab, + onTabChange, + width, + counts = {}, + focused = false, + showAuth = true, + showLogging = true, + showRequests = false, +}: TabsProps) { + let visibleTabs = tabs; + if (!showAuth) { + visibleTabs = visibleTabs.filter((tab) => tab.id !== "auth"); + } + if (!showLogging) { + visibleTabs = visibleTabs.filter((tab) => tab.id !== "logging"); + } + if (!showRequests) { + visibleTabs = visibleTabs.filter((tab) => tab.id !== "requests"); + } + + return ( + + {visibleTabs.map((tab) => { + const isActive = activeTab === tab.id; + const count = counts[tab.id]; + const countText = count !== undefined ? ` (${count})` : ""; + const firstChar = tab.label[0]; + const restOfLabel = tab.label.slice(1); + + return ( + + + {isActive ? "▶ " : " "} + {firstChar} + {restOfLabel} + {countText} + + + ); + })} + + ); +} diff --git a/tui/src/components/ToolTestModal.tsx b/tui/src/components/ToolTestModal.tsx new file mode 100644 index 000000000..ad44505b5 --- /dev/null +++ b/tui/src/components/ToolTestModal.tsx @@ -0,0 +1,282 @@ +import React, { useState, useEffect } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { Form } from "ink-form"; +import { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { schemaToForm } from "../utils/schemaToForm.js"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; + +interface ToolTestModalProps { + tool: any; + inspectorClient: InspectorClient | null; + width: number; + height: number; + onClose: () => void; +} + +type ModalState = "form" | "loading" | "results"; + +interface ToolResult { + input: any; + output: any; + error?: string; + errorDetails?: any; + duration: number; +} + +export function ToolTestModal({ + tool, + inspectorClient, + width, + height, + onClose, +}: ToolTestModalProps) { + const [state, setState] = useState("form"); + const [result, setResult] = useState(null); + const scrollViewRef = React.useRef(null); + + // Use full terminal dimensions instead of passed dimensions + const [terminalDimensions, setTerminalDimensions] = React.useState({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + + React.useEffect(() => { + const updateDimensions = () => { + setTerminalDimensions({ + width: process.stdout.columns || width, + height: process.stdout.rows || height, + }); + }; + process.stdout.on("resize", updateDimensions); + updateDimensions(); + return () => { + process.stdout.off("resize", updateDimensions); + }; + }, [width, height]); + + const formStructure = tool?.inputSchema + ? schemaToForm(tool.inputSchema, tool.name || "Unknown Tool") + : { + title: `Test Tool: ${tool?.name || "Unknown"}`, + sections: [{ title: "Parameters", fields: [] }], + }; + + // Reset state when modal closes + React.useEffect(() => { + return () => { + // Cleanup: reset state when component unmounts + setState("form"); + setResult(null); + }; + }, []); + + // Handle all input when modal is open - prevents input from reaching underlying components + // When in form mode, only handle escape (form handles its own input) + // When in results mode, handle scrolling keys + useInput( + (input: string, key: Key) => { + // Always handle escape to close modal + if (key.escape) { + setState("form"); + setResult(null); + onClose(); + return; + } + + if (state === "form") { + // In form mode, let the form handle all other input + // Don't process anything else - this prevents input from reaching underlying components + return; + } + + if (state === "results") { + // Allow scrolling in results view + if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } + } + }, + { isActive: true }, + ); + + const handleFormSubmit = async (values: Record) => { + if (!inspectorClient || !tool) return; + + setState("loading"); + const startTime = Date.now(); + + try { + // Use InspectorClient.callTool() which handles parameter conversion and metadata + const invocation = await inspectorClient.callTool(tool.name, values); + + const duration = Date.now() - startTime; + + // InspectorClient.callTool() returns ToolCallInvocation + // Check if the call succeeded and extract the result + if (!invocation.success || invocation.result === null) { + // Error case: tool call failed + setResult({ + input: values, + output: null, + error: invocation.error || "Tool call failed", + errorDetails: invocation, + duration, + }); + } else { + // Success case: extract the result + const result = invocation.result; + // Check for error indicators in the result (SDK may return error in result) + const isError = "isError" in result && result.isError === true; + const output = isError + ? { error: true, content: result.content } + : result.structuredContent || result.content || result; + + setResult({ + input: values, + output: isError ? null : output, + error: isError ? "Tool returned an error" : undefined, + errorDetails: isError ? output : undefined, + duration, + }); + } + setState("results"); + } catch (error) { + const duration = Date.now() - startTime; + const errorObj = + error instanceof Error + ? { message: error.message, name: error.name, stack: error.stack } + : { error: String(error) }; + + setResult({ + input: values, + output: null, + error: error instanceof Error ? error.message : "Unknown error", + errorDetails: errorObj, + duration, + }); + setState("results"); + } + }; + + // Calculate modal dimensions - use almost full screen + const modalWidth = terminalDimensions.width - 2; + const modalHeight = terminalDimensions.height - 2; + + return ( + + {/* Modal Content */} + + {/* Header */} + + + {formStructure.title} + + + (Press ESC to close) + + + {/* Content Area */} + + {state === "form" && ( + + + + )} + + {state === "loading" && ( + + Calling tool... + + )} + + {state === "results" && result && ( + + + {/* Timing */} + + + Duration: {result.duration}ms + + + + {/* Input */} + + + Input: + + + + {JSON.stringify(result.input, null, 2)} + + + + + {/* Output or Error */} + {result.error ? ( + + + Error: + + + {result.error} + + {result.errorDetails && ( + <> + + + Error Details: + + + + + {JSON.stringify(result.errorDetails, null, 2)} + + + + )} + + ) : ( + + + Output: + + + + {JSON.stringify(result.output, null, 2)} + + + + )} + + + )} + + + + ); +} diff --git a/tui/src/components/ToolsTab.tsx b/tui/src/components/ToolsTab.tsx new file mode 100644 index 000000000..8d1b5222b --- /dev/null +++ b/tui/src/components/ToolsTab.tsx @@ -0,0 +1,254 @@ +import React, { useState, useEffect, useRef } from "react"; +import { Box, Text, useInput, type Key } from "ink"; +import { ScrollView, type ScrollViewRef } from "ink-scroll-view"; +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { useSelectableList } from "../hooks/useSelectableList.js"; + +interface ToolsTabProps { + tools: any[]; + client: Client | null; + width: number; + height: number; + onCountChange?: (count: number) => void; + focusedPane?: "list" | "details" | null; + onTestTool?: (tool: any) => void; + onViewDetails?: (tool: any) => void; + modalOpen?: boolean; +} + +export function ToolsTab({ + tools, + client, + width, + height, + onCountChange, + focusedPane = null, + onTestTool, + onViewDetails, + modalOpen = false, +}: ToolsTabProps) { + const visibleCount = Math.max(1, height - 7); + const { selectedIndex, firstVisible, setSelection } = useSelectableList( + tools.length, + visibleCount, + { resetWhen: [tools] }, + ); + const [error, setError] = useState(null); + const scrollViewRef = useRef(null); + const listWidth = Math.floor(width * 0.4); + const detailWidth = width - listWidth; + + // Handle arrow key navigation when focused + useInput( + (input: string, key: Key) => { + // Handle Enter key to test tool (works from both list and details) + if (key.return && selectedTool && client && onTestTool) { + onTestTool(selectedTool); + return; + } + + if (focusedPane === "list") { + if (key.upArrow && selectedIndex > 0) { + setSelection(selectedIndex - 1); + } else if (key.downArrow && selectedIndex < tools.length - 1) { + setSelection(selectedIndex + 1); + } + return; + } + + if (focusedPane === "details") { + // Handle '+' key to view in full screen modal + if (input === "+" && selectedTool && onViewDetails) { + onViewDetails(selectedTool); + return; + } + + // Scroll the details pane using ink-scroll-view + if (key.upArrow) { + scrollViewRef.current?.scrollBy(-1); + } else if (key.downArrow) { + scrollViewRef.current?.scrollBy(1); + } else if (key.pageUp) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(-viewportHeight); + } else if (key.pageDown) { + const viewportHeight = + scrollViewRef.current?.getViewportHeight() || 1; + scrollViewRef.current?.scrollBy(viewportHeight); + } + } + }, + { + isActive: + !modalOpen && (focusedPane === "list" || focusedPane === "details"), + }, + ); + + // Helper to calculate content lines for a tool + const calculateToolContentLines = (tool: any): number => { + let lines = 1; // Name + if (tool.description) lines += tool.description.split("\n").length + 1; + if (tool.inputSchema) { + const schemaStr = JSON.stringify(tool.inputSchema, null, 2); + lines += schemaStr.split("\n").length + 2; // +2 for "Input Schema:" label + } + return lines; + }; + + // Reset scroll when selection changes + useEffect(() => { + scrollViewRef.current?.scrollTo(0); + }, [selectedIndex]); + + const selectedTool = tools[selectedIndex] || null; + + return ( + + {/* Tools List */} + + + + Tools ({tools.length}) + + + {error ? ( + + {error} + + ) : tools.length === 0 ? ( + + No tools available + + ) : ( + + {tools + .slice(firstVisible, firstVisible + visibleCount) + .map((tool, i) => { + const index = firstVisible + i; + const isSelected = index === selectedIndex; + return ( + + + {isSelected ? "▶ " : " "} + {tool.name || `Tool ${index + 1}`} + + + ); + })} + + )} + + + {/* Tool Details */} + + {selectedTool ? ( + <> + {/* Fixed header */} + + + {selectedTool.name} + + {client && ( + + + [Enter to Test] + + + )} + + + {/* Scrollable content area - direct ScrollView with height prop like NotificationsTab */} + + {/* Description */} + {selectedTool.description && ( + <> + {selectedTool.description + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + )} + + {/* Input Schema */} + {selectedTool.inputSchema && ( + <> + + Input Schema: + + {JSON.stringify(selectedTool.inputSchema, null, 2) + .split("\n") + .map((line: string, idx: number) => ( + + {line} + + ))} + + )} + + + {/* Fixed footer - only show when details pane is focused */} + {focusedPane === "details" && ( + + + ↑/↓ to scroll, + to zoom + + + )} + + ) : ( + + Select a tool to view details + + )} + + + ); +} diff --git a/tui/src/hooks/useSelectableList.ts b/tui/src/hooks/useSelectableList.ts new file mode 100644 index 000000000..8165edd18 --- /dev/null +++ b/tui/src/hooks/useSelectableList.ts @@ -0,0 +1,62 @@ +import { useState, useEffect, useCallback } from "react"; + +function clampFirstVisible( + first: number, + selected: number, + visibleCount: number, + total: number, +): number { + if (selected < first) return selected; + if (selected >= first + visibleCount) return selected - visibleCount + 1; + return first; +} + +export interface UseSelectableListOptions { + /** When these change, reset selection to 0 (e.g. [tools] when switching servers) */ + resetWhen?: unknown[]; +} + +/** + * Manages selection and scroll position for a virtualized list. + * Returns selection state and a setSelection that updates both + * selectedIndex and firstVisible so the selected item stays in view. + */ +export function useSelectableList( + itemCount: number, + visibleCount: number, + options?: UseSelectableListOptions, +) { + const [selectedIndex, setSelectedIndex] = useState(0); + const [firstVisible, setFirstVisible] = useState(0); + + const setSelection = useCallback( + (newIndex: number) => { + setSelectedIndex(newIndex); + setFirstVisible((prev) => + clampFirstVisible(prev, newIndex, visibleCount, itemCount), + ); + }, + [visibleCount, itemCount], + ); + + // Reset when deps change (e.g. different server) + useEffect(() => { + if (options?.resetWhen) { + setSelectedIndex(0); + setFirstVisible(0); + } + }, options?.resetWhen ?? []); + + // Clamp when list shrinks + useEffect(() => { + if (itemCount > 0 && selectedIndex >= itemCount) { + const newIndex = itemCount - 1; + setSelectedIndex(newIndex); + setFirstVisible((prev) => + clampFirstVisible(prev, newIndex, visibleCount, itemCount), + ); + } + }, [itemCount, selectedIndex, visibleCount]); + + return { selectedIndex, firstVisible, setSelection }; +} diff --git a/tui/src/logger.ts b/tui/src/logger.ts new file mode 100644 index 000000000..fe64650f6 --- /dev/null +++ b/tui/src/logger.ts @@ -0,0 +1,23 @@ +import path from "node:path"; +import pino from "pino"; + +const logDir = + process.env.MCP_INSPECTOR_LOG_DIR ?? + path.join( + process.env.HOME || process.env.USERPROFILE || ".", + ".mcp-inspector", + ); +const logPath = path.join(logDir, "auth.log"); + +/** + * TUI file logger for auth and InspectorClient events. + * Writes to ~/.mcp-inspector/auth.log so TUI console output is not corrupted. + * The app controls logger creation and configuration. + */ +export const tuiLogger = pino( + { + name: "mcp-inspector-tui", + level: process.env.LOG_LEVEL ?? "info", + }, + pino.destination({ dest: logPath, append: true, mkdir: true }), +); diff --git a/tui/src/utils/openUrl.ts b/tui/src/utils/openUrl.ts new file mode 100644 index 000000000..a2a7d9639 --- /dev/null +++ b/tui/src/utils/openUrl.ts @@ -0,0 +1,12 @@ +import open from "open"; + +/** + * Opens a URL in the user's default browser. + * Used when handling oauthAuthorizationRequired to launch the OAuth authorization page. + * + * @param url - URL to open (string or URL) + * @returns Promise that resolves when the opener completes (or rejects on error) + */ +export async function openUrl(url: string | URL): Promise { + await open(typeof url === "string" ? url : url.href); +} diff --git a/tui/src/utils/promptArgsToForm.ts b/tui/src/utils/promptArgsToForm.ts new file mode 100644 index 000000000..185f77da0 --- /dev/null +++ b/tui/src/utils/promptArgsToForm.ts @@ -0,0 +1,46 @@ +/** + * Converts prompt arguments to ink-form format + */ + +import type { FormStructure, FormSection, FormField } from "ink-form"; + +/** + * Converts prompt arguments array to ink-form structure + */ +export function promptArgsToForm( + promptArguments: any[], + promptName: string, +): FormStructure { + const fields: FormField[] = []; + + if (!promptArguments || promptArguments.length === 0) { + return { + title: `Get Prompt: ${promptName}`, + sections: [{ title: "Parameters", fields: [] }], + }; + } + + for (const arg of promptArguments) { + const field: FormField = { + name: arg.name, + label: arg.name, + type: "string", // Prompt arguments are always strings + required: arg.required !== false, // Default to required unless explicitly false + description: arg.description, + }; + + fields.push(field); + } + + const sections: FormSection[] = [ + { + title: "Prompt Arguments", + fields, + }, + ]; + + return { + title: `Get Prompt: ${promptName}`, + sections, + }; +} diff --git a/tui/src/utils/schemaToForm.ts b/tui/src/utils/schemaToForm.ts new file mode 100644 index 000000000..245ae2ab7 --- /dev/null +++ b/tui/src/utils/schemaToForm.ts @@ -0,0 +1,116 @@ +/** + * Converts JSON Schema to ink-form format + */ + +import type { FormStructure, FormSection, FormField } from "ink-form"; + +/** + * Converts a JSON Schema to ink-form structure + */ +export function schemaToForm(schema: any, toolName: string): FormStructure { + const fields: FormField[] = []; + + if (!schema || !schema.properties) { + return { + title: `Test Tool: ${toolName}`, + sections: [{ title: "Parameters", fields: [] }], + }; + } + + const properties = schema.properties || {}; + const required = schema.required || []; + + for (const [key, prop] of Object.entries(properties)) { + const property = prop as any; + const baseField = { + name: key, + label: property.title || key, + required: required.includes(key), + }; + + let field: FormField; + + // Handle enum -> select + if (property.enum) { + if (property.type === "array" && property.items?.enum) { + // For array of enums, we'll use select but handle it differently + // Note: ink-form doesn't have multiselect, so we'll use select + field = { + type: "select", + ...baseField, + options: property.items.enum.map((val: any) => ({ + label: String(val), + value: String(val), + })), + } as FormField; + } else { + // Single select + field = { + type: "select", + ...baseField, + options: property.enum.map((val: any) => ({ + label: String(val), + value: String(val), + })), + } as FormField; + } + } else { + // Map JSON Schema types to ink-form types + switch (property.type) { + case "string": + field = { + type: "string", + ...baseField, + } as FormField; + break; + case "integer": + field = { + type: "integer", + ...baseField, + ...(property.minimum !== undefined && { min: property.minimum }), + ...(property.maximum !== undefined && { max: property.maximum }), + } as FormField; + break; + case "number": + field = { + type: "float", + ...baseField, + ...(property.minimum !== undefined && { min: property.minimum }), + ...(property.maximum !== undefined && { max: property.maximum }), + } as FormField; + break; + case "boolean": + field = { + type: "boolean", + ...baseField, + } as FormField; + break; + default: + // Default to string for unknown types + field = { + type: "string", + ...baseField, + } as FormField; + } + } + + // Set initial value from default + if (property.default !== undefined) { + (field as any).initialValue = property.default; + } + + fields.push(field); + } + + const sections: FormSection[] = [ + { + title: "Parameters", + fields, + }, + ]; + + return { + title: `Test Tool: ${toolName}`, + sections, + }; +} diff --git a/tui/src/utils/uriTemplateToForm.ts b/tui/src/utils/uriTemplateToForm.ts new file mode 100644 index 000000000..f8d2ee10b --- /dev/null +++ b/tui/src/utils/uriTemplateToForm.ts @@ -0,0 +1,47 @@ +/** + * Converts URI Template to ink-form format for resource templates + */ + +import type { FormStructure, FormSection, FormField } from "ink-form"; +import { UriTemplate } from "@modelcontextprotocol/sdk/shared/uriTemplate.js"; + +/** + * Converts a URI Template to ink-form structure + */ +export function uriTemplateToForm( + uriTemplate: string, + templateName: string, +): FormStructure { + const fields: FormField[] = []; + + try { + const template = new UriTemplate(uriTemplate); + const variableNames = template.variableNames || []; + + for (const variableName of variableNames) { + const field: FormField = { + name: variableName, + label: variableName, + type: "string", + required: false, // URI template variables are typically optional + }; + + fields.push(field); + } + } catch (error) { + // If parsing fails, return empty form + console.error("Failed to parse URI template:", error); + } + + const sections: FormSection[] = [ + { + title: "Template Variables", + fields, + }, + ]; + + return { + title: `Read Resource: ${templateName}`, + sections, + }; +} diff --git a/tui/test-config.json b/tui/test-config.json new file mode 100644 index 000000000..0738f3328 --- /dev/null +++ b/tui/test-config.json @@ -0,0 +1 @@ +{ "servers": [] } diff --git a/tui/tsconfig.json b/tui/tsconfig.json new file mode 100644 index 000000000..c18f3bbb2 --- /dev/null +++ b/tui/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "Node16", + "moduleResolution": "node16", + "jsx": "react-jsx", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "outDir": "./build", + "rootDir": "." + }, + "include": ["src/**/*", "tui.tsx"], + "exclude": ["node_modules", "build"], + "references": [{ "path": "../shared" }] +} diff --git a/tui/tui.tsx b/tui/tui.tsx new file mode 100755 index 000000000..bfbf92aca --- /dev/null +++ b/tui/tui.tsx @@ -0,0 +1,152 @@ +#!/usr/bin/env node + +import { Command } from "commander"; +import { render } from "ink"; +import App from "./src/App.js"; + +export async function runTui(args?: string[]): Promise { + const program = new Command(); + + program + .name("mcp-inspector-tui") + .description("Terminal UI for MCP Inspector") + .argument("", "path to MCP servers config file") + .option( + "--client-id ", + "OAuth client ID (static client) for HTTP servers", + ) + .option( + "--client-secret ", + "OAuth client secret (for confidential clients)", + ) + .option( + "--client-metadata-url ", + "OAuth Client ID Metadata Document URL (CIMD) for HTTP servers", + ) + .option( + "--callback-url ", + "OAuth redirect/callback listener URL (default: http://127.0.0.1:0/oauth/callback)", + ) + .parse(args ?? process.argv); + + const configFile = program.args[0]; + const options = program.opts() as { + clientId?: string; + clientSecret?: string; + clientMetadataUrl?: string; + callbackUrl?: string; + }; + + if (!configFile) { + program.error("Config file is required"); + } + + interface CallbackUrlConfig { + hostname: string; + port: number; + pathname: string; + } + + function parseCallbackUrl(raw?: string): CallbackUrlConfig { + if (!raw) { + return { hostname: "127.0.0.1", port: 0, pathname: "/oauth/callback" }; + } + let url: URL; + try { + url = new URL(raw); + } catch (err) { + program.error( + `Invalid callback URL: ${(err as Error)?.message ?? String(err)}`, + ); + return { hostname: "127.0.0.1", port: 0, pathname: "/oauth/callback" }; + } + if (url.protocol !== "http:") { + program.error("Callback URL must use http scheme"); + return { hostname: "127.0.0.1", port: 0, pathname: "/oauth/callback" }; + } + const hostname = url.hostname; + if (!hostname) { + program.error("Callback URL must include a hostname"); + return { hostname: "127.0.0.1", port: 0, pathname: "/oauth/callback" }; + } + const pathname = url.pathname || "/"; + let port: number; + if (url.port === "") { + port = 80; + } else { + port = Number(url.port); + if ( + !Number.isFinite(port) || + !Number.isInteger(port) || + port < 0 || + port > 65535 + ) { + program.error("Callback URL port must be between 0 and 65535"); + } + } + return { hostname, port, pathname }; + } + + const callbackUrlConfig = parseCallbackUrl(options.callbackUrl); + + // Intercept stdout.write to filter out \x1b[3J (Erase Saved Lines) + // This prevents Ink's clearTerminal from clearing scrollback on macOS Terminal + // We can't access Ink's internal instance to prevent clearTerminal from being called, + // so we filter the escape code instead + const originalWrite = process.stdout.write.bind(process.stdout); + process.stdout.write = function ( + chunk: any, + encoding?: any, + cb?: any, + ): boolean { + if (typeof chunk === "string") { + // Only process if the escape code is present (minimize overhead) + if (chunk.includes("\x1b[3J")) { + chunk = chunk.replace(/\x1b\[3J/g, ""); + } + } else if (Buffer.isBuffer(chunk)) { + // Only process if the escape code is present (minimize overhead) + if (chunk.includes("\x1b[3J")) { + let str = chunk.toString("utf8"); + str = str.replace(/\x1b\[3J/g, ""); + chunk = Buffer.from(str, "utf8"); + } + } + return originalWrite(chunk, encoding, cb); + }; + + // Enter alternate screen buffer before rendering + if (process.stdout.isTTY) { + process.stdout.write("\x1b[?1049h"); + } + + // Render the app + const instance = render( + , + ); + + // Wait for exit, then switch back from alternate screen + try { + await instance.waitUntilExit(); + // Unmount has completed - clearTerminal was patched to not include \x1b[3J + // Switch back from alternate screen + if (process.stdout.isTTY) { + process.stdout.write("\x1b[?1049l"); + } + process.exit(0); + } catch (error: unknown) { + if (process.stdout.isTTY) { + process.stdout.write("\x1b[?1049l"); + } + console.error("Error:", error); + process.exit(1); + } +} + +runTui(); diff --git a/web/.gitignore b/web/.gitignore new file mode 100644 index 000000000..a547bf36d --- /dev/null +++ b/web/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/web/README.md b/web/README.md new file mode 100644 index 000000000..780c92d8b --- /dev/null +++ b/web/README.md @@ -0,0 +1,50 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: + +- Configure the top-level `parserOptions` property like this: + +```js +export default tseslint.config({ + languageOptions: { + // other options... + parserOptions: { + project: ["./tsconfig.node.json", "./tsconfig.app.json"], + tsconfigRootDir: import.meta.dirname, + }, + }, +}); +``` + +- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` +- Optionally add `...tseslint.configs.stylisticTypeChecked` +- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: + +```js +// eslint.config.js +import react from "eslint-plugin-react"; + +export default tseslint.config({ + // Set the react version + settings: { react: { version: "18.3" } }, + plugins: { + // Add the react plugin + react, + }, + rules: { + // other rules... + // Enable its recommended rules + ...react.configs.recommended.rules, + ...react.configs["jsx-runtime"].rules, + }, +}); +``` diff --git a/web/bin/client.js b/web/bin/client.js new file mode 100755 index 000000000..2a7419e66 --- /dev/null +++ b/web/bin/client.js @@ -0,0 +1,62 @@ +#!/usr/bin/env node + +import open from "open"; +import { join, dirname } from "path"; +import { fileURLToPath } from "url"; +import handler from "serve-handler"; +import http from "http"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const distPath = join(__dirname, "../dist"); + +const server = http.createServer((request, response) => { + const handlerOptions = { + public: distPath, + rewrites: [{ source: "/**", destination: "/index.html" }], + headers: [ + { + // Ensure index.html is never cached + source: "index.html", + headers: [ + { + key: "Cache-Control", + value: "no-cache, no-store, max-age=0", + }, + ], + }, + { + // Allow long-term caching for hashed assets + source: "assets/**", + headers: [ + { + key: "Cache-Control", + value: "public, max-age=31536000, immutable", + }, + ], + }, + ], + }; + + return handler(request, response, handlerOptions); +}); + +const port = parseInt(process.env.CLIENT_PORT || "6274", 10); +const host = process.env.HOST || "localhost"; +server.on("listening", () => { + const url = process.env.INSPECTOR_URL || `http://${host}:${port}`; + console.log(`\n🚀 MCP Inspector is up and running at:\n ${url}\n`); + if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") { + console.log(`🌐 Opening browser...`); + open(url); + } +}); +server.on("error", (err) => { + if (err.message.includes(`EADDRINUSE`)) { + console.error( + `❌ MCP Inspector PORT IS IN USE at http://${host}:${port} ❌ `, + ); + } else { + throw err; + } +}); +server.listen(port, host); diff --git a/web/bin/server.js b/web/bin/server.js new file mode 100755 index 000000000..63fcd9b23 --- /dev/null +++ b/web/bin/server.js @@ -0,0 +1,92 @@ +#!/usr/bin/env node + +import { serve } from "@hono/node-server"; +import { serveStatic } from "@hono/node-server/serve-static"; +import { Hono } from "hono"; +import { createRemoteApp } from "@modelcontextprotocol/inspector-shared/mcp/remote/node"; +import { join, dirname } from "path"; +import { fileURLToPath } from "url"; +import { randomBytes } from "node:crypto"; +import pino from "pino"; +import { readFileSync } from "node:fs"; +import { API_SERVER_ENV_VARS } from "@modelcontextprotocol/inspector-shared/mcp/remote"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const distPath = join(__dirname, "../dist"); + +const app = new Hono(); + +// Read Inspector API auth token from env (provided by start script via spawn env) +// createRemoteApp will use this, or generate one if not provided +// The token is passed explicitly from start script, not written to process.env +const authToken = + process.env[API_SERVER_ENV_VARS.AUTH_TOKEN] || + randomBytes(32).toString("hex"); + +// Add API routes first (more specific) +const port = parseInt(process.env.CLIENT_PORT || "6274", 10); +const host = process.env.HOST || "localhost"; +const baseUrl = `http://${host}:${port}`; + +const { app: apiApp } = createRemoteApp({ + authToken, + storageDir: process.env.MCP_STORAGE_DIR, + allowedOrigins: process.env.ALLOWED_ORIGINS?.split(",") || [baseUrl], + logger: process.env.MCP_LOG_FILE + ? pino( + { level: "info" }, + pino.destination({ + dest: process.env.MCP_LOG_FILE, + append: true, + mkdir: true, + }), + ) + : undefined, +}); +// Mount API app at root - routes inside are /api/mcp/connect, so they become /api/mcp/connect +// Static files need to be served without auth, so we check for /api/* first, then serve static +app.use("/api/*", async (c, next) => { + // Forward /api/* requests to apiApp + return apiApp.fetch(c.req.raw); +}); + +// Serve index.html for root (config is fetched from GET /api/config by the client) +app.get("/", async (c) => { + try { + const indexPath = join(distPath, "index.html"); + const html = readFileSync(indexPath, "utf-8"); + return c.html(html); + } catch (error) { + console.error("Error serving index.html:", error); + return c.notFound(); + } +}); + +// Then add static file serving (fallback for SPA routing) +app.use( + "/*", + serveStatic({ + root: distPath, + rewriteRequestPath: (path) => { + // If path doesn't exist and doesn't have extension, serve index.html (SPA routing) + if (!path.includes(".") && !path.startsWith("/api")) { + return "/index.html"; + } + return path; + }, + }), +); + +serve( + { + fetch: app.fetch, + port, + hostname: host, + }, + (info) => { + console.log( + `\n🚀 MCP Inspector Web is up and running at:\n http://${host}:${info.port}\n`, + ); + console.log(` Auth token: ${authToken}\n`); + }, +); diff --git a/web/bin/start.js b/web/bin/start.js new file mode 100755 index 000000000..338b804f2 --- /dev/null +++ b/web/bin/start.js @@ -0,0 +1,244 @@ +#!/usr/bin/env node + +import open from "open"; +import { resolve, dirname } from "path"; +import { spawnPromise, spawn } from "spawn-rx"; +import { fileURLToPath } from "url"; +import { randomBytes } from "crypto"; +import { API_SERVER_ENV_VARS } from "@modelcontextprotocol/inspector-shared/mcp/remote"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +async function startDevClient(clientOptions) { + const { + CLIENT_PORT, + inspectorApiToken, + command, + mcpServerArgs, + transport, + serverUrl, + envVars, + abort, + cancelled, + } = clientOptions; + const clientCommand = "npx"; + const host = process.env.HOST || "localhost"; + const clientArgs = ["vite", "--port", CLIENT_PORT, "--host", host]; + + // Prepare config values for injection into HTML + const configEnv = { + ...process.env, + CLIENT_PORT, + [API_SERVER_ENV_VARS.AUTH_TOKEN]: inspectorApiToken, // Pass Inspector API token to Vite (read-only) + // Pass config values for HTML injection + ...(command ? { MCP_INITIAL_COMMAND: command } : {}), + ...(mcpServerArgs && mcpServerArgs.length > 0 + ? { MCP_INITIAL_ARGS: mcpServerArgs.join(" ") } + : {}), + ...(transport ? { MCP_INITIAL_TRANSPORT: transport } : {}), + ...(serverUrl ? { MCP_INITIAL_SERVER_URL: serverUrl } : {}), + ...(envVars && Object.keys(envVars).length > 0 + ? { MCP_ENV_VARS: JSON.stringify(envVars) } + : {}), + }; + + const client = spawn(clientCommand, clientArgs, { + cwd: resolve(__dirname, ".."), + env: configEnv, + signal: abort.signal, + echoOutput: true, + }); + + // Include Inspector API auth token in URL for client + const params = new URLSearchParams(); + params.set(API_SERVER_ENV_VARS.AUTH_TOKEN, inspectorApiToken); + const url = + params.size > 0 + ? `http://${host}:${CLIENT_PORT}/?${params.toString()}` + : `http://${host}:${CLIENT_PORT}`; + + // Give vite time to start before opening or logging the URL + setTimeout(() => { + console.log(`\n🚀 MCP Inspector Web is up and running at:\n ${url}\n`); + console.log( + ` Static files served by: Vite (dev) / Inspector API server (prod)\n`, + ); + if (process.env.MCP_AUTO_OPEN_ENABLED !== "false") { + console.log("🌐 Opening browser..."); + open(url); + } + }, 3000); + + await new Promise((resolve) => { + client.subscribe({ + complete: resolve, + error: (err) => { + if (!cancelled || process.env.DEBUG) { + console.error("Client error:", err); + } + resolve(null); + }, + next: () => {}, // We're using echoOutput + }); + }); +} + +async function startProdClient(clientOptions) { + const { + CLIENT_PORT, + inspectorApiToken, + abort, + command, + mcpServerArgs, + transport, + serverUrl, + envVars, + } = clientOptions; + const honoServerPath = resolve(__dirname, "server.js"); + + // Inspector API server (Hono) serves static files + /api/* endpoints + // Pass Inspector API auth token and config values explicitly via env vars (read-only, server reads them) + await spawnPromise("node", [honoServerPath], { + env: { + ...process.env, + CLIENT_PORT, + [API_SERVER_ENV_VARS.AUTH_TOKEN]: inspectorApiToken, // Pass Inspector API token explicitly + // Pass config values for HTML injection + ...(command ? { MCP_INITIAL_COMMAND: command } : {}), + ...(mcpServerArgs && mcpServerArgs.length > 0 + ? { MCP_INITIAL_ARGS: mcpServerArgs.join(" ") } + : {}), + ...(transport ? { MCP_INITIAL_TRANSPORT: transport } : {}), + ...(serverUrl ? { MCP_INITIAL_SERVER_URL: serverUrl } : {}), + ...(envVars && Object.keys(envVars).length > 0 + ? { MCP_ENV_VARS: JSON.stringify(envVars) } + : {}), + }, + signal: abort.signal, + echoOutput: true, + }); +} + +async function main() { + // Parse command line arguments + const args = process.argv.slice(2); + const envVars = {}; + const mcpServerArgs = []; + let command = null; + let parsingFlags = true; + let isDev = false; + let transport = null; + let serverUrl = null; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (parsingFlags && arg === "--") { + parsingFlags = false; + continue; + } + + if (parsingFlags && arg === "--dev") { + isDev = true; + continue; + } + + if (parsingFlags && arg === "--transport" && i + 1 < args.length) { + transport = args[++i]; + continue; + } + + if (parsingFlags && arg === "--server-url" && i + 1 < args.length) { + serverUrl = args[++i]; + continue; + } + + if (parsingFlags && arg === "-e" && i + 1 < args.length) { + const envVar = args[++i]; + const equalsIndex = envVar.indexOf("="); + + if (equalsIndex !== -1) { + const key = envVar.substring(0, equalsIndex); + const value = envVar.substring(equalsIndex + 1); + envVars[key] = value; + } else { + envVars[envVar] = ""; + } + } else if (!parsingFlags) { + // After "--", first arg is command, rest are server args (same in dev and prod) + if (command === null) { + command = arg; + } else { + mcpServerArgs.push(arg); + } + } + } + + const CLIENT_PORT = process.env.CLIENT_PORT ?? "6274"; + + console.log( + isDev + ? "Starting MCP inspector in development mode..." + : "Starting MCP inspector...", + ); + + // Generate Inspector API auth token + const inspectorApiToken = + process.env[API_SERVER_ENV_VARS.AUTH_TOKEN] || + randomBytes(32).toString("hex"); + + const abort = new AbortController(); + + let cancelled = false; + process.on("SIGINT", () => { + cancelled = true; + abort.abort(); + }); + + if (isDev) { + // In dev mode: start Vite with Inspector API middleware + try { + const clientOptions = { + CLIENT_PORT, + inspectorApiToken, // Pass Inspector API token explicitly + command, + mcpServerArgs, + transport, + serverUrl, + envVars, + abort, + cancelled, + }; + await startDevClient(clientOptions); + } catch (e) { + if (!cancelled || process.env.DEBUG) throw e; + } + } else { + // In prod mode: start Inspector API server (serves static files + /api/* endpoints) + try { + const clientOptions = { + CLIENT_PORT, + inspectorApiToken, // Pass token explicitly + command, + mcpServerArgs, + transport, + serverUrl, + envVars, + abort, + cancelled, + }; + await startProdClient(clientOptions); + } catch (e) { + if (!cancelled || process.env.DEBUG) throw e; + } + } + + return 0; +} + +main() + .then((_) => process.exit(0)) + .catch((e) => { + console.error(e); + process.exit(1); + }); diff --git a/web/components.json b/web/components.json new file mode 100644 index 000000000..d296ddc68 --- /dev/null +++ b/web/components.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.js", + "css": "src/index.css", + "baseColor": "slate", + "cssVariables": true, + "prefix": "" + }, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + } +} diff --git a/web/e2e/cli-arguments.spec.ts b/web/e2e/cli-arguments.spec.ts new file mode 100644 index 000000000..a4dcdcce2 --- /dev/null +++ b/web/e2e/cli-arguments.spec.ts @@ -0,0 +1,65 @@ +import { test, expect } from "@playwright/test"; + +// These tests verify that CLI arguments correctly set URL parameters +// The CLI should parse config files and pass transport/serverUrl as URL params +test.describe("CLI Arguments @cli", () => { + test("should pass transport parameter from command line", async ({ + page, + }) => { + // Simulate: npx . --transport sse --server-url http://localhost:3000/sse + await page.goto( + "http://localhost:6274/?transport=sse&serverUrl=http://localhost:3000/sse", + ); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Verify transport dropdown shows SSE + await expect(selectTrigger).toContainText("SSE"); + + // Verify URL field is visible and populated + const urlInput = page.locator("#sse-url-input"); + await expect(urlInput).toBeVisible(); + await expect(urlInput).toHaveValue("http://localhost:3000/sse"); + }); + + test("should pass transport parameter for streamable-http", async ({ + page, + }) => { + // Simulate config with streamable-http transport + await page.goto( + "http://localhost:6274/?transport=streamable-http&serverUrl=http://localhost:3000/mcp", + ); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Verify transport dropdown shows Streamable HTTP + await expect(selectTrigger).toContainText("Streamable HTTP"); + + // Verify URL field is visible and populated + const urlInput = page.locator("#sse-url-input"); + await expect(urlInput).toBeVisible(); + await expect(urlInput).toHaveValue("http://localhost:3000/mcp"); + }); + + test("should not pass transport parameter for stdio config", async ({ + page, + }) => { + // Simulate stdio config (no transport param needed) + await page.goto("http://localhost:6274/"); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Verify transport dropdown defaults to STDIO + await expect(selectTrigger).toContainText("STDIO"); + + // Verify command/args fields are visible + await expect(page.locator("#command-input")).toBeVisible(); + await expect(page.locator("#arguments-input")).toBeVisible(); + }); +}); diff --git a/web/e2e/global-teardown.js b/web/e2e/global-teardown.js new file mode 100644 index 000000000..9308d940f --- /dev/null +++ b/web/e2e/global-teardown.js @@ -0,0 +1,18 @@ +import { rimraf } from "rimraf"; + +async function globalTeardown() { + if (!process.env.CI) { + console.log("Cleaning up test-results directory..."); + // Add a small delay to ensure all Playwright files are written + await new Promise((resolve) => setTimeout(resolve, 100)); + await rimraf("./e2e/test-results"); + console.log("Test-results directory cleaned up."); + } +} + +export default globalTeardown; + +// Call the function when this script is run directly +if (import.meta.url === `file://${process.argv[1]}`) { + globalTeardown().catch(console.error); +} diff --git a/web/e2e/startup-state.spec.ts b/web/e2e/startup-state.spec.ts new file mode 100644 index 000000000..414ebd3e6 --- /dev/null +++ b/web/e2e/startup-state.spec.ts @@ -0,0 +1,16 @@ +import { test, expect } from "@playwright/test"; + +// Adjust the URL if your dev server runs on a different port +const APP_URL = "http://localhost:6274/"; + +test.describe("Startup State", () => { + test("should not navigate to a tab when Inspector first opens", async ({ + page, + }) => { + await page.goto(APP_URL); + + // Check that there is no hash fragment in the URL + const url = page.url(); + expect(url).not.toContain("#"); + }); +}); diff --git a/web/e2e/transport-type-dropdown.spec.ts b/web/e2e/transport-type-dropdown.spec.ts new file mode 100644 index 000000000..e4ac8fbb4 --- /dev/null +++ b/web/e2e/transport-type-dropdown.spec.ts @@ -0,0 +1,113 @@ +import { test, expect } from "@playwright/test"; + +// Adjust the URL if your dev server runs on a different port +const APP_URL = "http://localhost:6274/"; + +test.describe("Transport Type Dropdown", () => { + test("should have options for STDIO, SSE, and Streamable HTTP", async ({ + page, + }) => { + await page.goto(APP_URL); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Open the dropdown + await selectTrigger.click(); + + // Check for the three options + await expect(page.getByRole("option", { name: "STDIO" })).toBeVisible(); + await expect(page.getByRole("option", { name: "SSE" })).toBeVisible(); + await expect( + page.getByRole("option", { name: "Streamable HTTP" }), + ).toBeVisible(); + }); + + test("should show Command and Arguments fields and hide URL field when Transport Type is STDIO", async ({ + page, + }) => { + await page.goto(APP_URL); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Open the dropdown and select STDIO + await selectTrigger.click(); + await page.getByRole("option", { name: "STDIO" }).click(); + + // Wait for the form to update + await page.waitForTimeout(100); + + // Check that Command and Arguments fields are visible + await expect(page.locator("#command-input")).toBeVisible(); + await expect(page.locator("#arguments-input")).toBeVisible(); + + // Check that URL field is not visible + await expect(page.locator("#sse-url-input")).not.toBeVisible(); + + // Also verify the labels are present + await expect(page.getByText("Command")).toBeVisible(); + await expect(page.getByText("Arguments")).toBeVisible(); + await expect(page.getByText("URL")).not.toBeVisible(); + }); + + test("should show URL field and hide Command and Arguments fields when Transport Type is SSE", async ({ + page, + }) => { + await page.goto(APP_URL); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Open the dropdown and select SSE + await selectTrigger.click(); + await page.getByRole("option", { name: "SSE" }).click(); + + // Wait for the form to update + await page.waitForTimeout(100); + + // Check that URL field is visible + await expect(page.locator("#sse-url-input")).toBeVisible(); + + // Check that Command and Arguments fields are not visible + await expect(page.locator("#command-input")).not.toBeVisible(); + await expect(page.locator("#arguments-input")).not.toBeVisible(); + + // Also verify the labels are present/absent + await expect(page.getByText("URL")).toBeVisible(); + await expect(page.getByText("Command")).not.toBeVisible(); + await expect(page.getByText("Arguments")).not.toBeVisible(); + }); + + test("should show URL field and hide Command and Arguments fields when Transport Type is Streamable HTTP", async ({ + page, + }) => { + await page.goto(APP_URL); + + // Wait for the Transport Type dropdown to be visible + const selectTrigger = page.getByLabel("Transport Type"); + await expect(selectTrigger).toBeVisible(); + + // Open the dropdown and select Streamable HTTP + await selectTrigger.click(); + await page.getByRole("option", { name: "Streamable HTTP" }).click(); + + // Wait for the form to update + await page.waitForTimeout(100); + + // Check that URL field is visible + await expect(page.locator("#sse-url-input")).toBeVisible(); + + // Check that Command and Arguments fields are not visible + await expect(page.locator("#command-input")).not.toBeVisible(); + await expect(page.locator("#arguments-input")).not.toBeVisible(); + + // Also verify the labels are present/absent + await expect(page.getByText("URL")).toBeVisible(); + await expect(page.getByText("Command")).not.toBeVisible(); + await expect(page.getByText("Arguments")).not.toBeVisible(); + }); +}); diff --git a/web/eslint.config.js b/web/eslint.config.js new file mode 100644 index 000000000..79a552ea9 --- /dev/null +++ b/web/eslint.config.js @@ -0,0 +1,28 @@ +import js from "@eslint/js"; +import globals from "globals"; +import reactHooks from "eslint-plugin-react-hooks"; +import reactRefresh from "eslint-plugin-react-refresh"; +import tseslint from "typescript-eslint"; + +export default tseslint.config( + { ignores: ["dist"] }, + { + extends: [js.configs.recommended, ...tseslint.configs.recommended], + files: ["**/*.{ts,tsx}"], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + plugins: { + "react-hooks": reactHooks, + "react-refresh": reactRefresh, + }, + rules: { + ...reactHooks.configs.recommended.rules, + "react-refresh/only-export-components": [ + "warn", + { allowConstantExport: true }, + ], + }, + }, +); diff --git a/web/index.html b/web/index.html new file mode 100644 index 000000000..57756a2a2 --- /dev/null +++ b/web/index.html @@ -0,0 +1,13 @@ + + + + + + + MCP Inspector Web + + +
+ + + diff --git a/web/jest.config.cjs b/web/jest.config.cjs new file mode 100644 index 000000000..ddbf5250e --- /dev/null +++ b/web/jest.config.cjs @@ -0,0 +1,47 @@ +module.exports = { + preset: "ts-jest", + testEnvironment: "jest-fixed-jsdom", + moduleNameMapper: { + "^@/(.*)$": "/src/$1", + "\\.css$": "/src/__mocks__/styleMock.js", + }, + transform: { + "^.+\\.tsx?$": [ + "ts-jest", + { + jsx: "react-jsx", + tsconfig: "tsconfig.jest.json", + }, + ], + // Transform ESM .js files from shared/build + "^.+\\.js$": [ + "ts-jest", + { + tsconfig: "tsconfig.jest.json", + }, + ], + }, + transformIgnorePatterns: [ + // Don't ignore shared/build - we need to transform those ESM .js files + "node_modules/(?!@modelcontextprotocol/inspector-shared)", + ], + extensionsToTreatAsEsm: [".ts", ".tsx"], + testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", + // Exclude directories and files that don't need to be tested + testPathIgnorePatterns: [ + "/node_modules/", + "/dist/", + "/bin/", + "/e2e/", + "\\.config\\.(js|ts|cjs|mjs)$", + ], + // Exclude the same patterns from coverage reports + coveragePathIgnorePatterns: [ + "/node_modules/", + "/dist/", + "/bin/", + "/e2e/", + "\\.config\\.(js|ts|cjs|mjs)$", + ], + randomize: true, +}; diff --git a/web/package.json b/web/package.json new file mode 100644 index 000000000..feccf67df --- /dev/null +++ b/web/package.json @@ -0,0 +1,86 @@ +{ + "name": "@modelcontextprotocol/inspector-web", + "version": "0.20.0", + "description": "Web application for the Model Context Protocol inspector", + "license": "MIT", + "author": "Anthropic, PBC (https://anthropic.com)", + "homepage": "https://modelcontextprotocol.io", + "bugs": "https://github.com/modelcontextprotocol/inspector/issues", + "type": "module", + "bin": { + "mcp-inspector-web": "./bin/start.js" + }, + "files": [ + "bin", + "dist" + ], + "scripts": { + "dev": "vite --port 6274", + "build": "tsc -b && vite build", + "start": "node bin/server.js", + "lint": "eslint .", + "preview": "vite preview --port 6274", + "test": "jest --config jest.config.cjs", + "test:watch": "jest --config jest.config.cjs --watch", + "test:e2e": "playwright test e2e && npm run cleanup:e2e", + "cleanup:e2e": "node e2e/global-teardown.js" + }, + "dependencies": { + "@hono/node-server": "^1.19.0", + "@modelcontextprotocol/inspector-shared": "*", + "@modelcontextprotocol/sdk": "^1.25.2", + "@radix-ui/react-checkbox": "^1.1.4", + "@radix-ui/react-dialog": "^1.1.3", + "@radix-ui/react-icons": "^1.3.0", + "@radix-ui/react-label": "^2.1.0", + "@radix-ui/react-popover": "^1.1.3", + "@radix-ui/react-select": "^2.1.2", + "@radix-ui/react-slot": "^1.1.0", + "@radix-ui/react-switch": "^1.2.6", + "@radix-ui/react-tabs": "^1.1.1", + "@radix-ui/react-toast": "^1.2.6", + "@radix-ui/react-tooltip": "^1.1.8", + "ajv": "^6.12.6", + "class-variance-authority": "^0.7.0", + "clsx": "^2.1.1", + "cmdk": "^1.0.4", + "lucide-react": "^0.523.0", + "pkce-challenge": "^4.1.0", + "prismjs": "^1.30.0", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-simple-code-editor": "^0.14.1", + "serve-handler": "^6.1.6", + "tailwind-merge": "^2.5.3", + "zod": "^3.25.76", + "pino": "^9.6.0" + }, + "devDependencies": { + "@eslint/js": "^9.11.1", + "@testing-library/jest-dom": "^6.6.3", + "@testing-library/react": "^16.2.0", + "@types/jest": "^29.5.14", + "@types/node": "^22.17.0", + "@types/prismjs": "^1.26.5", + "@types/react": "^18.3.23", + "@types/react-dom": "^18.3.0", + "@types/serve-handler": "^6.1.4", + "@vitejs/plugin-react": "^5.0.4", + "autoprefixer": "^10.4.20", + "co": "^4.6.0", + "eslint": "^9.11.1", + "eslint-plugin-react-hooks": "^5.1.0-rc.0", + "eslint-plugin-react-refresh": "^0.4.12", + "globals": "^15.9.0", + "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0", + "jest-fixed-jsdom": "^0.0.9", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.13", + "tailwindcss-animate": "^1.0.7", + "ts-jest": "^29.4.0", + "typescript": "^5.5.3", + "typescript-eslint": "^8.38.0", + "vite": "^7.1.11" + } +} diff --git a/web/playwright.config.ts b/web/playwright.config.ts new file mode 100644 index 000000000..570dd054e --- /dev/null +++ b/web/playwright.config.ts @@ -0,0 +1,70 @@ +import { defineConfig, devices } from "@playwright/test"; + +/** + * @see https://playwright.dev/docs/test-configuration + */ +export default defineConfig({ + /* Run your local dev server before starting the tests */ + webServer: { + cwd: "..", + command: "npm run dev", + url: "http://localhost:6274", + reuseExistingServer: !process.env.CI, + }, + + testDir: "./e2e", + outputDir: "./e2e/test-results", + /* Run tests in files in parallel */ + fullyParallel: true, + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + /* Opt out of parallel tests on CI. */ + workers: process.env.CI ? 1 : undefined, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + reporter: process.env.CI + ? [ + ["html", { outputFolder: "playwright-report" }], + ["json", { outputFile: "results.json" }], + ["line"], + ] + : [["line"]], + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL: "http://localhost:6274", + + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: "on-first-retry", + + /* Take screenshots on failure */ + screenshot: "only-on-failure", + + /* Record video on failure */ + video: "retain-on-failure", + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + }, + + { + name: "firefox", + use: { ...devices["Desktop Firefox"] }, + }, + + // Skip WebKit on macOS due to compatibility issues + ...(process.platform !== "darwin" + ? [ + { + name: "webkit", + use: { ...devices["Desktop Safari"] }, + }, + ] + : []), + ], +}); diff --git a/web/postcss.config.js b/web/postcss.config.js new file mode 100644 index 000000000..2aa7205d4 --- /dev/null +++ b/web/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +}; diff --git a/web/public/mcp.svg b/web/public/mcp.svg new file mode 100644 index 000000000..03d9f85d3 --- /dev/null +++ b/web/public/mcp.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/web/src/App.css b/web/src/App.css new file mode 100644 index 000000000..0d669ffa5 --- /dev/null +++ b/web/src/App.css @@ -0,0 +1,35 @@ +.logo { + height: 6em; + padding: 1.5em; + will-change: filter; + transition: filter 300ms; +} +.logo:hover { + filter: drop-shadow(0 0 2em #646cffaa); +} +.logo.react:hover { + filter: drop-shadow(0 0 2em #61dafbaa); +} + +@keyframes logo-spin { + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: no-preference) { + a:nth-of-type(2) .logo { + animation: logo-spin infinite 20s linear; + } +} + +.card { + padding: 2em; +} + +.read-the-docs { + color: #888; +} diff --git a/web/src/App.tsx b/web/src/App.tsx new file mode 100644 index 000000000..cc892aec7 --- /dev/null +++ b/web/src/App.tsx @@ -0,0 +1,1698 @@ +import { + CompatibilityCallToolResult, + CreateMessageResult, + EmptyResultSchema, + Resource, + ResourceReference, + PromptReference, + Root, + ServerNotification, + Tool, + LoggingLevel, +} from "@modelcontextprotocol/sdk/types.js"; +import { + hasValidMetaName, + hasValidMetaPrefix, + isReservedMetaKey, +} from "@/utils/metaUtils"; +import { cacheToolOutputSchemas } from "./utils/schemaUtils"; +import { cleanParams } from "./utils/paramUtils"; +import type { JsonSchemaType } from "./utils/jsonUtils"; +import type { JsonValue } from "@modelcontextprotocol/inspector-shared/json/jsonUtils.js"; +import React, { + Suspense, + useCallback, + useEffect, + useMemo, + useRef, + useState, +} from "react"; +import { useInspectorClient } from "@modelcontextprotocol/inspector-shared/react/useInspectorClient.js"; +import { + InspectorClient, + type InspectorClientOptions, +} from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import { createWebEnvironment } from "./lib/adapters/environmentFactory"; +import { RemoteInspectorClientStorage } from "@modelcontextprotocol/inspector-shared/mcp/remote/index.js"; +import { parseOAuthState } from "@modelcontextprotocol/inspector-shared/auth/index.js"; +import { webConfigToMcpServerConfig } from "./lib/adapters/configAdapter"; +import { useToast } from "./lib/hooks/useToast"; +import { + useDraggablePane, + useDraggableSidebar, +} from "./lib/hooks/useDraggablePane"; + +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { Button } from "@/components/ui/button"; +import { + Bell, + Files, + FolderTree, + Hammer, + Hash, + Key, + MessageSquare, + Network, + Settings, + Terminal, +} from "lucide-react"; + +import "./App.css"; +import AuthDebugger from "./components/AuthDebugger"; +import ConsoleTab from "./components/ConsoleTab"; +import HistoryAndNotifications from "./components/HistoryAndNotifications"; +import PingTab from "./components/PingTab"; +import PromptsTab, { Prompt } from "./components/PromptsTab"; +import RequestsTab from "./components/RequestsTab"; +import ResourcesTab from "./components/ResourcesTab"; +import RootsTab from "./components/RootsTab"; +import SamplingTab, { PendingRequest } from "./components/SamplingTab"; +import Sidebar from "./components/Sidebar"; +import ToolsTab from "./components/ToolsTab"; +import { InspectorConfig } from "./lib/configurationTypes"; +import { + getInitialSseUrl, + getInitialTransportType, + getInitialCommand, + getInitialArgs, + getInspectorApiToken, + initializeInspectorConfig, + saveInspectorConfig, +} from "./utils/configUtils"; +import ElicitationTab, { + PendingElicitationRequest, + ElicitationResponse, +} from "./components/ElicitationTab"; +import { + CustomHeaders, + migrateFromLegacyAuth, +} from "./lib/types/customHeaders"; +import MetadataTab from "./components/MetadataTab"; +import TokenLoginScreen from "./components/TokenLoginScreen"; + +const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1"; + +const filterReservedMetadata = ( + metadata: Record, +): Record => { + return Object.entries(metadata).reduce>( + (acc, [key, value]) => { + if ( + !isReservedMetaKey(key) && + hasValidMetaPrefix(key) && + hasValidMetaName(key) + ) { + acc[key] = value; + } + return acc; + }, + {}, + ); +}; + +const App = () => { + const [resourceContent, setResourceContent] = useState(""); + const [resourceContentMap, setResourceContentMap] = useState< + Record + >({}); + const [promptContent, setPromptContent] = useState(""); + const [toolResult, setToolResult] = + useState(null); + const [errors, setErrors] = useState>({ + resources: null, + prompts: null, + tools: null, + }); + const [command, setCommand] = useState(getInitialCommand); + const [args, setArgs] = useState(getInitialArgs); + + const [sseUrl, setSseUrl] = useState(getInitialSseUrl); + const [transportType, setTransportType] = useState< + "stdio" | "sse" | "streamable-http" + >(getInitialTransportType); + const [logLevel, setLogLevel] = useState("debug"); + const [notifications, setNotifications] = useState([]); + const [roots, setRoots] = useState([]); + const [env, setEnv] = useState>({}); + + const [config, setConfig] = useState(() => + initializeInspectorConfig(CONFIG_LOCAL_STORAGE_KEY), + ); + const [bearerToken, setBearerToken] = useState(() => { + return localStorage.getItem("lastBearerToken") || ""; + }); + + const [headerName, setHeaderName] = useState(() => { + return localStorage.getItem("lastHeaderName") || ""; + }); + + const [oauthClientId, setOauthClientId] = useState(() => { + return localStorage.getItem("lastOauthClientId") || ""; + }); + + const [oauthScope, setOauthScope] = useState(() => { + return localStorage.getItem("lastOauthScope") || ""; + }); + + const [oauthClientSecret, setOauthClientSecret] = useState(() => { + return localStorage.getItem("lastOauthClientSecret") || ""; + }); + + // Custom headers state with migration from legacy auth + const [customHeaders, setCustomHeaders] = useState(() => { + const savedHeaders = localStorage.getItem("lastCustomHeaders"); + if (savedHeaders) { + try { + return JSON.parse(savedHeaders); + } catch (error) { + console.warn( + `Failed to parse custom headers: "${savedHeaders}", will try legacy migration`, + error, + ); + // Fall back to migration if JSON parsing fails + } + } + + // Migrate from legacy auth if available + const legacyToken = localStorage.getItem("lastBearerToken") || ""; + const legacyHeaderName = localStorage.getItem("lastHeaderName") || ""; + + if (legacyToken) { + return migrateFromLegacyAuth(legacyToken, legacyHeaderName); + } + + // Default to empty array + return [ + { + name: "Authorization", + value: "Bearer ", + enabled: false, + }, + ]; + }); + + const [pendingSampleRequests, setPendingSampleRequests] = useState< + Array< + PendingRequest & { + resolve: (result: CreateMessageResult) => void; + reject: (error: Error) => void; + } + > + >([]); + const [pendingElicitationRequests, setPendingElicitationRequests] = useState< + Array< + PendingElicitationRequest & { + resolve: (response: ElicitationResponse) => void; + decline: (error: Error) => void; + } + > + >([]); + const [isAuthDebuggerVisible, setIsAuthDebuggerVisible] = useState(false); + + // Metadata state - persisted in localStorage + const [metadata, setMetadata] = useState>(() => { + const savedMetadata = localStorage.getItem("lastMetadata"); + if (savedMetadata) { + try { + const parsed = JSON.parse(savedMetadata); + if (parsed && typeof parsed === "object") { + return filterReservedMetadata(parsed); + } + } catch (error) { + console.warn("Failed to parse saved metadata:", error); + } + } + return {}; + }); + + const handleMetadataChange = (newMetadata: Record) => { + const sanitizedMetadata = filterReservedMetadata(newMetadata); + setMetadata(sanitizedMetadata); + localStorage.setItem("lastMetadata", JSON.stringify(sanitizedMetadata)); + }; + const rootsRef = useRef([]); + + const [selectedResource, setSelectedResource] = useState( + null, + ); + const [resourceSubscriptions, setResourceSubscriptions] = useState< + Set + >(new Set()); + + const [selectedPrompt, setSelectedPrompt] = useState(null); + const [selectedTool, setSelectedTool] = useState(null); + const [nextResourceCursor, setNextResourceCursor] = useState< + string | undefined + >(); + const [nextResourceTemplateCursor, setNextResourceTemplateCursor] = useState< + string | undefined + >(); + const [nextPromptCursor, setNextPromptCursor] = useState< + string | undefined + >(); + const [nextToolCursor, setNextToolCursor] = useState(); + const progressTokenRef = useRef(0); + + const [activeTab, setActiveTab] = useState(() => { + const hash = window.location.hash.slice(1); + const initialTab = hash || "resources"; + return initialTab; + }); + + const currentTabRef = useRef(activeTab); + const lastToolCallOriginTabRef = useRef(activeTab); + + useEffect(() => { + currentTabRef.current = activeTab; + }, [activeTab]); + + const { height: historyPaneHeight, handleDragStart } = useDraggablePane(300); + const { + width: sidebarWidth, + isDragging: isSidebarDragging, + handleDragStart: handleSidebarDragStart, + } = useDraggableSidebar(320); + + // InspectorClient is created lazily when needed (connect/auth operations) + const [inspectorClient, setInspectorClient] = + useState(null); + // Track the token used to create the current inspectorClient + const inspectorClientTokenRef = useRef(undefined); + + const { toast } = useToast(); + + // Helper function to ensure InspectorClient exists and is created with current token + // We use a ref to always read the latest config value, avoiding stale closure issues + const configRef = useRef(config); + // Update ref synchronously whenever config changes (before useEffect runs) + configRef.current = config; + + // Helper to check if we can create InspectorClient (without actually creating it) + const canCreateInspectorClient = useCallback((): boolean => { + const currentConfig = configRef.current; + const configItem = currentConfig.MCP_INSPECTOR_API_TOKEN; + const tokenValue = configItem?.value; + const tokenString = + typeof tokenValue === "string" ? tokenValue : String(tokenValue || ""); + const currentToken = tokenString.trim() || undefined; + return !!currentToken && (!!command || !!sseUrl); + }, [command, sseUrl]); + + const ensureInspectorClient = useCallback((): InspectorClient | null => { + // Read current token from config ref to ensure we always get the latest value + const currentConfig = configRef.current; + const configItem = currentConfig.MCP_INSPECTOR_API_TOKEN; + const tokenValue = configItem?.value; + + // Handle different value types (string, number, boolean, etc.) + const tokenString = + typeof tokenValue === "string" ? tokenValue : String(tokenValue || ""); + const currentToken = tokenString.trim() || undefined; + + // Check if API token is set + if (!currentToken) { + toast({ + title: "API Token Required", + description: "Please set the API Token in Configuration to connect.", + variant: "destructive", + }); + return null; + } + + // Check if server config is set (handle empty strings) + const hasCommand = command && command.trim().length > 0; + const hasSseUrl = sseUrl && sseUrl.trim().length > 0; + + if (!hasCommand && !hasSseUrl) { + toast({ + title: "Server Configuration Required", + description: "Please configure the server command or URL.", + variant: "destructive", + }); + return null; + } + + // If inspectorClient exists, check if token changed + if (inspectorClient && inspectorClientTokenRef.current !== currentToken) { + toast({ + title: "API Token Changed", + description: "API token has changed. Please disconnect and reconnect.", + variant: "destructive", + }); + return null; + } + + // If inspectorClient exists and token matches, return it + if (inspectorClient && inspectorClientTokenRef.current === currentToken) { + return inspectorClient; + } + + // Extract sessionId from OAuth callback if present + let sessionId: string | undefined; + const urlParams = new URLSearchParams(window.location.search); + const stateParam = urlParams.get("state"); + if (stateParam) { + const parsedState = parseOAuthState(stateParam); + if (parsedState?.authId) { + sessionId = parsedState.authId; + } + } + + // Create new InspectorClient + try { + const mcpConfig = webConfigToMcpServerConfig( + transportType, + command, + args, + sseUrl, + env, + customHeaders, + ); + + const redirectUrlProvider = { + getRedirectUrl: (_mode: "normal" | "guided") => + `${window.location.origin}/oauth/callback`, + }; + + const environment = createWebEnvironment( + currentToken, + redirectUrlProvider, + ); + + // Create session storage for persisting state across OAuth redirects + const baseUrl = `${window.location.protocol}//${window.location.host}`; + const fetchFn: typeof fetch = (...args) => globalThis.fetch(...args); + const sessionStorage = new RemoteInspectorClientStorage({ + baseUrl, + authToken: currentToken, + fetchFn, + }); + + // Only include oauth config if at least one OAuth field is provided + // This prevents InspectorClient from initializing OAuth when not needed + const hasOAuthConfig = oauthClientId || oauthClientSecret || oauthScope; + + const clientOptions: InspectorClientOptions = { + environment, + autoSyncLists: false, + maxMessages: 1000, + maxStderrLogEvents: 1000, + maxFetchRequests: 1000, + sessionStorage, + sessionId, + }; + + if (hasOAuthConfig) { + clientOptions.oauth = { + clientId: oauthClientId || undefined, + clientSecret: oauthClientSecret || undefined, + scope: oauthScope || undefined, + }; + } + + const client = new InspectorClient(mcpConfig, clientOptions); + inspectorClientTokenRef.current = currentToken; + setInspectorClient(client); + return client; + } catch (error) { + toast({ + title: "Failed to Create Client", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + return null; + } + }, [ + command, + sseUrl, + transportType, + args, + env, + customHeaders, + oauthClientId, + oauthClientSecret, + oauthScope, + inspectorClient, + toast, + ]); + + // Use InspectorClient hook + const { + status: connectionStatus, + capabilities: serverCapabilities, + serverInfo: serverImplementation, + client: mcpClient, + messages: inspectorMessages, + stderrLogs, + fetchRequests, + tools: inspectorTools, + resources: inspectorResources, + resourceTemplates: inspectorResourceTemplates, + prompts: inspectorPrompts, + disconnect: disconnectMcpServer, + } = useInspectorClient(inspectorClient); + + // Wrap connect to ensure InspectorClient exists first; show toast on error + const connectMcpServer = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client) return; // Error already shown in ensureInspectorClient + + try { + await client.connect(); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + toast({ + title: "Connection failed", + description: message, + variant: "destructive", + }); + if (client.getStatus() === "connecting") { + await client.disconnect(); + } + } + }, [ensureInspectorClient, inspectorClient, toast]); + + // Extract server notifications from messages + // Use useMemo to stabilize the array reference and prevent infinite loops + const extractedNotifications = useMemo(() => { + return inspectorMessages + .filter((msg) => msg.direction === "notification" && msg.message) + .map((msg) => msg.message as ServerNotification); + }, [inspectorMessages]); + + // Use ref to track previous serialized value to prevent infinite loops + const previousNotificationsRef = useRef("[]"); + + useEffect(() => { + // Compare by serializing to avoid infinite loops from reference changes + const currentSerialized = JSON.stringify(extractedNotifications); + if (currentSerialized !== previousNotificationsRef.current) { + setNotifications(extractedNotifications); + previousNotificationsRef.current = currentSerialized; + } + }, [extractedNotifications]); + + // Set up event listeners for sampling and elicitation + useEffect(() => { + if (!inspectorClient) return; + + // Handle sampling requests + const handleNewPendingSample = (event: CustomEvent) => { + const sample = event.detail; + const numericId = getNumericId(sample.id); + setPendingSampleRequests((prev) => [ + ...prev, + { + id: numericId, + request: sample.request, + resolve: async (result: CreateMessageResult) => { + await sample.respond(result); + }, + reject: async (error: Error) => { + await sample.reject(error); + }, + }, + ]); + }; + + // Handle elicitation requests + const handleNewPendingElicitation = (event: CustomEvent) => { + const elicitation = event.detail; + const currentTab = lastToolCallOriginTabRef.current; + const numericId = getNumericId(elicitation.id); + + setPendingElicitationRequests((prev) => [ + ...prev, + { + id: numericId, + request: { + id: numericId, + message: elicitation.request.params.message, + requestedSchema: elicitation.request.params.requestedSchema, + }, + originatingTab: currentTab, + resolve: async (result: any) => { + await elicitation.respond(result); + }, + decline: async (error: Error) => { + elicitation.remove(); + console.error("Elicitation request rejected:", error); + }, + }, + ]); + + setActiveTab("elicitations"); + window.location.hash = "elicitations"; + }; + + inspectorClient.addEventListener( + "newPendingSample", + handleNewPendingSample, + ); + inspectorClient.addEventListener( + "newPendingElicitation", + handleNewPendingElicitation, + ); + + return () => { + inspectorClient.removeEventListener( + "newPendingSample", + handleNewPendingSample, + ); + inspectorClient.removeEventListener( + "newPendingElicitation", + handleNewPendingElicitation, + ); + }; + }, [inspectorClient]); + + // Expose InspectorClient to window for debugging + useEffect(() => { + if (!inspectorClient) { + if ((window as any).__inspectorClient) { + delete (window as any).__inspectorClient; + } + return; + } + + (window as any).__inspectorClient = inspectorClient; + }, [inspectorClient]); + + const handleCompletion = useCallback( + async ( + ref: ResourceReference | PromptReference, + argName: string, + value: string, + context?: Record, + _signal?: AbortSignal, + ): Promise => { + if (!inspectorClient) return []; + const result = await inspectorClient.getCompletions( + ref.type === "ref/resource" + ? { type: "ref/resource", uri: ref.uri } + : { type: "ref/prompt", name: ref.name }, + argName, + value, + context, + undefined, // metadata + ); + return result.values || []; + }, + [inspectorClient], + ); + + const completionsSupported = + serverCapabilities?.completions !== undefined && + serverCapabilities.completions !== null; + + // Map MCP protocol messages (requests/responses) to requestHistory format + // Filter out notifications - those go in the Notifications tab + const requestHistory = useMemo(() => { + return inspectorMessages + .filter((msg) => msg.direction === "request") + .map((msg) => ({ + request: JSON.stringify(msg.message), + response: msg.response ? JSON.stringify(msg.response) : undefined, + })); + }, [inspectorMessages]); + + const clearRequestHistory = useCallback(() => { + // InspectorClient doesn't have a clear method, so this is a no-op + // The history is managed internally by InspectorClient + }, []); + + useEffect(() => { + if (serverCapabilities) { + const hash = window.location.hash.slice(1); + + const validTabs = [ + ...(serverCapabilities?.resources ? ["resources"] : []), + ...(serverCapabilities?.prompts ? ["prompts"] : []), + ...(serverCapabilities?.tools ? ["tools"] : []), + "ping", + "sampling", + "elicitations", + "roots", + "console", + "auth", + ]; + + const isValidTab = validTabs.includes(hash); + + if (!isValidTab) { + const defaultTab = serverCapabilities?.resources + ? "resources" + : serverCapabilities?.prompts + ? "prompts" + : serverCapabilities?.tools + ? "tools" + : "ping"; + + setActiveTab(defaultTab); + window.location.hash = defaultTab; + } + } + }, [serverCapabilities]); + + useEffect(() => { + localStorage.setItem("lastCommand", command); + }, [command]); + + useEffect(() => { + localStorage.setItem("lastArgs", args); + }, [args]); + + useEffect(() => { + localStorage.setItem("lastSseUrl", sseUrl); + }, [sseUrl]); + + useEffect(() => { + localStorage.setItem("lastTransportType", transportType); + }, [transportType]); + + useEffect(() => { + if (bearerToken) { + localStorage.setItem("lastBearerToken", bearerToken); + } else { + localStorage.removeItem("lastBearerToken"); + } + }, [bearerToken]); + + useEffect(() => { + if (headerName) { + localStorage.setItem("lastHeaderName", headerName); + } else { + localStorage.removeItem("lastHeaderName"); + } + }, [headerName]); + + useEffect(() => { + localStorage.setItem("lastCustomHeaders", JSON.stringify(customHeaders)); + }, [customHeaders]); + + // Auto-migrate from legacy auth when custom headers are empty but legacy auth exists + useEffect(() => { + if (customHeaders.length === 0 && (bearerToken || headerName)) { + const migratedHeaders = migrateFromLegacyAuth(bearerToken, headerName); + if (migratedHeaders.length > 0) { + setCustomHeaders(migratedHeaders); + // Clear legacy auth after migration + setBearerToken(""); + setHeaderName(""); + } + } + }, [bearerToken, headerName, customHeaders, setCustomHeaders]); + + useEffect(() => { + localStorage.setItem("lastOauthClientId", oauthClientId); + }, [oauthClientId]); + + useEffect(() => { + localStorage.setItem("lastOauthScope", oauthScope); + }, [oauthScope]); + + useEffect(() => { + localStorage.setItem("lastOauthClientSecret", oauthClientSecret); + }, [oauthClientSecret]); + + useEffect(() => { + saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, config); + }, [config]); + + // Persist immediately when config changes from Sidebar so new tabs (e.g. OAuth callback) have it + const setConfigAndPersist = useCallback((newConfig: InspectorConfig) => { + setConfig(newConfig); + saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, newConfig); + }, []); + + const onOAuthConnect = useCallback(() => { + setIsAuthDebuggerVisible(false); + void connectMcpServer(); + }, [connectMcpServer]); + + const handleTokenSubmit = useCallback( + (token: string) => { + setConfig((prev) => ({ + ...prev, + MCP_INSPECTOR_API_TOKEN: { + ...prev.MCP_INSPECTOR_API_TOKEN, + value: token, + }, + })); + // Persist immediately so refresh/callback keeps the token + saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, { + ...config, + MCP_INSPECTOR_API_TOKEN: { + ...config.MCP_INSPECTOR_API_TOKEN, + value: token, + }, + }); + }, + [config], + ); + + // Fetch initial server config from /api/config (same in dev and prod; requires API token in URL) + const fetchedInitialConfigRef = useRef(false); + useEffect(() => { + if (fetchedInitialConfigRef.current) return; + const token = getInspectorApiToken(config); + if (!token) return; + fetchedInitialConfigRef.current = true; + + const url = new URL("/api/config", window.location.origin); + fetch(url.toString(), { + headers: { "x-mcp-remote-auth": `Bearer ${token}` }, + }) + .then((res) => { + if (!res.ok) return null; + return res.json(); + }) + .then((data: Record | null) => { + if (!data) return; + if ( + data.defaultEnvironment && + typeof data.defaultEnvironment === "object" + ) { + setEnv(data.defaultEnvironment as Record); + } + setCommand((data.defaultCommand as string) ?? ""); + const argsVal = data.defaultArgs; + setArgs( + Array.isArray(argsVal) + ? argsVal.join(" ") + : typeof argsVal === "string" + ? argsVal + : "", + ); + const transport = data.defaultTransport as + | "stdio" + | "sse" + | "streamable-http" + | undefined; + setTransportType(transport || "stdio"); + setSseUrl((data.defaultServerUrl as string) ?? ""); + }) + .catch(() => { + fetchedInitialConfigRef.current = false; + }); + }, [config]); + + // Sync roots with InspectorClient + // Only run when inspectorClient changes, not when roots changes (to avoid infinite loop) + // The rootsChange event listener handles updates after initial sync + useEffect(() => { + if (!inspectorClient) return; + + // Get initial roots from InspectorClient + const inspectorRoots = inspectorClient.getRoots(); + setRoots(inspectorRoots); + rootsRef.current = inspectorRoots; + }, [inspectorClient]); + + // Listen for roots changes from InspectorClient + useEffect(() => { + if (!inspectorClient) return; + + const handleRootsChange = (event: CustomEvent) => { + setRoots(event.detail); + rootsRef.current = event.detail; + }; + + inspectorClient.addEventListener("rootsChange", handleRootsChange); + return () => { + inspectorClient.removeEventListener("rootsChange", handleRootsChange); + }; + }, [inspectorClient]); + + useEffect(() => { + if (mcpClient && !window.location.hash) { + const defaultTab = serverCapabilities?.resources + ? "resources" + : serverCapabilities?.prompts + ? "prompts" + : serverCapabilities?.tools + ? "tools" + : "ping"; + window.location.hash = defaultTab; + } else if (!mcpClient && window.location.hash) { + // Clear hash when disconnected - completely remove the fragment + window.history.replaceState( + null, + "", + window.location.pathname + window.location.search, + ); + } + }, [mcpClient, serverCapabilities]); + + useEffect(() => { + const handleHashChange = () => { + const hash = window.location.hash.slice(1); + if (hash && hash !== activeTab) { + setActiveTab(hash); + } + }; + + window.addEventListener("hashchange", handleHashChange); + return () => window.removeEventListener("hashchange", handleHashChange); + }, [activeTab]); + + // When transport is stdio, Requests tab is hidden; switch away if it was selected + useEffect(() => { + if ( + connectionStatus === "connected" && + transportType === "stdio" && + activeTab === "requests" + ) { + setActiveTab("ping"); + window.location.hash = "ping"; + } + }, [connectionStatus, transportType, activeTab]); + + // Map string IDs from InspectorClient to numbers for component compatibility + const stringIdToNumber = useRef>(new Map()); + const nextNumericId = useRef(1); + + const getNumericId = (stringId: string): number => { + if (!stringIdToNumber.current.has(stringId)) { + stringIdToNumber.current.set(stringId, nextNumericId.current++); + } + return stringIdToNumber.current.get(stringId)!; + }; + + const handleApproveSampling = (id: number, result: CreateMessageResult) => { + setPendingSampleRequests((prev) => { + // Find by numeric ID (stored in state) + const request = prev.find((r) => r.id === id); + request?.resolve(result); + return prev.filter((r) => r.id !== id); + }); + }; + + const handleRejectSampling = (id: number) => { + setPendingSampleRequests((prev) => { + const request = prev.find((r) => r.id === id); + request?.reject(new Error("Sampling request rejected")); + return prev.filter((r) => r.id !== id); + }); + }; + + const handleResolveElicitation = ( + id: number, + response: ElicitationResponse, + ) => { + setPendingElicitationRequests((prev) => { + const request = prev.find((r) => r.id === id); + if (request) { + request.resolve(response); + + if (request.originatingTab) { + const originatingTab = request.originatingTab; + + const validTabs = [ + ...(serverCapabilities?.resources ? ["resources"] : []), + ...(serverCapabilities?.prompts ? ["prompts"] : []), + ...(serverCapabilities?.tools ? ["tools"] : []), + "ping", + "sampling", + "elicitations", + "roots", + "auth", + ]; + + if (validTabs.includes(originatingTab)) { + setActiveTab(originatingTab); + window.location.hash = originatingTab; + + setTimeout(() => { + setActiveTab(originatingTab); + window.location.hash = originatingTab; + }, 100); + } + } + } + return prev.filter((r) => r.id !== id); + }); + }; + + const clearError = (tabKey: keyof typeof errors) => { + setErrors((prev) => ({ ...prev, [tabKey]: null })); + }; + + const listResources = async () => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + const response = await inspectorClient.listResources( + nextResourceCursor, + metadata, + ); + // InspectorClient now updates resources state automatically (accumulates when cursor provided) + setNextResourceCursor(response.nextCursor); + clearError("resources"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + resources: errorString, + })); + throw e; + } + }; + + const listResourceTemplates = async () => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + const response = await inspectorClient.listResourceTemplates( + nextResourceTemplateCursor, + metadata, + ); + // InspectorClient now updates resourceTemplates state automatically (accumulates when cursor provided) + setNextResourceTemplateCursor(response.nextCursor); + clearError("resources"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + resources: errorString, + })); + throw e; + } + }; + + const getPrompt = async (name: string, args: Record = {}) => { + lastToolCallOriginTabRef.current = currentTabRef.current; + + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + // Convert string args to JsonValue for InspectorClient + const jsonArgs: Record = {}; + for (const [key, value] of Object.entries(args)) { + jsonArgs[key] = value; // strings are valid JsonValue + } + const response = await inspectorClient.getPrompt( + name, + jsonArgs, + metadata, + ); + setPromptContent(JSON.stringify(response, null, 2)); + clearError("prompts"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + prompts: errorString, + })); + throw e; + } + }; + + const readResource = async (uri: string) => { + lastToolCallOriginTabRef.current = currentTabRef.current; + + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + const response = await inspectorClient.readResource(uri, metadata); + const content = JSON.stringify(response, null, 2); + setResourceContent(content); + setResourceContentMap((prev) => ({ + ...prev, + [uri]: content, + })); + clearError("resources"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + resources: errorString, + })); + throw e; + } + }; + + const subscribeToResource = async (uri: string) => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + await inspectorClient.subscribeToResource(uri); + // InspectorClient manages subscriptions internally, but we track them for UI + const clone = new Set(resourceSubscriptions); + clone.add(uri); + setResourceSubscriptions(clone); + clearError("resources"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + resources: errorString, + })); + throw e; + } + }; + + const unsubscribeFromResource = async (uri: string) => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + await inspectorClient.unsubscribeFromResource(uri); + // InspectorClient manages subscriptions internally, but we track them for UI + const clone = new Set(resourceSubscriptions); + clone.delete(uri); + setResourceSubscriptions(clone); + clearError("resources"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + resources: errorString, + })); + throw e; + } + }; + + const listPrompts = async () => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + const response = await inspectorClient.listPrompts( + nextPromptCursor, + metadata, + ); + // InspectorClient now updates prompts state automatically (accumulates when cursor provided) + setNextPromptCursor(response.nextCursor); + clearError("prompts"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + prompts: errorString, + })); + throw e; + } + }; + + const listTools = async () => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + const response = await inspectorClient.listTools( + nextToolCursor, + metadata, + ); + // InspectorClient now updates tools state automatically (accumulates when cursor provided) + setNextToolCursor(response.nextCursor); + cacheToolOutputSchemas(response.tools); + clearError("tools"); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + setErrors((prev) => ({ + ...prev, + tools: errorString, + })); + throw e; + } + }; + + const callTool = async ( + name: string, + params: Record, + toolMetadata?: Record, + ) => { + lastToolCallOriginTabRef.current = currentTabRef.current; + + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + + try { + // Find the tool schema to clean parameters properly + const tool = inspectorTools.find((t) => t.name === name); + const cleanedParams = tool?.inputSchema + ? cleanParams(params, tool.inputSchema as JsonSchemaType) + : params; + + // Merge general metadata with tool-specific metadata + // Tool-specific metadata takes precedence over general metadata + const generalMetadata = { + ...metadata, // General metadata + progressToken: String(progressTokenRef.current++), + }; + const toolSpecificMetadata = toolMetadata + ? Object.fromEntries( + Object.entries(toolMetadata).map(([k, v]) => [k, String(v)]), + ) + : undefined; + + const invocation = await inspectorClient.callTool( + name, + cleanedParams as Record, + generalMetadata, + toolSpecificMetadata, + ); + + // Convert ToolCallInvocation to CompatibilityCallToolResult + const compatibilityResult: CompatibilityCallToolResult = invocation.result + ? { + content: invocation.result.content || [], + isError: false, + } + : { + content: [ + { + type: "text", + text: invocation.error || "Tool call failed", + }, + ], + isError: true, + }; + + setToolResult(compatibilityResult); + // Clear any validation errors since tool execution completed + setErrors((prev) => ({ ...prev, tools: null })); + } catch (e) { + const toolResult: CompatibilityCallToolResult = { + content: [ + { + type: "text", + text: (e as Error).message ?? String(e), + }, + ], + isError: true, + }; + setToolResult(toolResult); + // Clear validation errors - tool execution errors are shown in ToolResults + setErrors((prev) => ({ ...prev, tools: null })); + } + }; + + const handleRootsChange = async () => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + // InspectorClient.setRoots() handles sending the notification internally + await inspectorClient.setRoots(roots); + }; + + const handleClearNotifications = () => { + setNotifications([]); + }; + + const sendLogLevelRequest = async (level: LoggingLevel) => { + if (!inspectorClient) { + throw new Error("InspectorClient is not connected"); + } + try { + await inspectorClient.setLoggingLevel(level); + setLogLevel(level); + } catch (e) { + const errorString = (e as Error).message ?? String(e); + console.error("Failed to set logging level:", errorString); + throw e; + } + }; + + const AuthDebuggerWrapper = () => ( + + setIsAuthDebuggerVisible(false)} + /> + + ); + + // Check for OAuth callback params (even if pathname is wrong - some OAuth servers redirect incorrectly) + const urlParams = new URLSearchParams(window.location.search); + const hasOAuthCallbackParams = + urlParams.has("code") || urlParams.has("error"); + const stateParam = urlParams.get("state"); + const isGuidedOAuthCallback = + hasOAuthCallbackParams && + (window.location.pathname === "/oauth/callback" || + window.location.pathname === "/") && + stateParam != null && + parseOAuthState(stateParam)?.mode === "guided"; + + // Guided auth callback in another tab: show callback UI (code to copy) without requiring API token. + // That tab has its own sessionStorage and won't have the token from the opener tab. + if (isGuidedOAuthCallback) { + const OAuthCallback = React.lazy( + () => import("./components/OAuthCallback"), + ); + return ( + + Loading... + + } + > + null} + onConnect={() => {}} + /> + + ); + } + + // No API token: show login screen so user can enter token (e.g. opened app without CLI) + // Once token is set we persist it; OAuth return flow relies on token in localStorage. + if (!getInspectorApiToken(config)) { + return ; + } + + // Handle OAuth callback - check pathname OR presence of callback params + // (Some OAuth servers redirect to root instead of /oauth/callback) + if ( + window.location.pathname === "/oauth/callback" || + (hasOAuthCallbackParams && window.location.pathname === "/") + ) { + const OAuthCallback = React.lazy( + () => import("./components/OAuthCallback"), + ); + return ( + Loading...}> + + + ); + } + + // If we have OAuth callback params but wrong pathname (and not root), log it + if ( + hasOAuthCallbackParams && + window.location.pathname !== "/oauth/callback" && + window.location.pathname !== "/" + ) { + console.warn( + "[App] OAuth callback params detected but unexpected pathname:", + { + pathname: window.location.pathname, + search: window.location.search, + fullUrl: window.location.href, + }, + ); + } + + return ( +
+
+ +
+
+
+
+ {connectionStatus === "connected" ? ( + { + setActiveTab(value); + window.location.hash = value; + }} + > + + + + Resources + + + + Prompts + + + + Tools + + + + Ping + + {transportType !== "stdio" && ( + + + Requests + + )} + + + Sampling + {pendingSampleRequests.length > 0 && ( + + {pendingSampleRequests.length} + + )} + + + + Elicitations + {pendingElicitationRequests.length > 0 && ( + + {pendingElicitationRequests.length} + + )} + + + + Roots + + {transportType === "stdio" && ( + + + Console + + )} + + + Auth + + + + Metadata + + + +
+ {!serverCapabilities?.resources && + !serverCapabilities?.prompts && + !serverCapabilities?.tools ? ( + <> +
+

+ The connected server does not support any MCP + capabilities +

+
+ { + if (!mcpClient) { + throw new Error("MCP client is not connected"); + } + try { + await mcpClient.request( + { method: "ping" }, + EmptyResultSchema, + ); + } catch (e) { + console.error("Ping failed:", e); + throw e; + } + }} + /> + + ) : ( + <> + { + clearError("resources"); + listResources(); + }} + clearResources={() => { + // InspectorClient now has clearResources() method + if (inspectorClient) { + inspectorClient.clearResources(); + } + setNextResourceCursor(undefined); + }} + listResourceTemplates={() => { + clearError("resources"); + listResourceTemplates(); + }} + clearResourceTemplates={() => { + // InspectorClient now has clearResourceTemplates() method + if (inspectorClient) { + inspectorClient.clearResourceTemplates(); + } + setNextResourceTemplateCursor(undefined); + }} + readResource={(uri) => { + clearError("resources"); + readResource(uri); + }} + selectedResource={selectedResource} + setSelectedResource={(resource) => { + clearError("resources"); + setSelectedResource(resource); + }} + resourceSubscriptionsSupported={ + serverCapabilities?.resources?.subscribe || false + } + resourceSubscriptions={resourceSubscriptions} + subscribeToResource={(uri) => { + clearError("resources"); + subscribeToResource(uri); + }} + unsubscribeFromResource={(uri) => { + clearError("resources"); + unsubscribeFromResource(uri); + }} + handleCompletion={handleCompletion} + completionsSupported={completionsSupported} + resourceContent={resourceContent} + nextCursor={nextResourceCursor} + nextTemplateCursor={nextResourceTemplateCursor} + error={errors.resources} + /> + { + clearError("prompts"); + listPrompts(); + }} + clearPrompts={() => { + // InspectorClient now has clearPrompts() method + if (inspectorClient) { + inspectorClient.clearPrompts(); + } + setNextPromptCursor(undefined); + }} + getPrompt={(name, args) => { + clearError("prompts"); + getPrompt(name, args); + }} + selectedPrompt={selectedPrompt} + setSelectedPrompt={(prompt) => { + clearError("prompts"); + setSelectedPrompt(prompt); + setPromptContent(""); + }} + handleCompletion={handleCompletion} + completionsSupported={completionsSupported} + promptContent={promptContent} + nextCursor={nextPromptCursor} + error={errors.prompts} + /> + { + clearError("tools"); + listTools(); + }} + clearTools={() => { + // InspectorClient now has clearTools() method + if (inspectorClient) { + inspectorClient.clearTools(); + } + setNextToolCursor(undefined); + cacheToolOutputSchemas([]); + }} + callTool={async ( + name: string, + params: Record, + metadata?: Record, + ) => { + clearError("tools"); + setToolResult(null); + await callTool(name, params, metadata); + }} + selectedTool={selectedTool} + setSelectedTool={(tool) => { + clearError("tools"); + setSelectedTool(tool); + setToolResult(null); + }} + toolResult={toolResult} + nextCursor={nextToolCursor} + error={errors.tools} + resourceContent={resourceContentMap} + onReadResource={(uri: string) => { + clearError("resources"); + readResource(uri); + }} + /> + + { + if (!mcpClient) { + throw new Error("MCP client is not connected"); + } + try { + await mcpClient.request( + { method: "ping" }, + EmptyResultSchema, + ); + } catch (e) { + console.error("Ping failed:", e); + throw e; + } + }} + /> + {transportType !== "stdio" && ( + + )} + + + + + + + )} +
+
+ ) : isAuthDebuggerVisible ? ( + (window.location.hash = value)} + > + + + ) : ( +
+

+ Connect to an MCP server to start inspecting +

+
+

+ Need to configure authentication? +

+ +
+
+ )} +
+
+
+
+
+
+ +
+
+
+
+ ); +}; + +export default App; diff --git a/web/src/__mocks__/styleMock.js b/web/src/__mocks__/styleMock.js new file mode 100644 index 000000000..f053ebf79 --- /dev/null +++ b/web/src/__mocks__/styleMock.js @@ -0,0 +1 @@ +module.exports = {}; diff --git a/web/src/__tests__/App.config.test.tsx b/web/src/__tests__/App.config.test.tsx new file mode 100644 index 000000000..908d6d5e3 --- /dev/null +++ b/web/src/__tests__/App.config.test.tsx @@ -0,0 +1,118 @@ +import { render, waitFor } from "@testing-library/react"; +import App from "../App"; +import { DEFAULT_INSPECTOR_CONFIG } from "../lib/constants"; +import { InspectorConfig } from "../lib/configurationTypes"; +import * as configUtils from "../utils/configUtils"; + +// Mock auth dependencies first +jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + auth: jest.fn(), +})); + +// Mock the config utils +jest.mock("../utils/configUtils", () => ({ + ...jest.requireActual("../utils/configUtils"), + getInitialTransportType: jest.fn(() => "stdio"), + getInitialSseUrl: jest.fn(() => "http://localhost:3001/sse"), + getInitialCommand: jest.fn(() => "mcp-server-everything"), + getInitialArgs: jest.fn(() => ""), + getInspectorApiToken: jest.fn( + (config: InspectorConfig) => + config.MCP_INSPECTOR_API_TOKEN?.value || undefined, + ), + initializeInspectorConfig: jest.fn(() => DEFAULT_INSPECTOR_CONFIG), + saveInspectorConfig: jest.fn(), +})); + +// Get references to the mocked functions +const mockInitializeInspectorConfig = + configUtils.initializeInspectorConfig as jest.Mock; + +// Mock InspectorClient hook +jest.mock( + "@modelcontextprotocol/inspector-shared/react/useInspectorClient.js", + () => ({ + useInspectorClient: () => ({ + status: "disconnected", + messages: [], + stderrLogs: [], + fetchRequests: [], + tools: [], + resources: [], + resourceTemplates: [], + prompts: [], + capabilities: null, + serverInfo: null, + instructions: undefined, + client: null, + connect: jest.fn(), + disconnect: jest.fn(), + }), + }), +); + +jest.mock("../lib/hooks/useDraggablePane", () => ({ + useDraggablePane: () => ({ + height: 300, + handleDragStart: jest.fn(), + }), + useDraggableSidebar: () => ({ + width: 320, + isDragging: false, + handleDragStart: jest.fn(), + }), +})); + +jest.mock("../components/Sidebar", () => ({ + __esModule: true, + default: () =>
Sidebar
, +})); + +// Mock fetch +global.fetch = jest.fn(); + +describe("App - Config Endpoint", () => { + beforeEach(() => { + jest.clearAllMocks(); + (global.fetch as jest.Mock).mockResolvedValue({ + ok: true, + json: () => + Promise.resolve({ + defaultEnvironment: { TEST_ENV: "test" }, + defaultCommand: "test-command", + defaultArgs: ["test-arg1", "test-arg2"], + defaultTransport: "stdio", + defaultServerUrl: "", + }), + }); + }); + + afterEach(() => { + jest.clearAllMocks(); + }); + + test("fetches /api/config when API token is present and applies response", async () => { + const mockConfig = { + ...DEFAULT_INSPECTOR_CONFIG, + MCP_INSPECTOR_API_TOKEN: { + ...DEFAULT_INSPECTOR_CONFIG.MCP_INSPECTOR_API_TOKEN, + value: "test-api-token", + }, + }; + + mockInitializeInspectorConfig.mockReturnValue(mockConfig); + + render(); + + await waitFor(() => { + expect(global.fetch).toHaveBeenCalledWith( + expect.stringContaining("/api/config"), + expect.objectContaining({ + headers: { + "x-mcp-remote-auth": "Bearer test-api-token", + }, + }), + ); + }); + }); +}); diff --git a/web/src/__tests__/App.routing.test.tsx b/web/src/__tests__/App.routing.test.tsx new file mode 100644 index 000000000..5dae15483 --- /dev/null +++ b/web/src/__tests__/App.routing.test.tsx @@ -0,0 +1,170 @@ +import { render, waitFor } from "@testing-library/react"; +import App from "../App"; +import { useInspectorClient } from "@modelcontextprotocol/inspector-shared/react/useInspectorClient.js"; + +// Mock auth dependencies first +jest.mock("@modelcontextprotocol/sdk/client/auth.js", () => ({ + auth: jest.fn(), +})); + +// Mock the config utils +jest.mock("../utils/configUtils", () => ({ + ...jest.requireActual("../utils/configUtils"), + getInitialTransportType: jest.fn(() => "stdio"), + getInitialSseUrl: jest.fn(() => "http://localhost:3001/sse"), + getInitialCommand: jest.fn(() => "mcp-server-everything"), + getInitialArgs: jest.fn(() => ""), + initializeInspectorConfig: jest.fn(() => ({ + MCP_INSPECTOR_API_TOKEN: { + label: "API Token", + description: + "Auth token for authenticating with the Inspector API server", + value: "", + is_session_item: true, + }, + })), + saveInspectorConfig: jest.fn(), +})); + +// Default connection state is disconnected +const disconnectedInspectorClientState = { + status: "disconnected" as const, + messages: [], + stderrLogs: [], + fetchRequests: [], + tools: [], + resources: [], + resourceTemplates: [], + prompts: [], + capabilities: null, + serverInfo: null, + instructions: undefined, + client: null, + connect: jest.fn(), + disconnect: jest.fn(), +}; + +// Connected state for tests that need an active connection +const connectedInspectorClientState = { + ...disconnectedInspectorClientState, + status: "connected" as const, + capabilities: {}, + client: {}, // Mock client object - needed for hash setting logic +}; + +// Mock required dependencies, but unrelated to routing. +jest.mock("../lib/hooks/useDraggablePane", () => ({ + useDraggablePane: () => ({ + height: 300, + handleDragStart: jest.fn(), + }), + useDraggableSidebar: () => ({ + width: 320, + isDragging: false, + handleDragStart: jest.fn(), + }), +})); + +jest.mock("../components/Sidebar", () => ({ + __esModule: true, + default: () =>
Sidebar
, +})); + +// Mock fetch +global.fetch = jest.fn().mockResolvedValue({ json: () => Promise.resolve({}) }); + +// Mock InspectorClient hook +jest.mock( + "@modelcontextprotocol/inspector-shared/react/useInspectorClient.js", + () => ({ + useInspectorClient: jest.fn(), + }), +); + +// jsdom does not provide window.matchMedia; useTheme calls it. +const mockMatchMedia = (matches = false) => ({ + matches, + addEventListener: jest.fn(), + removeEventListener: jest.fn(), + dispatchEvent: jest.fn(), + onchange: null, + addListener: jest.fn(), + removeListener: jest.fn(), + media: "", +}); + +describe("App - URL Fragment Routing", () => { + const mockUseInspectorClient = jest.mocked(useInspectorClient); + + beforeEach(() => { + jest.restoreAllMocks(); + + window.matchMedia = jest + .fn() + .mockImplementation((query: string) => + mockMatchMedia(false), + ) as unknown as typeof window.matchMedia; + + // Inspector starts disconnected. + mockUseInspectorClient.mockReturnValue(disconnectedInspectorClientState); + }); + + test("does not set hash when starting disconnected", async () => { + render(); + + await waitFor(() => { + expect(window.location.hash).toBe(""); + }); + }); + + test("sets default hash based on server capabilities priority", async () => { + // Tab priority follows UI order: Resources | Prompts | Tools | Ping | Sampling | Roots | Auth + // + // Server capabilities determine the first three tabs; if none are present, falls back to Ping. + + const testCases = [ + { + capabilities: { resources: { listChanged: true, subscribe: true } }, + expected: "#resources", + }, + { + capabilities: { prompts: { listChanged: true, subscribe: true } }, + expected: "#prompts", + }, + { + capabilities: { tools: { listChanged: true, subscribe: true } }, + expected: "#tools", + }, + { capabilities: {}, expected: "#ping" }, + ]; + + const { rerender } = render(); + + for (const { capabilities, expected } of testCases) { + window.location.hash = ""; + mockUseInspectorClient.mockReturnValue({ + ...connectedInspectorClientState, + capabilities, + }); + + rerender(); + + await waitFor(() => { + expect(window.location.hash).toBe(expected); + }); + } + }); + + test("clears hash when disconnected", async () => { + // Start with a hash set (simulating a connection) + window.location.hash = "#resources"; + + // App starts disconnected (default mock) + render(); + + // Should clear the hash when disconnected + await waitFor(() => { + expect(window.location.hash).toBe(""); + }); + }); +}); diff --git a/web/src/components/AuthDebugger.tsx b/web/src/components/AuthDebugger.tsx new file mode 100644 index 000000000..db391ca71 --- /dev/null +++ b/web/src/components/AuthDebugger.tsx @@ -0,0 +1,323 @@ +import { useCallback, useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { AlertCircle } from "lucide-react"; +import type { InspectorClient } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; +import type { AuthGuidedState } from "@modelcontextprotocol/inspector-shared/auth/types.js"; +import { OAuthFlowProgress } from "./OAuthFlowProgress"; +import { useToast } from "@/lib/hooks/useToast"; + +export interface AuthDebuggerProps { + inspectorClient: InspectorClient | null; + ensureInspectorClient: () => InspectorClient | null; + canCreateInspectorClient: () => boolean; + onBack: () => void; +} + +interface StatusMessageProps { + message: { type: "error" | "success" | "info"; message: string }; +} + +const StatusMessage = ({ message }: StatusMessageProps) => { + let bgColor: string; + let textColor: string; + let borderColor: string; + + switch (message.type) { + case "error": + bgColor = "bg-red-50"; + textColor = "text-red-700"; + borderColor = "border-red-200"; + break; + case "success": + bgColor = "bg-green-50"; + textColor = "text-green-700"; + borderColor = "border-green-200"; + break; + case "info": + default: + bgColor = "bg-blue-50"; + textColor = "text-blue-700"; + borderColor = "border-blue-200"; + break; + } + + return ( +
+
+ +

{message.message}

+
+
+ ); +}; + +const AuthDebugger = ({ + inspectorClient, + ensureInspectorClient, + canCreateInspectorClient, + onBack, +}: AuthDebuggerProps) => { + const { toast } = useToast(); + const [oauthState, setOauthState] = useState( + undefined, + ); + const [isInitiatingAuth, setIsInitiatingAuth] = useState(false); + + // Sync oauthState from InspectorClient (TUI pattern) + useEffect(() => { + if (!inspectorClient) { + setOauthState(undefined); + return; + } + + const update = () => setOauthState(inspectorClient.getOAuthState()); + update(); + + const onStepChange = () => update(); + inspectorClient.addEventListener("oauthStepChange", onStepChange); + inspectorClient.addEventListener("oauthComplete", onStepChange); + inspectorClient.addEventListener("oauthError", onStepChange); + + return () => { + inspectorClient.removeEventListener("oauthStepChange", onStepChange); + inspectorClient.removeEventListener("oauthComplete", onStepChange); + inspectorClient.removeEventListener("oauthError", onStepChange); + }; + }, [inspectorClient]); + + // Check for existing tokens on mount + useEffect(() => { + if (inspectorClient && !oauthState?.oauthTokens) { + inspectorClient.getOAuthTokens().then((tokens) => { + if (tokens) { + // State will be updated via getOAuthState() in sync effect + setOauthState(inspectorClient.getOAuthState()); + } + }); + } + }, [inspectorClient, oauthState]); + + const handleQuickOAuth = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client) { + return; // Error already shown in ensureInspectorClient + } + + setIsInitiatingAuth(true); + try { + // Quick Auth: normal flow (automatic redirect via BrowserNavigation) + const authUrl = await client.authenticate(); + // Log to InspectorClient's logger (persists through redirects) + const clientLogger = (client as any).logger; + if (clientLogger) { + clientLogger.info( + { + component: "AuthDebugger", + action: "authenticate", + authorizationUrl: authUrl.href, + redirectUri: authUrl.searchParams.get("redirect_uri"), + expectedRedirectUri: `${window.location.origin}/oauth/callback`, + currentOrigin: window.location.origin, + currentPathname: window.location.pathname, + }, + "OAuth authorization URL generated - about to redirect", + ); + } + // Log to console as well (will be lost on redirect but useful for debugging) + console.log("[AuthDebugger] Authorization URL:", authUrl.href); + console.log( + "[AuthDebugger] Redirect URI param:", + authUrl.searchParams.get("redirect_uri"), + ); + // BrowserNavigation handles redirect automatically + } catch (error) { + console.error("Quick OAuth failed:", error); + toast({ + title: "OAuth Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } finally { + setIsInitiatingAuth(false); + } + }, [ensureInspectorClient, toast]); + + const handleGuidedOAuth = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client) { + return; // Error already shown in ensureInspectorClient + } + + setIsInitiatingAuth(true); + try { + // Start guided flow + await client.beginGuidedAuth(); + // State updates via oauthStepChange events (handled in useEffect above) + } catch (error) { + console.error("Guided OAuth start failed:", error); + toast({ + title: "OAuth Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } finally { + setIsInitiatingAuth(false); + } + }, [ensureInspectorClient, toast]); + + const proceedToNextStep = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client || !oauthState) { + if (!client) { + // Error already shown in ensureInspectorClient + return; + } + return; // No oauthState, nothing to proceed + } + + setIsInitiatingAuth(true); + try { + await client.proceedOAuthStep(); + // Note: For guided flow, users manually copy the authorization code. + // There's a manual button in OAuthFlowProgress to open the URL if needed. + // Quick auth handles redirects automatically via BrowserNavigation. + } catch (error) { + console.error("OAuth step failed:", error); + toast({ + title: "OAuth Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } finally { + setIsInitiatingAuth(false); + } + }, [ensureInspectorClient, oauthState, toast]); + + const handleClearOAuth = useCallback(async () => { + const client = ensureInspectorClient(); + if (!client) { + return; // Error already shown in ensureInspectorClient + } + + try { + client.clearOAuthTokens(); + toast({ + title: "OAuth Cleared", + description: "OAuth tokens cleared successfully", + variant: "default", + }); + } catch (error) { + console.error("Clear OAuth failed:", error); + toast({ + title: "Error", + description: error instanceof Error ? error.message : String(error), + variant: "destructive", + }); + } + }, [ensureInspectorClient, toast]); + + return ( +
+
+

Authentication Settings

+ +
+ +
+
+
+

+ Configure authentication settings for your MCP server connection. +

+ +
+

OAuth Authentication

+

+ Use OAuth to securely authenticate with the MCP server. +

+ + {oauthState?.latestError && ( + + )} + +
+ {oauthState?.oauthTokens && ( +
+

Access Token:

+
+ {oauthState.oauthTokens.access_token.substring(0, 25)}... +
+
+ )} + +
+ + + + + +
+ {!inspectorClient && !canCreateInspectorClient() && ( +

+ API Token is required. Please set it in Configuration. +

+ )} + +

+ Choose "Guided" for step-by-step instructions or "Quick" for + the standard automatic flow. +

+
+
+ + +
+
+
+
+ ); +}; + +export default AuthDebugger; diff --git a/web/src/components/ConsoleTab.tsx b/web/src/components/ConsoleTab.tsx new file mode 100644 index 000000000..5c8bd0eb7 --- /dev/null +++ b/web/src/components/ConsoleTab.tsx @@ -0,0 +1,44 @@ +import { TabsContent } from "@/components/ui/tabs"; +import type { StderrLogEntry } from "@modelcontextprotocol/inspector-shared/mcp/index.js"; + +interface ConsoleTabProps { + stderrLogs: StderrLogEntry[]; +} + +const ConsoleTab = ({ stderrLogs }: ConsoleTabProps) => { + const formatTimestamp = (timestamp: Date) => { + return new Date(timestamp).toLocaleTimeString("en-US", { + hour12: false, + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + // @ts-expect-error - fractionalSecondDigits is valid but not in TypeScript types yet + fractionalSecondDigits: 3, + }); + }; + + return ( + +
+ {stderrLogs.length === 0 ? ( +
No stderr output yet
+ ) : ( +
+ {stderrLogs.map((log, index) => ( +
+ + {formatTimestamp(log.timestamp)} + + + {log.message} + +
+ ))} +
+ )} +
+
+ ); +}; + +export default ConsoleTab; diff --git a/web/src/components/CustomHeaders.tsx b/web/src/components/CustomHeaders.tsx new file mode 100644 index 000000000..463f7333b --- /dev/null +++ b/web/src/components/CustomHeaders.tsx @@ -0,0 +1,241 @@ +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Textarea } from "@/components/ui/textarea"; +import { Switch } from "@/components/ui/switch"; +import { Plus, Trash2, Eye, EyeOff } from "lucide-react"; +import { + CustomHeaders as CustomHeadersType, + CustomHeader, + createEmptyHeader, +} from "@/lib/types/customHeaders"; + +interface CustomHeadersProps { + headers: CustomHeadersType; + onChange: (headers: CustomHeadersType) => void; + className?: string; +} + +const CustomHeaders = ({ + headers, + onChange, + className, +}: CustomHeadersProps) => { + const [isJsonMode, setIsJsonMode] = useState(false); + const [jsonValue, setJsonValue] = useState(""); + const [jsonError, setJsonError] = useState(null); + const [visibleValues, setVisibleValues] = useState>(new Set()); + + const updateHeader = ( + index: number, + field: keyof CustomHeader, + value: string | boolean, + ) => { + const newHeaders = [...headers]; + newHeaders[index] = { ...newHeaders[index], [field]: value }; + onChange(newHeaders); + }; + + const addHeader = () => { + onChange([...headers, createEmptyHeader()]); + }; + + const removeHeader = (index: number) => { + const newHeaders = headers.filter((_, i) => i !== index); + onChange(newHeaders); + }; + + const toggleValueVisibility = (index: number) => { + const newVisible = new Set(visibleValues); + if (newVisible.has(index)) { + newVisible.delete(index); + } else { + newVisible.add(index); + } + setVisibleValues(newVisible); + }; + + const switchToJsonMode = () => { + const jsonObject: Record = {}; + headers.forEach((header) => { + if (header.enabled && header.name.trim() && header.value.trim()) { + jsonObject[header.name.trim()] = header.value.trim(); + } + }); + setJsonValue(JSON.stringify(jsonObject, null, 2)); + setJsonError(null); + setIsJsonMode(true); + }; + + const switchToFormMode = () => { + try { + const parsed = JSON.parse(jsonValue); + if ( + typeof parsed !== "object" || + parsed === null || + Array.isArray(parsed) + ) { + setJsonError("JSON must be an object with string key-value pairs"); + return; + } + + const newHeaders: CustomHeadersType = Object.entries(parsed).map( + ([name, value]) => ({ + name, + value: String(value), + enabled: true, + }), + ); + + onChange(newHeaders); + setJsonError(null); + setIsJsonMode(false); + } catch { + setJsonError("Invalid JSON format"); + } + }; + + const handleJsonChange = (value: string) => { + setJsonValue(value); + setJsonError(null); + }; + + if (isJsonMode) { + return ( +
+
+

+ Custom Headers (JSON) +

+ +
+
+