MCP Server Settings
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.test.tsx
index 8abb8855e3d..5d9dcba4778 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.test.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.test.tsx
@@ -1,12 +1,26 @@
import React from "react";
-import { render, waitFor, screen, act, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { QueryClientProvider } from "@tanstack/react-query";
+import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
import MCPServers from "./mcp_servers";
import * as networking from "@/components/networking";
+import type { MCPServer } from "@/components/mcp_tools/types";
+import { TOOLS_OAUTH_UI_STATE_KEY } from "@/hooks/mcpOAuthUtils";
+import { setSecureItem } from "@/utils/secureStorage";
+import { EDIT_OAUTH_UI_STATE_KEY } from "./mcp_server_edit";
+import {
+ act,
+ chooseSelectOption,
+ fireEvent,
+ render,
+ renderWithProviders,
+ screen,
+ testQueryClient,
+ waitFor,
+ within,
+} from "@/../tests/test-utils";
-// Mock the networking module
vi.mock("@/components/networking", () => ({
fetchMCPServers: vi.fn(),
fetchMCPServerHealth: vi.fn(),
@@ -19,385 +33,522 @@ vi.mock("@/components/networking", () => ({
listMCPUserEnvVarStatus: vi.fn().mockResolvedValue([]),
}));
-const createQueryClient = () =>
- new QueryClient({
- defaultOptions: {
- queries: {
- retry: false,
- gcTime: 0,
- },
- },
- });
+interface ServerViewStubProps {
+ mcpServer: MCPServer;
+ isEditing: boolean;
+ onBack: () => void;
+}
+
+vi.mock("./mcp_server_view", () => ({
+ MCPServerView: ({ mcpServer, isEditing, onBack }: ServerViewStubProps) => (
+
+ viewing {mcpServer.server_name}
+ {isEditing ? "settings editable" : "settings read only"}
+
+
+ ),
+}));
+
+interface EnvVarsModalStubProps {
+ server: MCPServer | null;
+ open: boolean;
+ onClose: () => void;
+}
+
+vi.mock("./UserEnvVarsModal", () => ({
+ default: ({ server, open, onClose }: EnvVarsModalStubProps) =>
+ open && server ? (
+
+ fill fields for {server.server_name}
+
+
+ ) : null,
+}));
+
+const BASE_SERVER = {
+ url: "https://example.com/mcp",
+ transport: "http",
+ auth_type: "none",
+ created_at: "2024-01-01T00:00:00Z",
+ created_by: "user-1",
+ updated_at: "2024-01-01T00:00:00Z",
+ updated_by: "user-1",
+ teams: [],
+ mcp_access_groups: [],
+};
+
+const makeServer = (overrides: Partial
& Pick): MCPServer => ({
+ ...BASE_SERVER,
+ server_name: overrides.server_id,
+ alias: `${overrides.server_id}-alias`,
+ ...overrides,
+});
+
+const TEAM_A = [{ team_id: "team-a", team_alias: "Team A" }];
+const TEAM_B = [{ team_id: "team-b", team_alias: "Team B" }];
+
+const urlServers: MCPServer[] = [
+ {
+ ...BASE_SERVER,
+ server_id: "alpha",
+ alias: "alpha-alias",
+ server_name: "Alpha",
+ teams: TEAM_A,
+ mcp_access_groups: ["group-x"],
+ },
+ {
+ ...BASE_SERVER,
+ server_id: "bravo",
+ alias: "bravo-alias",
+ server_name: "Bravo",
+ created_at: "2024-01-02T00:00:00Z",
+ teams: TEAM_B,
+ },
+ {
+ ...BASE_SERVER,
+ server_id: "charlie",
+ alias: "charlie-alias",
+ server_name: "Charlie",
+ created_at: "2024-01-03T00:00:00Z",
+ teams: TEAM_A,
+ },
+];
+
+const defaultProps = {
+ accessToken: "123",
+ userRole: "Admin",
+ userID: "admin-user-id",
+};
+
+const lastUrl = (onUrlUpdate: ReturnType>) => onUrlUpdate.mock.calls.at(-1)?.[0];
+
+const shownServerNames = () =>
+ within(screen.getByTestId("mcp-servers-grid"))
+ .getAllByText(/^(Alpha|Bravo|Charlie)$/)
+ .map((node) => node.textContent);
+
+const cardFor = (name: string): HTMLElement => {
+ const card = screen.getByText(name).closest('[role="button"]');
+ if (!card) throw new Error(`no card for ${name}`);
+ return card;
+};
+
+const selectNextTo = (label: string) => within(screen.getByText(label).parentElement!).getByRole("combobox");
+
+const renderPage = (searchParams: string, props: Partial = {}) => {
+ const onUrlUpdate = vi.fn();
+ renderWithProviders(, { searchParams, onUrlUpdate });
+ return onUrlUpdate;
+};
+
+const renderPageKeepingMountWrites = (searchParams: string, props: Partial = {}) => {
+ const onUrlUpdate = vi.fn();
+ render(
+
+
+
+
+ ,
+ );
+ return onUrlUpdate;
+};
describe("MCPServers", () => {
- const defaultProps = {
- accessToken: "123",
- userRole: "Admin",
- userID: "admin-user-id",
- };
-
beforeEach(() => {
vi.clearAllMocks();
+ testQueryClient.clear();
+ window.sessionStorage.clear();
+ vi.mocked(networking.fetchMCPServerHealth).mockResolvedValue([]);
});
it("should render the MCPServers component with title", async () => {
- // Mock empty response for simple render test
vi.mocked(networking.fetchMCPServers).mockResolvedValue([]);
- const queryClient = createQueryClient();
- render(
-
-
- ,
- );
+ renderWithProviders();
- // Wait for the component to load and check if title renders
await waitFor(() => {
expect(screen.getByText("MCP Servers")).toBeInTheDocument();
});
-
- // Verify the title is rendered
- expect(screen.getByText("MCP Servers")).toBeInTheDocument();
});
it("should render mocked MCP servers data in the table", async () => {
- // Mock MCP servers data
- const mockServers = [
- {
- server_id: "server-1",
- server_name: "Test Server 1",
- alias: "test-server-1",
- url: "https://example.com/mcp",
- transport: "http",
- auth_type: "none",
- created_at: "2024-01-01T00:00:00Z",
- created_by: "user-1",
- updated_at: "2024-01-01T00:00:00Z",
- updated_by: "user-1",
- teams: [],
- mcp_access_groups: [],
- },
+ const mockServers: MCPServer[] = [
+ { ...BASE_SERVER, server_id: "server-1", server_name: "Test Server 1", alias: "test-server-1" },
{
+ ...BASE_SERVER,
server_id: "server-2",
server_name: "Test Server 2",
alias: "test-server-2",
- url: "https://example2.com/mcp",
transport: "sse",
auth_type: "api_key",
- created_at: "2024-01-02T00:00:00Z",
- created_by: "user-2",
- updated_at: "2024-01-02T00:00:00Z",
- updated_by: "user-2",
- teams: [],
mcp_access_groups: ["group-1"],
},
];
-
vi.mocked(networking.fetchMCPServers).mockResolvedValue(mockServers);
- const queryClient = createQueryClient();
- render(
-
-
- ,
- );
+ renderWithProviders();
- // Wait for the component to load
- await waitFor(() => {
- expect(screen.getByText("MCP Servers")).toBeInTheDocument();
- });
-
- // Wait for the mocked data to render in the table
await waitFor(() => {
expect(screen.getByText("Test Server 1")).toBeInTheDocument();
});
-
- // Verify the mocked server data is rendered in the table
- expect(screen.getByText("Test Server 1")).toBeInTheDocument();
expect(screen.getByText("Test Server 2")).toBeInTheDocument();
expect(screen.getAllByText("test-server-1").length).toBeGreaterThan(0);
expect(screen.getAllByText("test-server-2").length).toBeGreaterThan(0);
-
- // Verify the API was called
- // Note: useMCPServers uses useAuthorized() internally, which returns "123" from global mock
+ // useMCPServers reads the token from the global useAuthorized mock
expect(networking.fetchMCPServers).toHaveBeenCalledWith("123", undefined);
});
it("should fetch and merge health status for servers", async () => {
- // Mock MCP servers data without health status
- const mockServers = [
- {
- server_id: "server-1",
- server_name: "Test Server 1",
- alias: "test-server-1",
- url: "https://example.com/mcp",
- transport: "http",
- auth_type: "none",
- created_at: "2024-01-01T00:00:00Z",
- created_by: "user-1",
- updated_at: "2024-01-01T00:00:00Z",
- updated_by: "user-1",
- teams: [],
- mcp_access_groups: [],
- status: undefined,
- },
- {
- server_id: "server-2",
- server_name: "Test Server 2",
- alias: "test-server-2",
- url: "https://example2.com/mcp",
- transport: "sse",
- auth_type: "api_key",
- created_at: "2024-01-02T00:00:00Z",
- created_by: "user-2",
- updated_at: "2024-01-02T00:00:00Z",
- updated_by: "user-2",
- teams: [],
- mcp_access_groups: ["group-1"],
- status: undefined,
- },
- ];
-
- // Mock health status data
- const mockHealthStatuses = [
+ vi.mocked(networking.fetchMCPServers).mockResolvedValue([
+ makeServer({ server_id: "server-1" }),
+ makeServer({ server_id: "server-2" }),
+ ]);
+ vi.mocked(networking.fetchMCPServerHealth).mockResolvedValue([
{ server_id: "server-1", status: "healthy" },
{ server_id: "server-2", status: "unhealthy" },
- ];
+ ]);
- vi.mocked(networking.fetchMCPServers).mockResolvedValue(mockServers);
- vi.mocked(networking.fetchMCPServerHealth).mockResolvedValue(mockHealthStatuses);
+ renderWithProviders();
- const queryClient = createQueryClient();
- render(
-
-
- ,
- );
-
- // Wait for the component to load
- await waitFor(() => {
- expect(screen.getByText("MCP Servers")).toBeInTheDocument();
- });
-
- // Verify the health check API was called (without a server ID filter — the hook always
- // fetches health for all servers so the query key stays stable)
await waitFor(() => {
expect(networking.fetchMCPServerHealth).toHaveBeenCalledWith("123");
});
});
it("should display loading state while health check is in progress", async () => {
- const mockServers = [
- {
- server_id: "server-1",
- server_name: "Test Server 1",
- alias: "test-server-1",
- url: "https://example.com/mcp",
- transport: "http",
- auth_type: "none",
- created_at: "2024-01-01T00:00:00Z",
- created_by: "user-1",
- updated_at: "2024-01-01T00:00:00Z",
- updated_by: "user-1",
- teams: [],
- mcp_access_groups: [],
- },
- ];
+ vi.mocked(networking.fetchMCPServers).mockResolvedValue([makeServer({ server_id: "server-1" })]);
+ vi.mocked(networking.fetchMCPServerHealth).mockImplementation(() => new Promise(() => {}));
- vi.mocked(networking.fetchMCPServers).mockResolvedValue(mockServers);
- // Mock health check to never resolve (to test loading state)
- vi.mocked(networking.fetchMCPServerHealth).mockImplementation(
- () => new Promise(() => {}), // Never resolves
- );
+ renderWithProviders();
- const queryClient = createQueryClient();
- render(
-
-
- ,
- );
-
- // Wait for the component to load
- await waitFor(() => {
- expect(screen.getByText("MCP Servers")).toBeInTheDocument();
- });
-
- // Verify that health check was initiated
await waitFor(() => {
expect(networking.fetchMCPServerHealth).toHaveBeenCalled();
});
});
it("should filter servers by team when a team is selected", async () => {
- // Mock MCP servers with different teams
- const mockServers = [
- {
+ vi.mocked(networking.fetchMCPServers).mockResolvedValue([
+ makeServer({
server_id: "server-1",
server_name: "Team A Server",
- alias: "team-a-server",
- url: "https://example.com/mcp",
- transport: "http",
- auth_type: "none",
- created_at: "2024-01-01T00:00:00Z",
- created_by: "user-1",
- updated_at: "2024-01-01T00:00:00Z",
- updated_by: "user-1",
teams: [{ team_id: "team-a", team_alias: "Team A" }],
- mcp_access_groups: [],
- },
- {
+ }),
+ makeServer({
server_id: "server-2",
server_name: "Team B Server",
- alias: "team-b-server",
- url: "https://example2.com/mcp",
- transport: "sse",
- auth_type: "api_key",
- created_at: "2024-01-02T00:00:00Z",
- created_by: "user-2",
- updated_at: "2024-01-02T00:00:00Z",
- updated_by: "user-2",
teams: [{ team_id: "team-b", team_alias: "Team B" }],
- mcp_access_groups: [],
- },
- {
+ }),
+ makeServer({
server_id: "server-3",
server_name: "Team A Server 2",
- alias: "team-a-server-2",
- url: "https://example3.com/mcp",
- transport: "http",
- auth_type: "none",
- created_at: "2024-01-03T00:00:00Z",
- created_by: "user-1",
- updated_at: "2024-01-03T00:00:00Z",
- updated_by: "user-1",
teams: [{ team_id: "team-a", team_alias: "Team A" }],
- mcp_access_groups: [],
- },
- ];
+ }),
+ ]);
- vi.mocked(networking.fetchMCPServers).mockResolvedValue(mockServers);
- vi.mocked(networking.fetchMCPServerHealth).mockResolvedValue([]);
+ renderWithProviders();
- const queryClient = createQueryClient();
- render(
-
-
- ,
- );
-
- // Wait for the component to load
- await waitFor(() => {
- expect(screen.getByText("MCP Servers")).toBeInTheDocument();
- });
-
- // Wait for servers to be rendered
await waitFor(() => {
expect(screen.getByText("Team A Server")).toBeInTheDocument();
});
-
- // Verify all servers are initially displayed
- expect(screen.getByText("Team A Server")).toBeInTheDocument();
expect(screen.getByText("Team B Server")).toBeInTheDocument();
expect(screen.getByText("Team A Server 2")).toBeInTheDocument();
- // Find the team select by its "Team" label, then the combobox it labels
- const teamLabel = screen.getByText("Team");
- const teamSelect = within(teamLabel.parentElement!).getByRole("combobox");
+ await chooseSelectOption(userEvent, selectNextTo("Team"), "Team A");
- await userEvent.click(teamSelect);
-
- // Pick the "Team A" option once the listbox opens
- const teamAOption = await screen.findByText("Team A");
- await userEvent.click(teamAOption);
-
- // Wait for filtering to complete
await waitFor(() => {
- // Team A servers should still be visible
- expect(screen.getByText("Team A Server")).toBeInTheDocument();
- expect(screen.getByText("Team A Server 2")).toBeInTheDocument();
+ expect(screen.queryByText("Team B Server")).not.toBeInTheDocument();
});
-
- // Team B server should not be visible
- expect(screen.queryByText("Team B Server")).not.toBeInTheDocument();
+ expect(screen.getByText("Team A Server")).toBeInTheDocument();
+ expect(screen.getByText("Team A Server 2")).toBeInTheDocument();
});
it("should not trigger an extra health check when the server list changes after deletion", async () => {
- // Regression test: previously useMCPServerHealth received serverIds derived from the
- // server list. Deleting a server changed serverIds, which changed the React Query key,
- // which caused a new health check request for every remaining server.
- //
- // Fix: useMCPServerHealth uses a stable, argument-free query key. The component
- // re-rendering with a shorter server list must NOT produce a second health fetch.
- const twoServers = [
- {
- server_id: "server-1",
- server_name: "Test Server 1",
- alias: "test-server-1",
- url: "https://example.com/mcp",
- transport: "http",
- auth_type: "none",
- created_at: "2024-01-01T00:00:00Z",
- created_by: "user-1",
- updated_at: "2024-01-01T00:00:00Z",
- updated_by: "user-1",
- teams: [],
- mcp_access_groups: [],
- },
- {
- server_id: "server-2",
- server_name: "Test Server 2",
- alias: "test-server-2",
- url: "https://example2.com/mcp",
- transport: "sse",
- auth_type: "api_key",
- created_at: "2024-01-02T00:00:00Z",
- created_by: "user-2",
- updated_at: "2024-01-02T00:00:00Z",
- updated_by: "user-2",
- teams: [],
- mcp_access_groups: [],
- },
- ];
- const oneServer = twoServers.slice(0, 1);
-
- // First call returns two servers; second (after deletion) returns one
- vi.mocked(networking.fetchMCPServers).mockResolvedValueOnce(twoServers).mockResolvedValueOnce(oneServer);
+ // Regression: the health query key must not depend on the server list, or a shorter
+ // list after a deletion would trigger a second health fetch.
+ const twoServers = [makeServer({ server_id: "server-1" }), makeServer({ server_id: "server-2" })];
+ vi.mocked(networking.fetchMCPServers)
+ .mockResolvedValueOnce(twoServers)
+ .mockResolvedValueOnce(twoServers.slice(0, 1));
vi.mocked(networking.fetchMCPServerHealth).mockResolvedValue([
{ server_id: "server-1", status: "healthy" },
{ server_id: "server-2", status: "healthy" },
]);
- // Use a shared queryClient with a non-zero gcTime so cached health data survives
- // the re-render triggered by the server list refresh
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, gcTime: 60_000 } },
- });
+ const { rerender } = renderWithProviders();
- const { rerender } = render(
-
-
- ,
- );
-
- // Wait for the initial health fetch to complete
await waitFor(() => {
expect(networking.fetchMCPServerHealth).toHaveBeenCalledTimes(1);
});
- // Simulate what happens after a server is deleted: the server list query is
- // refetched (returns oneServer), causing the component to re-render with the
- // shorter list.
await act(async () => {
- await queryClient.invalidateQueries({ queryKey: ["mcpServers"] });
+ await testQueryClient.invalidateQueries({ queryKey: ["mcpServers"] });
});
+ rerender();
- rerender(
-
-
- ,
- );
-
- // The server list refresh must NOT trigger a second health check
expect(networking.fetchMCPServerHealth).toHaveBeenCalledTimes(1);
});
+
+ describe("URL state", () => {
+ beforeEach(() => {
+ vi.mocked(networking.fetchMCPServers).mockResolvedValue(urlServers);
+ });
+
+ it.each([
+ ["toolsets", "Toolsets"],
+ ["connect", "Connect"],
+ ["semantic-filter", "Semantic Filter"],
+ ["tool-search", "Tool Search"],
+ ["network", "Network Settings"],
+ ["submitted", "Submitted MCPs"],
+ ])("opens the %s tab from the URL for an admin", (value, name) => {
+ renderPage(`?tab=${value}`);
+
+ expect(screen.getByRole("tab", { name })).toHaveAttribute("aria-selected", "true");
+ });
+
+ it("opens the tab named in the URL and writes the tab the user picks", async () => {
+ const onUrlUpdate = renderPage("?tab=toolsets");
+
+ expect(screen.getByRole("tab", { name: "Toolsets" })).toHaveAttribute("aria-selected", "true");
+
+ await userEvent.click(screen.getByRole("tab", { name: "Network Settings" }));
+
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("tab")).toBe("network");
+ expect(screen.getByRole("tab", { name: "Network Settings" })).toHaveAttribute("aria-selected", "true");
+ });
+
+ it("drops an admin-only tab from the URL for a non-admin", async () => {
+ const onUrlUpdate = renderPageKeepingMountWrites("?tab=submitted", { userRole: "Internal User" });
+
+ expect(screen.getByRole("tab", { name: "All Servers" })).toHaveAttribute("aria-selected", "true");
+ expect(screen.queryByRole("tab", { name: "Submitted MCPs" })).not.toBeInTheDocument();
+ await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
+ expect(lastUrl(onUrlUpdate)?.searchParams.has("tab")).toBe(false);
+ });
+
+ it("orders the cards by the sort in the URL", async () => {
+ renderPage("?sort=name_asc");
+
+ await screen.findByText("Alpha");
+ expect(shownServerNames()).toEqual(["Alpha", "Bravo", "Charlie"]);
+ expect(selectNextTo("Sort")).toHaveTextContent("Name (A→Z)");
+ });
+
+ it("falls back to newest first for an unknown sort", async () => {
+ renderPage("?sort=bogus");
+
+ await screen.findByText("Alpha");
+ expect(shownServerNames()).toEqual(["Charlie", "Bravo", "Alpha"]);
+ });
+
+ it("writes the sort the user picks", async () => {
+ const onUrlUpdate = renderPage("");
+ await screen.findByText("Alpha");
+ expect(shownServerNames()).toEqual(["Charlie", "Bravo", "Alpha"]);
+
+ await chooseSelectOption(userEvent, selectNextTo("Sort"), "Name (A→Z)");
+
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("sort")).toBe("name_asc");
+ expect(shownServerNames()).toEqual(["Alpha", "Bravo", "Charlie"]);
+ });
+
+ it("filters by the team and access group in the URL", async () => {
+ renderPage("?team=team-a&access_group=group-x");
+
+ await screen.findByText("Alpha");
+ expect(shownServerNames()).toEqual(["Alpha"]);
+ expect(selectNextTo("Team")).toHaveTextContent("Team A");
+ expect(selectNextTo("Access Group")).toHaveTextContent("group-x");
+ });
+
+ it("writes the team and access group the user picks", async () => {
+ const onUrlUpdate = renderPage("");
+ await screen.findByText("Alpha");
+
+ await chooseSelectOption(userEvent, selectNextTo("Team"), "Team A");
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("team")).toBe("team-a");
+ expect(shownServerNames()).toEqual(["Charlie", "Alpha"]);
+
+ await chooseSelectOption(userEvent, selectNextTo("Access Group"), "group-x");
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("access_group")).toBe("group-x");
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("team")).toBe("team-a");
+ expect(shownServerNames()).toEqual(["Alpha"]);
+
+ await chooseSelectOption(userEvent, selectNextTo("Team"), "All Servers");
+ expect(lastUrl(onUrlUpdate)?.searchParams.has("team")).toBe(false);
+ });
+
+ it("searches by the query in the URL and writes what the user types", async () => {
+ const onUrlUpdate = renderPage("?search=brav");
+
+ await screen.findByText("Bravo");
+ expect(shownServerNames()).toEqual(["Bravo"]);
+ const searchBox = screen.getByPlaceholderText("Search by name, alias, URL, or ID");
+ expect(searchBox).toHaveValue("brav");
+
+ fireEvent.change(searchBox, { target: { value: "charlie" } });
+
+ await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.get("search")).toBe("charlie"));
+ expect(shownServerNames()).toEqual(["Charlie"]);
+ });
+
+ it("says no server matches when a URL filter excludes every server", async () => {
+ renderPage("?team=unknown-team");
+
+ expect(await screen.findByText("No servers match the current filters or search.")).toBeInTheDocument();
+ expect(screen.queryByText(/No MCP servers configured/)).not.toBeInTheDocument();
+ });
+
+ it("says no servers are configured when the proxy has none", async () => {
+ vi.mocked(networking.fetchMCPServers).mockResolvedValue([]);
+ renderPage("?team=team-a");
+
+ expect(await screen.findByText(/No MCP servers configured/)).toBeInTheDocument();
+ });
+
+ it("opens the server in the URL even when the filters hide it", async () => {
+ renderPage("?server=bravo&team=team-a");
+
+ expect(await screen.findByText("viewing Bravo")).toBeInTheDocument();
+ expect(screen.getByText("settings read only")).toBeInTheDocument();
+ });
+
+ it("shows the list instead of a placeholder detail for an unknown server", async () => {
+ renderPage("?server=missing");
+
+ await screen.findByText("Alpha");
+ expect(screen.queryByRole("region", { name: "server detail" })).not.toBeInTheDocument();
+ });
+
+ it("pushes the clicked server and clears it on Back", async () => {
+ const onUrlUpdate = renderPage("?team=team-a&tool=stale&tool_search=old");
+
+ await screen.findByText("Charlie");
+ await userEvent.click(cardFor("Charlie"));
+
+ expect(await screen.findByText("viewing Charlie")).toBeInTheDocument();
+ expect(screen.getByText("settings editable")).toBeInTheDocument();
+ const opened = lastUrl(onUrlUpdate);
+ expect(opened?.searchParams.get("server")).toBe("charlie");
+ expect(opened?.searchParams.has("tool")).toBe(false);
+ expect(opened?.searchParams.has("tool_search")).toBe(false);
+ expect(opened?.searchParams.get("team")).toBe("team-a");
+ expect(opened?.options.history).toBe("push");
+
+ await userEvent.click(screen.getByRole("button", { name: "Back to All Servers" }));
+
+ expect(await screen.findByText("Alpha")).toBeInTheDocument();
+ const closed = lastUrl(onUrlUpdate);
+ expect(closed?.searchParams.has("server")).toBe(false);
+ expect(closed?.searchParams.get("team")).toBe("team-a");
+ expect(closed?.options.history).toBe("push");
+ });
+
+ it("clears the server tab, tool and tool search on Back but keeps the filters", async () => {
+ const onUrlUpdate = renderPage("?server=charlie&server_tab=tools&tool=search_docs&tool_search=se&team=team-a");
+
+ await userEvent.click(await screen.findByRole("button", { name: "Back to All Servers" }));
+
+ expect(await screen.findByText("Alpha")).toBeInTheDocument();
+ const closed = lastUrl(onUrlUpdate);
+ for (const key of ["server", "server_tab", "tool", "tool_search"]) {
+ expect(closed?.searchParams.has(key)).toBe(false);
+ }
+ expect(closed?.searchParams.get("team")).toBe("team-a");
+ });
+
+ it("opens a clicked server on its overview tab", async () => {
+ const onUrlUpdate = renderPage("?server=missing&server_tab=settings");
+
+ await screen.findByText("Alpha");
+ await userEvent.click(cardFor("Alpha"));
+
+ expect(await screen.findByText("viewing Alpha")).toBeInTheDocument();
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("server")).toBe("alpha");
+ expect(lastUrl(onUrlUpdate)?.searchParams.has("server_tab")).toBe(false);
+ });
+
+ it("opens the env vars modal for fill_env_vars once and drops the key", async () => {
+ const onUrlUpdate = renderPageKeepingMountWrites("?fill_env_vars=bravo&team=team-a");
+
+ expect(await screen.findByText("fill fields for Bravo")).toBeInTheDocument();
+ await waitFor(() => expect(lastUrl(onUrlUpdate)?.searchParams.has("fill_env_vars")).toBe(false));
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("team")).toBe("team-a");
+
+ await userEvent.click(screen.getByRole("button", { name: "Close env vars" }));
+
+ expect(screen.queryByRole("region", { name: "fill env vars" })).not.toBeInTheDocument();
+ });
+
+ it("returns to the tools tab of the server after a tools OAuth redirect", async () => {
+ setSecureItem(TOOLS_OAUTH_UI_STATE_KEY, JSON.stringify({ serverId: "alpha" }));
+
+ const onUrlUpdate = renderPageKeepingMountWrites("");
+
+ expect(await screen.findByText("viewing Alpha")).toBeInTheDocument();
+ expect(screen.getByText("settings read only")).toBeInTheDocument();
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("server")).toBe("alpha");
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("server_tab")).toBe("tools");
+ expect(window.sessionStorage.getItem(TOOLS_OAUTH_UI_STATE_KEY)).toBeNull();
+
+ await userEvent.click(screen.getByRole("button", { name: "Back to All Servers" }));
+
+ expect(await screen.findByText("Alpha")).toBeInTheDocument();
+ expect(screen.queryByRole("region", { name: "server detail" })).not.toBeInTheDocument();
+ expect(lastUrl(onUrlUpdate)?.searchParams.has("server")).toBe(false);
+ });
+
+ it("returns to the editable settings of the server after an edit OAuth redirect", async () => {
+ setSecureItem(EDIT_OAUTH_UI_STATE_KEY, JSON.stringify({ serverId: "charlie" }));
+
+ const onUrlUpdate = renderPageKeepingMountWrites("");
+
+ expect(await screen.findByText("viewing Charlie")).toBeInTheDocument();
+ expect(screen.getByText("settings editable")).toBeInTheDocument();
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("server")).toBe("charlie");
+ expect(lastUrl(onUrlUpdate)?.searchParams.get("server_tab")).toBe("settings");
+ expect(window.sessionStorage.getItem(EDIT_OAUTH_UI_STATE_KEY)).not.toBeNull();
+ });
+
+ it("keeps the server in the URL over a stale edit OAuth state and drops that state", async () => {
+ setSecureItem(EDIT_OAUTH_UI_STATE_KEY, JSON.stringify({ serverId: "charlie" }));
+
+ const onUrlUpdate = renderPageKeepingMountWrites("?server=bravo");
+
+ expect(await screen.findByText("viewing Bravo")).toBeInTheDocument();
+ expect(screen.getByText("settings read only")).toBeInTheDocument();
+ expect(onUrlUpdate.mock.calls.some(([update]) => update.searchParams.get("server") === "charlie")).toBe(false);
+ expect(window.sessionStorage.getItem(EDIT_OAUTH_UI_STATE_KEY)).toBeNull();
+ });
+
+ it("drops an edit OAuth state whose server no longer exists", async () => {
+ setSecureItem(EDIT_OAUTH_UI_STATE_KEY, JSON.stringify({ serverId: "deleted" }));
+
+ renderPageKeepingMountWrites("");
+
+ await screen.findByText("Alpha");
+ await waitFor(() => expect(window.sessionStorage.getItem(EDIT_OAUTH_UI_STATE_KEY)).toBeNull());
+ expect(screen.queryByRole("region", { name: "server detail" })).not.toBeInTheDocument();
+ });
+
+ it.each([
+ ["not json"],
+ [JSON.stringify({ serverId: 7 })],
+ [JSON.stringify({})],
+ [JSON.stringify({ serverId: "" })],
+ ])("ignores the malformed stored OAuth state %s", async (stored) => {
+ setSecureItem(TOOLS_OAUTH_UI_STATE_KEY, stored);
+
+ const onUrlUpdate = renderPageKeepingMountWrites("");
+
+ await screen.findByText("Alpha");
+ expect(screen.queryByRole("region", { name: "server detail" })).not.toBeInTheDocument();
+ expect(onUrlUpdate.mock.calls.some(([update]) => update.searchParams.has("server"))).toBe(false);
+ });
+ });
});
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.tsx
index e6148d5d997..baa7284e143 100644
--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.tsx
+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/mcp_servers.tsx
@@ -15,7 +15,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
-import React, { useEffect, useState, useMemo, useCallback } from "react";
+import React, { useState, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";
import { useMCPServerHealth } from "@/app/(dashboard)/hooks/mcpServers/useMCPServerHealth";
@@ -40,14 +40,11 @@ import MCPToolSearchSettings from "@/components/Settings/AdminSettings/MCPToolSe
import MCPNetworkSettings from "./MCPNetworkSettings";
import MCPDiscovery from "./mcp_discovery";
import { ByokCredentialModal } from "@/components/mcp_tools/ByokCredentialModal";
-import { getSecureItem } from "@/utils/secureStorage";
-import { TOOLS_OAUTH_UI_STATE_KEY } from "@/hooks/mcpOAuthUtils";
import UserEnvVarsModal from "./UserEnvVarsModal";
import { listMCPUserEnvVarStatus } from "@/components/networking";
+import { type McpServerSortKey, useMcpServersUrlState } from "./useMcpServersUrlState";
-type SortKey = "created_desc" | "updated_desc" | "name_asc" | "health";
-
-const SORT_OPTIONS: { value: SortKey; label: string }[] = [
+const SORT_OPTIONS: { value: McpServerSortKey; label: string }[] = [
{ value: "created_desc", label: "Recently created" },
{ value: "updated_desc", label: "Recently updated" },
{ value: "name_asc", label: "Name (A→Z)" },
@@ -60,7 +57,7 @@ const HEALTH_RANK: Record = {
healthy: 2,
};
-const compareServers = (a: MCPServer, b: MCPServer, sort: SortKey): number => {
+const compareServers = (a: MCPServer, b: MCPServer, sort: McpServerSortKey): number => {
switch (sort) {
case "name_asc": {
const nameA = (a.server_name || a.alias || a.server_id).toLowerCase();
@@ -89,25 +86,20 @@ const compareServers = (a: MCPServer, b: MCPServer, sort: SortKey): number => {
}
};
-const EDIT_OAUTH_UI_STATE_KEY = "litellm-mcp-oauth-edit-state";
-
-// Server id stashed by the Tools tab before an OBO OAuth redirect, read once at
-// mount so the redirect returns straight to that server's Tools tab.
-const readToolsOAuthServerId = (): string | null => {
- if (typeof window === "undefined") {
- return null;
- }
- try {
- const stored = getSecureItem(TOOLS_OAUTH_UI_STATE_KEY);
- if (!stored) {
- return null;
- }
- return JSON.parse(stored)?.serverId ?? null;
- } catch {
- return null;
- }
+const createdAtDesc = (a: MCPServer, b: MCPServer): number => {
+ if (!a.created_at && !b.created_at) return 0;
+ if (!a.created_at) return 1;
+ if (!b.created_at) return -1;
+ return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
};
+type AccessGroupEntry = string | { name?: string } | null;
+
+const accessGroupName = (group: AccessGroupEntry) => (typeof group === "string" ? group : group?.name);
+
+const inAccessGroup = (server: MCPServer, group: string): boolean =>
+ (server.mcp_access_groups ?? []).some((entry: AccessGroupEntry) => accessGroupName(entry) === group);
+
const MCPServers: React.FC = ({ accessToken, userRole, userID }) => {
const { data: mcpServers, isLoading: isLoadingServers, refetch } = useMCPServers();
@@ -135,32 +127,35 @@ const MCPServers: React.FC = ({ accessToken, userRole, userID })
});
}, [mcpServers, healthStatuses]);
- // state
+ const isAdmin = userRole !== null && isAdminRole(userRole);
+ const {
+ tab,
+ setTab,
+ team: selectedTeam,
+ setTeam,
+ accessGroup: selectedMcpAccessGroup,
+ setAccessGroup,
+ search: searchQuery,
+ setSearch,
+ sort: sortKey,
+ setSort,
+ selectedServerId,
+ selectedServer,
+ editServer,
+ openServer,
+ closeServer,
+ envVarsDeepLinkId,
+ clearEnvVarsDeepLink,
+ } = useMcpServersUrlState(isAdmin, serversWithHealth, mcpServers !== undefined);
const [serverIdToDelete, setServerToDelete] = useState(null);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
- // Server whose Tools tab should be reopened after an OBO OAuth redirect; read
- // once from sessionStorage so the restored server selection is correct on the
- // first render. Cleared when the user navigates back to the list (handleBack)
- // so a later visit to the same server defaults to Overview, not the Tools tab.
- const [toolsTabServerId, setToolsTabServerId] = useState(readToolsOAuthServerId);
- const [selectedServerId, setSelectedServerId] = useState(toolsTabServerId);
- const [editServer, setEditServer] = useState(false);
- const [selectedTeam, setSelectedTeam] = useState("all");
- const [selectedMcpAccessGroup, setSelectedMcpAccessGroup] = useState("all");
- const [filteredServers, setFilteredServers] = useState([]);
const [isModalVisible, setModalVisible] = useState(false);
const [isDiscoveryVisible, setDiscoveryVisible] = useState(false);
const [isImportVisible, setImportVisible] = useState(false);
const [prefillData, setPrefillData] = useState(null);
const [isDeletingServer, setIsDeletingServer] = useState(false);
const [byokModalServer, setByokModalServer] = useState(null);
- // Per-user env-var fill modal target + deep-link source captured once from the URL.
const [envVarsModalServer, setEnvVarsModalServer] = useState(null);
- const [deepLinkServerId, setDeepLinkServerId] = useState(() =>
- typeof window === "undefined" ? null : new URLSearchParams(window.location.search).get("fill_env_vars"),
- );
- const [searchQuery, setSearchQuery] = useState("");
- const [sortKey, setSortKey] = useState("created_desc");
const isInternalUser = userRole === "Internal User";
// Single bulk fetch of this user's per-server env-var status. Drives the
@@ -180,58 +175,12 @@ const MCPServers: React.FC = ({ accessToken, userRole, userID })
return map;
}, [envVarStatuses]);
- // Deep-link via ?fill_env_vars= — the link users follow from the
- // friendly error the proxy returns when a per-user var is missing. The id is
- // captured into state above and resolved to a server below; here we only strip
- // the param so a refresh doesn't reopen the modal.
- useEffect(() => {
- if (!deepLinkServerId || typeof window === "undefined") return;
- const params = new URLSearchParams(window.location.search);
- if (!params.has("fill_env_vars")) return;
- params.delete("fill_env_vars");
- const newSearch = params.toString();
- const newUrl = window.location.pathname + (newSearch ? `?${newSearch}` : "") + window.location.hash;
- window.history.replaceState({}, "", newUrl);
- }, [deepLinkServerId]);
-
const deepLinkServer = useMemo(
- () => (deepLinkServerId ? serversWithHealth.find((s) => s.server_id === deepLinkServerId) ?? null : null),
- [deepLinkServerId, serversWithHealth],
+ () => (envVarsDeepLinkId ? serversWithHealth.find((s) => s.server_id === envVarsDeepLinkId) ?? null : null),
+ [envVarsDeepLinkId, serversWithHealth],
);
const activeEnvVarsServer = envVarsModalServer ?? deepLinkServer;
- useEffect(() => {
- if (typeof window === "undefined") {
- return;
- }
- try {
- const stored = getSecureItem(EDIT_OAUTH_UI_STATE_KEY);
- if (!stored) {
- return;
- }
- const parsed = JSON.parse(stored);
- if (parsed?.serverId) {
- setSelectedServerId(parsed.serverId);
- setEditServer(true);
- }
- } catch (err) {
- console.error("Failed to restore MCP edit view state", err);
- }
- }, []);
-
- // The restored server id was consumed by the initializer above; remove the
- // one-shot sessionStorage key so a full page reload doesn't reopen the Tools
- // tab (removeItem only, no setState).
- useEffect(() => {
- if (typeof window !== "undefined") {
- try {
- window.sessionStorage.removeItem(TOOLS_OAUTH_UI_STATE_KEY);
- } catch {
- // ignore storage errors
- }
- }
- }, []);
-
// Get unique teams from all servers
const uniqueTeams = React.useMemo(() => {
if (!serversWithHealth) return [];
@@ -280,50 +229,13 @@ const MCPServers: React.FC = ({ accessToken, userRole, userID })
[uniqueMcpAccessGroups],
);
- // Filtering logic for both team and access group
- const filterServers = useCallback(
- (teamId: string, group: string) => {
- if (!serversWithHealth) return setFilteredServers([]);
- let filtered = serversWithHealth;
- if (teamId === "personal") {
- setFilteredServers([]);
- return;
- }
- if (teamId !== "all") {
- filtered = filtered.filter((server) => server.teams?.some((team) => team.team_id === teamId));
- }
- if (group !== "all") {
- filtered = filtered.filter((server) =>
- server.mcp_access_groups?.some((g: any) => (typeof g === "string" ? g === group : g && g.name === group)),
- );
- }
- const sorted = [...filtered].sort((a, b) => {
- if (!a.created_at && !b.created_at) return 0;
- if (!a.created_at) return 1;
- if (!b.created_at) return -1;
- return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
- });
- setFilteredServers(sorted);
- },
- [serversWithHealth],
- );
-
- // Handle team filter change
- const handleTeamChange = (teamId: string) => {
- setSelectedTeam(teamId);
- filterServers(teamId, selectedMcpAccessGroup);
- };
-
- // Handle MCP access group filter change
- const handleMcpAccessGroupChange = (group: string) => {
- setSelectedMcpAccessGroup(group);
- filterServers(selectedTeam, group);
- };
-
- // Initial and effect-based filtering (trigger on query data updates and health data updates)
- useEffect(() => {
- filterServers(selectedTeam, selectedMcpAccessGroup);
- }, [serversWithHealth, selectedTeam, selectedMcpAccessGroup, filterServers]);
+ const filteredServers = useMemo(() => {
+ if (selectedTeam === "personal") return [];
+ return serversWithHealth
+ .filter((server) => selectedTeam === "all" || server.teams?.some((team) => team.team_id === selectedTeam))
+ .filter((server) => selectedMcpAccessGroup === "all" || inAccessGroup(server, selectedMcpAccessGroup))
+ .sort(createdAtDesc);
+ }, [serversWithHealth, selectedTeam, selectedMcpAccessGroup]);
// Search + sort layer applied on top of the team/access-group filters.
const displayedServers = useMemo(() => {
@@ -353,13 +265,8 @@ const MCPServers: React.FC = ({ accessToken, userRole, userID })
setIsDeletingServer(true);
await deleteMCPServer(accessToken, serverIdToDelete);
toast.success("Deleted MCP Server successfully");
- // If the user is currently viewing the detail page of the server they
- // just deleted, return them to the All Servers list. Otherwise the
- // detail view would stay mounted, fall back to an empty stub server,
- // and show a phantom "Unnamed Server" page.
if (selectedServerId === serverIdToDelete) {
- setEditServer(false);
- setSelectedServerId(null);
+ closeServer();
}
refetch();
} catch (error) {
@@ -381,38 +288,15 @@ const MCPServers: React.FC = ({ accessToken, userRole, userID })
? (mcpServers || []).find((server) => server.server_id === serverIdToDelete)
: null;
- const handleCreateSuccess = (newMcpServer: MCPServer) => {
- setFilteredServers((prev) => [...prev, newMcpServer]);
+ const handleCreateSuccess = () => {
setModalVisible(false);
refetch();
};
- // Memoize the selected server to prevent unnecessary re-renders
- const selectedServer = React.useMemo(() => {
- return (
- filteredServers.find((server: MCPServer) => server.server_id === selectedServerId) || {
- server_id: "",
- server_name: "",
- alias: "",
- url: "",
- transport: "",
- auth_type: "",
- created_at: "",
- created_by: "",
- updated_at: "",
- updated_by: "",
- }
- );
- }, [filteredServers, selectedServerId]);
-
- // Memoize the onBack callback to prevent unnecessary re-renders
const handleBack = React.useCallback(() => {
- setEditServer(false);
- setSelectedServerId(null);
- // Drop the post-redirect one-shot so re-selecting that server opens Overview.
- setToolsTabServerId(null);
+ closeServer();
refetch();
- }, [refetch]);
+ }, [closeServer, refetch]);
if (!accessToken || !userRole || !userID) {
return Missing required authentication parameters.
;
@@ -484,7 +368,7 @@ const MCPServers: React.FC = ({ accessToken, userRole, userID })
Configure and manage your MCP servers