Skip to content

The platform for continuously improving AI agents.

11.2 KB
Raw Blame
from asgiref.sync import sync_to_async
from django.db import transaction
from django.db.models import Q

from overbae.core.errors import DatasetError, InputValidationError
from overbae.models import ResearchAction, ResearchExperiment
from overbae.services import (
    experiment_engine,
    experiment_operator,
    experiment_plans,
    experiment_source,
    research_experiments,
    research_triggers,
)
from overbae.services.mcp.contracts.common import JobReceipt, ResourceLinkContract
from overbae.services.mcp.contracts.experiments import (
    AutomationReceipt,
    ConfigureExperimentTrigger,
    ExperimentReceipt,
    InspectExperiment,
    PreviewExperimentCell,
    SaveExperimentSource,
    StartExperimentRun,
    SubmitExperimentEvent,
)
from overbae.services.mcp.errors import MCPError


def invoke(name, payload, context):
    experiment = ResearchExperiment.objects.filter(
        project=context.project, pk=payload.experiment, deleted_at__isnull=True
    ).first()
    if experiment is None:
        raise MCPError("experiment_not_found", "The experiment is unavailable in this project")
    try:
        arguments = payload.model_dump(mode="json", exclude={"experiment"})
        if name == "configure_experiment_trigger":
            result = research_triggers.configure(
                experiment,
                context.user,
                operation=payload.operation,
                trigger_id=payload.trigger,
                payload=arguments["payload"],
            )
            return AutomationReceipt(
                trigger=result,
                resource={
                    "uri": f"overmind://experiments/{experiment.pk}/automation",
                    "title": "Experiment automation",
                },
            )
        if name == "submit_experiment_event":
            result = research_triggers.receive(experiment, context.user, arguments)
            return AutomationReceipt(
                event=result,
                resource={
                    "uri": f"overmind://experiments/{experiment.pk}/automation",
                    "title": "Experiment automation",
                },
            )
        if name == "inspect_experiment" and payload.automation:
            return ExperimentReceipt(
                experiment=research_triggers.inspect(
                    experiment,
                    cursor=payload.cursor,
                    limit=payload.page_size,
                    evidence_fire=payload.evidence_fire,
                    evidence_cursor=payload.evidence_cursor,
                )
            )
        if name == "inspect_experiment" and payload.operator:
            return ExperimentReceipt(
                experiment=experiment_operator.journal(
                    experiment, after=payload.after, limit=payload.page_size
                )
            )
        if name == "inspect_experiment" and payload.decisions:
            decisions = ResearchAction.objects.filter(
                Q(agent__assignment__experiment_revision__experiment=experiment)
                | Q(agent__assignment__execution_mandate__experiment=str(experiment.pk)),
                agent__assignment__project_id=experiment.project_id,
                tool="experiment_decision",
            ).order_by("created_at", "pk")
            if payload.cursor:
                anchor = decisions.filter(pk=payload.cursor).first()
                if anchor is None:
                    raise InputValidationError("The decision cursor is unavailable")
                decisions = decisions.filter(
                    Q(created_at__gt=anchor.created_at)
                    | Q(created_at=anchor.created_at, pk__gt=anchor.pk)
                )
            page = list(decisions[: payload.page_size + 1])
            return ExperimentReceipt(
                experiment={
                    "decisions": [
                        {"id": str(item.pk), "state": item.state, "decision": item.result}
                        for item in page[: payload.page_size]
                    ],
                    "next_cursor": str(page[payload.page_size - 1].pk)
                    if len(page) > payload.page_size
                    else None,
                }
            )
        if name == "start_experiment_run":
            # Worker imports the execution domain when it receives the committed task.
            from overbae.tasks.research import advance_flow

            run = experiment_engine.start(experiment, context.user, budget={}, **arguments)
            transaction.on_commit(lambda: advance_flow.delay(str(run.pk)))
            return ExperimentReceipt(experiment=research_experiments.run_record(run))
        if name == "save_experiment_source":
            return ExperimentReceipt(
                experiment=experiment_source.page(
                    experiment_source.save(experiment, context.user, **arguments)
                )
            )
        if name == "preview_experiment_cell":
            run = experiment_source.preview(experiment, context.user, **arguments)
            return JobReceipt(
                kind="dataset_pipeline",
                id=run["id"],
                status=run["state"],
                resource=ResourceLinkContract(
                    uri=f"overmind://jobs/dataset_pipeline/{run['id']}", title="Preparation preview"
                ),
            )
        if payload.plan:
            return ExperimentReceipt(
                experiment=experiment_plans.resolve(
                    experiment,
                    revision=payload.revision or experiment.version,
                    parameters=payload.parameters,
                    reuse_run=payload.reuse_run,
                    rerun_from=payload.rerun_from,
                )
            )
        if payload.node:
            source = experiment_source.inspect(
                experiment,
                revision=payload.revision or experiment.version,
                node=payload.node,
                run=payload.run,
            )
            return ExperimentReceipt(
                experiment=experiment_source.page(
                    source, payload.file, payload.offset, payload.limit
                )
            )
        revision = experiment.revisions.filter(
            number=payload.revision or experiment.version
        ).first()
        if revision is None:
            raise InputValidationError("The experiment revision is unavailable")
        return ExperimentReceipt(
            experiment={
                "id": str(experiment.pk),
                "name": experiment.name,
                **research_experiments.flow(context.project, revision),
            }
        )
    except (InputValidationError, DatasetError) as exc:
        raise MCPError(getattr(exc, "code", "invalid_experiment"), exc.detail) from exc


