Skip to content

feat(mcp): relay authorized modern upstream subscriptions - #46153

Merged
joshua-berri merged 7 commits into
mainfrom
litellm_mcp_notification_subscriptions
Oct 15, 2026
Merged

joshua-berri merged 7 commits into
mainfrom
litellm_mcp_notification_subscriptions

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Restack verification pending: Current head 00a41f4993350ada008bfdd2e7a8ee9f86a0ef22 follows PR1 squash merge. Earlier tip-specific evidence below is historical. Local lint/type and affected tests passed (one known unrelated environment-origin failure); fresh CI, completed coverage, bot reviews, and independent verification are pending.

Ready for review: head d80e42a7926a4e2cf2118d9be78bedeec0a676cf, base 163c474de8101e0e2d319107f91b24f6c64a935f. Local changed executable-line coverage is 368/374 (98.4%); completed current-tip Codecov patch coverage is 98.39%. Independent live verification passed 23/23 cases, with 44/44 mapped cases on identical production source. Current-tip Veria and Bugbot reviews are clear; zero unresolved threads. Final evidence.

TLDR

Problem this solves:

  • MCP clients miss upstream changes between tool calls

How it solves it:

  • Relay SDK subscriptions and legacy notifications through caller-scoped streams
  • Recheck authorization before delivery and during idle periods
  • Refresh visible catalogs and release disconnected upstream listeners

User Flow

Before, subscribing through the gateway returns Method not found

  1. Discover modern protocol support at $GATEWAY_URL/mcp/
  2. Request tool, prompt, resource changes or a resource subscription
  3. Receive Method not found and no subscription events

After, authorized changes arrive and fresh listings include them

  1. Discover modern protocol support at $GATEWAY_URL/mcp/
  2. Request tool, prompt, resource changes or a resource subscription
  3. Receive acknowledgment and the requested upstream changes
  4. Re-list the changed catalog, then disconnect to close the listener

Linear ticket

Related to LIT-4510, prerequisite 2 of the approved three-PR stack. Depends on #46134 and targets litellm_mcp_progress_cancellation. Capability advertisement and the complete modern enablement acceptance tests follow in #46264. Existing #43340 and #34051 are unchanged

Implementation

The repair extends the existing listener owner with SDK legacy notification translation, resource subscribe/unsubscribe, bounded queues and session-owned cleanup. Legacy HTTP and SSE callers share the existing authorization, catalog and credential policies. A connection-local readiness event prevents startup notification loss. Non-notifying upstreams do not receive automatic subscription requests. Identity comparison and reauthorization now belong to the subscription owner; routes only extract requests and wire handlers.

The new interaction handler uses the SDK listener and bounded subscription bus. It reuses catalog, authorization, credential and rate-limit policies, including the existing protection against forwarding one caller bearer to multiple upstreams. Catalog events refresh listings and only notify when the caller-visible catalog changes. Each delivery rechecks authorization, including queued events. The stream is bound to the API key and its user, team, organization and end-user identity, so reassignment closes it before another event is delivered. Idle listeners recheck every 15 seconds

There are 128 downstream and upstream slots per process and eight listeners per caller. Partial setup failure releases acquired slots. Disconnect, revoked access, changed credentials or upstream configuration, and upstream closure end the listener. Resource URI subscriptions require exactly one selected server so identical URIs cannot cross server boundaries

Catalog snapshots retain the complete authorized server scope, so the existing credential policy protects both listener creation and listing refreshes. A pre-listen snapshot and post-registration reconciliation preserve setup-time changes. Reauthorization compares the existing catalog configuration identity, excluding discovered OAuth metadata while still rejecting real configuration changes

Managed client-credentials subscriptions bind to the existing grant configuration identity and effective granted scopes. Routine token renewal preserves the listener; a changed grant, reduced scope or failed credential resolution still closes it. Other authentication modes keep exact-token binding. Discovery-cache identity and token refresh behavior are unchanged.

The server declaration now names the existing SDK class directly so handler registration is typed. This uses the same runtime class, with no server lifecycle change

Pre-Submission checklist

  • I have added meaningful tests
  • Refreshed affected tests, coverage and canonical local gates pass
  • Current repair tip passes ticket-related CI
  • My PR's scope is as isolated as possible
  • Current repair tip has completed enabled reviews and independent verification

Verification

At 6d543461dcc1bd28def8a339474718dc77d8e00b, 169 affected coverage tests, three final renewal integration cases and two supplemental controls passed. The broader client/credential unit run passed 654 cases, with one existing isolated-interpreter environment mismatch. Canonical lint and type gates pass. The repair covers 11/11 changed executable lines. The complete PR covers 188/190, 98.95%, with subscription branches 27/28. The existing gaps are defensive catalog-page exhaustion and the post-cancellation fallback. No exclusions or budget increases

Seven standalone source-bound SDK replays passed, covering all four notification types, normal M2M renewal, scope reduction and credential-resolution failure. Routine renewal now preserves delivery. Reduced scopes and failed credentials close the listener. AWS signing and discovery-cache fingerprints retain their existing behavior

Independent Devin execution used source builds at base 163c474de8101e0e2d319107f91b24f6c64a935f, pre-repair control 2066acb93e61ea6565b6ff25e10c0566d2dd0c13, and historical head 6d543461dcc1bd28def8a339474718dc77d8e00b. The routine-renewal scenario failed on the control with SubscriptionLost and passed on head; both denial controls passed on both builds. All 22 subscription integration cases passed on head and were unsupported at the original base. Independent real-HTTP controls confirmed event delivery, identity isolation, idle revocation, credential scoping, setup races and cleanup. Progress/cancellation behavior matched the parent. Those historical results are supplemented by the current-head evidence linked above.

Completed current-tip Codecov confirms 98.39% patch coverage; local executable-line coverage is 368/374 (98.4%). Veria found no security issues; Bugbot found no issues, and all review threads are resolved. Relevant CI checks pass. The OSV scan still fails for existing mlflow 3.15.0 in unchanged uv.lock (PYSEC-2026-3865), outside this ticket. Greptile is disabled, LiteReview is deferred by the author, and the contributor agreement is confirmed signed

Screenshots / Proof of Fix

Use the standalone script below with the existing locked Python environment. $SOURCE points at the heading's source SHA and $OUT is an empty task scratch directory. It starts an actual SDK upstream and source-built gateway, caps logs at 10 MiB, prints the observed events/listings, and stops both services. No database or paid model calls are needed

Before (163c474)

Tool catalog change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/tools" tools
  2. Observed Method not found before acknowledgment

Prompt catalog change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/prompts" prompts
  2. Observed Method not found before acknowledgment

Resource catalog change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/resources" resources
  2. Observed Method not found before acknowledgment

Resource content change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/updated" updated
  2. Observed Method not found before acknowledgment

After (6d54346)

Tool catalog change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/tools" tools
  2. Observed ToolsListChanged(), then peer-added appears in tools/list and upstream disconnect cleanup

Prompt catalog change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/prompts" prompts
  2. Observed PromptsListChanged(), then peer-added appears in prompts/list and upstream disconnect cleanup

Resource catalog change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/resources" resources
  2. Observed ResourcesListChanged(), then test://added appears in resources/list and upstream disconnect cleanup

Resource content change

  1. Run python replay_subscriptions.py "$SOURCE" "$OUT/updated" updated
  2. Observed ResourceUpdated(uri=test://value), honoring only the requested URI and upstream disconnect cleanup

Additional head replays cover same-key user/team/organization/end-user reassignment, idle revocation, two-upstream credential scoping, setup-time changes, discovered metadata updates and actual configuration changes. Run the script with tools and respectively identity, team, org, end-user, idle, fanout, setup-race, metadata or config-change. Reassignment, revocation and configuration changes close the listener. Setup changes and metadata updates preserve delivery. Fanout captures no caller bearer on either listeners or catalog requests

replay_subscriptions.py
import sys, os, json, resource, subprocess
from pathlib import Path
from typing import Final
SOURCE = Path(sys.argv[1]).resolve()
OUT = Path(sys.argv[2]).resolve()
KIND = sys.argv[3]
ACCESS = sys.argv[4] if len(sys.argv)>4 else "normal"
OUT.mkdir(parents=True,exist_ok=True)
os.chdir(SOURCE)
sys.path[:0]=[str(SOURCE),str(SOURCE/"tests")]
os.environ["PYTHONPATH"]=os.pathsep.join((str(SOURCE),str(SOURCE/"tests")))
os.environ["INTEGRATION_PROXY_ROOT"]=str(SOURCE)
resource.setrlimit(resource.RLIMIT_FSIZE,(10485760,10485760))
import httpx, pytest, yaml
from integration._support.client import Gateway
from integration._support.process import owned_proxy
print(json.dumps({"source_sha":subprocess.check_output(["git","rev-parse","HEAD"],text=True).strip(),"source":str(SOURCE),"event_kind":KIND,"access":ACCESS}),flush=True)
def test_modern_subscription_delivers_changes_between_calls_and_refreshes_tools(
    tmp_path: Path, event_kind: str, access: str
) -> None:
    import asyncio
    from contextlib import asynccontextmanager

    import httpx2
    from mcp import ClientSession, MCPError
    from mcp.client.streamable_http import streamable_http_client
    from mcp.client.subscriptions import listen, SubscriptionLost
    from mcp.server.mcpserver import MCPServer
    from mcp.server.subscriptions import (
        InMemorySubscriptionBus,
        ListenHandler,
        ToolsListChanged,
        PromptsListChanged,
        ResourcesListChanged,
        ResourceUpdated,
    )
    from mcp.server.transport_security import TransportSecuritySettings
    from mcp.types import DiscoverResult, ListToolsResult, PaginatedRequestParams, SubscriptionsListenRequestParams
    from sse_starlette.sse import AppStatus
    from starlette.applications import Starlette
    from starlette.routing import Mount

    from integration._support.asgi import asgi_server
    from integration._support.mcp import _drain_sse_streams

    from threading import Event
    from collections.abc import Callable
    from mcp.shared.subscriptions import ServerEvent

    disconnected: Final = Event()
    connected: Final = Event()
    listener_credentials = []
    catalog_credentials = []
    setup_changed = Event()

    class ObservedBus(InMemorySubscriptionBus):
        def subscribe(self, listener: Callable[[ServerEvent], None]) -> Callable[[], None]:
            unsubscribe = super().subscribe(listener)
            connected.set()

            def close() -> None:
                unsubscribe()
                disconnected.set()

            return close

    auth_module: Final = tmp_path / "subscription_auth.py"
    auth_module.write_text(
        "from pathlib import Path\n"
        "from fastapi import HTTPException, Request\n"
        "from litellm.proxy._types import UserAPIKeyAuth\n"
        "async def authenticate(request: Request, api_key: str) -> UserAPIKeyAuth:\n"
        "    if api_key != 'sk-subscriptions-test':\n"
        "        raise HTTPException(status_code=401, detail='Unknown caller')\n"
        "    import json\n"
        "    data = json.loads(Path(__file__).with_suffix('.json').read_text())\n"
        "    change = data.pop('subscription_test_update', None)\n"
        "    if change:\n"
        "        from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager as manager\n"
        "        server = manager.config_mcp_servers['subscription-server']\n"
        "        fields = {'authorization_url': 'https://authorization.example/authorize'} if change == 'metadata' else {'url': server.url.rstrip('/') + '/changed'}\n"
        "        manager.config_mcp_servers[server.server_id] = server.model_copy(update=fields)\n"
        "    return UserAPIKeyAuth.model_validate(data)\n"
    )
    identity: Final = {
        "api_key": "sk-subscriptions-test",
        "user_id": "alice",
        "user_role": "internal_user",
        "object_permission": {
            "object_permission_id": "subscription-permission",
            "mcp_servers": ["subscription-server", "second-server"] if access == "fanout" else ["subscription-server"],
        },
    }
    auth_state: Final = auth_module.with_suffix(".json")
    auth_state.write_text(json.dumps(identity))
    bus: Final = ObservedBus()
    upstream_listener: Final = ListenHandler(bus)

    async def control_listen(ctx, call_next):
        if ctx.method == "tools/list":
            catalog_credentials.append(ctx.request.headers.get("authorization"))
            if access == "setup-race" and connected.is_set() and not setup_changed.is_set():
                setup_changed.set()
                await change_tools()
        if ctx.method == "subscriptions/listen":
            listener_credentials.append(ctx.request.headers.get("authorization"))
            return await upstream_listener(ctx, SubscriptionsListenRequestParams.model_validate(ctx.params))
        result = await call_next(ctx)
        if access == "pages" and ctx.method == "tools/list":
            result = ListToolsResult.model_validate(result)
            offset = int((ctx.params or {}).get("cursor") or "0")
            return result.model_copy(
                update={
                    "tools": result.tools[offset : offset + 1],
                    "next_cursor": str(offset + 1) if offset + 1 < len(result.tools) else None,
                }
            )
        return result

    upstream: Final = MCPServer("subscription-peer", subscriptions=bus, middleware=[control_listen])

    @upstream.resource("test://value")
    def value() -> str:
        return "value"

    @upstream.tool()
    async def change_tools() -> str:
        async def added() -> str:
            return "new tool"

        if access == "upstream-ended":
            upstream_listener.close()
            return "ended"
        if event_kind == "tools":
            upstream.add_tool(added)
            await bus.publish(ToolsListChanged())
        elif event_kind == "prompts":
            upstream.prompt()(added)
            await bus.publish(PromptsListChanged())
        elif event_kind == "resources":
            upstream.resource("test://added")(added)
            await bus.publish(ResourcesListChanged())
        else:
            await bus.publish(ResourceUpdated(uri="test://value"))
        return "changed"

    async def exercise(gateway: Gateway) -> None:
        headers = {"Authorization": "Bearer " + gateway.key}
        if access == "fanout":
            headers = {"x-litellm-api-key": gateway.key, "Authorization": "Bearer upstream-only-test-token"}
        async with httpx2.AsyncClient(headers=headers, timeout=30) as client:
            async with streamable_http_client(
                str(gateway.client.base_url).rstrip("/") + "/mcp/", http_client=client
            ) as streams:
                async with ClientSession(streams[0], streams[1]) as session:
                    session.adopt(DiscoverResult.model_validate(await session.send_discover("2026-07-28")))
                    before = await session.list_tools()
                    assert "peer-change_tools" in {tool.name for tool in before.tools}
                    assert "peer-added" not in {tool.name for tool in before.tools}
                    if access == "legacy":
                        with pytest.raises(MCPError, match="Select modern upstream"):
                            async with listen(session, tools_list_changed=True):
                                pytest.fail("Unsupported upstream was acknowledged")
                        assert not connected.is_set()
                        return
                    async with listen(
                        session,
                        tools_list_changed=event_kind == "tools",
                        prompts_list_changed=event_kind == "prompts",
                        resources_list_changed=event_kind == "resources",
                        resource_subscriptions=["test://value"] if event_kind == "updated" else (),
                    ) as subscription:
                        if access == "fanout":
                            assert listener_credentials == [None, None], (
                                "Unscoped caller credential reached multiple upstreams"
                            )
                            assert catalog_credentials and all(value is None for value in catalog_credentials), (
                                "Unscoped caller credential reached catalog listings"
                            )
                        if access in ("metadata", "config-change"):
                            auth_state.write_text(json.dumps({**identity, "subscription_test_update": access}))
                        if access in ("revoked", "identity", "team", "org", "end-user", "idle"):
                            changed_identity = (
                                {
                                    **identity,
                                    {
                                        "identity": "user_id",
                                        "team": "team_id",
                                        "org": "org_id",
                                        "end-user": "end_user_id",
                                    }[access]: "bob",
                                }
                                if access in ("identity", "team", "org", "end-user")
                                else {
                                    **identity,
                                    "object_permission": {
                                        "object_permission_id": "subscription-permission",
                                        "mcp_servers": ["denied"],
                                    },
                                }
                            )
                            auth_state.write_text(json.dumps(changed_identity))
                        if access == "idle":
                            with pytest.raises((SubscriptionLost, StopAsyncIteration)):
                                await asyncio.wait_for(anext(subscription), 20)
                            assert await asyncio.to_thread(disconnected.wait, 3)
                            return
                        if access != "setup-race":
                            async with streamable_http_client(upstream_url + "/mcp") as direct_streams:
                                async with ClientSession(direct_streams[0], direct_streams[1]) as direct:
                                    direct.adopt(DiscoverResult.model_validate(await direct.send_discover("2026-07-28")))
                                    changed = await direct.call_tool("change_tools", {})
                                    assert not changed.is_error
                        if access in ("revoked", "identity", "team", "org", "end-user", "idle", "upstream-ended", "config-change"):
                            with pytest.raises((SubscriptionLost, StopAsyncIteration)):
                                await asyncio.wait_for(anext(subscription), 5)
                            assert await asyncio.to_thread(disconnected.wait, 3)
                            return
                        if access == "hidden":
                            after = await session.list_tools()
                            assert {tool.name for tool in after.tools} == {"peer-change_tools"}
                            with pytest.raises(TimeoutError):
                                await asyncio.wait_for(anext(subscription), 0.5)
                            return
                        event = await asyncio.wait_for(anext(subscription), 5)
                        expected = {
                            "tools": ToolsListChanged(),
                            "prompts": PromptsListChanged(),
                            "resources": ResourcesListChanged(),
                            "updated": ResourceUpdated(uri="test://value"),
                        }
                        assert event == expected[event_kind]
                        print(json.dumps({"event":repr(event),"honored":subscription.honored.model_dump(by_alias=True,exclude_none=True)}),flush=True)
                        if access == "fanout":
                            assert all(value is None for value in catalog_credentials), (
                                "Unscoped caller credential reached refreshed catalogs"
                            )
                        if event_kind == "tools":
                            assert subscription.honored.tools_list_changed
                            after = await session.list_tools()
                            if access == "pages":
                                assert after.next_cursor
                                assert "peer-added" not in {tool.name for tool in after.tools}
                                after = await session.list_tools(
                                    params=PaginatedRequestParams(cursor=after.next_cursor)
                                )
                            assert "peer-added" in {tool.name for tool in after.tools}
                            print(json.dumps({"tools_after":[tool.name for tool in after.tools]}),flush=True)
                        elif event_kind == "prompts":
                            assert subscription.honored.prompts_list_changed
                            prompts = await session.list_prompts()
                            assert "peer-added" in {prompt.name for prompt in prompts.prompts}
                            print(json.dumps({"prompts_after":[prompt.name for prompt in prompts.prompts]}),flush=True)
                        elif event_kind == "resources":
                            assert subscription.honored.resources_list_changed
                            resources = await session.list_resources()
                            assert "test://added" in {str(resource.uri) for resource in resources.resources}
                            print(json.dumps({"resources_after":[str(resource.uri) for resource in resources.resources]}),flush=True)
                        else:
                            assert subscription.honored.resource_subscriptions == ["test://value"]
                    assert await asyncio.to_thread(disconnected.wait, 3), "Upstream listener survived disconnect"
                    print(json.dumps({"upstream_disconnected":disconnected.is_set(),"catalog_requests":len(catalog_credentials)}),flush=True)

    app: Final = upstream.streamable_http_app(
        transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False)
    )

    @asynccontextmanager
    async def lifespan(_: Starlette):
        AppStatus.should_exit = False
        async with app.router.lifespan_context(app):
            yield
        _drain_sse_streams()
        watchers = tuple(task for task in asyncio.all_tasks() if "_shutdown_watcher" in repr(task.get_coro()))
        await asyncio.wait_for(asyncio.gather(*watchers), 2)

    hosted: Final = Starlette(routes=[Mount("/", app=app)], lifespan=lifespan)
    with asgi_server(hosted) as upstream_url, httpx.Client() as client:
        config: Final = tmp_path / "proxy.yaml"
        config.write_text(
            yaml.safe_dump(
                {
                    "model_list": [],
                    "mcp_servers": {
                        "peer": {
                            "server_id": "subscription-server",
                            "url": upstream_url + "/mcp",
                            "transport": "http",
                            "protocol_version": "2025-11-25" if access == "legacy" else "2026-07-28",
                            **({"allowed_tools": ["change_tools"]} if access == "hidden" else {}),
                            **(
                                {"auth_type": "oauth_delegate", "extra_headers": ["Authorization"]}
                                if access == "fanout"
                                else {}
                            ),
                        },
                        **(
                            {
                                "second": {
                                    "server_id": "second-server",
                                    "url": upstream_url + "/mcp",
                                    "transport": "http",
                                    "protocol_version": "2026-07-28",
                                    "auth_type": "oauth_delegate",
                                    "extra_headers": ["Authorization"],
                                }
                            }
                            if access == "fanout"
                            else {}
                        ),
                    },
                    "general_settings": {
                        "master_key": "sk-subscriptions-test",
                        "custom_auth": "subscription_auth.authenticate",
                        "store_model_in_db": False,
                        "mcp_advertised_versions": ["2025-11-25", "2026-07-28"],
                    },
                }
            )
        )
        source: Final = SOURCE
        environment: Final = {
            "PYTHONPATH": os.pathsep.join((str(source), str(source / "tests"))),
            "LITELLM_SALT_KEY": "subscription-pagination-key",
            "STORE_MODEL_IN_DB": "False",
            "DISABLE_SCHEMA_UPDATE": "true",
            "LITELLM_LOCAL_MODEL_COST_MAP": "True",
            "LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY": "true",
        }
        seed: Final = Gateway(client, "sk-subscriptions-test", upstream_url)
        with owned_proxy(
            seed,
            tmp_path / "gateway",
            environment,
            config=config,
            database_setup=(),
            remove_environment=(
                "DATABASE_URL",
                "DATABASE_URL_READ_REPLICA",
                "DIRECT_URL",
                "INTEGRATION_PROXY_DATABASE_URL",
                "INTEGRATION_PROXY_READ_REPLICA_URL",
            ),
        ) as gateway:
            asyncio.run(exercise(gateway))


