Skip to content

The platform for continuously improving AI agents.

20.5 KB
Raw Blame
"""Official-SDK MCP server and Streamable HTTP application."""

from __future__ import annotations

import json
import logging
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager, suppress
from dataclasses import replace
from typing import Any
from urllib.parse import parse_qs, urlsplit
from uuid import UUID

from asgiref.sync import ThreadSensitiveContext, sync_to_async
from django.conf import settings
from django.db import connections
from django.http.request import split_domain_port, validate_host
from mcp import types
from mcp.server.lowlevel import Server
from mcp.server.streamable_http import MCP_PROTOCOL_VERSION_HEADER
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import (
    DEFAULT_MAX_REQUEST_BODY_SIZE,
    TransportSecuritySettings,
)
from mcp.shared.version import SUPPORTED_PROTOCOL_VERSIONS
from posthog import Posthog
from posthog.mcp import PostHogMcpStatelessSessionMiddleware, instrument
from posthog.mcp.types import MCPAnalyticsOptions, UserIdentity
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.types import Message, Receive, Scope, Send

from overbae.services.activity import connected
from overbae.services.mcp import CONTRACT_VERSION
from overbae.services.mcp.auth import MCP_PATHS, MCPAuthMiddleware
from overbae.services.mcp.catalog import CATALOG
from overbae.services.mcp.context import get_context
from overbae.services.mcp.errors import MCPError, error_payload
from overbae.services.mcp.oauth_routes import domain_challenge, oauth_routes
from overbae.services.mcp.prompts import get_prompt as render_prompt
from overbae.services.mcp.prompts import list_prompts
from overbae.services.mcp.resources import read_resource, resource_list, resource_templates

logger = logging.getLogger(__name__)

SERVER_NAME = "overmind-platform"
SERVER_VERSION = CONTRACT_VERSION

