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
[Feat] Agent Access Control - Enforce Allowed agents by key, team + add agent access groups on backend (#17502)
Ishaan Jaff8f592088edf5
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20251204142718_add_agent_permissions/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20251204142718_add_agent_permissions/migration.sqlnew file mode 100644index 00000000000..c1b3384a69d--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20251204142718_add_agent_permissions/migration.sql@@ -0,0 +1,7 @@+-- Add agent permission fields to LiteLLM_ObjectPermissionTable+ALTER TABLE "LiteLLM_ObjectPermissionTable" ADD COLUMN IF NOT EXISTS "agents" TEXT[] DEFAULT ARRAY[]::TEXT[];+ALTER TABLE "LiteLLM_ObjectPermissionTable" ADD COLUMN IF NOT EXISTS "agent_access_groups" TEXT[] DEFAULT ARRAY[]::TEXT[];++-- Add agent_access_groups field to LiteLLM_AgentsTable+ALTER TABLE "LiteLLM_AgentsTable" ADD COLUMN IF NOT EXISTS "agent_access_groups" TEXT[] DEFAULT ARRAY[]::TEXT[];+diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex 2883dfc4b82..583c493adc6 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -61,6 +61,7 @@ model LiteLLM_AgentsTable {agent_name String @uniquelitellm_params Json?agent_card_params Json+ agent_access_groups String[] @default([])created_at DateTime @default(now()) @map("created_at")created_by Stringupdated_at DateTime @default(now()) @updatedAt @map("updated_at")@@ -172,6 +173,8 @@ model LiteLLM_ObjectPermissionTable {mcp_access_groups String[] @default([])mcp_tool_permissions Json? // Tool-level permissions for MCP servers. Format: {"server_id": ["tool_name_1", "tool_name_2"]}vector_stores String[] @default([])+ agents String[] @default([])+ agent_access_groups String[] @default([])teams LiteLLM_TeamTable[]verification_tokens LiteLLM_VerificationToken[]organizations LiteLLM_OrganizationTable[]diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 4412466a169..f70d76dc68a 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -401,6 +401,15 @@ class LiteLLMRoutes(enum.Enum):"/mcp/tools/call",]+ agent_routes = [+ "/v1/agents",+ "/agents",++ "/a2a/{agent_id}",+ "/a2a/{agent_id}/message/send",+ "/a2a/{agent_id}/message/stream",+ ]+google_routes = ["/v1beta/models/{model_name}:countTokens","/v1beta/models/{model_name}:generateContent",@@ -423,6 +432,7 @@ class LiteLLMRoutes(enum.Enum):+ apply_guardrail_routes+ mcp_routes+ litellm_native_routes+ + agent_routes)info_routes = ["/key/info",@@ -779,6 +789,8 @@ class LiteLLM_ObjectPermissionBase(LiteLLMPydanticObjectBase):mcp_access_groups: Optional[List[str]] = Nonemcp_tool_permissions: Optional[Dict[str, List[str]]] = Nonevector_stores: Optional[List[str]] = None+ agents: Optional[List[str]] = None+ agent_access_groups: Optional[List[str]] = Noneclass GenerateRequestBase(LiteLLMPydanticObjectBase):@@ -1548,6 +1560,8 @@ class LiteLLM_ObjectPermissionTable(LiteLLMPydanticObjectBase):"""vector_stores: Optional[List[str]] = []+ agents: Optional[List[str]] = []+ agent_access_groups: Optional[List[str]] = []class LiteLLM_TeamTable(TeamBase):diff --git a/litellm/proxy/agent_endpoints/a2a_endpoints.py b/litellm/proxy/agent_endpoints/a2a_endpoints.pyindex 32af1232f6b..95f1f9a3f88 100644--- a/litellm/proxy/agent_endpoints/a2a_endpoints.py+++ b/litellm/proxy/agent_endpoints/a2a_endpoints.py@@ -89,11 +89,27 @@ async def get_agent_card(The URL in the agent card is rewritten to point to the LiteLLM proxy,so all subsequent A2A calls go through LiteLLM for logging and cost tracking."""+ from litellm.proxy._types import LitellmUserRoles+ from litellm.proxy.agent_endpoints.auth.agent_permission_handler import (+ AgentRequestHandler,+ )+try:agent = _get_agent(agent_id)if agent is None:raise HTTPException(status_code=404, detail=f"Agent '{agent_id}' not found")+ # Check agent permission (skip for admin users)+ is_allowed = await AgentRequestHandler.is_agent_allowed(+ agent_id=agent.agent_id,+ user_api_key_auth=user_api_key_dict,+ )+ if not is_allowed:+ raise HTTPException(+ status_code=403,+ detail=f"Agent '{agent_id}' is not allowed for your key/team. Contact proxy admin for access.",+ )+# Copy and rewrite URL to point to LiteLLM proxyagent_card = dict(agent.agent_card_params)agent_card["url"] = f"{str(request.base_url).rstrip('/')}/a2a/{agent_id}"@@ -139,6 +155,10 @@ async def invoke_agent_a2a(- message/stream: Send a message and stream the response"""from litellm.a2a_protocol import asend_message, create_a2a_client+ from litellm.proxy._types import LitellmUserRoles+ from litellm.proxy.agent_endpoints.auth.agent_permission_handler import (+ AgentRequestHandler,+ )from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_requestfrom litellm.proxy.proxy_server import (general_settings,@@ -164,6 +184,16 @@ async def invoke_agent_a2a(if agent is None:return _jsonrpc_error(request_id, -32000, f"Agent '{agent_id}' not found", 404)+ is_allowed = await AgentRequestHandler.is_agent_allowed(+ agent_id=agent.agent_id,+ user_api_key_auth=user_api_key_dict,+ )+ if not is_allowed:+ raise HTTPException(+ status_code=403,+ detail=f"Agent '{agent_id}' is not allowed for your key/team. Contact proxy admin for access.",+ )+# Get backend URL and agent nameagent_url = agent.agent_card_params.get("url")agent_name = agent.agent_card_params.get("name", agent_id)diff --git a/litellm/proxy/agent_endpoints/auth/__init__.py b/litellm/proxy/agent_endpoints/auth/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/litellm/proxy/agent_endpoints/auth/agent_permission_handler.py b/litellm/proxy/agent_endpoints/auth/agent_permission_handler.pynew file mode 100644index 00000000000..96e7a21cc33--- /dev/null+++ b/litellm/proxy/agent_endpoints/auth/agent_permission_handler.py@@ -0,0 +1,428 @@+"""+Agent Permission Handler for LiteLLM Proxy.++Handles agent permission checking for keys and teams using object_permission_id.+Follows the same pattern as MCP permission handling.+"""++from typing import List, Optional, Set++from litellm._logging import verbose_logger+from litellm.proxy._types import (+ LiteLLM_ObjectPermissionTable,+ LiteLLM_TeamTable,+ UserAPIKeyAuth,+)+++class AgentRequestHandler:+ """+ Class to handle agent permission checking, including:+ 1. Key-level agent permissions+ 2. Team-level agent permissions+ 3. Agent access group resolution++ Follows the same inheritance logic as MCP:+ - If team has restrictions and key has restrictions: use intersection+ - If team has restrictions and key has none: inherit from team+ - If team has no restrictions: use key restrictions+ - If no restrictions: allow all agents+ """++ @staticmethod+ async def get_allowed_agents(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> List[str]:+ """+ Get list of allowed agent IDs for the given user/key based on permissions.++ Returns:+ List[str]: List of allowed agent IDs. Empty list means no restrictions (allow all).+ """+ try:+ allowed_agents: List[str] = []+ allowed_agents_for_key = (+ await AgentRequestHandler._get_allowed_agents_for_key(user_api_key_auth)+ )+ allowed_agents_for_team = (+ await AgentRequestHandler._get_allowed_agents_for_team(user_api_key_auth)+ )++ # If team has agent restrictions, handle inheritance and intersection logic+ if len(allowed_agents_for_team) > 0:+ if len(allowed_agents_for_key) > 0:+ # Key has its own agent permissions - use intersection with team permissions+ for agent_id in allowed_agents_for_key:+ if agent_id in allowed_agents_for_team:+ allowed_agents.append(agent_id)+ else:+ # Key has no agent permissions - inherit from team+ allowed_agents = allowed_agents_for_team+ else:+ allowed_agents = allowed_agents_for_key++ return list(set(allowed_agents))+ except Exception as e:+ verbose_logger.warning(f"Failed to get allowed agents: {str(e)}")+ return []++ @staticmethod+ async def is_agent_allowed(+ agent_id: str,+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> bool:+ """+ Check if a specific agent is allowed for the given user/key.++ Args:+ agent_id: The agent ID to check+ user_api_key_auth: User authentication info++ Returns:+ bool: True if agent is allowed, False otherwise+ """+ allowed_agents = await AgentRequestHandler.get_allowed_agents(user_api_key_auth)++ # Empty list means no restrictions - allow all+ if len(allowed_agents) == 0:+ return True++ return agent_id in allowed_agents++ @staticmethod+ async def _get_key_object_permission(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> Optional[LiteLLM_ObjectPermissionTable]:+ """Helper to get key object_permission from cache or DB."""+ from litellm.proxy.auth.auth_checks import get_object_permission+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )++ if not user_api_key_auth:+ return None++ # Already loaded+ if user_api_key_auth.object_permission:+ return user_api_key_auth.object_permission++ # Need to fetch from DB+ if user_api_key_auth.object_permission_id and prisma_client:+ return await get_object_permission(+ object_permission_id=user_api_key_auth.object_permission_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=user_api_key_auth.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )++ return None++ @staticmethod+ async def _get_team_object_permission(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> Optional[LiteLLM_ObjectPermissionTable]:+ """Helper to get team object_permission from cache or DB."""+ from litellm.proxy.auth.auth_checks import (+ get_object_permission,+ get_team_object,+ )+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )++ if not user_api_key_auth or not user_api_key_auth.team_id or not prisma_client:+ return None++ # First get the team object (which may have object_permission already loaded)+ team_obj: Optional[LiteLLM_TeamTable] = await get_team_object(+ team_id=user_api_key_auth.team_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=user_api_key_auth.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )++ if not team_obj:+ return None++ # Already loaded+ if team_obj.object_permission:+ return team_obj.object_permission++ # Need to fetch from DB using object_permission_id+ if team_obj.object_permission_id:+ return await get_object_permission(+ object_permission_id=team_obj.object_permission_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=user_api_key_auth.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )++ return None++ @staticmethod+ async def _get_allowed_agents_for_key(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> List[str]:+ """+ Get allowed agents for a key from its object_permission.+ """+ from litellm.proxy.auth.auth_checks import get_object_permission+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )++ if user_api_key_auth is None:+ return []++ if user_api_key_auth.object_permission_id is None:+ return []++ if prisma_client is None:+ verbose_logger.debug("prisma_client is None")+ return []++ try:+ key_object_permission = await get_object_permission(+ object_permission_id=user_api_key_auth.object_permission_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=user_api_key_auth.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )+ if key_object_permission is None:+ return []++ # Get direct agents+ direct_agents = key_object_permission.agents or []++ # Get agents from access groups+ access_group_agents = await AgentRequestHandler._get_agents_from_access_groups(+ key_object_permission.agent_access_groups or []+ )++ # Combine both lists+ all_agents = direct_agents + access_group_agents+ return list(set(all_agents))+ except Exception as e:+ verbose_logger.warning(f"Failed to get allowed agents for key: {str(e)}")+ return []++ @staticmethod+ async def _get_allowed_agents_for_team(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> List[str]:+ """+ Get allowed agents for a team from its object_permission.+ """+ if user_api_key_auth is None:+ return []++ if user_api_key_auth.team_id is None:+ return []++ try:+ # Use the helper method that properly handles fetching from DB if needed+ object_permissions = await AgentRequestHandler._get_team_object_permission(+ user_api_key_auth+ )++ if object_permissions is None:+ return []++ # Get direct agents+ direct_agents = object_permissions.agents or []++ # Get agents from access groups+ access_group_agents = await AgentRequestHandler._get_agents_from_access_groups(+ object_permissions.agent_access_groups or []+ )++ # Combine both lists+ all_agents = direct_agents + access_group_agents+ return list(set(all_agents))+ except Exception as e:+ verbose_logger.warning(f"Failed to get allowed agents for team: {str(e)}")+ return []++ @staticmethod+ def _get_config_agent_ids_for_access_groups(+ config_agents: List, access_groups: List[str]+ ) -> Set[str]:+ """+ Helper to get agent_ids from config-loaded agents that match any of the given access groups.+ """+ server_ids: Set[str] = set()+ for agent in config_agents:+ agent_access_groups = getattr(agent, "agent_access_groups", None)+ if agent_access_groups:+ if any(group in agent_access_groups for group in access_groups):+ server_ids.add(agent.agent_id)+ return server_ids++ @staticmethod+ async def _get_db_agent_ids_for_access_groups(+ prisma_client, access_groups: List[str]+ ) -> Set[str]:+ """+ Helper to get agent_ids from DB agents that match any of the given access groups.+ """+ agent_ids: Set[str] = set()+ if access_groups and prisma_client is not None:+ try:+ agents = await prisma_client.db.litellm_agentstable.find_many(+ where={"agent_access_groups": {"hasSome": access_groups}}+ )+ for agent in agents:+ agent_ids.add(agent.agent_id)+ except Exception as e:+ verbose_logger.debug(+ f"Error getting agents from access groups: {e}"+ )+ return agent_ids++ @staticmethod+ async def _get_agents_from_access_groups(+ access_groups: List[str],+ ) -> List[str]:+ """+ Resolve agent access groups to agent IDs by querying BOTH the agent table (DB) AND config-loaded agents.+ """+ from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry+ from litellm.proxy.proxy_server import prisma_client++ try:+ # Use the helper for config-loaded agents+ agent_ids = AgentRequestHandler._get_config_agent_ids_for_access_groups(+ global_agent_registry.agent_list, access_groups+ )++ # Use the helper for DB agents+ db_agent_ids = await AgentRequestHandler._get_db_agent_ids_for_access_groups(+ prisma_client, access_groups+ )+ agent_ids.update(db_agent_ids)++ return list(agent_ids)+ except Exception as e:+ verbose_logger.warning(+ f"Failed to get agents from access groups: {str(e)}"+ )+ return []++ @staticmethod+ async def get_agent_access_groups(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> List[str]:+ """+ Get list of agent access groups for the given user/key based on permissions.+ """+ access_groups: List[str] = []+ access_groups_for_key = await AgentRequestHandler._get_agent_access_groups_for_key(+ user_api_key_auth+ )+ access_groups_for_team = await AgentRequestHandler._get_agent_access_groups_for_team(+ user_api_key_auth+ )++ # If team has access groups, then key must have a subset of the team's access groups+ if len(access_groups_for_team) > 0:+ for access_group in access_groups_for_key:+ if access_group in access_groups_for_team:+ access_groups.append(access_group)+ else:+ access_groups = access_groups_for_key++ return list(set(access_groups))++ @staticmethod+ async def _get_agent_access_groups_for_key(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> List[str]:+ """Get agent access groups for the key."""+ from litellm.proxy.auth.auth_checks import get_object_permission+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )++ if user_api_key_auth is None:+ return []++ if user_api_key_auth.object_permission_id is None:+ return []++ if prisma_client is None:+ verbose_logger.debug("prisma_client is None")+ return []++ try:+ key_object_permission = await get_object_permission(+ object_permission_id=user_api_key_auth.object_permission_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=user_api_key_auth.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )+ if key_object_permission is None:+ return []++ return key_object_permission.agent_access_groups or []+ except Exception as e:+ verbose_logger.warning(f"Failed to get agent access groups for key: {str(e)}")+ return []++ @staticmethod+ async def _get_agent_access_groups_for_team(+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,+ ) -> List[str]:+ """Get agent access groups for the team."""+ from litellm.proxy.auth.auth_checks import get_team_object+ from litellm.proxy.proxy_server import (+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ )++ if user_api_key_auth is None:+ return []++ if user_api_key_auth.team_id is None:+ return []++ if prisma_client is None:+ verbose_logger.debug("prisma_client is None")+ return []++ try:+ team_obj: Optional[LiteLLM_TeamTable] = await get_team_object(+ team_id=user_api_key_auth.team_id,+ prisma_client=prisma_client,+ user_api_key_cache=user_api_key_cache,+ parent_otel_span=user_api_key_auth.parent_otel_span,+ proxy_logging_obj=proxy_logging_obj,+ )+ if team_obj is None:+ verbose_logger.debug("team_obj is None")+ return []++ object_permissions = team_obj.object_permission+ if object_permissions is None:+ return []++ return object_permissions.agent_access_groups or []+ except Exception as e:+ verbose_logger.warning(+ f"Failed to get agent access groups for team: {str(e)}"+ )+ return []+diff --git a/litellm/proxy/agent_endpoints/endpoints.py b/litellm/proxy/agent_endpoints/endpoints.pyindex 90688036d84..7b18a2380c0 100644--- a/litellm/proxy/agent_endpoints/endpoints.py+++ b/litellm/proxy/agent_endpoints/endpoints.py@@ -49,25 +49,35 @@ async def get_agents("""from litellm.proxy.agent_endpoints.agent_registry import global_agent_registry+ from litellm.proxy.agent_endpoints.auth.agent_permission_handler import (+ AgentRequestHandler,+ )try:returned_agents: List[AgentResponse] = []++ # Admin users get all agentsif (user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMINor user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN.value):returned_agents = global_agent_registry.get_agent_list()- key_agents = user_api_key_dict.metadata.get("agents")- _team_metadata = user_api_key_dict.team_metadata or {}- team_agents = _team_metadata.get("agents")- if key_agents is not None:- returned_agents = global_agent_registry.get_agent_list(- agent_names=key_agents- )- if team_agents is not None:- returned_agents = global_agent_registry.get_agent_list(- agent_names=team_agents+ else:+ # Get allowed agents from object_permission (key/team level)+ allowed_agent_ids = await AgentRequestHandler.get_allowed_agents(+ user_api_key_auth=user_api_key_dict)++ # If no restrictions (empty list), return all agents+ if len(allowed_agent_ids) == 0:+ returned_agents = global_agent_registry.get_agent_list()+ else:+ # Filter agents by allowed IDs+ all_agents = global_agent_registry.get_agent_list()+ returned_agents = [+ agent for agent in all_agents+ if agent.agent_id in allowed_agent_ids+ ]# add is_public field to each agent - we do it this way, to allow setting config agents as publicfor agent in returned_agents:@@ -83,7 +93,7 @@ async def get_agents(raiseexcept Exception as e:verbose_proxy_logger.exception(- "litellm.proxy.anthropic_endpoints.count_tokens(): Exception occurred - {}".format(+ "litellm.proxy.agent_endpoints.get_agents(): Exception occurred - {}".format(str(e)))diff --git a/litellm/proxy/auth/route_checks.py b/litellm/proxy/auth/route_checks.pyindex aaef2103ad9..909c517a34d 100644--- a/litellm/proxy/auth/route_checks.py+++ b/litellm/proxy/auth/route_checks.py@@ -297,6 +297,11 @@ class RouteChecks:route=route, allowed_routes=LiteLLMRoutes.mcp_routes.value):return True++ if RouteChecks.check_route_access(+ route=route, allowed_routes=LiteLLMRoutes.agent_routes.value+ ):+ return True# fuzzy match routes like "/v1/threads/thread_49EIN5QF32s4mH20M7GFKdlZ"# Check for routes with placeholdersdiff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex 077e99491c3..da44bda791d 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -1023,7 +1023,7 @@ async def generate_key_fn(- prompts: Optional[List[str]] - List of prompts that the key is allowed to use.- allowed_routes: Optional[list] - List of allowed routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/chat/completions", "/embeddings", "/keys/*"]- allowed_passthrough_routes: Optional[list] - List of allowed pass through endpoints for the key. Store the actual endpoint or store a wildcard pattern for a set of endpoints. Example - ["/my-custom-endpoint"]. Use this instead of allowed_routes, if you just want to specify which pass through endpoints the key can access, without specifying the routes. If allowed_routes is specified, allowed_pass_through_endpoints is ignored.- - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.+ - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.- key_type: Optional[str] - Type of key that determines default allowed routes. Options: "llm_api" (can call LLM API routes), "management" (can call management routes), "read_only" (can only call info/read routes), "default" (uses default allowed routes). Defaults to "default".- prompts: Optional[List[str]] - List of allowed prompts for the key. If specified, the key will only be able to use these specific prompts.- auto_rotate: Optional[bool] - Whether this key should be automatically rotated (regenerated)@@ -1175,7 +1175,7 @@ async def generate_service_account_key_fn(- tags: Optional[List[str]] - Tags for [tracking spend](https://litellm.vercel.app/docs/proxy/enterprise#tracking-spend-for-custom-tags) and/or doing [tag-based routing](https://litellm.vercel.app/docs/proxy/tag_routing).- enforced_params: Optional[List[str]] - List of enforced params for the key (Enterprise only). [Docs](https://docs.litellm.ai/docs/proxy/enterprise#enforce-required-params-for-llm-requests)- allowed_routes: Optional[list] - List of allowed routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/chat/completions", "/embeddings", "/keys/*"]- - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.+ - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.Examples:- allowed_vector_store_indexes: Optional[List[dict]] - List of allowed vector store indexes for the key. Example - [{"index_name": "my-index", "index_permissions": ["write", "read"]}]. If specified, the key will only be able to use these specific vector store indexes. Create index, using `/v1/indexes` endpoint.@@ -1466,7 +1466,7 @@ async def update_key_fn(- allowed_routes: Optional[list] - List of allowed routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/chat/completions", "/embeddings", "/keys/*"]- allowed_passthrough_routes: Optional[list] - List of allowed pass through routes for the key. Store the actual route or store a wildcard pattern for a set of routes. Example - ["/my-custom-endpoint"]. Use this instead of allowed_routes, if you just want to specify which pass through routes the key can access, without specifying the routes. If allowed_routes is specified, allowed_passthrough_routes is ignored.- prompts: Optional[List[str]] - List of allowed prompts for the key. If specified, the key will only be able to use these specific prompts.- - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.+ - object_permission: Optional[LiteLLM_ObjectPermissionBase] - key-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.- auto_rotate: Optional[bool] - Whether this key should be automatically rotated- rotation_interval: Optional[str] - How often to rotate this key (e.g., '30d', '90d'). Required if auto_rotate=True- allowed_vector_store_indexes: Optional[List[dict]] - List of allowed vector store indexes for the key. Example - [{"index_name": "my-index", "index_permissions": ["write", "read"]}]. If specified, the key will only be able to use these specific vector store indexes. Create index, using `/v1/indexes` endpoint.diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex 751542c6b46..ba10d250417 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -679,7 +679,7 @@ async def new_team( # noqa: PLR0915- guardrails: Optional[List[str]] - Guardrails for the team. [Docs](https://docs.litellm.ai/docs/proxy/guardrails)- disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key.- prompts: Optional[List[str]] - List of prompts that the team is allowed to use.- - object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.+ - object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.- team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.- team_member_rpm_limit: Optional[int] - The RPM (Requests Per Minute) limit for individual team members.- team_member_tpm_limit: Optional[int] - The TPM (Tokens Per Minute) limit for individual team members.@@ -1202,7 +1202,7 @@ async def update_team(- guardrails: Optional[List[str]] - Guardrails for the team. [Docs](https://docs.litellm.ai/docs/proxy/guardrails)- disable_global_guardrails: Optional[bool] - Whether to disable global guardrails for the key.- prompts: Optional[List[str]] - List of prompts that the team is allowed to use.- - object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "mcp_tool_permissions": {"server_id_1": ["tool1", "tool2"]}}. IF null or {} then no object permission.+ - object_permission: Optional[LiteLLM_ObjectPermissionBase] - team-specific object permission. Example - {"vector_stores": ["vector_store_1", "vector_store_2"], "agents": ["agent_1", "agent_2"], "agent_access_groups": ["dev_group"]}. IF null or {} then no object permission.- team_member_budget: Optional[float] - The maximum budget allocated to an individual team member.- team_member_rpm_limit: Optional[int] - The RPM (Requests Per Minute) limit for individual team members.- team_member_tpm_limit: Optional[int] - The TPM (Tokens Per Minute) limit for individual team members.diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 2883dfc4b82..583c493adc6 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -61,6 +61,7 @@ model LiteLLM_AgentsTable {agent_name String @uniquelitellm_params Json?agent_card_params Json+ agent_access_groups String[] @default([])created_at DateTime @default(now()) @map("created_at")created_by Stringupdated_at DateTime @default(now()) @updatedAt @map("updated_at")@@ -172,6 +173,8 @@ model LiteLLM_ObjectPermissionTable {mcp_access_groups String[] @default([])mcp_tool_permissions Json? // Tool-level permissions for MCP servers. Format: {"server_id": ["tool_name_1", "tool_name_2"]}vector_stores String[] @default([])+ agents String[] @default([])+ agent_access_groups String[] @default([])teams LiteLLM_TeamTable[]verification_tokens LiteLLM_VerificationToken[]organizations LiteLLM_OrganizationTable[]diff --git a/schema.prisma b/schema.prismaindex 2883dfc4b82..583c493adc6 100644--- a/schema.prisma+++ b/schema.prisma@@ -61,6 +61,7 @@ model LiteLLM_AgentsTable {agent_name String @uniquelitellm_params Json?agent_card_params Json+ agent_access_groups String[] @default([])created_at DateTime @default(now()) @map("created_at")created_by Stringupdated_at DateTime @default(now()) @updatedAt @map("updated_at")@@ -172,6 +173,8 @@ model LiteLLM_ObjectPermissionTable {mcp_access_groups String[] @default([])mcp_tool_permissions Json? // Tool-level permissions for MCP servers. Format: {"server_id": ["tool_name_1", "tool_name_2"]}vector_stores String[] @default([])+ agents String[] @default([])+ agent_access_groups String[] @default([])teams LiteLLM_TeamTable[]verification_tokens LiteLLM_VerificationToken[]organizations LiteLLM_OrganizationTable[]diff --git a/tests/test_litellm/proxy/agent_endpoints/auth/__init__.py b/tests/test_litellm/proxy/agent_endpoints/auth/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.py b/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.pynew file mode 100644index 00000000000..111dd7c0764--- /dev/null+++ b/tests/test_litellm/proxy/agent_endpoints/auth/test_agent_permission_handler.py@@ -0,0 +1,113 @@+"""+Unit tests for AgentRequestHandler - Agent permission management for keys and teams.+"""++import os+import sys+from unittest.mock import patch++import pytest++sys.path.insert(0, os.path.abspath("../../../.."))++from litellm.proxy._types import UserAPIKeyAuth+from litellm.proxy.agent_endpoints.auth.agent_permission_handler import (+ AgentRequestHandler,+)+++class TestAgentRequestHandler:+ """+ Test suite for AgentRequestHandler permission logic.+ """++ async def test_get_allowed_agents_intersection_logic(self):+ """+ Test key/team intersection: when both have restrictions, only common agents are allowed.+ When team has restrictions but key has none, key inherits from team.+ When neither has restrictions, returns empty list (meaning allow all).+ """+ mock_user_auth = UserAPIKeyAuth(+ api_key="test-key",+ user_id="test-user",+ team_id="test-team",+ )++ # Case 1: Both key and team have agents - intersection+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_key") as mock_key:+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_team") as mock_team:+ mock_key.return_value = ["agent1", "agent2", "agent3"]+ mock_team.return_value = ["agent2", "agent4"]++ result = await AgentRequestHandler.get_allowed_agents(user_api_key_auth=mock_user_auth)+ assert sorted(result) == ["agent2"]++ # Case 2: Team has agents, key has none - inherit from team+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_key") as mock_key:+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_team") as mock_team:+ mock_key.return_value = []+ mock_team.return_value = ["team_agent1", "team_agent2"]++ result = await AgentRequestHandler.get_allowed_agents(user_api_key_auth=mock_user_auth)+ assert sorted(result) == ["team_agent1", "team_agent2"]++ # Case 3: No restrictions - returns empty list (allow all)+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_key") as mock_key:+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_team") as mock_team:+ mock_key.return_value = []+ mock_team.return_value = []++ result = await AgentRequestHandler.get_allowed_agents(user_api_key_auth=mock_user_auth)+ assert result == []++ async def test_is_agent_allowed_respects_permissions(self):+ """+ Test is_agent_allowed: returns True if agent in allowed list or if no restrictions.+ Returns False if agent not in allowed list.+ """+ mock_user_auth = UserAPIKeyAuth(api_key="test-key", user_id="test-user")++ # Agent in allowed list - should be allowed+ with patch.object(AgentRequestHandler, "get_allowed_agents") as mock_get_allowed:+ mock_get_allowed.return_value = ["agent1", "agent2"]+ assert await AgentRequestHandler.is_agent_allowed(agent_id="agent1", user_api_key_auth=mock_user_auth) is True++ # Agent not in allowed list - should be denied+ with patch.object(AgentRequestHandler, "get_allowed_agents") as mock_get_allowed:+ mock_get_allowed.return_value = ["agent1", "agent2"]+ assert await AgentRequestHandler.is_agent_allowed(agent_id="agent3", user_api_key_auth=mock_user_auth) is False++ # Empty list means no restrictions - should allow any agent+ with patch.object(AgentRequestHandler, "get_allowed_agents") as mock_get_allowed:+ mock_get_allowed.return_value = []+ assert await AgentRequestHandler.is_agent_allowed(agent_id="any_agent", user_api_key_auth=mock_user_auth) is True++ async def test_no_auth_allows_all_agents(self):+ """+ Test that when user_api_key_auth is None, all agents are allowed (no restrictions).+ """+ result = await AgentRequestHandler.get_allowed_agents(user_api_key_auth=None)+ assert result == []++ is_allowed = await AgentRequestHandler.is_agent_allowed(agent_id="any_agent", user_api_key_auth=None)+ assert is_allowed is True++ async def test_get_allowed_agents_handles_errors_gracefully(self):+ """+ Test that errors during permission lookup are handled gracefully (returns empty list).+ """+ mock_user_auth = UserAPIKeyAuth(+ api_key="test-key",+ user_id="test-user",+ team_id="test-team",+ object_permission_id="test-permission",+ )++ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_key") as mock_key:+ with patch.object(AgentRequestHandler, "_get_allowed_agents_for_team") as mock_team:+ mock_key.side_effect = Exception("DB Error")+ mock_team.return_value = []++ result = await AgentRequestHandler.get_allowed_agents(user_api_key_auth=mock_user_auth)+ assert result == []