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
[MCP Gateway] Fine-grained Database Object Storage Control (#15255)
Ishaan Jaff1d468a59f301
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.mdindex 50bd5aefa76..33e9ebad153 100644--- a/docs/my-website/docs/mcp.md+++ b/docs/my-website/docs/mcp.md@@ -23,6 +23,43 @@ LiteLLM Proxy provides an MCP Gateway that allows you to use a fixed endpoint fo## Adding your MCP+### Prerequisites++To store MCP servers in the database, you need to enable database storage:++**Environment Variable:**+```bash+export STORE_MODEL_IN_DB=True+```++**OR in config.yaml:**+```yaml+general_settings:+ store_model_in_db: true+```++#### Fine-grained Database Storage Control++By default, when `store_model_in_db` is `true`, all object types (models, MCPs, guardrails, vector stores, etc.) are stored in the database. If you want to store only specific object types, use the `supported_db_objects` setting.++**Example: Store only MCP servers in the database**++```yaml title="config.yaml" showLineNumbers+general_settings:+ store_model_in_db: true+ supported_db_objects: ["mcp"] # Only store MCP servers in DB++model_list:+ - model_name: gpt-4o+ litellm_params:+ model: openai/gpt-4o+ api_key: sk-xxxxxxx+```++**See all available object types:** [Config Settings - supported_db_objects](./proxy/config_settings.md#general_settings---reference)++If `supported_db_objects` is not set, all object types are loaded from the database (default behavior).+<Tabs><TabItem value="ui" label="LiteLLM UI">diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex ad3afd59a02..c674af1237d 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -224,6 +224,7 @@ router_settings:| service_account_settings | List[Dict[str, Any]] | Set `service_account_settings` if you want to create settings that only apply to service account keys (Doc on service accounts)[./service_accounts.md] || image_generation_model | str | The default model to use for image generation - ignores model set in request || store_model_in_db | boolean | If true, enables storing model + credential information in the DB. |+| supported_db_objects | List[str] | Fine-grained control over which object types to load from the database when `store_model_in_db` is True. Available types: `"models"`, `"mcp"`, `"guardrails"`, `"vector_stores"`, `"pass_through_endpoints"`, `"prompts"`, `"model_cost_map"`. If not set, all object types are loaded (default behavior). Example: `supported_db_objects: ["mcp"]` to only load MCP servers from DB. || store_prompts_in_spend_logs | boolean | If true, allows prompts and responses to be stored in the spend logs table. || max_request_size_mb | int | The maximum size for requests in MB. Requests above this size will be rejected. || max_response_size_mb | int | The maximum size for responses in MB. LLM Responses above this size will not be sent. |diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 9c41ad8e1aa..096bbc029b5 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -52,6 +52,24 @@ else:Span = Any+class SupportedDBObjectType(str, enum.Enum):+ """+ Supported database object types for fine-grained DB storage control.+ Use in general_settings.supported_db_objects to specify which objects to load from DB.+ """++ MODELS = "models"+ MCP = "mcp"+ GUARDRAILS = "guardrails"+ VECTOR_STORES = "vector_stores"+ PASS_THROUGH_ENDPOINTS = "pass_through_endpoints"+ PROMPTS = "prompts"+ MODEL_COST_MAP = "model_cost_map"++ def __str__(self):+ return str(self.value)++class LiteLLMTeamRoles(enum.Enum):# team adminTEAM_ADMIN = "admin"@@ -1760,6 +1778,10 @@ class ConfigGeneralSettings(LiteLLMPydanticObjectBase):description="[DEPRECATED] Use 'user_header_mappings' instead. When set, the header value is treated as the end user id unless overridden by user_header_mappings.",)user_header_mappings: Optional[List[UserHeaderMapping]] = None+ supported_db_objects: Optional[List[SupportedDBObjectType]] = Field(+ None,+ description="Fine-grained control over which object types to load from the database when store_model_in_db is True. Available types: 'models', 'mcp', 'guardrails', 'vector_stores', 'pass_through_endpoints', 'prompts', 'model_cost_map'. If not set, all objects are loaded (default behavior).",+ )class ConfigYAML(LiteLLMPydanticObjectBase):diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 5409d73164b..e60482bc8d7 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -2957,6 +2957,40 @@ class ProxyConfig:return config+ def _should_load_db_object(+ self, object_type: Union[str, SupportedDBObjectType]+ ) -> bool:+ """+ Check if an object type should be loaded from the database based on general_settings.supported_db_objects.++ Args:+ object_type: Type of object to check (e.g., SupportedDBObjectType.MODELS, "models", etc.)++ Returns:+ True if the object should be loaded, False otherwise+ """+ global general_settings++ # Get the supported_db_objects configuration+ supported_db_objects = general_settings.get("supported_db_objects", None)++ # If supported_db_objects is not set, load all objects (default behavior)+ if supported_db_objects is None:+ return True++ # If supported_db_objects is set, only load specified objects+ if not isinstance(supported_db_objects, list):+ verbose_proxy_logger.warning(+ f"supported_db_objects is not a list, got {type(supported_db_objects)}. Loading all objects."+ )+ return True++ # Convert object_type to string for comparison (handles both str and enum)+ object_type_str = str(object_type)++ # Check if the object type is in the list (supports both str and enum values)+ return any(str(obj) == object_type_str for obj in supported_db_objects)+async def _get_models_from_db(self, prisma_client: PrismaClient) -> list:try:new_models = await prisma_client.db.litellm_proxymodeltable.find_many()@@ -2988,12 +3022,14 @@ class ProxyConfig:f"Master key is not initialized or formatted. master_key={master_key}")- new_models = await self._get_models_from_db(prisma_client=prisma_client)+ # Only load models from DB if "models" is in supported_db_objects (or if supported_db_objects is not set)+ if self._should_load_db_object(object_type="models"):+ new_models = await self._get_models_from_db(prisma_client=prisma_client)- # update llm router- await self._update_llm_router(- new_models=new_models, proxy_logging_obj=proxy_logging_obj- )+ # update llm router+ await self._update_llm_router(+ new_models=new_models, proxy_logging_obj=proxy_logging_obj+ )db_general_settings = await prisma_client.db.litellm_config.find_first(where={"param_name": "general_settings"}@@ -3021,12 +3057,23 @@ class ProxyConfig:ex. Vector Stores, Guardrails, MCP tools, etc."""- await self._init_guardrails_in_db(prisma_client=prisma_client)- await self._init_vector_stores_in_db(prisma_client=prisma_client)- await self._init_mcp_servers_in_db()- await self._init_pass_through_endpoints_in_db()- await self._init_prompts_in_db(prisma_client=prisma_client)- await self._check_and_reload_model_cost_map(prisma_client=prisma_client)+ if self._should_load_db_object(object_type="guardrails"):+ await self._init_guardrails_in_db(prisma_client=prisma_client)++ if self._should_load_db_object(object_type="vector_stores"):+ await self._init_vector_stores_in_db(prisma_client=prisma_client)++ if self._should_load_db_object(object_type="mcp"):+ await self._init_mcp_servers_in_db()++ if self._should_load_db_object(object_type="pass_through_endpoints"):+ await self._init_pass_through_endpoints_in_db()++ if self._should_load_db_object(object_type="prompts"):+ await self._init_prompts_in_db(prisma_client=prisma_client)++ if self._should_load_db_object(object_type="model_cost_map"):+ await self._check_and_reload_model_cost_map(prisma_client=prisma_client)async def _check_and_reload_model_cost_map(self, prisma_client: PrismaClient):"""diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 63436899fcc..43e3e2ad0c9 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -2030,3 +2030,89 @@ def test_add_callback_from_db_to_in_memory_litellm_callbacks():existing_callbacks=existing_callbacks_with_item,)mock_callback_manager.add_litellm_success_callback.assert_not_called()+++def test_should_load_db_object_with_supported_db_objects():+ """+ Test _should_load_db_object method with supported_db_objects configuration.++ Verifies that when supported_db_objects is set, only specified object types+ are loaded from the database.+ """+ from unittest.mock import patch++ from litellm.proxy.proxy_server import ProxyConfig++ proxy_config = ProxyConfig()++ # Test Case 1: supported_db_objects not set - all objects should be loaded+ with patch("litellm.proxy.proxy_server.general_settings", {}):+ assert proxy_config._should_load_db_object(object_type="models") is True+ assert proxy_config._should_load_db_object(object_type="mcp") is True+ assert proxy_config._should_load_db_object(object_type="guardrails") is True+ assert proxy_config._should_load_db_object(object_type="vector_stores") is True++ # Test Case 2: supported_db_objects set to only load MCP+ with patch(+ "litellm.proxy.proxy_server.general_settings",+ {"supported_db_objects": ["mcp"]},+ ):+ assert proxy_config._should_load_db_object(object_type="models") is False+ assert proxy_config._should_load_db_object(object_type="mcp") is True+ assert proxy_config._should_load_db_object(object_type="guardrails") is False+ assert proxy_config._should_load_db_object(object_type="vector_stores") is False+ assert proxy_config._should_load_db_object(object_type="prompts") is False++ # Test Case 3: supported_db_objects set to load multiple types+ with patch(+ "litellm.proxy.proxy_server.general_settings",+ {"supported_db_objects": ["mcp", "guardrails", "vector_stores"]},+ ):+ assert proxy_config._should_load_db_object(object_type="models") is False+ assert proxy_config._should_load_db_object(object_type="mcp") is True+ assert proxy_config._should_load_db_object(object_type="guardrails") is True+ assert proxy_config._should_load_db_object(object_type="vector_stores") is True+ assert proxy_config._should_load_db_object(object_type="prompts") is False++ # Test Case 4: supported_db_objects is not a list (should default to loading all)+ with patch(+ "litellm.proxy.proxy_server.general_settings",+ {"supported_db_objects": "invalid_type"},+ ):+ assert proxy_config._should_load_db_object(object_type="models") is True+ assert proxy_config._should_load_db_object(object_type="mcp") is True++ # Test Case 5: supported_db_objects is an empty list (nothing should be loaded)+ with patch(+ "litellm.proxy.proxy_server.general_settings",+ {"supported_db_objects": []},+ ):+ assert proxy_config._should_load_db_object(object_type="models") is False+ assert proxy_config._should_load_db_object(object_type="mcp") is False+ assert proxy_config._should_load_db_object(object_type="guardrails") is False++ # Test Case 6: Test all available object types+ with patch(+ "litellm.proxy.proxy_server.general_settings",+ {+ "supported_db_objects": [+ "models",+ "mcp",+ "guardrails",+ "vector_stores",+ "pass_through_endpoints",+ "prompts",+ "model_cost_map",+ ]+ },+ ):+ assert proxy_config._should_load_db_object(object_type="models") is True+ assert proxy_config._should_load_db_object(object_type="mcp") is True+ assert proxy_config._should_load_db_object(object_type="guardrails") is True+ assert proxy_config._should_load_db_object(object_type="vector_stores") is True+ assert (+ proxy_config._should_load_db_object(object_type="pass_through_endpoints")+ is True+ )+ assert proxy_config._should_load_db_object(object_type="prompts") is True+ assert proxy_config._should_load_db_object(object_type="model_cost_map") is True