* feat(web): catalog vs read-only session launch model + apply --header (#1481, #1483) Per specification/v2_catalog_launch_config.md, `mcp-inspector --web` now selects the backend's server-list source and a session-wide writability, instead of seeding an inert `initialMcpConfig` the UI never read: - `--catalog <path>` (and `MCP_CATALOG_PATH`) → active WRITABLE catalog (seed/CRUD/watch), like the default catalog. - `--config <path>` → READ-ONLY session file: served in the UI but never written, seeded, or plaintext-secret-migrated — safe to point at a foreign config (e.g. claude_desktop_config.json). - ad-hoc `--server-url`/command (+ `--header`) → one server held IN MEMORY (no file written); `--header` is lifted onto the entry so the seeded connection actually uses it (closes the #1483 warn-only no-op). - nothing → default catalog (writable), unchanged. Backend (`createRemoteApp`): new `writable` + `initialServers` options. GET /api/servers branches three ways (in-memory / read-only file with no seed+no migrate / writable catalog); the four mutating routes return 403 when read-only; `/api/config` carries `writable`; the file watcher is skipped for in-memory sessions. `--catalog`/`--config` are mutually exclusive and neither combines with an ad-hoc target or `--header`; `--header` requires an ad-hoc HTTP/SSE server (clear errors otherwise — no silent no-op). UI: `useServerListWritable` reads `writable` from /api/config; the Servers screen hides add/edit/clone/remove/reorder/settings and shows a read-only banner when false. All new props default to writable=true (back-compatible). Docs: spec gaps G2/G3/G4 updated; launcher README documents the flags. Verified end-to-end against the built launcher: --config (writable:false, file byte-stable, mutations 403), ad-hoc --header (in-memory, header lifted), and --catalog (writable:true, POST persists). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(web): address review — Mantine <Code> in read-only banner, clarify watcher comment - Replace raw <code> with Mantine <Code> in the read-only-session Alert (repo convention: prefer Mantine primitives over raw HTML). - Add a comment near `watchable` clarifying that a read-only `--config` file is still watched on purpose (read-only blocks UI writes, not external observation; `writable` does not gate watching). Deferred (per reviewer): consolidating useSandboxUrl + useServerListWritable into one useConfig hook to avoid the duplicate /api/config fetch — optional follow-up. The redundant ad-hoc header type-guard is kept as defensive. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
12b8eb11fd
commit
91f02fd6db
22 changed files with 1281 additions and 157 deletions
|
|
@ -10,6 +10,22 @@ The launcher is the package that provides the global `mcp-inspector` binary (e.g
|
|||
|
||||
All configuration parsing, config-file loading, and server setup are handled by the app runners and by **core**; the launcher does not interpret config or env vars.
|
||||
|
||||
## Web server-list flags (`--web`)
|
||||
|
||||
`mcp-inspector --web` chooses which server list the UI shows and whether it is
|
||||
editable (see [specification/v2_catalog_launch_config.md](../../specification/v2_catalog_launch_config.md)):
|
||||
|
||||
| Invocation | Server list | Editable in UI? |
|
||||
|------------|-------------|-----------------|
|
||||
| `mcp-inspector --web` | Default catalog `~/.mcp-inspector/mcp.json` | Yes |
|
||||
| `mcp-inspector --web --catalog <path>` (or `MCP_CATALOG_PATH=<path>`) | That file as the active catalog (created/seeded if missing) | Yes |
|
||||
| `mcp-inspector --web --config <path>` | That file as a **read-only session** — shown but never written, seeded, or migrated (safe for a foreign config) | No |
|
||||
| `mcp-inspector --web --server-url <url> --transport http --header "Name: Value"` (or a positional command) | One ad-hoc server held in memory, connectable with the given `--header`s | No |
|
||||
|
||||
Rules: `--catalog` and `--config` are mutually exclusive; neither combines with
|
||||
an ad-hoc target or `--header`; `--header` requires an ad-hoc HTTP/SSE server
|
||||
and is applied to that connection (it is no longer a warn-only no-op).
|
||||
|
||||
## Publishing
|
||||
|
||||
The root `@modelcontextprotocol/inspector` package ships as one fat tarball: `npm run build` at the repo root builds all clients, then `prepack` runs before `npm publish`. Runtime dependencies are declared on the root `package.json`; client builds bundle `@inspector/core` and externalize npm packages resolved from the root install.
|
||||
|
|
|
|||
|
|
@ -7,7 +7,11 @@
|
|||
import { resolve, join, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Command } from "commander";
|
||||
import type { MCPServerConfig } from "../../../core/mcp/types.ts";
|
||||
import type {
|
||||
MCPConfig,
|
||||
MCPServerConfig,
|
||||
StoredMCPServer,
|
||||
} from "../../../core/mcp/types.ts";
|
||||
import {
|
||||
resolveServerConfigs,
|
||||
parseKeyValuePair,
|
||||
|
|
@ -31,6 +35,22 @@ function ensureStdioCwd(config: MCPServerConfig): MCPServerConfig {
|
|||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a readable catalog id for an ad-hoc server seeded from CLI flags:
|
||||
* the URL host for HTTP/SSE, or the command basename for stdio. Falls back to
|
||||
* "server" so the id is always a non-empty `mcpServers` map key.
|
||||
*/
|
||||
function deriveSeedServerId(config: MCPServerConfig): string {
|
||||
if (config.type === "sse" || config.type === "streamable-http") {
|
||||
try {
|
||||
return new URL(config.url).host || "server";
|
||||
} catch {
|
||||
return "server";
|
||||
}
|
||||
}
|
||||
return config.command?.split(/[\\/]/).pop() || "server";
|
||||
}
|
||||
|
||||
export async function runWeb(argv: string[]): Promise<number> {
|
||||
const program = new Command();
|
||||
|
||||
|
|
@ -53,7 +73,8 @@ export async function runWeb(argv: string[]): Promise<number> {
|
|||
parseKeyValuePair,
|
||||
{},
|
||||
)
|
||||
.option("--config <path>", "config file path")
|
||||
.option("--catalog <path>", "writable catalog file path")
|
||||
.option("--config <path>", "read-only session config file path")
|
||||
.option("--server <name>", "server name from config file")
|
||||
.option("--transport <type>", "transport type (stdio, sse, http)")
|
||||
.option("--server-url <url>", "server URL for SSE/HTTP transport")
|
||||
|
|
@ -68,6 +89,7 @@ export async function runWeb(argv: string[]): Promise<number> {
|
|||
.parse(preArgs);
|
||||
|
||||
const opts = program.opts() as {
|
||||
catalog?: string;
|
||||
config?: string;
|
||||
server?: string;
|
||||
e?: Record<string, string>;
|
||||
|
|
@ -82,50 +104,139 @@ export async function runWeb(argv: string[]): Promise<number> {
|
|||
const target = [...args, ...postArgs];
|
||||
const isDev = !!opts.dev;
|
||||
|
||||
const hasServerInput =
|
||||
opts.config ||
|
||||
// Catalog source for the web backend (spec: v2_catalog_launch_config.md):
|
||||
// - `--catalog <path>` / MCP_CATALOG_PATH → that file is the active WRITABLE
|
||||
// catalog (CRUD, seed-if-missing, file-watch) — like the default catalog.
|
||||
// - `--config <path>` → a READ-ONLY session file: shown in the UI but never
|
||||
// written, seeded, or migrated (so a foreign config is safe to point at).
|
||||
// - ad-hoc `--server-url` / command target → a one-server READ-ONLY session
|
||||
// held in memory (no file written), with `--header` lifted onto the entry
|
||||
// so the seeded connection actually uses those headers (#1483).
|
||||
// - nothing → default catalog (writable), backend uses its default path.
|
||||
// `initialMcpConfig` stays populated for the ad-hoc case only so the legacy
|
||||
// GET /api/config defaults survive; the catalog path / in-memory list is what
|
||||
// the UI's server list actually reads.
|
||||
const catalogPath = opts.catalog ?? process.env.MCP_CATALOG_PATH;
|
||||
const hasCatalog = !!catalogPath;
|
||||
const hasConfig = !!opts.config;
|
||||
const hasHeaders = !!opts.header && Object.keys(opts.header).length > 0;
|
||||
const hasAdHocServer =
|
||||
target.length > 0 ||
|
||||
opts.serverUrl ||
|
||||
(opts.transport && opts.transport !== "stdio");
|
||||
!!opts.serverUrl ||
|
||||
(!!opts.transport && opts.transport !== "stdio");
|
||||
|
||||
// Reject illegal flag combinations up front so each branch below is clean.
|
||||
const conflict =
|
||||
hasCatalog && hasConfig
|
||||
? "--catalog and --config are mutually exclusive. --catalog is the writable catalog; --config is a read-only session file."
|
||||
: hasCatalog && hasAdHocServer
|
||||
? "--catalog cannot be combined with an ad-hoc server URL/command."
|
||||
: hasCatalog && hasHeaders
|
||||
? "--header cannot be combined with --catalog. Set per-server headers in the catalog file."
|
||||
: hasConfig && hasAdHocServer
|
||||
? "--config cannot be combined with an ad-hoc server URL/command. --config selects a read-only session file."
|
||||
: hasConfig && hasHeaders
|
||||
? "--header cannot be combined with --config. Set per-server headers inside the config file instead."
|
||||
: null;
|
||||
if (conflict) {
|
||||
console.error(`Error: ${conflict}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let initialMcpConfig: MCPServerConfig | null = null;
|
||||
let mcpConfigPath: string | undefined;
|
||||
let writable = true;
|
||||
let initialServers: MCPConfig | null = null;
|
||||
|
||||
if (hasServerInput) {
|
||||
const serverOptions: ServerConfigOptions = {
|
||||
configPath: opts.config,
|
||||
serverName: opts.server,
|
||||
target: target.length > 0 ? target : undefined,
|
||||
transport: opts.transport as "stdio" | "sse" | "http" | undefined,
|
||||
serverUrl: opts.serverUrl,
|
||||
cwd: opts.cwd,
|
||||
env: opts.e,
|
||||
};
|
||||
|
||||
if (opts.header && Object.keys(opts.header).length > 0) {
|
||||
if (hasCatalog) {
|
||||
if (opts.server) {
|
||||
console.warn(
|
||||
"Warning: --header is accepted but initial HTTP headers are configured via server settings in the web UI (post-#1358).",
|
||||
"Note: --server has no effect on the web UI yet; it lists every server in the catalog.",
|
||||
);
|
||||
}
|
||||
|
||||
// A writable catalog may not exist yet — the backend seeds it on first
|
||||
// read, exactly like the default catalog — so we don't pre-validate it.
|
||||
mcpConfigPath = resolve(process.cwd(), catalogPath!);
|
||||
writable = true;
|
||||
} else if (hasConfig) {
|
||||
if (opts.server) {
|
||||
console.warn(
|
||||
"Note: --server has no effect on the web UI yet; it lists every server in the file.",
|
||||
);
|
||||
}
|
||||
const resolvedConfigPath = resolve(process.cwd(), opts.config!);
|
||||
try {
|
||||
const configs = resolveServerConfigs(serverOptions, "single");
|
||||
const config = configs[0];
|
||||
if (!config) {
|
||||
// Validate the file loads (and exists) before serving it: a read-only
|
||||
// session never seeds, so a typo'd path would otherwise show a silently
|
||||
// empty server list instead of a clear error.
|
||||
resolveServerConfigs({ configPath: resolvedConfigPath }, "multi");
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Could not load config file.";
|
||||
console.error("Error:", message);
|
||||
process.exit(1);
|
||||
}
|
||||
mcpConfigPath = resolvedConfigPath;
|
||||
writable = false;
|
||||
} else if (hasAdHocServer) {
|
||||
let config: MCPServerConfig;
|
||||
try {
|
||||
const serverOptions: ServerConfigOptions = {
|
||||
serverName: opts.server,
|
||||
target: target.length > 0 ? target : undefined,
|
||||
transport: opts.transport as "stdio" | "sse" | "http" | undefined,
|
||||
serverUrl: opts.serverUrl,
|
||||
cwd: opts.cwd,
|
||||
env: opts.e,
|
||||
};
|
||||
const resolved = resolveServerConfigs(serverOptions, "single")[0];
|
||||
if (!resolved) {
|
||||
console.error(
|
||||
"Error: Could not resolve server config. Use --config and --server, or pass a command/URL.",
|
||||
"Error: Could not resolve server config. Pass a command/URL, or use --catalog / --config to serve a file.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
initialMcpConfig = ensureStdioCwd(config);
|
||||
config = ensureStdioCwd(resolved);
|
||||
} catch (err) {
|
||||
const message =
|
||||
err instanceof Error ? err.message : "Could not resolve server config.";
|
||||
console.error("Error:", message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (hasHeaders && (config.type === "stdio" || config.type === undefined)) {
|
||||
console.error(
|
||||
"Error: --header only applies to HTTP/SSE servers; stdio servers take no HTTP headers.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
initialMcpConfig = config;
|
||||
|
||||
// In-memory session entry: the SDK config plus the flat `headers` record,
|
||||
// which the backend lifts into `settings.headers` on read. Nothing is
|
||||
// written to disk — the ad-hoc server is a read-only session list.
|
||||
const entry: StoredMCPServer =
|
||||
hasHeaders && config.type !== "stdio" && config.type !== undefined
|
||||
? { ...config, headers: opts.header }
|
||||
: { ...config };
|
||||
initialServers = {
|
||||
mcpServers: { [deriveSeedServerId(config)]: entry },
|
||||
};
|
||||
writable = false;
|
||||
} else if (hasHeaders) {
|
||||
console.error(
|
||||
"Error: --header requires an ad-hoc --server-url or command target.",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const webConfig = buildWebServerConfig({ initialMcpConfig });
|
||||
const webConfig = buildWebServerConfig({
|
||||
initialMcpConfig,
|
||||
mcpConfigPath,
|
||||
writable,
|
||||
initialServers,
|
||||
});
|
||||
if (!isDev) {
|
||||
webConfig.staticRoot = join(__dirname, "..", "dist");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -52,6 +52,9 @@ export async function startHonoServer(
|
|||
authToken: config.dangerouslyOmitAuth ? undefined : resolvedAuthToken,
|
||||
dangerouslyOmitAuth: config.dangerouslyOmitAuth,
|
||||
storageDir: config.storageDir,
|
||||
mcpConfigPath: config.mcpConfigPath,
|
||||
writable: config.writable,
|
||||
initialServers: config.initialServers ?? undefined,
|
||||
allowedOrigins: config.allowedOrigins,
|
||||
sandboxUrl: sandboxController.getUrl() ?? undefined,
|
||||
logger: config.logger,
|
||||
|
|
|
|||
|
|
@ -74,6 +74,9 @@ export function honoMiddlewarePlugin(config: WebServerConfig): Plugin {
|
|||
authToken: config.dangerouslyOmitAuth ? undefined : config.authToken,
|
||||
dangerouslyOmitAuth: config.dangerouslyOmitAuth,
|
||||
storageDir: config.storageDir,
|
||||
mcpConfigPath: config.mcpConfigPath,
|
||||
writable: config.writable,
|
||||
initialServers: config.initialServers ?? undefined,
|
||||
allowedOrigins: config.allowedOrigins,
|
||||
sandboxUrl: sandboxController.getUrl() ?? undefined,
|
||||
logger: config.logger,
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
import pino from "pino";
|
||||
import type { Logger } from "pino";
|
||||
import type { MCPServerConfig } from "../../../core/mcp/types.ts";
|
||||
import type { MCPConfig, MCPServerConfig } from "../../../core/mcp/types.ts";
|
||||
// Import directly from the leaf module — not the `core/mcp/remote/index.ts`
|
||||
// barrel — so Vite's config-time module graph doesn't pull in `createRemoteLogger`
|
||||
// (which references `pino/browser.js`) or other browser-side re-exports that
|
||||
|
|
@ -23,6 +23,28 @@ export interface WebServerConfig {
|
|||
dangerouslyOmitAuth: boolean;
|
||||
/** Single initial MCP server config, or null when no server specified. */
|
||||
initialMcpConfig: MCPServerConfig | null;
|
||||
/**
|
||||
* Absolute path to the `mcp.json` file the backend reads (and writes/watches
|
||||
* when {@link writable}). When undefined the backend falls back to the
|
||||
* default catalog (`~/.mcp-inspector/mcp.json`). Set by the launcher for
|
||||
* `--catalog <path>` (writable) or `--config <path>` (read-only session).
|
||||
* Mutually exclusive with {@link initialServers} (#1481).
|
||||
*/
|
||||
mcpConfigPath: string | undefined;
|
||||
/**
|
||||
* When false, the server list is read-only for the session: the backend
|
||||
* rejects `/api/servers` mutations and never seeds/migrates the file, and
|
||||
* the web UI hides catalog CRUD. True for the default catalog and
|
||||
* `--catalog`; false for `--config` and ad-hoc launches (#1481).
|
||||
*/
|
||||
writable: boolean;
|
||||
/**
|
||||
* In-memory server list served by the backend instead of reading a file —
|
||||
* set by the launcher to seed an ad-hoc `--server-url` / command target
|
||||
* (with `--header`) without writing any file. Implies `writable: false`.
|
||||
* Mutually exclusive with {@link mcpConfigPath} (#1481/#1483).
|
||||
*/
|
||||
initialServers: MCPConfig | null;
|
||||
storageDir: string | undefined;
|
||||
allowedOrigins: string[];
|
||||
/** Sandbox port (0 = dynamic). */
|
||||
|
|
@ -151,6 +173,12 @@ export function printServerBanner(
|
|||
|
||||
export interface BuildWebServerConfigOptions {
|
||||
initialMcpConfig?: MCPServerConfig | null;
|
||||
/** Catalog/session file the backend should serve; see {@link WebServerConfig.mcpConfigPath}. */
|
||||
mcpConfigPath?: string;
|
||||
/** Read-only when false; see {@link WebServerConfig.writable}. Defaults to true. */
|
||||
writable?: boolean;
|
||||
/** In-memory ad-hoc list; see {@link WebServerConfig.initialServers}. */
|
||||
initialServers?: MCPConfig | null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -160,7 +188,12 @@ export interface BuildWebServerConfigOptions {
|
|||
export function buildWebServerConfig(
|
||||
options: BuildWebServerConfigOptions = {},
|
||||
): WebServerConfig {
|
||||
const { initialMcpConfig = null } = options;
|
||||
const {
|
||||
initialMcpConfig = null,
|
||||
mcpConfigPath,
|
||||
writable = true,
|
||||
initialServers = null,
|
||||
} = options;
|
||||
const port = parseInt(process.env.CLIENT_PORT ?? "6274", 10);
|
||||
const hostname = process.env.HOST ?? "localhost";
|
||||
const baseUrl = `http://${hostname}:${port}`;
|
||||
|
|
@ -191,6 +224,9 @@ export function buildWebServerConfig(
|
|||
authToken,
|
||||
dangerouslyOmitAuth,
|
||||
initialMcpConfig,
|
||||
mcpConfigPath,
|
||||
writable,
|
||||
initialServers,
|
||||
storageDir: process.env.MCP_STORAGE_DIR,
|
||||
allowedOrigins: process.env.ALLOWED_ORIGINS?.split(",").filter(Boolean) ?? [
|
||||
baseUrl,
|
||||
|
|
|
|||
|
|
@ -78,6 +78,7 @@ import { useResourceSubscriptions } from "@inspector/core/react/useResourceSubsc
|
|||
import { useMessageLog } from "@inspector/core/react/useMessageLog.js";
|
||||
import { useFetchRequestLog } from "@inspector/core/react/useFetchRequestLog.js";
|
||||
import { useSandboxUrl } from "@inspector/core/react/useSandboxUrl.js";
|
||||
import { useServerListWritable } from "@inspector/core/react/useServerListWritable.js";
|
||||
import { usePendingClientRequests } from "@inspector/core/react/usePendingClientRequests.js";
|
||||
import { InspectorView } from "./components/views/InspectorView/InspectorView";
|
||||
import type {
|
||||
|
|
@ -537,11 +538,16 @@ function App() {
|
|||
// the active client's underlying SDK client so the running view can call the
|
||||
// server, and reads the tool's UI resource into the sandbox on handshake.
|
||||
const appRendererRef = useRef<AppRendererHandle>(null);
|
||||
const configBaseUrl =
|
||||
typeof window !== "undefined" ? window.location.origin : "http://localhost";
|
||||
const { sandboxUrl } = useSandboxUrl({
|
||||
baseUrl:
|
||||
typeof window !== "undefined"
|
||||
? window.location.origin
|
||||
: "http://localhost",
|
||||
baseUrl: configBaseUrl,
|
||||
authToken: getAuthToken(),
|
||||
});
|
||||
// Read-only sessions (launched with `--config` or an ad-hoc server) hide
|
||||
// catalog CRUD; the default catalog and `--catalog` stay writable.
|
||||
const { writable: serverListWritable } = useServerListWritable({
|
||||
baseUrl: configBaseUrl,
|
||||
authToken: getAuthToken(),
|
||||
});
|
||||
const sandboxBridgeFactory = useMemo(
|
||||
|
|
@ -2353,6 +2359,7 @@ function App() {
|
|||
<>
|
||||
<InspectorView
|
||||
servers={servers}
|
||||
serverListWritable={serverListWritable}
|
||||
activeServer={activeServerId}
|
||||
connectionStatus={connectionStatus}
|
||||
initializeResult={initializeResult}
|
||||
|
|
|
|||
|
|
@ -247,4 +247,34 @@ describe("ServerCard", () => {
|
|||
Node.DOCUMENT_POSITION_FOLLOWING,
|
||||
);
|
||||
});
|
||||
|
||||
describe("read-only (writable=false)", () => {
|
||||
it("hides Clone/Edit/Remove/Settings but keeps connect + Connection Info", () => {
|
||||
renderWithMantine(<ServerCard {...baseProps} writable={false} />);
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Clone" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Edit" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Remove" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Settings" }),
|
||||
).not.toBeInTheDocument();
|
||||
// connection === connected, so Connection Info stays available.
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Connection Info" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows mutation actions when writable (default)", () => {
|
||||
renderWithMantine(<ServerCard {...baseProps} />);
|
||||
expect(screen.getByRole("button", { name: "Edit" })).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole("button", { name: "Settings" }),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -19,6 +19,12 @@ export interface ServerCardProps extends ServerEntry {
|
|||
onClone: (id: string) => void;
|
||||
onRemove: (id: string) => void;
|
||||
compact?: boolean;
|
||||
/**
|
||||
* When false (read-only session), the catalog mutation actions
|
||||
* (Clone / Edit / Remove / Settings) are hidden; connect and Connection Info
|
||||
* remain. Defaults to true.
|
||||
*/
|
||||
writable?: boolean;
|
||||
/**
|
||||
* Optional drag-handle affordance rendered at the start of the card header,
|
||||
* before the server name. Supplied by the sortable wrapper
|
||||
|
|
@ -112,6 +118,7 @@ export function ServerCard({
|
|||
onClone,
|
||||
onRemove,
|
||||
compact = false,
|
||||
writable = true,
|
||||
dragHandle,
|
||||
}: ServerCardProps) {
|
||||
const isDimmed = activeServer !== undefined && activeServer !== id;
|
||||
|
|
@ -165,9 +172,17 @@ export function ServerCard({
|
|||
|
||||
<Group justify="space-between">
|
||||
<ActionsRow>
|
||||
<SubtleButton onClick={() => onClone(id)}>Clone</SubtleButton>
|
||||
<SubtleButton onClick={() => onEdit(id)}>Edit</SubtleButton>
|
||||
<RemoveButton onClick={() => onRemove(id)}>Remove</RemoveButton>
|
||||
{writable && (
|
||||
<>
|
||||
<SubtleButton onClick={() => onClone(id)}>
|
||||
Clone
|
||||
</SubtleButton>
|
||||
<SubtleButton onClick={() => onEdit(id)}>Edit</SubtleButton>
|
||||
<RemoveButton onClick={() => onRemove(id)}>
|
||||
Remove
|
||||
</RemoveButton>
|
||||
</>
|
||||
)}
|
||||
</ActionsRow>
|
||||
<ActionsRow>
|
||||
{connection.status === "connected" && (
|
||||
|
|
@ -175,9 +190,11 @@ export function ServerCard({
|
|||
Connection Info
|
||||
</SubtleButton>
|
||||
)}
|
||||
<SubtleButton onClick={() => onSettings(id)}>
|
||||
Settings
|
||||
</SubtleButton>
|
||||
{writable && (
|
||||
<SubtleButton onClick={() => onSettings(id)}>
|
||||
Settings
|
||||
</SubtleButton>
|
||||
)}
|
||||
</ActionsRow>
|
||||
</Group>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ export interface ServerListControlsProps extends AddServerMenuProps {
|
|||
onToggleList: () => void;
|
||||
/** Download the current server list as a canonical `mcp.json` file. */
|
||||
onExport: () => void;
|
||||
/** When false (read-only session), the Add menu is hidden. Defaults to true. */
|
||||
writable?: boolean;
|
||||
}
|
||||
|
||||
export function ServerListControls({
|
||||
|
|
@ -21,6 +23,7 @@ export function ServerListControls({
|
|||
onImportConfig,
|
||||
onImportServerJson,
|
||||
onExport,
|
||||
writable = true,
|
||||
}: ServerListControlsProps) {
|
||||
return (
|
||||
<Group justify="flex-end">
|
||||
|
|
@ -30,11 +33,13 @@ export function ServerListControls({
|
|||
<Button variant="default" onClick={onExport} disabled={serverCount === 0}>
|
||||
Export
|
||||
</Button>
|
||||
<ServerAddMenu
|
||||
onAddManually={onAddManually}
|
||||
onImportConfig={onImportConfig}
|
||||
onImportServerJson={onImportServerJson}
|
||||
/>
|
||||
{writable && (
|
||||
<ServerAddMenu
|
||||
onAddManually={onAddManually}
|
||||
onImportConfig={onImportConfig}
|
||||
onImportServerJson={onImportServerJson}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -91,4 +91,48 @@ describe("ServerListScreen", () => {
|
|||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("read-only session (writable=false)", () => {
|
||||
it("shows the read-only banner", () => {
|
||||
renderWithMantine(<ServerListScreen {...baseProps} writable={false} />);
|
||||
expect(screen.getByText("Read-only session")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides the Add menu and per-card mutation actions", () => {
|
||||
renderWithMantine(<ServerListScreen {...baseProps} writable={false} />);
|
||||
// Cards still render and connect controls remain.
|
||||
expect(screen.getByText("Alpha")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /add servers/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Edit" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Remove" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Clone" }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole("button", { name: "Settings" }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("omits drag handles even when onReorder is provided", () => {
|
||||
renderWithMantine(<ServerListScreen {...baseProps} writable={false} />);
|
||||
expect(
|
||||
screen.queryByRole("button", { name: /^Reorder / }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the Add menu and actions when writable (default)", () => {
|
||||
renderWithMantine(<ServerListScreen {...baseProps} />);
|
||||
expect(
|
||||
screen.getByRole("button", { name: /add servers/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getAllByRole("button", { name: "Edit" }).length).toBe(2);
|
||||
expect(screen.queryByText("Read-only session")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,11 @@
|
|||
import { ScrollArea, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import {
|
||||
Alert,
|
||||
Code,
|
||||
ScrollArea,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
Text,
|
||||
} from "@mantine/core";
|
||||
import {
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
|
|
@ -23,6 +30,13 @@ import {
|
|||
|
||||
export interface ServerListScreenProps {
|
||||
servers: ServerEntry[];
|
||||
/**
|
||||
* Whether the server list is writable (catalog) or read-only (a `--config`
|
||||
* session file / ad-hoc launch). When false, all catalog mutation controls
|
||||
* (add, edit, clone, remove, reorder, settings) are hidden and a read-only
|
||||
* banner is shown. Defaults to true.
|
||||
*/
|
||||
writable?: boolean;
|
||||
/** Id of the server the wiring layer treats as active (drives card dimming). */
|
||||
activeServer?: string;
|
||||
onAddManually: () => void;
|
||||
|
|
@ -57,6 +71,7 @@ const EmptyState = Text.withProps({
|
|||
|
||||
export function ServerListScreen({
|
||||
servers,
|
||||
writable = true,
|
||||
activeServer,
|
||||
onAddManually,
|
||||
onImportConfig,
|
||||
|
|
@ -81,11 +96,12 @@ export function ServerListScreen({
|
|||
|
||||
const ids = servers.map((s) => s.id);
|
||||
|
||||
// `reorderable` only when a persistence callback is wired. Without it we
|
||||
// render plain `ServerCard`s (no grip, no DndContext) so the screen stays
|
||||
// usable as a pure display — the SortableServerCard's grip would otherwise
|
||||
// be a dead affordance.
|
||||
const reorderable = onReorder !== undefined;
|
||||
// `reorderable` only when a persistence callback is wired AND the list is
|
||||
// writable. Without it we render plain `ServerCard`s (no grip, no DndContext)
|
||||
// so the screen stays usable as a pure display — the SortableServerCard's
|
||||
// grip would otherwise be a dead affordance (and reorder is a catalog write
|
||||
// the backend rejects in a read-only session).
|
||||
const reorderable = onReorder !== undefined && writable;
|
||||
|
||||
// Built only when reorderable — the drag-end handler and the fresh
|
||||
// announcements object (four closures) are otherwise allocated every render
|
||||
|
|
@ -99,6 +115,7 @@ export function ServerListScreen({
|
|||
|
||||
const cardProps = (server: ServerEntry) => ({
|
||||
compact,
|
||||
writable,
|
||||
activeServer,
|
||||
onToggleConnection,
|
||||
onConnectionInfo,
|
||||
|
|
@ -127,9 +144,17 @@ export function ServerListScreen({
|
|||
|
||||
return (
|
||||
<PageContainer>
|
||||
{!writable && (
|
||||
<Alert color="gray" variant="light" title="Read-only session">
|
||||
This server list was launched with <Code>--config</Code> or an ad-hoc
|
||||
server and can't be edited here. Changes won't be saved. Use{" "}
|
||||
<Code>--catalog</Code> (or no flag) to manage a writable catalog.
|
||||
</Alert>
|
||||
)}
|
||||
<ServerListControls
|
||||
serverCount={servers.length}
|
||||
compact={compact}
|
||||
writable={writable}
|
||||
onToggleList={onToggleCompact}
|
||||
onAddManually={onAddManually}
|
||||
onImportConfig={onImportConfig}
|
||||
|
|
|
|||
|
|
@ -188,6 +188,12 @@ export interface InspectorViewProps {
|
|||
// Server list (static config; runtime connection state comes from the
|
||||
// separate fields below and is merged into each card by this component).
|
||||
servers: ServerEntry[];
|
||||
/**
|
||||
* Whether the server list is writable (catalog) or read-only (a `--config`
|
||||
* session file / ad-hoc launch). When false, the Servers screen hides all
|
||||
* catalog mutation controls. Defaults to true.
|
||||
*/
|
||||
serverListWritable?: boolean;
|
||||
|
||||
// Connection state — driven by the parent via `useInspectorClient`.
|
||||
activeServer?: string;
|
||||
|
|
@ -349,6 +355,7 @@ export interface InspectorViewProps {
|
|||
|
||||
export function InspectorView({
|
||||
servers: serversInput,
|
||||
serverListWritable = true,
|
||||
activeServer,
|
||||
connectionStatus,
|
||||
initializeResult,
|
||||
|
|
@ -590,6 +597,7 @@ export function InspectorView({
|
|||
<ScreenStage active={activeTab === SERVERS_TAB}>
|
||||
<ServerListScreen
|
||||
servers={servers}
|
||||
writable={serverListWritable}
|
||||
activeServer={activeServer}
|
||||
onAddManually={onServerAdd}
|
||||
onImportConfig={onServerImportConfig}
|
||||
|
|
|
|||
105
clients/web/src/test/core/react/useServerListWritable.test.tsx
Normal file
105
clients/web/src/test/core/react/useServerListWritable.test.tsx
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
/**
|
||||
* Tests for useServerListWritable — runs in happy-dom under the unit project.
|
||||
* Uses a controlled fake `fetch` so each branch (writable / read-only / absent
|
||||
* field / HTTP error / network throw) and the auth header are asserted directly.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { useServerListWritable } from "@inspector/core/react/useServerListWritable";
|
||||
|
||||
function jsonResponse(body: unknown, ok = true): Response {
|
||||
return {
|
||||
ok,
|
||||
status: ok ? 200 : 401,
|
||||
json: async () => body,
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
describe("useServerListWritable", () => {
|
||||
it("defaults to writable while loading, then keeps true for a writable session", async () => {
|
||||
const fetchFn = vi.fn().mockResolvedValue(jsonResponse({ writable: true }));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useServerListWritable({ baseUrl: "http://test.local", fetchFn }),
|
||||
);
|
||||
|
||||
expect(result.current.loading).toBe(true);
|
||||
expect(result.current.writable).toBe(true);
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.writable).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves writable:false for a read-only session", async () => {
|
||||
const fetchFn = vi
|
||||
.fn()
|
||||
.mockResolvedValue(jsonResponse({ writable: false }));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useServerListWritable({ baseUrl: "http://test.local", fetchFn }),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.writable).toBe(false);
|
||||
});
|
||||
|
||||
it("stays writable when the field is absent (legacy backend)", async () => {
|
||||
const fetchFn = vi.fn().mockResolvedValue(jsonResponse({}));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useServerListWritable({ baseUrl: "http://test.local", fetchFn }),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.writable).toBe(true);
|
||||
});
|
||||
|
||||
it("sends the bearer auth header when a token is provided", async () => {
|
||||
const fetchFn = vi
|
||||
.fn()
|
||||
.mockResolvedValue(jsonResponse({ writable: false }));
|
||||
|
||||
renderHook(() =>
|
||||
useServerListWritable({
|
||||
baseUrl: "http://test.local/",
|
||||
authToken: "secret-token",
|
||||
fetchFn,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(fetchFn).toHaveBeenCalled());
|
||||
const [url, init] = fetchFn.mock.calls[0] as [string, RequestInit];
|
||||
// Trailing slash on baseUrl is trimmed.
|
||||
expect(url).toBe("http://test.local/api/config");
|
||||
expect((init.headers as Record<string, string>)["x-mcp-remote-auth"]).toBe(
|
||||
"Bearer secret-token",
|
||||
);
|
||||
});
|
||||
|
||||
it("stays writable on an HTTP error", async () => {
|
||||
const fetchFn = vi
|
||||
.fn()
|
||||
.mockResolvedValue(jsonResponse({ writable: false }, false));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useServerListWritable({ baseUrl: "http://test.local", fetchFn }),
|
||||
);
|
||||
|
||||
// An !ok response is ignored (the body is never read), so the writable
|
||||
// default survives even though loading still settles via `finally`.
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.writable).toBe(true);
|
||||
});
|
||||
|
||||
it("stays writable when fetch throws", async () => {
|
||||
const fetchFn = vi.fn().mockRejectedValue(new Error("network down"));
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useServerListWritable({ baseUrl: "http://test.local", fetchFn }),
|
||||
);
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.writable).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -55,4 +55,29 @@ describe("createRemoteApp GET /api/config", () => {
|
|||
expect(data.defaultCwd).toBe("/tmp");
|
||||
expect(data.defaultEnvironment).toEqual({ PATH: "/usr/bin" });
|
||||
});
|
||||
|
||||
it("reports writable:true by default and writable:false when set", async () => {
|
||||
const writableApp = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
}).app;
|
||||
const writableRes = await writableApp.request(
|
||||
new Request("http://test/api/config"),
|
||||
);
|
||||
expect(
|
||||
((await writableRes.json()) as { writable?: boolean }).writable,
|
||||
).toBe(true);
|
||||
|
||||
const readOnlyApp = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
writable: false,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
}).app;
|
||||
const readOnlyRes = await readOnlyApp.request(
|
||||
new Request("http://test/api/config"),
|
||||
);
|
||||
expect(
|
||||
((await readOnlyRes.json()) as { writable?: boolean }).writable,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -386,3 +386,57 @@ describe("GET /api/servers/events", () => {
|
|||
sink2.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/servers/events (in-memory ad-hoc session)", () => {
|
||||
let h: Harness;
|
||||
|
||||
beforeEach(async () => {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "inspector-events-mem-"));
|
||||
const configPath = join(tempDir, "mcp.json");
|
||||
const { app, close: closeApi } = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
mcpConfigPath: configPath,
|
||||
writable: false,
|
||||
initialServers: {
|
||||
mcpServers: { srv: { type: "stdio", command: "node" } },
|
||||
},
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
secretStore: new InMemorySecretStore(),
|
||||
});
|
||||
const { baseUrl, server } = await new Promise<{
|
||||
baseUrl: string;
|
||||
server: ServerType;
|
||||
}>((resolve, reject) => {
|
||||
const s = serve(
|
||||
{ fetch: app.fetch, port: 0, hostname: "127.0.0.1" },
|
||||
(info) => {
|
||||
const port =
|
||||
info && typeof info === "object" && "port" in info
|
||||
? (info as { port: number }).port
|
||||
: 0;
|
||||
resolve({ baseUrl: `http://127.0.0.1:${port}`, server: s });
|
||||
},
|
||||
);
|
||||
s.on("error", reject);
|
||||
});
|
||||
h = { baseUrl, server, configPath, tempDir, closeApi };
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await teardown(h);
|
||||
});
|
||||
|
||||
it("opens the stream but never broadcasts (no watcher, nothing to watch)", async () => {
|
||||
const sink = await subscribe(h.baseUrl); // 200 + open stream or it throws
|
||||
// Writing to the (unwatched) config path must not produce any event.
|
||||
writeFileSync(
|
||||
h.configPath,
|
||||
JSON.stringify({
|
||||
mcpServers: { other: { type: "stdio", command: "x" } },
|
||||
}),
|
||||
);
|
||||
await expect(sink.waitFor(1, 400)).rejects.toThrow(/Timed out/);
|
||||
expect(sink.events).toHaveLength(0);
|
||||
sink.close();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1845,3 +1845,214 @@ describe("/api/servers routes", () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/servers read-only sessions (#1481/#1483)", () => {
|
||||
interface RoHarness {
|
||||
baseUrl: string;
|
||||
server: ServerType;
|
||||
tempDir: string;
|
||||
configPath: string;
|
||||
}
|
||||
|
||||
async function listen(app: {
|
||||
fetch: (req: Request) => Response | Promise<Response>;
|
||||
}): Promise<{ baseUrl: string; server: ServerType }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = serve(
|
||||
{ fetch: app.fetch, port: 0, hostname: "127.0.0.1" },
|
||||
(info) => {
|
||||
const port =
|
||||
info && typeof info === "object" && "port" in info
|
||||
? (info as { port: number }).port
|
||||
: 0;
|
||||
resolve({ baseUrl: `http://127.0.0.1:${port}`, server });
|
||||
},
|
||||
);
|
||||
server.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function close(h: RoHarness): Promise<void> {
|
||||
await new Promise<void>((r) => h.server.close(() => r()));
|
||||
try {
|
||||
rmSync(h.tempDir, { recursive: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/** Read-only session backed by a `--config`-style file. */
|
||||
async function setupReadOnlyFile(contents?: string): Promise<RoHarness> {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "inspector-ro-file-"));
|
||||
const configPath = join(tempDir, "mcp.json");
|
||||
if (contents !== undefined) writeFileSync(configPath, contents);
|
||||
const { app } = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
mcpConfigPath: configPath,
|
||||
writable: false,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
secretStore: new InMemorySecretStore(),
|
||||
});
|
||||
const { baseUrl, server } = await listen(app);
|
||||
return { baseUrl, server, tempDir, configPath };
|
||||
}
|
||||
|
||||
/** Read-only session backed by an in-memory ad-hoc list (no file). */
|
||||
async function setupInMemory(servers: MCPConfig): Promise<RoHarness> {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), "inspector-ro-mem-"));
|
||||
const configPath = join(tempDir, "mcp.json");
|
||||
const { app } = createRemoteApp({
|
||||
dangerouslyOmitAuth: true,
|
||||
// mcpConfigPath points at a path that must NEVER be touched.
|
||||
mcpConfigPath: configPath,
|
||||
writable: false,
|
||||
initialServers: servers,
|
||||
initialConfig: { defaultEnvironment: {} },
|
||||
secretStore: new InMemorySecretStore(),
|
||||
});
|
||||
const { baseUrl, server } = await listen(app);
|
||||
return { baseUrl, server, tempDir, configPath };
|
||||
}
|
||||
|
||||
const jsonHeaders = { "Content-Type": "application/json" };
|
||||
|
||||
it("rejects every mutation with 403 and leaves the file untouched", async () => {
|
||||
const original = JSON.stringify(
|
||||
{ mcpServers: { api: { type: "stdio", command: "node" } } },
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const h = await setupReadOnlyFile(original);
|
||||
try {
|
||||
const mutations: Array<{ method: string; path: string; body: unknown }> =
|
||||
[
|
||||
{
|
||||
method: "POST",
|
||||
path: "/api/servers",
|
||||
body: { id: "new", config: { type: "stdio", command: "x" } },
|
||||
},
|
||||
{
|
||||
method: "PUT",
|
||||
path: "/api/servers/api",
|
||||
body: { config: { type: "stdio", command: "y" } },
|
||||
},
|
||||
{
|
||||
method: "PUT",
|
||||
path: "/api/servers/order",
|
||||
body: { order: ["api"] },
|
||||
},
|
||||
{ method: "DELETE", path: "/api/servers/api", body: undefined },
|
||||
];
|
||||
for (const m of mutations) {
|
||||
const res = await fetch(`${h.baseUrl}${m.path}`, {
|
||||
method: m.method,
|
||||
headers: m.body ? jsonHeaders : undefined,
|
||||
body: m.body ? JSON.stringify(m.body) : undefined,
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
const body = (await res.json()) as { error?: string };
|
||||
expect(body.error).toMatch(/read-only/i);
|
||||
}
|
||||
// The file is byte-for-byte unchanged.
|
||||
expect(readFileSync(h.configPath, "utf-8")).toBe(original);
|
||||
} finally {
|
||||
await close(h);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns 403 (not 404) for a mutation on a missing id — no existence leak", async () => {
|
||||
const h = await setupReadOnlyFile(
|
||||
JSON.stringify({ mcpServers: {} }, null, 2),
|
||||
);
|
||||
try {
|
||||
const res = await fetch(`${h.baseUrl}/api/servers/ghost`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
expect(res.status).toBe(403);
|
||||
} finally {
|
||||
await close(h);
|
||||
}
|
||||
});
|
||||
|
||||
it("serves a read-only file as-is and never seeds when the file is missing", async () => {
|
||||
const h = await setupReadOnlyFile(); // no file written
|
||||
try {
|
||||
const res = await fetch(`${h.baseUrl}/api/servers`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ mcpServers: {} });
|
||||
// No seed write happened.
|
||||
expect(existsSync(h.configPath)).toBe(false);
|
||||
} finally {
|
||||
await close(h);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not migrate on-disk plaintext secrets on read (file bytes stable)", async () => {
|
||||
// A foreign config with a plaintext stdio env value that the writable path
|
||||
// would migrate into the keychain (a write). Read-only must leave it be.
|
||||
const original = JSON.stringify(
|
||||
{
|
||||
mcpServers: {
|
||||
api: {
|
||||
type: "stdio",
|
||||
command: "node",
|
||||
env: { API_KEY: "plaintext-secret" },
|
||||
},
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
const h = await setupReadOnlyFile(original);
|
||||
try {
|
||||
const res = await fetch(`${h.baseUrl}/api/servers`);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as MCPConfig;
|
||||
// Plaintext flows straight back (no keychain swap) and disk is untouched.
|
||||
expect(
|
||||
(body.mcpServers.api as { env?: Record<string, string> }).env?.API_KEY,
|
||||
).toBe("plaintext-secret");
|
||||
expect(readFileSync(h.configPath, "utf-8")).toBe(original);
|
||||
} finally {
|
||||
await close(h);
|
||||
}
|
||||
});
|
||||
|
||||
it("serves an in-memory ad-hoc list (with lifted headers) and writes no file", async () => {
|
||||
const h = await setupInMemory({
|
||||
mcpServers: {
|
||||
"example.com": {
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
headers: { Authorization: "Bearer x" },
|
||||
},
|
||||
},
|
||||
});
|
||||
try {
|
||||
const res = await fetch(`${h.baseUrl}/api/servers`);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as MCPConfig;
|
||||
expect(body.mcpServers["example.com"]).toMatchObject({
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
headers: { Authorization: "Bearer x" },
|
||||
});
|
||||
// The configPath must never be created for an in-memory session.
|
||||
expect(existsSync(h.configPath)).toBe(false);
|
||||
|
||||
// Mutations are still rejected.
|
||||
const post = await fetch(`${h.baseUrl}/api/servers`, {
|
||||
method: "POST",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify({
|
||||
id: "x",
|
||||
config: { type: "stdio", command: "n" },
|
||||
}),
|
||||
});
|
||||
expect(post.status).toBe(403);
|
||||
expect(existsSync(h.configPath)).toBe(false);
|
||||
} finally {
|
||||
await close(h);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { mkdtemp, writeFile, rm } from "node:fs/promises";
|
||||
import { existsSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
|
|
@ -32,6 +33,7 @@ describe("runWeb", () => {
|
|||
let originalError: typeof console.error;
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>;
|
||||
let exitCode: number | undefined;
|
||||
let catalogEnvSnapshot: string | undefined;
|
||||
const signalHandlers = new Map<string, () => void>();
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -40,6 +42,8 @@ describe("runWeb", () => {
|
|||
mockClose.mockClear();
|
||||
signalHandlers.clear();
|
||||
exitCode = undefined;
|
||||
catalogEnvSnapshot = process.env.MCP_CATALOG_PATH;
|
||||
delete process.env.MCP_CATALOG_PATH;
|
||||
|
||||
logLines = [];
|
||||
warnLines = [];
|
||||
|
|
@ -79,6 +83,11 @@ describe("runWeb", () => {
|
|||
console.error = originalError;
|
||||
exitSpy.mockRestore();
|
||||
vi.restoreAllMocks();
|
||||
if (catalogEnvSnapshot === undefined) {
|
||||
delete process.env.MCP_CATALOG_PATH;
|
||||
} else {
|
||||
process.env.MCP_CATALOG_PATH = catalogEnvSnapshot;
|
||||
}
|
||||
});
|
||||
|
||||
async function expectServerStarted(
|
||||
|
|
@ -87,12 +96,29 @@ describe("runWeb", () => {
|
|||
await vi.waitFor(() => expect(starter).toHaveBeenCalledTimes(1));
|
||||
}
|
||||
|
||||
it("starts Hono in production mode with no server args", async () => {
|
||||
/** The single entry of a synthesized in-memory ad-hoc catalog. */
|
||||
function soleSeededEntry(): Record<string, unknown> {
|
||||
const initialServers = startHonoServer.mock.calls[0]?.[0]
|
||||
?.initialServers as {
|
||||
mcpServers: Record<string, Record<string, unknown>>;
|
||||
} | null;
|
||||
expect(initialServers).toBeTruthy();
|
||||
const entries = Object.values(initialServers!.mcpServers);
|
||||
expect(entries).toHaveLength(1);
|
||||
return entries[0]!;
|
||||
}
|
||||
|
||||
it("starts Hono in production mode with no server args (writable default catalog)", async () => {
|
||||
void runWeb(["node", "run-web"]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ initialMcpConfig: null }),
|
||||
expect.objectContaining({
|
||||
initialMcpConfig: null,
|
||||
mcpConfigPath: undefined,
|
||||
writable: true,
|
||||
initialServers: null,
|
||||
}),
|
||||
);
|
||||
expect(startHonoServer.mock.calls[0]?.[0]?.staticRoot).toMatch(/dist$/);
|
||||
expect(logLines.some((l) => l.includes("Starting MCP inspector..."))).toBe(
|
||||
|
|
@ -105,12 +131,14 @@ describe("runWeb", () => {
|
|||
await expectServerStarted(startViteDevServer);
|
||||
|
||||
expect(startViteDevServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ initialMcpConfig: null }),
|
||||
expect.objectContaining({ initialMcpConfig: null, writable: true }),
|
||||
);
|
||||
expect(logLines.some((l) => l.includes("development mode"))).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves an ad-hoc HTTP URL into initialMcpConfig", async () => {
|
||||
// --- ad-hoc launch → read-only in-memory session ------------------------
|
||||
|
||||
it("seeds an ad-hoc HTTP URL into an in-memory read-only session", async () => {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
|
|
@ -122,12 +150,18 @@ describe("runWeb", () => {
|
|||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
writable: false,
|
||||
mcpConfigPath: undefined,
|
||||
initialMcpConfig: expect.objectContaining({
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(soleSeededEntry()).toMatchObject({
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
});
|
||||
});
|
||||
|
||||
it("appends positional args after -- to the ad-hoc target", async () => {
|
||||
|
|
@ -141,21 +175,30 @@ describe("runWeb", () => {
|
|||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
initialMcpConfig: expect.objectContaining({
|
||||
url: "https://example.com/mcp",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(soleSeededEntry()).toMatchObject({
|
||||
url: "https://example.com/mcp",
|
||||
});
|
||||
});
|
||||
|
||||
it("resolves --server-url without a positional target", async () => {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"--server-url",
|
||||
"https://example.com/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(soleSeededEntry()).toMatchObject({ url: "https://example.com/mcp" });
|
||||
});
|
||||
|
||||
it("fills stdio cwd when omitted", async () => {
|
||||
void runWeb(["node", "run-web", "node", "server.js"]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
const config = startHonoServer.mock.calls[0]?.[0]?.initialMcpConfig;
|
||||
expect(config).toMatchObject({
|
||||
expect(soleSeededEntry()).toMatchObject({
|
||||
type: "stdio",
|
||||
command: "node",
|
||||
args: ["server.js"],
|
||||
|
|
@ -163,7 +206,21 @@ describe("runWeb", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("warns when --header is passed", async () => {
|
||||
it("preserves an explicit --cwd for an ad-hoc stdio server", async () => {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"--cwd",
|
||||
"/custom/cwd",
|
||||
"node",
|
||||
"server.js",
|
||||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(soleSeededEntry()).toMatchObject({ cwd: "/custom/cwd" });
|
||||
});
|
||||
|
||||
it("plumbs --header onto the seeded ad-hoc server (no warning)", async () => {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
|
|
@ -175,22 +232,190 @@ describe("runWeb", () => {
|
|||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
// No silent no-op warning anymore — the header is applied.
|
||||
expect(warnLines.some((l) => l.includes("--header"))).toBe(false);
|
||||
expect(soleSeededEntry()).toMatchObject({
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
headers: { Authorization: "Bearer x" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects --header for a stdio ad-hoc server", async () => {
|
||||
await expect(
|
||||
runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"node",
|
||||
"server.js",
|
||||
"--header",
|
||||
"Authorization: Bearer x",
|
||||
]),
|
||||
).rejects.toThrow("process.exit:1");
|
||||
expect(
|
||||
warnLines.some((l) => l.includes("Warning: --header is accepted")),
|
||||
errorLines.some((l) => l.includes("--header only applies to HTTP/SSE")),
|
||||
).toBe(true);
|
||||
expect(startHonoServer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects --header with no ad-hoc server to attach it to", async () => {
|
||||
await expect(
|
||||
runWeb(["node", "run-web", "--header", "Authorization: Bearer x"]),
|
||||
).rejects.toThrow("process.exit:1");
|
||||
expect(
|
||||
errorLines.some((l) => l.includes("--header requires an ad-hoc")),
|
||||
).toBe(true);
|
||||
expect(startHonoServer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("exits when an ad-hoc config resolves to no entries", async () => {
|
||||
vi.spyOn(nodeConfig, "resolveServerConfigs").mockReturnValueOnce([]);
|
||||
|
||||
await expect(
|
||||
runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"https://example.com/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
]),
|
||||
).rejects.toThrow("process.exit:1");
|
||||
expect(
|
||||
errorLines.some((l) => l.includes("Could not resolve server config")),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("loads a named server from a config file", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-test-"));
|
||||
// --- --catalog → writable catalog ---------------------------------------
|
||||
|
||||
it("points the backend at a writable catalog with --catalog", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-catalog-"));
|
||||
const catalogPath = join(dir, "mcp.json");
|
||||
await writeFile(
|
||||
catalogPath,
|
||||
JSON.stringify({
|
||||
mcpServers: {
|
||||
api: { type: "streamable-http", url: "https://example.com/mcp" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
void runWeb(["node", "run-web", "--catalog", catalogPath]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mcpConfigPath: catalogPath,
|
||||
writable: true,
|
||||
initialMcpConfig: null,
|
||||
initialServers: null,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts a non-existent --catalog path (backend seeds it)", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-catalog-"));
|
||||
const catalogPath = join(dir, "does-not-exist-yet.json");
|
||||
|
||||
try {
|
||||
void runWeb(["node", "run-web", "--catalog", catalogPath]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer.mock.calls[0]?.[0]).toMatchObject({
|
||||
mcpConfigPath: catalogPath,
|
||||
writable: true,
|
||||
});
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reads MCP_CATALOG_PATH as the catalog when --catalog is absent", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-catalog-"));
|
||||
const catalogPath = join(dir, "mcp.json");
|
||||
await writeFile(catalogPath, JSON.stringify({ mcpServers: {} }));
|
||||
process.env.MCP_CATALOG_PATH = catalogPath;
|
||||
|
||||
try {
|
||||
void runWeb(["node", "run-web"]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer.mock.calls[0]?.[0]).toMatchObject({
|
||||
mcpConfigPath: catalogPath,
|
||||
writable: true,
|
||||
});
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("notes that --server is ignored alongside --catalog", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-catalog-"));
|
||||
const catalogPath = join(dir, "mcp.json");
|
||||
await writeFile(catalogPath, JSON.stringify({ mcpServers: {} }));
|
||||
|
||||
try {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"--catalog",
|
||||
catalogPath,
|
||||
"--server",
|
||||
"api",
|
||||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(warnLines.some((l) => l.includes("--server has no effect"))).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// --- --config → read-only session file ----------------------------------
|
||||
|
||||
it("serves a --config file as a read-only session", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-config-"));
|
||||
const configPath = join(dir, "mcp.json");
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({
|
||||
mcpServers: {
|
||||
api: {
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
},
|
||||
api: { type: "streamable-http", url: "https://example.com/mcp" },
|
||||
other: { type: "sse", url: "https://example.com/sse" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
void runWeb(["node", "run-web", "--config", configPath]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
mcpConfigPath: configPath,
|
||||
writable: false,
|
||||
initialMcpConfig: null,
|
||||
initialServers: null,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("notes that --server is ignored alongside --config", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-config-"));
|
||||
const configPath = join(dir, "mcp.json");
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({
|
||||
mcpServers: {
|
||||
api: { type: "streamable-http", url: "https://example.com/mcp" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
|
@ -206,20 +431,15 @@ describe("runWeb", () => {
|
|||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
initialMcpConfig: expect.objectContaining({
|
||||
type: "streamable-http",
|
||||
url: "https://example.com/mcp",
|
||||
}),
|
||||
}),
|
||||
expect(warnLines.some((l) => l.includes("--server has no effect"))).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("exits when server config resolution fails", async () => {
|
||||
it("exits when the --config file cannot be loaded", async () => {
|
||||
await expect(
|
||||
runWeb(["node", "run-web", "--config", "/no/such/file.json"]),
|
||||
).rejects.toThrow("process.exit:1");
|
||||
|
|
@ -227,6 +447,58 @@ describe("runWeb", () => {
|
|||
expect(startHonoServer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// --- conflict matrix ----------------------------------------------------
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "--catalog + --config",
|
||||
argv: ["--catalog", "/a.json", "--config", "/b.json"],
|
||||
match: "mutually exclusive",
|
||||
},
|
||||
{
|
||||
name: "--catalog + ad-hoc",
|
||||
argv: [
|
||||
"--catalog",
|
||||
"/a.json",
|
||||
"--server-url",
|
||||
"https://x/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
],
|
||||
match: "--catalog cannot be combined with an ad-hoc",
|
||||
},
|
||||
{
|
||||
name: "--catalog + --header",
|
||||
argv: ["--catalog", "/a.json", "--header", "Authorization: Bearer x"],
|
||||
match: "--header cannot be combined with --catalog",
|
||||
},
|
||||
{
|
||||
name: "--config + ad-hoc",
|
||||
argv: [
|
||||
"--config",
|
||||
"/a.json",
|
||||
"--server-url",
|
||||
"https://x/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
],
|
||||
match: "--config cannot be combined with an ad-hoc",
|
||||
},
|
||||
{
|
||||
name: "--config + --header",
|
||||
argv: ["--config", "/a.json", "--header", "Authorization: Bearer x"],
|
||||
match: "--header cannot be combined with --config",
|
||||
},
|
||||
])("rejects $name", async ({ argv, match }) => {
|
||||
await expect(runWeb(["node", "run-web", ...argv])).rejects.toThrow(
|
||||
"process.exit:1",
|
||||
);
|
||||
expect(errorLines.some((l) => l.includes(match))).toBe(true);
|
||||
expect(startHonoServer).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// --- lifecycle ----------------------------------------------------------
|
||||
|
||||
it("exits when the web server fails to start", async () => {
|
||||
startHonoServer.mockRejectedValueOnce(new Error("bind failed"));
|
||||
|
||||
|
|
@ -246,78 +518,21 @@ describe("runWeb", () => {
|
|||
await vi.waitFor(() => expect(exitCode).toBe(0));
|
||||
});
|
||||
|
||||
it("preserves an existing stdio cwd", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "run-web-cwd-"));
|
||||
const configPath = join(dir, "mcp.json");
|
||||
await writeFile(
|
||||
configPath,
|
||||
JSON.stringify({
|
||||
mcpServers: {
|
||||
local: {
|
||||
type: "stdio",
|
||||
command: "node",
|
||||
args: ["server.js"],
|
||||
cwd: "/custom/cwd",
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
try {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"--config",
|
||||
configPath,
|
||||
"--server",
|
||||
"local",
|
||||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(
|
||||
startHonoServer.mock.calls[0]?.[0]?.initialMcpConfig,
|
||||
).toMatchObject({
|
||||
cwd: "/custom/cwd",
|
||||
});
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("resolves --server-url without a positional target", async () => {
|
||||
it("does not create any temp file for an ad-hoc launch", async () => {
|
||||
void runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"--server-url",
|
||||
"https://example.com/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
]);
|
||||
await expectServerStarted(startHonoServer);
|
||||
|
||||
expect(startHonoServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
initialMcpConfig: expect.objectContaining({
|
||||
url: "https://example.com/mcp",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("exits when resolveServerConfigs returns no entries", async () => {
|
||||
vi.spyOn(nodeConfig, "resolveServerConfigs").mockReturnValueOnce([]);
|
||||
|
||||
await expect(
|
||||
runWeb([
|
||||
"node",
|
||||
"run-web",
|
||||
"https://example.com/mcp",
|
||||
"--transport",
|
||||
"http",
|
||||
]),
|
||||
).rejects.toThrow("process.exit:1");
|
||||
expect(
|
||||
errorLines.some((l) => l.includes("Could not resolve server config")),
|
||||
).toBe(true);
|
||||
// The ad-hoc list is in memory only; no path is handed to the backend.
|
||||
const cfg = startHonoServer.mock.calls[0]?.[0];
|
||||
expect(cfg?.mcpConfigPath).toBeUndefined();
|
||||
// Sanity: existsSync is imported and the absence of a path means nothing
|
||||
// to clean up on shutdown.
|
||||
expect(existsSync(join(tmpdir(), "definitely-not-created"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -66,6 +66,9 @@ describe("startHonoServer index.html token injection (/ -> /api/*)", () => {
|
|||
authToken: TOKEN,
|
||||
dangerouslyOmitAuth: false,
|
||||
initialMcpConfig: null,
|
||||
mcpConfigPath: undefined,
|
||||
writable: true,
|
||||
initialServers: null,
|
||||
storageDir: undefined,
|
||||
// Allow the same-origin requests the test issues below.
|
||||
allowedOrigins: [baseUrl],
|
||||
|
|
|
|||
|
|
@ -34,6 +34,9 @@ const baseConfig = (): WebServerConfig => ({
|
|||
authToken: "tok",
|
||||
dangerouslyOmitAuth: false,
|
||||
initialMcpConfig: null,
|
||||
mcpConfigPath: undefined,
|
||||
writable: true,
|
||||
initialServers: null,
|
||||
storageDir: undefined,
|
||||
allowedOrigins: ["http://localhost:6274"],
|
||||
sandboxPort: 0,
|
||||
|
|
@ -202,6 +205,29 @@ describe("buildWebServerConfig", () => {
|
|||
);
|
||||
});
|
||||
|
||||
it("threads mcpConfigPath through and defaults it to undefined", () => {
|
||||
expect(buildWebServerConfig().mcpConfigPath).toBeUndefined();
|
||||
expect(
|
||||
buildWebServerConfig({ mcpConfigPath: "/tmp/catalog/mcp.json" })
|
||||
.mcpConfigPath,
|
||||
).toBe("/tmp/catalog/mcp.json");
|
||||
});
|
||||
|
||||
it("defaults writable to true and initialServers to null", () => {
|
||||
const cfg = buildWebServerConfig();
|
||||
expect(cfg.writable).toBe(true);
|
||||
expect(cfg.initialServers).toBeNull();
|
||||
});
|
||||
|
||||
it("threads writable and initialServers when provided", () => {
|
||||
const initialServers = {
|
||||
mcpServers: { srv: { type: "stdio" as const, command: "node" } },
|
||||
};
|
||||
const cfg = buildWebServerConfig({ writable: false, initialServers });
|
||||
expect(cfg.writable).toBe(false);
|
||||
expect(cfg.initialServers).toBe(initialServers);
|
||||
});
|
||||
|
||||
it("preserves a stdio initialMcpConfig while applying shared env defaults", () => {
|
||||
process.env.CLIENT_PORT = "7000";
|
||||
const initialMcpConfig = {
|
||||
|
|
|
|||
|
|
@ -62,6 +62,13 @@ export interface InitialConfigPayload {
|
|||
defaultServerUrl?: string;
|
||||
defaultCwd?: string;
|
||||
defaultEnvironment: Record<string, string>;
|
||||
/**
|
||||
* Whether the session's server list is writable (catalog) or read-only
|
||||
* (a `--config` session file or ad-hoc seeded server). Absent → treated as
|
||||
* true by clients for backward compatibility. Drives whether the web UI
|
||||
* shows catalog CRUD affordances.
|
||||
*/
|
||||
writable?: boolean;
|
||||
}
|
||||
|
||||
export interface RemoteServerOptions {
|
||||
|
|
@ -87,6 +94,26 @@ export interface RemoteServerOptions {
|
|||
/** Optional path for the user's server list file (/api/servers). Default: ~/.mcp-inspector/mcp.json */
|
||||
mcpConfigPath?: string;
|
||||
|
||||
/**
|
||||
* When false, the server list is read-only for this session: all
|
||||
* `/api/servers` mutations (POST/PUT/DELETE/order) are rejected with 403,
|
||||
* the file is never seeded on first read, and on-disk plaintext secrets are
|
||||
* not migrated into the keychain (migration is a write). Used for the web
|
||||
* launcher's read-only `--config` session file and ad-hoc seeded servers, so
|
||||
* a foreign config passed at launch is never silently rewritten. Defaults to
|
||||
* true (the default catalog and `--catalog` are writable).
|
||||
*/
|
||||
writable?: boolean;
|
||||
|
||||
/**
|
||||
* In-memory server list served by GET /api/servers instead of reading from
|
||||
* disk. Set by the web launcher to seed an ad-hoc `--server-url` / command
|
||||
* target (with `--header`) without writing any file. Implies a read-only
|
||||
* session — pass `writable: false` alongside it. When set, `mcpConfigPath`
|
||||
* is ignored for reads and the file watcher is not started.
|
||||
*/
|
||||
initialServers?: MCPConfig;
|
||||
|
||||
/** Optional sandbox URL for MCP Apps tab. When set, GET /api/config includes sandboxUrl. */
|
||||
sandboxUrl?: string;
|
||||
|
||||
|
|
@ -298,6 +325,19 @@ export function createRemoteApp(
|
|||
const secretStore: SecretStore =
|
||||
options.secretStore ?? new KeyringSecretStore();
|
||||
|
||||
// Read-only session support (#1481/#1483). `writable: false` rejects every
|
||||
// /api/servers mutation and suppresses the seed/migrate writes on read.
|
||||
// `initialServers` serves an in-memory list (ad-hoc launch) with no file at
|
||||
// all. Both default off so the catalog path is unchanged.
|
||||
const writable = options.writable ?? true;
|
||||
const inMemoryServers = options.initialServers;
|
||||
// Watch only a real on-disk catalog/session file — never for an in-memory
|
||||
// ad-hoc list (there is nothing to watch and the default path is unrelated).
|
||||
// A read-only `--config` *file* is still watched on purpose: read-only blocks
|
||||
// UI-driven writes, not external observation, so an external edit to the file
|
||||
// should still refresh the UI. (`writable` does not gate watching.)
|
||||
const watchable = !inMemoryServers;
|
||||
|
||||
// --- /api/servers/events: file-watch fanout state -----------------------
|
||||
//
|
||||
// Subscribers are SSE writers added by GET /api/servers/events and removed
|
||||
|
|
@ -447,9 +487,11 @@ export function createRemoteApp(
|
|||
}
|
||||
|
||||
app.get("/api/config", (c) => {
|
||||
const payload = options.sandboxUrl
|
||||
? { ...options.initialConfig, sandboxUrl: options.sandboxUrl }
|
||||
: options.initialConfig;
|
||||
const payload = {
|
||||
...options.initialConfig,
|
||||
writable,
|
||||
...(options.sandboxUrl ? { sandboxUrl: options.sandboxUrl } : {}),
|
||||
};
|
||||
return c.json(payload);
|
||||
});
|
||||
|
||||
|
|
@ -1420,8 +1462,31 @@ export function createRemoteApp(
|
|||
return undefined;
|
||||
};
|
||||
|
||||
// Reject catalog mutations in a read-only session. Checked first in each
|
||||
// mutating route — before body parse or existence checks — so a read-only
|
||||
// backend answers uniformly and never leaks whether an id exists (403, not
|
||||
// 404). Returns a Response to short-circuit, or undefined to proceed.
|
||||
const requireWritable = (c: Context): Response | undefined => {
|
||||
if (writable) return undefined;
|
||||
return c.json(
|
||||
{ error: "Server list is read-only for this session." },
|
||||
403,
|
||||
);
|
||||
};
|
||||
|
||||
app.get("/api/servers", async (c) => {
|
||||
try {
|
||||
// In-memory session (ad-hoc launch): serve the seeded list verbatim.
|
||||
// No disk read, no seed, no migration — there is no file. Ad-hoc env /
|
||||
// header values live as plaintext in this list and flow straight to
|
||||
// POST /api/mcp/connect, which is what makes `--header` take effect.
|
||||
if (inMemoryServers) {
|
||||
const normalized: MCPConfig = {
|
||||
mcpServers: normalizeMcpServers(inMemoryServers.mcpServers),
|
||||
};
|
||||
return c.json(await rehydrateConfig(normalized));
|
||||
}
|
||||
|
||||
// Fast path: peek at the file without taking the write lock. Most
|
||||
// GETs land here — file exists, no plaintext to migrate. The
|
||||
// unlocked read is safe because we don't write anything in this
|
||||
|
|
@ -1433,9 +1498,19 @@ export function createRemoteApp(
|
|||
const onDisk: MCPConfig = {
|
||||
mcpServers: normalizeMcpServers(parsed?.mcpServers),
|
||||
};
|
||||
// Read-only session file (`--config`): never migrate (a write) and
|
||||
// never seed. Return the file as-is so a foreign config is shown but
|
||||
// its bytes — and any plaintext secrets — are left untouched on disk.
|
||||
if (!writable) {
|
||||
return c.json(await rehydrateConfig(onDisk));
|
||||
}
|
||||
if (!hasPlaintextSecrets(onDisk)) {
|
||||
return c.json(await rehydrateConfig(onDisk));
|
||||
}
|
||||
} else if (!writable) {
|
||||
// Read-only and the file is absent: present an empty list rather than
|
||||
// seeding the default sample servers into a path the user pointed us at.
|
||||
return c.json({ mcpServers: {} });
|
||||
}
|
||||
|
||||
// Slow path: either the file is missing (first-launch seed) or it
|
||||
|
|
@ -1480,6 +1555,8 @@ export function createRemoteApp(
|
|||
});
|
||||
|
||||
app.post("/api/servers", async (c) => {
|
||||
const ro = requireWritable(c);
|
||||
if (ro) return ro;
|
||||
let body: { id?: unknown; config?: unknown; settings?: unknown };
|
||||
try {
|
||||
body = (await c.req.json()) as {
|
||||
|
|
@ -1553,6 +1630,8 @@ export function createRemoteApp(
|
|||
// values, so we just permute the existing stripped entries and reuse the
|
||||
// same atomic-write + watcher-notify path as the other mutators.
|
||||
app.put("/api/servers/order", async (c) => {
|
||||
const ro = requireWritable(c);
|
||||
if (ro) return ro;
|
||||
let body: { order?: unknown };
|
||||
try {
|
||||
body = (await c.req.json()) as { order?: unknown };
|
||||
|
|
@ -1605,6 +1684,8 @@ export function createRemoteApp(
|
|||
});
|
||||
|
||||
app.put("/api/servers/:id", async (c) => {
|
||||
const ro = requireWritable(c);
|
||||
if (ro) return ro;
|
||||
const originalId = c.req.param("id");
|
||||
if (!originalId || !validateStoreId(originalId)) {
|
||||
return c.json({ error: "Invalid id" }, 400);
|
||||
|
|
@ -1766,6 +1847,8 @@ export function createRemoteApp(
|
|||
});
|
||||
|
||||
app.delete("/api/servers/:id", async (c) => {
|
||||
const ro = requireWritable(c);
|
||||
if (ro) return ro;
|
||||
const id = c.req.param("id");
|
||||
if (!id || !validateStoreId(id)) {
|
||||
return c.json({ error: "Invalid id" }, 400);
|
||||
|
|
@ -1804,8 +1887,13 @@ export function createRemoteApp(
|
|||
const send = (data: string): void => {
|
||||
void stream.writeSSE({ event: "change", data });
|
||||
};
|
||||
serverEventSubscribers.add(send);
|
||||
ensureWatcher();
|
||||
// An in-memory ad-hoc list never changes and has no file to watch, so we
|
||||
// hold the stream open (so the client's fetch resolves cleanly) but
|
||||
// register no subscriber and start no watcher — there is nothing to emit.
|
||||
if (watchable) {
|
||||
serverEventSubscribers.add(send);
|
||||
ensureWatcher();
|
||||
}
|
||||
|
||||
stream.onAbort(() => {
|
||||
serverEventSubscribers.delete(send);
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue