* feat(servers): persist server list to ~/.mcp-inspector/mcp.json (#1343) Replaces the hardcoded SEED_SERVERS in App.tsx with a file-backed list at ~/.mcp-inspector/mcp.json. Full CRUD round-trips through new /api/servers routes; first launch writes the two existing seeds if the file is absent. Backend (core): - store-io: getDefaultMcpConfigPath() — sibling of getDefaultStorageDir() - core/mcp/serverList.ts: pure converters MCPConfig <-> ServerEntry[], DEFAULT_SEED_CONFIG, and normalizeServerType (moved from node/config.ts to keep serverList.ts Node-free) - core/mcp/remote/node/server.ts: GET/POST/PUT/:id/DELETE/:id /api/servers routes, plus RemoteServerOptions.mcpConfigPath defaulting to getDefaultMcpConfigPath(). Ids validated with validateStoreId. Frontend: - core/react/useServers.ts: { servers, loading, error, refresh, addServer, updateServer, removeServer } over the new endpoints - App.tsx: drops SEED_SERVERS, wires useServers, disconnects on remove of the active server, follows id on rename of the active server - ServerConfigModal: Add/Edit/Clone form (stdio: command/args/env/cwd; sse/streamable-http: url/headers as one-per-line text) - ServerRemoveConfirmModal: confirm-on-remove with id + transport summary Tests (52 new): - unit: getDefaultMcpConfigPath env-var permutations, serverList round-trip, hook flows against real Hono app.fetch (no TCP), modal forms + validation - integration: /api/servers routes against a real createRemoteApp + tmp file - stories with play functions for both new modals Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(servers): address PR #1349 review (correctness + nits) Bugs: - normalizeServerType: validate against the allowed set and default unknown / non-string types to "stdio" (matches the missing-type case). Prevents a hand-edited {"type":"websocket"} from leaking past `as ServerType` and surprising downstream narrowing. - onConfirmRemove: when removing the active server, also destroy() the 9 state managers and null them + the client out so they GC immediately instead of waiting for the next server switch. - /api/servers mutating routes: serialize POST/PUT/DELETE through an in-process write-lock so concurrent read-modify-write cycles can't lose updates. New integration test fires 25 parallel POSTs and asserts every entry lands. - readMcpConfig comment: update to match actual behavior (valid-JSON file with no `mcpServers` → empty; invalid JSON → 500 from the outer try, so corruption surfaces rather than silently emptying the list). New integration tests pin the 500 path on both GET and POST. Nits: - Add --inspector-surface-subtle token, use it in ServerRemoveConfirmModal instead of the raw Mantine var. - Rename useServers buildHeaders boolean param to includeJsonBody. - Add a comment on the env-value vs header-value trim asymmetry (env values preserve trailing whitespace; header values follow RFC 7230). Tests: 1630 unit + 404 integration + 306 storybook all green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(ServerConfigModal): null currentTarget in functional setState updater React nulls SyntheticEvent.currentTarget after the synchronous handler returns. Reading e.currentTarget.value inside `setForm((f) => ...)` worked under happy-dom (which keeps currentTarget around) but threw "Cannot read properties of null (reading 'value')" on the first keystroke in a real browser. Capture the value before the functional updater closes over it. All seven onChange handlers in ServerConfigModal had the bug. Extended the AddEmpty storybook play to type into Server ID and Command — the real-Chromium runner now exercises this path so a future regression fails the test suite instead of the user. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(remote-server): surface stderr + transport_error when subprocess crashes during startup A stdio subprocess that spawns successfully but exits before the browser opens the SSE events stream used to vanish into a bare "Session not found" 404. The fix has three parts: 1. RemoteSession.markTransportDead always pushes the transport_error event (via pushEvent's queue) rather than dropping it when no consumer is attached. The queued event drains when the consumer eventually arrives. 2. /api/mcp/connect's transport.onclose handler no longer deletes the session immediately when no consumer is attached. Instead it holds the session (with queued stderr + transport_error) for a 30s grace window so the events endpoint can drain it. A timeout sweeps if no consumer ever connects. 3. /api/mcp/events detects isTransportDead after attaching the consumer (which just drained the queue), yields once to flush, then closes the stream and deletes the session. End result: the user sees the actual error (e.g. "Cannot find module" from stderr + the transport-closed reason) instead of a confusing 404. Tests: - New unit tests (clients/web/src/test/integration/mcp/remote/remote-session.test.ts) cover the queueing behavior, live delivery, and clearEventConsumer signaling under all transport-state permutations. - New integration test (connect-crash.test.ts) spawns a node subprocess that writes to stderr and exits, then verifies the events stream delivers both the stderr line and the transport_error event before closing — the exact scenario from PR #1349. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(state): gate listRequestorTasks on the server's `tasks` capability ManagedRequestorTasksState was calling tasks/list on every connect. Servers that don't advertise the `tasks` capability (the common case) reply with -32601 "Method not found", which then surfaces in the inspector's console for every connect. Skip the call when the server doesn't declare `tasks` — empty tasks list is the right semantics. Existing tests opt into capabilities so the live-path coverage is preserved; two new tests pin the gated behavior (direct refresh + connect-event-triggered refresh). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(App): clear activeServerId on disconnect so other server cards re-enable ServerCard dims any card whose id differs from `activeServer` (and marks it inert), so cards stay non-interactive after a disconnect until the user reconnects elsewhere. activeServerId was set on connect but never reset on disconnect, leaving the whole screen locked to the just- disconnected card. Subscribe to InspectorClient's `disconnect` event and clear activeServerId there. Covers all three disconnect paths uniformly: - user toggles the connected card off - user clicks the header Disconnect button - mid-session transport failure (subprocess exit / network drop) Event-based instead of effect-based on connectionStatus to avoid the first-render-clobbers-new-id trap (status starts as "disconnected" for a freshly-created client before connect() runs). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
e9ac57c548
commit
db1916cd34
1 changed files with 3176 additions and 137 deletions
|
|
@ -9,7 +9,11 @@ import type {
|
|||
import type { AppBridge } from "@modelcontextprotocol/ext-apps/app-bridge";
|
||||
import { InspectorClient } from "@inspector/core/mcp/index.js";
|
||||
import type { JsonValue } from "@inspector/core/mcp/index.js";
|
||||
import type { MessageEntry, ServerEntry } from "@inspector/core/mcp/types.js";
|
||||
import type {
|
||||
MCPServerConfig,
|
||||
MessageEntry,
|
||||
ServerEntry,
|
||||
} from "@inspector/core/mcp/types.js";
|
||||
import { API_SERVER_ENV_VARS } from "@inspector/core/mcp/remote/constants.js";
|
||||
import { ManagedToolsState } from "@inspector/core/mcp/state/managedToolsState.js";
|
||||
import { ManagedPromptsState } from "@inspector/core/mcp/state/managedPromptsState.js";
|
||||
|
|
@ -22,6 +26,7 @@ import { FetchRequestLogState } from "@inspector/core/mcp/state/fetchRequestLogS
|
|||
import { StderrLogState } from "@inspector/core/mcp/state/stderrLogState.js";
|
||||
import type { RedirectUrlProvider } from "@inspector/core/auth/index.js";
|
||||
import { useInspectorClient } from "@inspector/core/react/useInspectorClient.js";
|
||||
import { useServers } from "@inspector/core/react/useServers.js";
|
||||
import { useManagedTools } from "@inspector/core/react/useManagedTools.js";
|
||||
import { useManagedPrompts } from "@inspector/core/react/useManagedPrompts.js";
|
||||
import { useManagedResources } from "@inspector/core/react/useManagedResources.js";
|
||||
|
|
@ -35,38 +40,13 @@ import type { GetPromptState } from "./components/screens/PromptsScreen/PromptsS
|
|||
import type { ReadResourceState } from "./components/screens/ResourcesScreen/ResourcesScreen";
|
||||
import type { BridgeFactory } from "./components/elements/AppRenderer/AppRenderer";
|
||||
import type { LogEntryData } from "./components/elements/LogEntry/LogEntry";
|
||||
import {
|
||||
ServerConfigModal,
|
||||
type ServerConfigModalMode,
|
||||
} from "./components/groups/ServerConfigModal/ServerConfigModal";
|
||||
import { ServerRemoveConfirmModal } from "./components/groups/ServerRemoveConfirmModal/ServerRemoveConfirmModal";
|
||||
import { createWebEnvironment } from "./lib/environmentFactory";
|
||||
|
||||
// Hardcoded seed servers so the Servers screen has something to connect to.
|
||||
// Persistence + an "Add server" UI are explicitly out of scope for #1244 (the
|
||||
// useServers v2-only hook is a separate effort); follow-up work will replace
|
||||
// this with a real `useServers` store. The two seeds here cover the common
|
||||
// shapes a developer reaches for first: a real filesystem (scoped to /tmp so
|
||||
// nothing destructive is possible by default) and the canonical "everything"
|
||||
// reference server (tools / prompts / resources / sampling / completion).
|
||||
const SEED_SERVERS: ServerEntry[] = [
|
||||
{
|
||||
id: "filesystem-server-default",
|
||||
name: "Local Filesystem (npx)",
|
||||
config: {
|
||||
type: "stdio",
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
|
||||
},
|
||||
connection: { status: "disconnected" },
|
||||
},
|
||||
{
|
||||
id: "everything-server-default",
|
||||
name: "Everything (npx)",
|
||||
config: {
|
||||
type: "stdio",
|
||||
command: "npx",
|
||||
args: ["-y", "@modelcontextprotocol/server-everything"],
|
||||
},
|
||||
connection: { status: "disconnected" },
|
||||
},
|
||||
];
|
||||
|
||||
// OAuth redirect URL provider — points at the dev backend's `/oauth/callback`
|
||||
// handler. The InspectorClient only consults this when the active server
|
||||
// requires OAuth; for stdio MCP servers it's never used. Created once and
|
||||
|
|
@ -150,9 +130,24 @@ function App() {
|
|||
setColorScheme(isDark ? "light" : "dark");
|
||||
}, [isDark, setColorScheme]);
|
||||
|
||||
// Server list — held locally; one seed entry per #1244's "hardcoded
|
||||
// sample server" scope decision. Future work: useServers hook.
|
||||
const [servers] = useState<ServerEntry[]>(SEED_SERVERS);
|
||||
// Server list — sourced from ~/.mcp-inspector/mcp.json via the backend's
|
||||
// `/api/servers` routes. First-launch seeds are written by the backend when
|
||||
// the file is absent, so this hook returns a non-empty list on first load.
|
||||
const { servers, addServer, updateServer, removeServer } = useServers({
|
||||
baseUrl:
|
||||
typeof window !== "undefined"
|
||||
? window.location.origin
|
||||
: "http://localhost",
|
||||
authToken: getAuthToken(),
|
||||
});
|
||||
|
||||
// CRUD-modal state. `configModal` drives Add / Edit / Clone via a single
|
||||
// shared form modal; `removeTarget` drives the remove-confirmation modal.
|
||||
const [configModal, setConfigModal] = useState<{
|
||||
mode: ServerConfigModalMode;
|
||||
targetId?: string;
|
||||
} | null>(null);
|
||||
const [removeTarget, setRemoveTarget] = useState<ServerEntry | null>(null);
|
||||
|
||||
// The active connection target. `null` between sessions; set as soon as
|
||||
// the user toggles a server card on. Drives state-manager lifetime.
|
||||
|
|
@ -277,6 +272,25 @@ function App() {
|
|||
};
|
||||
}, [inspectorClient]);
|
||||
|
||||
// Reset activeServerId whenever the live session ends. Without this the
|
||||
// other ServerCards stay `inert` after disconnect — ServerCard dims any
|
||||
// card whose id differs from `activeServer`. Subscribing to
|
||||
// InspectorClient's own `disconnect` event covers all three paths
|
||||
// (explicit toggle, header Disconnect button, mid-session transport
|
||||
// failure / process exit) and avoids the first-render-clobbers-new-id
|
||||
// trap that watching connectionStatus has (status starts as
|
||||
// "disconnected" for the new client before connect() runs).
|
||||
useEffect(() => {
|
||||
if (!inspectorClient) return;
|
||||
const onDisconnect = () => {
|
||||
setActiveServerId(undefined);
|
||||
};
|
||||
inspectorClient.addEventListener("disconnect", onDisconnect);
|
||||
return () => {
|
||||
inspectorClient.removeEventListener("disconnect", onDisconnect);
|
||||
};
|
||||
}, [inspectorClient]);
|
||||
|
||||
// Build the InitializeResult the connected ViewHeader expects from the
|
||||
// hook's split fields. `protocolVersion` is hard-coded for now — the
|
||||
// useInspectorClient hook doesn't expose it. TODO(#1324): consume the
|
||||
|
|
@ -591,6 +605,92 @@ function App() {
|
|||
/* TODO: not wired yet */
|
||||
}, []);
|
||||
|
||||
// Remove handler — runs after the user confirms in the modal. When removing
|
||||
// the active server, also tear down the session in-place so the client and
|
||||
// its 9 state managers can be GC'd now instead of lingering until the next
|
||||
// server switch. Mirrors the destroy sequence at the top of
|
||||
// `setupClientForServer` (lines ~304-312) but additionally nulls every ref.
|
||||
const onConfirmRemove = useCallback(async () => {
|
||||
if (!removeTarget) return;
|
||||
const id = removeTarget.id;
|
||||
if (id === activeServerId) {
|
||||
if (inspectorClient) {
|
||||
await inspectorClient.disconnect();
|
||||
}
|
||||
managedToolsState?.destroy();
|
||||
managedPromptsState?.destroy();
|
||||
managedResourcesState?.destroy();
|
||||
managedResourceTemplatesState?.destroy();
|
||||
managedRequestorTasksState?.destroy();
|
||||
resourceSubscriptionsState?.destroy();
|
||||
messageLogState?.destroy();
|
||||
fetchRequestLogState?.destroy();
|
||||
stderrLogState?.destroy();
|
||||
setInspectorClient(null);
|
||||
setManagedToolsState(null);
|
||||
setManagedPromptsState(null);
|
||||
setManagedResourcesState(null);
|
||||
setManagedResourceTemplatesState(null);
|
||||
setManagedRequestorTasksState(null);
|
||||
setResourceSubscriptionsState(null);
|
||||
setMessageLogState(null);
|
||||
setFetchRequestLogState(null);
|
||||
setStderrLogState(null);
|
||||
setActiveServerId(undefined);
|
||||
}
|
||||
await removeServer(id);
|
||||
setRemoveTarget(null);
|
||||
}, [
|
||||
removeTarget,
|
||||
activeServerId,
|
||||
inspectorClient,
|
||||
managedToolsState,
|
||||
managedPromptsState,
|
||||
managedResourcesState,
|
||||
managedResourceTemplatesState,
|
||||
managedRequestorTasksState,
|
||||
resourceSubscriptionsState,
|
||||
messageLogState,
|
||||
fetchRequestLogState,
|
||||
stderrLogState,
|
||||
removeServer,
|
||||
]);
|
||||
|
||||
// Submit handler for the Add / Edit / Clone modal. Add and Clone both go
|
||||
// through addServer; Edit uses updateServer (which supports id rename).
|
||||
// On rename of the active server, keep activeServerId pointed at the new id.
|
||||
const onConfigSubmit = useCallback(
|
||||
async (id: string, config: MCPServerConfig) => {
|
||||
if (configModal?.mode === "edit" && configModal.targetId) {
|
||||
const originalId = configModal.targetId;
|
||||
await updateServer(originalId, id, config);
|
||||
if (originalId === activeServerId && id !== originalId) {
|
||||
setActiveServerId(id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// add or clone
|
||||
await addServer(id, config);
|
||||
},
|
||||
[configModal, addServer, updateServer, activeServerId],
|
||||
);
|
||||
|
||||
// Derive the existingIds list the modal uses for uniqueness validation.
|
||||
// In edit mode the target's own id must be excluded so saving without
|
||||
// renaming doesn't trip the "already exists" check.
|
||||
const existingIds = useMemo(() => {
|
||||
const ids = servers.map((s) => s.id);
|
||||
if (configModal?.mode === "edit" && configModal.targetId) {
|
||||
return ids.filter((id) => id !== configModal.targetId);
|
||||
}
|
||||
return ids;
|
||||
}, [servers, configModal]);
|
||||
|
||||
const configModalTarget = useMemo(() => {
|
||||
if (!configModal?.targetId) return undefined;
|
||||
return servers.find((s) => s.id === configModal.targetId);
|
||||
}, [configModal, servers]);
|
||||
|
||||
// The Resources screen needs `isSubscribed` to flip the Subscribe button
|
||||
// label to "Unsubscribe". Derive it from the live subscriptions list rather
|
||||
// than threading it through every setReadResourceState site — that way the
|
||||
|
|
@ -608,75 +708,95 @@ function App() {
|
|||
}, [readResourceState, subscriptions]);
|
||||
|
||||
return (
|
||||
<InspectorView
|
||||
servers={servers}
|
||||
activeServer={activeServerId}
|
||||
connectionStatus={connectionStatus}
|
||||
initializeResult={initializeResult}
|
||||
latencyMs={latencyMs}
|
||||
errorMessage={errorMessage}
|
||||
tools={tools}
|
||||
prompts={prompts}
|
||||
resources={resources}
|
||||
resourceTemplates={resourceTemplates}
|
||||
subscriptions={subscriptions}
|
||||
logs={logs}
|
||||
tasks={tasks}
|
||||
history={messages}
|
||||
toolCallState={toolCallState}
|
||||
getPromptState={getPromptState}
|
||||
readResourceState={effectiveReadResourceState}
|
||||
currentLogLevel={currentLogLevel}
|
||||
sandboxPath={STUB_SANDBOX_PATH}
|
||||
bridgeFactory={stubBridgeFactory}
|
||||
onToggleTheme={onToggleTheme}
|
||||
onToggleConnection={(id) => {
|
||||
void onToggleConnection(id);
|
||||
}}
|
||||
onDisconnect={() => {
|
||||
void onDisconnect();
|
||||
}}
|
||||
onServerAdd={todoNoop}
|
||||
onServerImportConfig={todoNoop}
|
||||
onServerImportJson={todoNoop}
|
||||
onServerInfo={todoNoop}
|
||||
onServerSettings={todoNoop}
|
||||
onServerEdit={todoNoop}
|
||||
onServerClone={todoNoop}
|
||||
onServerRemove={todoNoop}
|
||||
onCallTool={(name, args) => {
|
||||
void onCallTool(name, args);
|
||||
}}
|
||||
onClearToolResult={onClearToolResult}
|
||||
onRefreshTools={onRefreshTools}
|
||||
onGetPrompt={(name, args) => {
|
||||
void onGetPrompt(name, args);
|
||||
}}
|
||||
onRefreshPrompts={onRefreshPrompts}
|
||||
onReadResource={(uri) => {
|
||||
void onReadResource(uri);
|
||||
}}
|
||||
onSubscribeResource={onSubscribeResource}
|
||||
onUnsubscribeResource={onUnsubscribeResource}
|
||||
onRefreshResources={onRefreshResources}
|
||||
onCompleteArgument={onCompleteArgument}
|
||||
completionsSupported={capabilities?.completions !== undefined}
|
||||
onCancelTask={onCancelTask}
|
||||
onClearCompletedTasks={todoNoop}
|
||||
onRefreshTasks={onRefreshTasks}
|
||||
onSetLogLevel={onSetLogLevel}
|
||||
onClearLogs={onClearLogs}
|
||||
onExportLogs={todoNoop}
|
||||
onCopyAllLogs={todoNoop}
|
||||
onClearHistory={onClearHistory}
|
||||
onExportHistory={todoNoop}
|
||||
onReplayHistory={todoNoop}
|
||||
onTogglePinHistory={todoNoop}
|
||||
onSelectApp={todoNoop}
|
||||
onOpenApp={todoNoop}
|
||||
onCloseApp={todoNoop}
|
||||
onRefreshApps={onRefreshTools}
|
||||
/>
|
||||
<>
|
||||
<InspectorView
|
||||
servers={servers}
|
||||
activeServer={activeServerId}
|
||||
connectionStatus={connectionStatus}
|
||||
initializeResult={initializeResult}
|
||||
latencyMs={latencyMs}
|
||||
errorMessage={errorMessage}
|
||||
tools={tools}
|
||||
prompts={prompts}
|
||||
resources={resources}
|
||||
resourceTemplates={resourceTemplates}
|
||||
subscriptions={subscriptions}
|
||||
logs={logs}
|
||||
tasks={tasks}
|
||||
history={messages}
|
||||
toolCallState={toolCallState}
|
||||
getPromptState={getPromptState}
|
||||
readResourceState={effectiveReadResourceState}
|
||||
currentLogLevel={currentLogLevel}
|
||||
sandboxPath={STUB_SANDBOX_PATH}
|
||||
bridgeFactory={stubBridgeFactory}
|
||||
onToggleTheme={onToggleTheme}
|
||||
onToggleConnection={(id) => {
|
||||
void onToggleConnection(id);
|
||||
}}
|
||||
onDisconnect={() => {
|
||||
void onDisconnect();
|
||||
}}
|
||||
onServerAdd={() => setConfigModal({ mode: "add" })}
|
||||
onServerImportConfig={todoNoop}
|
||||
onServerImportJson={todoNoop}
|
||||
onServerInfo={todoNoop}
|
||||
onServerSettings={todoNoop}
|
||||
onServerEdit={(id) => setConfigModal({ mode: "edit", targetId: id })}
|
||||
onServerClone={(id) => setConfigModal({ mode: "clone", targetId: id })}
|
||||
onServerRemove={(id) => {
|
||||
const target = servers.find((s) => s.id === id);
|
||||
if (target) setRemoveTarget(target);
|
||||
}}
|
||||
onCallTool={(name, args) => {
|
||||
void onCallTool(name, args);
|
||||
}}
|
||||
onClearToolResult={onClearToolResult}
|
||||
onRefreshTools={onRefreshTools}
|
||||
onGetPrompt={(name, args) => {
|
||||
void onGetPrompt(name, args);
|
||||
}}
|
||||
onRefreshPrompts={onRefreshPrompts}
|
||||
onReadResource={(uri) => {
|
||||
void onReadResource(uri);
|
||||
}}
|
||||
onSubscribeResource={onSubscribeResource}
|
||||
onUnsubscribeResource={onUnsubscribeResource}
|
||||
onRefreshResources={onRefreshResources}
|
||||
onCompleteArgument={onCompleteArgument}
|
||||
completionsSupported={capabilities?.completions !== undefined}
|
||||
onCancelTask={onCancelTask}
|
||||
onClearCompletedTasks={todoNoop}
|
||||
onRefreshTasks={onRefreshTasks}
|
||||
onSetLogLevel={onSetLogLevel}
|
||||
onClearLogs={onClearLogs}
|
||||
onExportLogs={todoNoop}
|
||||
onCopyAllLogs={todoNoop}
|
||||
onClearHistory={onClearHistory}
|
||||
onExportHistory={todoNoop}
|
||||
onReplayHistory={todoNoop}
|
||||
onTogglePinHistory={todoNoop}
|
||||
onSelectApp={todoNoop}
|
||||
onOpenApp={todoNoop}
|
||||
onCloseApp={todoNoop}
|
||||
onRefreshApps={onRefreshTools}
|
||||
/>
|
||||
<ServerConfigModal
|
||||
opened={configModal !== null}
|
||||
mode={configModal?.mode ?? "add"}
|
||||
initialId={configModalTarget?.id}
|
||||
initialConfig={configModalTarget?.config}
|
||||
existingIds={existingIds}
|
||||
onClose={() => setConfigModal(null)}
|
||||
onSubmit={onConfigSubmit}
|
||||
/>
|
||||
<ServerRemoveConfirmModal
|
||||
opened={removeTarget !== null}
|
||||
target={removeTarget}
|
||||
onCancel={() => setRemoveTarget(null)}
|
||||
onConfirm={onConfirmRemove}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue