Skip to content

The platform for continuously improving AI agents.

18.2 KB
Raw Blame
from __future__ import annotations

import asyncio
import json
import re
import threading
import time
import uuid
from concurrent.futures import ThreadPoolExecutor, TimeoutError
from contextlib import suppress
from threading import Event
from urllib.parse import parse_qs, urlsplit

import httpx
import pytest
from asgiref.sync import sync_to_async
from django.db import connection, transaction
from mcp_fixtures import EXPECTED_TOOL_NAMES, MAX_MANIFEST_BYTES, asgi_db
from starlette.testclient import TestClient

from overbae.models import APIToken, Capability, Project, ProjectMembership, Span, User
from overbae.services.mcp.server import create_mcp_application
from overbae.services.mcp.tools_projects import accessible_projects

pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]

MCP_URL = "/api/mcp/"


def _user() -> User:
    return User.objects.create_user(
        email=f"mcp-{uuid.uuid4().hex[:8]}@test.com",
        password="pw",
        clerk_user_id=f"clerk_{uuid.uuid4().hex}",
    )


def _token(*, permission: list[str] | None = None) -> tuple[str, APIToken]:
    user = _user()
    project = Project.objects.create(name="MCP", slug=f"mcp-{uuid.uuid4().hex[:8]}")
    ProjectMembership.objects.create(user=user, project=project)
    return APIToken.create_for_user(user, project=project, permission=permission)


def _rpc(method: str, params: dict | None = None) -> dict:
    payload = {"jsonrpc": "2.0", "id": 1, "method": method}
    if params is not None:
        payload["params"] = params
    return payload


def _post(client: TestClient, raw_key: str, body: dict, **headers):
    return client.post(
        MCP_URL,
        json=body,
        headers={
            "X-Api-Key": raw_key,
            "Accept": "application/json",
            **headers,
        },
    )


def _application():
    return create_mcp_application()


@asgi_db
def test_initialize_uses_official_streamable_http_transport(settings):
    settings.FRONTEND_URL = "https://console.example.test/workspace/"
    raw, token = _token()
    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc(
                "initialize",
                {
                    "protocolVersion": "2025-03-26",
                    "capabilities": {},
                    "clientInfo": {"name": "test-client", "version": "1.0"},
                },
            ),
        )

        result = response.json()["result"]
        project_uri = re.search(r"overmind://project/current", result["instructions"]).group()
        project_response = _post(client, raw, _rpc("resources/read", {"uri": project_uri}))

    assert response.status_code == 200
    result = response.json()["result"]
    assert result["protocolVersion"] == "2025-03-26"
    assert result["serverInfo"]["name"] == "overmind-platform"
    assert "tools" in result["capabilities"]
    assert project_response.status_code == 200
    project = json.loads(project_response.json()["result"]["contents"][0]["text"])
    console_url = urlsplit(project["console_url"])
    assert console_url.scheme == "https"
    assert console_url.netloc == "console.example.test"
    assert console_url.path == "/workspace/"
    assert parse_qs(console_url.query) == {"projectId": [str(token.project_id)]}


@asgi_db
def test_stateless_actions_keep_reported_client_identity_and_shared_keys_stay_ambiguous():
    from overbae.models import Activity

    raw, token = _token(permission=["read", "write"])
    with TestClient(_application()) as client:
        for client_name, expected_actor in [("codex", "Codex"), ("claude-code", "Coding agent")]:
            initialized = _post(
                client,
                raw,
                _rpc(
                    "initialize",
                    {
                        "protocolVersion": "2025-03-26",
                        "capabilities": {},
                        "clientInfo": {"name": client_name, "version": "1.0"},
                    },
                ),
            )
            assert "result" in initialized.json()
            created = _post(
                client,
                raw,
                _rpc(
                    "tools/call",
                    {
                        "name": "create_eval_matrix_row",
                        "arguments": {
                            "name": f"Rule from {client_name}",
                            "type": "llm",
                            "source": "Answer is grounded.",
                        },
                    },
                ),
            )
            assert not created.json()["result"].get("isError")
            event = Activity.objects.filter(project=token.project, kind="evaluation_added").first()
            assert event.actor_name == expected_actor
        before = Activity.objects.count()
        for _ in range(2):
            response = _post(
                client, raw, _rpc("resources/read", {"uri": "overmind://activity?limit=1"})
            )
            assert response.status_code == 200
        assert Activity.objects.count() == before
        renewed, _ = APIToken.create_for_user(
            token.user, project=token.project, permission=["read", "write"]
        )
        initialized = _post(
            client,
            renewed,
            _rpc(
                "initialize",
                {
                    "protocolVersion": "2025-03-26",
                    "capabilities": {},
                    "clientInfo": {"name": "codex", "version": "1.0"},
                },
            ),
        )
        assert "result" in initialized.json()
        assert Activity.objects.count() == before


@asgi_db
def test_transfer_preflight_does_not_register_an_agent_or_obscure_codex():
    from overbae.models import Activity, ActivityClient

    raw, token = _token(permission=["read", "write"])
    with TestClient(_application()) as client:
        for client_name in ["overmind-transfer", "codex", "overmind-transfer"]:
            response = _post(
                client,
                raw,
                _rpc(
                    "initialize",
                    {
                        "protocolVersion": "2025-03-26",
                        "capabilities": {},
                        "clientInfo": {"name": client_name, "version": "1"},
                    },
                ),
            )
            assert "result" in response.json()
            response = _post(
                client,
                raw,
                _rpc(
                    "tools/call",
                    {
                        "name": "list_projects",
                        "arguments": {},
                    },
                ),
            )
            assert not response.json()["result"].get("isError")
        assert list(
            ActivityClient.objects.filter(user=token.user).values_list("actor_name", flat=True)
        ) == ["Codex"]
        assert Activity.objects.filter(user=token.user).count() == 1
        response = _post(
            client,
            raw,
            _rpc(
                "tools/call",
                {
                    "name": "create_eval_matrix_row",
                    "arguments": {
                        "name": "After upload preflight",
                        "type": "llm",
                        "source": "Answer is grounded.",
                    },
                },
            ),
        )
        assert not response.json()["result"].get("isError")
        assert (
            Activity.objects.get(project=token.project, kind="evaluation_added").actor_name
            == "Codex"
        )


@asgi_db
def test_ping_is_protocol_level_and_catalog_lists_curated_tools():
    raw, token = _token()
    User.objects.filter(pk=token.user_id).update(agent_feedback=True)
    with TestClient(_application()) as client:
        response = _post(client, raw, _rpc("tools/list"))
        ping = _post(client, raw, _rpc("ping"))

    assert response.status_code == 200
    assert {tool["name"] for tool in response.json()["result"]["tools"]} == EXPECTED_TOOL_NAMES
    assert ping.status_code == 200
    assert ping.json()["result"] == {}


@asgi_db
def test_slow_tool_does_not_block_another_callers_authenticated_request(monkeypatch):
    slow_key, slow_token = _token()
    other_key, other_token = _token()
    entered, release = Event(), Event()

    def delayed_projects(context):
        if context.token.pk == slow_token.pk:
            entered.set()
            assert release.wait(10), "The test did not release the slow request"
        return accessible_projects(context)

    monkeypatch.setattr("overbae.services.mcp.tools_projects.accessible_projects", delayed_projects)
    body = _rpc("tools/call", {"name": "list_projects", "arguments": {}})
    with TestClient(_application()) as client, ThreadPoolExecutor(max_workers=2) as pool:
        slow = pool.submit(_post, client, slow_key, body)
        other_response = None
        try:
            assert entered.wait(5), "The slow request did not reach its domain operation"
            other = pool.submit(_post, client, other_key, body)
            with suppress(TimeoutError):
                other_response = other.result(timeout=3)
        finally:
            release.set()
        slow_response = slow.result(timeout=5)

    assert other_response is not None, "An independent authenticated request was blocked"
    for response, token in [(slow_response, slow_token), (other_response, other_token)]:
        assert response.status_code == 200
        result = response.json()["result"]
        assert not result.get("isError"), result
        assert [p["id"] for p in result["structuredContent"]["projects"]] == [str(token.project_id)]


