Skip to content

Commit 425b625

Browse files
cliffhallclaude
andcommitted
fix(servers): address PR review pass 2 — connect-timeout test, unmount cleanup, tagged intent, lenient settings read
Pass-2 review at #1353 (comment): (a) New integration test pins the new client-layer connect-timeout contract: a hanging stub transport with `connectionTimeout: 50` rejects with the descriptive error and lands the client in "error" status. Documents what TUI/CLI consumers should expect from the lifted Promise.race in InspectorClient.connect(). (b) useEffect cleanup clears `pendingSettingsTimerRef` on unmount so a route change or HMR mid-debounce can't fire one stale PUT against an unmounted component. (c) Refactor the PUT-route `settingsIntent` discriminator from `"preserve" | "clear" | { value }` to a tagged union with `kind`, and consume it with a `switch` for exhaustiveness — reads cleaner and makes adding a fourth intent painless. (d) `normalizeMcpServers` now runs `validateSettings` on the on-disk settings node and silently strips it if invalid, mirroring the existing lenient-on-read pattern from `normalizeServerType`. Closes the read/write asymmetry where a hand-edited malformed `settings` could survive on disk and get carried through preserve-on-PUT. New route test pins the strip-on-GET + no-propagate-on-preserve-PUT behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 2702ed2 commit 425b625

4 files changed

Lines changed: 141 additions & 14 deletions

File tree

‎clients/web/src/App.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -824,6 +824,19 @@ function App() {
824824
setSettingsModalTargetId(undefined);
825825
}, [flushPendingSettings]);
826826

827+
// Cancel any pending debounce on unmount (route change / HMR). Without
828+
// this a stale setTimeout could still fire one final `updateServerSettings`
829+
// against an unmounted component — harmless today (just an extra PUT of
830+
// the final payload) but the cleanest pattern is to clear the timer.
831+
useEffect(() => {
832+
return () => {
833+
if (pendingSettingsTimerRef.current) {
834+
clearTimeout(pendingSettingsTimerRef.current);
835+
pendingSettingsTimerRef.current = undefined;
836+
}
837+
};
838+
}, []);
839+
827840
// The Resources screen needs `isSubscribed` to flip the Subscribe button
828841
// label to "Unsubscribe". Derive it from the live subscriptions list rather
829842
// than threading it through every setReadResourceState site — that way the

‎clients/web/src/test/integration/mcp/inspectorClient.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,51 @@ describe("InspectorClient", () => {
289289
}
290290
messageLogState.destroy();
291291
});
292+
293+
it("rejects connect() with a timeout error when serverSettings.connectionTimeout fires", async () => {
294+
// Stub transport whose start() never resolves — simulates a slow /
295+
// unreachable upstream. InspectorClient.connect() should race against
296+
// serverSettings.connectionTimeout and reject with a descriptive error;
297+
// status should end up in "error", and the client should have
298+
// internally torn down the transport (next connect() must rebuild).
299+
const hangingTransport = {
300+
start: () => new Promise<void>(() => {}),
301+
send: async () => {},
302+
close: async () => {},
303+
onclose: undefined,
304+
onerror: undefined,
305+
onmessage: undefined,
306+
sessionId: undefined,
307+
};
308+
const fakeFactory = () => ({
309+
transport:
310+
hangingTransport as unknown as import("@modelcontextprotocol/sdk/shared/transport.js").Transport,
311+
});
312+
client = new InspectorClient(
313+
{ type: "streamable-http", url: "http://localhost:1/never" },
314+
{
315+
environment: { transport: fakeFactory },
316+
serverSettings: {
317+
headers: [],
318+
metadata: [],
319+
connectionTimeout: 50,
320+
requestTimeout: 0,
321+
},
322+
},
323+
);
324+
325+
const before = Date.now();
326+
await expect(client.connect()).rejects.toThrow(
327+
/Connection timed out after 50 ms/,
328+
);
329+
const elapsed = Date.now() - before;
330+
// Sanity: the race should fire near the configured timeout, not at
331+
// some far-future SDK default.
332+
expect(elapsed).toBeLessThan(2000);
333+
// connect() rejected → the outer catch transitions status to "error"
334+
// (the same end state any other handshake failure would produce).
335+
expect(client.getStatus()).toBe("error");
336+
});
292337
});
293338

