diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml new file mode 100644 index 00000000..a4fd6c52 --- /dev/null +++ b/.github/workflows/claude.yml @@ -0,0 +1,64 @@ +name: Claude Code + +on: + issue_comment: + types: [created] + pull_request_review_comment: + types: [created] + issues: + types: [opened, assigned] + pull_request_review: + types: [submitted] + +jobs: + claude: + if: | + ( + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) || + (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || + (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) + ) && + ( + github.actor == 'ihrpr' || + github.actor == 'olaservo' + ) + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: read + issues: read + id-token: write + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: Run Claude Code + id: claude + uses: anthropics/claude-code-action@beta + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + + # Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4) + # model: "claude-opus-4-20250514" + + # Optional: Customize the trigger phrase (default: @claude) + # trigger_phrase: "/claude" + + # Optional: Trigger when specific user is assigned to an issue + # assignee_trigger: "claude-bot" + + # Optional: Allow Claude to run specific commands + # allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)" + + # Optional: Add custom instructions for Claude to customize its behavior for your project + # custom_instructions: | + # Follow our coding standards + # Ensure all new code has tests + # Use TypeScript for new files + + # Optional: Custom environment variables for Claude + # claude_env: | + # NODE_ENV: test diff --git a/.github/workflows/cli_tests.yml b/.github/workflows/cli_tests.yml new file mode 100644 index 00000000..8bd3bb8e --- /dev/null +++ b/.github/workflows/cli_tests.yml @@ -0,0 +1,41 @@ +name: CLI Tests + +on: + push: + paths: + - "cli/**" + pull_request: + paths: + - "cli/**" + +jobs: + test: + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./cli + steps: + - uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version-file: package.json + cache: npm + + - name: Install dependencies + run: | + cd .. + npm ci --ignore-scripts + + - name: Build CLI + run: npm run build + + - name: Explicitly pre-install test dependencies + run: npx -y @modelcontextprotocol/server-everything --help || true + + - name: Run tests + run: npm test + env: + NPM_CONFIG_YES: true + CI: true diff --git a/.gitignore b/.gitignore index 8e184de8..eeee17fe 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,8 @@ client/tsconfig.app.tsbuildinfo client/tsconfig.node.tsbuildinfo cli/build test-output +# symlinked by `npm run link:sdk`: +sdk client/playwright-report/ client/results.json client/test-results/ - diff --git a/README.md b/README.md index 6368ed04..6a671f1c 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,12 @@ If you need to disable authentication (NOT RECOMMENDED), you can set the `DANGER DANGEROUSLY_OMIT_AUTH=true npm start ``` +You can also set the token via the `MCP_PROXY_AUTH_TOKEN` environment variable when starting the server: + +```bash +MCP_PROXY_AUTH_TOKEN=$(openssl rand -hex 32) npm start +``` + #### Local-only Binding By default, both the MCP Inspector proxy server and client bind only to `localhost` to prevent network access. This ensures they are not accessible from other devices on the network. If you need to bind to all interfaces for development purposes, you can override this with the `HOST` environment variable: @@ -254,6 +260,12 @@ Development mode: ```bash npm run dev + +# To co-develop with the typescript-sdk package (assuming it's cloned in ../typescript-sdk; set MCP_SDK otherwise): +npm run dev:sdk "cd sdk && npm run examples:simple-server:w" +# then open http://localhost:3000/mcp as SHTTP in the inspector. +# To go back to the deployed SDK version: +# npm run unlink:sdk && npm i ``` > **Note for Windows users:** @@ -303,7 +315,7 @@ npx @modelcontextprotocol/inspector --cli node build/index.js --method prompts/l 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 +npx @modelcontextprotocol/inspector --cli https://my-mcp-server.example.com --transport http --method tools/list # 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 7ace0392..bf344733 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-cli", - "version": "0.16.0", + "version": "0.16.2", "description": "CLI for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", @@ -21,7 +21,7 @@ }, "devDependencies": {}, "dependencies": { - "@modelcontextprotocol/sdk": "^1.13.1", + "@modelcontextprotocol/sdk": "^1.17.0", "commander": "^13.1.0", "spawn-rx": "^5.1.2" } diff --git a/cli/scripts/cli-tests.js b/cli/scripts/cli-tests.js index 51bda553..68ce3885 100755 --- a/cli/scripts/cli-tests.js +++ b/cli/scripts/cli-tests.js @@ -12,7 +12,7 @@ const colors = { import fs from "fs"; import path from "path"; -import { execSync, spawn } from "child_process"; +import { spawn } from "child_process"; import os from "os"; import { fileURLToPath } from "url"; @@ -680,7 +680,7 @@ async function runTests() { // Test 26: HTTP transport with explicit --transport http flag await runBasicTest( "http_transport_with_explicit_flag", - "http://127.0.0.1:3001", + "http://127.0.0.1:3001/mcp", "--transport", "http", "--cli", @@ -710,6 +710,26 @@ async function runTests() { "tools/list", ); + // Test 29: HTTP transport without URL (should fail) + await runErrorTest( + "http_transport_without_url", + "--transport", + "http", + "--cli", + "--method", + "tools/list", + ); + + // Test 30: SSE transport without URL (should fail) + await runErrorTest( + "sse_transport_without_url", + "--transport", + "sse", + "--cli", + "--method", + "tools/list", + ); + // Kill HTTP server try { process.kill(-httpServer.pid); diff --git a/cli/src/cli.ts b/cli/src/cli.ts index 1f87b516..5ff1f111 100644 --- a/cli/src/cli.ts +++ b/cli/src/cli.ts @@ -50,28 +50,15 @@ function delay(ms: number): Promise { } async function runWebClient(args: Args): Promise { - const inspectorServerPath = resolve( - __dirname, - "../../", - "server", - "build", - "index.js", - ); - // Path to the client entry point const inspectorClientPath = resolve( __dirname, "../../", "client", "bin", - "client.js", + "start.js", ); - const CLIENT_PORT: string = process.env.CLIENT_PORT ?? "6274"; - const SERVER_PORT: string = process.env.SERVER_PORT ?? "6277"; - - console.log("Starting MCP inspector..."); - const abort = new AbortController(); let cancelled: boolean = false; process.on("SIGINT", () => { @@ -79,42 +66,26 @@ async function runWebClient(args: Args): Promise { abort.abort(); }); - let server: ReturnType; - let serverOk: unknown; + // Build arguments to pass to start.js + const startArgs: string[] = []; + + // Pass environment variables + for (const [key, value] of Object.entries(args.envArgs)) { + startArgs.push("-e", `${key}=${value}`); + } + + // Pass command and args (using -- to separate them) + if (args.command) { + startArgs.push("--", args.command, ...args.args); + } try { - server = spawnPromise( - "node", - [ - inspectorServerPath, - ...(args.command ? [`--env`, args.command] : []), - ...(args.args ? [`--args=${args.args.join(" ")}`] : []), - ], - { - env: { - ...process.env, - PORT: SERVER_PORT, - MCP_ENV_VARS: JSON.stringify(args.envArgs), - }, - signal: abort.signal, - echoOutput: true, - }, - ); - - // Make sure server started before starting client - serverOk = await Promise.race([server, delay(2 * 1000)]); - } catch (error) {} - - if (serverOk) { - try { - await spawnPromise("node", [inspectorClientPath], { - env: { ...process.env, PORT: CLIENT_PORT }, - signal: abort.signal, - echoOutput: true, - }); - } catch (e) { - if (!cancelled || process.env.DEBUG) throw e; - } + await spawnPromise("node", [inspectorClientPath, ...startArgs], { + signal: abort.signal, + echoOutput: true, + }); + } catch (e) { + if (!cancelled || process.env.DEBUG) throw e; } } @@ -275,7 +246,7 @@ async function main(): Promise { const args = parseArgs(); if (args.cli) { - runCli(args); + await runCli(args); } else { await runWebClient(args); } diff --git a/cli/src/client/connection.ts b/cli/src/client/connection.ts index 931f803d..dcbe8e51 100644 --- a/cli/src/client/connection.ts +++ b/cli/src/client/connection.ts @@ -18,6 +18,12 @@ export async function connect( ): 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)}`, diff --git a/cli/src/index.ts b/cli/src/index.ts index 5d5dcf8b..2b0c4f53 100644 --- a/cli/src/index.ts +++ b/cli/src/index.ts @@ -287,6 +287,8 @@ async function main(): Promise { try { const args = parseArgs(); await callMethod(args); + // Explicitly exit to ensure process terminates in CI + process.exit(0); } catch (error) { handleError(error); } diff --git a/cli/src/transport.ts b/cli/src/transport.ts index e0d67b4e..b6276356 100644 --- a/cli/src/transport.ts +++ b/cli/src/transport.ts @@ -14,24 +14,6 @@ export type TransportOptions = { url?: string; }; -function createSSETransport(options: TransportOptions): Transport { - const baseUrl = new URL(options.url ?? ""); - const sseUrl = baseUrl.pathname.endsWith("/sse") - ? baseUrl - : new URL("/sse", baseUrl); - - return new SSEClientTransport(sseUrl); -} - -function createHTTPTransport(options: TransportOptions): Transport { - const baseUrl = new URL(options.url ?? ""); - const mcpUrl = baseUrl.pathname.endsWith("/mcp") - ? baseUrl - : new URL("/mcp", baseUrl); - - return new StreamableHTTPClientTransport(mcpUrl); -} - function createStdioTransport(options: TransportOptions): Transport { let args: string[] = []; @@ -75,12 +57,18 @@ export function createTransport(options: TransportOptions): Transport { 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") { - return createSSETransport(options); + return new SSEClientTransport(url); } if (transportType === "http") { - return createHTTPTransport(options); + return new StreamableHTTPClientTransport(url); } throw new Error(`Unsupported transport type: ${transportType}`); diff --git a/client/bin/start.js b/client/bin/start.js index 70ca046e..e0496cde 100755 --- a/client/bin/start.js +++ b/client/bin/start.js @@ -40,7 +40,7 @@ async function startDevServer(serverOptions) { ...process.env, SERVER_PORT, CLIENT_PORT, - MCP_PROXY_TOKEN: sessionToken, + MCP_PROXY_AUTH_TOKEN: sessionToken, MCP_ENV_VARS: JSON.stringify(envVars), }, signal: abort.signal, @@ -91,15 +91,17 @@ async function startProdServer(serverOptions) { "node", [ inspectorServerPath, - ...(command ? [`--env`, command] : []), - ...(mcpServerArgs ? [`--args=${mcpServerArgs.join(" ")}`] : []), + ...(command ? [`--command=${command}`] : []), + ...(mcpServerArgs && mcpServerArgs.length > 0 + ? [`--args=${mcpServerArgs.join(" ")}`] + : []), ], { env: { ...process.env, SERVER_PORT, CLIENT_PORT, - MCP_PROXY_TOKEN: sessionToken, + MCP_PROXY_AUTH_TOKEN: sessionToken, MCP_ENV_VARS: JSON.stringify(envVars), }, signal: abort.signal, @@ -247,8 +249,9 @@ async function main() { : "Starting MCP inspector...", ); - // Generate session token for authentication - const sessionToken = randomBytes(32).toString("hex"); + // Use provided token from environment or generate a new one + const sessionToken = + process.env.MCP_PROXY_AUTH_TOKEN || randomBytes(32).toString("hex"); const authDisabled = !!process.env.DANGEROUSLY_OMIT_AUTH; const abort = new AbortController(); diff --git a/client/e2e/startup-state.spec.ts b/client/e2e/startup-state.spec.ts new file mode 100644 index 00000000..414ebd3e --- /dev/null +++ b/client/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/client/jest.config.cjs b/client/jest.config.cjs index 8652eda5..9b793eae 100644 --- a/client/jest.config.cjs +++ b/client/jest.config.cjs @@ -32,4 +32,5 @@ module.exports = { "/e2e/", "\\.config\\.(js|ts|cjs|mjs)$", ], + randomize: true, }; diff --git a/client/package.json b/client/package.json index 2d0cc50b..cbb7d8b6 100644 --- a/client/package.json +++ b/client/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/inspector-client", - "version": "0.16.0", + "version": "0.16.2", "description": "Client-side application for the Model Context Protocol inspector", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", @@ -25,9 +25,8 @@ "cleanup:e2e": "node e2e/global-teardown.js" }, "dependencies": { - "@modelcontextprotocol/sdk": "^1.13.1", + "@modelcontextprotocol/sdk": "^1.17.0", "@radix-ui/react-checkbox": "^1.1.4", - "ajv": "^6.12.6", "@radix-ui/react-dialog": "^1.1.3", "@radix-ui/react-icons": "^1.3.0", "@radix-ui/react-label": "^2.1.0", @@ -37,6 +36,7 @@ "@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", @@ -49,19 +49,19 @@ "serve-handler": "^6.1.6", "tailwind-merge": "^2.5.3", "tailwindcss-animate": "^1.0.7", - "zod": "^3.23.8" + "zod": "^3.25.76" }, "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.7.5", + "@types/node": "^22.17.0", "@types/prismjs": "^1.26.5", - "@types/react": "^18.3.10", + "@types/react": "^18.3.23", "@types/react-dom": "^18.3.0", "@types/serve-handler": "^6.1.4", - "@vitejs/plugin-react": "^4.3.2", + "@vitejs/plugin-react": "^4.7.0", "autoprefixer": "^10.4.20", "co": "^4.6.0", "eslint": "^9.11.1", @@ -70,11 +70,11 @@ "globals": "^15.9.0", "jest": "^29.7.0", "jest-environment-jsdom": "^29.7.0", - "postcss": "^8.4.47", + "postcss": "^8.5.6", "tailwindcss": "^3.4.13", - "ts-jest": "^29.2.6", + "ts-jest": "^29.4.0", "typescript": "^5.5.3", - "typescript-eslint": "^8.7.0", - "vite": "^6.3.0" + "typescript-eslint": "^8.38.0", + "vite": "^6.3.5" } } diff --git a/client/src/App.tsx b/client/src/App.tsx index 3ceafcae..537f80bf 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -71,6 +71,10 @@ import { initializeInspectorConfig, saveInspectorConfig, } from "./utils/configUtils"; +import ElicitationTab, { + PendingElicitationRequest, + ElicitationResponse, +} from "./components/ElicitationTab"; const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1"; @@ -80,6 +84,9 @@ const App = () => { ResourceTemplate[] >([]); const [resourceContent, setResourceContent] = useState(""); + const [resourceContentMap, setResourceContentMap] = useState< + Record + >({}); const [prompts, setPrompts] = useState([]); const [promptContent, setPromptContent] = useState(""); const [tools, setTools] = useState([]); @@ -116,6 +123,14 @@ const App = () => { return localStorage.getItem("lastHeaderName") || ""; }); + const [oauthClientId, setOauthClientId] = useState(() => { + return localStorage.getItem("lastOauthClientId") || ""; + }); + + const [oauthScope, setOauthScope] = useState(() => { + return localStorage.getItem("lastOauthScope") || ""; + }); + const [pendingSampleRequests, setPendingSampleRequests] = useState< Array< PendingRequest & { @@ -124,13 +139,19 @@ const App = () => { } > >([]); + const [pendingElicitationRequests, setPendingElicitationRequests] = useState< + Array< + PendingElicitationRequest & { + resolve: (response: ElicitationResponse) => void; + decline: (error: Error) => void; + } + > + >([]); const [isAuthDebuggerVisible, setIsAuthDebuggerVisible] = useState(false); - // Auth debugger state const [authState, setAuthState] = useState(EMPTY_DEBUGGER_STATE); - // Helper function to update specific auth state properties const updateAuthState = (updates: Partial) => { setAuthState((prev) => ({ ...prev, ...updates })); }; @@ -158,6 +179,19 @@ const App = () => { 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, @@ -184,6 +218,8 @@ const App = () => { env, bearerToken, headerName, + oauthClientId, + oauthScope, config, onNotification: (notification) => { setNotifications((prev) => [...prev, notification as ServerNotification]); @@ -200,9 +236,65 @@ const App = () => { { id: nextRequestId.current++, request, resolve, reject }, ]); }, + onElicitationRequest: (request, resolve) => { + const currentTab = lastToolCallOriginTabRef.current; + + setPendingElicitationRequests((prev) => [ + ...prev, + { + id: nextRequestId.current++, + request: { + id: nextRequestId.current, + message: request.params.message, + requestedSchema: request.params.requestedSchema, + }, + originatingTab: currentTab, + resolve, + decline: (error: Error) => { + console.error("Elicitation request rejected:", error); + }, + }, + ]); + + setActiveTab("elicitations"); + window.location.hash = "elicitations"; + }, getRoots: () => rootsRef.current, + defaultLoggingLevel: logLevel, }); + 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", + "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]); @@ -227,11 +319,18 @@ const App = () => { localStorage.setItem("lastHeaderName", headerName); }, [headerName]); + useEffect(() => { + localStorage.setItem("lastOauthClientId", oauthClientId); + }, [oauthClientId]); + + useEffect(() => { + localStorage.setItem("lastOauthScope", oauthScope); + }, [oauthScope]); + useEffect(() => { saveInspectorConfig(CONFIG_LOCAL_STORAGE_KEY, config); }, [config]); - // Auto-connect to previously saved serverURL after OAuth callback const onOAuthConnect = useCallback( (serverUrl: string) => { setSseUrl(serverUrl); @@ -241,7 +340,6 @@ const App = () => { [connectMcpServer], ); - // Update OAuth debug state during debug callback const onOAuthDebugConnect = useCallback( async ({ authorizationCode, @@ -262,7 +360,6 @@ const App = () => { } if (restoredState && authorizationCode) { - // Restore the previous auth state and continue the OAuth flow let currentState: AuthDebuggerState = { ...restoredState, authorizationCode, @@ -273,12 +370,10 @@ const App = () => { }; try { - // Create a new state machine instance to continue the flow const stateMachine = new OAuthStateMachine(sseUrl, (updates) => { currentState = { ...currentState, ...updates }; }); - // Continue stepping through the OAuth flow from where we left off while ( currentState.oauthStep !== "complete" && currentState.oauthStep !== "authorization_code" @@ -287,7 +382,6 @@ const App = () => { } if (currentState.oauthStep === "complete") { - // After the flow completes or reaches a user-input step, update the app state updateAuthState({ ...currentState, statusMessage: { @@ -310,7 +404,6 @@ const App = () => { }); } } else if (authorizationCode) { - // Fallback to the original behavior if no state was restored updateAuthState({ authorizationCode, oauthStep: "token_request", @@ -320,7 +413,6 @@ const App = () => { [sseUrl], ); - // Load OAuth tokens when sseUrl changes useEffect(() => { const loadOAuthTokens = async () => { try { @@ -374,10 +466,36 @@ const App = () => { }, [roots]); useEffect(() => { - if (!window.location.hash) { - window.location.hash = "resources"; + 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]); const handleApproveSampling = (id: number, result: CreateMessageResult) => { setPendingSampleRequests((prev) => { @@ -395,6 +513,44 @@ const App = () => { }); }; + 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 })); }; @@ -452,7 +608,23 @@ const App = () => { setNextResourceTemplateCursor(response.nextCursor); }; + const getPrompt = async (name: string, args: Record = {}) => { + lastToolCallOriginTabRef.current = currentTabRef.current; + + const response = await sendMCPRequest( + { + method: "prompts/get" as const, + params: { name, arguments: args }, + }, + GetPromptResultSchema, + "prompts", + ); + setPromptContent(JSON.stringify(response, null, 2)); + }; + const readResource = async (uri: string) => { + lastToolCallOriginTabRef.current = currentTabRef.current; + const response = await sendMCPRequest( { method: "resources/read" as const, @@ -461,7 +633,12 @@ const App = () => { ReadResourceResultSchema, "resources", ); - setResourceContent(JSON.stringify(response, null, 2)); + const content = JSON.stringify(response, null, 2); + setResourceContent(content); + setResourceContentMap((prev) => ({ + ...prev, + [uri]: content, + })); }; const subscribeToResource = async (uri: string) => { @@ -509,18 +686,6 @@ const App = () => { setNextPromptCursor(response.nextCursor); }; - const getPrompt = async (name: string, args: Record = {}) => { - const response = await sendMCPRequest( - { - method: "prompts/get" as const, - params: { name, arguments: args }, - }, - GetPromptResultSchema, - "prompts", - ); - setPromptContent(JSON.stringify(response, null, 2)); - }; - const listTools = async () => { const response = await sendMCPRequest( { @@ -532,11 +697,12 @@ const App = () => { ); setTools(response.tools); setNextToolCursor(response.nextCursor); - // Cache output schemas for validation cacheToolOutputSchemas(response.tools); }; const callTool = async (name: string, params: Record) => { + lastToolCallOriginTabRef.current = currentTabRef.current; + try { const response = await sendMCPRequest( { @@ -552,6 +718,7 @@ const App = () => { CompatibilityCallToolResultSchema, "tools", ); + setToolResult(response); } catch (e) { const toolResult: CompatibilityCallToolResult = { @@ -586,7 +753,6 @@ const App = () => { setStdErrNotifications([]); }; - // Helper component for rendering the AuthDebugger const AuthDebuggerWrapper = () => ( { ); - // Helper function to render OAuth callback components if (window.location.pathname === "/oauth/callback") { const OAuthCallback = React.lazy( () => import("./components/OAuthCallback"), @@ -650,6 +815,10 @@ const App = () => { setBearerToken={setBearerToken} headerName={headerName} setHeaderName={setHeaderName} + oauthClientId={oauthClientId} + setOauthClientId={setOauthClientId} + oauthScope={oauthScope} + setOauthScope={setOauthScope} onConnect={connectMcpServer} onDisconnect={disconnectMcpServer} stdErrNotifications={stdErrNotifications} @@ -658,7 +827,6 @@ const App = () => { loggingSupported={!!serverCapabilities?.logging || false} clearStdErrNotifications={clearStdErrNotifications} /> - {/* Drag handle for resizing sidebar */}
{
{mcpClient ? ( (window.location.hash = value)} + onValueChange={(value) => { + setActiveTab(value); + window.location.hash = value; + }} > { )} + + + Elicitations + {pendingElicitationRequests.length > 0 && ( + + {pendingElicitationRequests.length} + + )} + Roots @@ -846,7 +1014,6 @@ const App = () => { clearTools={() => { setTools([]); setNextToolCursor(undefined); - // Clear cached output schemas cacheToolOutputSchemas([]); }} callTool={async (name, params) => { @@ -863,6 +1030,11 @@ const App = () => { toolResult={toolResult} nextCursor={nextToolCursor} error={errors.tools} + resourceContent={resourceContentMap} + onReadResource={(uri: string) => { + clearError("resources"); + readResource(uri); + }} /> { onApprove={handleApproveSampling} onReject={handleRejectSampling} /> + ({ + auth: jest.fn(), +})); + +jest.mock("../lib/oauth-state-machine", () => ({ + OAuthStateMachine: jest.fn(), +})); + +jest.mock("../lib/auth", () => ({ + InspectorOAuthClientProvider: jest.fn().mockImplementation(() => ({ + tokens: jest.fn().mockResolvedValue(null), + clear: jest.fn(), + })), + DebugInspectorOAuthClientProvider: jest.fn(), +})); + +// Mock the config utils +jest.mock("../utils/configUtils", () => ({ + ...jest.requireActual("../utils/configUtils"), + getMCPProxyAddress: jest.fn(() => "http://localhost:6277"), + getMCPProxyAuthToken: jest.fn(() => ({ + token: "", + header: "X-MCP-Proxy-Auth", + })), + getInitialTransportType: jest.fn(() => "stdio"), + getInitialSseUrl: jest.fn(() => "http://localhost:3001/sse"), + getInitialCommand: jest.fn(() => "mcp-server-everything"), + getInitialArgs: jest.fn(() => ""), + initializeInspectorConfig: jest.fn(() => ({})), + saveInspectorConfig: jest.fn(), +})); + +// Default connection state is disconnected +const disconnectedConnectionState = { + connectionStatus: "disconnected" as const, + serverCapabilities: null, + mcpClient: null, + requestHistory: [], + makeRequest: jest.fn(), + sendNotification: jest.fn(), + handleCompletion: jest.fn(), + completionsSupported: false, + connect: jest.fn(), + disconnect: jest.fn(), +}; + +// Connected state for tests that need an active connection +const connectedConnectionState = { + ...disconnectedConnectionState, + connectionStatus: "connected" as const, + serverCapabilities: {}, + mcpClient: { + request: jest.fn(), + notification: jest.fn(), + close: jest.fn(), + } as unknown as Client, +}; + +// 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({}) }); + +// Use an empty module mock, so that mock state can be reset between tests. +jest.mock("../lib/hooks/useConnection", () => ({ + useConnection: jest.fn(), +})); + +describe("App - URL Fragment Routing", () => { + const mockUseConnection = jest.mocked(useConnection); + + beforeEach(() => { + jest.restoreAllMocks(); + + // Inspector starts disconnected. + mockUseConnection.mockReturnValue(disconnectedConnectionState); + }); + + 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 = ""; + mockUseConnection.mockReturnValue({ + ...connectedConnectionState, + serverCapabilities: 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/client/src/components/DynamicJsonForm.tsx b/client/src/components/DynamicJsonForm.tsx index efa4d2ad..7f7d472d 100644 --- a/client/src/components/DynamicJsonForm.tsx +++ b/client/src/components/DynamicJsonForm.tsx @@ -28,10 +28,10 @@ export interface DynamicJsonFormRef { const isSimpleObject = (schema: JsonSchemaType): boolean => { const supportedTypes = ["string", "number", "integer", "boolean", "null"]; - if (supportedTypes.includes(schema.type)) return true; + if (schema.type && supportedTypes.includes(schema.type)) return true; if (schema.type === "object") { - return Object.values(schema.properties ?? {}).every((prop) => - supportedTypes.includes(prop.type), + return Object.values(schema.properties ?? {}).every( + (prop) => prop.type && supportedTypes.includes(prop.type), ); } if (schema.type === "array") { @@ -236,10 +236,89 @@ const DynamicJsonForm = forwardRef( parentSchema?.required?.includes(propertyName || "") ?? false; switch (propSchema.type) { - case "string": + case "string": { + if ( + propSchema.oneOf && + propSchema.oneOf.every( + (option) => + typeof option.const === "string" && + typeof option.title === "string", + ) + ) { + return ( + + ); + } + + if (propSchema.enum) { + return ( + + ); + } + + let inputType = "text"; + switch (propSchema.format) { + case "email": + inputType = "email"; + break; + case "uri": + inputType = "url"; + break; + case "date": + inputType = "date"; + break; + case "date-time": + inputType = "datetime-local"; + break; + default: + inputType = "text"; + break; + } + return ( { const val = e.target.value; @@ -248,8 +327,13 @@ const DynamicJsonForm = forwardRef( }} placeholder={propSchema.description} required={isRequired} + minLength={propSchema.minLength} + maxLength={propSchema.maxLength} + pattern={propSchema.pattern} /> ); + } + case "number": return ( ( }} placeholder={propSchema.description} required={isRequired} + min={propSchema.minimum} + max={propSchema.maximum} /> ); + case "integer": return ( ( handleFieldChange(path, undefined); } else { const num = Number(val); - // Only update if it's a valid integer if (!isNaN(num) && Number.isInteger(num)) { handleFieldChange(path, num); } @@ -290,8 +376,11 @@ const DynamicJsonForm = forwardRef( }} placeholder={propSchema.description} required={isRequired} + min={propSchema.minimum} + max={propSchema.maximum} /> ); + case "boolean": return ( void; +}; + +const ElicitationRequest = ({ + request, + onResolve, +}: ElicitationRequestProps) => { + const [formData, setFormData] = useState({}); + const [validationError, setValidationError] = useState(null); + + useEffect(() => { + const defaultValue = generateDefaultValue(request.request.requestedSchema); + setFormData(defaultValue); + setValidationError(null); + }, [request.request.requestedSchema]); + + const validateEmailFormat = (email: string): boolean => { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(email); + }; + + const validateFormData = ( + data: JsonValue, + schema: JsonSchemaType, + ): boolean => { + if ( + schema.type === "object" && + schema.properties && + typeof data === "object" && + data !== null + ) { + const dataObj = data as Record; + + if (Array.isArray(schema.required)) { + for (const field of schema.required) { + const value = dataObj[field]; + if (value === undefined || value === null || value === "") { + setValidationError(`Required field missing: ${field}`); + return false; + } + } + } + + for (const [fieldName, fieldValue] of Object.entries(dataObj)) { + const fieldSchema = schema.properties[fieldName]; + if ( + fieldSchema && + fieldSchema.format === "email" && + typeof fieldValue === "string" + ) { + if (!validateEmailFormat(fieldValue)) { + setValidationError(`Invalid email format: ${fieldName}`); + return false; + } + } + } + } + + return true; + }; + + const handleAccept = () => { + try { + if (!validateFormData(formData, request.request.requestedSchema)) { + return; + } + + const ajv = new Ajv(); + const validate = ajv.compile(request.request.requestedSchema); + const isValid = validate(formData); + + if (!isValid) { + const errorMessage = ajv.errorsText(validate.errors); + setValidationError(errorMessage); + return; + } + + onResolve(request.id, { + action: "accept", + content: formData as Record, + }); + } catch (error) { + setValidationError( + error instanceof Error ? error.message : "Validation failed", + ); + } + }; + + const handleDecline = () => { + onResolve(request.id, { action: "decline" }); + }; + + const handleCancel = () => { + onResolve(request.id, { action: "cancel" }); + }; + + const schemaTitle = + request.request.requestedSchema.title || "Information Request"; + const schemaDescription = request.request.requestedSchema.description; + + return ( +
+
+
+

{schemaTitle}

+

{request.request.message}

+ {schemaDescription && ( +

{schemaDescription}

+ )} +
+
Request Schema:
+ +
+
+
+ +
+
+

Response Form

+ { + setFormData(newValue); + setValidationError(null); + }} + /> + + {validationError && ( +
+
+ Validation Error: {validationError} +
+
+ )} +
+ +
+ + + +
+
+
+ ); +}; + +export default ElicitationRequest; diff --git a/client/src/components/ElicitationTab.tsx b/client/src/components/ElicitationTab.tsx new file mode 100644 index 00000000..cf3be2b5 --- /dev/null +++ b/client/src/components/ElicitationTab.tsx @@ -0,0 +1,56 @@ +import { Alert, AlertDescription } from "@/components/ui/alert"; +import { TabsContent } from "@/components/ui/tabs"; +import { JsonSchemaType } from "@/utils/jsonUtils"; +import ElicitationRequest from "./ElicitationRequest"; + +export interface ElicitationRequestData { + id: number; + message: string; + requestedSchema: JsonSchemaType; +} + +export interface ElicitationResponse { + action: "accept" | "decline" | "cancel"; + content?: Record; +} + +export type PendingElicitationRequest = { + id: number; + request: ElicitationRequestData; + originatingTab?: string; +}; + +export type Props = { + pendingRequests: PendingElicitationRequest[]; + onResolve: (id: number, response: ElicitationResponse) => void; +}; + +const ElicitationTab = ({ pendingRequests, onResolve }: Props) => { + return ( + +
+ + + When the server requests information from the user, requests will + appear here for response. + + +
+

Recent Requests

+ {pendingRequests.map((request) => ( + + ))} + {pendingRequests.length === 0 && ( +

No pending requests

+ )} +
+
+
+ ); +}; + +export default ElicitationTab; diff --git a/client/src/components/PromptsTab.tsx b/client/src/components/PromptsTab.tsx index 466b3d52..fa590558 100644 --- a/client/src/components/PromptsTab.tsx +++ b/client/src/components/PromptsTab.tsx @@ -48,6 +48,7 @@ const PromptsTab = ({ ref: PromptReference | ResourceReference, argName: string, value: string, + context?: Record, ) => Promise; completionsSupported: boolean; promptContent: string; @@ -73,6 +74,7 @@ const PromptsTab = ({ }, argName, value, + promptArgs, ); } }; diff --git a/client/src/components/ResourceLinkView.tsx b/client/src/components/ResourceLinkView.tsx new file mode 100644 index 00000000..9a42747b --- /dev/null +++ b/client/src/components/ResourceLinkView.tsx @@ -0,0 +1,112 @@ +import { useState, useCallback, useMemo, memo } from "react"; +import JsonView from "./JsonView"; + +interface ResourceLinkViewProps { + uri: string; + name?: string; + description?: string; + mimeType?: string; + resourceContent: string; + onReadResource?: (uri: string) => void; +} + +const ResourceLinkView = memo( + ({ + uri, + name, + description, + mimeType, + resourceContent, + onReadResource, + }: ResourceLinkViewProps) => { + const [{ expanded, loading }, setState] = useState({ + expanded: false, + loading: false, + }); + + const expandedContent = useMemo( + () => + expanded && resourceContent ? ( +
+
+ Resource: +
+ +
+ ) : null, + [expanded, resourceContent], + ); + + const handleClick = useCallback(() => { + if (!onReadResource) return; + if (!expanded) { + setState((prev) => ({ ...prev, expanded: true, loading: true })); + onReadResource(uri); + setState((prev) => ({ ...prev, loading: false })); + } else { + setState((prev) => ({ ...prev, expanded: false })); + } + }, [expanded, onReadResource, uri]); + + const handleKeyDown = useCallback( + (e: React.KeyboardEvent) => { + if ((e.key === "Enter" || e.key === " ") && onReadResource) { + e.preventDefault(); + handleClick(); + } + }, + [handleClick, onReadResource], + ); + + return ( +
+
+
+
+ + {uri} + +
+ {mimeType && ( + + {mimeType} + + )} + {onReadResource && ( +
+ {name && ( +
+ {name} +
+ )} + {description && ( +

+ {description} +

+ )} +
+
+ {expandedContent} +
+ ); + }, +); + +export default ResourceLinkView; diff --git a/client/src/components/ResourcesTab.tsx b/client/src/components/ResourcesTab.tsx index 8ec3f91b..874e0ff7 100644 --- a/client/src/components/ResourcesTab.tsx +++ b/client/src/components/ResourcesTab.tsx @@ -52,6 +52,7 @@ const ResourcesTab = ({ ref: ResourceReference | PromptReference, argName: string, value: string, + context?: Record, ) => Promise; completionsSupported: boolean; resourceContent: string; @@ -94,6 +95,7 @@ const ResourcesTab = ({ }, key, value, + templateValues, ); } }; diff --git a/client/src/components/Sidebar.tsx b/client/src/components/Sidebar.tsx index 938e5b5a..a41e4bfc 100644 --- a/client/src/components/Sidebar.tsx +++ b/client/src/components/Sidebar.tsx @@ -56,6 +56,10 @@ interface SidebarProps { setBearerToken: (token: string) => void; headerName?: string; setHeaderName?: (name: string) => void; + oauthClientId: string; + setOauthClientId: (id: string) => void; + oauthScope: string; + setOauthScope: (scope: string) => void; onConnect: () => void; onDisconnect: () => void; stdErrNotifications: StdErrNotification[]; @@ -83,6 +87,10 @@ const Sidebar = ({ setBearerToken, headerName, setHeaderName, + oauthClientId, + setOauthClientId, + oauthScope, + setOauthScope, onConnect, onDisconnect, stdErrNotifications, @@ -95,7 +103,7 @@ const Sidebar = ({ }: SidebarProps) => { const [theme, setTheme] = useTheme(); const [showEnvVars, setShowEnvVars] = useState(false); - const [showBearerToken, setShowBearerToken] = useState(false); + const [showAuthConfig, setShowAuthConfig] = useState(false); const [showConfig, setShowConfig] = useState(false); const [shownEnvVars, setShownEnvVars] = useState>(new Set()); const [copiedServerEntry, setCopiedServerEntry] = useState(false); @@ -308,51 +316,6 @@ const Sidebar = ({ /> )}
-
- - {showBearerToken && ( -
- - - setHeaderName && setHeaderName(e.target.value) - } - data-testid="header-input" - className="font-mono" - value={headerName} - /> - - setBearerToken(e.target.value)} - data-testid="bearer-token-input" - className="font-mono" - type="password" - /> -
- )} -
)} @@ -521,6 +484,94 @@ const Sidebar = ({
+
+ + {showAuthConfig && ( + <> + {/* Bearer Token Section */} +
+

+ API Token Authentication +

+
+ + + setHeaderName && setHeaderName(e.target.value) + } + data-testid="header-input" + className="font-mono" + value={headerName} + /> + + setBearerToken(e.target.value)} + data-testid="bearer-token-input" + className="font-mono" + type="password" + /> +
+
+ {transportType !== "stdio" && ( + // OAuth Configuration +
+

+ OAuth 2.0 Flow +

+
+ + setOauthClientId(e.target.value)} + value={oauthClientId} + data-testid="oauth-client-id-input" + className="font-mono" + /> + + + + setOauthScope(e.target.value)} + value={oauthScope} + data-testid="oauth-scope-input" + className="font-mono" + /> +
+
+ )} + + )} +
{/* Configuration */}
)} + {structuredResult._meta && ( +
+
Meta:
+
+ +
+
+ )} {!structuredResult.structuredContent && validationResult && !validationResult.isValid && ( @@ -200,6 +216,16 @@ const ToolResults = ({ toolResult, selectedTool }: ToolResultsProps) => { ) : ( ))} + {item.type === "resource_link" && ( + + )} ))} diff --git a/client/src/components/ToolsTab.tsx b/client/src/components/ToolsTab.tsx index 7258eaa8..07f329a5 100644 --- a/client/src/components/ToolsTab.tsx +++ b/client/src/components/ToolsTab.tsx @@ -25,6 +25,10 @@ import ListPane from "./ListPane"; import JsonView from "./JsonView"; import ToolResults from "./ToolResults"; +// Type guard to safely detect the optional _meta field without using `any` +const hasMeta = (tool: Tool): tool is Tool & { _meta: unknown } => + typeof (tool as { _meta?: unknown })._meta !== "undefined"; + const ToolsTab = ({ tools, listTools, @@ -35,6 +39,8 @@ const ToolsTab = ({ toolResult, nextCursor, error, + resourceContent, + onReadResource, }: { tools: Tool[]; listTools: () => void; @@ -45,10 +51,13 @@ const ToolsTab = ({ toolResult: CompatibilityCallToolResult | null; nextCursor: ListToolsResult["nextCursor"]; error: string | null; + resourceContent: Record; + onReadResource?: (uri: string) => void; }) => { const [params, setParams] = useState>({}); const [isToolRunning, setIsToolRunning] = useState(false); const [isOutputSchemaExpanded, setIsOutputSchemaExpanded] = useState(false); + const [isMetaExpanded, setIsMetaExpanded] = useState(false); const formRefs = useRef>({}); useEffect(() => { @@ -257,6 +266,40 @@ const ToolsTab = ({ )} + {selectedTool && + hasMeta(selectedTool) && + selectedTool._meta && ( +
+
+

Meta:

+ +
+
+ +
+
+ )}