mcp_server = Server(
    SERVER_NAME,
    version=SERVER_VERSION,
    instructions=(
        "Use MCP for Overmind operations and the local CLI for file bytes. Missing tools, credentials or upload failures are not reasons to open a browser; report the connection error. Only open the Console when the user explicitly requests a visual view. "
        "Overmind is an agent improvement platform. Read overmind://interface/current for connected contract identity and workflow rules. Drafts never submit provider work; use explicit preparation and launch operations. Call list_projects first to find "
        "accessible projects and choose the project relevant to the user's request. "
        "Use list_objects to discover models, jobs and evaluations. Account connections require project_id on each project tool and resource URI; "
        "there is no shared selected-project state. Follow returned resource links. "
        "Read overmind://project/current?project_id=ID for repository provenance and "
        "the ordinary Console URL. Project-scoped API keys remain limited to their project; "
        "do not mix records from a different Console project or put credentials in tool arguments. "
        "MCP provides the integration without a plugin or custom UI. Discover tools, "
        "resources and prompts through their MCP lists; use the current schemas and returned "
        "identifiers rather than inventing endpoint-shaped tools. Native prompts guide longer "
        "workflows; optional skills cover local repository work and clients without prompt support. "
        "Tools return the same data as structured content and JSON text. Treat isError and "
        "structured error fields as failures; follow resource links and poll get_job with "
        "the returned kind and id for asynchronous work. Preserve pagination, truncation, "
        "missing scores, metric errors and pinned dataset/model identities in conclusions. "
        "Inspection does not authorize mutations or paid runs. Check readiness and costs "
        "before an authorized evaluation or training launch. Use get_credit_balance for balances and "
        "budget monitoring; read credit_reporting in overmind://interface/current for limits. "
        "The calling coding agent owns dataset interpretation, transformation authoring and semantic work. "
        "The Console has its own assistant that uses these same tools; it never acts for an MCP connection. Retain scripts automatically with save_dataset_pipeline(dataset=..., package=...); never ask users whether to keep them. Retain scoped uncertainties and their evidence in the script and output; successful formatting and execution do not establish suitability. Discover reusable project revisions with inspect_dataset_workbench; prefer reuse or an attributed derived_from variant. Upload original source bytes once, pin upstream dataset revisions, and retain transformation code before full-data processing. Never upload locally transformed derivatives as unrelated source datasets. New transformations require a retained Python package; package-free historical revisions are read-only. Upload scripts using overmind dataset pipeline-upload, register with save_dataset_pipeline, validate_dataset_pipeline, preview then run_dataset_pipeline. Each successful run replaces the displayed preparation with its selected end-to-end process. Corrections update the same recipe family and rerun from its original source; do not append repair cells or create prepared-v2 datasets. Pinned consumer inputs remain immutable internally. Enable saved source bindings explicitly for repeated snapshot rebuilds. import_dataset_version is for genuine external results, not a substitute for retaining transformation code. "
        "When asked to prepare data in Overmind, local files alone are not completion: publish and inspect the requested dataset or report an explicit blocker. Inspect the named capability's contract and examples before choosing target semantics; link it explicitly. Preserve unknown meaning rather than inventing task labels. Separate meaningful preparation stages and review branches from final formatting. Use the returned upload argv and identifiers verbatim, replacing only documented placeholders. "
        "Declare the final step consumer (decision_train, decision_eval, chat_train or model_eval) so previews validate nested targets. Use batch_rows only for row-independent steps; sorting, grouping and deduplication require the full population. Preserve evidenced target semantics and structured provenance; never remove them to bypass a validator. Preview defers absolute min_rows/max_rows bounds to publication; lineage and preserve_rows checks remain enforced. Inspect deferred checks before publishing. Follow poll_after_seconds; queued work alone is not a failure or reason to resubmit. Report format compatibility separately from task suitability, which remains unmeasured without attributable evidence. "
        "Author explicit step IDs and input dependencies. Converge intended branches with inputs=[earlier IDs]; disjoint rows concatenate in declared order, overlapping source_row identities fail. The last step is the output: inspect flow.unconsumed_steps before publication. Training preparation should end in trainable examples with review metadata, not disconnected inspection tables; never invent targets or treat flags as resolved. Script conditions cite their entrypoint line and describe code, not independently verified semantics. Receipts record actual parent cells, counts and fingerprints. Pin sources and use stable request keys: an identical retry with a mutation's request_key returns its stored result once the first call finishes; until then it returns request_in_progress, so never resubmit under a new key. "
        "Use author-dataset-transformation for conditional authoring, retrieval and adaptation. inspect_dataset_workbench(pipeline=revision ID) retrieves an exact recipe and its family history. Only retained packages execute in the approved isolated runtime; other code and semantic/provider work stay in the native environment. Technical format checks do not prove semantic quality or exhaustive/exclusive branches. "
        "When submit_feedback is listed and an Overmind operation fails, contradicts its "
        "description or needs repeated attempts, report it once with submit_feedback. "
        "Local scanning, file transfers, credentials and repository execution use the CLI "
        "handoffs in the relevant resources/prompts. The server does not edit local files. "
        "When a user wants a visual view, open the ordinary Console for this project; "
        "opening a page does not authorize its write actions."
    ),
)


@mcp_server.list_tools()
async def _list_tools() -> list[types.Tool]:
    return CATALOG.visible_to(get_context())


@mcp_server.call_tool(validate_input=False)
async def _call_tool(name: str, arguments: dict[str, Any] | None) -> types.CallToolResult:
    context = get_context()
    params = mcp_server.request_context.session.client_params
    if params:
        context = replace(context, client_name=params.clientInfo.name[:100])
    elif hasattr(context.token, "grant"):
        client_name = await sync_to_async(
            lambda: context.token.grant.client.metadata.get("client_name", ""),
            thread_sensitive=True,
        )()
        context = replace(context, client_name=str(client_name)[:100])
    return await CATALOG.call(name, arguments or {}, context)


@mcp_server.list_resources()
async def _list_resources() -> list[types.Resource]:
    get_context()
    return resource_list()


@mcp_server.list_resource_templates()
async def _list_resource_templates() -> list[types.ResourceTemplate]:
    get_context()
    return resource_templates()


@mcp_server.list_prompts()
async def _list_prompts() -> list[types.Prompt]:
    get_context()
    return list_prompts()


@mcp_server.get_prompt()
async def _get_prompt(name: str, arguments: dict[str, str] | None) -> types.GetPromptResult:
    get_context()
    return render_prompt(name, arguments)


@mcp_server.read_resource()
async def _read_resource(uri):
    return await read_resource(uri)


def _identify(_request, _extra) -> UserIdentity | None:
    user = get_context().user
    if not user.clerk_user_id:
        return None
    properties = {"email": user.email} if user.email and not user.is_guest else None
    return UserIdentity(distinct_id=user.clerk_user_id, properties=properties)


def _project_properties(request, _extra) -> dict[str, str]:
    project = get_context().project
    if project is not None:
        return {"project_id": str(project.pk)}
    params = request.get("params") if isinstance(request, dict) else None
    params = params if isinstance(params, dict) else {}
    arguments = params.get("arguments")
    candidate = arguments.get("project_id") if isinstance(arguments, dict) else None
    if candidate is None and isinstance(params.get("uri"), str):
        candidate = parse_qs(urlsplit(params["uri"]).query).get("project_id", [None])[0]
    try:
        return {"project_id": str(UUID(str(candidate)))}
    except ValueError:
        return {}


def _error_code(response: Any) -> str | None:
    structured = response.get("structuredContent") if isinstance(response, dict) else None
    error = structured.get("error") if isinstance(structured, dict) else None
    code = error.get("code") if isinstance(error, dict) else None
    return code if isinstance(code, str) else None


# Tool arguments, results and error text carry customer data and stay on the server.
_PAYLOAD_PROPERTIES = ("$mcp_parameters", "$mcp_response", "$mcp_error_message")


def _drop_payloads(event: dict[str, Any]) -> dict[str, Any]:
    properties = event.get("properties") or {}
    if properties.get("$mcp_is_error") and (code := _error_code(properties.get("$mcp_response"))):
        properties["error_code"] = code
    for key in _PAYLOAD_PROPERTIES:
        properties.pop(key, None)
    return event


# The low-level server passes injected analytics arguments through to the
# catalog, whose input models forbid extra fields.
ANALYTICS_OPTIONS = MCPAnalyticsOptions(
    context=False,
    enable_conversation_id=False,
    capture_model=False,
    enable_exception_autocapture=False,
    identify=_identify,
    event_properties=_project_properties,
    before_send=_drop_payloads,
)
posthog_client = (
    Posthog(settings.POSTHOG_PROJECT_TOKEN, host=settings.POSTHOG_HOST)
    if settings.POSTHOG_PROJECT_TOKEN
    else None
)
mcp_analytics = (
    instrument(mcp_server, posthog_client, ANALYTICS_OPTIONS) if posthog_client else None
)


def _allowed_hosts() -> list[str]:
    hosts = list(getattr(settings, "ALLOWED_HOSTS", []))
    if "testserver" not in hosts:
        hosts.append("testserver")
    return hosts


def _transport_security() -> TransportSecuritySettings:
    # SDK host matching is exact and drops Django `*` / `.domain` wildcards.
    # MCPTransportMiddleware already applies Django's rules.
    return TransportSecuritySettings(enable_dns_rebinding_protection=False)


def _json_error(error: MCPError, status_code: int) -> JSONResponse:
    return JSONResponse({"error": error_payload(error)}, status_code=status_code)


def _header(scope: Scope, name: str) -> str | None:
    for key, value in scope.get("headers", []):
        if key.decode("latin-1").lower() == name.lower():
            return value.decode("latin-1")
    return None


def _origin_allowed(origin: str | None) -> bool:
    return not origin or origin in getattr(settings, "CORS_ALLOWED_ORIGINS", [])


def _host_allowed(host: str | None) -> bool:
    if not host:
        return False
    domain, _port = split_domain_port(host)
    return bool(domain and validate_host(domain, _allowed_hosts()))


def _protocol_allowed(version: Any) -> bool:
    return version is None or version in SUPPORTED_PROTOCOL_VERSIONS


async def _read_body(receive: Receive) -> tuple[bytes, Receive]:
    chunks: list[bytes] = []
    size = 0
    while True:
        message = await receive()
        if message["type"] != "http.request":
            break
        chunk = message.get("body", b"")
        size += len(chunk)
        if size > DEFAULT_MAX_REQUEST_BODY_SIZE:
            raise MCPError("invalid_request", "The MCP request body is too large.")
        chunks.append(chunk)
        if not message.get("more_body", False):
            break
    body = b"".join(chunks)
    replayed = False

    async def replay() -> Message:
        nonlocal replayed
        if not replayed:
            replayed = True
            return {"type": "http.request", "body": body, "more_body": False}
        return await receive()

    return body, replay


_close_connections = sync_to_async(connections.close_all, thread_sensitive=True)


class RequestThreadMiddleware:
    """Django's ASGIHandler gives each request its own sync thread and closes its
    connections; MCP and OAuth requests never reach that handler. Without the
    context, every thread-sensitive call in the process shares one thread, so one
    slow tool call queues every other request behind it."""

    def __init__(self, app):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
        async with ThreadSensitiveContext():
            try:
                await self.app(scope, receive, send)
            finally:
                # Connections are per thread, and this thread ends with the context.
                await _close_connections()


class MCPTransportMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        if scope.get("type") != "http" or scope.get("path") not in MCP_PATHS:
            await self.app(scope, receive, send)
            return

        if not _host_allowed(_header(scope, "host")):
            await _json_error(
                MCPError("invalid_request", "The MCP host is not allowed."),
                421,
            )(scope, receive, send)
            return
        if not _origin_allowed(_header(scope, "origin")):
            await _json_error(
                MCPError("origin_not_allowed", "The MCP origin is not allowed."),
                403,
            )(scope, receive, send)
            return

        header_version = _header(scope, MCP_PROTOCOL_VERSION_HEADER)
        if not _protocol_allowed(header_version):
            await _json_error(
                MCPError(
                    "protocol_version_unsupported",
                    "The MCP protocol version is not supported.",
                ),
                400,
            )(scope, receive, send)
            return

        if scope.get("method") != "POST":
            await self.app(scope, receive, send)
            return

        content_type = (_header(scope, "content-type") or "").split(";", 1)[0].lower()
        if content_type != "application/json":
            await _json_error(
                MCPError("invalid_request", "MCP requests must use application/json."),
                400,
            )(scope, receive, send)
            return

        try:
            body, replay = await _read_body(receive)
        except MCPError as error:
            await _json_error(error, 413)(scope, receive, send)
            return
        try:
            payload = json.loads(body)
        except (TypeError, ValueError):
            payload = None
        if isinstance(payload, dict) and payload.get("method") == "initialize":
            params = payload.get("params")
            requested_version = params.get("protocolVersion") if isinstance(params, dict) else None
            if not _protocol_allowed(requested_version):
                await _json_error(
                    MCPError(
                        "protocol_version_unsupported",
                        "The MCP protocol version is not supported.",
                    ),
                    400,
                )(scope, replay, send)
                return

        if isinstance(payload, dict) and payload.get("method") == "initialize":
            chunks = []
            succeeded = False

            async def capture(message):
                nonlocal succeeded
                if message["type"] == "http.response.body":
                    chunks.append(message.get("body", b""))
                    if not message.get("more_body", False):
                        with suppress(TypeError, ValueError):
                            succeeded = "result" in json.loads(b"".join(chunks))
                await send(message)

            await self.app(scope, replay, capture)
            if succeeded:
                client_info = (payload.get("params") or {}).get("clientInfo") or {}
                client_name = client_info.get("name")
                if isinstance(client_name, str):
                    try:
                        await sync_to_async(connected, thread_sensitive=True)(
                            replace(get_context(), client_name=client_name[:100])
                        )
                    except Exception:
                        logger.exception("Could not retain MCP connection milestone")
            return
        await self.app(scope, replay, send)


class _TransportEndpoint:
    def __init__(self, manager: StreamableHTTPSessionManager) -> None:
        self.manager = manager

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        await self.manager.handle_request(scope, receive, send)


def create_mcp_application() -> Starlette:
    manager = StreamableHTTPSessionManager(
        app=mcp_server,
        json_response=True,
        stateless=True,
        session_idle_timeout=None,
        security_settings=_transport_security(),
    )

    @asynccontextmanager
    async def lifespan(_: Starlette) -> AsyncIterator[None]:
        async with manager.run():
            yield
        if mcp_analytics:
            await mcp_analytics.flush()
            posthog_client.shutdown()

    endpoint = _TransportEndpoint(manager)
    if mcp_analytics:
        endpoint = PostHogMcpStatelessSessionMiddleware(endpoint)

    app = Starlette(
        routes=[
            *oauth_routes(),
            Route("/.well-known/openai-apps-challenge", endpoint=domain_challenge, methods=["GET"]),
            *(
                Route(path, endpoint=endpoint, methods=["GET", "POST", "DELETE"])
                for path in MCP_PATHS
            ),
        ],
        middleware=[
            Middleware(RequestThreadMiddleware),
            Middleware(MCPAuthMiddleware),
            Middleware(MCPTransportMiddleware),
        ],
        lifespan=lifespan,
    )
    return app