294339
describe("Message Tracking", () => {

‎clients/web/src/test/integration/mcp/remote/servers-route.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -555,6 +555,55 @@ describe("/api/servers routes", () => {
555555
const body = (await res.json()) as { error?: string };
556556
expect(body.error).toMatch(/object/);
557557
});
558+
559+
it("strips a malformed settings node on read (lenient-on-read; preserve-on-PUT cannot propagate it)", async () => {
560+
// Hand-edited mcp.json with a malformed `settings.headers` (string
561+
// instead of array). The write-path validator would reject it, but a
562+
// user could write it directly. GET should surface the entry with
563+
// settings dropped, and a subsequent config-only PUT should not
564+
// re-attach the broken node via the preserve branch.
565+
writeFileSync(
566+
h.configPath,
567+
JSON.stringify({
568+
mcpServers: {
569+
broken: {
570+
type: "streamable-http",
571+
url: "https://x.test/mcp",
572+
settings: {
573+
headers: "oops",
574+
metadata: [],
575+
connectionTimeout: 0,
576+
requestTimeout: 0,
577+
},
578+
},
579+
},
580+
}),
581+
);
582+
583+
// GET surfaces the entry without the malformed settings.
584+
const getRes = await fetch(`${h.baseUrl}/api/servers`);
585+
expect(getRes.status).toBe(200);
586+
const getBody = (await getRes.json()) as {
587+
mcpServers: Record<string, { settings?: unknown }>;
588+
};
589+
expect(getBody.mcpServers.broken).toBeDefined();
590+
expect(getBody.mcpServers.broken!.settings).toBeUndefined();
591+
592+
// PUT without settings preserves the (now-stripped) absence, not the
593+
// original malformed node.
594+
const putRes = await fetch(`${h.baseUrl}/api/servers/broken`, {
595+
method: "PUT",
596+
headers: { "Content-Type": "application/json" },
597+
body: JSON.stringify({
598+
config: { type: "streamable-http", url: "https://x.test/other" },
599+
}),
600+
});
601+
expect(putRes.status).toBe(200);
602+
const stored = readConfig(h.configPath).mcpServers.broken as {
603+
settings?: unknown;
604+
};
605+
expect(stored.settings).toBeUndefined();
606+
});
558607
});
559608

560609
describe("concurrent mutations", () => {

‎core/mcp/remote/node/server.ts‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -635,17 +635,27 @@ export function createRemoteApp(
635635
// --- /api/servers (server list backed by mcp.json) ---
636636

637637
// Defensive normalize so editor-edited files with type:"http" or missing
638-
// type round-trip into the canonical form on every read. The optional
639-
// Inspector-specific `settings` node is preserved verbatim by the spread
640-
// inside normalizeServerType.
638+
// type round-trip into the canonical form on every read. Settings that
639+
// fail `validateSettings` are silently stripped (lenient-on-read pattern
640+
// matching `normalizeServerType`'s unknown→stdio fallback) so a malformed
641+
// hand-edit can't propagate through preserve-on-PUT.
641642
const normalizeMcpServers = (raw: unknown): Record<string, StoredMCPServer> => {
642643
if (!raw || typeof raw !== "object") return {};
643644
const out: Record<string, StoredMCPServer> = {};
644645
for (const [id, val] of Object.entries(raw as Record<string, unknown>)) {
645646
if (!val || typeof val !== "object") continue;
646-
out[id] = normalizeServerType(
647+
const normalized = normalizeServerType(
647648
val as Record<string, unknown> & { type?: string },
648649
) as StoredMCPServer;
650+
if (normalized.settings !== undefined) {
651+
const checked = validateSettings(normalized.settings);
652+
if (checked.ok) {
653+
normalized.settings = checked.value;
654+
} else {
655+
delete normalized.settings;
656+
}
657+
}
658+
out[id] = normalized;
649659
}
650660
return out;
651661
};
@@ -852,15 +862,19 @@ export function createRemoteApp(
852862
// - a settings object → validate and apply
853863
// Preserving on omission means callers that only want to update config
854864
// (e.g. ServerConfigModal save) don't silently wipe persisted settings.
855-
let settingsIntent: "preserve" | "clear" | { value: InspectorServerSettings };
865+
type SettingsIntent =
866+
| { kind: "preserve" }
867+
| { kind: "clear" }
868+
| { kind: "apply"; value: InspectorServerSettings };
869+
let settingsIntent: SettingsIntent;
856870
if (body.settings === undefined) {
857-
settingsIntent = "preserve";
871+
settingsIntent = { kind: "preserve" };
858872
} else if (body.settings === null) {
859-
settingsIntent = "clear";
873+
settingsIntent = { kind: "clear" };
860874
} else {
861875
const validated = validateSettings(body.settings);
862876
if (!validated.ok) return c.json({ error: validated.error }, 400);
863-
settingsIntent = { value: validated.value };
877+
settingsIntent = { kind: "apply", value: validated.value };
864878
}
865879
const newId = typeof body.id === "string" ? body.id : originalId;
866880
if (!validateStoreId(newId)) {
@@ -879,12 +893,18 @@ export function createRemoteApp(
879893
// Rebuild preserving insertion order; replace the original key in place
880894
// so the file diff stays minimal when not renaming.
881895
const existing = current.mcpServers[originalId]!;
882-
const nextSettings: InspectorServerSettings | undefined =
883-
settingsIntent === "preserve"
884-
? existing.settings
885-
: settingsIntent === "clear"
886-
? undefined
887-
: settingsIntent.value;
896+
let nextSettings: InspectorServerSettings | undefined;
897+
switch (settingsIntent.kind) {
898+
case "preserve":
899+
nextSettings = existing.settings;
900+
break;
901+
case "clear":
902+
nextSettings = undefined;
903+
break;
904+
case "apply":
905+
nextSettings = settingsIntent.value;
906+
break;
907+
}
888908
const next: MCPConfig = { mcpServers: {} };
889909
for (const [key, val] of Object.entries(current.mcpServers)) {
890910
if (key === originalId) {

0 commit comments

Comments
 (0)