Skip to content

Commit 49d6be6

Browse files
cliffhallclaude
andauthored
feat(web): add per-server Roots config + client roots capability (#1425) (#1431)
* feat(web): add per-server Roots config + client roots capability (#1425) Add MCP roots support to the v2 web Inspector as a per-server config section in the server settings form (no separate Roots tab/screen). - Persistence: add `roots: Root[]` to `InspectorServerSettings` and `StoredMCPServer`; thread through serverList converters (lift on read, drop empty-uri rows / blank names on write, omit when empty) and the remote server's read-side drop guard + `validateSettings`. - Capability: `setupClientForServer` always advertises the roots capability (`roots: cleanRoots(savedSettings?.roots ?? [])`) so the server can issue `roots/list` and receive `roots/list_changed`. - Live apply: edits to a connected server's roots are pushed via `inspectorClient.setRoots(...)` once, on settings-dialog close — diffed against the client's current roots — rather than per keystroke, to avoid flooding the server with `roots/list_changed` / `roots/list`. - Form: new Roots accordion section with a required URI and an optional name per row (unlike v1, which was URI-only), + Add Root, and remove. Tests cover the persistence round-trip (serverList + servers-route), the form/modal section, and reuse the existing InspectorClient roots/`setRoots` integration coverage. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * refactor(roots): address review — dedup guards/cleanRoots, preserve extra fields, test live-apply Responding to the PR #1431 code review: - Dedup `isRootArray`: drop the copy inside `validateSettings` and reuse the module-scope guard the read path uses, so the two can't drift (core/mcp/remote/node/server.ts). - Dedup the clean-roots normalizer: hoist a single exported `cleanRoots` into core/mcp/serverList.ts and reuse it from both `inspectorSettingsToStoredFields` and App.tsx (drops the local copy). - Preserve non-form root fields (e.g. `_meta`): `cleanRoots` now spreads the carried-through fields and only normalizes uri/name, and the modal's `handleRootChange` spreads the existing root on edit — so a hand-edited root's `_meta` survives load + persist + edit instead of being silently dropped. - Test the App live-apply-on-close path: new App.test.tsx cases assert setRoots is called once with cleaned roots when changed on the active server, and not called when the cleaned roots already match what the client advertises. Adds a cleanRoots unit test (blank drop + _meta preserve). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent ed6eda7 commit 49d6be6

18 files changed

Lines changed: 716 additions & 6 deletions

‎clients/web/src/App.test.tsx‎

Lines changed: 109 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { describe, it, expect, beforeEach, vi } from "vitest";
1+
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
22
import {
33
renderWithMantine,
44
screen,
@@ -53,6 +53,8 @@ vi.mock("@inspector/core/mcp/index.js", () => {
5353
getOAuthState = vi.fn().mockReturnValue(undefined);
5454
getPendingSamples = vi.fn().mockReturnValue([]);
5555
getPendingElicitations = vi.fn().mockReturnValue([]);
56+
getRoots = vi.fn().mockReturnValue([]);
57+
setRoots = vi.fn().mockResolvedValue(undefined);
5658
}
5759
const instances: FakeInspectorClient[] = [];
5860
return {
@@ -187,7 +189,9 @@ vi.mock("@inspector/core/react/useFetchRequestLog.js", () => ({
187189
}));
188190
vi.mock("@inspector/core/react/useSettingsDraft.js", () => ({
189191
useSettingsDraft: vi.fn(() => ({
190-
draft: undefined,
192+
// `draft` is widened so tests can override the return with a populated
193+
// settings draft via `mockReturnValue` (the roots live-apply-on-close path).
194+
draft: undefined as InspectorServerSettings | undefined,
191195
onChange: vi.fn(),
192196
flush: vi.fn(),
193197
})),
@@ -243,6 +247,7 @@ vi.mock("./components/views/InspectorView/InspectorView", () => ({
243247
onCancelTask: (taskId: string) => void;
244248
onClearCompletedTasks: () => void;
245249
onRefreshTasks: () => void;
250+
onServerSettings: (id: string) => void;
246251
}) => (
247252
<div>
248253
<span data-testid="tool-status">
@@ -339,6 +344,7 @@ vi.mock("./components/views/InspectorView/InspectorView", () => ({
339344
read-resource
340345
</button>
341346
<button onClick={() => props.onSetLogLevel("debug")}>set-level</button>
347+
<button onClick={() => props.onServerSettings("A")}>open-settings</button>
342348
</div>
343349
),
344350
}));
@@ -347,6 +353,8 @@ import App from "./App";
347353
import * as McpIndex from "@inspector/core/mcp/index.js";
348354
import { useManagedRequestorTasks } from "@inspector/core/react/useManagedRequestorTasks.js";
349355
import { useInspectorClient } from "@inspector/core/react/useInspectorClient.js";
356+
import { useSettingsDraft } from "@inspector/core/react/useSettingsDraft.js";
357+
import type { InspectorServerSettings } from "@inspector/core/mcp/types.js";
350358

351359
// Default useInspectorClient return — capabilities empty (no task tool calls).
352360
// Individual tests override via vi.mocked(...).mockReturnValue(...).
@@ -843,3 +851,102 @@ describe("App task wiring", () => {
843851
);
844852
});
845853
});
854+
855+
// Live-apply roots on settings-dialog close: the App diffs the final draft
856+
// roots against what the connected client advertises and calls `setRoots`
857+
// once (not per keystroke), and only for the active server. App.tsx is
858+
// excluded from the coverage gate, but the acceptance criterion ("editing
859+
// roots on a live connection notifies the server on dialog close") lives
860+
// here, so it's worth a direct test of the gate/diff/notify path.
861+
type RootsFakeClient = EventTarget & {
862+
setRoots: ReturnType<typeof vi.fn>;
863+
getRoots: ReturnType<typeof vi.fn>;
864+
};
865+
866+
const settingsWithRoots = (
867+
roots: InspectorServerSettings["roots"],
868+
): InspectorServerSettings => ({
869+
headers: [],
870+
metadata: [],
871+
connectionTimeout: 0,
872+
requestTimeout: 0,
873+
taskTtl: 60000,
874+
roots,
875+
});
876+
877+
describe("App roots live-apply on settings-dialog close", () => {
878+
beforeEach(() => {
879+
clientInstances.length = 0;
880+
vi.mocked(useInspectorClient).mockReturnValue(DEFAULT_USE_INSPECTOR_CLIENT);
881+
});
882+
883+
afterEach(() => {
884+
// Restore the default empty draft so the override doesn't leak.
885+
vi.mocked(useSettingsDraft).mockReturnValue({
886+
draft: undefined,
887+
onChange: vi.fn(),
888+
flush: vi.fn(),
889+
});
890+
});
891+
892+
async function openSettingsForConnectedServer(
893+
draft: InspectorServerSettings,
894+
): Promise<RootsFakeClient> {
895+
vi.mocked(useSettingsDraft).mockReturnValue({
896+
draft,
897+
onChange: vi.fn(),
898+
flush: vi.fn(),
899+
});
900+
const user = userEvent.setup();
901+
renderWithMantine(<App />);
902+
await user.click(screen.getByText("connect"));
903+
await waitFor(() => expect(clientInstances).toHaveLength(1));
904+
await user.click(screen.getByText("open-settings"));
905+
await waitFor(() =>
906+
expect(screen.getByText("Server Settings")).toBeInTheDocument(),
907+
);
908+
return clientInstances[0] as RootsFakeClient;
909+
}
910+
911+
async function closeModal(user: ReturnType<typeof userEvent.setup>) {
912+
const closeBtn = document.querySelector(
913+
"button.mantine-CloseButton-root",
914+
) as HTMLButtonElement | null;
915+
expect(closeBtn).not.toBeNull();
916+
await user.click(closeBtn!);
917+
}
918+
919+
it("calls setRoots once with cleaned roots when roots changed on the active server", async () => {
920+
const user = userEvent.setup();
921+
const client = await openSettingsForConnectedServer(
922+
// A blank-uri row (left mid-edit) must be dropped; the named root kept.
923+
settingsWithRoots([{ uri: "file:///x", name: "X" }, { uri: "" }]),
924+
);
925+
// Client currently advertises no roots → the draft differs → notify.
926+
client.getRoots.mockReturnValue([]);
927+
928+
await closeModal(user);
929+
930+
await waitFor(() => expect(client.setRoots).toHaveBeenCalledTimes(1));
931+
expect(client.setRoots).toHaveBeenCalledWith([
932+
{ uri: "file:///x", name: "X" },
933+
]);
934+
});
935+
936+
it("does not call setRoots when the cleaned roots match what the client advertises", async () => {
937+
const user = userEvent.setup();
938+
const client = await openSettingsForConnectedServer(
939+
settingsWithRoots([{ uri: "file:///x" }]),
940+
);
941+
// Same roots already advertised → no notification on close.
942+
client.getRoots.mockReturnValue([{ uri: "file:///x" }]);
943+
944+
await closeModal(user);
945+
946+
// Let any close-handler microtasks settle, then assert no notification.
947+
await waitFor(() =>
948+
expect(screen.queryByText("Server Settings")).not.toBeInTheDocument(),
949+
);
950+
expect(client.setRoots).not.toHaveBeenCalled();
951+
});
952+
});

‎clients/web/src/App.tsx‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ import { ManagedResourcesState } from "@inspector/core/mcp/state/managedResource
4242
import { ManagedResourceTemplatesState } from "@inspector/core/mcp/state/managedResourceTemplatesState.js";
4343
import { ManagedRequestorTasksState } from "@inspector/core/mcp/state/managedRequestorTasksState.js";
4444
import { ResourceSubscriptionsState } from "@inspector/core/mcp/state/resourceSubscriptionsState.js";
45-
import { serializeMcpConfig } from "@inspector/core/mcp/serverList.js";
45+
import {
46+
cleanRoots,
47+
serializeMcpConfig,
48+
} from "@inspector/core/mcp/serverList.js";
4649
import { MessageLogState } from "@inspector/core/mcp/state/messageLogState.js";
4750
import { FetchRequestLogState } from "@inspector/core/mcp/state/fetchRequestLogState.js";
4851
import { StderrLogState } from "@inspector/core/mcp/state/stderrLogState.js";
@@ -197,6 +200,7 @@ const EMPTY_SETTINGS: InspectorServerSettings = {
197200
connectionTimeout: 0,
198201
requestTimeout: 0,
199202
taskTtl: DEFAULT_TASK_TTL_MS,
203+
roots: [],
200204
};
201205

202206
// Body of the output-schema-mismatch warning toast: a one-line summary plus a
@@ -951,6 +955,11 @@ function App() {
951955
// Sampling / elicitation are on by default; keep the parameterized
952956
// options off until the UI grows the surface to render them.
953957
elicit: { form: true, url: true },
958+
// Always advertise the roots capability (even with no configured
959+
// roots) so the server can issue roots/list and receive
960+
// roots/list_changed; the configured roots are the answer to
961+
// roots/list. Empty-uri rows are dropped before they reach the wire.
962+
roots: cleanRoots(savedSettings?.roots ?? []),
954963
...(savedSettings &&
955964
savedSettings.requestTimeout > 0 && {
956965
timeout: savedSettings.requestTimeout,
@@ -1693,8 +1702,36 @@ function App() {
16931702

16941703
const onSettingsModalClose = useCallback(() => {
16951704
flushSettingsDraft();
1705+
// Apply root edits to the live client once, on close — not on every
1706+
// keystroke. `setRoots` fires `notifications/roots/list_changed`, which
1707+
// makes the server re-request `roots/list`; doing that per character while
1708+
// the user types a URI would flood the wire. We diff the final draft roots
1709+
// against what the client currently advertises (both cleaned) and notify
1710+
// only when they actually differ, and only for the connected server.
1711+
if (
1712+
inspectorClient &&
1713+
settingsModalTargetId !== undefined &&
1714+
settingsModalTargetId === activeServerId &&
1715+
settingsDraft
1716+
) {
1717+
const nextRoots = cleanRoots(settingsDraft.roots);
1718+
const currentRoots = cleanRoots(inspectorClient.getRoots());
1719+
if (JSON.stringify(nextRoots) !== JSON.stringify(currentRoots)) {
1720+
void inspectorClient.setRoots(nextRoots).catch(() => {
1721+
// setRoots swallows notification failures internally; a throw here
1722+
// only means the client is mid-teardown — the persisted roots will
1723+
// re-advertise on the next connect, so nothing to surface.
1724+
});
1725+
}
1726+
}
16961727
setSettingsModalTargetId(undefined);
1697-
}, [flushSettingsDraft]);
1728+
}, [
1729+
flushSettingsDraft,
1730+
inspectorClient,
1731+
settingsModalTargetId,
1732+
activeServerId,
1733+
settingsDraft,
1734+
]);
16981735

16991736
// The Resources screen needs `isSubscribed` to flip the Subscribe button
17001737
// label to "Unsubscribe". Derive it from the live subscriptions list rather

‎clients/web/src/components/groups/ServerSettingsForm/ServerSettingsForm.stories.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const defaultSettings: InspectorServerSettings = {
1313
connectionTimeout: 30000,
1414
requestTimeout: 60000,
1515
taskTtl: 60000,
16+
roots: [],
1617
};
1718

1819
function InteractiveRender(args: ServerSettingsFormProps) {
@@ -171,6 +172,10 @@ export const AllConfigured: Story = {
171172
oauthClientId: "my-client-id",
172173
oauthClientSecret: "super-secret-value",
173174
oauthScopes: "read write",
175+
roots: [
176+
{ uri: "file:///home/user/project", name: "Project" },
177+
{ uri: "file:///tmp" },
178+
],
174179
},
175180
},
176181
};

‎clients/web/src/components/groups/ServerSettingsForm/ServerSettingsForm.test.tsx‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const emptySettings: InspectorServerSettings = {
1313
connectionTimeout: 30000,
1414
requestTimeout: 60000,
1515
taskTtl: 60000,
16+
roots: [],
1617
};
1718

1819
const populatedSettings: InspectorServerSettings = {
@@ -24,13 +25,15 @@ const populatedSettings: InspectorServerSettings = {
2425
oauthClientId: "cid",
2526
oauthClientSecret: "secret",
2627
oauthScopes: "read",
28+
roots: [{ uri: "file:///project", name: "Project" }],
2729
};
2830

2931
const allSections: ServerSettingsSection[] = [
3032
"headers",
3133
"metadata",
3234
"timeouts",
3335
"oauth",
36+
"roots",
3437
];
3538

3639
const baseHandlers = {
@@ -43,6 +46,9 @@ const baseHandlers = {
4346
onMetadataChange: vi.fn(),
4447
onTimeoutChange: vi.fn(),
4548
onOAuthChange: vi.fn(),
49+
onAddRoot: vi.fn(),
50+
onRemoveRoot: vi.fn(),
51+
onRootChange: vi.fn(),
4652
};
4753

4854
describe("ServerSettingsForm", () => {
@@ -58,6 +64,7 @@ describe("ServerSettingsForm", () => {
5864
expect(screen.getByText("Request Metadata")).toBeInTheDocument();
5965
expect(screen.getByText("Timeouts")).toBeInTheDocument();
6066
expect(screen.getByText("OAuth Settings")).toBeInTheDocument();
67+
expect(screen.getByText("Roots")).toBeInTheDocument();
6168
});
6269

6370
it("shows empty hints for headers and metadata when no entries exist", () => {
@@ -288,6 +295,71 @@ describe("ServerSettingsForm", () => {
288295
});
289296
});
290297

298+
it("shows the empty hint for roots when none are configured", () => {
299+
renderWithMantine(
300+
<ServerSettingsForm
301+
{...baseHandlers}
302+
settings={emptySettings}
303+
expandedSections={["roots"]}
304+
/>,
305+
);
306+
expect(screen.getByText("No roots configured")).toBeInTheDocument();
307+
});
308+
309+
it("invokes onAddRoot when + Add Root is clicked", async () => {
310+
const user = userEvent.setup();
311+
const onAddRoot = vi.fn();
312+
renderWithMantine(
313+
<ServerSettingsForm
314+
{...baseHandlers}
315+
onAddRoot={onAddRoot}
316+
settings={emptySettings}
317+
expandedSections={["roots"]}
318+
/>,
319+
);
320+
await user.click(screen.getByRole("button", { name: "+ Add Root" }));
321+
expect(onAddRoot).toHaveBeenCalledTimes(1);
322+
});
323+
324+
it("renders a row's uri and optional name and reports edits via onRootChange", async () => {
325+
const user = userEvent.setup();
326+
const onRootChange = vi.fn();
327+
renderWithMantine(
328+
<ServerSettingsForm
329+
{...baseHandlers}
330+
onRootChange={onRootChange}
331+
settings={populatedSettings}
332+
expandedSections={["roots"]}
333+
/>,
334+
);
335+
// populatedSettings has one root { uri: "file:///project", name: "Project" }
336+
expect(screen.getByDisplayValue("file:///project")).toBeInTheDocument();
337+
const nameInput = screen.getByDisplayValue("Project");
338+
await user.type(nameInput, "X");
339+
expect(onRootChange).toHaveBeenCalled();
340+
const lastCall =
341+
onRootChange.mock.calls[onRootChange.mock.calls.length - 1];
342+
expect(lastCall[0]).toBe(0);
343+
// uri is threaded through unchanged when only the name changes
344+
expect(lastCall[1]).toBe("file:///project");
345+
});
346+
347+
it("invokes onRemoveRoot when X is clicked on a root row", async () => {
348+
const user = userEvent.setup();
349+
const onRemoveRoot = vi.fn();
350+
renderWithMantine(
351+
<ServerSettingsForm
352+
{...baseHandlers}
353+
onRemoveRoot={onRemoveRoot}
354+
settings={populatedSettings}
355+
expandedSections={["roots"]}
356+
/>,
357+
);
358+
const removeButtons = screen.getAllByRole("button", { name: "X" });
359+
await user.click(removeButtons[0]);
360+
expect(onRemoveRoot).toHaveBeenCalledWith(0);
361+
});
362+
291363
it("invokes onExpandedSectionsChange when an Accordion section is toggled", async () => {
292364
const user = userEvent.setup();
293365
const onExpandedSectionsChange = vi.fn();

0 commit comments

Comments
 (0)