try:
    test_modern_subscription_delivers_changes_between_calls_and_refreshes_tools(OUT,KIND,ACCESS)
except BaseException as error:
    def messages(value):
        if isinstance(value,BaseExceptionGroup):
            return [message for child in value.exceptions for message in messages(child)]
        return [str(value)]
    print(json.dumps({"result":"failed","errors":messages(error)}),flush=True)
    raise SystemExit(1)
else:
    print(json.dumps({"result":"passed"}),flush=True)

Managed renewal regression

Subscription validation now uses the existing managed M2M grant identity and resolved scopes instead of the changing access token. URL, other headers, caller authorization and server configuration remain checked. Discovery-cache identity is unchanged. Caller-supplied and per-user OAuth credentials retain exact-token comparison

Before (2066acb)

  1. Run python replay_managed_renewal.py "$SOURCE" "$OUT/renewal" renewal using the script below
  2. The listener is acknowledged. A second token is issued with identical client, server and scope inputs. The pending event fails with SubscriptionLost, and the gateway reports Subscription authorization or upstream configuration changed

After (6d54346)

  1. Run the same command against this commit
  2. Two matching grants are observed and ToolsListChanged is delivered. The added tool appears in the next listing
  3. Run with renewal-scopes and renewal-failed instead of renewal. Both close the listener before delivering an event, preserving authorization controls
