mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-17 09:34:48 +00:00
Merge 70e822cc96 into 8fc9c46d1a
This commit is contained in:
commit
345b3b520a
14 changed files with 1253 additions and 660 deletions
|
|
@ -566,9 +566,6 @@
|
|||
"src/app/(dashboard)/mcp-servers/_components/mcp_connect.tsx": {
|
||||
"local/filename-pascal-case": {
|
||||
"count": 1
|
||||
},
|
||||
"react-hooks/static-components": {
|
||||
"count": 4
|
||||
}
|
||||
},
|
||||
"src/app/(dashboard)/mcp-servers/_components/mcp_connection_status.tsx": {
|
||||
|
|
@ -622,9 +619,6 @@
|
|||
},
|
||||
"no-nested-ternary": {
|
||||
"count": 1
|
||||
},
|
||||
"react-hooks/set-state-in-effect": {
|
||||
"count": 2
|
||||
}
|
||||
},
|
||||
"src/app/(dashboard)/mcp-servers/_components/mcp_tool_configuration.tsx": {
|
||||
|
|
@ -636,9 +630,6 @@
|
|||
"local/filename-pascal-case": {
|
||||
"count": 1
|
||||
},
|
||||
"local/no-complex-jsx-arrow": {
|
||||
"count": 1
|
||||
},
|
||||
"no-nested-ternary": {
|
||||
"count": 1
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,101 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import { MCPSubmissionsTab } from "./MCPSubmissionsTab";
|
||||
import { fetchMCPSubmissions } from "@/components/networking";
|
||||
import type { MCPServer, MCPSubmissionsSummary } from "@/components/mcp_tools/types";
|
||||
import { fireEvent, renderWithProviders, screen, waitFor } from "@/../tests/test-utils";
|
||||
|
||||
vi.mock("@/components/networking", () => ({
|
||||
fetchMCPSubmissions: vi.fn(),
|
||||
approveMCPServer: vi.fn(),
|
||||
rejectMCPServer: vi.fn(),
|
||||
getGeneralSettingsCall: vi.fn().mockResolvedValue({ data: [] }),
|
||||
updateConfigFieldSetting: vi.fn(),
|
||||
}));
|
||||
|
||||
const submission = (alias: string, approval_status: MCPServer["approval_status"]): MCPServer => ({
|
||||
server_id: `id-${alias}`,
|
||||
alias,
|
||||
url: `https://${alias}.example.com/mcp`,
|
||||
approval_status,
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
created_by: "user-1",
|
||||
updated_at: "2024-01-01T00:00:00Z",
|
||||
updated_by: "user-1",
|
||||
});
|
||||
|
||||
const SUBMISSION_NAMES = ["github-pending", "github-live", "linear-pending"];
|
||||
|
||||
const shownSubmissions = () =>
|
||||
screen
|
||||
.getAllByRole("heading", { level: 3 })
|
||||
.map((heading) => heading.textContent)
|
||||
.filter((name) => name !== null && SUBMISSION_NAMES.includes(name));
|
||||
|
||||
const renderTab = (searchParams: string, onUrlUpdate?: OnUrlUpdateFunction) =>
|
||||
renderWithProviders(<MCPSubmissionsTab accessToken="sk-test" />, { searchParams, onUrlUpdate });
|
||||
|
||||
const SUMMARY: MCPSubmissionsSummary = {
|
||||
total: 3,
|
||||
pending_review: 2,
|
||||
active: 1,
|
||||
rejected: 0,
|
||||
items: [
|
||||
submission("github-pending", "pending_review"),
|
||||
submission("github-live", "active"),
|
||||
submission("linear-pending", "pending_review"),
|
||||
],
|
||||
};
|
||||
|
||||
describe("MCPSubmissionsTab filter URL state", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(fetchMCPSubmissions).mockResolvedValue(SUMMARY);
|
||||
});
|
||||
|
||||
it("lists every submission without filters", async () => {
|
||||
renderTab("");
|
||||
|
||||
await screen.findByRole("heading", { level: 3, name: "linear-pending" });
|
||||
expect(shownSubmissions()).toEqual(SUBMISSION_NAMES);
|
||||
});
|
||||
|
||||
it("applies the search and status in the URL", async () => {
|
||||
renderTab("?sub_search=github&sub_status=pending_review");
|
||||
|
||||
await screen.findByRole("heading", { level: 3, name: "github-pending" });
|
||||
expect(shownSubmissions()).toEqual(["github-pending"]);
|
||||
expect(screen.getByPlaceholderText("Search MCP servers...")).toHaveValue("github");
|
||||
expect(screen.getByRole("combobox")).toHaveValue("pending_review");
|
||||
});
|
||||
|
||||
it("ignores an unknown status in the URL", async () => {
|
||||
renderTab("?sub_status=archived");
|
||||
|
||||
await screen.findByRole("heading", { level: 3, name: "linear-pending" });
|
||||
expect(shownSubmissions()).toEqual(SUBMISSION_NAMES);
|
||||
expect(screen.getByRole("combobox")).toHaveValue("all");
|
||||
});
|
||||
|
||||
it("writes the search and status the user picks", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderTab("?tab=submitted", onUrlUpdate);
|
||||
await screen.findByRole("heading", { level: 3, name: "linear-pending" });
|
||||
|
||||
fireEvent.change(screen.getByPlaceholderText("Search MCP servers..."), { target: { value: "pending" } });
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("sub_search")).toBe("pending"));
|
||||
expect(shownSubmissions()).toEqual(["github-pending", "linear-pending"]);
|
||||
|
||||
fireEvent.change(screen.getByRole("combobox"), { target: { value: "active" } });
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("sub_status")).toBe("active"));
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("sub_search")).toBe("pending");
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("tab")).toBe("submitted");
|
||||
expect(screen.getByText("No MCP server submissions match your filters.")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByRole("combobox"), { target: { value: "all" } });
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("sub_status")).toBe(false));
|
||||
expect(shownSubmissions()).toEqual(["github-pending", "linear-pending"]);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import { parseAsString, parseAsStringLiteral, useQueryStates } from "nuqs";
|
||||
import {
|
||||
SearchIcon,
|
||||
CheckIcon,
|
||||
|
|
@ -24,6 +25,17 @@ import { toast } from "@/lib/toast";
|
|||
|
||||
type MCPStatus = "active" | "pending_review" | "rejected";
|
||||
|
||||
const STATUS_FILTERS = ["all", "pending_review", "active", "rejected"] as const;
|
||||
type StatusFilter = (typeof STATUS_FILTERS)[number];
|
||||
|
||||
const submissionFilterParsers = {
|
||||
sub_search: parseAsString.withDefault(""),
|
||||
sub_status: parseAsStringLiteral(STATUS_FILTERS).withDefault("all"),
|
||||
};
|
||||
|
||||
const toStatusFilter = (value: string): StatusFilter | null =>
|
||||
STATUS_FILTERS.find((status) => status === value) ?? null;
|
||||
|
||||
const STATUS_CONFIG: Record<MCPStatus, { label: string; bg: string; text: string; dot: string }> = {
|
||||
active: {
|
||||
label: "Active",
|
||||
|
|
@ -456,8 +468,8 @@ export function MCPSubmissionsTab({ accessToken }: MCPSubmissionsTabProps) {
|
|||
rejected: 0,
|
||||
items: [],
|
||||
});
|
||||
const [search, setSearch] = useState("");
|
||||
const [statusFilter, setStatusFilter] = useState<"all" | MCPStatus>("all");
|
||||
const [{ sub_search: search, sub_status: statusFilter }, setSubmissionFilters] =
|
||||
useQueryStates(submissionFilterParsers);
|
||||
const [confirmAction, setConfirmAction] = useState<{
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
|
|
@ -578,13 +590,13 @@ export function MCPSubmissionsTab({ accessToken }: MCPSubmissionsTabProps) {
|
|||
type="text"
|
||||
placeholder="Search MCP servers..."
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
onChange={(e) => void setSubmissionFilters({ sub_search: e.target.value })}
|
||||
className="w-full pl-9 pr-4 py-2 border border-border rounded-md text-sm text-foreground placeholder:text-muted-foreground focus:outline-hidden focus:ring-1 focus:ring-ring focus:border-info"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value as typeof statusFilter)}
|
||||
onChange={(e) => void setSubmissionFilters({ sub_status: toStatusFilter(e.target.value) })}
|
||||
className="border border-border rounded-md px-3 py-2 text-sm text-foreground focus:outline-hidden focus:ring-1 focus:ring-ring focus:border-info bg-card"
|
||||
>
|
||||
<option value="all">All Status</option>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import React from "react";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import { MCPToolsetsTab } from "./MCPToolsetsTab";
|
||||
import { fireEvent, renderWithProviders, screen, waitFor, within } from "@/../tests/test-utils";
|
||||
import * as networking from "@/components/networking";
|
||||
import { useMCPToolsets } from "@/app/(dashboard)/hooks/mcpServers/useMCPToolsets";
|
||||
import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";
|
||||
|
|
@ -22,17 +22,13 @@ vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({ useMCPServe
|
|||
|
||||
const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
|
||||
|
||||
const renderTab = (toolsets: MCPToolset[] = []) => {
|
||||
const renderTab = (toolsets: MCPToolset[] = [], searchParams = "", onUrlUpdate?: OnUrlUpdateFunction) => {
|
||||
vi.mocked(useMCPToolsets).mockReturnValue({
|
||||
data: toolsets,
|
||||
isLoading: false,
|
||||
} as unknown as ReturnType<typeof useMCPToolsets>);
|
||||
vi.mocked(useMCPServers).mockReturnValue({ data: [] } as unknown as ReturnType<typeof useMCPServers>);
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } })}>
|
||||
<MCPToolsetsTab accessToken="sk-test" userRole="Admin" />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
renderWithProviders(<MCPToolsetsTab accessToken="sk-test" userRole="Admin" />, { searchParams, onUrlUpdate });
|
||||
};
|
||||
|
||||
const dialogWithButton = async (name: string) => {
|
||||
|
|
@ -195,3 +191,69 @@ describe("MCPToolsetsTab create/edit toolset form", () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
const makeToolset = (name: string, day: number): MCPToolset =>
|
||||
({
|
||||
toolset_id: `id-${name}`,
|
||||
toolset_name: name,
|
||||
description: "",
|
||||
tools: [],
|
||||
created_at: `2024-01-${String(day).padStart(2, "0")}T00:00:00Z`,
|
||||
}) as MCPToolset;
|
||||
|
||||
const shownToolsetNames = () => screen.getAllByText(/^ts-\d{2}$/).map((node) => node.textContent);
|
||||
|
||||
describe("MCPToolsetsTab table URL state", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const namedToolsets = [makeToolset("ts-02", 1), makeToolset("ts-03", 2), makeToolset("ts-01", 3)];
|
||||
const manyToolsets = Array.from({ length: 30 }, (_, index) =>
|
||||
makeToolset(`ts-${String(index + 1).padStart(2, "0")}`, index + 1),
|
||||
);
|
||||
|
||||
it("lists the newest toolsets first by default", () => {
|
||||
renderTab(namedToolsets);
|
||||
|
||||
expect(shownToolsetNames()).toEqual(["ts-01", "ts-03", "ts-02"]);
|
||||
});
|
||||
|
||||
it("orders the rows by the sort in the URL", () => {
|
||||
renderTab(namedToolsets, "?toolset_sort_by=toolset_name&toolset_sort_order=asc");
|
||||
|
||||
expect(shownToolsetNames()).toEqual(["ts-01", "ts-02", "ts-03"]);
|
||||
});
|
||||
|
||||
it("writes the sort the user picks under the toolset prefix", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderTab(namedToolsets, "?toolset_page=1", onUrlUpdate);
|
||||
|
||||
await userEvent.click(screen.getByTestId("sort-header-toolset_name"));
|
||||
|
||||
const update = onUrlUpdate.mock.calls.at(-1)?.[0];
|
||||
expect(update?.searchParams.get("toolset_sort_by")).toBe("toolset_name");
|
||||
expect(update?.searchParams.get("toolset_sort_order")).toBe("asc");
|
||||
expect(update?.searchParams.has("sort_by")).toBe(false);
|
||||
expect(shownToolsetNames()).toEqual(["ts-01", "ts-02", "ts-03"]);
|
||||
});
|
||||
|
||||
it("opens the page in the URL", () => {
|
||||
renderTab(manyToolsets, "?toolset_page=2");
|
||||
|
||||
expect(screen.getByText("Page 2 of 2")).toBeInTheDocument();
|
||||
expect(shownToolsetNames()).toEqual(["ts-05", "ts-04", "ts-03", "ts-02", "ts-01"]);
|
||||
});
|
||||
|
||||
it("writes the page the user moves to under the toolset prefix", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderTab(manyToolsets, "", onUrlUpdate);
|
||||
|
||||
expect(shownToolsetNames()).toHaveLength(25);
|
||||
await userEvent.click(screen.getByRole("button", { name: "Go to next page" }));
|
||||
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("toolset_page")).toBe("2");
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("page")).toBe(false);
|
||||
expect(shownToolsetNames()).toEqual(["ts-05", "ts-04", "ts-03", "ts-02", "ts-01"]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
import React, { useState, useCallback } from "react";
|
||||
import { z } from "zod/v4";
|
||||
import { SortingState } from "@tanstack/react-table";
|
||||
import { Inbox, Plus, X } from "lucide-react";
|
||||
import { useMCPToolsets } from "@/app/(dashboard)/hooks/mcpServers/useMCPToolsets";
|
||||
import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { DataTable } from "@/components/shared/DataTable";
|
||||
import { DataTable, useUrlTableState, type UrlTableStateOptions } from "@/components/shared/DataTable";
|
||||
import {
|
||||
createMCPToolset,
|
||||
updateMCPToolset,
|
||||
|
|
@ -37,6 +36,14 @@ const toolsetSchema = z.object({
|
|||
|
||||
type ToolsetFormValues = z.infer<typeof toolsetSchema>;
|
||||
|
||||
const TOOLSET_TABLE_STATE: UrlTableStateOptions<never> = {
|
||||
sortFields: ["toolset_name", "created_at"],
|
||||
defaultSort: { id: "created_at", desc: true },
|
||||
defaultPageSize: 25,
|
||||
filterColumns: [],
|
||||
keyPrefix: "toolset_",
|
||||
};
|
||||
|
||||
interface MCPToolListProps {
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
|
|
@ -418,7 +425,7 @@ export function MCPToolsetsTab({ accessToken, userRole }: MCPToolsetsTabProps) {
|
|||
() => new Map(mcpServers.map((s) => [s.server_id, s.alias || s.server_name || s.server_id])),
|
||||
[mcpServers],
|
||||
);
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const { sorting, onSortingChange, pagination, onPaginationChange } = useUrlTableState(TOOLSET_TABLE_STATE);
|
||||
const columns = React.useMemo(() => {
|
||||
const deps = {
|
||||
isAdmin,
|
||||
|
|
@ -456,7 +463,9 @@ export function MCPToolsetsTab({ accessToken, userRole }: MCPToolsetsTabProps) {
|
|||
getRowId={(toolset, index) => toolset.toolset_id || String(index)}
|
||||
sortingMode="client"
|
||||
sorting={sorting}
|
||||
onSortingChange={setSorting}
|
||||
onSortingChange={onSortingChange}
|
||||
pagination={pagination}
|
||||
onPaginationChange={onPaginationChange}
|
||||
isLoading={isLoading}
|
||||
loadingMessage="Loading toolsets…"
|
||||
noDataMessage={<ToolsetsEmptyState />}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import React from "react";
|
||||
import { render, screen, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import MCPConnect from "./mcp_connect";
|
||||
import { render, renderWithProviders, screen, waitFor, within } from "@/../tests/test-utils";
|
||||
|
||||
vi.mock("@/components/networking", () => ({
|
||||
getProxyBaseUrl: vi.fn().mockReturnValue("http://localhost:4000"),
|
||||
|
|
@ -12,7 +13,7 @@ const activePanel = () => screen.getByRole("tabpanel");
|
|||
|
||||
describe("MCPConnect (tab mount contract)", () => {
|
||||
it("keeps the x-mcp-servers header toggle on after switching tabs away and back", async () => {
|
||||
render(<MCPConnect />);
|
||||
renderWithProviders(<MCPConnect />);
|
||||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "LiteLLM Proxy" }));
|
||||
expect(within(activePanel()).queryByText(/"x-mcp-servers":/)).not.toBeInTheDocument();
|
||||
|
|
@ -27,3 +28,48 @@ describe("MCPConnect (tab mount contract)", () => {
|
|||
expect(within(activePanel()).getByText(/"x-mcp-servers": "Zapier_MCP,dev-group"/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("MCPConnect client tab URL state", () => {
|
||||
it.each([
|
||||
["litellm", "LiteLLM Proxy"],
|
||||
["cursor", "Cursor"],
|
||||
["http", "Streamable HTTP"],
|
||||
])("opens the %s client tab named in the URL", (value, name) => {
|
||||
renderWithProviders(<MCPConnect />, { searchParams: `?connect_client=${value}` });
|
||||
|
||||
expect(screen.getByRole("tab", { name })).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
|
||||
it("writes the client tab the user picks and drops the default", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderWithProviders(<MCPConnect />, { searchParams: "?tab=connect", onUrlUpdate });
|
||||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "LiteLLM Proxy" }));
|
||||
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("connect_client")).toBe("litellm");
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("tab")).toBe("connect");
|
||||
expect(screen.getByRole("tab", { name: "LiteLLM Proxy" })).toHaveAttribute("aria-selected", "true");
|
||||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "OpenAI API" }));
|
||||
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("connect_client")).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to the first client and drops an unknown one from the URL", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
render(
|
||||
<NuqsTestingAdapter
|
||||
searchParams="?connect_client=vim"
|
||||
onUrlUpdate={onUrlUpdate}
|
||||
hasMemory
|
||||
resetUrlUpdateQueueOnMount={false}
|
||||
>
|
||||
<MCPConnect />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
|
||||
expect(screen.getByRole("tab", { name: "OpenAI API" })).toHaveAttribute("aria-selected", "true");
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("connect_client")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,6 +21,9 @@ import {
|
|||
} from "lucide-react";
|
||||
import { getProxyBaseUrl } from "@/components/networking";
|
||||
import { copyToClipboard as utilCopyToClipboard } from "@/utils/dataUtils";
|
||||
import { useUrlTab } from "@/hooks/useUrlTab";
|
||||
|
||||
const CONNECT_CLIENTS = ["openai", "litellm", "cursor", "http"] as const;
|
||||
|
||||
interface CodeBlockProps {
|
||||
code: string;
|
||||
|
|
@ -126,31 +129,16 @@ const FeatureCard: React.FC<FeatureCardProps> = ({
|
|||
);
|
||||
};
|
||||
|
||||
interface MCPConnectProps {
|
||||
currentServerAccessGroups?: string[];
|
||||
}
|
||||
const CodeBlock: React.FC<CodeBlockProps> = ({ code, title, className = "" }) => {
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = [] }) => {
|
||||
const proxyBaseUrl = getProxyBaseUrl();
|
||||
const [copiedStates, setCopiedStates] = useState<Record<string, boolean>>({});
|
||||
const [currentServer] = useState("Zapier_MCP"); // This should match the current server being viewed
|
||||
|
||||
const copyToClipboard = async (text: string, key: string) => {
|
||||
const success = await utilCopyToClipboard(text);
|
||||
if (success) {
|
||||
setCopiedStates((prev) => ({ ...prev, [key]: true }));
|
||||
setTimeout(() => {
|
||||
setCopiedStates((prev) => ({ ...prev, [key]: false }));
|
||||
}, 2000);
|
||||
}
|
||||
const copyCode = async () => {
|
||||
if (!(await utilCopyToClipboard(code))) return;
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
const CodeBlock: React.FC<{
|
||||
code: string;
|
||||
copyKey: string;
|
||||
title?: string;
|
||||
className?: string;
|
||||
}> = ({ code, copyKey, title, className = "" }) => (
|
||||
return (
|
||||
<div className="relative group">
|
||||
{title && (
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
|
|
@ -163,40 +151,50 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []
|
|||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={() => copyToClipboard(code, copyKey)}
|
||||
onClick={copyCode}
|
||||
className={`absolute top-2 right-2 z-raised transition-all duration-200 ${
|
||||
copiedStates[copyKey]
|
||||
copied
|
||||
? "text-success bg-success/10 border-success/20"
|
||||
: "text-muted-foreground hover:text-foreground hover:bg-accent"
|
||||
}`}
|
||||
>
|
||||
{copiedStates[copyKey] ? <CheckIcon size={12} /> : <CopyIcon size={12} />}
|
||||
{copied ? <CheckIcon size={12} /> : <CopyIcon size={12} />}
|
||||
</Button>
|
||||
<pre className="text-sm overflow-x-auto pr-10 text-foreground font-mono leading-relaxed">{code}</pre>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const StepCard: React.FC<{
|
||||
step: number;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}> = ({ step, title, children }) => (
|
||||
<div className="flex gap-4">
|
||||
<div className="shrink-0">
|
||||
<div className="w-8 h-8 bg-info text-info-foreground rounded-full flex items-center justify-center text-sm font-semibold">
|
||||
{step}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<strong className="mb-2 block font-semibold text-foreground">{title}</strong>
|
||||
{children}
|
||||
const StepCard: React.FC<{
|
||||
step: number;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}> = ({ step, title, children }) => (
|
||||
<div className="flex gap-4">
|
||||
<div className="shrink-0">
|
||||
<div className="w-8 h-8 bg-info text-info-foreground rounded-full flex items-center justify-center text-sm font-semibold">
|
||||
{step}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
<div className="flex-1">
|
||||
<strong className="mb-2 block font-semibold text-foreground">{title}</strong>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const LiteLLMProxyTab = () => (
|
||||
interface MCPConnectProps {
|
||||
currentServerAccessGroups?: string[];
|
||||
}
|
||||
|
||||
const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = [] }) => {
|
||||
const proxyBaseUrl = getProxyBaseUrl();
|
||||
const [currentServer] = useState("Zapier_MCP"); // This should match the current server being viewed
|
||||
const [connectClient, setConnectClient] = useUrlTab(CONNECT_CLIENTS, "openai", "connect_client");
|
||||
|
||||
const liteLLMProxyTab = (
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="bg-linear-to-r from-success/15 to-success/5 p-6 rounded-lg border border-success/15">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
|
|
@ -266,7 +264,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []
|
|||
</div>
|
||||
);
|
||||
|
||||
const OpenAITab = () => (
|
||||
const openAITab = (
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="bg-linear-to-r from-info/15 to-info/5 p-6 rounded-lg border border-info/15">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
|
|
@ -346,7 +344,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []
|
|||
</div>
|
||||
);
|
||||
|
||||
const CursorTab = () => (
|
||||
const cursorTab = (
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="bg-linear-to-r from-purple-50 to-blue-50 p-6 rounded-lg border border-purple-100 dark:from-purple-950 dark:to-blue-950 dark:border-purple-900">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
|
|
@ -410,7 +408,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []
|
|||
</div>
|
||||
);
|
||||
|
||||
const StreamableHTTPTab = () => (
|
||||
const streamableHTTPTab = (
|
||||
<div className="flex w-full flex-col gap-6">
|
||||
<div className="bg-linear-to-r from-success/15 to-success/5 p-6 rounded-lg border border-success/15">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
|
|
@ -479,7 +477,7 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []
|
|||
</p>
|
||||
</div>
|
||||
|
||||
<Tabs defaultValue="openai" className="w-full">
|
||||
<Tabs value={connectClient} onValueChange={setConnectClient} className="w-full">
|
||||
<TabsList variant="line" className="mt-8 mb-6 h-auto w-full justify-start rounded-none border-b p-0">
|
||||
<div className="flex rounded-lg bg-muted p-1">
|
||||
<TabsTrigger value="openai" className="flex-none px-6 py-3">
|
||||
|
|
@ -509,16 +507,16 @@ const MCPConnect: React.FC<MCPConnectProps> = ({ currentServerAccessGroups = []
|
|||
</div>
|
||||
</TabsList>
|
||||
<TabsContent value="openai" keepMounted className="mt-6">
|
||||
<OpenAITab />
|
||||
{openAITab}
|
||||
</TabsContent>
|
||||
<TabsContent value="litellm" keepMounted className="mt-6">
|
||||
<LiteLLMProxyTab />
|
||||
{liteLLMProxyTab}
|
||||
</TabsContent>
|
||||
<TabsContent value="cursor" keepMounted className="mt-6">
|
||||
<CursorTab />
|
||||
{cursorTab}
|
||||
</TabsContent>
|
||||
<TabsContent value="http" keepMounted className="mt-6">
|
||||
<StreamableHTTPTab />
|
||||
{streamableHTTPTab}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { render, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { NuqsTestingAdapter, type OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import { MCPServerView } from "./mcp_server_view";
|
||||
import type { MCPServer } from "@/components/mcp_tools/types";
|
||||
import { setSecureItem } from "@/utils/secureStorage";
|
||||
import { render, renderWithProviders, screen, waitFor, within } from "@/../tests/test-utils";
|
||||
|
||||
vi.mock(".", () => ({
|
||||
MCPToolsViewer: () => <div>tools viewer</div>,
|
||||
|
|
@ -23,24 +25,48 @@ const baseServer = {
|
|||
auth_type: "api_key",
|
||||
} as MCPServer;
|
||||
|
||||
const renderView = (overrides: Partial<MCPServer> = {}, props: Record<string, unknown> = {}) =>
|
||||
const viewElement = (overrides: Partial<MCPServer>, props: Record<string, unknown>) => (
|
||||
<MCPServerView
|
||||
mcpServer={{ ...baseServer, ...overrides } as MCPServer}
|
||||
onBack={vi.fn()}
|
||||
isProxyAdmin
|
||||
isEditing={false}
|
||||
accessToken="tok"
|
||||
userRole="Admin"
|
||||
userID="u1"
|
||||
availableAccessGroups={[]}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
const renderView = (
|
||||
overrides: Partial<MCPServer> = {},
|
||||
props: Record<string, unknown> = {},
|
||||
searchParams = "",
|
||||
onUrlUpdate?: OnUrlUpdateFunction,
|
||||
) => renderWithProviders(viewElement(overrides, props), { searchParams, onUrlUpdate });
|
||||
|
||||
const renderViewKeepingMountWrites = (searchParams: string, props: Record<string, unknown>) => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
render(
|
||||
<MCPServerView
|
||||
mcpServer={{ ...baseServer, ...overrides } as MCPServer}
|
||||
onBack={vi.fn()}
|
||||
isProxyAdmin
|
||||
isEditing={false}
|
||||
accessToken="tok"
|
||||
userRole="Admin"
|
||||
userID="u1"
|
||||
availableAccessGroups={[]}
|
||||
{...props}
|
||||
/>,
|
||||
<NuqsTestingAdapter
|
||||
searchParams={searchParams}
|
||||
onUrlUpdate={onUrlUpdate}
|
||||
hasMemory
|
||||
resetUrlUpdateQueueOnMount={false}
|
||||
>
|
||||
{viewElement({}, props)}
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
return onUrlUpdate;
|
||||
};
|
||||
|
||||
const activePanel = () => screen.getByRole("tabpanel");
|
||||
|
||||
describe("MCPServerView", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
window.sessionStorage.clear();
|
||||
});
|
||||
|
||||
// Name, alias and description each label the header and a Settings row, so
|
||||
|
|
@ -86,7 +112,7 @@ describe("MCPServerView", () => {
|
|||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "MCP Tools" }));
|
||||
|
||||
expect(await screen.findByText("tools viewer")).toBeInTheDocument();
|
||||
expect(within(activePanel()).getByText("tools viewer")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the read-only settings summary before editing", async () => {
|
||||
|
|
@ -119,10 +145,61 @@ describe("MCPServerView", () => {
|
|||
expect(screen.queryByRole("button", { name: "Edit Settings" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens on the tab named by initialTabIndex", async () => {
|
||||
renderView({}, { initialTabIndex: 1 });
|
||||
it("opens on the server tab named in the URL", () => {
|
||||
renderView({}, {}, "?server=srv-1&server_tab=tools");
|
||||
|
||||
expect(await screen.findByText("tools viewer")).toBeInTheDocument();
|
||||
expect(screen.getByRole("tab", { name: "MCP Tools" })).toHaveAttribute("aria-selected", "true");
|
||||
expect(within(activePanel()).getByText("tools viewer")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the settings named in the URL for an admin", () => {
|
||||
renderView({}, {}, "?server_tab=settings");
|
||||
|
||||
expect(within(activePanel()).getByText("MCP Server Settings")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("writes the server tab the user picks and drops it for the default tab", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderView({}, {}, "?server=srv-1", onUrlUpdate);
|
||||
|
||||
expect(within(activePanel()).getByText("Host URL")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "Settings" }));
|
||||
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("server_tab")).toBe("settings");
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("server")).toBe("srv-1");
|
||||
expect(within(activePanel()).getByText("MCP Server Settings")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("tab", { name: "Overview" }));
|
||||
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("server_tab")).toBe(false);
|
||||
expect(within(activePanel()).getByText("Host URL")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("drops a settings tab from the URL for a non-admin", async () => {
|
||||
const onUrlUpdate = renderViewKeepingMountWrites("?server=srv-1&server_tab=settings", { isProxyAdmin: false });
|
||||
|
||||
expect(within(activePanel()).getByText("Host URL")).toBeInTheDocument();
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("server_tab")).toBe(false);
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("server")).toBe("srv-1");
|
||||
});
|
||||
|
||||
it("reopens the edit form when returning from an edit OAuth redirect for this server", () => {
|
||||
setSecureItem("litellm-mcp-oauth-edit-state", JSON.stringify({ serverId: "srv-1" }));
|
||||
|
||||
renderView({}, {}, "?server_tab=settings");
|
||||
|
||||
expect(within(activePanel()).getByText("edit form")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("stays read only when the edit OAuth redirect was for another server", () => {
|
||||
setSecureItem("litellm-mcp-oauth-edit-state", JSON.stringify({ serverId: "other" }));
|
||||
|
||||
renderView({}, {}, "?server_tab=settings");
|
||||
|
||||
expect(within(activePanel()).getByRole("button", { name: "Edit Settings" })).toBeInTheDocument();
|
||||
expect(screen.queryByText("edit form")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("returns to the server list when Back is pressed", async () => {
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ import MCPServerCostDisplay from "./mcp_server_cost_display";
|
|||
import { getMaskedAndFullUrl } from "./utils";
|
||||
import { copyToClipboard as utilCopyToClipboard } from "@/utils/dataUtils";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import { useMcpServerTab } from "./useMcpServersUrlState";
|
||||
|
||||
interface MCPServerViewProps {
|
||||
mcpServer: MCPServer;
|
||||
|
|
@ -24,12 +25,8 @@ interface MCPServerViewProps {
|
|||
userRole: string | null;
|
||||
userID: string | null;
|
||||
availableAccessGroups: string[];
|
||||
initialTabIndex?: number;
|
||||
}
|
||||
|
||||
// True when this render is the return from the edit-settings OAuth redirect for this
|
||||
// server: the edit form wrote its UI-state snapshot before redirecting. Used to open
|
||||
// the editing Settings tab on first render instead of defaulting to Overview.
|
||||
function isReturningFromEditOAuth(isProxyAdmin: boolean, serverId: string): boolean {
|
||||
if (typeof window === "undefined" || !isProxyAdmin) {
|
||||
return false;
|
||||
|
|
@ -54,15 +51,13 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
|
|||
userRole,
|
||||
userID,
|
||||
availableAccessGroups,
|
||||
initialTabIndex = 0,
|
||||
}) => {
|
||||
// Open the editing Settings tab on first render when returning from the edit OAuth
|
||||
// redirect, so the "token fetched" feedback shows where the user left off (Settings=2).
|
||||
const returningFromEditOAuth = isReturningFromEditOAuth(isProxyAdmin, mcpServer.server_id);
|
||||
const [editing, setEditing] = useState(isEditing || returningFromEditOAuth);
|
||||
const [editing, setEditing] = useState(
|
||||
() => isEditing || isReturningFromEditOAuth(isProxyAdmin, mcpServer.server_id),
|
||||
);
|
||||
const [showFullUrl, setShowFullUrl] = useState(false);
|
||||
const [copiedStates, setCopiedStates] = useState<Record<string, boolean>>({});
|
||||
const [selectedTabIndex, setSelectedTabIndex] = useState(returningFromEditOAuth ? 2 : initialTabIndex);
|
||||
const [serverTab, setServerTab] = useMcpServerTab(isProxyAdmin);
|
||||
|
||||
const handleSuccess = (updated: MCPServer) => {
|
||||
setEditing(false);
|
||||
|
|
@ -129,23 +124,23 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
|
|||
{mcpServer.description && <p className="mt-2 text-sm text-muted-foreground">{mcpServer.description}</p>}
|
||||
</div>
|
||||
|
||||
<Tabs value={String(selectedTabIndex)} onValueChange={(v: unknown) => setSelectedTabIndex(Number(v))}>
|
||||
<Tabs value={serverTab} onValueChange={setServerTab}>
|
||||
<TabsList variant="line" className="mb-4 h-auto w-full justify-start rounded-none border-b p-0">
|
||||
<TabsTrigger value="0" className="flex-none rounded-none px-4 py-2">
|
||||
<TabsTrigger value="overview" className="flex-none rounded-none px-4 py-2">
|
||||
Overview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="1" className="flex-none rounded-none px-4 py-2">
|
||||
<TabsTrigger value="tools" className="flex-none rounded-none px-4 py-2">
|
||||
MCP Tools
|
||||
</TabsTrigger>
|
||||
{isProxyAdmin && (
|
||||
<TabsTrigger value="2" className="flex-none rounded-none px-4 py-2">
|
||||
<TabsTrigger value="settings" className="flex-none rounded-none px-4 py-2">
|
||||
Settings
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
|
||||
{/* Overview Panel */}
|
||||
<TabsContent value="0" keepMounted>
|
||||
<TabsContent value="overview" keepMounted>
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Card className="p-4">
|
||||
<p className="text-xs font-medium tracking-wide text-muted-foreground uppercase">Transport</p>
|
||||
|
|
@ -192,7 +187,7 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
|
|||
</TabsContent>
|
||||
|
||||
{/* Tool Panel */}
|
||||
<TabsContent value="1" keepMounted>
|
||||
<TabsContent value="tools" keepMounted>
|
||||
<MCPToolsViewer
|
||||
serverId={mcpServer.server_id}
|
||||
accessToken={accessToken}
|
||||
|
|
@ -209,7 +204,7 @@ export const MCPServerView: React.FC<MCPServerViewProps> = ({
|
|||
</TabsContent>
|
||||
|
||||
{/* Settings Panel */}
|
||||
<TabsContent value="2" keepMounted>
|
||||
<TabsContent value="settings" keepMounted>
|
||||
<Card className="p-6">
|
||||
<div className="mb-4 flex items-center justify-between">
|
||||
<h2 className="text-lg font-medium">MCP Server Settings</h2>
|
||||
|
|
|
|||
|
|
@ -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) => (
|
||||
<section aria-label="server detail">
|
||||
<p>viewing {mcpServer.server_name}</p>
|
||||
<p>{isEditing ? "settings editable" : "settings read only"}</p>
|
||||
<button onClick={onBack}>Back to All Servers</button>
|
||||
</section>
|
||||
),
|
||||
}));
|
||||
|
||||
interface EnvVarsModalStubProps {
|
||||
server: MCPServer | null;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
vi.mock("./UserEnvVarsModal", () => ({
|
||||
default: ({ server, open, onClose }: EnvVarsModalStubProps) =>
|
||||
open && server ? (
|
||||
<section aria-label="fill env vars">
|
||||
<p>fill fields for {server.server_name}</p>
|
||||
<button onClick={onClose}>Close env vars</button>
|
||||
</section>
|
||||
) : 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<MCPServer> & Pick<MCPServer, "server_id">): 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<typeof vi.fn<OnUrlUpdateFunction>>) => 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<HTMLElement>('[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<typeof defaultProps> = {}) => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderWithProviders(<MCPServers {...defaultProps} {...props} />, { searchParams, onUrlUpdate });
|
||||
return onUrlUpdate;
|
||||
};
|
||||
|
||||
const renderPageKeepingMountWrites = (searchParams: string, props: Partial<typeof defaultProps> = {}) => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
render(
|
||||
<NuqsTestingAdapter
|
||||
searchParams={searchParams}
|
||||
onUrlUpdate={onUrlUpdate}
|
||||
hasMemory
|
||||
resetUrlUpdateQueueOnMount={false}
|
||||
>
|
||||
<QueryClientProvider client={testQueryClient}>
|
||||
<MCPServers {...defaultProps} {...props} />
|
||||
</QueryClientProvider>
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
renderWithProviders(<MCPServers {...defaultProps} />);
|
||||
|
||||
// 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(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
renderWithProviders(<MCPServers {...defaultProps} />);
|
||||
|
||||
// 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(<MCPServers {...defaultProps} />);
|
||||
|
||||
const queryClient = createQueryClient();
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
// 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(<MCPServers {...defaultProps} />);
|
||||
|
||||
const queryClient = createQueryClient();
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
// 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(<MCPServers {...defaultProps} />);
|
||||
|
||||
const queryClient = createQueryClient();
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
// 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(<MCPServers {...defaultProps} />);
|
||||
|
||||
const { rerender } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
// 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(<MCPServers {...defaultProps} />);
|
||||
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MCPServers {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<string, number> = {
|
|||
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<MCPServerProps> = ({ accessToken, userRole, userID }) => {
|
||||
const { data: mcpServers, isLoading: isLoadingServers, refetch } = useMCPServers();
|
||||
|
||||
|
|
@ -135,32 +127,35 @@ const MCPServers: React.FC<MCPServerProps> = ({ 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<string | null>(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<string | null>(readToolsOAuthServerId);
|
||||
const [selectedServerId, setSelectedServerId] = useState<string | null>(toolsTabServerId);
|
||||
const [editServer, setEditServer] = useState(false);
|
||||
const [selectedTeam, setSelectedTeam] = useState<string>("all");
|
||||
const [selectedMcpAccessGroup, setSelectedMcpAccessGroup] = useState<string>("all");
|
||||
const [filteredServers, setFilteredServers] = useState<MCPServer[]>([]);
|
||||
const [isModalVisible, setModalVisible] = useState(false);
|
||||
const [isDiscoveryVisible, setDiscoveryVisible] = useState(false);
|
||||
const [isImportVisible, setImportVisible] = useState(false);
|
||||
const [prefillData, setPrefillData] = useState<DiscoverableMCPServer | null>(null);
|
||||
const [isDeletingServer, setIsDeletingServer] = useState(false);
|
||||
const [byokModalServer, setByokModalServer] = useState<MCPServer | null>(null);
|
||||
// Per-user env-var fill modal target + deep-link source captured once from the URL.
|
||||
const [envVarsModalServer, setEnvVarsModalServer] = useState<MCPServer | null>(null);
|
||||
const [deepLinkServerId, setDeepLinkServerId] = useState<string | null>(() =>
|
||||
typeof window === "undefined" ? null : new URLSearchParams(window.location.search).get("fill_env_vars"),
|
||||
);
|
||||
const [searchQuery, setSearchQuery] = useState<string>("");
|
||||
const [sortKey, setSortKey] = useState<SortKey>("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<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
return map;
|
||||
}, [envVarStatuses]);
|
||||
|
||||
// Deep-link via ?fill_env_vars=<server_id> — 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<MCPServerProps> = ({ 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<MCPServerProps> = ({ 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<MCPServerProps> = ({ 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 <div className="p-6 text-center text-muted-foreground">Missing required authentication parameters.</div>;
|
||||
|
|
@ -484,7 +368,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
<p className="mt-1 text-sm text-muted-foreground">Configure and manage your MCP servers</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isAdminRole(userRole) && (
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Button className="shrink-0" variant="secondary" onClick={() => setImportVisible(true)}>
|
||||
Import from JSON
|
||||
|
|
@ -494,7 +378,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
</Button>
|
||||
</>
|
||||
)}
|
||||
{!isAdminRole(userRole) && (
|
||||
{!isAdmin && (
|
||||
<Button
|
||||
className="shrink-0"
|
||||
onClick={() => {
|
||||
|
|
@ -529,7 +413,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
}}
|
||||
accessToken={accessToken}
|
||||
/>
|
||||
<Tabs defaultValue="servers" className="mt-2 w-full">
|
||||
<Tabs value={tab} onValueChange={setTab} className="mt-2 w-full">
|
||||
<TabsList variant="line" className="h-auto w-full justify-start rounded-none border-b p-0">
|
||||
<TabsTrigger value="servers" className="flex-none rounded-none px-4 py-2">
|
||||
All Servers
|
||||
|
|
@ -540,40 +424,35 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
<TabsTrigger value="connect" className="flex-none rounded-none px-4 py-2">
|
||||
Connect
|
||||
</TabsTrigger>
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsTrigger value="semantic-filter" className="flex-none rounded-none px-4 py-2">
|
||||
Semantic Filter
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsTrigger value="tool-search" className="flex-none rounded-none px-4 py-2">
|
||||
Tool Search
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsTrigger value="network-settings" className="flex-none rounded-none px-4 py-2">
|
||||
Network Settings
|
||||
</TabsTrigger>
|
||||
)}
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsTrigger value="submitted" className="flex-none rounded-none px-4 py-2">
|
||||
Submitted MCPs
|
||||
</TabsTrigger>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<TabsTrigger value="semantic-filter" className="flex-none rounded-none px-4 py-2">
|
||||
Semantic Filter
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="tool-search" className="flex-none rounded-none px-4 py-2">
|
||||
Tool Search
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="network" className="flex-none rounded-none px-4 py-2">
|
||||
Network Settings
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="submitted" className="flex-none rounded-none px-4 py-2">
|
||||
Submitted MCPs
|
||||
</TabsTrigger>
|
||||
</>
|
||||
)}
|
||||
</TabsList>
|
||||
<TabsContent value="servers" keepMounted>
|
||||
{selectedServerId ? (
|
||||
{selectedServer ? (
|
||||
<MCPServerView
|
||||
key={selectedServerId}
|
||||
key={selectedServer.server_id}
|
||||
mcpServer={selectedServer}
|
||||
onBack={handleBack}
|
||||
isProxyAdmin={isAdminRole(userRole)}
|
||||
isProxyAdmin={isAdmin}
|
||||
isEditing={editServer}
|
||||
accessToken={accessToken}
|
||||
userID={userID}
|
||||
userRole={userRole}
|
||||
availableAccessGroups={uniqueMcpAccessGroups}
|
||||
initialTabIndex={selectedServerId === toolsTabServerId ? 1 : 0}
|
||||
/>
|
||||
) : (
|
||||
<div className="w-full h-full">
|
||||
|
|
@ -585,7 +464,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
<Select
|
||||
items={teamSelectItems}
|
||||
value={selectedTeam}
|
||||
onValueChange={(v: string | null) => handleTeamChange(v ?? "all")}
|
||||
onValueChange={(v: string | null) => setTeam(v)}
|
||||
>
|
||||
<SelectTrigger className="w-55">
|
||||
<SelectValue />
|
||||
|
|
@ -625,7 +504,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
<Select
|
||||
items={accessGroupSelectItems}
|
||||
value={selectedMcpAccessGroup}
|
||||
onValueChange={(v: string | null) => handleMcpAccessGroupChange(v ?? "all")}
|
||||
onValueChange={(v: string | null) => setAccessGroup(v)}
|
||||
>
|
||||
<SelectTrigger className="w-55">
|
||||
<SelectValue />
|
||||
|
|
@ -651,16 +530,12 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
<InputGroupInput
|
||||
placeholder="Search by name, alias, URL, or ID"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
</InputGroup>
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="text-sm font-medium whitespace-nowrap text-muted-foreground">Sort</p>
|
||||
<Select
|
||||
items={SORT_OPTIONS}
|
||||
value={sortKey}
|
||||
onValueChange={(v: string | null) => setSortKey((v ?? "created_desc") as SortKey)}
|
||||
>
|
||||
<Select items={SORT_OPTIONS} value={sortKey} onValueChange={(v: string | null) => setSort(v)}>
|
||||
<SelectTrigger className="w-55">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
|
|
@ -686,7 +561,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
) : displayedServers.length === 0 ? (
|
||||
<div className="rounded-lg border border-dashed border-border bg-card p-12 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{filteredServers.length === 0
|
||||
{serversWithHealth.length === 0
|
||||
? "No MCP servers configured. Click '+ Add New MCP Server' to get started."
|
||||
: "No servers match the current filters or search."}
|
||||
</p>
|
||||
|
|
@ -703,16 +578,13 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
missingUserFields={missingFieldsByServer[server.server_id]}
|
||||
isLoadingHealth={isLoadingHealth}
|
||||
isRechecking={recheckingServerIds?.has(server.server_id)}
|
||||
onClick={() => {
|
||||
setSelectedServerId(server.server_id);
|
||||
setEditServer(true);
|
||||
}}
|
||||
onClick={() => openServer(server.server_id)}
|
||||
onRecheckHealth={
|
||||
recheckServerHealth ? () => recheckServerHealth(server.server_id) : undefined
|
||||
}
|
||||
onByokConnect={server.is_byok ? () => setByokModalServer(server) : undefined}
|
||||
onOpenFillFields={() => setEnvVarsModalServer(server)}
|
||||
onDelete={isAdminRole(userRole) ? () => handleDelete(server.server_id) : undefined}
|
||||
onDelete={isAdmin ? () => handleDelete(server.server_id) : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -727,25 +599,21 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
<TabsContent value="connect" keepMounted>
|
||||
<MCPConnect />
|
||||
</TabsContent>
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsContent value="semantic-filter" keepMounted>
|
||||
<MCPSemanticFilterSettings accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
)}
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsContent value="tool-search" keepMounted>
|
||||
<MCPToolSearchSettings accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
)}
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsContent value="network-settings" keepMounted>
|
||||
<MCPNetworkSettings accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
)}
|
||||
{isAdminRole(userRole) && (
|
||||
<TabsContent value="submitted" keepMounted>
|
||||
<MCPSubmissionsTab accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<TabsContent value="semantic-filter" keepMounted>
|
||||
<MCPSemanticFilterSettings accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
<TabsContent value="tool-search" keepMounted>
|
||||
<MCPToolSearchSettings accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
<TabsContent value="network" keepMounted>
|
||||
<MCPNetworkSettings accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
<TabsContent value="submitted" keepMounted>
|
||||
<MCPSubmissionsTab accessToken={accessToken} />
|
||||
</TabsContent>
|
||||
</>
|
||||
)}
|
||||
</Tabs>
|
||||
|
||||
|
|
@ -768,7 +636,7 @@ const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID })
|
|||
accessToken={accessToken}
|
||||
onClose={() => {
|
||||
setEnvVarsModalServer(null);
|
||||
setDeepLinkServerId(null);
|
||||
clearEnvVarsDeepLink();
|
||||
}}
|
||||
onSaved={() => {
|
||||
// Refresh the bulk status so the red "N user fields missing" footer
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { parseAsString, useQueryState } from "nuqs";
|
||||
import type { OnUrlUpdateFunction } from "nuqs/adapters/testing";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import MCPToolsViewer from "./mcp_tools";
|
||||
import { listMCPTools, getMCPOAuthUserCredentialStatus } from "@/components/networking";
|
||||
import { callMCPTool, listMCPTools, getMCPOAuthUserCredentialStatus } from "@/components/networking";
|
||||
import type { MCPTool } from "@/components/mcp_tools/types";
|
||||
import { isTokenValid, getToken } from "@/utils/mcpTokenStore";
|
||||
import { fireEvent, renderWithProviders, screen, testQueryClient, waitFor } from "@/../tests/test-utils";
|
||||
|
||||
vi.mock("@/components/networking", () => ({
|
||||
listMCPTools: vi.fn(),
|
||||
|
|
@ -35,21 +38,25 @@ const GATE_TEXT = "Authentication required";
|
|||
// what makes the passthrough cases fail on the pre-fix code.
|
||||
const TOKEN_URL = "https://slack.com/api/oauth.v2.user.access";
|
||||
|
||||
const renderViewer = (props: Record<string, unknown>) =>
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
|
||||
<MCPToolsViewer
|
||||
serverId="srv-1"
|
||||
accessToken="litellm-key"
|
||||
userRole="admin"
|
||||
userID="tin@berri.ai"
|
||||
serverAlias="slack"
|
||||
auth_type="oauth2"
|
||||
tokenUrl={TOKEN_URL}
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
const viewer = (props: Record<string, unknown>) => (
|
||||
<MCPToolsViewer
|
||||
serverId="srv-1"
|
||||
accessToken="litellm-key"
|
||||
userRole="admin"
|
||||
userID="tin@berri.ai"
|
||||
serverAlias="slack"
|
||||
auth_type="oauth2"
|
||||
tokenUrl={TOKEN_URL}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
const renderViewer = (props: Record<string, unknown>, searchParams = "", onUrlUpdate?: OnUrlUpdateFunction) =>
|
||||
renderWithProviders(viewer(props), { searchParams, onUrlUpdate });
|
||||
|
||||
beforeEach(() => {
|
||||
testQueryClient.clear();
|
||||
});
|
||||
|
||||
const credStatus = (overrides: Record<string, unknown> = {}) => ({
|
||||
server_id: "srv-1",
|
||||
|
|
@ -215,3 +222,131 @@ describe("MCPToolsViewer auth gate routing", () => {
|
|||
expect(vi.mocked(getMCPOAuthUserCredentialStatus)).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
const makeTool = (name: string, description: string): MCPTool => ({
|
||||
name,
|
||||
description,
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
mcp_info: { server_name: "slack" },
|
||||
});
|
||||
|
||||
const M2M = { oauth2_flow: "client_credentials", delegate_auth_to_upstream: false };
|
||||
|
||||
describe("MCPToolsViewer URL state", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(listMCPTools)
|
||||
.mockReset()
|
||||
.mockResolvedValue({
|
||||
tools: [makeTool("search_docs", "Search the docs"), makeTool("fetch_page", "Fetch one page")],
|
||||
error: null,
|
||||
});
|
||||
vi.mocked(callMCPTool)
|
||||
.mockReset()
|
||||
.mockResolvedValue({ content: [{ type: "text", text: "tool output" }] });
|
||||
});
|
||||
|
||||
const toolListItem = (name: string) => screen.getByRole("heading", { level: 4, name });
|
||||
|
||||
it("opens the tool named in the URL and calls that tool", async () => {
|
||||
renderViewer(M2M, "?tool=fetch_page");
|
||||
|
||||
expect(await screen.findByText("Input Parameters")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Select a Tool to Test")).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Call Tool" }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(vi.mocked(callMCPTool)).toHaveBeenCalledWith(
|
||||
"litellm-key",
|
||||
"srv-1",
|
||||
"fetch_page",
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
),
|
||||
);
|
||||
expect(await screen.findByText("Tool executed successfully")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the empty playground for a tool the server does not list", async () => {
|
||||
renderViewer(M2M, "?tool=gone");
|
||||
|
||||
await screen.findByRole("heading", { level: 4, name: "search_docs" });
|
||||
expect(screen.getByText("Select a Tool to Test")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("pushes the clicked tool, clears it on close, and drops the previous result", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderViewer(M2M, "?server=srv-1&tool=search_docs", onUrlUpdate);
|
||||
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Call Tool" }));
|
||||
expect(await screen.findByText("Tool executed successfully")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(toolListItem("fetch_page"));
|
||||
|
||||
const picked = onUrlUpdate.mock.calls.at(-1)?.[0];
|
||||
expect(picked?.searchParams.get("tool")).toBe("fetch_page");
|
||||
expect(picked?.searchParams.get("server")).toBe("srv-1");
|
||||
expect(picked?.options.history).toBe("push");
|
||||
expect(await screen.findByText("Ready to Call Tool")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Tool executed successfully")).not.toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Close" }));
|
||||
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("tool")).toBe(false);
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].options.history).toBe("push");
|
||||
expect(await screen.findByText("Select a Tool to Test")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides the previous tool's result when the URL switches to another tool", async () => {
|
||||
const ToolLink = ({ name }: { name: string }) => {
|
||||
const [, setTool] = useQueryState("tool", parseAsString.withOptions({ history: "push" }));
|
||||
return <button onClick={() => void setTool(name)}>go to {name}</button>;
|
||||
};
|
||||
renderWithProviders(
|
||||
<>
|
||||
{viewer(M2M)}
|
||||
<ToolLink name="fetch_page" />
|
||||
</>,
|
||||
{ searchParams: "?tool=search_docs" },
|
||||
);
|
||||
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Call Tool" }));
|
||||
expect(await screen.findByText("Tool executed successfully")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "go to fetch_page" }));
|
||||
|
||||
expect(await screen.findByText("Ready to Call Tool")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Tool executed successfully")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("clears the previous result when the selected tool is picked again", async () => {
|
||||
renderViewer(M2M, "?tool=search_docs");
|
||||
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Call Tool" }));
|
||||
expect(await screen.findByText("Tool executed successfully")).toBeInTheDocument();
|
||||
|
||||
await userEvent.click(toolListItem("search_docs"));
|
||||
|
||||
expect(await screen.findByText("Ready to Call Tool")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters the tool list by the search in the URL and writes what the user types", async () => {
|
||||
const onUrlUpdate = vi.fn<OnUrlUpdateFunction>();
|
||||
renderViewer(M2M, "?tool_search=fetch", onUrlUpdate);
|
||||
|
||||
expect(await screen.findByRole("heading", { level: 4, name: "fetch_page" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("heading", { level: 4, name: "search_docs" })).not.toBeInTheDocument();
|
||||
const searchBox = screen.getByPlaceholderText("Search tools...");
|
||||
expect(searchBox).toHaveValue("fetch");
|
||||
|
||||
fireEvent.change(searchBox, { target: { value: "docs" } });
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get("tool_search")).toBe("docs"));
|
||||
expect(toolListItem("search_docs")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("heading", { level: 4, name: "fetch_page" })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.change(searchBox, { target: { value: "" } });
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.has("tool_search")).toBe(false));
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -26,6 +26,13 @@ import { Card } from "@/components/ui/card";
|
|||
import { InputGroup, InputGroupAddon, InputGroupInput } from "@/components/ui/input-group";
|
||||
import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";
|
||||
import { cn } from "@/lib/cva.config";
|
||||
import { useMcpToolUrlState } from "./useMcpServersUrlState";
|
||||
|
||||
interface ToolOutcome {
|
||||
toolName: string;
|
||||
result: MCPContent[] | null;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
const MCPToolsViewer = ({
|
||||
serverId,
|
||||
|
|
@ -39,10 +46,8 @@ const MCPToolsViewer = ({
|
|||
serverAlias,
|
||||
extraHeaders,
|
||||
}: MCPToolsViewerProps) => {
|
||||
const [selectedTool, setSelectedTool] = useState<MCPTool | null>(null);
|
||||
const [toolResult, setToolResult] = useState<MCPContent[] | null>(null);
|
||||
const [toolError, setToolError] = useState<Error | null>(null);
|
||||
const [toolSearchTerm, setToolSearchTerm] = useState("");
|
||||
const [{ tool: selectedToolName, tool_search: toolSearchTerm }, setToolUrlState] = useMcpToolUrlState();
|
||||
const [toolOutcome, setToolOutcome] = useState<ToolOutcome | null>(null);
|
||||
|
||||
// State for passthrough headers
|
||||
const [passthroughHeaders, setPassthroughHeaders] = useState<Record<string, string>>({});
|
||||
|
|
@ -244,13 +249,11 @@ const MCPToolsViewer = ({
|
|||
throw error;
|
||||
}
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
setToolResult(data.content);
|
||||
setToolError(null);
|
||||
onSuccess: (data, args) => {
|
||||
setToolOutcome({ toolName: args.tool.name, result: data.content, error: null });
|
||||
},
|
||||
onError: (error: Error & { status?: number; response?: { status?: number } }) => {
|
||||
setToolError(error);
|
||||
setToolResult(null);
|
||||
onError: (error: Error & { status?: number; response?: { status?: number } }, args) => {
|
||||
setToolOutcome({ toolName: args.tool.name, result: null, error });
|
||||
// On 401, clear the cached token so the auth gate is shown again
|
||||
if (error?.status === 401 || (error as any)?.response?.status === 401) {
|
||||
removeToken(serverId, userID);
|
||||
|
|
@ -260,6 +263,8 @@ const MCPToolsViewer = ({
|
|||
});
|
||||
|
||||
const toolsData = mcpToolsResponse?.tools || [];
|
||||
const selectedTool = toolsData.find((tool: MCPTool) => tool.name === selectedToolName) ?? null;
|
||||
const selectedOutcome = toolOutcome?.toolName === selectedToolName ? toolOutcome : null;
|
||||
|
||||
const toolsError = mcpToolsError as (Error & { status?: number; response?: { status?: number } }) | null;
|
||||
// authorization_code only: a 401 from the list call means the stored credential is unusable and
|
||||
|
|
@ -426,7 +431,7 @@ const MCPToolsViewer = ({
|
|||
<InputGroupInput
|
||||
placeholder="Search tools..."
|
||||
value={toolSearchTerm}
|
||||
onChange={(e) => setToolSearchTerm(e.target.value)}
|
||||
onChange={(e) => void setToolUrlState({ tool_search: e.target.value })}
|
||||
/>
|
||||
</InputGroup>
|
||||
</div>
|
||||
|
|
@ -496,9 +501,8 @@ const MCPToolsViewer = ({
|
|||
: "border-border bg-card",
|
||||
)}
|
||||
onClick={() => {
|
||||
setSelectedTool(tool);
|
||||
setToolResult(null);
|
||||
setToolError(null);
|
||||
void setToolUrlState({ tool: tool.name });
|
||||
setToolOutcome(null);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start space-x-2">
|
||||
|
|
@ -569,10 +573,10 @@ const MCPToolsViewer = ({
|
|||
onSubmit={(args) => {
|
||||
executeTool({ tool: selectedTool, arguments: args });
|
||||
}}
|
||||
result={toolResult}
|
||||
error={toolError}
|
||||
result={selectedOutcome?.result ?? null}
|
||||
error={selectedOutcome?.error ?? null}
|
||||
isLoading={isCallingTool}
|
||||
onClose={() => setSelectedTool(null)}
|
||||
onClose={() => void setToolUrlState({ tool: null })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,144 @@
|
|||
import { parseAsString, parseAsStringLiteral, useQueryState, useQueryStates } from "nuqs";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { z } from "zod/v4";
|
||||
import type { MCPServer } from "@/components/mcp_tools/types";
|
||||
import { clearStorage, TOOLS_OAUTH_UI_STATE_KEY } from "@/hooks/mcpOAuthUtils";
|
||||
import { useUrlTab } from "@/hooks/useUrlTab";
|
||||
import { getSecureItem } from "@/utils/secureStorage";
|
||||
import { EDIT_OAUTH_UI_STATE_KEY } from "./mcp_server_edit";
|
||||
|
||||
export const MCP_SERVER_SORT_KEYS = ["created_desc", "updated_desc", "name_asc", "health"] as const;
|
||||
export type McpServerSortKey = (typeof MCP_SERVER_SORT_KEYS)[number];
|
||||
|
||||
const USER_PAGE_TABS = ["servers", "toolsets", "connect"] as const;
|
||||
const ADMIN_PAGE_TABS = [...USER_PAGE_TABS, "semantic-filter", "tool-search", "network", "submitted"] as const;
|
||||
export type McpPageTab = (typeof ADMIN_PAGE_TABS)[number];
|
||||
|
||||
const ADMIN_SERVER_TABS = ["overview", "tools", "settings"] as const;
|
||||
export type McpServerTab = (typeof ADMIN_SERVER_TABS)[number];
|
||||
const USER_SERVER_TABS: readonly McpServerTab[] = ["overview", "tools"];
|
||||
|
||||
const listParsers = {
|
||||
team: parseAsString.withDefault("all"),
|
||||
access_group: parseAsString.withDefault("all"),
|
||||
search: parseAsString.withDefault(""),
|
||||
sort: parseAsStringLiteral(MCP_SERVER_SORT_KEYS).withDefault("created_desc"),
|
||||
};
|
||||
|
||||
const detailParsers = {
|
||||
server: parseAsString,
|
||||
server_tab: parseAsString,
|
||||
tool: parseAsString,
|
||||
tool_search: parseAsString,
|
||||
};
|
||||
|
||||
const CLOSED_DETAIL = { server: null, server_tab: null, tool: null, tool_search: null };
|
||||
|
||||
const toolParsers = {
|
||||
tool: parseAsString.withOptions({ history: "push" }),
|
||||
tool_search: parseAsString.withDefault(""),
|
||||
};
|
||||
|
||||
const storedServerSchema = z.object({ serverId: z.string().min(1) });
|
||||
|
||||
interface OAuthRestore {
|
||||
serverId: string;
|
||||
tab: McpServerTab;
|
||||
}
|
||||
|
||||
const readStoredServerId = (key: string): string | null => {
|
||||
const stored = getSecureItem(key);
|
||||
if (!stored) return null;
|
||||
try {
|
||||
const parsed = storedServerSchema.safeParse(JSON.parse(stored));
|
||||
return parsed.success ? parsed.data.serverId : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const readOAuthRestore = (): OAuthRestore | null => {
|
||||
if (typeof window === "undefined") return null;
|
||||
const editServerId = readStoredServerId(EDIT_OAUTH_UI_STATE_KEY);
|
||||
if (editServerId) return { serverId: editServerId, tab: "settings" };
|
||||
const toolsServerId = readStoredServerId(TOOLS_OAUTH_UI_STATE_KEY);
|
||||
return toolsServerId ? { serverId: toolsServerId, tab: "tools" } : null;
|
||||
};
|
||||
|
||||
const toSortKey = (value: string | null): McpServerSortKey | null =>
|
||||
MCP_SERVER_SORT_KEYS.find((key) => key === value) ?? null;
|
||||
|
||||
export function useMcpServersUrlState(isAdmin: boolean, servers: readonly MCPServer[], serversLoaded: boolean) {
|
||||
const [tab, setTab] = useUrlTab<McpPageTab>(isAdmin ? ADMIN_PAGE_TABS : USER_PAGE_TABS, "servers");
|
||||
const [filters, setFilters] = useQueryStates(listParsers);
|
||||
const [detail, setDetail] = useQueryStates(detailParsers);
|
||||
const [fillEnvVars, setFillEnvVars] = useQueryState("fill_env_vars", parseAsString);
|
||||
const [envVarsDeepLinkId, setEnvVarsDeepLinkId] = useState(fillEnvVars);
|
||||
const [oauthRestore] = useState(() => {
|
||||
const stored = readOAuthRestore();
|
||||
return stored && (detail.server ?? stored.serverId) === stored.serverId ? stored : null;
|
||||
});
|
||||
const [editServer, setEditServer] = useState(oauthRestore?.tab === "settings");
|
||||
const restoredServerMissing =
|
||||
oauthRestore !== null && serversLoaded && !servers.some((server) => server.server_id === oauthRestore.serverId);
|
||||
|
||||
useEffect(() => {
|
||||
clearStorage(TOOLS_OAUTH_UI_STATE_KEY);
|
||||
if (!oauthRestore) {
|
||||
clearStorage(EDIT_OAUTH_UI_STATE_KEY);
|
||||
return;
|
||||
}
|
||||
void setDetail({ server: oauthRestore.serverId, server_tab: oauthRestore.tab });
|
||||
}, [oauthRestore, setDetail]);
|
||||
|
||||
useEffect(() => {
|
||||
if (restoredServerMissing) clearStorage(EDIT_OAUTH_UI_STATE_KEY);
|
||||
}, [restoredServerMissing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (fillEnvVars !== null) void setFillEnvVars(null);
|
||||
}, [fillEnvVars, setFillEnvVars]);
|
||||
|
||||
const selectedServer = useMemo(
|
||||
() => servers.find((server) => server.server_id === detail.server) ?? null,
|
||||
[servers, detail.server],
|
||||
);
|
||||
|
||||
const openServer = useCallback(
|
||||
(serverId: string) => {
|
||||
setEditServer(true);
|
||||
void setDetail({ ...CLOSED_DETAIL, server: serverId }, { history: "push" });
|
||||
},
|
||||
[setDetail],
|
||||
);
|
||||
|
||||
const closeServer = useCallback(() => {
|
||||
setEditServer(false);
|
||||
void setDetail(CLOSED_DETAIL, { history: "push" });
|
||||
}, [setDetail]);
|
||||
|
||||
return {
|
||||
tab,
|
||||
setTab,
|
||||
team: filters.team,
|
||||
setTeam: (team: string | null) => void setFilters({ team }),
|
||||
accessGroup: filters.access_group,
|
||||
setAccessGroup: (group: string | null) => void setFilters({ access_group: group }),
|
||||
search: filters.search,
|
||||
setSearch: (search: string) => void setFilters({ search }),
|
||||
sort: filters.sort,
|
||||
setSort: (sort: string | null) => void setFilters({ sort: toSortKey(sort) }),
|
||||
selectedServerId: detail.server,
|
||||
selectedServer,
|
||||
editServer,
|
||||
openServer,
|
||||
closeServer,
|
||||
envVarsDeepLinkId,
|
||||
clearEnvVarsDeepLink: () => setEnvVarsDeepLinkId(null),
|
||||
};
|
||||
}
|
||||
|
||||
export const useMcpServerTab = (isProxyAdmin: boolean) =>
|
||||
useUrlTab(isProxyAdmin ? ADMIN_SERVER_TABS : USER_SERVER_TABS, "overview", "server_tab");
|
||||
|
||||
export const useMcpToolUrlState = () => useQueryStates(toolParsers);
|
||||
Loading…
Add table
Reference in a new issue