mirror of
https://github.com/tiennm99/litellm.git
synced 2026-07-12 19:04:59 +00:00
6d6eda8101
* fix(proxy): point /metrics 401 at the opt-out flag Operators upgrading past35bbca60b0(which made /metrics auth default-on) see "Malformed API Key passed in. Ensure Key has 'Bearer ' prefix." with no hint that litellm_settings.require_auth_for_metrics_endpoint: false restores the previous unauthenticated behavior. Append that discovery hint to the existing 401 body so a Prometheus scraper that breaks after upgrade has a clear migration path. No behavior change. * fix(proxy): bound budget reservation per request instead of pinning to remaining headroom reserve_budget_for_request fell back to reserving the entire remaining team/key/user headroom whenever a request omitted max_tokens, which pinned the spend counter at max_budget for the duration of the in-flight request and false-positive-blocked every concurrent or back-to-back request until the success callback reconciled. Surfaced as an integration-test team being budget-blocked at its $2000 cap while DB spend was $0.144. Switch the missing-max_tokens path to a fixed default of 16384 output tokens (mirrors parallel_request_limiter_v3's DEFAULT_MAX_TOKENS_ESTIMATE precedent), and clamp explicit max_tokens at the model's max_output_tokens for reservation accounting only. The outbound request body is unchanged, so providers see whatever the caller actually sent; only the local integer used to compute reservation cost is bounded. This also prevents a hostile max_tokens=999999999 from inflating one request's reservation up to the entire team headroom. For Opus 4.7 (output $25/M, max_output 128K) on a $2000 budget the worst-case per-request reservation drops from "everything left" to $3.20, raising admittable concurrency from 1 to ~625. * fix(proxy): reserve per-image cost for image-generation requests Image-generation routes (dall-e-3, flux, etc.) have no per-token output cost so they fell through to the no-reservation read-time-only path. Concurrent image requests against a depleted budget could all pass common_checks (counter exactly at max_budget passes the strict-`>` gate) and reach the provider before reconciliation caught up. Add per-image reservation in _estimate_request_max_cost_for_model: when the model has a per-image cost field, reserve `n × cost_per_image` upfront. The atomic counter increment serializes concurrent admissions, so the second request sees the post-first-reservation counter and raises BudgetExceededError instead of silently leaking through. Both `output_cost_per_image` and `input_cost_per_image` are honored — naming is inconsistent across providers (OpenAI dall-e-3 uses input_cost_per_image, aiml/dall-e-3 uses output_cost_per_image for the same per-generated-image price). Per-pixel pricing (DALL-E 2 size variants) and TTS/STT routes still fall through to read-time enforcement; those are follow-ups. * fix(proxy): gate image-gen reservation strictly on model mode The previous detection treated any model with input_cost_per_image or output_cost_per_image as image generation. Several chat and embedding models carry those fields to price multimodal vision input, not generated images: - gemini-3.1-pro-preview (mode=chat) has output_cost_per_image=0.00012 alongside input/output token pricing. - azure/gpt-realtime-* (mode=chat) has input_cost_per_image=5e-6. - amazon.titan-embed-image-v1 (mode=embedding) has input_cost_per_image=6e-5. For these models the image-gen branch fired first and reserved a fraction of a cent per request, short-circuiting the token-priced path entirely. Long Gemini chats reserved 1 × $0.00012 instead of the true token cost. Gate strictly on mode in {"image_generation", "image_edit"}. All 197 real image_generation entries and all 31 image_edit entries (Flux Kontext, Stability inpaint/outpaint, etc.) carry the right mode, so the field-presence fallback was unnecessary. Adds regression tests for the chat-model-with-image-cost-field case and for image_edit reservation. * build(packaging): relax core runtime pins to ranges Backport of #27241 onto litellm_1.84.0rc2. The 12 entries in `[project.dependencies]` were exact `==` pins, a side effect of the Poetry -> uv migration. This forces every downstream package that lists litellm as a dependency to downgrade common runtime libraries (openai, pydantic, aiohttp, click, jsonschema, ...) to the exact versions we ship. Switch to lower-bounded ranges with upper bounds where the upstream package is pre-1.0 or has a known breaking-major-version policy. Reproducibility for our Docker proxy and CI continues to come from `uv.lock`, which is regenerated here as a metadata-only diff. Conflict resolution vs upstream merge: - The upstream merge commit also surfaced unrelated context entries (nvidia-riva-client, soundfile/stt-nvidia-riva extra) that exist in staging but not in rc2. Those are not part of #27241's intent and were dropped from the resolution; the rc2 uv.lock keeps its existing entry set, only the 12 specifier strings changed. - `uv lock --check` passes (392 packages resolved, no drift). * build(packaging): raise jinja2 floor to 3.1.6 Our `uv.lock` already resolves jinja2 to 3.1.6, so Docker / CI installs get that version. The `pyproject.toml` floor was lagging at 3.1.0, which means downstream consumers using `--resolution=lowest-direct` or older constraint files can land on 3.1.0-3.1.5 instead of the version we actually test against. Aligns the declared floor with the resolved version so external installers see the same baseline our test matrix exercises. `uv lock` diff is metadata-only (no resolved-version drift). * fix(mcp): forward extra_headers for OpenAPI MCP tools OpenAPI-generated tools only applied static closure headers and BYOK Authorization via ContextVar. Copy MCPServer.extra_headers from the incoming MCP request into _request_extra_headers (set in server.py before local tool dispatch), merge in openapi_to_mcp_generator via a small helper. OAuth2 M2M: do not forward caller Authorization from raw_headers (same rule as _prepare_mcp_server_headers for managed MCP). Adds TestRequestExtraHeaders and clarifies mcp_server_manager registration comment. Fixes #26794 Co-authored-by: Cursor <cursoragent@cursor.com> * refactor(mcp): access has_client_credentials on MCPServer directly Greptile: getattr default was redundant; property exists on MCPServer and mcp_server is non-None inside the extra_headers forwarding block. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(mcp): static headers win over forwarded headers in OpenAPI MCP Match the existing MCP invariant in merge_mcp_headers and the managed MCP path: operator-configured static headers always override caller-forwarded headers on name conflict, with case-insensitive comparison so different casing cannot bypass the precedence. _request_auth_header (BYOK) still overrides Authorization last. Addresses Veria review on PR #27383. Co-authored-by: Mateo Wang <mateo-berri@users.noreply.github.com> * fix(proxy): always merge caller-supplied tags into request metadata Caller-supplied tags (`x-litellm-tags` header, body `tags`, `metadata.tags`) were silently dropped unless the key/team had `metadata.allow_client_tags: true` set. Restore the documented behavior: tags from the request always flow into `metadata.tags` and union with any admin-configured static tags from key/team/project metadata. Removes the `allow_client_tags` opt-in flag from the pre-call pipeline. The flag was only ever read here; it has no schema or endpoint footprint, so leftover values in existing key metadata are inert. Test cleanup mirrors the simplification: drop the three tests that verified the strip-when-not-opted-in path, drop the `allow_client_tags` fixture lines from the merge/union tests. * docs(proxy): refresh stale comments referencing removed tag strip The tag-strip block was removed in the parent commit but two surrounding comments still referenced "tags without opt-in" and "runs AFTER the strip". Update them to describe the remaining user_api_key_* and _pipeline_managed_guardrails strip that the snapshot/merge ordering actually protects against. * chore: reject bare str at file-input sinks to prevent local-file read (#27762) Cherry-pick of #27762 onto litellm_1.84.0rc2. * chore: reject bare str at file-input sinks to prevent local-file read (#27667) * fix: use os.PathLike in ocr sink and check truthy reasoningSummary for bridge - ocr/main.py: widen Path check to os.PathLike for consistency with other sinks - main.py: bridge condition checks truthiness of reasoning_summary, not just None * fix: remove unused pathlib.Path import in ocr/main.py Co-authored-by: yuneng-jiang <yuneng@berri.ai> Co-authored-by: ryan-crabbe-berri <ryan@berri.ai> Co-authored-by: stuxf <70670632+stuxf@users.noreply.github.com> * Strip SERVER_ROOT_PATH before lazy-feature prefix match LazyFeatureMiddleware compared the raw scope path against registered prefixes (e.g. /policies), so requests under a server root path like /api/v1/policies/... never matched, the feature never loaded, and the endpoint returned 404. Strip the configured root path before matching, normalizing trailing slashes and enforcing a component boundary so /api does not falsely match /apiv2. * Cache normalized SERVER_ROOT_PATH at middleware init SERVER_ROOT_PATH is a process-startup env var. Read it once in __init__ instead of calling get_server_root_path() + rstrip on every request that arrives before all lazy features have loaded. * chore(proxy): backport /key/regenerate ownership-rebind + premium-gate guards (#27793) Backport of #27793 onto litellm_1.84.0rc2. A non-admin caller could rebind their own key's user_id via /key/regenerate. _execute_virtual_key_regeneration had org/team guards but no user_id guard, and prepare_key_update_data did not strip the field — it survived model_dump(exclude_unset=True) into the Prisma update. On the next request, _return_user_api_key_auth_obj resolved the rebound user_id against litellm_usertable and returned PROXY_ADMIN whenever the target row's user_role was admin. /key/update had the equivalent guard inline at _validate_update_key_data; extract it to a shared helper _validate_caller_can_change_key_ownership and call from both /key/update and _execute_virtual_key_regeneration. Also tighten the premium gate that allowed the master-key rotation branch to skip the enterprise check. The previous predicate was a field-presence test, not an identity check. Verify the caller actually holds the master key via _is_master_key before allowing the non-premium path. Block explicit-null user_id and empty-string user_id as removal attempts; both 403-reject for non-admin callers. * fix(proxy): expose db status on public /health/readiness Backport of #27866 onto litellm_1.84.0rc2. External readiness probes consumed the legacy detailed payload's `db` field to drive alerting and pod-rotation decisions. Stripping the body to {"status": "healthy"} broke those probes silently — the HTTP code still flipped to 503, but probes checking body.db == "connected" treated the response as healthy. Add `db` back to the unauthenticated payload. The rest of the diagnostic fields (litellm_version, callbacks, cache, log_level) stay behind /health/readiness/details so the recon-leak gate from #26912 holds. Values match the legacy contract: "connected", "disconnected", "Not connected". The 503-on-DB-disconnect behavior from LIT-2607 is preserved. * fix(ui): fetch version + debug flag from /health/readiness/details The proxy moved `litellm_version`, `is_detailed_debug`, and other diagnostic fields off the public `/health/readiness` payload behind an auth-gated `/health/readiness/details` endpoint. The navbar version tag and the detailed-debug-mode banner stopped working because they were still reading those fields from the unauthed response, which no longer contains them. Replace `useHealthReadiness` with a `useHealthReadinessDetails` hook that takes an `accessToken` argument and sends a Bearer header to the auth-gated endpoint. The hook stays disabled while `accessToken` is falsy, so the navbar can keep rendering on the public model hub (where the token is null) without triggering an auth redirect or a 401-loop. * fix(ui): disable retries on readiness/details + cover token forwarding Two small follow-ups on the readiness/details migration: - Set `retry: false` on the query. The payload feeds a passive navbar tag and a debug banner; a 401 from an expired token shouldn't fan out into three retries against the proxy. - Add navbar specs that assert the `accessToken` prop is forwarded into the hook (matches the DebugWarningBanner spec). Without this, the navbar could silently regress to passing `undefined` and the existing tests wouldn't catch it. * chore: update Next.js build artifacts (2026-05-14 03:52 UTC, node v20.20.2) * Merge pull request #27898 from stuxf/chore/banned-params-extra-body-cover chore(proxy): cover extra_body + azure_ad_token in banned-params check (cherry picked from commita6a9d8edf0) * Merge pull request #27801 from stuxf/chore/get-instance-fn-runtime-s3-gate chore(proxy): refuse remote-URL instance-fn loads outside config-file path (cherry picked from commite3e5209f51) * fix: block client-side pricing injection via request body Authenticated clients could supply CustomPricingLiteLLMParams fields (input_cost_per_token, output_cost_per_token, etc.) in the request body. These were forwarded to register_model() in main.py, permanently mutating the shared global litellm.model_cost dict for all users on the instance. Adds all CustomPricingLiteLLMParams fields to _BANNED_REQUEST_BODY_PARAMS so is_request_body_safe() rejects them before they reach completion(). New pricing fields added to CustomPricingLiteLLMParams are auto-covered. Admin opt-in via allow_client_side_credentials or configurable_clientside_auth_params still works as before. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: block SSRF fields in RAG ingest vector_store config aws_sts_endpoint, aws_web_identity_token, and aws_bedrock_runtime_endpoint in ingest_options.vector_store were passed directly to the Bedrock ingestion class, which reads them into boto3 STS client construction. Any authenticated caller could redirect AssumeRole calls to an attacker-controlled server, leaking the proxy's instance profile credentials. Calls is_request_body_safe() on ingest_options["vector_store"] before forwarding to litellm.aingest(). Same banned-params list and admin opt-in escape hatch (allow_client_side_credentials) as the /chat/completions path. ValueError from the safety check is caught and re-raised as HTTP 400. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: harden /key/update authorization checks (#27878) * fix: patch Host-header auth bypass in get_request_route Starlette reconstructs request.url from the Host header. A malformed Host like `localhost/?x=1` causes Starlette to build the full URL as `http://localhost/?x=1/health`, which url-parses to path="/". Since "/" is in LiteLLMRoutes.public_routes, all protected routes became reachable without authentication. Fix: read scope["path"] (set by uvicorn from the HTTP request line, not derivable from headers) instead of request.url.path. Sub-path deployments are handled via scope["app_root_path"] / scope["root_path"], mirroring Starlette's own base_url construction logic. Affected variants confirmed fixed: Host: localhost/?x=1 Host: localhost:4000/?x=1 Host: localhost/#test Host: localhost:4000/#test Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * style: reduce comments in route fix Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: block credential fields in RAG ingest vector_store options Credential fields (vertex_credentials, aws_access_key_id, api_key, etc.) in ingest_options.vector_store are now rejected at the API boundary with a 400 error. Credentials must be configured server-side. Previously any authenticated user could supply a vertex_credentials dict with type=external_account pointing credential_source.file at an arbitrary path (e.g. /proc/1/environ) and token_url at an attacker-controlled server. google-auth's identity_pool.Credentials refresh() would read the file and POST its contents to the attacker. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: block /key/update self-escalation by assigned users Non-admin users who were assigned a key (created_by != caller) could update any non-budget field — models, rpm_limit, guardrails, etc. — without admin authorization, allowing privilege self-escalation. Gate: only the key creator (created_by == caller) may edit their own key without admin check; budget changes always require admin regardless of creator status. All other callers must pass _check_key_admin_access. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: block user-controlled api_base in RAG ingest vector_store options A user-supplied api_base in ingest_options.vector_store caused the server to forward its configured provider credentials (Gemini, OpenAI) to an attacker-controlled endpoint via SSRF. Add api_base to the blocked credential params set alongside api_key and the existing credential fields. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: restrict /utils/transform_request to PROXY_ADMIN and apply body safety check Any authenticated internal_user could POST arbitrary provider config (aws_sts_endpoint, api_base, etc.) to /utils/transform_request and have the server forward its credentials to an attacker-controlled endpoint. - Gate the endpoint on PROXY_ADMIN role (403 for all other roles) - Call is_request_body_safe() to reject banned params even for admins - Convert ValueError from safety check to HTTP 400 Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: apply banned-param check to /utils/transform_request Without is_request_body_safe(), any authenticated user could pass aws_sts_endpoint, api_base, or aws_web_identity_token to /utils/transform_request and have the server forward its configured provider credentials to an attacker-controlled endpoint during SDK credential resolution. Applies the same banned-param blocklist already used by LLM endpoints. Endpoint remains accessible to all authenticated users. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: block SSRF via api_base in /prompts/test dotprompt YAML frontmatter Any frontmatter key not in ["model","input","output"] flowed into optional_params and was merged into the LLM call data dict, bypassing is_request_body_safe. An attacker with any bearer key could set api_base in YAML to redirect the outbound LLM request — including the provider API key — to an attacker-controlled host. Fix: call is_request_body_safe on the constructed data dict after optional_params are merged, before invoking ProxyBaseLLMRequestProcessing. ValueError from the banned-param check is surfaced as HTTP 400. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * Update litellm/proxy/rag_endpoints/endpoints.py Co-authored-by: veria-ai[bot] <224490171+veria-ai[bot]@users.noreply.github.com> * fix: coerce nested config strings before banned-param check _NESTED_CONFIG_KEYS descent used isinstance(nested, dict) which silently skipped litellm_embedding_config when delivered as a JSON string via multipart/form-data. Banned params (api_base, aws_sts_endpoint, etc.) nested inside the stringified value were invisible to is_request_body_safe. _NESTED_METADATA_KEYS already used _coerce_metadata_to_dict which parses JSON strings before checking. Apply the same coercion to _NESTED_CONFIG_KEYS. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: replace substring match with prefix match in is_llm_api_route mapped_pass_through_routes used `_llm_passthrough_route in route` (substring) so any admin-only path whose URL contained a provider name (openai, anthropic, azure, bedrock, etc.) was misclassified as an LLM API route and bypassed the admin gate in non_proxy_admin_allowed_routes_check. Confirmed live: non-admin key could GET /credentials/by_name/openai (read masked provider API key) and DELETE /credentials/openai (delete credential). Fix: use exact match or startswith(prefix + "/") — the same pattern used everywhere else in RouteChecks — so only routes that actually start with a passthrough prefix are allowed through. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: stabilize PR #27878 test failures - key_management_endpoints: extend can_skip_admin_check to team keys so team members with /key/update permission can update non-budget fields. can_team_member_execute_key_management_endpoint already validates team membership + permission and raises if unauthorized; reaching the admin check on a team key means the caller was authorized. - test: set created_by on mock key in test_update_key_non_budget_fields_allowed_for_internal_user so caller_is_creator resolves correctly (MagicMock default ≠ user_id). - auth_utils.get_request_route: guard against non-dict request.scope (e.g. MagicMock in unit tests) to prevent a MagicMock leaking into UserAPIKeyAuth.request_route and failing Pydantic validation. - ci: assign test_multipart_bypass_repro.py to the proxy-runtime shard in test-unit-proxy-db.yml to satisfy the shard-coverage check. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix(lint): add explicit str() cast in get_request_route for MyPy scope.get() returns Any|None which MyPy cannot coerce to str implicitly. Wrap both scope.get() calls in str() to satisfy the type checker. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: guard bare-/ root_path strip + make total_spend migration idempotent auth_utils.get_request_route: when Starlette sets scope["app_root_path"] to "/" (e.g. behind some middleware), the old stripping logic would remove the leading slash from every path ("/team/new" → "team/new"), breaking route matching and causing auth to misclassify protected routes. Skip stripping when root_path is bare "/". migration: add IF NOT EXISTS to total_spend ALTER TABLE so the migration is safe to replay when a prior partial run already created the column. Without this guard, prisma migrate deploy fails on CI DBs that were partially migrated, causing all subsequent DB operations (including /team/new) to 500. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: require creator still owns key for personal-key bypass in /key/update caller_is_creator now requires both created_by == caller AND user_id == caller. Previously checking only created_by let a demoted admin who originally created a key for another user continue editing non-budget fields on it after reassignment, bypassing _check_key_admin_access. Adds regression test: creator whose key was reassigned is blocked (403). Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> * fix: extract auth checks to fix PLR0915 + broaden max_budget assertion internal_user_endpoints._update_single_user_helper exceeded 50 statements (PLR0915). Extract authorization checks into _check_user_update_authz helper to bring statement count under the limit. test_validate_max_budget: assert "negative" (substring of both the local "cannot be negative" and the CI "non-negative finite number" messages) so the test is stable regardless of which exact wording the function uses. Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: veria-ai[bot] <224490171+veria-ai[bot]@users.noreply.github.com> * bump: version 0.4.71 → 0.4.72 * uv lock * feat(mcp): support OAuth passthrough discovery * fix(mcp): support OAuth browser auth * fix(mcp): refine upstream OAuth metadata fallback * feat(proxy): support issuer-scoped JWT auth * fix(mcp): validate oauth callback redirect sink * feat(proxy): support issuer-scoped JWT auth * test(mcp): align trusted proxy fixtures * style(mcp): satisfy black formatting * chore(ui): bump next to 16.2.6 * fix(mcp): address oauth passthrough review findings * test(mcp): split oauth passthrough regressions * fix(interactions): align openapi response fields * security: prevent forwarding litellm api keys to upstream mcp servers - Strip Authorization header from extra_headers for pass-through servers - Pass-through servers (auth_type=None with extra_headers: [Authorization]) must not receive the user's LiteLLM API key - Only OAuth2 M2M and pass-through servers skip Authorization header - Other headers (x-request-id, x-trace-id) are still forwarded normally - Fixes credential leakage / authentication bypass in MCP pass-through mode * fix(interactions): remove steps field not in google openapi spec The steps field was added but is not present in the current Google Interactions OpenAPI specification. Revert to using only the fields that are actually defined in the spec. * fix(mcp): forward Authorization in pass-through when x-litellm-api-key is admission Commit 3753970cc9 widened the Authorization strip to cover all is_oauth_passthrough servers — protecting against the LiteLLM admission key leaking upstream when the caller used Authorization for admission, but also silently stripping legitimate upstream OAuth bearers when the caller used x-litellm-api-key for admission. That broke transparent OAuth pass-through (EAI-506 V5/V6): standards- compliant MCP clients (OpenCode, Claude Code, mcp-inspector) complete PKCE against the upstream IdP and send the resulting token as plain Authorization: Bearer per the MCP spec — with the wider strip in place, that token never reaches the upstream and tools/list returns empty. Narrow the strip: skip Authorization for pass-through servers only when the caller did NOT supply x-litellm-api-key. When x-litellm-api-key is present, admission is unambiguous and Authorization is free to carry the upstream OAuth bearer. The original security guarantee is preserved — a client that sends only Authorization (no x-litellm-api-key) still has it stripped, so the LiteLLM key cannot leak upstream via that path. Tests: - new: forwards Authorization when x-litellm-api-key is present - new: still strips Authorization when only Authorization is present - existing pass-through + M2M tests unchanged Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(interactions): align status enum with openapi spec * fix(mcp,jwt): address greptile review concerns - Cache _get_agent_object_permission via user_api_key_cache (sentinel for no-permission rows) so MCP requests from agent keys don't hit the DB on every tool-list / tool-call. - Re-raise HTTPException in handle_sse_mcp so 401 + WWW-Authenticate challenges (and other HTTP errors) propagate to SSE clients instead of being swallowed as 500. - Normalise booleans in _validate_token_response so admin rules written as JSON-style "true" / "false" match upstream responses that return Python True / False. - Treat configured JWT issuer claim mappings as advisory: when a mapped field is absent or empty, leave the normalised claim unset instead of raising, matching the global litellm_jwtauth path. Co-authored-by: Claude <noreply@anthropic.com> * test: replace dall-e-3 with gpt-image-1 in health check and router tests (#27813) OpenAI returns 'The model dall-e-3 does not exist' for the test account, breaking test_openai_img_gen_health_check and test_image_generation. Switch to gpt-image-1, matching the existing TestOpenAIGPTImage1 pattern. (cherry picked from commitaee58db880) * fix(tests): drop dall-e-only test classes; route live image tests via gpt-image-1 Second wave of failures from the 2026-05-12 DALL-E shutdown: - tests/image_gen_tests/test_image_edits.py::TestOpenAIImageEditDallE2 and tests/image_gen_tests/test_image_generation.py::TestOpenAIDalle3 are explicitly named for the deprecated models and can't pass; remove. gpt-image-1 coverage already exists in sibling classes. - tests/local_testing/test_router.py image gen tests use dall-e-3 only as a routing example; swap to gpt-image-1. - tests/local_testing/test_custom_callback_input.py image_generation success/failure paths swapped to gpt-image-1. (cherry picked from commit945b10ded4) * test(fireworks): replace deprecated llama-v3p3-70b-instruct model Fireworks removed llama-v3p3-70b-instruct from serverless, so every live test using it now fails with NotFoundError ("Model not found, inaccessible, and/or not deployed"). Swap the 6 references (3 files) to the currently-served accounts/fireworks/models/deepseek-v3p1 — the canonical model in Fireworks' current docs examples and present in LiteLLM's cost map. test_get_model_params_fireworks_ai is a pure pricing-heuristic test (no network) asserting the >16b branch, so it uses llama-v3p1-70b- instruct instead to keep the "fireworks-ai-above-16b" assertion and branch coverage intact. (cherry picked from commit39a1d438f2) * test(fireworks): mock remaining live smoke tests test_completion_fireworks_ai and test_completion_cost_fireworks_ai made real Fireworks calls and broke whenever Fireworks rotated its serverless catalog (no externally-verifiable model list exists). They also asserted nothing — just printed. Mock the HTTP post and assert real behavior instead: the request is built with the right model/messages and the OpenAI-compatible response parses back; the cost path yields a non-zero cost against the local cost map. No network, no model dependency, stronger than the old smoke checks. (cherry picked from commitb5db7ed37d) * fix(tests): replace shut-down gpt-4o-audio-preview with gpt-audio-1.5 (#28281) * fix(tests): replace shut-down gpt-4o-audio-preview with gpt-audio-1.5 OpenAI shut down gpt-4o-audio-preview on 2026-05-07, so the live audio calls in test_stream_chunk_builder_openai_audio_output_usage and test_standard_logging_payload_audio now hard-fail with a model-not-found error on every PR. The error was not "openai-internal", so the except block swallowed it and execution fell through to an unbound completion/response (UnboundLocalError). Switch both tests to gpt-audio-1.5, OpenAI's recommended successor (GA, not deprecated, already present in the litellm cost map so the response_cost assertion still resolves). Also broaden the except to skip with the real error in the reason instead of crashing, so a transient upstream blip can't reintroduce the UnboundLocalError. * fix(tests): narrow audio-test skip to model-not-found, re-raise the rest Address review feedback: an unconditional skip on any exception would silently mask a litellm-internal regression in the audio path (broken param transformation, serialization, bad header) instead of failing CI. Skip only on the upstream-unavailable class (model_not_found / "does not exist" / openai-internal) and re-raise everything else, so genuine regressions still fail loudly. The UnboundLocalError is still fixed because the handler either skips or raises - it never falls through. * fix(tests): add budget_exceeded to expected Interaction status enum Staging added budget_exceeded to the Interaction OpenAPI status enum; the staging merge into this branch picked up the spec change but not the matching test update, so test_status_enum_values failed in CI. Align the test's expected list (exact-match by design) with the live spec. * fix(tests): mock HTTP fetch in test_img_url_token_counter The test parameterized a live third-party image URL (blog.purpureus.net) which now 404s, causing get_image_dimensions to fall through to its base64 decode path and crash with 'not enough values to unpack' on every PR run. Mock safe_get with a tiny 1x1 PNG so the URL branch is still exercised without any network dependency. * fix(tests): swap gpt-4o-audio-preview to gpt-audio-1.5 in test_gpt4o_audio OpenAI shut down gpt-4o-audio-preview on 2026-05-07, so both live tests in test_gpt4o_audio.py (test_audio_output_from_model and test_audio_input_to_model) hard-fail model_not_found on every PR. Swap the hardcoded model to OpenAI's successor gpt-audio-1.5 (same chat-completions audio surface; already in the litellm cost map). Mirror the narrowed-skip pattern from the prior audio fixes: skip on model_not_found / does-not-exist / openai-internal, re-raise everything else so genuine litellm regressions still fail CI loudly. (cherry picked from commit92de7423ef) * fix(tests): migrate realtime + rerank tests off shut-down upstream models (#28191) * fix(tests): use gpt-realtime in realtime guardrails test OpenAI shut down gpt-4o-realtime-preview-2024-12-17 on 2026-05-07, so the live OpenAI realtime guardrails integration test now fails with model_not_found (session.created never arrives, _wait_for_event times out). Point OPENAI_REALTIME_URL at the current GA model, gpt-realtime. Scope limited to this test: the pricing-catalog JSON keeps the retired entries intentionally (historical cost calc + separate Azure timeline), and the Azure realtime cost-calc test is unaffected. * fix(tests): mock nvidia_nim rerank instead of hitting EOL'd endpoint NVIDIA reached end-of-life for the hosted nvidia/llama-3.2-nv-rerankqa-1b-v2 rerank API on 2026-05-18 with no published replacement, so the live BaseLLMRerankTest.test_basic_rerank for nvidia_nim now returns HTTP 410 ("Gone"). NVIDIA's hosted catalog rotates on a schedule, so swapping in another live model would only defer the failure. Override test_basic_rerank in TestNvidiaNim to mock the sync/async HTTP transport (same pattern as test_nvidia_nim_rerank_ranking_endpoint in this file) and inject a fake NVIDIA_NIM_API_KEY via monkeypatch. The request/response transformation and cost calculation stay covered offline. Scope limited to nvidia_nim; other BaseLLMRerankTest providers untouched. * fix(tests): migrate remaining realtime tests off shut-down gpt-4o-realtime-preview OpenAI's 2026-05-07 shutdown removed the entire gpt-4o-realtime-preview family, including the undated 'gpt-4o-realtime-preview' alias (not just the dated snapshot fixed earlier). Three live tests still connected with the dead alias and failed with messages_received=1 (an error event instead of session.created): - test_openai_realtime_simple.py: get_model() -> gpt-realtime (drives TestOpenAIRealtime.test_realtime_connection / test_realtime_with_query_params) - test_openai_realtime.py: test_openai_realtime_direct_call_no_intent and test_openai_realtime_direct_call_with_intent -> openai/gpt-realtime (the with_intent test shares the same dead alias even though it was not in the failing set this run) Mocked unit tests (test_realtime_query_params_construction, test_realtime_query_params_use_normalized_model_name) are left as-is: they never hit the network and assert string plumbing only. Also fixes test_text_message_blocked_by_guardrail_no_ai_response, which now connects (the earlier URL swap worked) but tripped a model-wording-brittle assertion. The guardrail flow asks the model to voice the block message verbatim; gpt-4o-realtime-preview complied (output contained 'blocked'), gpt-realtime refuses verbatim-repeat instructions ('I'm sorry, but I can't repeat that message.'). Since the original user message is blocked before it reaches OpenAI, the refusal is still a safe outcome. Assertion #3 now accepts both voicing and refusal, and adds a hard check that the blocked phrase never leaks into AI output. (cherry picked from commitce87c411bf) * fix(model_prices): register mistral/ministral-8b-2512 Mistral's API now returns model='ministral-8b-2512' when 'mistral-tiny' is requested, so test_completion_mistral_api fails with 'This model isn't mapped yet'. Adding the entry so completion_cost can resolve the cost for that response. Author: Claude <noreply@anthropic.com> * fix(mcp,auth): address greptile review concerns - handle_sse_mcp now calls _raise_preemptive_401_for_unauthenticated_servers so SSE clients to pass-through OAuth MCP servers receive the RFC 9728 401 + WWW-Authenticate challenge that the streamable-HTTP path already emits. - get_request_route strips a trailing slash from root_path before length-based prefix removal so non-canonical ASGI root_path values like "/litellm/" don't strip the leading slash from the returned route. - _mcp_oauth_user_api_key_auth's cookie JWT decode now passes options={"verify_aud": False} so a future revision of the UI session JWT containing an aud claim cannot silently downgrade the request to unauthenticated. Co-authored-by: Claude <claude@anthropic.com> * fix(tests): backfill local model_cost into remote-fetched map litellm.model_cost is loaded at import time from LITELLM_MODEL_COST_MAP_URL (pinned to main), so pricing entries that exist only in this branch (e.g. mistral/ministral-8b-2512, freshly added because Mistral's API now returns this id from mistral-tiny) are absent at test time and completion_cost lookups raise 'This model isn't mapped yet'. Backfill the in-tree backup into litellm.model_cost in the local_testing conftest so cassette-driven cost calculations resolve against the entries that ship with the branch under test. Fixes local_testing_part1 failures on test_completion_mistral_api and test_completion_mistral_api_modified_input. * fix(mcp,jwt): address greptile concurrency and code-quality concerns - _apply_issuer_claim_mappings now builds a new dict and reads from the original token, rather than mutating its input. The change is behaviour-preserving (caller passes a fresh jwt.decode result), but avoids the surprise-mutation pattern flagged by greptile. - is_network_error uses isinstance(exc, httpx.TransportError) instead of matching type(exc).__name__ against a hand-maintained string set, so ReadError / WriteError / ProxyError / etc. are also treated as transport-level failures and surfaced as HTTP 502. - fetch_upstream_oauth_protected_resource now coalesces concurrent discovery requests per (server_id, resource_url) through an asyncio.Lock so concurrent .well-known calls share a single upstream fetch + cache write. - Drop the redundant 'if trusted_ranges:' branch in get_mcp_client_ip; it is always true on the path that reaches it (the prior 'if not trusted_ranges:' early-returns). Co-authored-by: Claude <claude@anthropic.com> * fix(jwt,mcp): fall back to global JWKS on unknown issuer; prune fetch locks - handle_jwt._get_configured_issuer now returns None for tokens whose 'iss' is not in the configured issuers list, letting auth_jwt fall through to the legacy JWT_PUBLIC_KEY_URL path instead of hard-raising. This keeps existing tokens from non-configured IdPs working when an operator adds the new 'issuers' list to a live deployment. - discoverable_endpoints._prune_oauth_metadata_cache now also prunes entries in _OAUTH_METADATA_FETCH_LOCKS whose cache entry has been evicted and whose lock isn't currently held, bounding the locks dict to match the cache it guards. Co-authored-by: Claude <claude@anthropic.com> * fix(mcp,auth): restore client_ip in oauth2 target check, drop from delegate check The merge of staging into the PR branch (d42a66adb6) misplaced the client_ip=client_ip kwarg: it landed inside _target_servers_delegate_auth_to_upstream (which never accepted client_ip and isn't called with it), while the sibling _target_servers_use_oauth2 has client_ip in its signature but stopped passing it through to get_mcp_server_by_name. That left ruff flagging F821 on the undefined name and lint failing. Move client_ip back into _target_servers_use_oauth2's lookup (matching the call site that already forwards IPAddressUtils.get_mcp_client_ip) and drop it from _target_servers_delegate_auth_to_upstream so its body matches its signature again. * fix(mcp): respect client ip for delegated auth * fix(auth): address remaining greptile style findings - get_request_route: require root_path to match whole path segments before stripping, so '/apifoo' isn't truncated to 'foo' when root_path='/api'. - get_mcp_client_ip: collapse the two trusted-proxy validation branches into a single is_request_from_trusted_proxy call so the return value drives control flow instead of being discarded for the side-effect warning. Co-authored-by: Claude <claude@anthropic.com> * fix(jwt): strip internal _litellm_* claims in global JWKS auth path Prevents identity spoofing where a token signed by the global JWKS could inject _litellm_jwt_issuer and other _litellm_* claims that downstream getters trust. The issuer-scoped path already strips these via _apply_issuer_claim_mappings; mirror that behavior for the global fallback path. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): surface MCPUpstreamAuthError as 401 in SSE/HTTP transport handlers Both handle_sse_mcp and handle_streamable_http_mcp only caught HTTPException to preserve 401 + WWW-Authenticate challenges, but MCPUpstreamAuthError (raised when a pass-through server's upstream rejects a bearer token mid-session) inherits from Exception. It was falling through to the generic handler and surfacing as an opaque 500. Mirror the REST endpoint behavior: translate MCPUpstreamAuthError into an HTTPException(status_code=e.status_code) with the upstream www-authenticate header so standards-compliant MCP clients trigger the upstream OAuth flow. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): add upstream auth pre-flight in SSE handler Mirror handle_streamable_http_mcp by calling _check_passthrough_upstream_auth after the cold-start 401 emitter so expired/invalid upstream tokens surface a proper 401 + WWW-Authenticate challenge before the SSE session commits 200 headers, instead of letting list_tools silently return [] when the upstream rejects the token. Co-authored-by: Claude <noreply@anthropic.com> * fix(mcp): tighten cold-start bypass against CSV paths + dedupe upstream auth probe - Return None from _parse_mcp_server_names_from_path for CSV multi-server paths (/mcp/a,b). The regex previously truncated at the first comma and silently passed a single server name to the cold-start gate. - Switch _is_mcp_passthrough_cold_start to all-targets semantics, matching _target_servers_use_oauth2: one non-passthrough target in a co-targeted set must not flip the anonymous-admission bypass open for the others. - Drop the redundant HTTPStatusError block in _extract_upstream_auth_failure - any HTTPStatusError carries a .response, so the preceding generic block already handles 401/403 detection. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp,tests): sync stubs and cold-start assertions with delegate-check The merge of base-branch _target_servers_delegate_auth_to_upstream into process_mcp_request inserts an additional get_mcp_server_by_name(name) lookup ahead of the cold-start path, which breaks two test patterns: 1. lookup_by_name(name) side-effect stubs in TestMCPDelegateAuthToUpstream are called positionally by the delegate check, then again by the cold-start path with client_ip=... — raising TypeError: unexpected keyword argument 'client_ip'. Accept **_kwargs to match the real signature. 2. TestMCPPassthroughColdStartAdmission assertions count the lookup exactly once with client_ip=..., but the delegate check now adds a positional-only call ahead of it. Switch assert_called_once_with to assert_any_call for the cold-start invocation, and assert client_ip was *not* passed for the aggregate /mcp test where cold-start must not fire. Both updates align with CLAUDE.md guidance to keep monkeypatch stubs in sync with the real signature when an optional parameter is added. Co-authored-by: Claude <claude@anthropic.com> * fix(mcp): correct passthrough probe 401 + slashed-name cold start parser - _check_passthrough_upstream_auth now emits 'Bearer resource_metadata="..."' pointing at the gateway's oauth-protected-resource well-known URL, mirroring the pre-emptive 401 path. Pass-through servers don't use the gateway as an authorization server, so the previous 'authorization_uri=' challenge sent clients to the wrong metadata endpoint. - _parse_mcp_server_names_from_path now accepts server names that contain a single slash (e.g. custom_solutions/user_123), mirroring MCPRequestHandler._extract_target_server_names_from_path. Without this, the cold-start bypass missed slashed-name servers and the generic admission error propagated instead of the spec-compliant 401 challenge. - _is_mcp_passthrough_cold_start drops the unused scope parameter from its signature. Co-authored-by: Yassin Kortam <yassin@berri.ai> * style(mcp): format discoverable endpoints * refactor(mcp): dedupe MCPUpstreamAuthError->HTTPException + thread client_ip into delegate-auth gate Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): handle passthrough OAuth metadata and startup auth errors - discoverable_endpoints: For pass-through MCP servers, when upstream oauth-protected-resource returns a non-200/non-dict response, raise HTTP 502 instead of falling through to default gateway metadata. Falling through would direct MCP clients at the gateway, which is not the authorization server for pass-through configs. - mcp_server_manager: Wrap _get_tools_from_server in startup tool name mapping with try/except. Since _get_tools_from_server now re-raises MCPUpstreamAuthError, an upstream 401 from a pass-through server at startup (when no user token is present) would otherwise abort the loop and leave subsequent servers unmapped. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): restrict passthrough probe challenge to OAuth passthrough servers The probe filter previously matched any server with Authorization in extra_headers, including gateway-managed OAuth2 servers. Those would then receive the resource_metadata= WWW-Authenticate challenge meant for pass-through servers, instead of the authorization_uri= challenge pointing at the gateway AS metadata. Use srv.is_oauth_passthrough so only genuine pass-through servers get the resource-metadata challenge. Co-authored-by: Yassin Kortam <yassin@berri.ai> * test(proxy): cover issuer-scoped JWT auth * fix(mcp): use resource metadata for passthrough reauth * fix(mcp,tests): assert cold-start helper directly for aggregate /mcp Threading client_ip into _target_servers_delegate_auth_to_upstream made get_mcp_server_by_name(name, client_ip=...) also fire from the delegate-auth check, so the call_args_list assertion on client_ip-in-kwargs no longer uniquely signals a cold-start lookup. Patch _is_mcp_passthrough_cold_start and assert it is not invoked, which is the actual contract the test is pinning. * fix(mcp,jwt): drop unneeded async helper + suppress misleading unscoped JWT warning - _build_oauth_authorization_server_response: revert to sync (no awaits in body). The function only does dict construction and synchronous registry lookups; async added coroutine creation overhead per discovery call without need. - _build_decode_kwargs: accept has_issuer_config so the global path's 'JWT auth is unscoped' warning is suppressed when LiteLLM_JWTAuth.issuers provides per-issuer scoping. Previously the warning fired spuriously for admins who intentionally use only the new issuers config. * fix(jwt,mcp): clarify issuers fallthrough + add TTL on mcp permission cache - LiteLLM_JWTAuth.issuers docs now state explicitly that unlisted issuers fall back to the global JWT_AUDIENCE/JWT_ISSUER path; the field is additive routing, not an allow-list. Matches actual control flow in handle_jwt.auth_jwt and the regression tests asserting backwards compatibility with the global JWKS path. - MCPRequestHandler._get_{org,agent}_object_permission now pass ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL on async_set_cache, mirroring the auth_checks.py pattern so the cache TTL is explicit on both DualCache layers. * fix(tests): align merged JWT and MCP cold-start assertions Update the tests carried over from PR #28008 to match the assertions on the staging branch: - tests/test_litellm/proxy/auth/test_handle_jwt.py: unknown issuers now fall back to the legacy JWT_PUBLIC_KEY_URL path (per litellm_feat/v1.84.0-mcp-gateway-jwt-auth's '\''fall back to global JWKS on unknown issuer'\''), and mapped issuer claims that are absent no longer fail closed — they simply leave the normalised LiteLLM internal claim absent. - tests/test_litellm/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py: the aggregate '\''/mcp'\'' route still triggers the delegate-auth-to-upstream lookup once for the header-supplied server name; cold-start admission must NOT fire on top of that. Tighten the assertion to assert_called_once_with so a future regression that re-enters cold-start is caught. Co-authored-by: Mateo Wang <mateo-berri@users.noreply.github.com> * fix(jwt): guard litellm_jwtauth access in auth_jwt global path JWTHandler() can be constructed without update_environment() being called (tests do this directly), in which case self.litellm_jwtauth does not exist. Accessing it raises AttributeError before getattr can fall back. Use the same safe pattern other call sites use. * Gate MCP OAuth pass-through on delegate_auth_to_upstream flag Sameer's review on #28356/#28008 flagged that the new pass-through behaviors (preemptive 401 challenges, /.well-known/oauth-protected- resource proxying, upstream 401/403 propagation as MCPUpstreamAuthError, and Authorization-stripping when no x-litellm-api-key is supplied) were implicitly enabled for every server with auth_type=none plus Authorization in extra_headers. Existing users doing static bearer pass-through for non-OAuth reasons would have silently regressed. Make the detection rule explicit: extend the existing delegate_auth_to_upstream flag (previously oauth2-only) to also gate is_oauth_passthrough. Now requires flag + auth_type=None + Authorization in extra_headers, per Sameer's suggested detection rule. The UI toggle now appears for both modes (oauth2 PKCE passthrough and auth_type=none OAuth pass-through) with mode-appropriate copy. Update test fixtures to set the flag where the test intent is to exercise OAuth pass-through behavior, and add negative tests covering the new default-false case. * fix(mcp): route org object_permission lookup through shared auth helpers Replace the bespoke litellm_organizationtable.find_unique + dedicated cache key in _get_org_object_permission with get_org_object + get_object_permission so MCP requests share the same user_api_key_cache entries as the rest of the proxy and no longer fragment org-row caching. * fix(mcp): wrap get_object_permission call in shared try/except Ensure exceptions from get_object_permission in _get_org_object_permission are caught and return None, preserving the original fail-safe semantics. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(jwt): validate issuer audience at config load + dedicated key-miss exception - Move JWTIssuerConfig audience-required guard into a Pydantic model_validator so misconfiguration fails at startup instead of on the first request. - Replace the string-match `No matching public key found` filter in get_public_key's multi-URL fallback with a dedicated NoMatchingJWTPublicKeyError; only that specific exception triggers continuation, every other error still surfaces. * fix(mcp): admit and forward Authorization for passthrough OAuth return For pass-through MCP servers (auth_type=none with delegate_auth_to_upstream) the RFC 9728 cold-start flow sends the client back with only "Authorization: Bearer <upstream-token>" after upstream OAuth discovery. Previously this path 1) was rejected in process_mcp_request because the oauth2_headers fallback only covered auth_type=oauth2 targets, and 2) had the Authorization header stripped by _prepare_mcp_server_headers when no x-litellm-api-key was present, treating the upstream token as a potential LiteLLM key leak. - Extend the elif oauth2_headers fallback to also admit anonymously when every target is a pass-through server. - Pass user_api_key_auth into _prepare_mcp_server_headers so it can forward Authorization for pass-through servers when admission did not consume the bearer as a LiteLLM key (api_key is unset). Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): consistent www-authenticate casing + SSE toolset scoping - Normalize the WWW-Authenticate header key emitted by _check_passthrough_upstream_auth to lowercase to match the other 401 emitters in the OAuth pass-through flow. - Mirror the streamable HTTP handler's toolset scoping in handle_sse_mcp: strip client-supplied x-mcp-toolset-id and apply _apply_toolset_scope before _check_passthrough_upstream_auth so the upstream probe list is derived from the fully-authorized server set. - Tighten _has_client_supplied_mcp_auth signature so mcp_server_auth_headers is Optional, matching its caller in process_mcp_request. Co-authored-by: Yassin Kortam <yassin@berri.ai> * security(mcp): strip Authorization in call_tool when LiteLLM admission used legacy header Mirror the OAuth pass-through admission check from _prepare_mcp_server_headers (list-tools path) in _call_regular_mcp_tool (tool-call path): when the server is OAuth pass-through and the caller did not supply x-litellm-api-key, Authorization on the inbound request may itself be the LiteLLM API key — so strip it before forwarding instead of leaking the gateway credential upstream. When x-litellm-api-key is present, admission is unambiguous and Authorization continues to carry the upstream OAuth bearer (transparent pass-through). * refactor(mcp): centralize caller Authorization strip decision Extracted the security-sensitive logic that decides whether the caller's Authorization header is forwarded to (or stripped from) an outgoing MCP request into a single helper, _should_strip_caller_authorization, in mcp_server_manager.py. Previously the same condition was duplicated across _call_regular_mcp_tool (mcp_server_manager.py) and _prepare_mcp_server_headers (server.py). Keeping two copies of this check risked future divergence and credential-leak / broken-passthrough bugs. Both call sites now share the helper, preserving exact behavior. Co-authored-by: Yassin Kortam <yassin@berri.ai> * log MCP OAuth discovery diagnostics for unmatched paths and non-transport upstream errors * fix(jwt): include issuer-normalized team id in get_all_jwt_team_ids The aggregator for team IDs only consulted the issuer-normalized claim for the plural (team_ids) path and fell back to the global config for the singular path. When an operator configures team_id_jwt_field only at the issuer level, get_team_id correctly returned the mapped value but get_all_jwt_team_ids silently dropped it, causing membership reconciliation to disagree with request routing. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp/jwt): dedupe cold-start path parser; reject conflicting audience flags - _parse_mcp_server_names_from_path now delegates to MCPRequestHandler._extract_target_server_names_from_path so the names used by the cold-start passthrough bypass cannot drift from the names used by downstream routing. - JWTIssuerConfig now rejects the combination of audience and disable_audience_validation=True at validation time instead of silently ignoring the flag. * fix(mcp): restrict passthrough cold-start bypass to 401 only The new elif passthrough cold-start branch reused is_auth_error which matches both 401 and 403. A 403 from user_api_key_auth indicates the LiteLLM key WAS recognized but is forbidden (e.g. over budget / rate limited); falling through to anonymous UserAPIKeyAuth() in that case bypasses spend and rate-limit controls on passthrough servers. Only trigger the cold-start anonymous admission on 401, which is the signal that the bearer is an upstream OAuth token rather than a recognized LiteLLM key. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(jwt/mcp): warn on unscoped JWT fallback; route agent permission lookup through shared helper - _build_decode_kwargs no longer suppresses the unscoped-fallback warning when LiteLLM_JWTAuth.issuers is set: tokens whose iss does not match any configured issuer still fall through to the global path, and that fallback is itself unscoped when JWT_AUDIENCE/JWT_ISSUER are absent. - _get_agent_object_permission now caches the agent_id -> object_permission_id mapping and delegates the permission lookup to the shared get_object_permission helper, so the agent path reuses the same cache entries as the org / team / key paths. * fix(mcp): fabricate resource_metadata challenge when upstream 401 omits WWW-Authenticate When an upstream pass-through MCP server returns 401 without a WWW-Authenticate header (non-compliant per RFC 7235 §3.1), to_http_exception() now produces a synthetic Bearer challenge pointing at the gateway's standard-pattern oauth-protected-resource well-known endpoint for that server. This keeps MCP clients on the RFC 9728 discovery flow instead of receiving a bare 401 with no recovery hint. * fix(jwt): make _get_decode_options explicitly control verify_iss Previously, _get_decode_options only set verify_aud based on whether audience was provided. The issuer JWT path relied on always passing issuer=issuer_config.issuer to trigger PyJWT's default verify_iss=True, making the helper's behavior implicitly dependent on caller behavior. Now _get_decode_options accepts issuer as well, mirroring the verify_aud handling and matching the dimensions handled by _build_decode_kwargs. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): emit absolute resource_metadata URI in fabricated 401 challenge Per RFC 9728 §3.2 the resource_metadata Bearer challenge must be an absolute URI; strict MCP clients reject relative URIs and fail to initiate discovery. MCPUpstreamAuthError.to_http_exception now accepts the gateway base URL and prepends it when the upstream omitted WWW-Authenticate, and all four call sites (streamable HTTP, SSE, and the two REST tool-list paths) supply it. * fix(mcp): correct 403 detail text and remove dead _list_tools_for_single_server duplicate - MCPUpstreamAuthError.to_http_exception() now returns detail='Forbidden' for 403 upstream responses (and 'Unauthorized' for 401), matching the _check_passthrough_upstream_auth pre-flight probe. - Remove the shadowed first definition of _list_tools_for_single_server in rest_endpoints.py; the second definition was the live one and the dead copy was a maintenance trap. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix: address potential bugs in auth_utils, mcp discoverable endpoints, and mcp auth - auth_utils.get_request_route: return '/' instead of empty string when raw_path exactly equals root_path so downstream route allowlist checks still see a leading slash - discoverable_endpoints.fetch_upstream_oauth_protected_resource: also cache negative results (no upstream metadata) for a shorter TTL so we don't re-fetch on every discovery request and so the per-key fetch lock can be pruned - user_api_key_auth_mcp: guard the oauth2_headers 401 cold-start passthrough bypass with _has_client_supplied_mcp_auth, matching the parallel bypass in the no-Authorization branch so MCP-auth-bearing requests don't silently downgrade to anonymous admission Co-authored-by: Yassin Kortam <yassin@berri.ai> * test(vertex): tolerate transient InternalServerError in google maps tool test test_gemini_google_maps_tool_simple makes live calls to Vertex AI's Google Maps grounding backend, which intermittently returns 500 INTERNAL ("Please retry") — a transient upstream failure, not a LiteLLM bug. The test already passes on RateLimitError; treat InternalServerError the same way so transient Vertex-side failures don't fail CI. * refactor(mcp): drop redundant has_client_credentials filter on passthrough probe is_oauth_passthrough already requires auth_type in (None, MCPAuth.none), which is mutually exclusive with has_client_credentials (auth_type == MCPAuth.oauth2), so the extra guard was always True and only added confusion about whether a server could be both passthrough and M2M. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix: restore unreachable InternalServerError skip handler in vertex test Co-authored-by: Yassin Kortam <yassin@berri.ai> * feat(mcp): add dedicated oauth_passthrough flag for non-oauth2 pass-through Previously is_oauth_passthrough reused delegate_auth_to_upstream — a flag scoped to oauth2 servers (PKCE bypass) — to gate OAuth pass-through for auth_type=none servers. Overloading it risked regressing existing deployments that set delegate_auth_to_upstream, since the same flag would silently start driving pass-through (discovery proxying, 401 challenges, upstream 401/403 propagation) on non-oauth2 servers. Introduce a separate oauth_passthrough opt-in so the two behaviors never imply each other: - MCPServer.is_oauth_passthrough now requires oauth_passthrough (not delegate_auth_to_upstream). - Persist oauth_passthrough on LiteLLM_MCPServerTable (new column + migration) and wire it through config/DB load and API responses. - UI splits the single toggle into two: "Delegate auth to upstream (PKCE passthrough)" for oauth2 and "OAuth pass-through" for auth_type=none servers forwarding Authorization. Adds backend tests (property, round-trip, and a regression guard that delegate_auth_to_upstream alone never enables pass-through) and UI tests for the toggle split. * fix(mcp): reconcile cold-start bypass with x-mcp-servers header and skip non-absolute WWW-Authenticate fabrication - _parse_mcp_server_names_from_path now fails closed when the x-mcp-servers header introduces any target not present in the path-derived target set, closing a header/path mismatch where the cold-start passthrough bypass could otherwise admit anonymously while the header advertises a non-passthrough server. - MCPUpstreamAuthError.to_http_exception no longer emits a relative resource_metadata URI when base_url is missing; per RFC 9728 3.2 the URI must be absolute, so we skip fabrication entirely rather than send a challenge strict MCP clients will reject. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(mcp): fabricate path-aware resource_metadata URI for upstream 401 When MCPUpstreamAuthError.to_http_exception fabricates a `WWW-Authenticate: Bearer resource_metadata=...` challenge (because the upstream 401 omitted one), the URL now matches the inbound MCP transport pattern the client originally used: - /mcp/{server_name} -> /.well-known/oauth-protected-resource/mcp/{server_name} - /{server_name}/mcp -> /.well-known/oauth-protected-resource/{server_name}/mcp This mirrors the path-aware behaviour of _get_passthrough_resource_metadata_url in server.py so strict RFC 9728 \xA73.2 clients on legacy routes get a resource_metadata URI aligned with the resource pattern they originally targeted. Co-authored-by: Yassin Kortam <yassin@berri.ai> * fix(jwt+mcp): tighten issuer-scoped claim type handling, RFC-quote authorization_uri, surface MCP upstream auth errors, defense-in-depth on decode options - handle_jwt: when an issuer-scoped _litellm_team_ids claim exists but has an unexpected type, return [] instead of falling through to the global team_ids_jwt_field path (different claim semantically). - handle_jwt: _get_decode_options/_decode_jwt_with_public_key now take an explicit disable_audience_validation flag; passing audience=None without it raises, so audience checks can't silently disappear if the model validator is ever bypassed. _auth_jwt_with_issuer forwards the flag from JWTIssuerConfig. - mcp_server: quote the authorization_uri WWW-Authenticate parameter value (RFC 6750 / 9728 auth-param must be quoted-string), matching the pass-through path. - mcp_server: in _fetch_and_filter_server_tools, re-raise MCPUpstreamAuthError so the outer streamable-HTTP handler can surface a proper 401 + WWW-Authenticate challenge instead of returning an empty tool list. Co-authored-by: Yassin Kortam <yassin@berri.ai> * chore(docker): align Dockerfile.non_root/Dockerfile.database to current wolfi-base SHA The older sha256:3258be... pin has been intermittently returning 500/not-found from cgr.dev, breaking the test-server-root-path GitHub Action and the build_docker_database_image CircleCI job. Move both Dockerfiles onto the same sha256:31da65... digest already in use by Dockerfile, gateway/Dockerfile, backend/Dockerfile, and migrations/Dockerfile so the base image is consistent across the repo. * ci(docker): bump wolfi-base pin to current working digest The previously aligned sha256:31da6565f35a... and the older sha256:3258be... both return HTTP 500 from cgr.dev's manifest endpoint, breaking the build_docker_database_image CircleCI job and test-server-root-path GitHub Action. The current 'latest' tag resolves to sha256:5743937d521c... which serves manifests normally, so move docker/Dockerfile.database and docker/Dockerfile.non_root onto that digest. * ci(docker): retry apk add in Dockerfile.database for apk.cgr.dev flakes Mirror the retry-loop pattern from #28888 (which fixed backend/Dockerfile, gateway/Dockerfile, and migrations/Dockerfile) into docker/Dockerfile.database. The build_docker_database_image CI job has been intermittently failing with "remote server returned error (try 'apk update')" when apk.cgr.dev flakes mid-fetch; bumping the wolfi-base SHA doesn't address the mirror, only a retry does. Same explicit-failure form as #28888: exit non-zero on the 3rd miss instead of silently succeeding because `sleep 5` was the last command in the `&& break || sleep 5` chain. * fix(mcp): scope preemptive 401 to toolset-narrowed server set Move _raise_preemptive_401_for_unauthenticated_servers after toolset scoping in both the StreamableHTTP and SSE handlers, and add an optional allowed_server_ids parameter so passthrough/oauth2 servers that the active toolset excludes no longer trigger a spurious 401 challenge. Without this, a client targeting a toolset whose scope excludes a passthrough server could be pushed into an OAuth flow for a server it would be 403'd on immediately after authentication. Co-authored-by: Yassin Kortam <yassin@berri.ai> * revert(docker): drop unrelated Wolfi bump and apk retry loop from MCP/JWT PR These Docker changes are out of scope for the MCP OAuth passthrough + JWT auth work and duplicate the build-reliability fix already merged to litellm_internal_staging in #28888, which adds the same apk retry loop on the componentized backend/gateway/migrations Dockerfiles and also fixes the underlying nodeenv/libatomic root cause. Restoring docker/Dockerfile.database and docker/Dockerfile.non_root to the base so this PR is purely the MCP/JWT change. * fix(mcp): surface upstream 403 challenges from REST tools/list The single-server pass-through path converted an upstream MCPUpstreamAuthError into an HTTPException, but list_tool_rest_api only re-raised 401s; an upstream 403 (valid token, insufficient scope) collapsed into a 200 response with error=unexpected_error, so clients never saw the status or WWW-Authenticate challenge needed to refresh scopes. Let MCPUpstreamAuthError propagate and convert it once in list_tool_rest_api so both 401 and 403 reach the client, while internal access/IP 403s keep the legacy error-dict shape. * fix(mcp): fail closed for IP access control when XFF trusted ranges unset When use_x_forwarded_for is enabled but mcp_trusted_proxy_ranges is not configured, get_mcp_client_ip previously fell back to the direct peer IP. Behind an internal reverse proxy that peer is the proxy's private address, so every external caller was classified as internal and could reach MCP servers with available_on_public_internet=false. Return an empty string in that case so is_internal_ip treats the caller as external. --------- Co-authored-by: Yuneng Jiang <yuneng@berri.ai> Co-authored-by: Milan <milan@berri.ai> Co-authored-by: Cursor <cursoragent@cursor.com> Co-authored-by: Mateo Wang <mateo-berri@users.noreply.github.com> Co-authored-by: Krrish Dholakia <krrish+github@berri.ai> Co-authored-by: ryan-crabbe-berri <ryan@berri.ai> Co-authored-by: stuxf <70670632+stuxf@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: veria-ai[bot] <224490171+veria-ai[bot]@users.noreply.github.com> Co-authored-by: gym-cmd <186399764+gym-cmd@users.noreply.github.com> Co-authored-by: Artem Dudarev <artem.dudarev@justeattakeaway.com> Co-authored-by: Claude <claude@anthropic.com> Co-authored-by: Yassin Kortam <yassin@berri.ai>
2981 lines
107 KiB
Python
2981 lines
107 KiB
Python
# Create server parameters for stdio connection
|
|
import os
|
|
import sys
|
|
import pytest
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
from contextlib import asynccontextmanager
|
|
|
|
sys.path.insert(
|
|
0, os.path.abspath("../../..")
|
|
) # Adds the parent directory to the system path
|
|
|
|
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
|
|
MCPServerManager,
|
|
MCPServer,
|
|
MCPTransport,
|
|
)
|
|
from litellm.proxy._types import LiteLLM_ObjectPermissionTable
|
|
from mcp.types import Tool as MCPTool, CallToolResult, ListToolsResult
|
|
from mcp.types import TextContent
|
|
|
|
|
|
mcp_server_manager = MCPServerManager()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.skip(reason="Local only test")
|
|
async def test_mcp_server_manager():
|
|
await mcp_server_manager.load_servers_from_config(
|
|
{
|
|
"zapier_mcp_server": {
|
|
"url": os.environ.get("ZAPIER_MCP_SERVER_URL"),
|
|
}
|
|
}
|
|
)
|
|
tools = await mcp_server_manager.list_tools()
|
|
print("TOOLS FROM MCP SERVER MANAGER== ", tools)
|
|
|
|
result = await mcp_server_manager.call_tool(
|
|
name="gmail_send_email", arguments={"body": "Test"}, proxy_logging_obj=None
|
|
)
|
|
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_https_server():
|
|
# Create mock tools and results
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="gmail_send_email",
|
|
description="Send an email via Gmail",
|
|
inputSchema={
|
|
"type": "object",
|
|
"properties": {
|
|
"body": {"type": "string"},
|
|
"message": {"type": "string"},
|
|
"instructions": {"type": "string"},
|
|
},
|
|
"required": ["body"],
|
|
},
|
|
)
|
|
]
|
|
|
|
mock_result = CallToolResult(
|
|
content=[TextContent(type="text", text="Email sent successfully")],
|
|
isError=False,
|
|
)
|
|
|
|
# Create a mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.call_tool = AsyncMock(return_value=mock_result)
|
|
|
|
# Mock the MCPClient constructor
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
await mcp_server_manager.load_servers_from_config(
|
|
{
|
|
"zapier_mcp_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
}
|
|
}
|
|
)
|
|
|
|
allowed_server_ids = list(mcp_server_manager.get_registry().keys())
|
|
assert allowed_server_ids, "Expected registry to contain the configured server"
|
|
|
|
with patch.object(
|
|
mcp_server_manager,
|
|
"get_allowed_mcp_servers",
|
|
new=AsyncMock(return_value=allowed_server_ids),
|
|
):
|
|
tools = await mcp_server_manager.list_tools()
|
|
print("TOOLS FROM MCP SERVER MANAGER== ", tools)
|
|
|
|
# Verify tools were returned and properly prefixed
|
|
assert len(tools) == 1
|
|
# The server should use the server_name as prefix since no alias is provided
|
|
expected_prefix = "zapier_mcp_server"
|
|
assert tools[0].name == f"{expected_prefix}-gmail_send_email"
|
|
|
|
# Manually set up the tool mapping for the call_tool test
|
|
mcp_server_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = (
|
|
expected_prefix
|
|
)
|
|
mcp_server_manager.tool_name_to_mcp_server_name_mapping[
|
|
f"{expected_prefix}-gmail_send_email"
|
|
] = expected_prefix
|
|
|
|
result = await mcp_server_manager.call_tool(
|
|
server_name="zapier_mcp_server",
|
|
name=f"{expected_prefix}-gmail_send_email",
|
|
arguments={
|
|
"body": "Test",
|
|
"message": "Test",
|
|
"instructions": "Test",
|
|
},
|
|
proxy_logging_obj=None,
|
|
)
|
|
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
|
|
|
|
# Verify result
|
|
assert result.isError is False
|
|
assert len(result.content) == 1
|
|
assert isinstance(result.content[0], TextContent)
|
|
assert result.content[0].text == "Email sent successfully"
|
|
|
|
# Verify client methods were called
|
|
mock_client.list_tools.assert_called()
|
|
mock_client.call_tool.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_http_transport_list_tools_mock():
|
|
"""Test HTTP transport list_tools functionality with mocked dependencies"""
|
|
|
|
# Create a fresh manager for testing
|
|
test_manager = MCPServerManager()
|
|
|
|
# Mock tools that should be returned
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="gmail_send_email",
|
|
description="Send an email via Gmail",
|
|
inputSchema={
|
|
"type": "object",
|
|
"properties": {
|
|
"to": {"type": "string"},
|
|
"subject": {"type": "string"},
|
|
"body": {"type": "string"},
|
|
},
|
|
"required": ["to", "subject", "body"],
|
|
},
|
|
),
|
|
MCPTool(
|
|
name="calendar_create_event",
|
|
description="Create a calendar event",
|
|
inputSchema={
|
|
"type": "object",
|
|
"properties": {
|
|
"title": {"type": "string"},
|
|
"date": {"type": "string"},
|
|
"time": {"type": "string"},
|
|
},
|
|
"required": ["title", "date"],
|
|
},
|
|
),
|
|
]
|
|
|
|
# Create a mock MCPClient that returns our test tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
# Mock the MCPClient constructor to return our mock
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Load server config with HTTP transport
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"test_http_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test HTTP MCP Server",
|
|
}
|
|
}
|
|
)
|
|
|
|
# Call list_tools
|
|
allowed_server_ids = list(test_manager.get_registry().keys())
|
|
assert allowed_server_ids, "Expected registry to contain configured server"
|
|
|
|
with patch.object(
|
|
test_manager,
|
|
"get_allowed_mcp_servers",
|
|
new=AsyncMock(return_value=allowed_server_ids),
|
|
):
|
|
tools = await test_manager.list_tools()
|
|
|
|
# Assertions
|
|
assert len(tools) == 2
|
|
# The server should use the server_name as prefix since no alias is provided
|
|
expected_prefix = "test_http_server"
|
|
assert tools[0].name == f"{expected_prefix}-gmail_send_email"
|
|
assert tools[1].name == f"{expected_prefix}-calendar_create_event"
|
|
|
|
# Verify client methods were called
|
|
mock_client.list_tools.assert_called()
|
|
|
|
# Verify tool mapping was updated
|
|
expected_prefix = "test_http_server"
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping[
|
|
f"{expected_prefix}-gmail_send_email"
|
|
]
|
|
== expected_prefix
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping[
|
|
f"{expected_prefix}-calendar_create_event"
|
|
]
|
|
== expected_prefix
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_http_transport_call_tool_mock():
|
|
"""Test HTTP transport call_tool functionality with mocked dependencies"""
|
|
|
|
# Create a fresh manager for testing
|
|
test_manager = MCPServerManager()
|
|
|
|
# Mock tool call result
|
|
mock_result = CallToolResult(
|
|
content=[
|
|
TextContent(type="text", text="Email sent successfully to test@example.com")
|
|
],
|
|
isError=False,
|
|
)
|
|
|
|
# Create a mock MCPClient that returns our test result
|
|
mock_client = AsyncMock()
|
|
mock_client.call_tool = AsyncMock(return_value=mock_result)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
# Mock the MCPClient constructor to return our mock
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Load server config with HTTP transport
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"test_http_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test HTTP MCP Server",
|
|
}
|
|
}
|
|
)
|
|
|
|
# Manually set up tool mapping (normally done by list_tools)
|
|
test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = (
|
|
"test_http_server"
|
|
)
|
|
|
|
# Call the tool
|
|
result = await test_manager.call_tool(
|
|
server_name="test_http_server",
|
|
name="gmail_send_email",
|
|
arguments={
|
|
"to": "test@example.com",
|
|
"subject": "Test Subject",
|
|
"body": "Test email body",
|
|
},
|
|
proxy_logging_obj=None,
|
|
)
|
|
|
|
# Assertions
|
|
assert result.isError is False
|
|
assert len(result.content) == 1
|
|
# Type check before accessing text attribute
|
|
assert isinstance(result.content[0], TextContent)
|
|
assert result.content[0].text == "Email sent successfully to test@example.com"
|
|
|
|
# Verify client methods were called
|
|
mock_client.call_tool.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_http_transport_call_tool_error_mock():
|
|
"""Test HTTP transport call_tool error handling with mocked dependencies"""
|
|
|
|
# Create a fresh manager for testing
|
|
test_manager = MCPServerManager()
|
|
|
|
# Mock tool call error result
|
|
mock_error_result = CallToolResult(
|
|
content=[TextContent(type="text", text="Error: Invalid email address")],
|
|
isError=True,
|
|
)
|
|
|
|
# Create a mock MCPClient that returns our test error result
|
|
mock_client = AsyncMock()
|
|
mock_client.call_tool = AsyncMock(return_value=mock_error_result)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
# Mock the MCPClient constructor to return our mock
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Load server config with HTTP transport
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"test_http_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test HTTP MCP Server",
|
|
}
|
|
}
|
|
)
|
|
|
|
# Manually set up tool mapping
|
|
test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = (
|
|
"test_http_server"
|
|
)
|
|
|
|
# Call the tool with invalid data
|
|
result = await test_manager.call_tool(
|
|
server_name="test_http_server",
|
|
name="gmail_send_email",
|
|
arguments={"to": "invalid-email", "subject": "Test", "body": "Test"},
|
|
proxy_logging_obj=None,
|
|
)
|
|
|
|
# Assertions for error case
|
|
assert result.isError is True
|
|
assert len(result.content) == 1
|
|
# Type check before accessing text attribute
|
|
assert isinstance(result.content[0], TextContent)
|
|
assert "Error: Invalid email address" in result.content[0].text
|
|
|
|
# Verify client methods were called
|
|
mock_client.call_tool.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_http_transport_tool_not_found():
|
|
"""Test calling a tool that doesn't exist"""
|
|
|
|
# Create a fresh manager for testing
|
|
test_manager = MCPServerManager()
|
|
|
|
# Load server config
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"test_http_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test HTTP MCP Server",
|
|
}
|
|
}
|
|
)
|
|
|
|
# Mapping populated for this server but not for the requested tool
|
|
test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = (
|
|
"test_http_server"
|
|
)
|
|
|
|
# Try to call a tool that doesn't exist in mapping
|
|
with pytest.raises(ValueError, match="Tool nonexistent_tool not found"):
|
|
await test_manager.call_tool(
|
|
server_name="test_http_server",
|
|
name="nonexistent_tool",
|
|
arguments={"param": "value"},
|
|
proxy_logging_obj=None,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_streamable_http_mcp_handler_mock():
|
|
"""Test the streamable HTTP MCP handler functionality"""
|
|
# Mock streamable HTTP session managers and their methods
|
|
mock_session_manager_stateless = AsyncMock()
|
|
mock_session_manager_stateless.handle_request = AsyncMock()
|
|
mock_session_manager_stateful = AsyncMock()
|
|
mock_session_manager_stateful.handle_request = AsyncMock()
|
|
|
|
# Mock scope, receive, send with proper ASGI scope format
|
|
mock_scope = {
|
|
"type": "http",
|
|
"method": "POST",
|
|
"path": "/mcp",
|
|
"headers": [(b"content-type", b"application/json")],
|
|
"query_string": b"",
|
|
"server": ("localhost", 8000),
|
|
"scheme": "http",
|
|
}
|
|
mock_receive = AsyncMock(return_value={"body": b"{}", "more_body": False})
|
|
mock_send = AsyncMock()
|
|
|
|
# Mock extract_mcp_auth_context to bypass auth checks in the handler
|
|
mock_auth_context = (None, None, None, {}, {}, {})
|
|
|
|
with (
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
|
|
True,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.session_manager_stateless",
|
|
mock_session_manager_stateless,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.session_manager_stateful",
|
|
mock_session_manager_stateful,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",
|
|
AsyncMock(return_value=mock_auth_context),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.set_auth_context",
|
|
),
|
|
):
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
handle_streamable_http_mcp,
|
|
)
|
|
|
|
# Call the handler
|
|
await handle_streamable_http_mcp(mock_scope, mock_receive, mock_send)
|
|
|
|
# Verify stateless session manager handle_request was called
|
|
mock_session_manager_stateless.handle_request.assert_called_once()
|
|
mock_session_manager_stateful.handle_request.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sse_mcp_handler_mock():
|
|
"""Test the SSE MCP handler functionality"""
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Mock the SSE session manager and its methods
|
|
mock_sse_session_manager = AsyncMock()
|
|
mock_sse_session_manager.handle_request = AsyncMock()
|
|
|
|
# Mock scope, receive, send with proper ASGI scope format
|
|
mock_scope = {
|
|
"type": "http",
|
|
"method": "GET",
|
|
"path": "/mcp/sse",
|
|
"headers": [(b"accept", b"text/event-stream")],
|
|
"query_string": b"",
|
|
"server": ("localhost", 8000),
|
|
"scheme": "http",
|
|
}
|
|
mock_receive = AsyncMock()
|
|
mock_send = AsyncMock()
|
|
|
|
mock_auth_result = (
|
|
UserAPIKeyAuth(),
|
|
None,
|
|
None,
|
|
{},
|
|
{},
|
|
[],
|
|
)
|
|
|
|
with (
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
|
|
True,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.sse_session_manager",
|
|
mock_sse_session_manager,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",
|
|
new=AsyncMock(return_value=mock_auth_result),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.set_auth_context",
|
|
),
|
|
):
|
|
from litellm.proxy._experimental.mcp_server.server import handle_sse_mcp
|
|
|
|
# Call the handler
|
|
await handle_sse_mcp(mock_scope, mock_receive, mock_send)
|
|
|
|
# Verify SSE session manager handle_request was called
|
|
mock_sse_session_manager.handle_request.assert_called_once_with(
|
|
mock_scope, mock_receive, mock_send
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sse_mcp_handler_propagates_passthrough_401():
|
|
"""SSE handler must raise 401 + WWW-Authenticate when the upstream
|
|
pass-through probe rejects the client's bearer token, instead of letting
|
|
the SSE session start and silently return empty tool lists."""
|
|
from fastapi import HTTPException
|
|
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
mock_scope = {
|
|
"type": "http",
|
|
"method": "GET",
|
|
"path": "/mcp/sse",
|
|
"headers": [(b"accept", b"text/event-stream")],
|
|
"query_string": b"",
|
|
"server": ("localhost", 8000),
|
|
"scheme": "http",
|
|
}
|
|
mock_receive = AsyncMock()
|
|
mock_send = AsyncMock()
|
|
|
|
mock_auth_result = (UserAPIKeyAuth(), None, None, {}, {}, [])
|
|
|
|
challenge = HTTPException(
|
|
status_code=401,
|
|
detail="Unauthorized",
|
|
headers={"WWW-Authenticate": "Bearer authorization_uri=https://example/"},
|
|
)
|
|
|
|
with (
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
|
|
True,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.sse_session_manager",
|
|
AsyncMock(),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",
|
|
new=AsyncMock(return_value=mock_auth_result),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.set_auth_context",
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._raise_preemptive_401_for_unauthenticated_servers",
|
|
new=AsyncMock(),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._check_passthrough_upstream_auth",
|
|
new=AsyncMock(side_effect=challenge),
|
|
),
|
|
):
|
|
from litellm.proxy._experimental.mcp_server.server import handle_sse_mcp
|
|
|
|
with pytest.raises(HTTPException) as excinfo:
|
|
await handle_sse_mcp(mock_scope, mock_receive, mock_send)
|
|
|
|
assert excinfo.value.status_code == 401
|
|
assert excinfo.value.headers and "WWW-Authenticate" in excinfo.value.headers
|
|
|
|
|
|
def test_generate_stable_server_id():
|
|
"""
|
|
Test the _generate_stable_server_id method to ensure hash stability across releases.
|
|
|
|
This test verifies that:
|
|
1. The same inputs always produce the same hash output
|
|
2. Different inputs produce different hash outputs
|
|
3. The hash format is consistent (32 character hex string)
|
|
4. Edge cases work correctly (None auth_type)
|
|
|
|
IMPORTANT: If this test fails, it means the hashing algorithm has changed
|
|
and will break backwards compatibility with existing server IDs!
|
|
"""
|
|
manager = MCPServerManager()
|
|
|
|
# Test Case 1: Basic functionality with known inputs
|
|
# These expected values MUST remain stable across releases
|
|
test_cases = [
|
|
{
|
|
"params": {
|
|
"server_name": "zapier_mcp_server",
|
|
"url": "https://actions.zapier.com/mcp/sse",
|
|
"transport": "sse",
|
|
"auth_type": "api_key",
|
|
},
|
|
"expected_hash": "8d5c9f8a12e3b7c4f6a2d8e1b5c9f2a4",
|
|
},
|
|
{
|
|
"params": {
|
|
"server_name": "google_drive_mcp_server",
|
|
"url": "https://drive.google.com/mcp/http",
|
|
"transport": "http",
|
|
"auth_type": None,
|
|
},
|
|
"expected_hash": "7a4b2e8f3c1d9e6b5a7c8f2d4e1b9c6a",
|
|
},
|
|
{
|
|
"params": {
|
|
"server_name": "local_test_server",
|
|
"url": "http://localhost:8080/mcp",
|
|
"transport": "http",
|
|
"auth_type": "basic",
|
|
},
|
|
"expected_hash": "2f1e8d7c6b5a4e3f2d1c9b8a7e6f5d4c",
|
|
},
|
|
]
|
|
|
|
# Test that our known inputs produce expected hash values
|
|
for test_case in test_cases:
|
|
result = manager._generate_stable_server_id(**test_case["params"])
|
|
|
|
# For now, just verify the format and stability, not exact hash
|
|
# (since we need to first run to see what the actual hashes are)
|
|
assert len(result) == 32, f"Hash should be 32 characters, got {len(result)}"
|
|
assert result.isalnum(), f"Hash should be alphanumeric, got: {result}"
|
|
assert result.islower(), f"Hash should be lowercase, got: {result}"
|
|
|
|
# Test stability - same inputs should always produce same output
|
|
result2 = manager._generate_stable_server_id(**test_case["params"])
|
|
assert (
|
|
result == result2
|
|
), f"Hash should be stable for same inputs: {result} != {result2}"
|
|
|
|
# Test Case 2: Different inputs produce different outputs
|
|
base_params = {
|
|
"server_name": "test_server",
|
|
"url": "https://test.com/mcp",
|
|
"transport": "sse",
|
|
"auth_type": "api_key",
|
|
}
|
|
|
|
base_hash = manager._generate_stable_server_id(**base_params)
|
|
|
|
# Change each parameter and verify hash changes
|
|
variations = [
|
|
{"server_name": "different_server"},
|
|
{"url": "https://different.com/mcp"},
|
|
{"transport": "http"},
|
|
{"auth_type": "basic"},
|
|
{"auth_type": None},
|
|
]
|
|
|
|
for variation in variations:
|
|
modified_params = {**base_params, **variation}
|
|
modified_hash = manager._generate_stable_server_id(**modified_params)
|
|
assert (
|
|
modified_hash != base_hash
|
|
), f"Different params should produce different hash: {variation}"
|
|
assert (
|
|
len(modified_hash) == 32
|
|
), f"Modified hash should be 32 characters: {variation}"
|
|
|
|
# Test Case 3: Edge case with None auth_type
|
|
params_with_none = {
|
|
"server_name": "test_server",
|
|
"url": "https://test.com/mcp",
|
|
"transport": "sse",
|
|
"auth_type": None,
|
|
}
|
|
|
|
params_with_empty = {
|
|
"server_name": "test_server",
|
|
"url": "https://test.com/mcp",
|
|
"transport": "sse",
|
|
"auth_type": "",
|
|
}
|
|
|
|
hash_none = manager._generate_stable_server_id(**params_with_none)
|
|
hash_empty = manager._generate_stable_server_id(**params_with_empty)
|
|
|
|
# None and empty string should produce the same hash (both become empty string)
|
|
assert (
|
|
hash_none == hash_empty
|
|
), "None auth_type should be equivalent to empty string"
|
|
|
|
# Test Case 4: Real-world example hashes that must remain stable
|
|
# These are based on common configurations and MUST NOT CHANGE
|
|
zapier_sse_hash = manager._generate_stable_server_id(
|
|
server_name="zapier_mcp_server",
|
|
url="https://actions.zapier.com/mcp/sk-ak-example/sse",
|
|
transport="sse",
|
|
auth_type="api_key",
|
|
)
|
|
|
|
github_http_hash = manager._generate_stable_server_id(
|
|
server_name="github_mcp_server",
|
|
url="https://api.github.com/mcp/http",
|
|
transport="http",
|
|
auth_type=None,
|
|
)
|
|
|
|
# These should be deterministic - same call should produce same result
|
|
assert zapier_sse_hash == manager._generate_stable_server_id(
|
|
server_name="zapier_mcp_server",
|
|
url="https://actions.zapier.com/mcp/sk-ak-example/sse",
|
|
transport="sse",
|
|
auth_type="api_key",
|
|
)
|
|
|
|
assert github_http_hash == manager._generate_stable_server_id(
|
|
server_name="github_mcp_server",
|
|
url="https://api.github.com/mcp/http",
|
|
transport="http",
|
|
auth_type=None,
|
|
)
|
|
|
|
# Verify format
|
|
assert len(zapier_sse_hash) == 32
|
|
assert len(github_http_hash) == 32
|
|
assert zapier_sse_hash != github_http_hash
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tools_rest_api_server_not_found():
|
|
"""Test the list_tools REST API when server is not found"""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
list_tool_rest_api,
|
|
global_mcp_server_manager,
|
|
)
|
|
from fastapi import Query
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Mock UserAPIKeyAuth with explicit permission to access the requested server id
|
|
mock_user_auth = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=["non_existent_server_id"],
|
|
),
|
|
)
|
|
|
|
# Mock request with proper client attribute (internal IP for no filtering)
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {}
|
|
mock_request.client = MagicMock()
|
|
mock_request.client.host = "127.0.0.1" # Internal IP to bypass IP filtering
|
|
|
|
# Mock the global_mcp_server_manager to allow the server ID but return None for the server
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Allow the server ID in permissions
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["non_existent_server_id"]
|
|
)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
# Return None when trying to get the server (server doesn't exist)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=None)
|
|
|
|
# Test with non-existent server ID
|
|
response = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="non_existent_server_id",
|
|
user_api_key_dict=mock_user_auth,
|
|
)
|
|
|
|
assert isinstance(response, dict)
|
|
assert response["tools"] == []
|
|
assert response["error"] == "server_not_found"
|
|
assert "Server with id non_existent_server_id not found" in response["message"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tools_rest_api_success():
|
|
"""Test the list_tools REST API successful case"""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
list_tool_rest_api,
|
|
)
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
from fastapi import Query
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Mock successful tools
|
|
mock_tools = [
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="test_tool",
|
|
description="A test tool",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "test_server"},
|
|
)
|
|
]
|
|
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.server_id = "test-server-123"
|
|
mock_server.alias = "test_server"
|
|
mock_server.name = "test_server"
|
|
mock_server.mcp_info = {"server_name": "test_server"}
|
|
|
|
# Mock UserAPIKeyAuth
|
|
mock_user_auth = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=["test-server-123"],
|
|
),
|
|
)
|
|
|
|
# Mock request with proper client attribute (internal IP for no filtering)
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {}
|
|
mock_request.client = MagicMock()
|
|
mock_request.client.host = "127.0.0.1" # Internal IP to bypass IP filtering
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
mock_get_tools.return_value = mock_tools
|
|
|
|
# Test successful case
|
|
response = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="test-server-123",
|
|
user_api_key_dict=mock_user_auth,
|
|
)
|
|
|
|
assert isinstance(response, dict)
|
|
assert len(response["tools"]) == 1
|
|
assert response["tools"][0].name == "test_tool"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_tools_from_mcp_servers():
|
|
"""Test _get_tools_from_mcp_servers function with both specific and no server filters"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
|
|
MCPServer,
|
|
MCPTransport,
|
|
)
|
|
|
|
# Mock data
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
mock_auth_header = "Bearer test_token"
|
|
mock_server_1 = MCPServer(
|
|
server_id="server1_id",
|
|
name="server1",
|
|
server_name="server1",
|
|
url="http://test1.com",
|
|
transport=MCPTransport.http,
|
|
)
|
|
mock_server_2 = MCPServer(
|
|
server_id="server2_id",
|
|
name="server2",
|
|
server_name="server2",
|
|
url="http://test2.com",
|
|
transport=MCPTransport.http,
|
|
)
|
|
mock_server_3 = MCPServer(
|
|
server_id="server3_id",
|
|
name="server3",
|
|
server_name="server3",
|
|
url="http://test3.com",
|
|
transport=MCPTransport.http,
|
|
access_groups=["group-a"],
|
|
)
|
|
mock_tool_1 = MCPTool(name="tool1", description="test tool 1", inputSchema={})
|
|
mock_tool_2 = MCPTool(name="tool2", description="test tool 2", inputSchema={})
|
|
|
|
# Test Case 1: With specific MCP servers
|
|
try:
|
|
# Mock the necessary methods
|
|
def mock_get_server_by_id(server_id):
|
|
if server_id == "server1_id":
|
|
return mock_server_1
|
|
elif server_id == "server2_id":
|
|
return mock_server_2
|
|
elif server_id == "server3_id":
|
|
return mock_server_3
|
|
return None
|
|
|
|
# Create a mock manager
|
|
mock_manager = AsyncMock()
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["server1_id", "server2_id"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = lambda server_id: (
|
|
mock_server_1 if server_id == "server1_id" else mock_server_2
|
|
)
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=[mock_tool_1])
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
|
|
mock_manager,
|
|
):
|
|
# Test with specific servers
|
|
result = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header=mock_auth_header,
|
|
mcp_servers=["server1"],
|
|
)
|
|
assert len(result) == 1, "Should only return tools from server1"
|
|
assert result[0].name == "tool1", "Should return tool from server1"
|
|
|
|
# Test Case 2: Without specific MCP servers
|
|
# Create a different mock manager for the second test case
|
|
mock_manager_2 = AsyncMock()
|
|
mock_manager_2.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["server1_id", "server2_id"]
|
|
)
|
|
mock_manager_2.get_mcp_server_by_id = lambda server_id: (
|
|
mock_server_1 if server_id == "server1_id" else mock_server_2
|
|
)
|
|
|
|
async def mock_get_tools_side_effect(
|
|
server,
|
|
mcp_auth_header=None,
|
|
extra_headers=None,
|
|
add_prefix=False,
|
|
raw_headers=None,
|
|
user_api_key_auth=None,
|
|
):
|
|
if server.server_id == "server1_id":
|
|
return [mock_tool_1]
|
|
return [mock_tool_2]
|
|
|
|
mock_manager_2._get_tools_from_server = AsyncMock(
|
|
side_effect=mock_get_tools_side_effect
|
|
)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager_2.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
|
|
mock_manager_2,
|
|
):
|
|
result = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header=mock_auth_header,
|
|
mcp_servers=None,
|
|
)
|
|
assert len(result) == 2, "Should return tools from all servers"
|
|
assert (
|
|
result[0].name == "tool1" and result[1].name == "tool2"
|
|
), "Should return tools from all servers"
|
|
|
|
#
|
|
# Test Case 3: With specific MCP servers and access groups
|
|
# Create a mock manager
|
|
mock_manager = AsyncMock()
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["server1_id", "server2_id", "server3_id"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = lambda server_id: (
|
|
mock_server_1
|
|
if server_id == "server1_id"
|
|
else (mock_server_2 if server_id == "server2_id" else mock_server_3)
|
|
)
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=[mock_tool_1])
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
|
|
mock_manager,
|
|
):
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.MCPRequestHandler._get_mcp_servers_from_access_groups",
|
|
AsyncMock(return_value=["server3_id"]),
|
|
):
|
|
# Test with specific servers
|
|
result = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header=mock_auth_header,
|
|
mcp_servers=["group-a"],
|
|
)
|
|
assert len(result) == 1, "Should only return tools from server3"
|
|
assert result[0].name == "tool1", "Should return tool from server1"
|
|
|
|
except AssertionError as e:
|
|
pytest.fail(f"Test failed: {str(e)}")
|
|
except Exception as e:
|
|
pytest.fail(f"Unexpected error in tests: {str(e)}")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tools_only_returns_allowed_servers(monkeypatch):
|
|
"""
|
|
Test that list_tools only returns tools from servers allowed for the user.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Setup two servers in the config
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"server_a": {
|
|
"url": "https://server-a.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Server A",
|
|
},
|
|
"server_b": {
|
|
"url": "https://server-b.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Server B",
|
|
},
|
|
}
|
|
)
|
|
|
|
# Patch get_allowed_mcp_servers to only allow server_a
|
|
async def mock_get_allowed_mcp_servers(self, user_api_key_auth=None):
|
|
return [
|
|
list(test_manager.get_registry().keys())[0]
|
|
] # Only first server (server_a)
|
|
|
|
monkeypatch.setattr(
|
|
MCPServerManager, "get_allowed_mcp_servers", mock_get_allowed_mcp_servers
|
|
)
|
|
|
|
# Mock tools for each server
|
|
mock_tools_a = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email via Server A",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
mock_tools_b = [
|
|
MCPTool(
|
|
name="create_event",
|
|
description="Create an event via Server B",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Patch MCPClient to return different tools for each server
|
|
def mock_client_constructor(*args, **kwargs):
|
|
mock_client = AsyncMock()
|
|
# Return tools based on server URL
|
|
if kwargs.get("server_url") == "https://server-a.com/mcp":
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools_a)
|
|
else:
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools_b)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call list_tools
|
|
tools = await test_manager.list_tools(user_api_key_auth=MagicMock())
|
|
# Should only return tools from server_a
|
|
assert len(tools) == 1
|
|
# The server should use the server_name as prefix since no alias is provided
|
|
expected_prefix = "server_a"
|
|
assert tools[0].name.startswith(f"{expected_prefix}-")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_access_groups_from_config():
|
|
"""
|
|
Test that access_groups are loaded from config and can be resolved.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"config_server": {
|
|
"url": "https://config-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"access_groups": ["group-a", "group-b"],
|
|
},
|
|
"other_server": {
|
|
"url": "https://other-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"access_groups": ["group-b", "group-c"],
|
|
},
|
|
}
|
|
)
|
|
# Check that access_groups are loaded
|
|
config_server = next(
|
|
(
|
|
s
|
|
for s in test_manager.config_mcp_servers.values()
|
|
if s.name == "config_server"
|
|
),
|
|
None,
|
|
)
|
|
assert config_server is not None
|
|
assert set(config_server.access_groups) == {"group-a", "group-b"}
|
|
# Check that the lookup logic finds the correct server ids
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
|
|
# Patch global_mcp_server_manager for this test and restore afterwards to
|
|
# avoid leaking state into other tests (e.g. the proxy MCP e2e suite).
|
|
import litellm.proxy._experimental.mcp_server.mcp_server_manager as mcp_server_manager_mod
|
|
|
|
original_manager = mcp_server_manager_mod.global_mcp_server_manager
|
|
mcp_server_manager_mod.global_mcp_server_manager = test_manager
|
|
try:
|
|
# Should find config_server for group-a, both for group-b, other_server for group-c
|
|
import asyncio
|
|
|
|
server_ids_a = await MCPRequestHandler._get_mcp_servers_from_access_groups(
|
|
["group-a"]
|
|
)
|
|
server_ids_b = await MCPRequestHandler._get_mcp_servers_from_access_groups(
|
|
["group-b"]
|
|
)
|
|
server_ids_c = await MCPRequestHandler._get_mcp_servers_from_access_groups(
|
|
["group-c"]
|
|
)
|
|
assert any(config_server.server_id == sid for sid in server_ids_a)
|
|
assert set(server_ids_b) == set(
|
|
[
|
|
s.server_id
|
|
for s in test_manager.config_mcp_servers.values()
|
|
if "group-b" in s.access_groups
|
|
]
|
|
)
|
|
assert any(
|
|
s.name == "other_server" and s.server_id in server_ids_c
|
|
for s in test_manager.config_mcp_servers.values()
|
|
)
|
|
finally:
|
|
mcp_server_manager_mod.global_mcp_server_manager = original_manager
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_config_integration_with_database():
|
|
"""
|
|
Test that config-based servers properly integrate with database servers,
|
|
specifically testing access_groups and description fields.
|
|
"""
|
|
import datetime
|
|
from litellm.proxy._types import LiteLLM_MCPServerTable
|
|
|
|
test_manager = MCPServerManager()
|
|
|
|
# Test 1: Load config with access_groups and description
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"config_server_with_groups": {
|
|
"url": "https://config-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test config server",
|
|
"access_groups": ["fr_staff", "admin"],
|
|
}
|
|
}
|
|
)
|
|
|
|
# Verify config server has correct access_groups
|
|
config_servers = test_manager.config_mcp_servers
|
|
assert len(config_servers) == 1
|
|
config_server = next(iter(config_servers.values()))
|
|
assert config_server.access_groups == ["fr_staff", "admin"]
|
|
assert config_server.mcp_info["description"] == "Test config server"
|
|
|
|
# Test 2: Create a database server record and test add_update_server method
|
|
db_server = LiteLLM_MCPServerTable(
|
|
server_id="db-server-123",
|
|
server_name="database-server",
|
|
url="https://db-server.com/mcp",
|
|
transport="http",
|
|
auth_type="none",
|
|
description="Database server description",
|
|
created_at=datetime.datetime.now(),
|
|
updated_at=datetime.datetime.now(),
|
|
mcp_access_groups=["db_group", "test_group"],
|
|
)
|
|
|
|
# Test the add_update_server method (this tests our fix)
|
|
await test_manager.add_server(db_server)
|
|
|
|
# Verify the server was added with correct access_groups
|
|
registry = test_manager.get_registry()
|
|
assert "db-server-123" in registry
|
|
|
|
db_server_in_registry = registry["db-server-123"]
|
|
assert db_server_in_registry.access_groups == ["db_group", "test_group"]
|
|
assert db_server_in_registry.server_name == "database-server"
|
|
|
|
# Test 3: Test config server conversion to LiteLLM_MCPServerTable format
|
|
# This tests that config servers are properly converted with access_groups and description fields
|
|
|
|
# Mock user auth to get all servers
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
mock_user_auth = UserAPIKeyAuth(user_role="proxy_admin")
|
|
|
|
# Mock the get_allowed_mcp_servers to return only config server IDs
|
|
# (to avoid database dependency in this test)
|
|
async def mock_get_allowed_servers(user_auth=None):
|
|
config_server_ids = list(test_manager.config_mcp_servers.keys())
|
|
return config_server_ids
|
|
|
|
test_manager.get_allowed_mcp_servers = mock_get_allowed_servers
|
|
|
|
# Mock health_check_server to avoid real network calls that timeout
|
|
async def mock_health_check(server_id: str, mcp_auth_header=None):
|
|
server = test_manager.get_mcp_server_by_id(server_id)
|
|
if not server:
|
|
return None
|
|
return LiteLLM_MCPServerTable(
|
|
server_id=server_id,
|
|
server_name=server.name,
|
|
url=server.url,
|
|
transport=server.transport,
|
|
description=server.mcp_info.get("description") if server.mcp_info else None,
|
|
mcp_access_groups=server.access_groups,
|
|
status="healthy",
|
|
last_health_check=datetime.datetime.now(),
|
|
mcp_info=server.mcp_info,
|
|
)
|
|
|
|
test_manager.health_check_server = mock_health_check
|
|
|
|
# Test the method (this tests our second fix)
|
|
servers_list = await test_manager.get_all_mcp_servers_with_health_and_teams(
|
|
user_api_key_auth=mock_user_auth
|
|
)
|
|
|
|
# Verify we have the config server properly converted
|
|
assert len(servers_list) == 1
|
|
|
|
# Find the config server in the list
|
|
config_server_in_list = servers_list[0]
|
|
assert config_server_in_list.server_name == "config_server_with_groups"
|
|
assert config_server_in_list.mcp_access_groups == ["fr_staff", "admin"]
|
|
assert config_server_in_list.description == "Test config server"
|
|
|
|
# Verify the mcp_info is also correct
|
|
assert config_server_in_list.mcp_info["description"] == "Test config server"
|
|
assert config_server_in_list.mcp_info["server_name"] == "config_server_with_groups"
|
|
|
|
|
|
# Tests for Server Alias Functionality
|
|
def test_get_server_prefix_with_alias():
|
|
"""
|
|
Test that get_server_prefix returns alias when present.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server with alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "my_alias"
|
|
mock_server.server_name = "My Server Name"
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "my_alias"
|
|
|
|
|
|
def test_get_server_prefix_without_alias():
|
|
"""
|
|
Test that get_server_prefix falls back to server_name when alias is not present.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server without alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = None
|
|
mock_server.server_name = "My Server Name"
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "My Server Name"
|
|
|
|
|
|
def test_get_server_prefix_fallback_to_server_id():
|
|
"""
|
|
Test that get_server_prefix falls back to server_id when neither alias nor server_name are present.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server without alias or server_name
|
|
mock_server = MagicMock()
|
|
mock_server.alias = None
|
|
mock_server.server_name = None
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "server-123"
|
|
|
|
|
|
def test_get_server_prefix_empty_strings():
|
|
"""
|
|
Test that get_server_prefix handles empty strings correctly.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server with empty strings
|
|
mock_server = MagicMock()
|
|
mock_server.alias = ""
|
|
mock_server.server_name = ""
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "server-123"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_alias_tool_prefixing():
|
|
"""
|
|
Test that MCP server manager uses alias for tool prefixing when available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock server with alias
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server",
|
|
alias="my_alias",
|
|
server_name="Test Server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
)
|
|
|
|
# Add server to registry
|
|
test_manager.registry["test-server-123"] = mock_server
|
|
|
|
# Mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Get tools from server
|
|
tools = await test_manager._get_tools_from_server(mock_server)
|
|
|
|
# Verify tool is prefixed with alias
|
|
assert len(tools) == 1
|
|
assert tools[0].name == "my_alias-send_email"
|
|
|
|
# Verify mapping is updated correctly
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
|
|
== "my_alias"
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["my_alias-send_email"]
|
|
== "my_alias"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_server_name_tool_prefixing():
|
|
"""
|
|
Test that MCP server manager falls back to server_name for tool prefixing when alias is not available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock server without alias
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server",
|
|
alias=None,
|
|
server_name="Test Server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
)
|
|
|
|
# Add server to registry
|
|
test_manager.registry["test-server-123"] = mock_server
|
|
|
|
# Mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Get tools from server
|
|
tools = await test_manager._get_tools_from_server(mock_server)
|
|
|
|
# Verify tool is prefixed with server_name (normalized)
|
|
assert len(tools) == 1
|
|
assert tools[0].name == "Test_Server-send_email"
|
|
|
|
# Verify mapping is updated correctly
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
|
|
== "Test Server"
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["Test_Server-send_email"]
|
|
== "Test Server"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_server_id_tool_prefixing():
|
|
"""
|
|
Test that MCP server manager falls back to server_id for tool prefixing when neither alias nor server_name are available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock server without alias or server_name
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server",
|
|
alias=None,
|
|
server_name=None,
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
)
|
|
|
|
# Add server to registry
|
|
test_manager.registry["test-server-123"] = mock_server
|
|
|
|
# Mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Get tools from server
|
|
tools = await test_manager._get_tools_from_server(mock_server)
|
|
|
|
# Verify tool is prefixed with server_id
|
|
assert len(tools) == 1
|
|
assert tools[0].name == "test-server-123-send_email"
|
|
|
|
# Verify mapping is updated correctly
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
|
|
== "test-server-123"
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping[
|
|
"test-server-123-send_email"
|
|
]
|
|
== "test-server-123"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_update_server_with_alias():
|
|
"""
|
|
Test that add_update_server correctly handles servers with alias.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock LiteLLM_MCPServerTable with alias
|
|
mock_mcp_server = MagicMock()
|
|
mock_mcp_server.server_id = "test-server-123"
|
|
mock_mcp_server.alias = "my_alias"
|
|
mock_mcp_server.server_name = "Test Server"
|
|
mock_mcp_server.url = "https://test-server.com/mcp"
|
|
mock_mcp_server.transport = MCPTransport.http
|
|
mock_mcp_server.auth_type = None
|
|
mock_mcp_server.credentials = {}
|
|
mock_mcp_server.description = "Test server description"
|
|
mock_mcp_server.mcp_info = {}
|
|
mock_mcp_server.static_headers = {}
|
|
mock_mcp_server.command = None
|
|
mock_mcp_server.args = []
|
|
mock_mcp_server.env = None
|
|
mock_mcp_server.spec_path = None
|
|
# OAuth fields - set explicitly to None to avoid MagicMock objects
|
|
mock_mcp_server.client_id = None
|
|
mock_mcp_server.client_secret = None
|
|
mock_mcp_server.authorization_url = None
|
|
mock_mcp_server.registration_url = None
|
|
mock_mcp_server.token_url = None
|
|
mock_mcp_server.oauth2_flow = None
|
|
# Additional fields used by build_mcp_server_from_table
|
|
mock_mcp_server.extra_headers = None
|
|
mock_mcp_server.allow_all_keys = False
|
|
mock_mcp_server.available_on_public_internet = True
|
|
mock_mcp_server.mcp_access_groups = None
|
|
mock_mcp_server.allowed_tools = None
|
|
mock_mcp_server.disallowed_tools = None
|
|
mock_mcp_server.tool_name_to_display_name = None
|
|
mock_mcp_server.tool_name_to_description = None
|
|
mock_mcp_server.is_byok = False
|
|
mock_mcp_server.byok_description = None
|
|
mock_mcp_server.byok_api_key_help_url = None
|
|
mock_mcp_server.created_at = None
|
|
mock_mcp_server.updated_at = None
|
|
mock_mcp_server.instructions = None
|
|
mock_mcp_server.source_url = None
|
|
mock_mcp_server.approval_status = "active"
|
|
|
|
# Add server to manager
|
|
await test_manager.add_server(mock_mcp_server)
|
|
|
|
# Verify server was added with correct name (should use alias)
|
|
assert "test-server-123" in test_manager.registry
|
|
added_server = test_manager.registry["test-server-123"]
|
|
assert added_server.name == "my_alias"
|
|
assert added_server.alias == "my_alias"
|
|
assert added_server.server_name == "Test Server"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_update_server_without_alias():
|
|
"""
|
|
Test that add_update_server correctly handles servers without alias.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock LiteLLM_MCPServerTable without alias
|
|
mock_mcp_server = MagicMock()
|
|
mock_mcp_server.server_id = "test-server-123"
|
|
mock_mcp_server.alias = None
|
|
mock_mcp_server.server_name = "Test Server"
|
|
mock_mcp_server.url = "https://test-server.com/mcp"
|
|
mock_mcp_server.transport = MCPTransport.http
|
|
mock_mcp_server.auth_type = None
|
|
mock_mcp_server.credentials = {}
|
|
mock_mcp_server.description = "Test server description"
|
|
mock_mcp_server.mcp_info = {}
|
|
mock_mcp_server.static_headers = {}
|
|
mock_mcp_server.command = None
|
|
mock_mcp_server.args = []
|
|
mock_mcp_server.env = None
|
|
mock_mcp_server.spec_path = None
|
|
# OAuth fields - set explicitly to None to avoid MagicMock objects
|
|
mock_mcp_server.client_id = None
|
|
mock_mcp_server.client_secret = None
|
|
mock_mcp_server.authorization_url = None
|
|
mock_mcp_server.registration_url = None
|
|
mock_mcp_server.token_url = None
|
|
mock_mcp_server.oauth2_flow = None
|
|
# Additional fields used by build_mcp_server_from_table
|
|
mock_mcp_server.extra_headers = None
|
|
mock_mcp_server.allow_all_keys = False
|
|
mock_mcp_server.available_on_public_internet = True
|
|
mock_mcp_server.mcp_access_groups = None
|
|
mock_mcp_server.allowed_tools = None
|
|
mock_mcp_server.disallowed_tools = None
|
|
mock_mcp_server.tool_name_to_display_name = None
|
|
mock_mcp_server.tool_name_to_description = None
|
|
mock_mcp_server.is_byok = False
|
|
mock_mcp_server.byok_description = None
|
|
mock_mcp_server.byok_api_key_help_url = None
|
|
mock_mcp_server.created_at = None
|
|
mock_mcp_server.updated_at = None
|
|
mock_mcp_server.instructions = None
|
|
mock_mcp_server.source_url = None
|
|
mock_mcp_server.approval_status = "active"
|
|
|
|
# Add server to manager
|
|
await test_manager.add_server(mock_mcp_server)
|
|
|
|
# Verify server was added with correct name (should use server_name)
|
|
assert "test-server-123" in test_manager.registry
|
|
added_server = test_manager.registry["test-server-123"]
|
|
assert added_server.name == "Test Server"
|
|
assert added_server.alias is None
|
|
assert added_server.server_name == "Test Server"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_update_server_fallback_to_server_id():
|
|
"""
|
|
Test that add_update_server falls back to server_id when neither alias nor server_name are available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock LiteLLM_MCPServerTable without alias or server_name
|
|
mock_mcp_server = MagicMock()
|
|
mock_mcp_server.server_id = "test-server-123"
|
|
mock_mcp_server.alias = None
|
|
mock_mcp_server.server_name = None
|
|
mock_mcp_server.url = "https://test-server.com/mcp"
|
|
mock_mcp_server.transport = MCPTransport.http
|
|
mock_mcp_server.auth_type = None
|
|
mock_mcp_server.credentials = {}
|
|
mock_mcp_server.description = "Test server description"
|
|
mock_mcp_server.mcp_info = {}
|
|
mock_mcp_server.static_headers = {}
|
|
mock_mcp_server.command = None
|
|
mock_mcp_server.args = []
|
|
mock_mcp_server.env = None
|
|
mock_mcp_server.spec_path = None
|
|
# OAuth fields - set explicitly to None to avoid MagicMock objects
|
|
mock_mcp_server.client_id = None
|
|
mock_mcp_server.client_secret = None
|
|
mock_mcp_server.authorization_url = None
|
|
mock_mcp_server.registration_url = None
|
|
mock_mcp_server.token_url = None
|
|
mock_mcp_server.oauth2_flow = None
|
|
# Additional fields used by build_mcp_server_from_table - set explicitly
|
|
# to avoid MagicMock objects being passed to Pydantic MCPServer constructor
|
|
mock_mcp_server.extra_headers = None
|
|
mock_mcp_server.allow_all_keys = False
|
|
mock_mcp_server.available_on_public_internet = True
|
|
mock_mcp_server.mcp_access_groups = None
|
|
mock_mcp_server.allowed_tools = None
|
|
mock_mcp_server.disallowed_tools = None
|
|
mock_mcp_server.tool_name_to_display_name = None
|
|
mock_mcp_server.tool_name_to_description = None
|
|
mock_mcp_server.is_byok = False
|
|
mock_mcp_server.byok_description = None
|
|
mock_mcp_server.byok_api_key_help_url = None
|
|
mock_mcp_server.created_at = None
|
|
mock_mcp_server.updated_at = None
|
|
mock_mcp_server.instructions = None
|
|
mock_mcp_server.source_url = None
|
|
mock_mcp_server.approval_status = "active"
|
|
# Add server to manager
|
|
await test_manager.add_server(mock_mcp_server)
|
|
|
|
# Verify server was added with correct name (should use server_id)
|
|
assert "test-server-123" in test_manager.registry
|
|
added_server = test_manager.registry["test-server-123"]
|
|
assert added_server.name == "test-server-123"
|
|
assert added_server.alias is None
|
|
assert added_server.server_name is None
|
|
|
|
|
|
def test_normalize_server_name():
|
|
"""
|
|
Test that normalize_server_name correctly replaces spaces with underscores.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import normalize_server_name
|
|
|
|
# Test basic space replacement
|
|
assert normalize_server_name("My Server Name") == "My_Server_Name"
|
|
|
|
# Test multiple consecutive spaces
|
|
assert normalize_server_name("My Server Name") == "My__Server___Name"
|
|
|
|
# Test no spaces
|
|
assert normalize_server_name("MyServerName") == "MyServerName"
|
|
|
|
# Test empty string
|
|
assert normalize_server_name("") == ""
|
|
|
|
# Test string with only spaces
|
|
assert normalize_server_name(" ") == "___"
|
|
|
|
|
|
def test_add_server_prefix_to_name():
|
|
"""Ensure add_server_prefix_to_name correctly formats resource names."""
|
|
from litellm.proxy._experimental.mcp_server.utils import add_server_prefix_to_name
|
|
|
|
# Test basic prefixing
|
|
result = add_server_prefix_to_name("send_email", "My Server")
|
|
assert result == "My_Server-send_email"
|
|
|
|
# Test with server name that already has underscores
|
|
result = add_server_prefix_to_name("create_event", "my_server")
|
|
assert result == "my_server-create_event"
|
|
|
|
# Test with empty name
|
|
result = add_server_prefix_to_name("", "My Server")
|
|
assert result == "My_Server-"
|
|
|
|
# Test with empty server name
|
|
result = add_server_prefix_to_name("send_email", "")
|
|
assert result == "-send_email"
|
|
|
|
|
|
def test_get_server_auth_header_with_alias():
|
|
"""Test _get_server_auth_header function with server alias."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server with alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "zapier"
|
|
mock_server.server_name = "zapier_server"
|
|
|
|
# Test with server-specific auth headers
|
|
mcp_server_auth_headers = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
mcp_auth_header = "Bearer default_token"
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer zapier_token"
|
|
|
|
# Test case-insensitive matching
|
|
mcp_server_auth_headers = {
|
|
"ZAPIER": "Bearer zapier_token_upper",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer zapier_token_upper"
|
|
|
|
|
|
def test_get_server_auth_header_with_server_name():
|
|
"""Test _get_server_auth_header function with server name (no alias)."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server with server_name but no alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = None
|
|
mock_server.server_name = "slack_server"
|
|
|
|
# Test with server-specific auth headers
|
|
mcp_server_auth_headers = {
|
|
"slack_server": "Bearer slack_token",
|
|
"zapier": "Bearer zapier_token",
|
|
}
|
|
mcp_auth_header = "Bearer default_token"
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer slack_token"
|
|
|
|
# Test case-insensitive matching
|
|
mcp_server_auth_headers = {
|
|
"SLACK_SERVER": "Bearer slack_token_upper",
|
|
"zapier": "Bearer zapier_token",
|
|
}
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer slack_token_upper"
|
|
|
|
|
|
def test_get_server_auth_header_fallback_to_default():
|
|
"""Test _get_server_auth_header function fallback to default auth header."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "unknown_server"
|
|
mock_server.server_name = "unknown_server_name"
|
|
|
|
# Test with no matching server-specific headers
|
|
mcp_server_auth_headers = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
mcp_auth_header = "Bearer default_token"
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer default_token"
|
|
|
|
# Test with no server-specific headers at all
|
|
result = _get_server_auth_header(mock_server, None, mcp_auth_header)
|
|
assert result == "Bearer default_token"
|
|
|
|
|
|
def test_get_server_auth_header_hyphenated_alias_sanitized_header_key():
|
|
"""Header keys use sanitized alias; lookup must match legacy hyphenated aliases."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "GitHub-MCP"
|
|
mock_server.server_name = "github_mcp_server"
|
|
|
|
mcp_server_auth_headers = {
|
|
"github_mcp": {"Authorization": "Bearer github-mcp-token"},
|
|
}
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, "Bearer default_token"
|
|
)
|
|
assert result == {"Authorization": "Bearer github-mcp-token"}
|
|
|
|
|
|
def test_get_server_auth_header_no_auth_headers():
|
|
"""Test _get_server_auth_header function with no auth headers."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "zapier"
|
|
mock_server.server_name = "zapier_server"
|
|
|
|
# Test with no auth headers
|
|
result = _get_server_auth_header(mock_server, None, None)
|
|
assert result is None
|
|
|
|
result = _get_server_auth_header(mock_server, {}, None)
|
|
assert result is None
|
|
|
|
|
|
def test_create_tool_response_objects():
|
|
"""Test _create_tool_response_objects function."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_create_tool_response_objects,
|
|
)
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object", "properties": {"to": {"type": "string"}}},
|
|
),
|
|
MCPTool(
|
|
name="create_event",
|
|
description="Create a calendar event",
|
|
inputSchema={"type": "object", "properties": {"title": {"type": "string"}}},
|
|
),
|
|
]
|
|
|
|
server_mcp_info = {
|
|
"server_name": "zapier",
|
|
"logo_url": "https://zapier.com/logo.png",
|
|
}
|
|
|
|
result = _create_tool_response_objects(mock_tools, server_mcp_info)
|
|
|
|
assert len(result) == 2
|
|
assert result[0].name == "send_email"
|
|
assert result[0].description == "Send an email"
|
|
assert result[0].mcp_info == server_mcp_info
|
|
assert result[1].name == "create_event"
|
|
assert result[1].description == "Create a calendar event"
|
|
assert result[1].mcp_info == server_mcp_info
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_tools_for_single_server():
|
|
"""Test _get_tools_for_single_server function."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_tools_for_single_server,
|
|
)
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock server (pin allowlist fields; MagicMock auto-attrs are truthy)
|
|
mock_server = MagicMock()
|
|
mock_server.mcp_info = {"server_name": "zapier"}
|
|
mock_server.allowed_tools = None
|
|
mock_server.disallowed_tools = None
|
|
|
|
# Create mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object", "properties": {"to": {"type": "string"}}},
|
|
)
|
|
]
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
result = await _get_tools_for_single_server(mock_server, "Bearer test_token")
|
|
|
|
# Verify the manager was called with correct parameters
|
|
mock_manager._get_tools_from_server.assert_called_once_with(
|
|
server=mock_server,
|
|
mcp_auth_header="Bearer test_token",
|
|
extra_headers=None,
|
|
add_prefix=False,
|
|
raw_headers=None,
|
|
user_api_key_auth=None,
|
|
)
|
|
|
|
# Verify the result
|
|
assert len(result) == 1
|
|
assert result[0].name == "send_email"
|
|
assert result[0].mcp_info == {"server_name": "zapier"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_tools_for_single_server_applies_disallowed_tools_without_allowlist():
|
|
"""REST listing must honor disallowed_tools even when no allowlist is set."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_tools_for_single_server,
|
|
)
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
mock_server = MagicMock()
|
|
mock_server.mcp_info = {"server_name": "zapier"}
|
|
mock_server.name = "zapier"
|
|
mock_server.server_id = "zapier"
|
|
mock_server.allowed_tools = None
|
|
mock_server.disallowed_tools = ["send_email"]
|
|
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="read_email",
|
|
description="Read an email",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
result = await _get_tools_for_single_server(mock_server, "Bearer test_token")
|
|
|
|
assert [tool.name for tool in result] == ["read_email"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tool_rest_api_with_server_specific_auth():
|
|
"""Test list_tool_rest_api with server-specific auth headers."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create mock request with server-specific auth headers
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {
|
|
"authorization": "Bearer user_token",
|
|
"x-mcp-zapier-authorization": "Bearer zapier_token",
|
|
"x-mcp-slack-authorization": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the MCPRequestHandler methods
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_auth_header_from_headers"
|
|
) as mock_get_auth:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
|
|
) as mock_get_server_auth:
|
|
mock_get_auth.return_value = "Bearer default_token"
|
|
mock_get_server_auth.return_value = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.server_id = "test-server-123"
|
|
mock_server.alias = "zapier"
|
|
mock_server.name = "zapier_server"
|
|
mock_server.mcp_info = {"server_name": "zapier"}
|
|
|
|
mock_manager.get_mcp_server_by_id.return_value = mock_server
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
mock_user_api_key_dict = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test_user",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=[mock_server.server_id],
|
|
),
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
|
|
mock_tools = [
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "zapier"},
|
|
)
|
|
]
|
|
mock_get_tools.return_value = mock_tools
|
|
|
|
# Call the function
|
|
result = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="test-server-123",
|
|
user_api_key_dict=mock_user_api_key_dict,
|
|
)
|
|
|
|
# Verify the result
|
|
assert result["error"] is None
|
|
assert len(result["tools"]) == 1
|
|
assert result["tools"][0].name == "send_email"
|
|
|
|
# Verify that _get_tools_for_single_server was called with the correct auth header
|
|
mock_get_tools.assert_called_once()
|
|
call_args = mock_get_tools.call_args
|
|
assert call_args[0][0] == mock_server # server
|
|
assert (
|
|
call_args[0][1] == "Bearer zapier_token"
|
|
) # server_auth_header
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tool_rest_api_with_default_auth():
|
|
"""Test list_tool_rest_api with default auth header when no server-specific header is found."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create mock request with default auth header only
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {
|
|
"authorization": "Bearer user_token",
|
|
"x-mcp-authorization": "Bearer default_token",
|
|
}
|
|
|
|
# Mock the MCPRequestHandler methods
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_auth_header_from_headers"
|
|
) as mock_get_auth:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
|
|
) as mock_get_server_auth:
|
|
mock_get_auth.return_value = "Bearer default_token"
|
|
mock_get_server_auth.return_value = {} # No server-specific headers
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.server_id = "test-server-123"
|
|
mock_server.alias = "unknown_server"
|
|
mock_server.name = "unknown_server"
|
|
mock_server.mcp_info = {"server_name": "unknown_server"}
|
|
|
|
mock_manager.get_mcp_server_by_id.return_value = mock_server
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
mock_user_api_key_dict = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test_user",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=[mock_server.server_id],
|
|
),
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
|
|
mock_tools = [
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "unknown_server"},
|
|
)
|
|
]
|
|
mock_get_tools.return_value = mock_tools
|
|
|
|
# Call the function
|
|
result = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="test-server-123",
|
|
user_api_key_dict=mock_user_api_key_dict,
|
|
)
|
|
|
|
# Verify the result
|
|
assert result["error"] is None
|
|
assert len(result["tools"]) == 1
|
|
assert result["tools"][0].name == "send_email"
|
|
|
|
# Verify that _get_tools_for_single_server was called with the default auth header
|
|
mock_get_tools.assert_called_once()
|
|
call_args = mock_get_tools.call_args
|
|
assert call_args[0][0] == mock_server # server
|
|
assert (
|
|
call_args[0][1] == "Bearer default_token"
|
|
) # server_auth_header
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tool_rest_api_all_servers_with_auth():
|
|
"""Test list_tool_rest_api for all servers with server-specific auth headers."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create mock request with server-specific auth headers
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {
|
|
"authorization": "Bearer user_token",
|
|
"x-mcp-zapier-authorization": "Bearer zapier_token",
|
|
"x-mcp-slack-authorization": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the MCPRequestHandler methods
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_auth_header_from_headers"
|
|
) as mock_get_auth:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
|
|
) as mock_get_server_auth:
|
|
mock_get_auth.return_value = "Bearer default_token"
|
|
mock_get_server_auth.return_value = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Create mock servers
|
|
mock_zapier_server = MagicMock()
|
|
mock_zapier_server.alias = "zapier"
|
|
mock_zapier_server.server_name = "zapier_server"
|
|
mock_zapier_server.mcp_info = {"server_name": "zapier"}
|
|
|
|
mock_slack_server = MagicMock()
|
|
mock_slack_server.alias = "slack"
|
|
mock_slack_server.server_name = "slack_server"
|
|
mock_slack_server.mcp_info = {"server_name": "slack"}
|
|
|
|
mock_manager.get_registry.return_value = {
|
|
"zapier": mock_zapier_server,
|
|
"slack": mock_slack_server,
|
|
}
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["zapier", "slack"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id.side_effect = (
|
|
lambda server_id: mock_manager.get_registry.return_value.get(
|
|
server_id
|
|
)
|
|
)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
mock_user_api_key_dict = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test_user",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=["zapier", "slack"],
|
|
),
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
|
|
# Mock tools for each server
|
|
mock_get_tools.side_effect = [
|
|
[
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "zapier"},
|
|
)
|
|
],
|
|
[
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_message",
|
|
description="Send a message",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "slack"},
|
|
)
|
|
],
|
|
]
|
|
|
|
# Call the function without server_id (query all servers)
|
|
result = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id=None,
|
|
user_api_key_dict=mock_user_api_key_dict,
|
|
)
|
|
|
|
# Verify the result
|
|
assert result["error"] is None
|
|
assert len(result["tools"]) == 2
|
|
assert result["tools"][0].name == "send_email"
|
|
assert result["tools"][1].name == "send_message"
|
|
|
|
# Verify that _get_tools_for_single_server was called for both servers
|
|
assert mock_get_tools.call_count == 2
|
|
server_auth_map = {
|
|
call_args[0][0]: call_args[0][1]
|
|
for call_args in mock_get_tools.call_args_list
|
|
}
|
|
|
|
assert (
|
|
server_auth_map.get(mock_zapier_server) == "Bearer zapier_token"
|
|
)
|
|
assert (
|
|
server_auth_map.get(mock_slack_server) == "Bearer slack_token"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_filter_tools_by_allowed_tools_integration():
|
|
"""Test that filter_tools_by_allowed_tools works correctly via _get_tools_from_mcp_servers"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock user auth
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
|
|
# Create mock tools that will be returned by the server
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="allowed_tool_1",
|
|
description="This tool should be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="allowed_tool_2",
|
|
description="This tool should also be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="blocked_tool_1",
|
|
description="This tool should be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="blocked_tool_2",
|
|
description="This tool should also be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
# Create a mock server with allowed_tools restriction
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server_with_allowed_tools",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
allowed_tools=[
|
|
"allowed_tool_1",
|
|
"allowed_tool_2",
|
|
], # Only these tools should be returned
|
|
disallowed_tools=None,
|
|
)
|
|
|
|
# Create a mock MCPClient that returns all tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
# Mock the global MCP server manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Mock manager methods
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
# Mock the _get_tools_from_server method to return all tools
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
# Mock the MCPClient constructor
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call _get_tools_from_mcp_servers which should apply the filtering
|
|
filtered_tools = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header="Bearer test_token",
|
|
mcp_servers=None, # Get from all servers
|
|
)
|
|
|
|
# Verify that only allowed tools are returned
|
|
assert (
|
|
len(filtered_tools) == 2
|
|
), f"Expected 2 tools, got {len(filtered_tools)}"
|
|
|
|
tool_names = [tool.name for tool in filtered_tools]
|
|
assert (
|
|
"allowed_tool_1" in tool_names
|
|
), "allowed_tool_1 should be in filtered results"
|
|
assert (
|
|
"allowed_tool_2" in tool_names
|
|
), "allowed_tool_2 should be in filtered results"
|
|
assert (
|
|
"blocked_tool_1" not in tool_names
|
|
), "blocked_tool_1 should be filtered out"
|
|
assert (
|
|
"blocked_tool_2" not in tool_names
|
|
), "blocked_tool_2 should be filtered out"
|
|
|
|
# Verify the manager methods were called correctly
|
|
mock_manager.get_allowed_mcp_servers.assert_called_once_with(mock_user_auth)
|
|
# Note: get_mcp_server_by_id is now called for each server ID instead of batch
|
|
# Verify it was called with the correct server ID
|
|
assert mock_manager.get_mcp_server_by_id.call_count > 0
|
|
mock_manager._get_tools_from_server.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_filter_tools_by_disallowed_tools_integration():
|
|
"""Test that filter_tools_by_allowed_tools works correctly with disallowed_tools via _get_tools_from_mcp_servers"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock user auth
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
|
|
# Create mock tools that will be returned by the server
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="safe_tool_1",
|
|
description="This tool should be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="safe_tool_2",
|
|
description="This tool should also be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="dangerous_tool_1",
|
|
description="This tool should be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="dangerous_tool_2",
|
|
description="This tool should also be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
# Create a mock server with disallowed_tools restriction
|
|
mock_server = MCPServer(
|
|
server_id="test-server-456",
|
|
name="test_server_with_disallowed_tools",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
allowed_tools=None,
|
|
disallowed_tools=[
|
|
"dangerous_tool_1",
|
|
"dangerous_tool_2",
|
|
], # These tools should be filtered out
|
|
)
|
|
|
|
# Create a mock MCPClient that returns all tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
# Mock the global MCP server manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Mock manager methods
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-456"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
# Mock the _get_tools_from_server method to return all tools
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
# Mock the MCPClient constructor
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call _get_tools_from_mcp_servers which should apply the filtering
|
|
filtered_tools = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header="Bearer test_token",
|
|
mcp_servers=None, # Get from all servers
|
|
)
|
|
|
|
# Verify that only safe tools are returned (dangerous tools filtered out)
|
|
assert (
|
|
len(filtered_tools) == 2
|
|
), f"Expected 2 tools, got {len(filtered_tools)}"
|
|
|
|
tool_names = [tool.name for tool in filtered_tools]
|
|
assert (
|
|
"safe_tool_1" in tool_names
|
|
), "safe_tool_1 should be in filtered results"
|
|
assert (
|
|
"safe_tool_2" in tool_names
|
|
), "safe_tool_2 should be in filtered results"
|
|
assert (
|
|
"dangerous_tool_1" not in tool_names
|
|
), "dangerous_tool_1 should be filtered out"
|
|
assert (
|
|
"dangerous_tool_2" not in tool_names
|
|
), "dangerous_tool_2 should be filtered out"
|
|
|
|
# Verify the manager methods were called correctly
|
|
mock_manager.get_allowed_mcp_servers.assert_called_once_with(mock_user_auth)
|
|
# Note: get_mcp_server_by_id is now called for each server ID instead of batch
|
|
# Verify it was called with the correct server ID
|
|
assert mock_manager.get_mcp_server_by_id.call_count > 0
|
|
mock_manager._get_tools_from_server.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_filter_tools_no_restrictions_integration():
|
|
"""Test that filter_tools_by_allowed_tools returns all tools when no restrictions are set"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock user auth
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
|
|
# Create mock tools that will be returned by the server
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="tool_1",
|
|
description="Tool 1",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="tool_2",
|
|
description="Tool 2",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
# Create a mock server with no tool restrictions
|
|
mock_server = MCPServer(
|
|
server_id="test-server-000",
|
|
name="test_server_no_restrictions",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
allowed_tools=None, # No restrictions
|
|
disallowed_tools=None, # No restrictions
|
|
)
|
|
|
|
# Create a mock MCPClient that returns all tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
# Mock the global MCP server manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Mock manager methods
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-000"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
# Mock the _get_tools_from_server method to return all tools
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
# Mock the MCPClient constructor
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call _get_tools_from_mcp_servers which should apply the filtering
|
|
filtered_tools = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header="Bearer test_token",
|
|
mcp_servers=None, # Get from all servers
|
|
)
|
|
|
|
# Should return all tools when no restrictions
|
|
assert (
|
|
len(filtered_tools) == 2
|
|
), f"Expected 2 tools, got {len(filtered_tools)}"
|
|
|
|
tool_names = [tool.name for tool in filtered_tools]
|
|
assert "tool_1" in tool_names, "tool_1 should be in filtered results"
|
|
assert "tool_2" in tool_names, "tool_2 should be in filtered results"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_access_group_permission_inheritance_integration():
|
|
"""Integration test for MCP access group permission inheritance"""
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Test scenario: team has access groups, key has no permissions -> should inherit
|
|
# Use direct mocking of the helper functions instead of complex database mocking
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_key"
|
|
) as mock_key:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
|
|
) as mock_team:
|
|
# Key has no permissions, team has servers
|
|
mock_key.return_value = [] # Key inherits nothing directly
|
|
mock_team.return_value = [
|
|
"staff-server-1",
|
|
"staff-server-2",
|
|
"ops-server-1",
|
|
] # Team has servers
|
|
|
|
# Create user auth object
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="test-key",
|
|
user_id="test-user",
|
|
team_id="team-staff",
|
|
object_permission_id=None, # Key has no explicit permissions
|
|
)
|
|
|
|
# Test the inheritance logic
|
|
allowed_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_auth)
|
|
|
|
# Should inherit all team servers since key has no permissions
|
|
expected_servers = ["staff-server-1", "staff-server-2", "ops-server-1"]
|
|
assert sorted(allowed_servers) == sorted(expected_servers)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_access_group_permission_intersection_integration():
|
|
"""Integration test for MCP access group permission intersection"""
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Test scenario: both team and key have access groups -> should intersect
|
|
# Use direct mocking of the helper functions instead of complex database mocking
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_key"
|
|
) as mock_key:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
|
|
) as mock_team:
|
|
# Both key and team have permissions - should intersect
|
|
mock_key.return_value = [
|
|
"ops-server",
|
|
"external-server",
|
|
] # Key has these servers
|
|
mock_team.return_value = [
|
|
"staff-server",
|
|
"ops-server",
|
|
"admin-server",
|
|
] # Team has these servers
|
|
|
|
# Create user auth object
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="test-key",
|
|
user_id="test-user",
|
|
team_id="team-staff",
|
|
object_permission_id="key-permission-id", # Key has explicit permissions
|
|
)
|
|
|
|
# Test the intersection logic
|
|
allowed_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_auth)
|
|
|
|
# Should only get intersection (ops-server is common)
|
|
expected_servers = ["ops-server"]
|
|
assert sorted(allowed_servers) == sorted(expected_servers)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_with_access_groups_integration():
|
|
"""Integration test for MCPServerManager with access group filtering"""
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create a test manager
|
|
test_manager = MCPServerManager()
|
|
|
|
# Load servers with access groups
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"staff_server": {
|
|
"url": "https://staff-server.com/mcp",
|
|
"access_groups": ["staff"],
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"ops_server": {
|
|
"url": "https://ops-server.com/mcp",
|
|
"access_groups": ["ops"],
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"admin_server": {
|
|
"url": "https://admin-server.com/mcp",
|
|
"access_groups": ["admin"],
|
|
"transport": MCPTransport.http,
|
|
},
|
|
}
|
|
)
|
|
|
|
# Mock user with specific access groups
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="test-key", user_id="test-user", team_id="team-staff"
|
|
)
|
|
|
|
# Mock the permission lookup to return staff access group
|
|
with patch.object(MCPRequestHandler, "get_allowed_mcp_servers") as mock_get_allowed:
|
|
mock_get_allowed.return_value = [
|
|
"staff-server-id",
|
|
"ops-server-id",
|
|
] # User has access to staff and ops
|
|
|
|
allowed_servers = await test_manager.get_allowed_mcp_servers(user_auth)
|
|
|
|
# Should only get servers user has access to
|
|
assert len(allowed_servers) >= 0 # At least verify no errors
|
|
mock_get_allowed.assert_called_once_with(user_auth)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_allowed_mcp_servers_returns_registry_for_admin():
|
|
from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
|
|
test_manager = MCPServerManager()
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"alpha_server": {
|
|
"url": "https://alpha.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"beta_server": {
|
|
"url": "https://beta.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
}
|
|
)
|
|
|
|
admin_auth = UserAPIKeyAuth(
|
|
api_key="admin-key",
|
|
user_role=LitellmUserRoles.PROXY_ADMIN,
|
|
)
|
|
|
|
with patch.object(
|
|
MCPRequestHandler, "get_allowed_mcp_servers", new_callable=AsyncMock
|
|
) as mock_permission_lookup:
|
|
allowed_servers = await test_manager.get_allowed_mcp_servers(admin_auth)
|
|
|
|
assert set(allowed_servers) == set(test_manager.get_registry().keys())
|
|
mock_permission_lookup.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_allowed_mcp_servers_returns_empty_for_non_admin_without_permissions():
|
|
from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
|
|
test_manager = MCPServerManager()
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"alpha_server": {
|
|
"url": "https://alpha.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"beta_server": {
|
|
"url": "https://beta.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
}
|
|
)
|
|
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="user-key",
|
|
user_role=LitellmUserRoles.INTERNAL_USER,
|
|
)
|
|
|
|
with patch.object(
|
|
MCPRequestHandler, "get_allowed_mcp_servers", new_callable=AsyncMock
|
|
) as mock_permission_lookup:
|
|
mock_permission_lookup.return_value = []
|
|
allowed_servers = await test_manager.get_allowed_mcp_servers(user_auth)
|
|
|
|
assert allowed_servers == []
|
|
mock_permission_lookup.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_mcp_tool_uses_manager_permission_lookup():
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
call_mcp_tool,
|
|
global_mcp_server_manager,
|
|
)
|
|
|
|
mock_server = MCPServer(
|
|
server_id="server-123",
|
|
name="test_server",
|
|
alias="test_server",
|
|
server_name="test_server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
mcp_info={"server_name": "test_server"},
|
|
)
|
|
|
|
expected_response = [TextContent(type="text", text="ok")]
|
|
|
|
with (
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_allowed_mcp_servers",
|
|
new_callable=AsyncMock,
|
|
) as mock_get_allowed,
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_mcp_server_by_id",
|
|
return_value=mock_server,
|
|
),
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"_get_mcp_server_from_tool_name",
|
|
return_value=mock_server,
|
|
) as mock_get_server,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_tool_registry"
|
|
) as mock_tool_registry,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._handle_managed_mcp_tool",
|
|
new_callable=AsyncMock,
|
|
) as mock_handle_managed,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",
|
|
return_value=True,
|
|
),
|
|
):
|
|
mock_get_allowed.return_value = [mock_server.server_id]
|
|
mock_tool_registry.get_tool.return_value = None
|
|
mock_handle_managed.return_value = expected_response
|
|
|
|
result = await call_mcp_tool(
|
|
name=f"{mock_server.name}/gmail_send_email",
|
|
arguments={"body": "hello"},
|
|
mcp_servers=["test_server"],
|
|
)
|
|
|
|
assert result == expected_response
|
|
mock_get_allowed.assert_awaited_once()
|
|
# We call `_get_mcp_server_from_tool_name` multiple times:
|
|
# - for logging/metadata
|
|
# - for resolving the server during dispatch
|
|
# - and inside `call_tool` for guardrails/hooks
|
|
# The exact count isn't important, only that it is used.
|
|
assert mock_get_server.call_count >= 2
|
|
# First call should use the prefixed tool name
|
|
assert (
|
|
mock_get_server.call_args_list[0][0][0]
|
|
== f"{mock_server.name}/gmail_send_email"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_mcp_tool_resolves_unprefixed_tool_name_and_checks_permissions():
|
|
"""
|
|
Ensure `call_mcp_tool` correctly resolves the MCP server for an unprefixed tool
|
|
name and enforces server-level permissions using that resolved server.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
call_mcp_tool,
|
|
global_mcp_server_manager,
|
|
)
|
|
|
|
mock_server = MCPServer(
|
|
server_id="server-123",
|
|
name="test_server",
|
|
alias="test_server",
|
|
server_name="test_server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
mcp_info={"server_name": "test_server"},
|
|
)
|
|
|
|
expected_response = [TextContent(type="text", text="ok")]
|
|
|
|
with (
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_allowed_mcp_servers",
|
|
new_callable=AsyncMock,
|
|
) as mock_get_allowed,
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_mcp_server_by_id",
|
|
return_value=mock_server,
|
|
),
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"_get_mcp_server_from_tool_name",
|
|
return_value=mock_server,
|
|
) as mock_get_server,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_tool_registry"
|
|
) as mock_tool_registry,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._handle_managed_mcp_tool",
|
|
new_callable=AsyncMock,
|
|
) as mock_handle_managed,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",
|
|
return_value=True,
|
|
) as mock_is_allowed,
|
|
):
|
|
mock_get_allowed.return_value = [mock_server.server_id]
|
|
mock_tool_registry.get_tool.return_value = None
|
|
mock_handle_managed.return_value = expected_response
|
|
|
|
# Call with UNPREFIXED tool name; server should be resolved via mapping
|
|
result = await call_mcp_tool(
|
|
name="gmail_send_email",
|
|
arguments={"body": "hello"},
|
|
mcp_servers=["test_server"],
|
|
)
|
|
|
|
assert result == expected_response
|
|
mock_get_allowed.assert_awaited_once()
|
|
# We should resolve the server at least once using the unprefixed name
|
|
assert mock_get_server.call_count >= 1
|
|
assert mock_get_server.call_args_list[0][0][0] == "gmail_send_email"
|
|
# Permissions check should be invoked with the resolved server name
|
|
mock_is_allowed.assert_called_once()
|