replay_managed_renewal.py
import sys, os, json, resource, subprocess, runpy
from pathlib import Path
SOURCE=Path(sys.argv[1]).resolve(); OUT=Path(sys.argv[2]).resolve(); MODE=sys.argv[3]
OUT.mkdir(parents=True,exist_ok=True)
os.chdir(SOURCE);sys.path[:0]=[str(SOURCE),str(SOURCE/'tests')]
os.environ['PYTHONPATH']=os.pathsep.join((str(SOURCE),str(SOURCE/'tests')))
os.environ['INTEGRATION_PROXY_ROOT']=str(SOURCE)
resource.setrlimit(resource.RLIMIT_FSIZE,(10485760,10485760))
import litellm
assert Path(litellm.__file__).resolve().is_relative_to(SOURCE)
print(json.dumps({'sha':subprocess.check_output(['git','rev-parse','HEAD'],text=True).strip(),'mode':MODE,'source_import':str(Path(litellm.__file__).resolve())}),flush=True)
globals().update({k:v for k,v in runpy.run_path(str(SOURCE/'tests/integration/mcp/test_interactions.py')).items() if not k.startswith('__')})
def test_modern_subscription_delivers_changes_between_calls_and_refreshes_tools(
    tmp_path: Path, event_kind: str, access: str
) -> None:
    import asyncio
    from contextlib import asynccontextmanager

    import httpx2
    from mcp import ClientSession, MCPError
    from mcp.client.streamable_http import streamable_http_client
    from mcp.client.subscriptions import listen, SubscriptionLost
    from mcp.server.mcpserver import MCPServer
    from mcp.server.subscriptions import (
        InMemorySubscriptionBus,
        ListenHandler,
        ToolsListChanged,
        PromptsListChanged,
        ResourcesListChanged,
        ResourceUpdated,
    )
    from mcp.server.transport_security import TransportSecuritySettings
    from mcp.types import DiscoverResult, ListToolsResult, PaginatedRequestParams, SubscriptionsListenRequestParams
    from sse_starlette.sse import AppStatus
    from starlette.applications import Starlette
    from starlette.routing import Mount, Route
    from starlette.responses import JSONResponse

    from integration._support.asgi import asgi_server
    from integration._support.mcp import _drain_sse_streams

    from threading import Event
    from collections.abc import Callable
    from mcp.shared.subscriptions import ServerEvent

    disconnected: Final = Event()
    connected: Final = Event()
    token_grants = []
    renewal_started = Event()
    async def token_endpoint(request):
        from urllib.parse import parse_qs

        form = parse_qs((await request.body()).decode())
        assert form["grant_type"] == ["client_credentials"]
        assert form["client_id"] == ["subscription-service"]
        assert form["scope"] == ["read write"]
        token_grants.append(form)
        if renewal_started.is_set() and access == "renewal-failed":
            return JSONResponse({"error": "invalid_client"}, status_code=401)
        return JSONResponse({
            "access_token": "synthetic-renewal-" + str(len(token_grants)),
            "token_type": "Bearer", "expires_in": 70,
            "scope": "read" if renewal_started.is_set() and access == "renewal-scopes" else "read write",
        })

    listener_credentials = []
    catalog_credentials = []
    setup_changed = Event()

    class ObservedBus(InMemorySubscriptionBus):
        def subscribe(self, listener: Callable[[ServerEvent], None]) -> Callable[[], None]:
            unsubscribe = super().subscribe(listener)
            connected.set()

            def close() -> None:
                unsubscribe()
                disconnected.set()

            return close

    auth_module: Final = tmp_path / "subscription_auth.py"
    auth_module.write_text(
        "from pathlib import Path\n"
        "from fastapi import HTTPException, Request\n"
        "from litellm.proxy._types import UserAPIKeyAuth\n"
        "async def authenticate(request: Request, api_key: str) -> UserAPIKeyAuth:\n"
        "    if api_key != 'sk-subscriptions-test':\n"
        "        raise HTTPException(status_code=401, detail='Unknown caller')\n"
        "    import json\n"
        "    data = json.loads(Path(__file__).with_suffix('.json').read_text())\n"
        "    change = data.pop('subscription_test_update', None)\n"
        "    if change:\n"
        "        from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager as manager\n"
        "        server = manager.config_mcp_servers['subscription-server']\n"
        "        fields = {'authorization_url': 'https://authorization.example/authorize'} if change == 'metadata' else {'url': server.url.rstrip('/') + '/changed'}\n"
        "        manager.config_mcp_servers[server.server_id] = server.model_copy(update=fields)\n"
        "    return UserAPIKeyAuth.model_validate(data)\n"
    )
    identity: Final = {
        "api_key": "sk-subscriptions-test",
        "user_id": "alice",
        "user_role": "internal_user",
        "object_permission": {
            "object_permission_id": "subscription-permission",
            "mcp_servers": ["subscription-server", "second-server"] if access == "fanout" else ["subscription-server"],
        },
    }
    auth_state: Final = auth_module.with_suffix(".json")
    auth_state.write_text(json.dumps(identity))
    bus: Final = ObservedBus()
    upstream_listener: Final = ListenHandler(bus)

    async def control_listen(ctx, call_next):
        if ctx.method == "tools/list":
            catalog_credentials.append(ctx.request.headers.get("authorization"))
            if access == "setup-race" and connected.is_set() and not setup_changed.is_set():
                setup_changed.set()
                await change_tools()
        if ctx.method == "subscriptions/listen":
            listener_credentials.append(ctx.request.headers.get("authorization"))
            return await upstream_listener(ctx, SubscriptionsListenRequestParams.model_validate(ctx.params))
        result = await call_next(ctx)
        if access == "pages" and ctx.method == "tools/list":
            result = ListToolsResult.model_validate(result)
            offset = int((ctx.params or {}).get("cursor") or "0")
            return result.model_copy(
                update={
                    "tools": result.tools[offset : offset + 1],
                    "next_cursor": str(offset + 1) if offset + 1 < len(result.tools) else None,
                }
            )
        return result

    upstream: Final = MCPServer("subscription-peer", subscriptions=bus, middleware=[control_listen])

    @upstream.resource("test://value")
    def value() -> str:
        return "value"

    @upstream.tool()
    async def change_tools() -> str:
        async def added() -> str:
            return "new tool"

        if access == "upstream-ended":
            upstream_listener.close()
            return "ended"
        if event_kind == "tools":
            upstream.add_tool(added)
            await bus.publish(ToolsListChanged())
        elif event_kind == "prompts":
            upstream.prompt()(added)
            await bus.publish(PromptsListChanged())
        elif event_kind == "resources":
            upstream.resource("test://added")(added)
            await bus.publish(ResourcesListChanged())
        else:
            await bus.publish(ResourceUpdated(uri="test://value"))
        return "changed"

    async def exercise(gateway: Gateway) -> None:
        headers = {"Authorization": "Bearer " + gateway.key}
        if access == "fanout":
            headers = {"x-litellm-api-key": gateway.key, "Authorization": "Bearer upstream-only-test-token"}
        async with httpx2.AsyncClient(headers=headers, timeout=30) as client:
            async with streamable_http_client(
                str(gateway.client.base_url).rstrip("/") + "/mcp/", http_client=client
            ) as streams:
                async with ClientSession(streams[0], streams[1]) as session:
                    session.adopt(DiscoverResult.model_validate(await session.send_discover("2026-07-28")))
                    before = await session.list_tools()
                    assert "peer-change_tools" in {tool.name for tool in before.tools}
                    assert "peer-added" not in {tool.name for tool in before.tools}
                    if access == "legacy":
                        with pytest.raises(MCPError, match="Select modern upstream"):
                            async with listen(session, tools_list_changed=True):
                                pytest.fail("Unsupported upstream was acknowledged")
                        assert not connected.is_set()
                        return
                    async with listen(
                        session,
                        tools_list_changed=event_kind == "tools",
                        prompts_list_changed=event_kind == "prompts",
                        resources_list_changed=event_kind == "resources",
                        resource_subscriptions=["test://value"] if event_kind == "updated" else (),
                    ) as subscription:
                        if access == "fanout":
                            assert listener_credentials == [None, None], (
                                "Unscoped caller credential reached multiple upstreams"
                            )
                            assert catalog_credentials and all(value is None for value in catalog_credentials), (
                                "Unscoped caller credential reached catalog listings"
                            )
                        if access in ("metadata", "config-change"):
                            auth_state.write_text(json.dumps({**identity, "subscription_test_update": access}))
                        if access in ("revoked", "identity", "team", "org", "end-user", "idle"):
                            changed_identity = (
                                {
                                    **identity,
                                    {
                                        "identity": "user_id",
                                        "team": "team_id",
                                        "org": "org_id",
                                        "end-user": "end_user_id",
                                    }[access]: "bob",
                                }
                                if access in ("identity", "team", "org", "end-user")
                                else {
                                    **identity,
                                    "object_permission": {
                                        "object_permission_id": "subscription-permission",
                                        "mcp_servers": ["denied"],
                                    },
                                }
                            )
                            auth_state.write_text(json.dumps(changed_identity))
                        if access == "idle":
                            with pytest.raises((SubscriptionLost, StopAsyncIteration)):
                                await asyncio.wait_for(anext(subscription), 20)
                            assert await asyncio.to_thread(disconnected.wait, 3)
                            return
                        if access.startswith("renewal"):
                            assert token_grants
                            admitted_grants = len(token_grants)
                            renewal_started.set()
                            async with asyncio.timeout(25):
                                while len(token_grants) == admitted_grants:
                                    try:
                                        await session.list_tools()
                                    except MCPError:
                                        assert access == "renewal-failed"
                                    await asyncio.sleep(0.2)
                            assert token_grants[0] == token_grants[-1]
                            print(json.dumps({"stage":"renewed", "grants_before":admitted_grants, "grants_after":len(token_grants), "same_grant_inputs":True}),flush=True)
                        if access != "setup-race":
                            async with streamable_http_client(upstream_url + "/mcp") as direct_streams:
                                async with ClientSession(direct_streams[0], direct_streams[1]) as direct:
                                    direct.adopt(DiscoverResult.model_validate(await direct.send_discover("2026-07-28")))
                                    changed = await direct.call_tool("change_tools", {})
                                    assert not changed.is_error
                        if access in ("revoked", "identity", "team", "org", "end-user", "idle", "upstream-ended", "config-change", "renewal-scopes", "renewal-failed"):
                            with pytest.raises((SubscriptionLost, StopAsyncIteration)):
                                await asyncio.wait_for(anext(subscription), 5)
                            assert await asyncio.to_thread(disconnected.wait, 3)
                            return
                        if access == "hidden":
                            after = await session.list_tools()
                            assert {tool.name for tool in after.tools} == {"peer-change_tools"}
                            with pytest.raises(TimeoutError):
                                await asyncio.wait_for(anext(subscription), 0.5)
                            return
                        event = await asyncio.wait_for(anext(subscription), 5)
                        expected = {
                            "tools": ToolsListChanged(),
                            "prompts": PromptsListChanged(),
                            "resources": ResourcesListChanged(),
                            "updated": ResourceUpdated(uri="test://value"),
                        }
                        assert event == expected[event_kind]
                        print(json.dumps({"stage":"delivered", "event":event_kind, "grants":len(token_grants)}),flush=True)
                        if access == "fanout":
                            assert all(value is None for value in catalog_credentials), (
                                "Unscoped caller credential reached refreshed catalogs"
                            )
                        if event_kind == "tools":
                            assert subscription.honored.tools_list_changed
                            after = await session.list_tools()
                            if access == "pages":
                                assert after.next_cursor
                                assert "peer-added" not in {tool.name for tool in after.tools}
                                after = await session.list_tools(
                                    params=PaginatedRequestParams(cursor=after.next_cursor)
                                )
                            assert "peer-added" in {tool.name for tool in after.tools}
                        elif event_kind == "prompts":
                            assert subscription.honored.prompts_list_changed
                            prompts = await session.list_prompts()
                            assert "peer-added" in {prompt.name for prompt in prompts.prompts}
                        elif event_kind == "resources":
                            assert subscription.honored.resources_list_changed
                            resources = await session.list_resources()
                            assert "test://added" in {str(resource.uri) for resource in resources.resources}
                        else:
                            assert subscription.honored.resource_subscriptions == ["test://value"]
                    assert await asyncio.to_thread(disconnected.wait, 3), "Upstream listener survived disconnect"

    app: Final = upstream.streamable_http_app(
        transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False)
    )

    @asynccontextmanager
    async def lifespan(_: Starlette):
        AppStatus.should_exit = False
        async with app.router.lifespan_context(app):
            yield
        _drain_sse_streams()
        watchers = tuple(task for task in asyncio.all_tasks() if "_shutdown_watcher" in repr(task.get_coro()))
        await asyncio.wait_for(asyncio.gather(*watchers), 2)

    hosted: Final = Starlette(routes=[Route("/token", token_endpoint, methods=["POST"]), Mount("/", app=app)], lifespan=lifespan)
    with asgi_server(hosted) as upstream_url, httpx.Client() as client:
        config: Final = tmp_path / "proxy.yaml"
        config.write_text(
            yaml.safe_dump(
                {
                    "model_list": [],
                    "mcp_servers": {
                        "peer": {
                            "server_id": "subscription-server",
                            **({
                                "auth_type": "oauth2", "oauth2_flow": "client_credentials",
                                "client_id": "subscription-service", "client_secret": "synthetic-client-secret",
                                "token_url": upstream_url + "/token", "scopes": ["read", "write"],
                            } if access.startswith("renewal") else {}),
                            "url": upstream_url + "/mcp",
                            "transport": "http",
                            "protocol_version": "2025-11-25" if access == "legacy" else "2026-07-28",
                            **({"allowed_tools": ["change_tools"]} if access == "hidden" else {}),
                            **(
                                {"auth_type": "oauth_delegate", "extra_headers": ["Authorization"]}
                                if access == "fanout"
                                else {}
                            ),
                        },
                        **(
                            {
                                "second": {
                                    "server_id": "second-server",
                                    "url": upstream_url + "/mcp",
                                    "transport": "http",
                                    "protocol_version": "2026-07-28",
                                    "auth_type": "oauth_delegate",
                                    "extra_headers": ["Authorization"],
                                }
                            }
                            if access == "fanout"
                            else {}
                        ),
                    },
                    "general_settings": {
                        "master_key": "sk-subscriptions-test",
                        "custom_auth": "subscription_auth.authenticate",
                        "store_model_in_db": False,
                        "mcp_advertised_versions": ["2025-11-25", "2026-07-28"],
                    },
                }
            )
        )
        source: Final = SOURCE
        environment: Final = {
            "PYTHONPATH": os.pathsep.join((str(source), str(source / "tests"))),
            "LITELLM_SALT_KEY": "subscription-pagination-key",
            "STORE_MODEL_IN_DB": "False",
            "DISABLE_SCHEMA_UPDATE": "true",
            "LITELLM_LOCAL_MODEL_COST_MAP": "True",
            "LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY": "true",
        }
        seed: Final = Gateway(client, "sk-subscriptions-test", upstream_url)
        with owned_proxy(
            seed,
            tmp_path / "gateway",
            environment,
            config=config,
            database_setup=(),
            remove_environment=(
                "DATABASE_URL",
                "DATABASE_URL_READ_REPLICA",
                "DIRECT_URL",
                "INTEGRATION_PROXY_DATABASE_URL",
                "INTEGRATION_PROXY_READ_REPLICA_URL",
            ),
        ) as gateway:
            asyncio.run(exercise(gateway))
test_modern_subscription_delivers_changes_between_calls_and_refreshes_tools(OUT,"tools",MODE)
print(json.dumps({"result":"passed","mode":MODE}),flush=True)

Type

New Feature

Caveats

Medium

  • Requires explicitly configured modern upstream protocol
  • Resource URI subscriptions require one selected server
  • Legacy upstream subscription bridging remains unsupported

Low

  • Capability advertisement follows in the enablement child PR
  • Dropped streams require resubscription and a fresh listing
  • Per-user credential replacement still requires resubscription

Final Attestation

  • Current-tip ticket verification, coverage and required enabled reviews are complete; unrelated CI failure is explicitly recorded above

Note

High Risk
Long-lived subscription tasks touch auth, outbound credentials, and multi-upstream fan-out with reauthorization on every event—bugs could leak notifications across callers or hold upstream connections incorrectly.

Overview
Adds MCP subscription relay on the experimental gateway so clients can use subscriptions/listen (and legacy notification/resource subscribe paths) to receive upstream catalog and resource events without polling.

A new GatewaySubscriptions layer opens authorized upstream listeners per caller, merges fan-out across allowed servers, refreshes gateway catalogs when listings change, and re-checks auth before each delivery and on idle. Listeners are capped (global and per-caller), bound to caller identity, and torn down on revocation, credential/config drift, or upstream disconnect. Legacy clients get bridged via notifications/initialized, resource subscribe/unsubscribe, and SSE request context; modern 2026-07-28 uses the SDK subscription flow.

