* 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>
109 lines
2.8 KiB
TypeScript
109 lines
2.8 KiB
TypeScript
/**
|
|
* Remote session - holds a transport and event queue for a remote client.
|
|
*/
|
|
|
|
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|
import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
|
|
import type { FetchRequestEntryBase } from "../../types.js";
|
|
import type { RemoteEvent } from "../types.js";
|
|
|
|
export interface SessionEvent {
|
|
type: RemoteEvent["type"];
|
|
data: unknown;
|
|
}
|
|
|
|
export class RemoteSession {
|
|
public readonly sessionId: string;
|
|
public transport!: Transport;
|
|
private eventQueue: SessionEvent[] = [];
|
|
private eventConsumer: ((event: SessionEvent) => void) | null = null;
|
|
private transportDead: boolean = false;
|
|
private transportError: string | null = null;
|
|
|
|
constructor(sessionId: string) {
|
|
this.sessionId = sessionId;
|
|
}
|
|
|
|
setTransport(transport: Transport): void {
|
|
this.transport = transport;
|
|
}
|
|
|
|
setEventConsumer(consumer: (event: SessionEvent) => void): void {
|
|
this.eventConsumer = consumer;
|
|
// Flush queued events
|
|
while (this.eventQueue.length > 0) {
|
|
const ev = this.eventQueue.shift()!;
|
|
consumer(ev);
|
|
}
|
|
}
|
|
|
|
clearEventConsumer(): boolean {
|
|
this.eventConsumer = null;
|
|
// If transport is dead and no client connected, signal to cleanup
|
|
return this.transportDead;
|
|
}
|
|
|
|
markTransportDead(error: string): void {
|
|
this.transportDead = true;
|
|
this.transportError = error;
|
|
// Always push the transport_error event — pushEvent queues it if no
|
|
// consumer is attached yet, so a process that crashes during startup
|
|
// (between POST /api/mcp/connect returning 200 and the browser opening
|
|
// /api/mcp/events) still surfaces its error to the eventual consumer
|
|
// instead of vanishing.
|
|
this.pushEvent({
|
|
type: "transport_error",
|
|
data: {
|
|
error,
|
|
code: -32000, // MCP error code for connection closed
|
|
},
|
|
});
|
|
}
|
|
|
|
isTransportDead(): boolean {
|
|
return this.transportDead;
|
|
}
|
|
|
|
getTransportError(): string | null {
|
|
return this.transportError;
|
|
}
|
|
|
|
hasEventConsumer(): boolean {
|
|
return this.eventConsumer !== null;
|
|
}
|
|
|
|
pushEvent(event: SessionEvent): void {
|
|
if (this.eventConsumer) {
|
|
this.eventConsumer(event);
|
|
} else {
|
|
this.eventQueue.push(event);
|
|
}
|
|
}
|
|
|
|
onMessage(message: JSONRPCMessage): void {
|
|
this.pushEvent({ type: "message", data: message });
|
|
}
|
|
|
|
onFetchRequest(entry: FetchRequestEntryBase): void {
|
|
this.pushEvent({
|
|
type: "fetch_request",
|
|
data: {
|
|
...entry,
|
|
timestamp:
|
|
entry.timestamp instanceof Date
|
|
? entry.timestamp.toISOString()
|
|
: entry.timestamp,
|
|
},
|
|
});
|
|
}
|
|
|
|
onStderr(entry: { timestamp: Date; message: string }): void {
|
|
this.pushEvent({
|
|
type: "stdio_log",
|
|
data: {
|
|
timestamp: entry.timestamp.toISOString(),
|
|
message: entry.message,
|
|
},
|
|
});
|
|
}
|
|
}
|