The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(ui): stop a deselected MCP server keeping its grant on a virtual key (#36840)
Yassin Kortamb344043eaf3d
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.test.tsxindex c704da301ad..237e3b2c842 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.test.tsx@@ -1,7 +1,8 @@import { render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi, beforeEach } from "vitest";-import UserInfoView, { extractMcpEntitlement } from "./user_info_view";+import UserInfoView from "./user_info_view";+import { extractMcpEntitlement } from "@/components/mcp_server_management/mcpEntitlement";const mockTeamMemberAddCall = vi.fn();const mockTeamMemberDeleteCall = vi.fn();@@ -371,7 +372,11 @@ describe("extractMcpEntitlement", () => {const CATALOG = [{ server_id: "srv-1", server_name: "deploy_tracker", alias: "deploy" },{ server_id: "srv-2", server_name: "issue_tracker", alias: null },- { server_id: "srv-via-group", server_name: "audit_log", alias: null },+ { server_id: "srv-via-group", server_name: "audit_log", alias: null, mcp_access_groups: ["ops_readonly"] },+ ] as any;++ const TOOLSETS = [+ { toolset_id: "ts-1", toolset_name: "audit", tools: [{ server_id: "srv-via-group", tool_name: "read" }] },] as any;const form = (@@ -465,12 +470,43 @@ describe("extractMcpEntitlement", () => {});it("keeps the allowlist of a deselected server that a retained access group still supplies", () => {- const result = extractMcpEntitlement(form({ accessGroups: ["ops_readonly"] }, { "srv-1": ["read"] }), CATALOG);- expect(result?.mcp_tool_permissions).toEqual({ "srv-1": ["read"] });+ const result = extractMcpEntitlement(+ form({ accessGroups: ["ops_readonly"] }, { "srv-via-group": ["read"] }),+ CATALOG,+ TOOLSETS,+ );+ expect(result?.mcp_tool_permissions).toEqual({ "srv-via-group": ["read"] });+ });++ it("drops the allowlist of a deselected server that the retained access group does not contain", () => {+ // The gateway grants each allowlist key as its own server, so retaining a group covering only+ // srv-via-group must not keep srv-1 callable after the admin removed it.+ const result = extractMcpEntitlement(+ form({ accessGroups: ["ops_readonly"] }, { "srv-1": ["read"] }),+ CATALOG,+ TOOLSETS,+ );+ expect(result?.mcp_tool_permissions).toEqual({});+ });++ it("keeps the allowlist of a deselected server that a retained toolset still supplies", () => {+ const result = extractMcpEntitlement(+ form({ toolsets: ["ts-1"] }, { "srv-via-group": ["read"] }),+ CATALOG,+ TOOLSETS,+ );+ expect(result?.mcp_tool_permissions).toEqual({ "srv-via-group": ["read"] });+ });++ it("drops the allowlist of a deselected server that the retained toolset does not cover", () => {+ const result = extractMcpEntitlement(form({ toolsets: ["ts-1"] }, { "srv-1": ["read"] }), CATALOG, TOOLSETS);+ expect(result?.mcp_tool_permissions).toEqual({});});- it("keeps the allowlist of a deselected server when a toolset is retained", () => {- const result = extractMcpEntitlement(form({ toolsets: ["ts-1"] }, { "srv-1": ["read"] }), CATALOG);+ it("prunes nothing when a selected toolset is missing from the toolset catalog", () => {+ // An unresolvable toolset could supply any server, so pruning against it would be a guess in+ // the widening direction.+ const result = extractMcpEntitlement(form({ toolsets: ["ts-unknown"] }, { "srv-1": ["read"] }), CATALOG, TOOLSETS);expect(result?.mcp_tool_permissions).toEqual({ "srv-1": ["read"] });});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsx b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsxindex 7c7b6b51ef4..34b34066f14 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/users/_components/view_users/user_info_view.tsx@@ -42,77 +42,9 @@ import NotificationsManager from "@/components/molecules/notifications_manager";import { getBudgetDurationLabel } from "@/components/common_components/budget_duration_dropdown";import DeleteResourceModal from "@/components/common_components/DeleteResourceModal";import MCPServerPermissions from "@/components/permissions/MCPServerPermissions";-import { MCPServer } from "@/components/mcp_tools/types";import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";--interface McpEntitlementUpdate {- mcp_servers: string[];- mcp_access_groups: string[];- mcp_toolsets: string[];- mcp_tool_permissions: Record<string, string[]>;-}--const asStringArray = (value: unknown): string[] =>- Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];--const asToolPermissions = (value: unknown): Record<string, string[]> => {- if (value === null || typeof value !== "object" || Array.isArray(value)) return {};- return Object.fromEntries(- Object.entries(value as Record<string, unknown>).map(([serverId, tools]) => [serverId, asStringArray(tools)]),- );-};--const mcpServerMatchesIdentifier = (server: MCPServer, identifier: string): boolean =>- server.server_id === identifier || server.server_name === identifier || server.alias === identifier;--/**- * The `object_permission` a save sends, derived from what the editor currently shows.- *- * A tool allowlist is what narrows a grant and an absent one reads as no restriction, so dropping- * an entry is the direction that widens. An entry is kept when an access group or toolset the admin- * retained could still supply its server, and dropped once nothing indirect survives, which is what- * makes removing a grant actually remove it.- *- * A tool-permission key may be a server id, a name or an alias: the gateway normalizes all three- * before looking up the allowlist, so an entry written by the API or by config can use any of them.- * `allServers` is what resolves a key to its servers, plural: names and aliases are not unique, and- * the gateway unions such a key into EVERY server answering to it, so the entry is kept while any- * one of them is still granted. Resolving to the first match instead would make the outcome depend- * on catalog order and could drop a restriction that was also covering a server still granted. A key- * that resolves to nothing is kept too, since a server we cannot identify is one we cannot confirm- * was deselected; that also covers a catalog that has not loaded or failed to load, where every key- * is unresolvable and nothing is pruned.- */-export const extractMcpEntitlement = (- formValues: Record<string, unknown>,- allServers: MCPServer[],-): McpEntitlementUpdate | null => {- const selection = formValues.mcp_servers_and_groups;- if (selection === null || typeof selection !== "object") return null;-- const { servers, accessGroups, toolsets } = selection as Record<string, unknown>;- const mcpServers = asStringArray(servers);- const mcpAccessGroups = asStringArray(accessGroups);- const mcpToolsets = asStringArray(toolsets);- const retainsIndirectGrant = mcpAccessGroups.length > 0 || mcpToolsets.length > 0;-- const grantsServerNamedBy = (permissionKey: string): boolean => {- const named = allServers.filter((candidate) => mcpServerMatchesIdentifier(candidate, permissionKey));- if (named.length === 0) return true;- return named.some((server) => mcpServers.some((identifier) => mcpServerMatchesIdentifier(server, identifier)));- };-- return {- mcp_servers: mcpServers,- mcp_access_groups: mcpAccessGroups,- mcp_toolsets: mcpToolsets,- mcp_tool_permissions: Object.fromEntries(- Object.entries(asToolPermissions(formValues.mcp_tool_permissions)).filter(- ([permissionKey]) => retainsIndirectGrant || grantsServerNamedBy(permissionKey),- ),- ),- };-};+import { useMCPToolsets } from "@/app/(dashboard)/hooks/mcpServers/useMCPToolsets";+import { extractMcpEntitlement } from "@/components/mcp_server_management/mcpEntitlement";interface UserInfoViewProps {userId: string;@@ -164,6 +96,7 @@ export default function UserInfoView({const [selectedRole, setSelectedRole] = useState<string>("user");const [isLoadingTeams, setIsLoadingTeams] = useState(false);const { data: allMcpServers = [] } = useMCPServers();+ const { data: allMcpToolsets = [] } = useMCPToolsets();React.useEffect(() => {setBaseUrl(getProxyBaseUrl());@@ -365,7 +298,7 @@ export default function UserInfoView({try {if (!accessToken || !userData) return;- const mcpEntitlement = extractMcpEntitlement(formValues, allMcpServers);+ const mcpEntitlement = extractMcpEntitlement(formValues, allMcpServers, allMcpToolsets);const userFields = Object.fromEntries(Object.entries(formValues).filter(([field]) => field !== "mcp_servers_and_groups" && field !== "mcp_tool_permissions",diff --git a/ui/litellm-dashboard/src/components/mcp_server_management/mcpEntitlement.ts b/ui/litellm-dashboard/src/components/mcp_server_management/mcpEntitlement.tsnew file mode 100644index 00000000000..66f59f5b71d--- /dev/null+++ b/ui/litellm-dashboard/src/components/mcp_server_management/mcpEntitlement.ts@@ -0,0 +1,91 @@+import { ALL_PROXY_MCP_SERVERS_SENTINEL } from "@/components/mcp_tools/constants";+import { MCPServer, MCPToolset } from "@/components/mcp_tools/types";++export interface McpEntitlementUpdate {+ mcp_servers: string[];+ mcp_access_groups: string[];+ mcp_toolsets: string[];+ mcp_tool_permissions: Record<string, string[]>;+}++const asStringArray = (value: unknown): string[] =>+ Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];++const asToolPermissions = (value: unknown): Record<string, string[]> => {+ if (value === null || typeof value !== "object" || Array.isArray(value)) return {};+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([serverId, tools]) => [serverId, asStringArray(tools)]),+ );+};++const mcpServerMatchesIdentifier = (server: MCPServer, identifier: string): boolean =>+ server.server_id === identifier || server.server_name === identifier || server.alias === identifier;++/**+ * The `object_permission` a save sends, derived from what the editor currently shows.+ *+ * A tool allowlist is what narrows a grant and an absent one reads as no restriction, so dropping+ * an entry is the direction that widens. An entry is kept while its own server is still reachable,+ * directly or through a retained access group or toolset, and dropped once nothing reaches it, which+ * is what makes removing a grant actually remove it. Reachability is resolved per server rather than+ * per selection: the gateway treats every allowlist key as an independent server grant, so keeping+ * every key because some unrelated group survived would leave a deselected server callable.+ *+ * The catalog carries `mcp_access_groups` on each server and `tools[].server_id` on each toolset,+ * which is the same membership the gateway resolves against. A selected toolset missing from the+ * catalog is unresolvable, so nothing is pruned in that save.+ *+ * A tool-permission key may be a server id, a name or an alias: the gateway normalizes all three+ * before looking up the allowlist, so an entry written by the API or by config can use any of them.+ * `allServers` is what resolves a key to its servers, plural: names and aliases are not unique, and+ * the gateway unions such a key into EVERY server answering to it, so the entry is kept while any+ * one of them is still granted. Resolving to the first match instead would make the outcome depend+ * on catalog order and could drop a restriction that was also covering a server still granted. A key+ * that resolves to nothing is kept too, since a server we cannot identify is one we cannot confirm+ * was deselected; that also covers a catalog that has not loaded or failed to load, where every key+ * is unresolvable and nothing is pruned.+ */+export const extractMcpEntitlement = (+ formValues: Record<string, unknown>,+ allServers: MCPServer[],+ allToolsets: MCPToolset[] = [],+): McpEntitlementUpdate | null => {+ const selection = formValues.mcp_servers_and_groups;+ if (selection === null || typeof selection !== "object") return null;++ const { servers, accessGroups, toolsets } = selection as Record<string, unknown>;+ const mcpServers = asStringArray(servers);+ const mcpAccessGroups = asStringArray(accessGroups);+ const mcpToolsets = asStringArray(toolsets);+ const grantsEveryServer =+ mcpServers.includes(ALL_PROXY_MCP_SERVERS_SENTINEL) ||+ mcpToolsets.some((toolsetId) => !allToolsets.some((toolset) => toolset.toolset_id === toolsetId));++ const toolsetServerIds = new Set(+ allToolsets+ .filter((toolset) => mcpToolsets.includes(toolset.toolset_id))+ .flatMap((toolset) => toolset.tools.map((tool) => tool.server_id)),+ );++ const grants = (server: MCPServer): boolean =>+ mcpServers.some((identifier) => mcpServerMatchesIdentifier(server, identifier)) ||+ (server.mcp_access_groups ?? []).some((group) => mcpAccessGroups.includes(group)) ||+ toolsetServerIds.has(server.server_id);++ const grantsServerNamedBy = (permissionKey: string): boolean => {+ const named = allServers.filter((candidate) => mcpServerMatchesIdentifier(candidate, permissionKey));+ if (named.length === 0) return true;+ return named.some(grants);+ };++ return {+ mcp_servers: mcpServers,+ mcp_access_groups: mcpAccessGroups,+ mcp_toolsets: mcpToolsets,+ mcp_tool_permissions: Object.fromEntries(+ Object.entries(asToolPermissions(formValues.mcp_tool_permissions)).filter(+ ([permissionKey]) => grantsEveryServer || grantsServerNamedBy(permissionKey),+ ),+ ),+ };+};diff --git a/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx b/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsxindex 16b1be0d74a..374e36029a0 100644--- a/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx+++ b/ui/litellm-dashboard/src/components/templates/KeyInfoView.handleKeyUpdate.test.tsx@@ -255,6 +255,15 @@ vi.mock("@/app/(dashboard)/hooks/uiSettings/useUISettings", () => ({useUISettings: vi.fn().mockReturnValue({ data: { values: {} }, isLoading: false }),}));+// Mock useMCPServers hook (requires QueryClientProvider which is not available in this test)+vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({+ useMCPServers: vi.fn().mockReturnValue({ data: [] }),+}));++vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPToolsets", () => ({+ useMCPToolsets: vi.fn().mockReturnValue({ data: [] }),+}));+// Mock useResetKeySpend hook (requires QueryClientProvider which is not available in this test)vi.mock("@/app/(dashboard)/hooks/keys/useResetKeySpend", () => ({useResetKeySpend: vi.fn().mockReturnValue({diff --git a/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsx b/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsxindex d2390a633d5..1437689958c 100644--- a/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_info_view.test.tsx@@ -32,6 +32,26 @@ vi.mock("@/app/(dashboard)/hooks/projects/useProjects", () => ({useProjects: vi.fn().mockReturnValue({ data: [], isLoading: false }),}));+const MCP_CATALOG = [+ { server_id: "srv-1", server_name: "deploy_tracker", alias: "deploy" },+ { server_id: "srv-2", server_name: "incident_log", alias: "incidents", mcp_access_groups: ["ops_readonly"] },+];++const MCP_TOOLSETS = [+ { toolset_id: "ts-1", toolset_name: "incidents", tools: [{ server_id: "srv-2", tool_name: "write" }] },+];++vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({+ useMCPServers: vi.fn(() => ({ data: MCP_CATALOG })),+}));++vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPToolsets", () => ({+ useMCPToolsets: vi.fn(() => ({ data: MCP_TOOLSETS })),+}));++import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";+import { useMCPToolsets } from "@/app/(dashboard)/hooks/mcpServers/useMCPToolsets";+vi.mock("../networking", () => ({keyDeleteCall: vi.fn().mockResolvedValue({}),keyUpdateCall: vi.fn().mockResolvedValue({}),@@ -881,6 +901,182 @@ describe("KeyInfoView", () => {});});+ describe("MCP tool permissions on save", () => {+ const KEY_WITH_TOOL_PERMISSIONS: KeyResponse = {+ ...MOCK_KEY_DATA,+ user_id: "proxy-admin-user",+ object_permission: {+ ...MOCK_KEY_DATA.object_permission,+ mcp_servers: ["srv-1", "srv-2"],+ mcp_access_groups: [],+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ },+ } as KeyResponse;++ const enterEditMode = async (keyData: KeyResponse) => {+ vi.mocked(useAuthorized).mockReturnValue({+ ...baseUseAuthorizedMock,+ userId: "proxy-admin-user",+ userRole: "proxy_admin",+ });+ renderWithProviders(+ <KeyInfoView keyData={keyData} onClose={() => {}} keyId="test-key-id" onKeyDataUpdate={() => {}} teams={[]} />,+ );+ await userEvent.click(screen.getByRole("tab", { name: /settings/i }));+ await userEvent.click(screen.getByRole("button", { name: /edit settings/i }));+ await waitFor(() => expect(editViewMocks.onSubmit).toBeDefined());+ };++ const submittedToolPermissions = () => {+ const payload = vi.mocked(keyUpdateCall).mock.calls.at(-1)?.[1] as Record<string, any>;+ return payload.object_permission.mcp_tool_permissions;+ };++ beforeEach(() => {+ editViewMocks.onSubmit = undefined;+ vi.mocked(keyUpdateCall).mockClear();+ vi.mocked(keyUpdateCall).mockResolvedValue({});+ vi.mocked(useMCPServers).mockReturnValue({ data: MCP_CATALOG } as unknown as ReturnType<typeof useMCPServers>);+ vi.mocked(useMCPToolsets).mockReturnValue({ data: MCP_TOOLSETS } as unknown as ReturnType<typeof useMCPToolsets>);+ });++ it("drops the allowlist of every deselected server instead of leaving it entitled", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: [], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({});+ });++ it("drops only the deselected server and keeps the one still granted", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: ["srv-1"], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({ "srv-1": ["read"] });+ });++ it("keeps an allowlist whose server is reachable through a retained access group", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: [], accessGroups: ["ops_readonly"], toolsets: [] },+ mcp_tool_permissions: { "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({ "srv-2": ["write"] });+ });++ it("drops an allowlist the retained access group does not reach", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: [], accessGroups: ["ops_readonly"], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({ "srv-2": ["write"] });+ });++ it("drops an allowlist the retained toolset does not cover", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: [], accessGroups: [], toolsets: ["ts-1"] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({ "srv-2": ["write"] });+ });++ it("refuses to save a permission change while a selected toolset is unresolvable", async () => {+ vi.mocked(useMCPToolsets).mockReturnValue({ data: undefined } as unknown as ReturnType<typeof useMCPToolsets>);+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: [], accessGroups: [], toolsets: ["ts-1"] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(keyUpdateCall).not.toHaveBeenCalled();+ });++ it("resolves a name-keyed allowlist against the server catalog", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: ["srv-1"], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { deploy_tracker: ["read"], incident_log: ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({ deploy_tracker: ["read"] });+ });++ it("clears every allowlist when the admin picks the no-MCP-servers sentinel", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: ["no-mcp-servers"], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({});+ });++ it("keeps every allowlist when the admin grants all proxy servers", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: ["all-proxy-mcpservers"], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(submittedToolPermissions()).toEqual({ "srv-1": ["read"], "srv-2": ["write"] });+ });++ it("refuses to save a permission change it cannot compute without the server catalog", async () => {+ vi.mocked(useMCPServers).mockReturnValue({ data: undefined } as ReturnType<typeof useMCPServers>);+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ mcp_servers_and_groups: { servers: [], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"], "srv-2": ["write"] },+ });++ expect(keyUpdateCall).not.toHaveBeenCalled();+ });++ it("preserves a vector-store edit made in the same save", async () => {+ await enterEditMode(KEY_WITH_TOOL_PERMISSIONS);+ await editViewMocks.onSubmit!({+ key: KEY_WITH_TOOL_PERMISSIONS.token,+ token: KEY_WITH_TOOL_PERMISSIONS.token,+ vector_stores: ["vs-1"],+ mcp_servers_and_groups: { servers: ["srv-1"], accessGroups: [], toolsets: [] },+ mcp_tool_permissions: { "srv-1": ["read"] },+ });++ const payload = vi.mocked(keyUpdateCall).mock.calls.at(-1)?.[1] as Record<string, any>;+ expect(payload.object_permission.vector_stores).toEqual(["vs-1"]);+ });+ });+describe("delete flow", () => {it("invalidates the keys list query after a successful delete so active filters survive (LIT-4080)", async () => {const invalidateSpy = vi.spyOn(QueryClient.prototype, "invalidateQueries");diff --git a/ui/litellm-dashboard/src/components/templates/key_info_view.tsx b/ui/litellm-dashboard/src/components/templates/key_info_view.tsxindex f7720874968..15d14d5abf5 100644--- a/ui/litellm-dashboard/src/components/templates/key_info_view.tsx+++ b/ui/litellm-dashboard/src/components/templates/key_info_view.tsx@@ -24,6 +24,9 @@ import { useResetKeySpend } from "@/app/(dashboard)/hooks/keys/useResetKeySpend"import { useSetKeyBlockedState } from "@/app/(dashboard)/hooks/keys/useSetKeyBlockedState";import { keyKeys } from "@/app/(dashboard)/hooks/keys/useKeys";import { useQueryClient } from "@tanstack/react-query";+import { useMCPServers } from "@/app/(dashboard)/hooks/mcpServers/useMCPServers";+import { useMCPToolsets } from "@/app/(dashboard)/hooks/mcpServers/useMCPToolsets";+import { extractMcpEntitlement } from "../mcp_server_management/mcpEntitlement";import ObjectPermissionsView from "../object_permissions_view";import { RegenerateKeyModal } from "../organisms/RegenerateKeyModal";import { parseErrorMessage } from "../shared/errorUtils";@@ -74,6 +77,8 @@ export default function KeyInfoView({const { teams: teamsData } = useTeams();const { data: projects } = useProjects();const { data: uiSettingsData } = useUISettings();+ const { data: allMcpServers } = useMCPServers();+ const { data: allMcpToolsets } = useMCPToolsets();const enableProjectsUI = Boolean(uiSettingsData?.values?.enable_projects_ui);const [isEditing, setIsEditing] = useState(false);const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);@@ -201,33 +206,28 @@ export default function KeyInfoView({delete formValues.vector_stores;}- if (formValues.mcp_servers_and_groups !== undefined) {- const { servers, accessGroups, toolsets } = formValues.mcp_servers_and_groups || {- servers: [],- accessGroups: [],- toolsets: [],- };+ const mcpEntitlement = extractMcpEntitlement(formValues, allMcpServers ?? [], allMcpToolsets ?? []);+ if (mcpEntitlement) {+ // Without a catalog the grants an allowlist key still has are unresolvable, so nothing is+ // pruned and a revocation would save as a no-op while reporting success. Refuse instead.+ const unresolvableSelection =+ allMcpServers === undefined ||+ mcpEntitlement.mcp_toolsets.some(+ (toolsetId) => !(allMcpToolsets ?? []).some((toolset) => toolset.toolset_id === toolsetId),+ );+ if (unresolvableSelection && Object.keys(mcpEntitlement.mcp_tool_permissions).length > 0) {+ NotificationManager.error(+ "MCP server or toolset list is unavailable, so MCP permissions cannot be saved yet. Retry.",+ );+ return;+ }formValues.object_permission = {- ...currentKeyData.object_permission,- mcp_servers: servers || [],- mcp_access_groups: accessGroups || [],- mcp_toolsets: toolsets || [],+ ...(formValues.object_permission ?? currentKeyData.object_permission),+ ...mcpEntitlement,};- // Remove mcp_servers_and_groups from the top level as it should be in object_permission- delete formValues.mcp_servers_and_groups;- }-- // Handle MCP tool permissions- if (formValues.mcp_tool_permissions !== undefined) {- const mcpToolPermissions = formValues.mcp_tool_permissions || {};- if (Object.keys(mcpToolPermissions).length > 0) {- formValues.object_permission = {- ...formValues.object_permission,- mcp_tool_permissions: mcpToolPermissions,- };- }- delete formValues.mcp_tool_permissions;}+ delete formValues.mcp_servers_and_groups;+ delete formValues.mcp_tool_permissions;// Handle agent permissionsif (formValues.agents_and_groups !== undefined) {