Compare commits

...

24 Commits

Author SHA1 Message Date
Cliff Hall
3032a67d4e Merge pull request #261 from cliffhall/bump-to-version-0.8.1
Bump to version 0.8.1 - package-lock.json
2025-04-03 18:07:31 -04:00
Cliff Hall
f0651baf4a Merge branch 'modelcontextprotocol:main' into bump-to-version-0.8.1 2025-04-03 16:33:52 -04:00
cliffhall
3f73ec83a2 Bump version to 0.8.1
* package-lock.json
2025-04-03 16:32:59 -04:00
Cliff Hall
bdab26dbeb Merge pull request #260 from cliffhall/bump-to-version-0.8.1
Bump version to 0.8.1
2025-04-03 15:36:00 -04:00
Cliff Hall
0f075af42c Merge branch 'main' into bump-to-version-0.8.1 2025-04-03 14:48:47 -04:00
Cliff Hall
06fcc74638 Merge pull request #247 from max-stytch/fix/use-https-protocol
fix: Use same protocol for proxy server URL
2025-04-03 14:48:02 -04:00
cliffhall
9092c780f7 Bump version to 0.8.1
* In client/package.json
  - version bumped to 0.8.1
  - typescript SDK version 0.8.0 (latest)
* In server/package.json
  - version bumped to 0.8.1
  - typescript SDK version 0.8.0 (latest)
* In client/package.json
  - version bumped to 0.8.1
  - inspector-client bumped to 0.8.1
  - inspector-server bumped to 0.8.1
2025-04-03 14:30:59 -04:00
Cliff Hall
a75dd7ba1f Merge pull request #253 from max-stytch/max/fix-reloads
fix: Do not reconnect on rerender
2025-04-03 13:38:11 -04:00
Maxwell Gerber
a414033354 fix: Use same protocol for proxy server URL 2025-04-03 09:18:11 -07:00
Cliff Hall
ce1a9d3905 Merge pull request #243 from pulkitsharma07/add_proxy_config
Add MCP proxy address config support, better error messages, redesigned Config panel
2025-04-02 18:40:57 -04:00
Maxwell Gerber
0bd51fa84a fix: Do not reconnect on rerender 2025-04-02 15:18:33 -07:00
Pulkit Sharma
2a544294ba merge main 2025-04-03 00:47:21 +05:30
Cliff Hall
897e637db4 Merge pull request #244 from NicolasMontone/feat/new-alert-and-copy-button
feat: add new toast and add copy button to JSON.
2025-04-02 13:04:54 -04:00
NicolasMontone
5db5fc26c7 fix prettier 2025-04-02 10:42:52 -03:00
NicolasMontone
8b31f495ba fix unkown type. 2025-04-02 10:41:33 -03:00
NicolasMontone
c964ff5cfe Use copy button insde JSON view component 2025-04-02 10:39:39 -03:00
Pulkit Sharma
e69bfc58bc prettier-fix 2025-04-02 13:45:09 +05:30
Pulkit Sharma
debb00344a Merge branch 'main' into add_proxy_config 2025-04-02 13:43:42 +05:30
NicolasMontone
c9ee22b781 fix(Select): add missing style. 2025-04-01 19:23:57 -03:00
NicolasMontone
cc70fbd0f5 add ring color 2025-04-01 19:14:32 -03:00
NicolasMontone
8586d63e6d Add shadcn alert to match project design 2025-04-01 17:38:25 -03:00
NicolasMontone
539de0fd85 add copy button 2025-04-01 17:18:40 -03:00
Pulkit Sharma
0dcd10c1dd Update readme 2025-04-01 19:48:48 +05:30
Pulkit Sharma
51c7eda6a6 Add MCP proxy address config support, better error messages 2025-04-01 19:21:19 +05:30
26 changed files with 1211 additions and 2764 deletions

View File

@@ -53,6 +53,7 @@ The MCP Inspector supports the following configuration settings. To change them
| Name | Purpose | Default Value |
| -------------------------- | ----------------------------------------------------------------------------------------- | ------------- |
| MCP_SERVER_REQUEST_TIMEOUT | Maximum time in milliseconds to wait for a response from the MCP server before timing out | 10000 |
| MCP_PROXY_FULL_ADDRESS | The full URL of the MCP Inspector proxy server (e.g. `http://10.2.1.14:2277`) | `null` |
### From this repository

View File

