diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..0db5467a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,36 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "" +labels: "" +assignees: "" +--- + +**Inspector Version** + +- [e.g. 0.16.5) + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Environment (please complete the following information):** + +- OS: [e.g. iOS] +- Browser [e.g. chrome, safari] + +**Additional context** +Add any other context about the problem here. diff --git a/.gitignore b/.gitignore index eefb0a79..a7eee74a 100644 --- a/.gitignore +++ b/.gitignore @@ -15,4 +15,6 @@ sdk client/playwright-report/ client/results.json client/test-results/ +client/e2e/test-results/ mcp.json +.claude/settings.local.json diff --git a/.prettierignore b/.prettierignore index cd910373..167a7cb4 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,3 +3,4 @@ server/build CODE_OF_CONDUCT.md SECURITY.md mcp.json +.claude/settings.local.json \ No newline at end of file diff --git a/README.md b/README.md index a0716556..29037550 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,16 @@ The MCP Inspector provides convenient buttons to export server launch configurat } ``` + **Streamable HTTP transport example:** + + ```json + { + "type": "streamable-http", + "url": "http://localhost:3000/mcp", + "note": "For Streamable HTTP connections, add this URL directly in your MCP Client" + } + ``` + - **Servers File** - Copies a complete MCP configuration file structure to your clipboard, with your current server configuration added as `default-server`. This can be saved directly as `mcp.json`. **STDIO transport example:** @@ -131,9 +141,23 @@ The MCP Inspector provides convenient buttons to export server launch configurat } ``` + **Streamable HTTP transport example:** + + ```json + { + "mcpServers": { + "default-server": { + "type": "streamable-http", + "url": "http://localhost:3000/mcp", + "note": "For Streamable HTTP connections, add this URL directly in your MCP Client" + } + } + } + ``` + These buttons appear in the Inspector UI after you've configured your server settings, making it easy to save and reuse your configurations. -For SSE transport connections, the Inspector provides similar functionality for both buttons. The "Server Entry" button copies the SSE URL configuration that can be added to your existing configuration file, while the "Servers File" button creates a complete configuration file containing the SSE URL for direct use in clients. +For SSE and Streamable HTTP transport connections, the Inspector provides similar functionality for both buttons. The "Server Entry" button copies the configuration that can be added to your existing configuration file, while the "Servers File" button creates a complete configuration file containing the URL for direct use in clients. You can paste the Server Entry into your existing `mcp.json` file under your chosen server name, or use the complete Servers File payload to create a new configuration file. @@ -410,6 +434,9 @@ npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com # Connect to a remote MCP server (with Streamable HTTP transport) npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http --method tools/list +# Connect to a remote MCP server (with custom headers) +npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http --method tools/list --header "X-API-Key: your-api-key" + # Call a tool on a remote server npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --method tools/call --tool-name remotetool --tool-arg param=value diff --git a/cli/package.json b/cli/package.json index e274bbdf..ddeb3b93 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-cli", - "version": "0.16.5", + "version": "0.17.0", "description": "CLI for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", @@ -17,13 +17,14 @@ "scripts": { "build": "tsc", "postbuild": "node scripts/make-executable.js", - "test": "node scripts/cli-tests.js && node scripts/cli-tool-tests.js", + "test": "node scripts/cli-tests.js && node scripts/cli-tool-tests.js && node scripts/cli-header-tests.js", "test:cli": "node scripts/cli-tests.js", - "test:cli-tools": "node scripts/cli-tool-tests.js" + "test:cli-tools": "node scripts/cli-tool-tests.js", + "test:cli-headers": "node scripts/cli-header-tests.js" }, "devDependencies": {}, "dependencies": { - "@modelcontextprotocol/sdk": "^1.17.3", + "@modelcontextprotocol/sdk": "^1.18.0", "commander": "^13.1.0", "spawn-rx": "^5.1.2" } diff --git a/cli/scripts/cli-header-tests.js b/cli/scripts/cli-header-tests.js new file mode 100644 index 00000000..0f1d22a9 --- /dev/null +++ b/cli/scripts/cli-header-tests.js @@ -0,0 +1,252 @@ +#!/usr/bin/env node + +/** + * Integration tests for header functionality + * Tests the CLI header parsing end-to-end + */ + +import { spawn } from "node:child_process"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const CLI_PATH = resolve(__dirname, "..", "build", "index.js"); + +// ANSI colors for output +const colors = { + GREEN: "\x1b[32m", + RED: "\x1b[31m", + YELLOW: "\x1b[33m", + BLUE: "\x1b[34m", + NC: "\x1b[0m", // No Color +}; + +let testsPassed = 0; +let testsFailed = 0; + +/** + * Run a CLI test with given arguments and check for expected behavior + */ +function runHeaderTest( + testName, + args, + expectSuccess = false, + expectedInOutput = null, +) { + return new Promise((resolve) => { + console.log(`\n${colors.BLUE}Testing: ${testName}${colors.NC}`); + console.log( + `${colors.BLUE}Command: node ${CLI_PATH} ${args.join(" ")}${colors.NC}`, + ); + + const child = spawn("node", [CLI_PATH, ...args], { + stdio: ["pipe", "pipe", "pipe"], + timeout: 10000, + }); + + let stdout = ""; + let stderr = ""; + + child.stdout.on("data", (data) => { + stdout += data.toString(); + }); + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + const output = stdout + stderr; + let passed = true; + let reason = ""; + + // Check exit code expectation + if (expectSuccess && code !== 0) { + passed = false; + reason = `Expected success (exit code 0) but got ${code}`; + } else if (!expectSuccess && code === 0) { + passed = false; + reason = `Expected failure (non-zero exit code) but got success`; + } + + // Check expected output + if (passed && expectedInOutput && !output.includes(expectedInOutput)) { + passed = false; + reason = `Expected output to contain "${expectedInOutput}"`; + } + + if (passed) { + console.log(`${colors.GREEN}PASS: ${testName}${colors.NC}`); + testsPassed++; + } else { + console.log(`${colors.RED}FAIL: ${testName}${colors.NC}`); + console.log(`${colors.RED}Reason: ${reason}${colors.NC}`); + console.log(`${colors.RED}Exit code: ${code}${colors.NC}`); + console.log(`${colors.RED}Output: ${output}${colors.NC}`); + testsFailed++; + } + + resolve(); + }); + + child.on("error", (error) => { + console.log( + `${colors.RED}ERROR: ${testName} - ${error.message}${colors.NC}`, + ); + testsFailed++; + resolve(); + }); + }); +} + +async function runHeaderIntegrationTests() { + console.log( + `${colors.YELLOW}=== MCP Inspector CLI Header Integration Tests ===${colors.NC}`, + ); + console.log( + `${colors.BLUE}Testing header parsing and validation${colors.NC}`, + ); + + // Test 1: Valid header format should parse successfully (connection will fail) + await runHeaderTest( + "Valid single header", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "Authorization: Bearer token123", + ], + false, + ); + + // Test 2: Multiple headers should parse successfully + await runHeaderTest( + "Multiple headers", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "Authorization: Bearer token123", + "--header", + "X-API-Key: secret123", + ], + false, + ); + + // Test 3: Invalid header format - no colon + await runHeaderTest( + "Invalid header format - no colon", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "InvalidHeader", + ], + false, + "Invalid header format", + ); + + // Test 4: Invalid header format - empty name + await runHeaderTest( + "Invalid header format - empty name", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + ": value", + ], + false, + "Invalid header format", + ); + + // Test 5: Invalid header format - empty value + await runHeaderTest( + "Invalid header format - empty value", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "Header:", + ], + false, + "Invalid header format", + ); + + // Test 6: Header with colons in value + await runHeaderTest( + "Header with colons in value", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + "X-Time: 2023:12:25:10:30:45", + ], + false, + ); + + // Test 7: Whitespace handling + await runHeaderTest( + "Whitespace handling in headers", + [ + "https://example.com", + "--method", + "tools/list", + "--transport", + "http", + "--header", + " X-Header : value with spaces ", + ], + false, + ); + + console.log(`\n${colors.YELLOW}=== Test Results ===${colors.NC}`); + console.log(`${colors.GREEN}Tests passed: ${testsPassed}${colors.NC}`); + console.log(`${colors.RED}Tests failed: ${testsFailed}${colors.NC}`); + + if (testsFailed === 0) { + console.log( + `${colors.GREEN}All header integration tests passed!${colors.NC}`, + ); + process.exit(0); + } else { + console.log( + `${colors.RED}Some header integration tests failed.${colors.NC}`, + ); + process.exit(1); + } +} + +// Handle graceful shutdown +process.on("SIGINT", () => { + console.log(`\n${colors.YELLOW}Test interrupted by user${colors.NC}`); + process.exit(1); +}); + +process.on("SIGTERM", () => { + console.log(`\n${colors.YELLOW}Test terminated${colors.NC}`); + process.exit(1); +}); + +// Run the tests +runHeaderIntegrationTests().catch((error) => { + console.error(`${colors.RED}Test runner error: ${error.message}${colors.NC}`); + process.exit(1); +}); diff --git a/cli/src/cli.ts b/cli/src/cli.ts index 13c7e492..f4187e02 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -16,6 +16,7 @@ type Args = { cli: boolean; transport?: "stdio" | "sse" | "streamable-http"; serverUrl?: string; + headers?: Record; }; type CliOptions = { @@ -25,6 +26,7 @@ type CliOptions = { cli?: boolean; transport?: string; serverUrl?: string; + header?: Record; }; type ServerConfig = @@ -104,6 +106,10 @@ async function runWebClient(args: Args): Promise { await spawnPromise("node", [inspectorClientPath, ...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; @@ -127,6 +133,9 @@ async function runCli(args: Args): Promise { // Build CLI arguments const cliArgs = [cliPath]; + // Add target URL/command first + cliArgs.push(args.command, ...args.args); + // Add transport flag if specified if (args.transport && args.transport !== "stdio") { // Convert streamable-http back to http for CLI mode @@ -135,13 +144,21 @@ async function runCli(args: Args): Promise { cliArgs.push("--transport", cliTransport); } - // Add command and remaining args - cliArgs.push(args.command, ...args.args); + // Add headers if specified + if (args.headers) { + for (const [key, value] of Object.entries(args.headers)) { + cliArgs.push("--header", `${key}: ${value}`); + } + } await spawnPromise("node", cliArgs, { env: { ...process.env, ...args.envArgs }, 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) { @@ -201,6 +218,30 @@ function parseKeyValuePair( return { ...previous, [key as string]: val }; } +function parseHeaderPair( + value: string, + previous: Record = {}, +): Record { + const colonIndex = value.indexOf(":"); + + if (colonIndex === -1) { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + const key = value.slice(0, colonIndex).trim(); + const val = value.slice(colonIndex + 1).trim(); + + if (key === "" || val === "") { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + return { ...previous, [key]: val }; +} + function parseArgs(): Args { const program = new Command(); @@ -227,7 +268,13 @@ function parseArgs(): Args { .option("--server ", "server name from config file") .option("--cli", "enable CLI mode") .option("--transport ", "transport type (stdio, sse, http)") - .option("--server-url ", "server URL for SSE/HTTP transport"); + .option("--server-url ", "server URL for SSE/HTTP transport") + .option( + "--header ", + 'HTTP headers as "HeaderName: Value" pairs (for HTTP/SSE transports)', + parseHeaderPair, + {}, + ); // Parse only the arguments before -- program.parse(preArgs); @@ -280,6 +327,7 @@ function parseArgs(): Args { envArgs: { ...(config.env || {}), ...(options.e || {}) }, cli: options.cli || false, transport: "stdio", + headers: options.header, }; } else if (config.type === "sse" || config.type === "streamable-http") { return { @@ -289,6 +337,7 @@ function parseArgs(): Args { cli: options.cli || false, transport: config.type, serverUrl: config.url, + headers: options.header, }; } else { // Backwards compatibility: if no type field, assume stdio @@ -298,6 +347,7 @@ function parseArgs(): Args { envArgs: { ...((config as any).env || {}), ...(options.e || {}) }, cli: options.cli || false, transport: "stdio", + headers: options.header, }; } } @@ -319,6 +369,7 @@ function parseArgs(): Args { cli: options.cli || false, transport: transport as "stdio" | "sse" | "streamable-http" | undefined, serverUrl: options.serverUrl, + headers: options.header, }; } diff --git a/cli/src/index.ts b/cli/src/index.ts index 563160bc..90c9f5e6 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -1,5 +1,6 @@ #!/usr/bin/env node +import * as fs from "fs"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Command } from "commander"; import { @@ -19,6 +20,7 @@ import { } from "./client/index.js"; import { handleError } from "./error-handler.js"; import { createTransport, TransportOptions } from "./transport.js"; +import { awaitableLog } from "./utils/awaitable-log.js"; // JSON value type for CLI arguments type JsonValue = @@ -40,11 +42,13 @@ type Args = { toolName?: string; toolArg?: Record; transport?: "sse" | "stdio" | "http"; + headers?: Record; }; function createTransportOptions( target: string[], transport?: "sse" | "stdio" | "http", + headers?: Record, ): TransportOptions { if (target.length === 0) { throw new Error( @@ -91,16 +95,32 @@ function createTransportOptions( command: isUrl ? undefined : command, args: isUrl ? undefined : commandArgs, url: isUrl ? command : undefined, + headers, }; } async function callMethod(args: Args): Promise { - const transportOptions = createTransportOptions(args.target, args.transport); - const transport = createTransport(transportOptions); - const client = new Client({ - name: "inspector-cli", - version: "0.5.1", + // Read package.json to get name and version for client identity + const pathA = "../package.json"; // We're in package @modelcontextprotocol/inspector-cli + const pathB = "../../package.json"; // We're in package @modelcontextprotocol/inspector + let packageJson: { name: string; version: string }; + let packageJsonData = await import(fs.existsSync(pathA) ? pathA : pathB, { + with: { type: "json" }, }); + 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); try { await connect(client, transport); @@ -160,7 +180,7 @@ async function callMethod(args: Args): Promise { ); } - console.log(JSON.stringify(result, null, 2)); + await awaitableLog(JSON.stringify(result, null, 2)); } finally { try { await disconnect(transport); @@ -196,6 +216,30 @@ function parseKeyValuePair( return { ...previous, [key as string]: parsedValue }; } +function parseHeaderPair( + value: string, + previous: Record = {}, +): Record { + const colonIndex = value.indexOf(":"); + + if (colonIndex === -1) { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + const key = value.slice(0, colonIndex).trim(); + const val = value.slice(colonIndex + 1).trim(); + + if (key === "" || val === "") { + throw new Error( + `Invalid header format: ${value}. Use "HeaderName: Value" format.`, + ); + } + + return { ...previous, [key]: val }; +} + function parseArgs(): Args { const program = new Command(); @@ -275,12 +319,24 @@ function parseArgs(): Args { } return value as "sse" | "http" | "stdio"; }, + ) + // + // HTTP headers + // + .option( + "--header ", + 'HTTP headers as "HeaderName: Value" pairs (for HTTP/SSE transports)', + parseHeaderPair, + {}, ); // Parse only the arguments before -- program.parse(preArgs); - const options = program.opts() as Omit; + const options = program.opts() as Omit & { + header?: Record; + }; + let remainingArgs = program.args; // Add back any arguments that came after -- @@ -295,6 +351,7 @@ function parseArgs(): Args { return { target: finalArgs, ...options, + headers: options.header, // commander.js uses 'header' field, map to 'headers' }; } @@ -306,6 +363,7 @@ async function main(): Promise { try { const args = parseArgs(); await callMethod(args); + // Explicitly exit to ensure process terminates in CI process.exit(0); } catch (error) { diff --git a/cli/src/transport.ts b/cli/src/transport.ts index 812e9e30..84af393b 100644 --- a/cli/src/transport.ts +++ b/cli/src/transport.ts @@ -12,6 +12,7 @@ export type TransportOptions = { command?: string; args?: string[]; url?: string; + headers?: Record; }; function createStdioTransport(options: TransportOptions): Transport { @@ -64,11 +65,25 @@ export function createTransport(options: TransportOptions): Transport { const url = new URL(options.url); if (transportType === "sse") { - return new SSEClientTransport(url); + const transportOptions = options.headers + ? { + requestInit: { + headers: options.headers, + }, + } + : undefined; + return new SSEClientTransport(url, transportOptions); } if (transportType === "http") { - return new StreamableHTTPClientTransport(url); + const transportOptions = options.headers + ? { + requestInit: { + headers: options.headers, + }, + } + : undefined; + return new StreamableHTTPClientTransport(url, transportOptions); } throw new Error(`Unsupported transport type: ${transportType}`); diff --git a/cli/src/utils/awaitable-log.ts b/cli/src/utils/awaitable-log.ts new file mode 100644 index 00000000..144f0112 --- /dev/null +++ b/cli/src/utils/awaitable-log.ts @@ -0,0 +1,7 @@ +export function awaitableLog(logValue: string): Promise { + return new Promise((resolve) => { + process.stdout.write(logValue, () => { + resolve(); + }); + }); +} diff --git a/client/package.json b/client/package.json index 5d634ee1..6881c1f7 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-client", - "version": "0.16.5", + "version": "0.17.0", "description": "Client-side application for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", @@ -25,7 +25,7 @@ "cleanup:e2e": "node e2e/global-teardown.js" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.17.3", + "@modelcontextprotocol/sdk": "^1.18.0", "@radix-ui/react-checkbox": "^1.1.4", "@radix-ui/react-dialog": "^1.1.3", "@radix-ui/react-icons": "^1.3.0", @@ -33,6 +33,7 @@ "@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", @@ -48,7 +49,6 @@ "react-simple-code-editor": "^0.14.1", "serve-handler": "^6.1.6", "tailwind-merge": "^2.5.3", - "tailwindcss-animate": "^1.0.7", "zod": "^3.25.76" }, "devDependencies": { @@ -70,8 +70,10 @@ "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", diff --git a/client/src/App.tsx b/client/src/App.tsx index fecd9839..b7fc607b 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -22,6 +22,8 @@ import { SESSION_KEYS, getServerSpecificKey } from "./lib/constants"; import { AuthDebuggerState, EMPTY_DEBUGGER_STATE } from "./lib/auth-types"; import { OAuthStateMachine } from "./lib/oauth-state-machine"; import { cacheToolOutputSchemas } from "./utils/schemaUtils"; +import { cleanParams } from "./utils/paramUtils"; +import type { JsonSchemaType } from "./utils/jsonUtils"; import React, { Suspense, useCallback, @@ -74,6 +76,10 @@ import ElicitationTab, { PendingElicitationRequest, ElicitationResponse, } from "./components/ElicitationTab"; +import { + CustomHeaders, + migrateFromLegacyAuth, +} from "./lib/types/customHeaders"; const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1"; @@ -103,6 +109,14 @@ const App = () => { const [transportType, setTransportType] = useState< "stdio" | "sse" | "streamable-http" >(getInitialTransportType); + const [connectionType, setConnectionType] = useState<"direct" | "proxy">( + () => { + return ( + (localStorage.getItem("lastConnectionType") as "direct" | "proxy") || + "proxy" + ); + }, + ); const [logLevel, setLogLevel] = useState("debug"); const [notifications, setNotifications] = useState([]); const [roots, setRoots] = useState([]); @@ -127,6 +141,39 @@ const App = () => { return localStorage.getItem("lastOauthScope") || ""; }); + // 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 & { @@ -200,6 +247,7 @@ const App = () => { serverCapabilities, mcpClient, requestHistory, + clearRequestHistory, makeRequest, sendNotification, handleCompletion, @@ -212,11 +260,11 @@ const App = () => { args, sseUrl, env, - bearerToken, - headerName, + customHeaders, oauthClientId, oauthScope, config, + connectionType, onNotification: (notification) => { setNotifications((prev) => [...prev, notification as ServerNotification]); }, @@ -302,13 +350,42 @@ const App = () => { }, [transportType]); useEffect(() => { - localStorage.setItem("lastBearerToken", bearerToken); + localStorage.setItem("lastConnectionType", connectionType); + }, [connectionType]); + + useEffect(() => { + if (bearerToken) { + localStorage.setItem("lastBearerToken", bearerToken); + } else { + localStorage.removeItem("lastBearerToken"); + } }, [bearerToken]); useEffect(() => { - localStorage.setItem("lastHeaderName", headerName); + 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]); @@ -702,12 +779,18 @@ const App = () => { lastToolCallOriginTabRef.current = currentTabRef.current; try { + // Find the tool schema to clean parameters properly + const tool = tools.find((t) => t.name === name); + const cleanedParams = tool?.inputSchema + ? cleanParams(params, tool.inputSchema as JsonSchemaType) + : params; + const response = await sendMCPRequest( { method: "tools/call" as const, params: { name, - arguments: params, + arguments: cleanedParams, _meta: { progressToken: progressTokenRef.current++, }, @@ -718,6 +801,8 @@ const App = () => { ); setToolResult(response); + // Clear any validation errors since tool execution completed + setErrors((prev) => ({ ...prev, tools: null })); } catch (e) { const toolResult: CompatibilityCallToolResult = { content: [ @@ -729,6 +814,8 @@ const App = () => { isError: true, }; setToolResult(toolResult); + // Clear validation errors - tool execution errors are shown in ToolResults + setErrors((prev) => ({ ...prev, tools: null })); } }; @@ -736,6 +823,10 @@ const App = () => { await sendNotification({ method: "notifications/roots/list_changed" }); }; + const handleClearNotifications = () => { + setNotifications([]); + }; + const sendLogLevelRequest = async (level: LoggingLevel) => { await sendMCPRequest( { @@ -805,10 +896,8 @@ const App = () => { setEnv={setEnv} config={config} setConfig={setConfig} - bearerToken={bearerToken} - setBearerToken={setBearerToken} - headerName={headerName} - setHeaderName={setHeaderName} + customHeaders={customHeaders} + setCustomHeaders={setCustomHeaders} oauthClientId={oauthClientId} setOauthClientId={setOauthClientId} oauthScope={oauthScope} @@ -818,6 +907,8 @@ const App = () => { logLevel={logLevel} sendLogLevelRequest={sendLogLevelRequest} loggingSupported={!!serverCapabilities?.logging || false} + connectionType={connectionType} + setConnectionType={setConnectionType} />
{
diff --git a/client/src/__tests__/App.config.test.tsx b/client/src/__tests__/App.config.test.tsx index b2e03d36..7458c205 100644 --- a/client/src/__tests__/App.config.test.tsx +++ b/client/src/__tests__/App.config.test.tsx @@ -49,6 +49,7 @@ jest.mock("../lib/hooks/useConnection", () => ({ serverCapabilities: null, mcpClient: null, requestHistory: [], + clearRequestHistory: jest.fn(), makeRequest: jest.fn(), sendNotification: jest.fn(), handleCompletion: jest.fn(), diff --git a/client/src/__tests__/App.routing.test.tsx b/client/src/__tests__/App.routing.test.tsx index dbd463f9..cc80f77d 100644 --- a/client/src/__tests__/App.routing.test.tsx +++ b/client/src/__tests__/App.routing.test.tsx @@ -42,6 +42,7 @@ const disconnectedConnectionState = { serverCapabilities: null, mcpClient: null, requestHistory: [], + clearRequestHistory: jest.fn(), makeRequest: jest.fn(), sendNotification: jest.fn(), handleCompletion: jest.fn(), diff --git a/client/src/components/AuthDebugger.tsx b/client/src/components/AuthDebugger.tsx index e7acbd80..6252c116 100644 --- a/client/src/components/AuthDebugger.tsx +++ b/client/src/components/AuthDebugger.tsx @@ -187,7 +187,7 @@ const AuthDebugger = ({ JSON.stringify(currentState), ); // Open the authorization URL automatically - window.location.href = currentState.authorizationUrl; + window.location.href = currentState.authorizationUrl.toString(); break; } } diff --git a/client/src/components/CustomHeaders.tsx b/client/src/components/CustomHeaders.tsx new file mode 100644 index 00000000..463f7333 --- /dev/null +++ b/client/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) +

+ +
+
+