feat(web): catalog vs read-only session launch model + apply --header (#1481, #1483) (#1496)

* 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:
Cliff Hall 2026-06-16 14:24:58 -04:00 • committed by GitHub
commit 91f02fd6db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 1281 additions and 157 deletions

View 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);
});
});

View file

@ -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);
});
});

View file

@ -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();
});
});

View file

@ -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);
}
});
});

View file

@ -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);
});
});

View file

@ -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],

View file

@ -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 = {