def register_experiment_tools(catalog):
    from overbae.services.mcp.catalog import ToolDefinition

    for name, request, response, description, read_only in (
        (
            "configure_experiment_trigger",
            ConfigureExperimentTrigger,
            AutomationReceipt,
            "Create, update or disable a durable experiment trigger with frozen authority. Reuse mutation keys; update requires expected_version. Returns the retained synchronous configuration receipt. Integration triggers use kind=integration, target=run, every_hours, and configuration.integration={partner:openrouter,event:model_added,conditions:[{field,operator,value}],include_existing:false}. Bind a string flow parameter through event_parameters={parameter:model}. OpenRouter supports provider/is, id/is or starts_with, family/starts_with (model slug after provider/), context_length/at_least, prompt_price or completion_price/at_most (USD per million tokens), supported_parameters/includes. The initial catalogue is a baseline unless include_existing is explicit; duplicate model IDs never refire.",
            False,
        ),
        (
            "submit_experiment_event",
            SubmitExperimentEvent,
            AutomationReceipt,
            "Retain an authenticated event with exact project bindings. Events supply evidence, never execution authority. Repeat the same key after unknown acknowledgement. Returns a durable receipt before background execution.",
            False,
        ),
        (
            "inspect_experiment",
            InspectExperiment,
            ExperimentReceipt,
            "Inspect a saved experiment, a node source inventory, or plan=true for exact work/reuse before admission. Read source with file, offset and limit; follow next_offset without truncation. operator=true pages the operator's journal with after.",
            True,
        ),
        (
            "save_experiment_source",
            SaveExperimentSource,
            ExperimentReceipt,
            "Save preparation or connected training source as a new experiment revision. Pin expected_version; concurrent edits conflict. Active and historical jobs keep their original source. Does not execute.",
            False,
        ),
        (
            "preview_experiment_cell",
            PreviewExperimentCell,
            JobReceipt,
            "Preview one retained Python cell and its dependencies from exact readable inputs. Bounded to 1–1000 rows. Does not publish data or launch training. Poll the dataset_pipeline receipt.",
            False,
        ),
        (
            "start_experiment_run",
            StartExperimentRun,
            ExperimentReceipt,
            "Start the exact run plan returned by inspect_experiment(plan=true). Stale plans conflict; repeat the same request key after unknown acknowledgement. Does not imply completion. operator attaches a background agent that journals findings (suggest) and may also retry or correct the run (remediate).",
            False,
        ),
    ):

        async def handler(payload, context, name=name):
            return await sync_to_async(invoke, thread_sensitive=True)(name, payload, context)

        catalog.register(
            ToolDefinition(
                name=name,
                title=name.replace("_", " ").capitalize(),
                description=description,
                input_model=request,
                output_model=response,
                read_only=read_only,
                idempotent=True,
                open_world=name
                in {
                    "preview_experiment_cell",
                    "start_experiment_run",
                    "configure_experiment_trigger",
                    "submit_experiment_event",
                },
                required_scopes=frozenset(
                    {
                        "overmind:read"
                        if read_only
                        else "overmind:train"
                        if name
                        in {
                            "start_experiment_run",
                            "configure_experiment_trigger",
                            "submit_experiment_event",
                        }
                        else "overmind:data:write"
                    }
                ),
                cost_class="compute"
                if name in {"preview_experiment_cell", "start_experiment_run"}
                else "free",
                async_mode="job"
                if name in {"preview_experiment_cell", "start_experiment_run"}
                else "sync",
            ),
            handler,
        )