MCPClient now accepts an on_notification hook on run_with_session and exposes subscription_auth_fingerprint(). Managed client-credentials grants get a stable subscription_identity (config + granted scopes) so token renewal does not drop listeners; discovery fingerprint behavior is unchanged.

Reviewed by Cursor Bugbot for commit 00a41f4. Bugbot is set up for automated code reviews on this repo. Configure here.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the current commit, including caller isolation and subscription cleanup.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review the current commit, including authorization, credential scoping and subscription cleanup.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@litereview

litereview Bot commented Oct 13, 2026

Copy link
Copy Markdown

Review not started

Sign in to LiteReview with your workspace Google account and link your GitHub account once before requesting a review. Your linked GitHub account can then request reviews without signing in again.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@veria-ai

veria-ai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.39572% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...lm/proxy/_experimental/mcp_server/subscriptions.py 98.36% 5 Missing ⚠️
litellm/proxy/_experimental/mcp_server/server.py 97.95% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review current commit 2066acb for catalog credential scoping, setup notification delivery, metadata stability, and remaining actionable concerns.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@Veria Please review commit 2066acb. Catalog refresh now preserves full authorized scope, with regression evidence covering initial and refreshed requests.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

cursor review Please review commit 2066acb. Setup races and metadata changes are repaired; credential lifetime evidence addresses the remaining fingerprint concern.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review current commit 2066acb, including subscription setup ordering, catalog credential policy, configuration identity, and the updated live evidence.

