Skip to content

feat(mcp): let a key scope to zero MCP servers - #31028

Closed
ryan-crabbe-berri wants to merge 1 commit into
mainfrom
litellm_mcp_key_explicit_empty_scope
Closed

ryan-crabbe-berri wants to merge 1 commit into
mainfrom
litellm_mcp_key_explicit_empty_scope

Conversation

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor

Summary

A virtual key's object_permission.mcp_servers was a non-nullable String[], so an empty list and an unset value both collapsed to [], and the runtime resolver read either one as "inherit the team's full MCP server list". There was no way to give a key zero servers under a team that has servers, which pushed keys past provider tool caps (for example OpenAI's 128-tool limit)

This makes the column a nullable JSON value with a clear tri-state: null inherits the team, [] means no servers, and a list means exactly those servers. The resolver honors the distinction, a data-preserving migration converts the column in place and backfills existing [] to null so every current key and team keeps inheriting and no live row changes behavior, and the dashboard key forms get an explicit Inherit / No access / Specific control so the zero state is reachable without the API

Type

New Feature

Changes

  • schema.prisma and its two synced copies: mcp_servers is now Json? instead of String[] @default([])
  • New migration 20260622120000_make_mcp_servers_nullable_jsonb does an in-place ALTER ... TYPE jsonb USING (...) that backfills empty arrays to null. Prisma's own diff drops and recreates the column (data loss), so this is hand-authored per the migration runbook
  • MCPRequestHandler._get_allowed_mcp_servers_for_key now returns Optional[List[str]]; the key/team combination treats null as inherit and [] as an explicit empty scope that intersects the team down to nothing
  • LiteLLM_ObjectPermissionTable.mcp_servers default changed to None so the inherit/zero distinction survives cache round-trips
  • the object_permission write path serializes mcp_servers like its existing mcp_tool_permissions JSON sibling
  • get_objectpermissions_for_mcp_server matches in Python because the jsonb column cannot use the prisma has filter
  • dashboard: the key create and edit forms gain an Inherit / No access / Specific mode control

Test plan

  • resolver regressions: explicit [] under a populated team resolves to zero, null inherits the team, a real subset intersects
  • _get_allowed_mcp_servers_for_key returns None / [] / list for the three stored shapes
  • cache round-trip keeps None as None and [] as [], guarding the model default
  • migration applies with zero drift via the runbook generator
  • live proxy on :4000 against real MCP servers (see Proof of Fix)

Proof of Fix

Live on a proxy at localhost:4000 with three local MCP servers and a team scoped to all three. Three keys created under that team:

# explicit [] key — write round-trip
GET /key/info -> object_permission.mcp_servers == []     # persisted as [], not collapsed

# resolved tool counts (GET /mcp-rest/tools/list per key)
explicit []   -> 0 tools     # was 6 before this change
unset/inherit -> 6 tools
subset [A]    -> 2 tools

UI: Virtual Keys -> Create or Edit a key -> the "MCP Servers / Access Groups" control now offers Inherit from team, No MCP access, and Specific servers

A key's object_permission.mcp_servers was a non-nullable String[], so an
empty list and an unset value both collapsed to [], and the resolver read
either one as "inherit the team's full MCP server list". That made it
impossible to give a key zero servers under a team that has servers, which
pushed keys past provider tool caps. The column is now nullable JSON where
null inherits the team, [] means no servers, and a list means exactly those,
and the resolver honors the distinction. A data-preserving migration
converts the column in place and backfills existing [] to null, so every
current key and team keeps inheriting and no live row changes behavior. The
dashboard key create and edit forms gain an explicit Inherit / No access /
Specific control so the new zero state is reachable without the API
@codecov

codecov Bot commented Jun 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.47619% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/proxy/_experimental/mcp_server/db.py 0.00% 1 Missing ⚠️
...roxy/management_helpers/object_permission_utils.py 75.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@greptile-apps

greptile-apps Bot commented Jun 22, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR introduces a nullable-JSONB tri-state for mcp_servers on LiteLLM_ObjectPermissionTable so that null (inherit team scope), [] (explicitly no servers), and a concrete list are all distinguishable, enabling a key to be scoped to zero MCP servers under a team that has them.

  • The hand-authored migration converts the old String[] column in-place, backfills empty arrays to NULL, and avoids Prisma's destructive DROP/ADD path.
  • _get_allowed_mcp_servers_for_key now returns Optional[List[str]]; None means "inherit team" and [] means "intersect team down to nothing"; the combination logic and cache round-trip handling are both updated.
  • The dashboard key create and edit forms gain an Inherit / No access / Specific radio control wired end-to-end through the submit handlers.

Confidence Score: 3/5

The resolver, cache, and UI changes are correct and well-tested, but two write-path issues should be resolved before merging.

get_objectpermissions_for_mcp_server now pulls every object-permission row into memory with joined relations to filter in Python, and the update path passes Python None directly for mcp_servers while the sibling mcp_tool_permissions always goes through safe_dumps — if Prisma treats bare None as omit-field, switching a key back to inherit mode will silently leave the old restriction in the DB.