@@ -1,6 +1,6 @@
{
"name": "@modelcontextprotocol/inspector-client",
"version": "0.8.0",
"version": "0.8.1",
"description": "Client-side application for the Model Context Protocol inspector",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
@@ -23,7 +23,7 @@
"test:watch": "jest --config jest.config.cjs --watch"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.6.1",
"@modelcontextprotocol/sdk": "^1.8.0",
"@radix-ui/react-checkbox": "^1.1.4",
"@radix-ui/react-dialog": "^1.1.3",
"@radix-ui/react-icons": "^1.3.0",
@@ -32,6 +32,8 @@
"@radix-ui/react-select": "^2.1.2",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.1",
"@radix-ui/react-tooltip": "^1.1.8",
"@radix-ui/react-toast": "^1.2.6",
"@types/prismjs": "^1.26.5",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
@@ -42,7 +44,6 @@
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-simple-code-editor": "^0.14.1",
"react-toastify": "^10.0.6",
"serve-handler": "^6.1.6",
"tailwind-merge": "^2.5.3",
"tailwindcss-animate": "^1.0.7",

View File

@@ -20,7 +20,6 @@ import {
import React, { Suspense, useEffect, useRef, useState } from "react";
import { useConnection } from "./lib/hooks/useConnection";
import { useDraggablePane } from "./lib/hooks/useDraggablePane";
import { StdErrNotification } from "./lib/notificationTypes";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
@@ -33,7 +32,6 @@ import {
MessageSquare,
} from "lucide-react";
import { toast } from "react-toastify";
import { z } from "zod";
import "./App.css";
import ConsoleTab from "./components/ConsoleTab";
@@ -47,13 +45,17 @@ import Sidebar from "./components/Sidebar";
import ToolsTab from "./components/ToolsTab";
import { DEFAULT_INSPECTOR_CONFIG } from "./lib/constants";
import { InspectorConfig } from "./lib/configurationTypes";
import {
getMCPProxyAddress,
getMCPServerRequestTimeout,
} from "./utils/configUtils";
import { useToast } from "@/hooks/use-toast";
const params = new URLSearchParams(window.location.search);
const PROXY_PORT = params.get("proxyPort") ?? "6277";
const PROXY_SERVER_URL = `http://${window.location.hostname}:${PROXY_PORT}`;
const CONFIG_LOCAL_STORAGE_KEY = "inspectorConfig_v1";
const App = () => {
const { toast } = useToast();
// Handle OAuth callback route
const [resources, setResources] = useState<Resource[]>([]);
const [resourceTemplates, setResourceTemplates] = useState<
@@ -95,7 +97,13 @@ const App = () => {
const [config, setConfig] = useState<InspectorConfig>(() => {
const savedConfig = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);
return savedConfig ? JSON.parse(savedConfig) : DEFAULT_INSPECTOR_CONFIG;
if (savedConfig) {
return {
...DEFAULT_INSPECTOR_CONFIG,
...JSON.parse(savedConfig),
} as InspectorConfig;
}
return DEFAULT_INSPECTOR_CONFIG;
});
const [bearerToken, setBearerToken] = useState<string>(() => {
return localStorage.getItem("lastBearerToken") || "";
@@ -153,8 +161,8 @@ const App = () => {
sseUrl,
env,
bearerToken,
proxyServerUrl: PROXY_SERVER_URL,
requestTimeout: config.MCP_SERVER_REQUEST_TIMEOUT.value as number,
proxyServerUrl: getMCPProxyAddress(config),
requestTimeout: getMCPServerRequestTimeout(config),
onNotification: (notification) => {
setNotifications((prev) => [...prev, notification as ServerNotification]);
},
@@ -197,8 +205,13 @@ const App = () => {
localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));
}, [config]);
const hasProcessedRef = useRef(false);
// Auto-connect if serverUrl is provided in URL params (e.g. after OAuth callback)
useEffect(() => {
if (hasProcessedRef.current) {
// Only try to connect once
return;
}
const serverUrl = params.get("serverUrl");
if (serverUrl) {
setSseUrl(serverUrl);
@@ -208,14 +221,18 @@ const App = () => {
newUrl.searchParams.delete("serverUrl");
window.history.replaceState({}, "", newUrl.toString());
// Show success toast for OAuth
toast.success("Successfully authenticated with OAuth");
toast({
title: "Success",
description: "Successfully authenticated with OAuth",
});
hasProcessedRef.current = true;
// Connect to the server
connectMcpServer();
}
}, [connectMcpServer]);
}, [connectMcpServer, toast]);
useEffect(() => {
fetch(`${PROXY_SERVER_URL}/config`)
fetch(`${getMCPProxyAddress(config)}/config`)
.then((response) => response.json())
.then((data) => {
setEnv(data.defaultEnvironment);
@@ -229,6 +246,7 @@ const App = () => {
.catch((error) =>
console.error("Error fetching default environment:", error),
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {

View File

@@ -1,5 +1,4 @@
import { ServerNotification } from "@modelcontextprotocol/sdk/types.js";
import { Copy } from "lucide-react";
import { useState } from "react";
import JsonView from "./JsonView";
@@ -25,10 +24,6 @@ const HistoryAndNotifications = ({
setExpandedNotifications((prev) => ({ ...prev, [index]: !prev[index] }));
};
const copyToClipboard = (text: string) => {
navigator.clipboard.writeText(text);
};
return (
<div className="bg-card overflow-hidden flex h-full">
<div className="flex-1 overflow-y-auto p-4 border-r">
@@ -68,16 +63,12 @@ const HistoryAndNotifications = ({
<span className="font-semibold text-blue-600">
Request:
</span>
<button
onClick={() => copyToClipboard(request.request)}
className="text-blue-500 hover:text-blue-700"
>
<Copy size={16} />
</button>
</div>
<div className="bg-background p-2 rounded">
<JsonView data={request.request} />
</div>
<JsonView
data={request.request}
className="bg-background"
/>
</div>
{request.response && (
<div className="mt-2">
@@ -85,16 +76,11 @@ const HistoryAndNotifications = ({
<span className="font-semibold text-green-600">
Response:
</span>
<button
onClick={() => copyToClipboard(request.response!)}
className="text-blue-500 hover:text-blue-700"
>
<Copy size={16} />
</button>
</div>
<div className="bg-background p-2 rounded">
<JsonView data={request.response} />
</div>
<JsonView
data={request.response}
className="bg-background"
/>
</div>
)}
</>
@@ -134,20 +120,11 @@ const HistoryAndNotifications = ({
<span className="font-semibold text-purple-600">
Details:
</span>
<button
onClick={() =>
copyToClipboard(JSON.stringify(notification))
}
className="text-blue-500 hover:text-blue-700"
>
<Copy size={16} />
</button>
</div>
<div className="bg-background p-2 rounded">
<JsonView
data={JSON.stringify(notification, null, 2)}
/>
</div>
<JsonView
data={JSON.stringify(notification, null, 2)}
className="bg-background"
/>
</div>
)}
</li>

View File

@@ -1,11 +1,16 @@
import { useState, memo } from "react";
import { useState, memo, useMemo, useCallback, useEffect } from "react";
import { JsonValue } from "./DynamicJsonForm";
import clsx from "clsx";
import { Copy, CheckCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useToast } from "@/hooks/use-toast";
interface JsonViewProps {
data: unknown;
name?: string;
initialExpandDepth?: number;
className?: string;
withCopyButton?: boolean;
}
function tryParseJson(str: string): { success: boolean; data: JsonValue } {
@@ -24,22 +29,79 @@ function tryParseJson(str: string): { success: boolean; data: JsonValue } {
}
const JsonView = memo(
({ data, name, initialExpandDepth = 3 }: JsonViewProps) => {
const normalizedData =
typeof data === "string"
({
data,
name,
initialExpandDepth = 3,
className,
withCopyButton = true,
}: JsonViewProps) => {
const { toast } = useToast();
const [copied, setCopied] = useState(false);
useEffect(() => {
let timeoutId: NodeJS.Timeout;
if (copied) {
timeoutId = setTimeout(() => {
setCopied(false);
}, 500);
}
return () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
};
}, [copied]);
const normalizedData = useMemo(() => {
return typeof data === "string"
? tryParseJson(data).success
? tryParseJson(data).data
: data
: data;
}, [data]);
const handleCopy = useCallback(() => {
try {
navigator.clipboard.writeText(
typeof normalizedData === "string"
? normalizedData
: JSON.stringify(normalizedData, null, 2),
);
setCopied(true);
} catch (error) {
toast({
title: "Error",
description: `There was an error coping result into the clipboard: ${error instanceof Error ? error.message : String(error)}`,
variant: "destructive",
});
}
}, [toast, normalizedData]);
return (
<div className="font-mono text-sm transition-all duration-300 ">
<JsonNode
data={normalizedData as JsonValue}
name={name}
depth={0}
initialExpandDepth={initialExpandDepth}
/>
<div className={clsx("p-4 border rounded relative", className)}>
{withCopyButton && (
<Button
size="icon"
variant="ghost"
className="absolute top-2 right-2"
onClick={handleCopy}
>
{copied ? (
<CheckCheck className="size-4 dark:text-green-700 text-green-600" />
) : (
<Copy className="size-4 text-foreground" />
)}
</Button>
)}
<div className="font-mono text-sm transition-all duration-300">
<JsonNode
data={normalizedData as JsonValue}
name={name}
depth={0}
initialExpandDepth={initialExpandDepth}
/>
</div>
</div>
);
},

View File

@@ -152,9 +152,7 @@ const PromptsTab = ({
Get Prompt
</Button>
{promptContent && (
<div className="p-4 border rounded">
<JsonView data={promptContent} />
</div>
<JsonView data={promptContent} withCopyButton={false} />
)}
</div>
) : (

View File

@@ -215,9 +215,10 @@ const ResourcesTab = ({
<AlertDescription>{error}</AlertDescription>
</Alert>
) : selectedResource ? (
<div className="bg-gray-50 dark:bg-gray-800 p-4 rounded text-sm overflow-auto max-h-96 text-gray-900 dark:text-gray-100">
<JsonView data={resourceContent} />
</div>
<JsonView
data={resourceContent}
className="bg-gray-50 dark:bg-gray-800 p-4 rounded text-sm overflow-auto max-h-96 text-gray-900 dark:text-gray-100"
/>
) : selectedTemplate ? (
<div className="space-y-4">
<p className="text-sm text-gray-600">

View File

@@ -44,9 +44,11 @@ const SamplingTab = ({ pendingRequests, onApprove, onReject }: Props) => {
<h3 className="text-lg font-semibold">Recent Requests</h3>
{pendingRequests.map((request) => (
<div key={request.id} className="p-4 border rounded-lg space-y-4">
<div className="bg-gray-50 dark:bg-gray-800 dark:text-gray-100 p-2 rounded">
<JsonView data={JSON.stringify(request.request)} />
</div>
<JsonView
className="bg-gray-50 dark:bg-gray-800 dark:text-gray-100 rounded"
data={JSON.stringify(request.request)}
/>
<div className="flex space-x-2">
<Button onClick={() => handleApprove(request.id)}>Approve</Button>
<Button variant="outline" onClick={() => onReject(request.id)}>

View File

@@ -10,6 +10,7 @@ import {
EyeOff,
RotateCcw,
Settings,
HelpCircle,
RefreshCwOff,
} from "lucide-react";
import { Button } from "@/components/ui/button";
@@ -27,12 +28,17 @@ import {
LoggingLevelSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { InspectorConfig } from "@/lib/configurationTypes";
import { ConnectionStatus } from "@/lib/constants";
import useTheme from "../lib/useTheme";
import { version } from "../../../package.json";
import {
Tooltip,
TooltipTrigger,
TooltipContent,
} from "@/components/ui/tooltip";
interface SidebarProps {
connectionStatus: "disconnected" | "connected" | "error";
connectionStatus: ConnectionStatus;
transportType: "stdio" | "sse";
setTransportType: (type: "stdio" | "sse") => void;
command: string;
@@ -180,6 +186,7 @@ const Sidebar = ({
variant="outline"
onClick={() => setShowEnvVars(!showEnvVars)}
className="flex items-center w-full"
data-testid="env-vars-button"
>
{showEnvVars ? (
<ChevronDown className="w-4 h-4 mr-2" />
@@ -301,6 +308,7 @@ const Sidebar = ({
variant="outline"
onClick={() => setShowConfig(!showConfig)}
className="flex items-center w-full"
data-testid="config-button"
>
{showConfig ? (
<ChevronDown className="w-4 h-4 mr-2" />
@@ -316,9 +324,19 @@ const Sidebar = ({
const configKey = key as keyof InspectorConfig;
return (
<div key={key} className="space-y-2">
<label className="text-sm font-medium">
{configItem.description}
</label>
<div className="flex items-center gap-1">
<label className="text-sm font-medium text-green-600">
{configKey}
</label>
<Tooltip>
<TooltipTrigger asChild>
<HelpCircle className="h-4 w-4 text-muted-foreground" />
</TooltipTrigger>
<TooltipContent>
{configItem.description}
</TooltipContent>
</Tooltip>
</div>
{typeof configItem.value === "number" ? (
<Input
type="number"
@@ -380,7 +398,7 @@ const Sidebar = ({
<div className="space-y-2">
{connectionStatus === "connected" && (
<div className="grid grid-cols-2 gap-4">
<Button onClick={onConnect}>
<Button data-testid="connect-button" onClick={onConnect}>
<RotateCcw className="w-4 h-4 mr-2" />
{transportType === "stdio" ? "Restart" : "Reconnect"}
</Button>
@@ -399,20 +417,32 @@ const Sidebar = ({
<div className="flex items-center justify-center space-x-2 mb-4">
<div
className={`w-2 h-2 rounded-full ${
connectionStatus === "connected"
? "bg-green-500"
: connectionStatus === "error"
? "bg-red-500"
: "bg-gray-500"
}`}
className={`w-2 h-2 rounded-full ${(() => {
switch (connectionStatus) {
case "connected":
return "bg-green-500";
case "error":
return "bg-red-500";
case "error-connecting-to-proxy":
return "bg-red-500";
default:
return "bg-gray-500";
}
})()}`}
/>
<span className="text-sm text-gray-600">
{connectionStatus === "connected"
? "Connected"
: connectionStatus === "error"
? "Connection Error"
: "Disconnected"}
{(() => {
switch (connectionStatus) {
case "connected":
return "Connected";
case "error":
return "Connection Error, is your MCP server running?";
case "error-connecting-to-proxy":
return "Error Connecting to MCP Inspector Proxy - Check Console logs";
default:
return "Disconnected";
}
})()}
</span>
</div>

View File

@@ -52,14 +52,10 @@ const ToolsTab = ({
return (
<>
<h4 className="font-semibold mb-2">Invalid Tool Result:</h4>
<div className="p-4 border rounded">
<JsonView data={toolResult} />
</div>
<JsonView data={toolResult} />
<h4 className="font-semibold mb-2">Errors:</h4>
{parsedResult.error.errors.map((error, idx) => (
<div key={idx} className="p-4 border rounded">
<JsonView data={error} />
</div>
<JsonView data={error} key={idx} />
))}
</>
);
@@ -74,11 +70,7 @@ const ToolsTab = ({
</h4>
{structuredResult.content.map((item, index) => (
<div key={index} className="mb-2">
{item.type === "text" && (
<div className="p-4 border rounded">
<JsonView data={item.text} />
</div>
)}
{item.type === "text" && <JsonView data={item.text} />}
{item.type === "image" && (
<img
src={`data:${item.mimeType};base64,${item.data}`}
@@ -96,9 +88,7 @@ const ToolsTab = ({
<p>Your browser does not support audio playback</p>
</audio>
) : (
<div className="p-4 border rounded">
<JsonView data={item.resource} />
</div>
<JsonView data={item.resource} />
))}
</div>
))}
@@ -108,9 +98,8 @@ const ToolsTab = ({
return (
<>
<h4 className="font-semibold mb-2">Tool Result (Legacy):</h4>
<div className="p-4 border rounded">
<JsonView data={toolResult.toolResult} />
</div>
<JsonView data={toolResult.toolResult} />
</>
);
}

View File

@@ -1,8 +1,9 @@
import { render, screen, fireEvent } from "@testing-library/react";
import { describe, it, beforeEach, jest } from "@jest/globals";
import Sidebar from "../Sidebar";
import { DEFAULT_INSPECTOR_CONFIG } from "../../lib/constants";
import { InspectorConfig } from "../../lib/configurationTypes";
import { DEFAULT_INSPECTOR_CONFIG } from "@/lib/constants";
import { InspectorConfig } from "@/lib/configurationTypes";
import { TooltipProvider } from "@/components/ui/tooltip";
// Mock theme hook
jest.mock("../../lib/useTheme", () => ({
@@ -36,11 +37,15 @@ describe("Sidebar Environment Variables", () => {
};
const renderSidebar = (props = {}) => {
return render(<Sidebar {...defaultProps} {...props} />);
return render(
<TooltipProvider>
<Sidebar {...defaultProps} {...props} />
</TooltipProvider>,
);
};
const openEnvVarsSection = () => {
const button = screen.getByText("Environment Variables");
const button = screen.getByTestId("env-vars-button");
fireEvent.click(button);
};
@@ -216,7 +221,11 @@ describe("Sidebar Environment Variables", () => {
const updatedEnv = setEnv.mock.calls[0][0] as Record<string, string>;
// Rerender with the updated env
rerender(<Sidebar {...defaultProps} env={updatedEnv} setEnv={setEnv} />);
rerender(
<TooltipProvider>
<Sidebar {...defaultProps} env={updatedEnv} setEnv={setEnv} />
</TooltipProvider>,
);
// Second key edit
const secondKeyInput = screen.getByDisplayValue("SECOND_KEY");
@@ -247,7 +256,11 @@ describe("Sidebar Environment Variables", () => {
fireEvent.change(keyInput, { target: { value: "NEW_KEY" } });
// Rerender with updated env
rerender(<Sidebar {...defaultProps} env={{ NEW_KEY: "test_value" }} />);
rerender(
<TooltipProvider>
<Sidebar {...defaultProps} env={{ NEW_KEY: "test_value" }} />
</TooltipProvider>,
);
// Value should still be visible
const updatedValueInput = screen.getByDisplayValue("test_value");
@@ -312,7 +325,7 @@ describe("Sidebar Environment Variables", () => {
describe("Configuration Operations", () => {
const openConfigSection = () => {
const button = screen.getByText("Configuration");
const button = screen.getByTestId("config-button");
fireEvent.click(button);
};
@@ -327,12 +340,14 @@ describe("Sidebar Environment Variables", () => {
);
fireEvent.change(timeoutInput, { target: { value: "5000" } });
expect(setConfig).toHaveBeenCalledWith({
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 5000,
},
});
expect(setConfig).toHaveBeenCalledWith(
expect.objectContaining({
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 5000,
},
}),
);
});
it("should handle invalid timeout values entered by user", () => {
@@ -346,12 +361,14 @@ describe("Sidebar Environment Variables", () => {
);
fireEvent.change(timeoutInput, { target: { value: "abc1" } });
expect(setConfig).toHaveBeenCalledWith({
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 0,
},
});
expect(setConfig).toHaveBeenCalledWith(
expect.objectContaining({
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 0,
},
}),
);
});
it("should maintain configuration state after multiple updates", () => {
@@ -362,7 +379,6 @@ describe("Sidebar Environment Variables", () => {
});
openConfigSection();
// First update
const timeoutInput = screen.getByTestId(
"MCP_SERVER_REQUEST_TIMEOUT-input",
@@ -374,11 +390,13 @@ describe("Sidebar Environment Variables", () => {
// Rerender with the updated config
rerender(
<Sidebar
{...defaultProps}
config={updatedConfig}
setConfig={setConfig}
/>,
<TooltipProvider>
<Sidebar
{...defaultProps}
config={updatedConfig}
setConfig={setConfig}
/>
</TooltipProvider>,
);
// Second update
@@ -388,12 +406,14 @@ describe("Sidebar Environment Variables", () => {
fireEvent.change(updatedTimeoutInput, { target: { value: "3000" } });
// Verify the final state matches what we expect
expect(setConfig).toHaveBeenLastCalledWith({
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 3000,
},
});
expect(setConfig).toHaveBeenLastCalledWith(
expect.objectContaining({
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 3000,
},
}),
);
});
});
});

View File

@@ -22,7 +22,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 hover:border-[#646cff] hover:border-1",
className,
)}
{...props}

View File

@@ -0,0 +1,126 @@
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils";
import { Cross2Icon } from "@radix-ui/react-icons";
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className,
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
},
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
);
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className,
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className,
)}
toast-close=""
{...props}
>
<Cross2Icon className="h-4 w-4" />
</ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold [&+div]:text-xs", className)}
{...props}
/>
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
};

View File

@@ -0,0 +1,33 @@
import { useToast } from "@/hooks/use-toast";
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}

View File

@@ -0,0 +1,30 @@
"use client";
import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { cn } from "@/lib/utils";
const TooltipProvider = TooltipPrimitive.Provider;
const Tooltip = TooltipPrimitive.Root;
const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin]",
className,
)}
{...props}
/>
));
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

View File

@@ -0,0 +1,191 @@
"use client";
// Inspired by react-hot-toast library
import * as React from "react";
import type { ToastActionElement, ToastProps } from "@/components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1000000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t,
),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id: id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };

View File

@@ -38,29 +38,6 @@ h1 {
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
button[role="checkbox"] {
padding: 0;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
@@ -69,9 +46,6 @@ button[role="checkbox"] {
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
@layer base {

View File

@@ -15,4 +15,5 @@ export type InspectorConfig = {
* Maximum time in milliseconds to wait for a response from the MCP server before timing out.
*/
MCP_SERVER_REQUEST_TIMEOUT: ConfigItem;
MCP_PROXY_FULL_ADDRESS: ConfigItem;
};

View File

@@ -8,9 +8,26 @@ export const SESSION_KEYS = {
CLIENT_INFORMATION: "mcp_client_information",
} as const;
export type ConnectionStatus =
| "disconnected"
| "connected"
| "error"
| "error-connecting-to-proxy";
export const DEFAULT_MCP_PROXY_LISTEN_PORT = "6277";
/**
* Default configuration for the MCP Inspector, Currently persisted in local_storage in the Browser.
* Future plans: Provide json config file + Browser local_storage to override default values
**/
export const DEFAULT_INSPECTOR_CONFIG: InspectorConfig = {
MCP_SERVER_REQUEST_TIMEOUT: {
description: "Timeout for requests to the MCP server (ms)",
value: 10000,
},
MCP_PROXY_FULL_ADDRESS: {
description:
"Set this if you are running the MCP Inspector Proxy on a non-default address. Example: http://10.1.1.22:5577",
value: "",
},
} as const;

View File

@@ -25,9 +25,9 @@ import {
PromptListChangedNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { useState } from "react";
import { toast } from "react-toastify";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";
import { SESSION_KEYS } from "../constants";
import { ConnectionStatus, SESSION_KEYS } from "../constants";
import { Notification, StdErrNotificationSchema } from "../notificationTypes";
import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
import { authProvider } from "../auth";
@@ -70,9 +70,9 @@ export function useConnection({
onPendingRequest,
getRoots,
}: UseConnectionOptions) {
const [connectionStatus, setConnectionStatus] = useState<
"disconnected" | "connected" | "error"
>("disconnected");
const [connectionStatus, setConnectionStatus] =
useState<ConnectionStatus>("disconnected");
const { toast } = useToast();
const [serverCapabilities, setServerCapabilities] =
useState<ServerCapabilities | null>(null);
const [mcpClient, setMcpClient] = useState<Client | null>(null);
@@ -125,7 +125,11 @@ export function useConnection({
} catch (e: unknown) {
if (!options?.suppressToast) {
const errorString = (e as Error).message ?? String(e);
toast.error(errorString);
toast({
title: "Error",
description: errorString,
variant: "destructive",
});
}
throw e;
}
@@ -167,7 +171,11 @@ export function useConnection({
}
// Unexpected errors - show toast and rethrow
toast.error(e instanceof Error ? e.message : String(e));
toast({
title: "Error",
description: e instanceof Error ? e.message : String(e),
variant: "destructive",
});
throw e;
}
};
@@ -175,7 +183,11 @@ export function useConnection({
const sendNotification = async (notification: ClientNotification) => {
if (!mcpClient) {
const error = new Error("MCP client not connected");
toast.error(error.message);
toast({
title: "Error",
description: error.message,
variant: "destructive",
});
throw error;
}
@@ -188,7 +200,25 @@ export function useConnection({
// Log MCP protocol errors
pushHistory(notification, { error: e.message });
}
toast.error(e instanceof Error ? e.message : String(e));
toast({
title: "Error",
description: e instanceof Error ? e.message : String(e),
variant: "destructive",
});
throw e;
}
};
const checkProxyHealth = async () => {
try {
const proxyHealthUrl = new URL(`${proxyServerUrl}/health`);
const proxyHealthResponse = await fetch(proxyHealthUrl);
const proxyHealth = await proxyHealthResponse.json();
if (proxyHealth?.status !== "ok") {
throw new Error("MCP Proxy Server is not healthy");
}
} catch (e) {
console.error("Couldn't connect to MCP Proxy Server", e);
throw e;
}
};
@@ -205,33 +235,38 @@ export function useConnection({
};
const connect = async (_e?: unknown, retryCount: number = 0) => {
try {
const client = new Client<Request, Notification, Result>(
{
name: "mcp-inspector",
version: packageJson.version,
},
{
capabilities: {
sampling: {},
roots: {
listChanged: true,
},
const client = new Client<Request, Notification, Result>(
{
name: "mcp-inspector",
version: packageJson.version,
},
{
capabilities: {
sampling: {},
roots: {
listChanged: true,
},
},
);
},
);
const backendUrl = new URL(`${proxyServerUrl}/sse`);
backendUrl.searchParams.append("transportType", transportType);
if (transportType === "stdio") {
backendUrl.searchParams.append("command", command);
backendUrl.searchParams.append("args", args);
backendUrl.searchParams.append("env", JSON.stringify(env));
} else {
backendUrl.searchParams.append("url", sseUrl);
}
try {
await checkProxyHealth();
} catch {
setConnectionStatus("error-connecting-to-proxy");
return;
}
const mcpProxyServerUrl = new URL(`${proxyServerUrl}/sse`);
mcpProxyServerUrl.searchParams.append("transportType", transportType);
if (transportType === "stdio") {
mcpProxyServerUrl.searchParams.append("command", command);
mcpProxyServerUrl.searchParams.append("args", args);
mcpProxyServerUrl.searchParams.append("env", JSON.stringify(env));
} else {
mcpProxyServerUrl.searchParams.append("url", sseUrl);
}
try {
// Inject auth manually instead of using SSEClientTransport, because we're
// proxying through the inspector server first.
const headers: HeadersInit = {};
@@ -242,7 +277,7 @@ export function useConnection({
headers["Authorization"] = `Bearer ${token}`;
}
const clientTransport = new SSEClientTransport(backendUrl, {
const clientTransport = new SSEClientTransport(mcpProxyServerUrl, {
eventSourceInit: {
fetch: (url, init) => fetch(url, { ...init, headers }),
},
@@ -282,7 +317,10 @@ export function useConnection({
try {
await client.connect(clientTransport);
} catch (error) {
console.error("Failed to connect to MCP server:", error);
console.error(
`Failed to connect to MCP Server via the MCP Inspector Proxy: ${mcpProxyServerUrl}:`,
error,
);
const shouldRetry = await handleAuthError(error);
if (shouldRetry) {
return connect(undefined, retryCount + 1);

View File

@@ -1,13 +1,15 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { Toaster } from "@/components/ui/toaster.tsx";
import App from "./App.tsx";
import "./index.css";
import { TooltipProvider } from "./components/ui/tooltip.tsx";
createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
<ToastContainer />
<TooltipProvider>
<App />
</TooltipProvider>
<Toaster />
</StrictMode>,
);

View File

@@ -0,0 +1,14 @@
import { InspectorConfig } from "@/lib/configurationTypes";
import { DEFAULT_MCP_PROXY_LISTEN_PORT } from "@/lib/constants";
export const getMCPProxyAddress = (config: InspectorConfig): string => {
const proxyFullAddress = config.MCP_PROXY_FULL_ADDRESS.value as string;
if (proxyFullAddress) {
return proxyFullAddress;
}
return `${window.location.protocol}//${window.location.hostname}:${DEFAULT_MCP_PROXY_LISTEN_PORT}`;
};
export const getMCPServerRequestTimeout = (config: InspectorConfig): number => {
return config.MCP_SERVER_REQUEST_TIMEOUT.value as number;
};

3031
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@modelcontextprotocol/inspector",
"version": "0.8.0",
"version": "0.8.1",
"description": "Model Context Protocol inspector",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
@@ -36,8 +36,8 @@
"publish-all": "npm publish --workspaces --access public && npm publish --access public"
},
"dependencies": {
"@modelcontextprotocol/inspector-client": "^0.8.0",
"@modelcontextprotocol/inspector-server": "^0.8.0",
"@modelcontextprotocol/inspector-client": "^0.8.1",
"@modelcontextprotocol/inspector-server": "^0.8.1",
"concurrently": "^9.0.1",
"shell-quote": "^1.8.2",
"spawn-rx": "^5.1.2",

View File

@@ -1,6 +1,6 @@
{
"name": "@modelcontextprotocol/inspector-server",
"version": "0.8.0",
"version": "0.8.1",
"description": "Server-side application for the Model Context Protocol inspector",
"license": "MIT",
"author": "Anthropic, PBC (https://anthropic.com)",
@@ -27,7 +27,7 @@
"typescript": "^5.6.2"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.6.1",
"@modelcontextprotocol/sdk": "^1.8.0",
"cors": "^2.8.5",
"express": "^4.21.0",
"ws": "^8.18.0",

View File

@@ -38,7 +38,7 @@ app.use(cors());
let webAppTransports: SSEServerTransport[] = [];
const createTransport = async (req: express.Request) => {
const createTransport = async (req: express.Request): Promise<Transport> => {
const query = req.query;
console.log("Query parameters:", query);
@@ -70,6 +70,7 @@ const createTransport = async (req: express.Request) => {
const headers: HeadersInit = {
Accept: "text/event-stream",
};
for (const key of SSE_HEADERS_PASSTHROUGH) {
if (req.headers[key] === undefined) {
continue;
@@ -172,6 +173,12 @@ app.post("/message", async (req, res) => {
}
});
app.get("/health", (req, res) => {
res.json({
status: "ok",
});
});
app.get("/config", (req, res) => {
try {
res.json({