@litereview

litereview Bot commented Oct 13, 2026

Copy link
Copy Markdown

Review not started

Sign in to LiteReview with your workspace Google account and link your GitHub account once before requesting a review. Your linked GitHub account can then request reviews without signing in again.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@cursor review Please review commit 2066acb. Setup and metadata regressions pass; the description demonstrates stable signing identity and explicit credential expiry behavior.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai Please review commit 2066acb. Catalog refresh retains complete authorized scope, with live credential capture verifying both initial and refreshed requests.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@cursor review Independent execution confirms different SigV4 signatures retain identical fingerprints. Token rotation intentionally expires listeners; see updated credential-lifetime evidence.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review this draft before I make it official. Please assess current commit 2066acb and its subscription authorization evidence.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@cursor review the remaining credential-lifetime finding using the thread clarification and existing signer evidence. Preserve the approved reconnect contract

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@cursor review the managed M2M renewal repair at 6d54346. Live renewal, reduced-scope rejection and failed-credential controls pass

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai the managed M2M renewal repair at 6d54346. Live renewal, reduced-scope rejection and failed-credential controls pass

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@cursor review

Please confirm current head d80e42a7926a4e2cf2118d9be78bedeec0a676cf. The remaining implicit-modern-initialize finding is resolved as a demonstrated false positive: independent source builds reproduce the exact SDK rejection and zero implicit upstream listeners, as recorded in the thread. No gateway guard or product change was added to duplicate SDK validation.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