@asgi_db
def test_tools_list_is_permission_filtered_and_stays_within_manifest_budget():
    read_raw, _ = _token(permission=["read"])
    full_raw, full_token = _token()
    User.objects.filter(pk=full_token.user_id).update(agent_feedback=True)
    with TestClient(_application()) as client:
        read_response = _post(client, read_raw, _rpc("tools/list"))
        full_response = _post(client, full_raw, _rpc("tools/list"))

    read_names = {tool["name"] for tool in read_response.json()["result"]["tools"]}
    full_tools = full_response.json()["result"]["tools"]

    assert read_response.status_code == 200
    assert full_response.status_code == 200
    assert read_names < {tool["name"] for tool in full_tools}
    assert len(full_tools) == len(EXPECTED_TOOL_NAMES)
    assert len(full_response.content) <= MAX_MANIFEST_BYTES


@asgi_db
def test_resources_and_prompts_list_over_streamable_http():
    raw, _ = _token()
    with TestClient(_application()) as client:
        resources = _post(client, raw, _rpc("resources/list"))
        prompts = _post(client, raw, _rpc("prompts/list"))

    assert resources.status_code == 200
    assert {item["name"] for item in resources.json()["result"]["resources"]} >= {
        "dataset-upload",
        "dataset-export",
        "connector-setup",
    }
    assert prompts.status_code == 200
    assert {item["name"] for item in prompts.json()["result"]["prompts"]} >= {
        "upload-dataset-file",
        "connect-traces",
    }


@asgi_db
def test_tool_call_exposes_complete_json_and_resource_links_to_text_only_clients():
    raw, token = _token(permission=["read"])
    capability = Capability.objects.create(
        project=token.project,
        name="Support",
        slug=f"support-{uuid.uuid4().hex[:8]}",
    )
    trace_id = uuid.uuid4().hex
    root = Span.objects.create(
        span_id=uuid.uuid4().hex[:16],
        trace_id=trace_id,
        project=token.project,
        capability=capability,
        name="support request",
        start_time_ns=1,
        end_time_ns=2,
        duration_ns=1,
        status_code=1,
    )
    Span.objects.create(
        span_id=uuid.uuid4().hex[:16],
        trace_id=trace_id,
        parent_span_id=root.span_id,
        project=token.project,
        attributes={"genai.total_tokens": 8, "genai.cost": 0.005},
    )

    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc("tools/call", {"name": "query_traces", "arguments": {}}),
        )

    assert response.status_code == 200
    result = response.json()["result"]
    text = next(item["text"] for item in result["content"] if item["type"] == "text")
    visible = json.loads(text)
    assert visible == result["structuredContent"]
    assert visible["n"] == 1
    assert visible["traces"][0]["trace_id"] == trace_id
    assert visible["traces"][0]["total_tokens"] == 8
    assert visible["traces"][0]["total_cost"] == 0.005
    assert any(
        item["type"] == "resource_link" and item["uri"] == f"overmind://traces/{trace_id}"
        for item in result["content"]
    )


@asgi_db
def test_initialize_accepts_the_path_with_or_without_a_trailing_slash():
    raw, _ = _token()
    body = _rpc(
        "initialize",
        {
            "protocolVersion": "2025-03-26",
            "capabilities": {},
            "clientInfo": {"name": "test-client", "version": "1.0"},
        },
    )
    with TestClient(_application(), follow_redirects=False) as client:
        responses = [
            client.post(
                path,
                json=body,
                headers={"X-Api-Key": raw, "Accept": "application/json"},
            )
            for path in ("/api/mcp/", "/api/mcp")
        ]

    assert [response.status_code for response in responses] == [200, 200]
    assert [response.headers.get("location") for response in responses] == [None, None]
    assert [response.json()["result"]["serverInfo"]["name"] for response in responses] == [
        "overmind-platform",
        "overmind-platform",
    ]


@asgi_db
def test_initialize_accepts_an_allowed_host_with_a_port():
    raw, _ = _token()
    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc("initialize", {"protocolVersion": "2025-03-26"}),
            Host="testserver:8123",
        )

    assert response.status_code == 200


@asgi_db
def test_initialize_allows_any_host_when_allowed_hosts_is_star(settings):
    settings.ALLOWED_HOSTS = ["*"]
    raw, _ = _token()
    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc(
                "initialize",
                {
                    "protocolVersion": "2025-03-26",
                    "capabilities": {},
                    "clientInfo": {"name": "test-client", "version": "1.0"},
                },
            ),
            Host="api-staging.overmindlab.ai",
        )

    assert response.status_code == 200
    assert response.json()["result"]["serverInfo"]["name"] == "overmind-platform"


@asgi_db
def test_unknown_host_is_rejected():
    raw, _ = _token()
    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc("initialize", {"protocolVersion": "2025-03-26"}),
            Host="evil.example",
        )

    assert response.status_code == 421
    assert response.json()["error"]["code"] == "invalid_request"


@asgi_db
def test_unsupported_protocol_version_is_rejected():
    raw, _ = _token()
    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc("initialize", {"protocolVersion": "2099-01-01"}),
        )

    assert response.status_code == 400
    assert response.json()["error"]["code"] == "protocol_version_unsupported"


@asgi_db
def test_origin_is_validated_on_initialize():
    raw, _ = _token()
    with TestClient(_application()) as client:
        response = _post(
            client,
            raw,
            _rpc("initialize", {"protocolVersion": "2025-03-26"}),
            Origin="https://not-allowed.example",
        )

    assert response.status_code == 403
    assert response.json()["error"]["code"] == "origin_not_allowed"


def _hold_token_row(
    token: APIToken, holder: list[int], locked: threading.Event, release: threading.Event
) -> None:
    try:
        with transaction.atomic():
            APIToken.objects.select_for_update().get(pk=token.pk)
            with connection.cursor() as cursor:
                cursor.execute("SELECT pg_backend_pid()")
                holder.append(cursor.fetchone()[0])
            locked.set()
            release.wait(30)
    finally:
        connection.close()


def _a_request_waits_behind(holder_pid: int) -> bool:
    try:
        deadline = time.monotonic() + 10
        while time.monotonic() < deadline:
            with connection.cursor() as cursor:
                cursor.execute(
                    "SELECT 1 FROM pg_stat_activity WHERE %s = ANY(pg_blocking_pids(pid))",
                    [holder_pid],
                )
                if cursor.fetchone():
                    return True
            time.sleep(0.05)
        return False
    finally:
        connection.close()


@asgi_db
@pytest.mark.asyncio
async def test_a_request_blocked_in_the_database_does_not_hold_up_other_requests():
    raw_blocked, blocked = await sync_to_async(_token)()
    raw_free, _ = await sync_to_async(_token)()
    holder_pid: list[int] = []
    locked, release = threading.Event(), threading.Event()
    holder = threading.Thread(target=_hold_token_row, args=(blocked, holder_pid, locked, release))
    holder.start()
    assert await asyncio.to_thread(locked.wait, 10)

    app = _application()
    body = _rpc("ping")
    headers = {"Accept": "application/json", "Host": "testserver"}
    try:
        async with (
            app.router.lifespan_context(app),
            httpx.AsyncClient(
                transport=httpx.ASGITransport(app=app), base_url="http://testserver"
            ) as client,
        ):
            stuck = asyncio.create_task(
                client.post(MCP_URL, json=body, headers={**headers, "X-Api-Key": raw_blocked})
            )
            assert await asyncio.to_thread(_a_request_waits_behind, holder_pid[0])
            free = await asyncio.wait_for(
                client.post(MCP_URL, json=body, headers={**headers, "X-Api-Key": raw_free}), 10
            )
            assert free.status_code == 200
            assert not stuck.done()
            release.set()
            assert (await asyncio.wait_for(stuck, 10)).status_code == 200
    finally:
        release.set()
        await asyncio.to_thread(holder.join)