Commit Graph

163 Commits

Author SHA1 Message Date
joereyna 0c1739390b fix: remove skip decorators from m2m tests now that oauth2_flow is set 2026-03-16 13:17:27 -07:00
Cursor Agent ff145398d5 fix(ci): skip tests requiring openai>=2.x and MCP M2M oauth2_flow
- Skip test_apply_patch_tool_call_converted_to_chat_completion_tool_call
  when openai.types.responses.response_apply_patch_tool_call is unavailable
  (CI uses openai==1.100.1 which doesn't have this module)
- Skip MCP M2M tests (test_m2m_credentials_forwarded_to_server_model,
  test_m2m_drops_incoming_oauth2_headers) that fail because PR #23187
  changed has_client_credentials to require explicit oauth2_flow opt-in
  but _execute_with_mcp_client was not updated to pass it through
- Revert source code change to rest_endpoints.py that auto-inferred
  oauth2_flow (regression risk: this changes MCP OAuth behavior)

Co-authored-by: yuneng-jiang <yuneng-jiang@users.noreply.github.com>
2026-03-13 01:09:56 +00:00
Cursor Agent 177edb06ae fix: stabilize 5 CI test failures
- Vertex AI batch cost tests: replace removed gemini-1.5-flash-001 model
  with gemini-2.0-flash-001 in pricing lookups
- MCP test_executes_tool_when_allowed: add server_id and auth_type attrs
  to StubServer to match new _resolve_allowed_mcp_servers_with_ip_filter
- MCP M2M tests: infer oauth2_flow='client_credentials' in
  _execute_with_mcp_client when client_id/client_secret/token_url present
  (NewMCPServerRequest lacks oauth2_flow field)
- Team list test: update mock find_many to filter by team_id per the
  current per-team query pattern in list_team
- Azure DALL-E 3 health check: skip test due to 410 ModelDeprecated

Co-authored-by: yuneng-jiang <yuneng-jiang@users.noreply.github.com>
2026-03-13 01:03:35 +00:00
Joe Reyna 03a0c37608 Merge pull request #23467 from joereyna/fix/mcp-oauth2-token-cache-tests
fix: add oauth2_flow="client_credentials" to MCPServer test helper
2026-03-12 14:55:42 -07:00
joereyna 180e72d15d fix: add oauth2_flow=client_credentials to MCPServer test helper 2026-03-12 12:22:18 -07:00
Chesars 4e6e1d8de8 merge: resolve conflicts with upstream staging (bedrock + mcp tests)
Keep both sets of tests: upstream's OAuth2 token injection test and
our case-insensitive tool matching tests. Use upstream's version of
the bedrock output_config test (more comprehensive).
2026-03-12 13:40:16 -03:00
Chesars feed274aa3 Reapply "feat: add model_cost aliases expansion support"
This reverts commit 3d2df7e8b5.
2026-03-12 13:36:57 -03:00
Chesars 1be6b31e2f merge: resolve conflicts between main and litellm_oss_staging_03_11_2026 2026-03-12 09:38:31 -03:00
Ishaan Jaff 19db79db17 fix(mcp): OAuth2 chat connect - tools fetch, auth, and status fixes (#23406)
* fix(mcp): OAuth2 chat connect - tools fetch, auth flow, and status fixes

- schema.prisma: add missing MCP table fields (approval_status, submitted_by, submitted_at, reviewed_at, review_notes) to prevent destructive migrations
- rest_endpoints.py: inject user OAuth token via extra_headers for OAuth2 servers so tools list is populated; add server name->UUID resolution so MCPConnectPicker name lookups work
- mcp_registry.json: fix Atlassian defaults (transport: http, url: .../v1/mcp)
- ChatPage.tsx: read mcpOauthReturn param to init sidebarView="apps" on OAuth return, clean up param after mount
- MCPAppsPanel.tsx: auto-add OAuth2 servers to selectedServers when credential detected; onConnect also enables server for chat; disconnect removes from selectedServers
- mcp_servers.tsx: sort servers by created_at DESC
- useUserMcpOAuthFlow.tsx: append mcpOauthReturn=apps to return URL so Apps panel is mounted on return

* address greptile review feedback (greploop iteration 1)

* fix(mcp): inject stored OAuth2 token when fetching tools via /responses API

When a user has connected an OAuth2 MCP server (e.g. Atlassian) and then
uses the /responses endpoint with that server, tool listing was failing
because the stored per-user OAuth token was never injected.

Two fixes:
1. server.py: add _get_user_oauth_extra_headers_from_db() helper; call it
   in _get_tools_from_mcp_servers when oauth2_headers is None for an OAuth2
   server, falling back to the user's stored token in LiteLLM_MCPUserCredentials
2. litellm_proxy_mcp_handler.py: also intercept MCP tools whose server_url
   matches */mcp/<server_name> (e.g. http://localhost:4000/mcp/atlassian_test)
   by rewriting them to litellm_proxy/mcp/<server_name> so they go through
   the internal handler (and get the OAuth token injected) instead of being
   forwarded to OpenAI raw where localhost is unreachable

* address greptile review feedback (greploop iteration 2)

* test(mcp): add unit test for OAuth2 token injection in _get_tools_from_mcp_servers

Verifies that when _get_tools_from_mcp_servers is called for an OAuth2 MCP
server without oauth2_headers in the request, the implementation:
- calls _prefetch_oauth_creds_for_user once (not per-server) to avoid N+1 queries
- passes the stored token as extra_headers={"Authorization": "Bearer ..."} to
  _get_tools_from_server so the upstream OAuth2 MCP server authenticates correctly

* address greptile review feedback (greploop iteration 3)

* address greptile review feedback (greploop iteration 4)

* address greptile review feedback (greploop iteration 5)

* redesign credentials table to use Tremor table layout matching Keys page

* fix: /server/oauth authorize 422 - make client_id optional, fall back to real DB server

* fix: mcp_token client_id optional, resolve from server record

* fix: look up real server by UUID (get_mcp_server_by_id) before falling back to name

* Update litellm/responses/mcp/litellm_proxy_mcp_handler.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: address greptile feedback - client_id guards, dict spread, helper refactor, tests

- mcp_management_endpoints: raise 400 when resolved_client_id is empty in
  mcp_authorize and mcp_token instead of forwarding "" to upstream
- litellm_proxy_mcp_handler: use {**tool, "server_url": ...} spread instead
  of dict(tool) + mutation for shallow copy safety
- rest_endpoints: extract _oauth2_server_ids set comprehension to a named
  _get_oauth2_server_ids() helper for clarity; add Set to typing imports
- test_rest_endpoints: add tests for name→UUID resolution path,
  access-denied when resolved UUID not in allowed list, and OAuth2 user
  token injection for single-server requests; fix fake_get_tools signature
  to accept extra_headers kwarg

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-11 22:07:02 -07:00
michelligabriele 24ad510617 feat(mcp): add AWS SigV4 auth support in UI and fix credential merge on edit (#23282) 2026-03-11 09:43:28 -07:00
Sameer Kankute 43217c8a4b Merge branch 'main' into litellm_oss_staging_03_10_2026 2026-03-11 18:32:17 +05:30
Cesar Garcia 3d2df7e8b5 Revert "feat: add model_cost aliases expansion support" 2026-03-10 22:39:19 -03:00
michelligabriele ffc89e4ef6 fix(mcp): add AWS SigV4 auth for Bedrock AgentCore MCP servers (#22782)
* fix(mcp): add AWS SigV4 auth for Bedrock AgentCore MCP servers

Add aws_sigv4 auth type to MCP client via httpx.Auth subclass that
signs each request with SigV4 using botocore. Enables mcp_servers
config to connect to AgentCore-hosted MCP servers.

* docs(mcp): add AWS SigV4 auth documentation for Bedrock AgentCore

Add dedicated docs page for configuring MCP servers with AWS SigV4
authentication, update MCP overview with aws_sigv4 auth type and
config example, and link from Bedrock AgentCore provider docs.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(mcp): address Greptile review — requires_request_body, full header signing, health check

- Add requires_request_body = True to MCPSigV4Auth so httpx buffers the
  request body before calling auth_flow (prevents empty body hash for
  streaming requests)
- Pass all request headers to AWSRequest for canonical SigV4 signing
  instead of only Content-Type
- Exclude aws_sigv4 from health check skip logic since it has its own
  credential fields (not authentication_token)
- Fix docs: mark aws_access_key_id/aws_secret_access_key as optional
  (falls back to boto3 credential chain)
- Add test for requires_request_body flag

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Krish Dholakia <krrishdholakia@gmail.com>
2026-03-10 11:11:20 -07:00
Ishaan Jaff 9543d785b5 fix(mcp): don't auto-detect M2M OAuth from field presence (#23187)
* fix(mcp): require explicit opt-in for OAuth2 M2M client_credentials flow

Auto-detecting M2M from client_id+secret+token_url presence broke existing
interactive OAuth setups (e.g. GitHub Enterprise). Add oauth2_flow field and
default has_client_credentials to False — M2M must be explicitly opted into
with oauth2_flow: client_credentials.

* test(mcp): add regression tests for oauth2_flow M2M opt-in behavior
2026-03-10 10:59:49 -07:00
Sameer Kankute db99fdeff3 fix(mcp): OpenAPI tool listing and execution for relative URLs and camelCase
- Fix case-insensitive tool name matching in _tool_name_matches() so that
  OpenAPI operationIds (camelCase) match lowercase registered tool names
  when filtering by allowed_tools
- Fix get_base_url() to resolve relative server URLs (e.g. /api/v3) by
  deriving full base URL from spec_path when OpenAPI spec has relative URLs
- Add tests for case-insensitive matching and filter_tools_by_allowed_tools

Made-with: Cursor
2026-03-10 11:34:23 +05:30
Ishaan Jaff bb52b0b6b0 fix(mcp): resolve $ref params and path-level params in OpenAPI spec parsing (#22952)
* fix(mcp): resolve \$ref params and merge path-level params in OpenAPI tool registration

Real-world OpenAPI specs (e.g. GitHub's 11.8 MB official spec) use two
patterns that crashed tool registration:

1. \$ref parameters: params defined as {"$ref": "#/components/parameters/foo"}
   instead of inline objects. Accessing param["name"] on a $ref raises KeyError.
   Fix: resolve each param against components/parameters before processing.

2. Path-level parameters: params defined on the path object apply to all
   HTTP methods on that path, but the operation object doesn't include them.
   GitHub's spec uses this for owner/repo/etc. path params.
   Fix: merge path-level params with operation-level params (op-level wins
   when the same name+in combination appears in both).

With this fix the full GitHub REST API spec loads successfully:
720 paths → 1079 tools, all with correct parameter schemas.

* fix(mcp): resolve \$ref params in OpenAPI preview endpoint (test/tools/list)

The _preview_openapi_tools function (called by the UI add-server form to show
connection status and available tools) had the same bug as _register_openapi_tools:
it accessed param["name"] directly without resolving \$ref parameters or merging
path-level parameters from the path item.

This caused "Failed to load OpenAPI spec: 'name'" for any spec that uses
component-level parameter references (e.g. GitHub's official REST API spec).

Apply the same fix: resolve \$ref against components/parameters and merge
path-level params (with operation-level taking priority) before building schemas.

* refactor(openapi-mcp): extract resolve_operation_params, add tests

- Hoist _resolve_ref and _resolve_param_list to module level in
  openapi_to_mcp_generator.py (were being redefined on every loop iteration)
- _resolve_ref now returns None for unresolvable $refs instead of
  the stub dict, preventing (None, None) from poisoning deduplication
- Add resolve_operation_params() as a shared helper that handles both
  $ref resolution and path-level param merging
- Replace duplicated inline logic in mcp_server_manager.py and
  rest_endpoints.py with calls to resolve_operation_params()
- Add TestResolveRef, TestResolveParamList, TestResolveOperationParams
  test classes covering $ref resolution, path-level merging, collision
  semantics, unresolvable ref filtering, and a GitHub-style spec fixture
2026-03-06 18:02:48 -08:00
Sameer Kankute 159c477c18 feat(proxy): client-side provider API key precedence for Anthropic /v1/messages
- Add forward_llm_provider_auth_headers support from litellm_settings
- When enabled, client x-api-key takes precedence over deployment keys
- Forward x-api-key when x-litellm-api-key or Authorization used for auth
- Fix duplicate patch lines in test_byok_oauth_endpoints.py
- Add Claude Code BYOK documentation with /login and ANTHROPIC_CUSTOM_HEADERS
- Add unit tests for clean_headers x-api-key forwarding logic
- Sync model_prices backup (pre-commit hook)

Made-with: Cursor
2026-03-06 18:20:46 +05:30
Ishaan Jaff 1bb713bc7b feat(mcp): BYOK MCP servers with OAuth 2.1 PKCE authorization flow (#22850)
* feat(mcp): BYOK (Bring Your Own Key) for OpenAPI MCP servers with OAuth 2.1 flow

Adds per-user credential storage for BYOK MCP servers so external clients
can authenticate via standard OAuth 2.1 PKCE without needing a full identity
provider.

Backend:
- New DB table LiteLLM_MCPUserCredentials (user_id, server_id, credential_b64)
- is_byok, byok_description, byok_api_key_help_url fields on MCPServerTable
- OAuth 2.1 authorization server endpoints (/.well-known/oauth-authorization-server,
  /.well-known/oauth-protected-resource, /v1/mcp/oauth/authorize, /v1/mcp/oauth/token)
- 401 challenge with WWW-Authenticate header when BYOK server has no credential
- CRUD endpoints: POST/DELETE /v1/mcp/server/{id}/user-credential
- has_user_credential annotated on GET /v1/mcp/server response

UI:
- ByokCredentialModal: 2-step Connect flow (access description + API key entry)
- BYOK toggle + description fields on admin MCP server create form
- Connect/Connected state in MCP server table
- BYOK Demo page (/tools/byok-demo) showing full OAuth 2.1 PKCE flow

* feat(mcp/byok): redesign OAuth authorize page to match 2-step Connect mockup

- Step 1: L→S logos, requested access checklist, How it works box, Continue button
- Step 2: API key input, Save toggle, Duration pills (1h/24h/7d/30d/until_revoked), security note
- Matches screenshots: white modal on dark bg, progress dots, dark CTA buttons
- Authorize handler now fetches byok_description and byok_api_key_help_url from server registry
- CLAUDE.md: replace SQL snippet with proper DB migration troubleshooting guidance

* fix: address greptile review feedback (greploop iteration 1)

- XSS: escape all user-supplied values in _build_authorize_html() with html.escape()
- Open redirect: validate redirect_uri scheme and URL-encode code/state in redirect
- N+1 query: batch BYOK credential lookup into single find_many() call
- Critical path DB: add 60s TTL in-memory cache to _check_byok_credential()
- Encrypt BYOK credentials at rest using encrypt_value_helper/decrypt_value_helper

* fix(byok): update OAuth popup with LiteLLM logo, MCP title suffix, remove emojis

* fix(byok-demo): fix token endpoint URL (/v1/mcp/oauth/token not /v1/mcp/token)

* feat(byok): inject stored BYOK credential as mcp_auth_header on tool execution

* feat(byok): use contextvars to inject per-user credential into OpenAPI tool closures; remove byok-demo from LiteLLM UI

OpenAPI tools have auth headers baked into their closures at registration time. BYOK servers have
no static auth token, so per-user credentials were never reaching the HTTP calls.

Fix: add _request_auth_header ContextVar in openapi_to_mcp_generator.py. create_tool_function now
reads this var at call time and overrides the Authorization header if set. execute_mcp_tool resolves
the MCP server and performs BYOK checks before the local-tool dispatch branch, then sets the
ContextVar around _handle_local_mcp_tool so the credential flows into the HTTP request.

Also remove the /tools/byok-demo page from the LiteLLM UI dashboard — the demo lives at
~/Downloads/litellm-byok-demo/index.html (served separately on port 8080).

* fix: address greptile review feedback (greploop iteration 2)

- Cache invalidation: add _invalidate_byok_cred_cache() and call it after
  store_user_credential() in both token endpoint and management endpoint
- Unbounded cache: add _BYOK_CRED_CACHE_MAX_SIZE=4096 with clear-on-overflow
- Unbounded auth codes: add _AUTH_CODES_MAX_SIZE=1000 with 503 on overflow
- Double DB query: merge _check_byok_credential + _get_byok_credential into
  single _get_byok_credential call; raise 401 inline if None returned
- Sidebar: remove byok-demo entry (page was deleted in prior commit)
- JWT comment: document why byok_session HS256 token can't be used as proxy auth

* fix: address greptile review feedback (greploop iteration 3)

- auth_type: pre-format Authorization header (Bearer/ApiKey/Basic) in server.py
  before setting ContextVar so openapi_to_mcp_generator respects server auth_type
- cache invalidation on delete: call _invalidate_byok_cred_cache after
  delete_user_credential so stale True entries don't persist for 60s
- ContextVar guard: only set _request_auth_header when mcp_auth_header is set,
  avoiding unnecessary ContextVar overhead on non-BYOK tool calls

* fix: address greptile review feedback (greploop iteration 4)

- Unified credential cache: store actual credential value (Optional[str])
  instead of just bool so _get_byok_credential also benefits from caching —
  eliminates the DB hit on every BYOK tool call within the 60s TTL window
- Extracted _write_byok_cred_cache() helper for consistent cache writes
- Replaced has_user_credential with get_user_credential in _check_byok_credential
  so one DB call satisfies both existence check and value retrieval
- Remove false 'encrypted at rest' claim from OAuth HTML and ByokCredentialModal

* Update tests/test_litellm/proxy/_experimental/mcp_server/test_byok_oauth_endpoints.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update tests/test_litellm/proxy/_experimental/mcp_server/test_byok_oauth_endpoints.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-04 21:19:25 -08:00
Ishaan Jaff 9897df5089 feat(mcp): allow admins to override tool name and description per MCP server (#22828)
* feat(mcp): add tool_name_to_display_name and tool_name_to_description overrides for MCP servers

* docs(mcp): add mcp_openapi.md with OpenAPI→MCP guide and tool override section

* docs(mcp): add sequential UI screenshots to mcp_openapi.md

* fix(mcp): apply tool overrides after permission filtering; reverse-map display names in tools/call
2026-03-04 17:58:05 -08:00
yuneng-jiang 76e3dba0f8 fix mcp server created_at and updated_at timestamps being overwritten with current time
- Add created_at field to MCPServer type (was missing)
- Map created_at from LiteLLM_MCPServerTable in build_mcp_server_from_table()
- Use server.created_at and server.updated_at instead of datetime.now() in _build_mcp_server_table() and health check table builder
- Add regression tests to verify timestamps are preserved through round-trip conversions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 09:41:45 -08:00
Umut Polat 64077553ec fix: include mcp_tool_permissions server ids in allowed mcp servers (#22311)
when a key/team/end-user has mcp_tool_permissions for a server but that
server is not in mcp_servers, the server was excluded from the allowed
list — making the tool permissions useless.

now we union the keys from mcp_tool_permissions into the allowed server
set alongside direct servers and access group servers.

fixes #21954
2026-03-02 19:21:11 +05:30
Julio Quinteros Pro ace49b18d3 fix(tests): update MCP server test mocks to match production API
The tests were mocking `filter_server_ids_by_ip` but the production
code in server.py now calls `filter_server_ids_by_ip_with_info` which
returns a (server_ids, blocked_count) tuple. Update all 8 mock sites
to use the correct method name and return signature.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 13:11:57 -03:00
Krish Dholakia 12c4876891 Agents - assign tools (#22064)
* feat(proxy): add max_iterations limiter for agent session loops (#22058)

Adds a new proxy hook that enforces a per-session cap on the number of
LLM calls an agentic loop can make. Callers send a session_id with each
request, and the hook counts calls per session, returning 429 when the
configured max_iterations limit is exceeded.

- Uses Redis Lua script for atomic increment (multi-instance safe)
- Falls back to in-memory cache when Redis unavailable
- Follows parallel_request_limiter_v3 pattern
- Configurable via key metadata: {"max_iterations": 25}
- Session counters auto-expire via TTL (default 1hr)

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add new code execution dataset

* feat(agent_endpoints/): allow giving agents keys

* fix: ui fixes

* feat: allow assigning mcp servers to agents

* fix: eliminate duplicate DB queries in MCP agent auth and N+1 in agent listing (#22110)

- Extract _get_agent_object_permission helper so _get_allowed_mcp_servers_for_agent
  and _get_agent_tool_permissions_for_server share a single DB fetch instead of
  each independently querying the same agent row (was 1+N queries per MCP request)
- Use include={"object_permission": True} on find_many in get_all_agents_from_db
  to eagerly load permissions in one query instead of N+1
- Use include={"object_permission": True} on create/update/find_unique in all
  agent CRUD operations, removing attach_object_permission_to_dict follow-up calls

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 11:44:30 -08:00
Sameer Kankute c17caf4cc7 Merge pull request #21992 from BerriAI/litellm_fix_oauth_mcp
fix: Missing OAuth session state
2026-02-24 19:37:09 +05:30
Sameer Kankute 12f37cea43 fix: Missing OAuth session state. Please retry 2026-02-24 14:22:38 +05:30
Sameer Kankute 62d5d96e12 Fix: skip health check for MCP integration with passthrough token authentication 2026-02-24 12:05:37 +05:30
Sameer Kankute ba74ee5a31 Add test for base url extraction and migration 2026-02-20 13:47:44 +05:30
Julio Quinteros Pro a9d3c49572 fix(tests): update MCP tests broken by user permissions commit (#21462)
Four tests were broken by commit e00c181f0c (Mcp user permissions #21462):

1. test_list_tools_single_server_unprefixed_names: The commit changed
   _get_tools_from_mcp_servers to always add server prefixes (add_prefix=True),
   removing the conditional that skipped prefixing for single servers.
   Updated assertion from "toolA" → "zapier-toolA".

2. test_mcp_get_prompt_success: mcp_get_prompt now extracts the server name
   from a prefixed prompt name via split_server_prefix_from_name(). Passing
   unprefixed "hello" returns server_name="" which matches no server → 403.
   Updated call to use "server_a-hello" so the server lookup succeeds.

3. test_e2e_jwt_team_mcp_permissions_enforced &
4. test_e2e_jwt_team_mcp_key_intersection:
   The commit replaced `from typing import List` with
   `from litellm.proxy.proxy_server import general_settings` in
   MCPRequestHandler.get_allowed_mcp_servers(). Both tests mock
   litellm.proxy.proxy_server with a types.ModuleType that lacked
   general_settings, causing ImportError. Added general_settings={} to
   both mock modules.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-19 02:09:11 -03:00
Julio Quinteros Pro 2e0a8b3cf8 fix(tests): resolve MCP test isolation failures in parallel execution
Three test isolation issues fixed:

1. test_mcp_debug.py: Replace deprecated asyncio.get_event_loop().run_until_complete()
   with asyncio.run() in TestWrapSendWithDebugHeaders. In Python 3.10+,
   get_event_loop() raises RuntimeError when no event loop is set in the
   current thread, causing test_injects_headers and test_body_messages_unchanged
   to fail in isolation.

2. test_mcp_server_manager.py: After _reload_mcp_manager_module() creates a new
   global_mcp_server_manager instance, server.py still holds a stale reference
   to the old instance. Tests in test_mcp_server.py that populate the new
   manager's registry and then call server.py functions (e.g. _get_tools_from_mcp_servers)
   get empty results because server.py reads from the old manager. Fix: update
   server.py's module-level reference after each reload.

3. test_litellm_pre_call_utils.py: test_add_litellm_metadata_from_request_headers
   sets litellm.callbacks without restoring it afterward. Add cleanup to restore
   original callbacks after the test to prevent state leaking to subsequent tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-18 14:08:48 -03:00
Sameer Kankute 1ced47c612 fix tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py 2026-02-17 20:14:56 +05:30
michelligabriele 035f0916ad fix(mcp): revert StreamableHTTPSessionManager to stateless mode (#21323)
PR #19809 changed stateless=True to stateless=False to enable progress
notifications for MCP tool calls. This caused the mcp library to enforce
mcp-session-id headers on all non-initialize requests, breaking MCP
Inspector, curl, and any client without automatic session management.

Revert to stateless=True to restore compatibility with all MCP clients.
The progress notification code already handles missing sessions gracefully
(defensive checks + try/except), so no other changes are needed.

Fixes #20242
2026-02-16 09:08:44 -08:00
jquinter c3fb5e1ea5 Update tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-16 12:12:48 -03:00
Julio Quinteros Pro cc2dff0581 fix(test): add cleanup fixture and no_parallel mark for MCP tests
Two MCP server tests were failing when run with pytest-xdist parallel
execution (--dist=loadscope):
- test_mcp_routing_with_conflicting_alias_and_group_name
- test_oauth2_headers_passed_to_mcp_client

Both tests showed assertion failures where mocks weren't being called
(0 times instead of expected 1 time).

Root cause: These tests rely on global_mcp_server_manager singleton
state and complex async mocking that doesn't work reliably with
parallel execution. Each worker process can have different state
and patches may not apply correctly.

Solution:
1. Added autouse fixture to clean up global_mcp_server_manager registry
   before and after each test for better isolation
2. Added @pytest.mark.no_parallel to these specific tests to ensure
   they run sequentially, avoiding parallel execution issues

This approach maintains test reliability while allowing other tests
in the file to still benefit from parallelization.

Fixes test failures exposed by PR #21277.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-15 20:42:03 -03:00
Ishaan Jaff a06113ec82 feat: MCP OAuth2 client-side debug headers (#21151)
* fix: SCOPES on Atlassian issue

* feat: add MCPDebug class for client-side MCP OAuth2 debugging

* feat: inject MCP debug headers into streamable HTTP response path

* test: add unit tests for MCPDebug class

* fix: refactor MCPDebug - move all logic into class static methods

* fix: collapse server.py debug code to two-liner using MCPDebug methods

* test: add tests for resolve_auth_resolution and wrap_send_with_debug_headers

* docs: add MCP debug headers section to troubleshooting guide

* docs: add Debugging OAuth section to mcp_oauth.md

* docs: replace inline debug section with cross-link to mcp_oauth

* docs: extract UI troubleshooting into its own page

* docs: simplify troubleshoot.md to issue reporting only

* docs: add quick-start debug command to MCP troubleshoot page

* docs: restructure sidebar - UI, MCP, Performance, Issue Reporting
2026-02-13 12:55:47 -08:00
Ishaan Jaff 40b290aa84 fix: MCP Gateway SCOPES on Atlassian issue (#21150)
* fix: SCOPES on Atlassian issue

* test: add regression tests for scopes=None in OAuth discovery endpoints
2026-02-13 12:43:56 -08:00
Sameer Kankute ef456cafc8 Merge pull request #21040 from BerriAI/litellm_fix_stale_mcp_issue
[Bug] Fix Session not found errors
2026-02-13 21:52:27 +05:30
Ishaan Jaff 9202e67e33 feat: MCP server discovery UI (#21079)
* feat: add curated MCP server registry for discovery UI

Curated list of 31 well-known MCP servers with names, icons,
categories, transport config, and registry URLs. Includes HTTP
endpoints for GitHub, Atlassian, Sentry, Snowflake, and Cloudflare.

* feat: add GET /v1/mcp/discover endpoint for MCP discovery

Admin-only endpoint that serves the curated MCP registry with
optional query and category filters. Used by the UI discovery modal.

* feat: add DiscoverableMCPServer types for MCP discovery

* feat: add fetchDiscoverableMCPServers network function

* feat: add MCP discovery modal component

Compact list-row layout with category filters, search, and
grouped server list. Follows dev-tool aesthetic.

* feat: wire MCP discovery modal into server management page

Add MCP Server button now opens discovery modal. Card click
pre-fills the create form. Custom Server opens blank form.

* feat: add prefill from discovery and back-to-registry link

Create form accepts prefillData from discovery selection and
shows a Browse MCP Registry link to return to discovery modal.

* test: add unit tests for MCP discovery endpoint and registry

Tests for registry JSON structure validation and endpoint
query/category filtering logic. 15 tests total.

* fix: sync registry with official MCP API and fix stdio prefill

- Updated transport types and URLs from registry.modelcontextprotocol.io API
- GitHub: streamable-http at api.githubcopilot.com/mcp/
- GitLab: streamable-http at gitlab.com/api/v4/mcp (remote only)
- Atlassian: SSE at mcp.atlassian.com/v1/sse (remote only)
- Linear: SSE at mcp.linear.app/sse (remote only)
- Notion: SSE at mcp.notion.com/sse (remote only)
- Stripe: streamable-http at mcp.stripe.com (remote only)
- Exa: streamable-http at mcp.exa.ai/mcp (remote only)
- Cloudflare: SSE at bindings.mcp.cloudflare.com/sse (remote only)
- Sentry: stdio via @sentry/mcp-server (npm, correct package)
- Snowflake: stdio via snowflake-labs-mcp (pypi/uvx, not npm)
- Brave Search: stdio via @brave/brave-search-mcp-server (correct package)
- Fixed stdio prefill to generate stdio_config JSON instead of separate fields
- Discovery modal matches create modal width and header style
- Back arrow positioned on left of create modal header

* Update ui/litellm-dashboard/src/components/mcp_tools/mcp_discovery.tsx

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update litellm/proxy/management_endpoints/mcp_management_endpoints.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: address Greptile review feedback

- Move `import json` and `import os` to module top level
- Move mcp_registry.json into litellm/proxy/ for pip distribution
- Fix `Text` component: destructure from antd Typography instead of deprecated Tremor
- Update test fixture path to match new registry location

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-12 17:59:21 -08:00
Ishaan Jaff 5f40f93846 fix: MCP - inject NPM_CONFIG_CACHE into STDIO MCP subprocess env (#21069)
* fix: inject NPM_CONFIG_CACHE into STDIO MCP subprocess env for Docker

npm/npx needs a writable cache directory. In containers the default
(~/.npm) may not exist or be read-only, causing STDIO MCP servers
launched via npx to fail with ENOENT. Inject NPM_CONFIG_CACHE=/tmp/.npm_mcp_cache
into the subprocess env when not already set.

* test: add unit test for NPM_CONFIG_CACHE injection in STDIO MCP

Verifies that NPM_CONFIG_CACHE is auto-injected when not set, and
preserved when explicitly provided. Also moves the import to module
level per code style rules.

* Update litellm/constants.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Apply suggestion from @greptile-apps[bot]

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-02-12 15:11:37 -08:00
Sameer Kankute e8f97bbfca Return 200 response for stale dlete requests from client 2026-02-12 19:21:14 +05:30
Krish Dholakia 5736fd32d9 MCP fixes
* fix(oldteams.tsx): show policies when creating

* fix(proxy/_types.py): ensure mcp rest endpoints can be called by virtual key

ensures UI works with virtual key testing mcp endpoints

* refactor: migrate get object permissions table logic to happen in user api key auth - allows functions to trust user api key object they receive has what they need

* fix(rest_endpoints.py): filter for allowed tools based on what key has access to

* fix(mcp_server_manager.py): ensure only allowed MCP's are returned to the user, via rest endpoints
2026-02-11 18:07:24 -08:00
michelligabriele 81a1cb1318 fix(mcp): merge query params when authorization_url already contains them (#20968) 2026-02-11 08:43:19 -08:00
Alexsander Hamir ebce0e5f8c [Release - 02/10/2026] v1.81.10-nightly 2026-02-10 16:26:30 -08:00
michelligabriele 969710477f fix(mcp): resolve OAuth2 root endpoints returning "MCP server not found" (#20784)
When MCP SDK hits root-level /register, /authorize, /token without
server name prefix, auto-resolve to the single configured OAuth2
server. Also fix WWW-Authenticate header to use correct public URL
behind reverse proxy.
2026-02-09 19:58:37 -08:00
Ishaan Jaff 36e0361187 [UI] M2M OAuth2 UI Flow (#20794)
* add has_client_credentials

* MCPOAuth2TokenCache

* init MCP Oauth2 constants

* MCPOAuth2TokenCache

* resolve_mcp_auth

* test fixes

* docs fix

* address greptile review: min TTL, env-configurable constants, tests, docs

- Fix zero-TTL edge case: floor at MCP_OAUTH2_TOKEN_CACHE_MIN_TTL (10s)
- Make all MCP OAuth2 constants env-configurable via os.getenv()
- Move test file to follow 1:1 mapping convention (test_oauth2_token_cache.py)
- Add MCP OAuth doc page (mcp_oauth.md) with M2M and PKCE sections
- Update FAQ in mcp.md to reflect M2M support
- Add E2E test script and config

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix mypy lint

* fix oauth2

* ui feat fixes

* test M2M

* test fix

* ui feats

* ui fixes

* ui fix client ID

* fix: backend endpoints

* docs fix

* fixes greptile

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:28:02 -08:00
Ishaan Jaff 19024e0602 [Feat] MCP Oauth2 Fixes - Add support for MCP M2M Oauth2 support (#20788)
* add has_client_credentials

* MCPOAuth2TokenCache

* init MCP Oauth2 constants

* MCPOAuth2TokenCache

* resolve_mcp_auth

* test fixes

* docs fix

* address greptile review: min TTL, env-configurable constants, tests, docs

- Fix zero-TTL edge case: floor at MCP_OAUTH2_TOKEN_CACHE_MIN_TTL (10s)
- Make all MCP OAuth2 constants env-configurable via os.getenv()
- Move test file to follow 1:1 mapping convention (test_oauth2_token_cache.py)
- Add MCP OAuth doc page (mcp_oauth.md) with M2M and PKCE sections
- Update FAQ in mcp.md to reflect M2M support
- Add E2E test script and config

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix mypy lint

* fix oauth2

* remove old files

* docs fix

* address greptile comments

* fix: atomic lock creation + validate JSON response shape

- Use dict.setdefault() for atomic per-server lock creation
- Add isinstance(body, dict) check before accessing token response fields

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: replace asserts with proper guards, wrap HTTP errors with context

- Replace `assert` statements with `if/raise ValueError` (asserts can be
  disabled with python -O in production)
- Wrap `httpx.HTTPStatusError` to provide a clear error message with
  server_id and status code
- Add tests for HTTP error and non-dict JSON response error paths
- Remove unused imports

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 17:35:11 -08:00
shin-bot-litellm 1477b4b46b fix(tests): Add missing mocks for MCP IP filtering and updated APIs (#20652)
Fixes 15 failing tests in the MCP test suite:

1. **OAuth discoverable endpoints** (test_discoverable_endpoints.py):
   - Added autouse fixture to mock IPAddressUtils.get_mcp_client_ip
   - This bypasses IP-based access control which was blocking server lookup
   - Fixes: test_authorize_*, test_token_*, test_oauth_*, test_register_*

2. **A2A endpoints** (test_a2a_endpoints.py):
   - Fixed mock path for add_litellm_data_to_request
   - Was patching litellm_pre_call_utils but function is called from common_request_processing

3. **MCP guardrail handler** (test_mcp_guardrail_handler.py):
   - Updated tests to match new handler behavior
   - Handler now passes tools (not texts) to guardrail
   - Handler checks for mcp_tool_name (not messages array)

4. **MCP path-based segregation** (test_user_api_key_auth_mcp.py):
   - Added client_ip to get_auth_context unpacking (7 values now)
   - get_auth_context was updated to include client_ip

5. **MCP registry** (test_mcp_management_endpoints.py):
   - Added mock for get_filtered_registry (not just get_registry)
   - Registry endpoint uses get_filtered_registry for IP filtering

Co-authored-by: Shin <shin@openclaw.ai>
2026-02-07 11:30:49 -08:00
Ishaan Jaffer 1780b1716f filter_server_ids_by_ip 2026-02-07 10:08:20 -08:00
michelligabriele 6a213fc3bc fix(mcp): resolve OAuth2 'Capabilities: none' bug for upstream MCP servers (#20602)
- process_mcp_request() now falls back to OAuth2 passthrough when Authorization header contains a non-LiteLLM token (catches HTTPException and ProxyException 401/403)
- MCPClient._get_auth_headers() adds missing MCPAuth.oauth2 case
2026-02-06 15:00:35 -08:00
Ishaan Jaff 66eadfabe4 [Bug] Ensure MCP permissions are enforced when using JWT Auth (#20383)
* fix: enforce team MCP permissions when using JWT authentication

Root cause: When JWT auth was used with teams in groups (via team_ids_jwt_field),
the team's MCP permissions were not being enforced because:

1. The default team_allowed_routes did not include mcp_routes
2. allowed_routes_check() failed for MCP endpoints like /mcp/tools/list
3. find_team_with_model_access() skipped the team due to failed route check
4. team_id was None in UserAPIKeyAuth
5. MCPRequestHandler._get_allowed_mcp_servers_for_team() returned empty list

Fix: Add 'mcp_routes' to the default team_allowed_routes in LiteLLM_JWTAuth.

This ensures that teams can access MCP endpoints by default, allowing the
team's MCP server permissions to be properly enforced.

Added tests:
- test_reproduce_jwt_mcp_enforcement_issue: Reproduces the exact bug scenario
- test_verify_mcp_routes_in_default_team_allowed_routes: Verifies fix
- test_mcp_route_check_passes_for_team: Verifies route check works

Co-authored-by: ishaan <ishaan@berri.ai>

* test: add comprehensive E2E tests for JWT + team MCP permission enforcement

Added tests:
- test_e2e_jwt_team_mcp_permissions_enforced: Full E2E test verifying JWT auth
  with teams in groups properly sets team_id and MCPRequestHandler returns
  the team's MCP servers
- test_e2e_jwt_without_team_no_mcp_servers: Verifies no MCP servers returned
  when JWT has no teams
- test_e2e_jwt_team_mcp_key_intersection: Verifies intersection logic when
  both key and team have MCP permissions (result = intersection)

These tests verify the complete flow:
1. JWT token with team in groups field
2. JWT auth properly sets team_id on UserAPIKeyAuth
3. MCPRequestHandler.get_allowed_mcp_servers() returns team's MCP servers
4. Key/team permission intersection works correctly

Co-authored-by: ishaan <ishaan@berri.ai>

* test: add simple tests for JWT + MCP permission enforcement

Simple, focused tests that validate:
1. test_simple_jwt_mcp_permissions_enforced: JWT user with team gets team's MCP servers
2. test_simple_jwt_no_team_no_mcp_servers: JWT user without team gets no MCP servers
3. test_simple_jwt_team_id_required_for_mcp_permissions: Verifies team_id is required
4. test_jwt_auth_sets_team_id_for_mcp_route: JWT auth sets team_id for MCP routes

These tests directly verify the core MCP permission enforcement logic works
when using JWT authentication with teams.

Co-authored-by: ishaan <ishaan@berri.ai>

* Add test: MCP route without model still returns team_id

Co-authored-by: ishaan <ishaan@berri.ai>

* Add 2 debug logs for JWT+MCP troubleshooting

- handle_jwt.py: Log team route check result (team_id, route, is_allowed)
- user_api_key_auth_mcp.py: Log team_id when looking up MCP permissions

Co-authored-by: ishaan <ishaan@berri.ai>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: ishaan <ishaan@berri.ai>
2026-02-03 19:13:13 -08:00
Sameer Kankute 9a6bafe89e Fix litellm/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py tests 2026-02-03 15:01:10 +05:30