litellm/proxy/_experimental/mcp_server/db.py (full table scan) and litellm/proxy/management_helpers/object_permission_utils.py (None vs safe_dumps inconsistency in the update path).

Important Files Changed

Filename Overview
litellm-proxy-extras/litellm_proxy_extras/migrations/20260622120000_make_mcp_servers_nullable_jsonb/migration.sql Hand-authored in-place ALTER using a USING cast that preserves data and backfills empty arrays to NULL; avoids Prisma's destructive DROP/ADD approach. Logic is correct and well-commented.
litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py Tri-state resolver logic (None=inherit, []=zero, list=intersect) is correctly implemented; guard-clause returns and exception handler now return None instead of [], matching the new semantics. Test coverage is thorough.
litellm/proxy/_experimental/mcp_server/db.py get_objectpermissions_for_mcp_server replaced a targeted DB-level has-filter with a full Python-side scan of all object-permission rows (with eagerly loaded relations), introducing a potentially severe performance regression.
litellm/proxy/management_helpers/object_permission_utils.py mcp_servers serialization added for both create and update paths, but None is passed directly to the Prisma upsert (unlike sibling field mcp_tool_permissions which always goes through safe_dumps), creating a potential null-reset gap.
litellm/models/object_permission.py Default changed from [] to None so cache round-trips (exclude_none serialization) correctly preserve the inherit/zero distinction. Cache round-trip tests confirm this.
ui/litellm-dashboard/src/components/templates/key_edit_view.tsx Radio group (Inherit/No access/Specific) correctly drives conditional rendering of MCPServerSelector; getMcpScopeMode initialises the form field from existing key data using the correct null/empty/list checks.
ui/litellm-dashboard/src/components/templates/key_info_view.tsx handleKeyUpdate correctly translates the mcp_scope_mode tri-state into the object_permission payload, clears access groups and toolsets when mode is not specific, and deletes internal form fields before the API call.
ui/litellm-dashboard/src/components/organisms/create_key_button.tsx Create-key form properly maps mcp_scope_mode to the object_permission payload; inherit leaves mcp_servers absent (DB defaults to NULL), none sends [], specific sends the selected servers.
tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py Existing tests correctly updated from [] to None for inherit guard conditions; new parametrised test covers all three tri-state scenarios end-to-end through get_allowed_mcp_servers.

Reviews (1): Last reviewed commit: "feat(mcp): let a key scope to zero MCP s..." | Re-trigger Greptile

Comment on lines 521 to +534
object_permission_records = await ObjectPermissionRepository(
prisma_client
).table.find_many(
where={
"mcp_servers": {"has": mcp_server_id},
},
include={
"teams": True,
"verification_tokens": True,
},
)

return object_permission_records
return [
record
for record in object_permission_records
if isinstance(record.mcp_servers, list) and mcp_server_id in record.mcp_servers
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Full table scan replacing targeted DB query

get_objectpermissions_for_mcp_server now loads every LiteLLM_ObjectPermissionTable row (including eagerly-joined teams and verification_tokens) and filters by mcp_server_id in Python. Before this change, a PostgreSQL GIN-indexed has filter did the work in the engine. With even a few thousand object-permission rows this will be slow and memory-heavy.

The JSONB column can't use Prisma's scalar-list has, but PostgreSQL's JSONB containment operator @> works directly: WHERE "mcp_servers" @> '["<id>"]'::jsonb. A prisma_client.execute_raw call with that predicate would restore the index-backed query without pulling every row into Python.

Comment on lines +139 to +143
# mcp_servers is a JSON column; serialize the list (None stays NULL = inherit).
if isinstance(existing_object_permissions_dict.get("mcp_servers"), list):
existing_object_permissions_dict["mcp_servers"] = safe_dumps(
existing_object_permissions_dict["mcp_servers"]
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 None passed directly to Prisma may not reset the JSON column to SQL NULL

mcp_tool_permissions (the sibling Json? field) is always routed through safe_dumps(), including when the value is None (safe_dumps(None) → "null"), so Prisma receives an explicit JSON null string and writes JSON null to the column. Here, mcp_servers = None is passed as a raw Python None in the upsert dict, which some Prisma client versions treat as "omit field" rather than "SET NULL". If the column isn't reset to SQL NULL when a user switches back to "inherit" mode, the old [] / specific-list value will persist and the key will remain locked out of team servers silently.

If Prisma's Python client does correctly map None → NULL for Json? fields this is fine, but the inconsistency with the existing mcp_tool_permissions pattern is worth a quick regression test against the real ORM path.

@yuneng-berri
yuneng-berri deleted the branch main September 13, 2026 04:25
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 16:00
@CLAassistant

CLAassistant commented Nov 4, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@mateo-berri

Copy link
Copy Markdown
Contributor

Main already lets a key opt out of every MCP server with the no-mcp-servers option from #31029, reopen if something is still missing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants