Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
userRole: string | null;
userID: string | null;
availableAccessGroups: string[];
initialTabIndex?: number;
}

export const MCPServerView: React.FC<MCPServerViewProps> = ({
Expand All @@ -32,11 +33,12 @@
userRole,
userID,
availableAccessGroups,
initialTabIndex = 0,
}) => {

Check warning on line 37 in ui/litellm-dashboard/src/components/mcp_tools/mcp_server_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Arrow function has a complexity of 44. Maximum allowed is 20
const [editing, setEditing] = useState(isEditing);
const [showFullUrl, setShowFullUrl] = useState(false);
const [copiedStates, setCopiedStates] = useState<Record<string, boolean>>({});
const [selectedTabIndex, setSelectedTabIndex] = useState(0);
const [selectedTabIndex, setSelectedTabIndex] = useState(initialTabIndex);

const handleSuccess = (updated: MCPServer) => {
setEditing(false);
Expand Down Expand Up @@ -342,7 +344,7 @@
<div className="col-span-2">
{mcpServer.mcp_access_groups && mcpServer.mcp_access_groups.length > 0 ? (
<div className="flex flex-wrap gap-1.5">
{mcpServer.mcp_access_groups.map((group: any, index: number) => (

Check warning on line 347 in ui/litellm-dashboard/src/components/mcp_tools/mcp_server_view.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
<span
key={index}
className="inline-flex items-center text-xs font-medium px-2 py-0.5 rounded bg-gray-100 text-gray-700 border border-gray-200"
Expand Down
41 changes: 40 additions & 1 deletion ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import MCPDiscovery from "./mcp_discovery";
import { ByokCredentialModal } from "./ByokCredentialModal";
import { getSecureItem } from "@/utils/secureStorage";
import { TOOLS_OAUTH_UI_STATE_KEY } from "@/hooks/mcpOAuthUtils";
import UserEnvVarsModal from "./UserEnvVarsModal";
import { listMCPUserEnvVarStatus } from "../networking";

Expand Down Expand Up @@ -71,9 +72,26 @@
const { Text: AntdText, Title: AntdTitle } = Typography;
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 { Option } = Select;

const MCPServers: React.FC<MCPServerProps> = ({ accessToken, userRole, userID }) => {

Check warning on line 94 in ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Arrow function has a complexity of 24. Maximum allowed is 20
const { data: mcpServers, isLoading: isLoadingServers, refetch } = useMCPServers();

// Fetch health status for all servers
Expand Down Expand Up @@ -103,7 +121,12 @@
// state
const [serverIdToDelete, setServerToDelete] = useState<string | null>(null);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [selectedServerId, setSelectedServerId] = useState<string | null>(null);
// 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");
Expand Down Expand Up @@ -178,6 +201,19 @@
}
}, []);

// 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 [];
Expand Down Expand Up @@ -223,7 +259,7 @@
}
if (group !== "all") {
filtered = filtered.filter((server) =>
server.mcp_access_groups?.some((g: any) => (typeof g === "string" ? g === group : g && g.name === group)),

Check warning on line 262 in ui/litellm-dashboard/src/components/mcp_tools/mcp_servers.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
);
}
const sorted = [...filtered].sort((a, b) => {
Expand Down Expand Up @@ -338,6 +374,8 @@
const handleBack = React.useCallback(() => {
setEditServer(false);
setSelectedServerId(null);
// Drop the post-redirect one-shot so re-selecting that server opens Overview.
setToolsTabServerId(null);
refetch();
}, [refetch]);

Expand Down Expand Up @@ -483,6 +521,7 @@
userID={userID}
Comment thread
tin-berri marked this conversation as resolved.
Resolved
userRole={userRole}
availableAccessGroups={uniqueMcpAccessGroups}
initialTabIndex={selectedServerId === toolsTabServerId ? 1 : 0}
/>
) : (
<div className="w-full h-full">
Expand Down
55 changes: 53 additions & 2 deletions ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { describe, expect, it, vi, beforeEach } from "vitest";
import MCPToolsViewer from "./mcp_tools";
import { listMCPTools } from "../networking";
import { listMCPTools, getMCPOAuthUserCredentialStatus } from "../networking";
import { isTokenValid, getToken } from "@/utils/mcpTokenStore";

vi.mock("../networking", () => ({
listMCPTools: vi.fn(),
callMCPTool: vi.fn(),
getMCPOAuthUserCredentialStatus: vi.fn(),
}));

vi.mock("@/utils/mcpTokenStore", () => ({
Expand All @@ -20,6 +21,10 @@
useToolsOAuthFlow: () => ({ startOAuthFlow: vi.fn(), status: "idle", error: null }),
}));

vi.mock("@/hooks/useUserMcpOAuthFlow", () => ({
useUserMcpOAuthFlow: () => ({ startOAuthFlow: vi.fn(), status: "idle", error: null }),
}));

const GATE_TEXT = "Authentication required";
// Realistic interactive servers carry a token endpoint; the old heuristic
// (`oauth2 && !tokenUrl`) mislabeled exactly these as M2M. Setting it here is
Expand All @@ -42,13 +47,22 @@
</QueryClientProvider>,
);

const credStatus = (overrides: Record<string, unknown> = {}) => ({
server_id: "srv-1",
has_credential: true,
is_expired: false,
...overrides,
});

describe("MCPToolsViewer auth gate routing", () => {
beforeEach(() => {
vi.mocked(listMCPTools).mockReset().mockResolvedValue({ tools: [], error: null });
vi.mocked(isTokenValid).mockReset().mockReturnValue(false);
vi.mocked(getToken)
.mockReset()
.mockReturnValue(undefined as any);

Check warning on line 63 in ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type
// Default: the OBO credential exists and is valid, so OBO servers list tools.
vi.mocked(getMCPOAuthUserCredentialStatus).mockReset().mockResolvedValue(credStatus());
});

it("shows the Authorize gate for a passthrough server with a token endpoint and does not list tools", async () => {
Expand All @@ -57,11 +71,13 @@
expect(await screen.findByText(GATE_TEXT)).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Authorize" })).toBeInTheDocument();
expect(vi.mocked(listMCPTools)).not.toHaveBeenCalled();
// Passthrough must not consult the per-user DB credential.
expect(vi.mocked(getMCPOAuthUserCredentialStatus)).not.toHaveBeenCalled();
});

it("forwards the session token via the x-mcp header for a passthrough server that has one", async () => {
vi.mocked(isTokenValid).mockReturnValue(true);
vi.mocked(getToken).mockReturnValue({ access_token: "slack-tok" } as any);

Check warning on line 80 in ui/litellm-dashboard/src/components/mcp_tools/mcp_tools.test.tsx

View workflow job for this annotation

GitHub Actions / frontend-lint

Unexpected any. Specify a different type

renderViewer({ oauth2_flow: null, delegate_auth_to_upstream: true });

Expand All @@ -75,7 +91,40 @@
expect(screen.queryByText(GATE_TEXT)).not.toBeInTheDocument();
});

it("does not gate an OBO server with a token endpoint; lists with the LiteLLM key and no x-mcp header", async () => {
it("lists tools for an OBO server when the user has a DB credential, with no x-mcp header", async () => {
renderViewer({ oauth2_flow: null, delegate_auth_to_upstream: false });

await waitFor(() => expect(vi.mocked(listMCPTools)).toHaveBeenCalledWith("litellm-key", "srv-1", undefined));
expect(screen.queryByText(GATE_TEXT)).not.toBeInTheDocument();
});

it("shows the Authorize gate for an OBO server when the user has no DB credential and does not list tools", async () => {
vi.mocked(getMCPOAuthUserCredentialStatus).mockResolvedValue(credStatus({ has_credential: false }));

renderViewer({ oauth2_flow: null, delegate_auth_to_upstream: false });

expect(await screen.findByText(GATE_TEXT)).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Authorize" })).toBeInTheDocument();
expect(vi.mocked(listMCPTools)).not.toHaveBeenCalled();
});

it("shows the Authorize gate for an OBO server when the credential-status check fails", async () => {
vi.mocked(getMCPOAuthUserCredentialStatus).mockRejectedValue(new Error("network down"));

renderViewer({ oauth2_flow: null, delegate_auth_to_upstream: false });

expect(await screen.findByText(GATE_TEXT)).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Authorize" })).toBeInTheDocument();
expect(vi.mocked(listMCPTools)).not.toHaveBeenCalled();
});

it("does not gate an OBO server whose stored token is expired; the list call refreshes it server-side", async () => {
// has_credential=true with is_expired=true must NOT gate: resolve_valid_user_oauth_token
// refreshes from the stored refresh_token on the list call, so the user never reauthorizes.
vi.mocked(getMCPOAuthUserCredentialStatus).mockResolvedValue(
credStatus({ has_credential: true, is_expired: true }),
);

renderViewer({ oauth2_flow: null, delegate_auth_to_upstream: false });

await waitFor(() => expect(vi.mocked(listMCPTools)).toHaveBeenCalledWith("litellm-key", "srv-1", undefined));
Expand All @@ -87,5 +136,7 @@

await waitFor(() => expect(vi.mocked(listMCPTools)).toHaveBeenCalledWith("litellm-key", "srv-1", undefined));
expect(screen.queryByText(GATE_TEXT)).not.toBeInTheDocument();
// M2M uses the backend service token, not a per-user DB credential.
expect(vi.mocked(getMCPOAuthUserCredentialStatus)).not.toHaveBeenCalled();
});
});
Loading
Loading