Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

5.0 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Studio's fastmcp>=4.1.5,<5 has no lockfile, so these check the installed version."""

from __future__ import annotations

import importlib
import sys
from pathlib import Path

import pytest

_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
    sys.path.insert(0, _BACKEND_DIR)

from core.inference import mcp_client

LEGACY_ENV = "UNSLOTH_STUDIO_MAX_STDIO_MCP_SESSIONS"
ENV = "UNSLOTH_STUDIO_MAX_MCP_SESSIONS"


def test_the_old_close_name_still_works():
    """close_stdio_sessions stays public for outside callers, though nothing in-repo uses it."""
    assert mcp_client.close_stdio_sessions is mcp_client.close_mcp_sessions
    mcp_client.close_stdio_sessions()


def test_the_old_close_name_takes_the_same_arguments():
    mcp_client.close_stdio_sessions("https://mcp.example.test/mcp", None)


@pytest.fixture(autouse = True)
def clean_env(monkeypatch):
    monkeypatch.delenv(ENV, raising = False)
    monkeypatch.delenv(LEGACY_ENV, raising = False)


def test_unset_falls_back_to_the_default():
    assert mcp_client._max_sessions_from_env() == mcp_client._DEFAULT_MAX_SESSIONS


def test_a_deployment_that_set_the_legacy_name_keeps_its_value(monkeypatch):
    """The legacy env name is stale, but resetting a tuned value to 32 would be worse."""
    monkeypatch.setenv(LEGACY_ENV, "7")
    assert mcp_client._max_sessions_from_env() == 7


def test_the_new_name_works(monkeypatch):
    monkeypatch.setenv(ENV, "9")
    assert mcp_client._max_sessions_from_env() == 9


def test_the_new_name_wins_when_both_are_set(monkeypatch):
    monkeypatch.setenv(LEGACY_ENV, "7")
    monkeypatch.setenv(ENV, "9")
    assert mcp_client._max_sessions_from_env() == 9


@pytest.mark.parametrize("raw", ["", "abc", "1.5", "  "])
def test_an_unparseable_value_falls_back_instead_of_crashing_startup(monkeypatch, raw):
    monkeypatch.setenv(ENV, raw)
    assert mcp_client._max_sessions_from_env() == mcp_client._DEFAULT_MAX_SESSIONS


@pytest.mark.parametrize("raw,expected", [("0", 1), ("-5", 1), ("1", 1)])
def test_the_cap_never_drops_below_one(monkeypatch, raw, expected):
    monkeypatch.setenv(ENV, raw)
    assert mcp_client._max_sessions_from_env() == expected


def test_the_transports_this_code_builds_still_exist():
    from fastmcp.client.transports import SSETransport, StdioTransport, StreamableHttpTransport
    for cls in (StdioTransport, SSETransport, StreamableHttpTransport):
        assert cls is not None


def test_only_stdio_answers_the_liveness_probe():
    """_transport_dead answers only for stdio; if a future fastmcp probes HTTP too, this test fails
    so the recheck can get cheaper."""
    from fastmcp.client.transports import SSETransport, StreamableHttpTransport
    for cls in (StreamableHttpTransport, SSETransport):
        transport = cls(url = "https://x.test/mcp")
        assert not hasattr(
            transport, "_is_session_dead"
        ), f"{cls.__name__} grew a liveness probe; _transport_dead can use it now"


def test_the_installed_fastmcp_meets_the_declared_floor():
    version = importlib.metadata.version("fastmcp")
    major, minor, *_ = (int(part) for part in version.split(".")[:2])
    assert (major, minor) >= (4, 1), f"fastmcp {version} is below the declared >=4.1.5"


def test_the_middleware_hooks_tool_access_overrides_still_exist():
    """StudioToolAccess hides turned-off tools and prompts through these four hooks."""
    from fastmcp.exceptions import PromptError
    from fastmcp.server.middleware import Middleware

    from studio_mcp.tool_access import StudioToolAccess

    for hook in ("on_list_tools", "on_call_tool", "on_list_prompts", "on_get_prompt"):
        assert callable(getattr(Middleware, hook, None)), hook
        assert hook in vars(StudioToolAccess), hook
    assert issubclass(PromptError, Exception)


def test_tool_errors_are_still_distinguishable_from_transport_errors():
    """The whole keep-or-drop-the-session decision rests on this import."""
    from fastmcp.exceptions import ToolError

    assert mcp_client._is_tool_error(ToolError("nope")) is True
    assert mcp_client._is_tool_error(RuntimeError("stream closed")) is False


def test_a_row_without_use_oauth_is_treated_as_non_oauth():
    """Old rows backfilled by ALTER can read use_oauth as None rather than 0."""
    assert bool({"url": "https://x.test/mcp"}.get("use_oauth")) is False


def test_header_identity_survives_a_rewritten_headers_dict():
    """Same headers in another key order must not make a re-saved row drop the live session."""
    a = mcp_client._headers_key({"Authorization": "Bearer x", "X-Trace": "1"})
    b = mcp_client._headers_key({"X-Trace": "1", "Authorization": "Bearer x"})
    assert a == b


def test_header_values_are_part_of_the_identity():
    a = mcp_client._headers_key({"Authorization": "Bearer x"})
    b = mcp_client._headers_key({"Authorization": "Bearer y"})
    assert a != b, "two credentials would have shared one session"