Current gap-repair evidence for d80e42a7926a4e2cf2118d9be78bedeec0a676cf, base 163c474de8101e0e2d319107f91b24f6c64a935f (MCP SDK 2.2.0):

Verification Measured result
Independent source-build compatibility replay 23/23 head cases pass. Baseline passes only the two ordinary-use controls; subscription features are absent.
Covered flows Four legacy/modern caller/upstream combinations for tools, prompts, resource-list and resource updates; legacy SSE; caller isolation; revocation; failed setup; ordinary calls without notification support; explicit modern listener and disconnect cleanup.
Repository integration fixture 44/44 pass at 7b567b9; product tree is byte-identical to d80e42a7. The two corrected context-cleanup tests also pass on d80e42a7.
Modern SDK dispatch finding Independent wire execution confirms zero implicit listeners, immediate 404/-32601 for removed modern request methods, and one explicit listener/event with cleanup. Recorded resolution.
Completed Codecov 98.39% patch coverage, matching 368/374 changed executable lines locally. Six defensive/terminal lines remain uncovered; no exclusions or threshold changes.
CI MCP shard passed, and real upstream OAuth CI passed. The unchanged OSV dependency failure is unrelated.

The initial independent isolation observation was a harness synchronization/shared-registry artifact. After synchronizing on the existing catalog readiness boundary, each caller receives only its authorized changes; unauthorized tool calls remain rejected.

A separate inconsistent-upstream control advertises subscription support but refuses listen. It preserves ordinary tool use and leaves zero listeners, but a subsequent legacy resource subscription reaches the existing 10-second setup bound with an unhelpful error. This is distinct from empty advertised capabilities (prompt rejection and no listener), and is retained as a limitation rather than adding retry/fallback behavior outside the approved scope.

Reviewer reproduction uses the committed tests/integration/mcp/test_interactions.py fixture:

uv run --no-sync pytest --override-ini=pythonpath=tests tests/integration/mcp/test_interactions.py -q

The standalone wire replay is also available above. Both enabled-review threads are resolved and Bugbot's fresh d80e42a7 review reports no issues. Current-tip Veria and the final aggregate-stack gate remain pending; this comment does not declare readiness or close LIT-4510.

@joshua-berri
joshua-berri marked this pull request as ready for review October 15, 2026 04:57
@greptile-apps

greptile-apps Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@mrinal-berri mrinal-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lgtm

Base automatically changed from litellm_mcp_progress_cancellation to main October 15, 2026 18:53
@joshua-berri
joshua-berri force-pushed the litellm_mcp_notification_subscriptions branch from d80e42a to 00a41f4 Compare October 15, 2026 19:17
@joshua-berri

Copy link
Copy Markdown
Contributor Author

Restacked onto main at 00a41f4; local checks passed. Current-tip CI, coverage, and independent verification pending. @cursor review @veria-ai please review.

@codspeed

codspeed Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 31 untouched benchmarks


Comparing litellm_mcp_notification_subscriptions (00a41f4) with main (1f041a3)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (7774784) during the generation of this report, so 1f041a3 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@cursor review

@joshua-berri
joshua-berri merged commit 4a4a0e8 into main Oct 15, 2026
109 checks passed
@joshua-berri
joshua-berri deleted the litellm_mcp_notification_subscriptions branch October 15, 2026 20:16

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 00a41f4. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor

Main CircleCI job integration-mcp fails test_shared_redis_enforces_paginated_tools_and_rest_listings since this merged and passes before it, likely the relay's per-session rate-limit check. https://app.circleci.com/pipelines/github/BerriAI/litellm/91275

This branch was previously deployed

1 inactive deployment
e2e-changed — 00a41f49 Deployed Oct 15, 2026 by joshua-berri via oauth #5310
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants