The platform for continuously improving AI agents.
Improve MCP discovery, monitoring and mutation recovery (#281)
Tyler-Edwardsd7dade6406e2
diff --git a/.agents/skills/mcp/SKILL.md b/.agents/skills/mcp/SKILL.mdindex 2564b63b..2ecb192c 100644--- a/.agents/skills/mcp/SKILL.md+++ b/.agents/skills/mcp/SKILL.md@@ -87,7 +87,7 @@ Tools call the domain layer directly. They may share serializers or entity-resol1. Register one `ToolDefinition` in that module's `register_<domain>_tools` with accurate `read_only`, `idempotent`, `open_world`, `required_scopes`, `cost_class` and `async_mode`. Import a new domain module into `CATALOG` only when it is genuinely new.1. Return the declared output model, never a raw dict. Add `resource` or `resource_links` for durable entities.1. For background work, return a `JobReceipt` with `kind`, `id`, `status` and an `overmind://jobs/{kind}/{id}` resource, and teach `get_job` and the resource reader that kind.-1. Operations that start paid or long work take a stable `request_key`; an identical retry returns the original receipt and a changed payload conflicts.+1. Operations that start paid or long work take a stable `request_key`; an identical retry returns the original receipt and a changed payload conflicts. The catalog adds an optional `request_key` to other project mutations (`services/mcp/mutations.py`): it stores the response, a retryable `MCPError` releases the key, and an unexpected failure leaves the receipt `unknown`.1. Bump `CONTRACT_VERSION` in `services/mcp/__init__.py` with every contract change. `overmind://interface/current` publishes it with the catalog fingerprint.1. Keep `tools/list` within `MAX_MANIFEST_BYTES` (`tests/mcp_fixtures.py`); output schemas and secrets stay out of discovery.@@ -97,7 +97,7 @@ Keep handlers thin. Never copy a Console view's business logic into `tools_*.py``ToolCatalog.call` validates input, runs the handler, validates output, then `tool_result` emits the same object as `structuredContent` and as compact JSON text for clients that read only text. Matching `resource`/`resource_links` also become native `ResourceLink` content. Identifiers, costs, rows and receipts are contract fields, never prose only.-`MCPError` becomes `{"error": {"code", "message", "retryable", "fields"}}` with `isError=true`. Unexpected failures become a safe `internal_error`. Messages come from authored text or authored domain errors; never leak raw exceptions, provider responses, tokens or tracebacks.+`MCPError` becomes `{"error": {"code", "message", "retryable", "fields", "next_actions"}}` with `isError=true`. Unexpected failures become a safe `internal_error`. Messages come from authored text or authored domain errors; never leak raw exceptions, provider responses, tokens or tracebacks.Bound tool responses losslessly: page large results, or fail with a typed error such as `query_result_too_large`, rather than clip values. Action receipts stay compact and point to a resource with the full evidence.diff --git a/overbae/migrations/0056_mcp_mutations_and_eval_revisions.py b/overbae/migrations/0056_mcp_mutations_and_eval_revisions.pynew file mode 100644index 00000000..6bdd4e59--- /dev/null+++ b/overbae/migrations/0056_mcp_mutations_and_eval_revisions.py@@ -0,0 +1,44 @@+# Generated by Django 6.0.8 on 2026-11-01 21:24++import django.db.models.deletion+import uuid+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('overbae', '0055_activity_task_index'),+ ]++ operations = [+ migrations.CreateModel(+ name='EvalMatrixRevision',+ fields=[+ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),+ ('definition', models.JSONField()),+ ('created_at', models.DateTimeField(auto_now_add=True)),+ ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),+ ('row', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='revisions', to='overbae.evalmatrix')),+ ],+ ),+ migrations.CreateModel(+ name='MCPMutation',+ fields=[+ ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),+ ('request_key', models.CharField(max_length=128)),+ ('tool', models.CharField(max_length=64)),+ ('fingerprint', models.CharField(max_length=64)),+ ('state', models.CharField(default='pending', max_length=16)),+ ('result', models.JSONField(default=dict)),+ ('created_at', models.DateTimeField(auto_now_add=True)),+ ('updated_at', models.DateTimeField(auto_now=True)),+ ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='overbae.project')),+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),+ ],+ options={+ 'constraints': [models.UniqueConstraint(fields=('project', 'request_key'), name='mcp_mutation_project_key')],+ },+ ),+ ]diff --git a/overbae/models/__init__.py b/overbae/models/__init__.pyindex 7b151245..71d64437 100644--- a/overbae/models/__init__.py+++ b/overbae/models/__init__.py@@ -63,6 +63,7 @@ from .innermind import (SignalSubscription,)from .mcp_oauth import MCPOAuthClient, MCPOAuthGrant, MCPOAuthToken+from .mcp_operations import EvalMatrixRevision, MCPMutationfrom .operations import InferenceRequest, OperationalEvent, OperationalRunfrom .optimizer import (OptimizerCandidate,@@ -75,6 +76,8 @@ from .training_monitoring import TrainingCheckpoint, TrainingValidationRunfrom .training_plan import TrainingPlan__all__ = [+ "MCPMutation",+ "EvalMatrixRevision","Activity","ActivityRead","ActivityClient",diff --git a/overbae/models/mcp_operations.py b/overbae/models/mcp_operations.pynew file mode 100644index 00000000..d3886897--- /dev/null+++ b/overbae/models/mcp_operations.py@@ -0,0 +1,34 @@+import uuid++from django.conf import settings+from django.db import models+++class MCPMutation(models.Model):+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ project = models.ForeignKey("overbae.Project", on_delete=models.CASCADE)+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)+ request_key = models.CharField(max_length=128)+ tool = models.CharField(max_length=64)+ fingerprint = models.CharField(max_length=64)+ state = models.CharField(max_length=16, default="pending")+ result = models.JSONField(default=dict)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["project", "request_key"], name="mcp_mutation_project_key"+ )+ ]+++class EvalMatrixRevision(models.Model):+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ row = models.ForeignKey(+ "overbae.EvalMatrix", on_delete=models.CASCADE, related_name="revisions"+ )+ definition = models.JSONField()+ created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)+ created_at = models.DateTimeField(auto_now_add=True)diff --git a/overbae/services/billing_ledger.py b/overbae/services/billing_ledger.pyindex f9913313..36e8d8bf 100644--- a/overbae/services/billing_ledger.py+++ b/overbae/services/billing_ledger.py@@ -9,9 +9,11 @@ from typing import Anyfrom uuid import UUIDfrom django.db import IntegrityError, transaction-from django.db.models import Q, Sum+from django.db.models import Case, CharField, Count, Q, Sum, Value, When+from django.db.models.fields.json import KeyTextTransform+from django.utils import timezone-from overbae.models import BillingService, BillingTelemetry, User+from overbae.models import BillingService, BillingTelemetry, FinetuningJob, Userfrom overbae.services import model_cataloglogger = logging.getLogger(__name__)@@ -226,3 +228,63 @@ def charge_llm_usage(getattr(user, "pk", None),)return None+++def project_credit_report(+ user,+ project,+ *,+ since=None,+ before=None,+ training_job=None,+ training_experiment=None,+ offset=0,+ limit=20,+):+ """Account-owned posted charges; missing attribution stays in the null group."""+ observed_at = timezone.now()+ query = BillingTelemetry.objects.filter(+ user=user, project=project, amount__lt=0, timestamp__lte=observed_at+ )+ if since:+ query = query.filter(timestamp__gte=since)+ if before:+ query = query.filter(timestamp__lt=before)+ query = query.annotate(+ training_job_id=Case(+ When(+ service=BillingService.FINETUNING_JOB, then=KeyTextTransform("job_id", "metadata")+ ),+ default=Value(None),+ output_field=CharField(),+ )+ )+ if training_job:+ query = query.filter(training_job_id=str(training_job))+ if training_experiment:+ jobs = FinetuningJob.objects.filter(+ project=project, group_id=training_experiment+ ).values_list("id", flat=True)+ query = query.filter(training_job_id__in=[str(pk) for pk in jobs])+ grouped = (+ query.values("service", "training_job_id")+ .annotate(spent_credits=-Sum("amount") * CREDITS_PER_USD, entries=Count("pk"))+ .order_by("service", "training_job_id")+ )+ total = grouped.count()+ spent = -query.aggregate(amount=Sum("amount", default=Decimal("0")))["amount"] * CREDITS_PER_USD+ return {+ "project_id": str(project.pk),+ "observed_at": observed_at,+ "since": since,+ "before": before,+ "spent_credits": spent,+ "groups": list(grouped[offset : offset + limit]),+ "total_groups": total,+ "next_offset": offset + limit if offset + limit < total else None,+ "limitations": [+ "Posted charges owned by this connection's account only; not all project members' spending.",+ "Unposted charges and provider estimates are excluded; no hard spending cap.",+ "Only recorded training job attribution is resolved. Other services and historical missing job metadata remain unattributed; experiment filtering includes only linked training charges, not a complete experiment bill.",+ ],+ }diff --git a/overbae/services/evaluation_revisions.py b/overbae/services/evaluation_revisions.pynew file mode 100644index 00000000..2a0ceddc--- /dev/null+++ b/overbae/services/evaluation_revisions.py@@ -0,0 +1,64 @@+from types import SimpleNamespace++from django.db import IntegrityError, transaction+from rest_framework.exceptions import ValidationError++from overbae.api.eval_serializers import EvalMatrixSerializer+from overbae.models import EvalMatrix, EvalMatrixRevision+from overbae.services.mcp.contracts.evaluations import ROW_SOURCE_MAX_CHARS+from overbae.services.mcp.errors import MCPError, serializer_fields+++def revise(project, user, payload):+ row = EvalMatrix.objects.select_for_update().filter(project=project, pk=payload.row).first()+ if row is None:+ raise MCPError("resource_not_found", "The evaluation row was not found in this project.")+ if payload.expected_updated_at != row.updated_at:+ raise MCPError(+ "revision_conflict",+ "The evaluator changed. Read its resource and review the current definition before revising.",+ )+ current = {**row.snapshot(), "enabled": row.enabled}+ definition = {+ **current,+ **payload.model_dump(exclude={"row", "expected_updated_at"}, exclude_none=True),+ }+ if len(definition["source"]) > ROW_SOURCE_MAX_CHARS:+ raise MCPError(+ "eval_matrix_row_invalid",+ "The revision failed validation.",+ fields={"source": f"A source is at most {ROW_SOURCE_MAX_CHARS} characters."},+ )+ serializer = EvalMatrixSerializer(+ instance=row,+ data={+ "project": str(project.pk),+ "capability": str(row.capability_id) if row.capability_id else None,+ **definition,+ },+ context={"request": SimpleNamespace(user=user)},+ )+ try:+ serializer.is_valid(raise_exception=True)+ except ValidationError as error:+ raise MCPError(+ "eval_matrix_row_invalid",+ "The revision failed validation.",+ fields=serializer_fields(error.detail),+ ) from None+ if all(serializer.validated_data[field] == value for field, value in current.items()):+ raise MCPError("invalid_input", "The revision changes nothing.")+ EvalMatrixRevision.objects.create(+ row=row,+ definition={**current, "updated_at": row.updated_at.isoformat()},+ created_by=user,+ )+ try:+ return serializer.save()+ except IntegrityError:+ raise MCPError(+ "eval_matrix_row_invalid",+ "The revision failed validation.",+ fields={"name": "Another evaluator in this scope has this name."},+ ) from Nonediff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex b1c1a35e..25e9b51e 100644--- a/overbae/services/mcp/__init__.py+++ b/overbae/services/mcp/__init__.py@@ -1,3 +1,3 @@"""MCP protocol and catalog services."""-CONTRACT_VERSION = "7.22.0"+CONTRACT_VERSION = "7.23.0"diff --git a/overbae/services/mcp/catalog.py b/overbae/services/mcp/catalog.pyindex 561bb6fc..0ff1d991 100644--- a/overbae/services/mcp/catalog.py+++ b/overbae/services/mcp/catalog.py@@ -14,6 +14,7 @@ from mcp import typesfrom pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validatorfrom overbae.services.activity import mcp_succeeded+from overbae.services.mcp import mutationsfrom overbae.services.mcp.annotations import annotations_forfrom overbae.services.mcp.context import MCPContext, project_contextfrom overbae.services.mcp.errors import MCPError, error_result, internal_error@@ -98,8 +99,23 @@ class ToolDefinition(BaseModel):if self.destructive != (self.name in _DESTRUCTIVE_TOOLS):raise CatalogError("destructive tools are not supported")+ @property+ def receipt_supported(self) -> bool:+ return (+ self.project_scoped+ and not self.read_only+ and "request_key" not in self.input_model.model_fields+ )+def as_mcp_tool(self) -> types.Tool:schema = _compact_schema(self.input_model.model_json_schema(by_alias=True))+ if self.receipt_supported:+ schema.setdefault("properties", {})["request_key"] = {+ "type": "string",+ "minLength": 1,+ "maxLength": 128,+ "description": "An identical retry after completion returns the stored result.",+ }if self.project_scoped:schema.setdefault("properties", {})["project_id"] = {"type": "string",@@ -208,6 +224,13 @@ class ToolCatalog:context = await sync_to_async(project_context, thread_sensitive=True)(context, arguments.pop("project_id", None))+ request_key = (+ arguments.pop("request_key", None) if entry.definition.receipt_supported else None+ )+ if request_key is not None and (+ not isinstance(request_key, str) or not 1 <= len(request_key) <= 128+ ):+ raise MCPError("invalid_input", "request_key must contain 1–128 characters.")payload = entry.definition.input_model.model_validate(arguments)except MCPError as error:return error_result(error)@@ -224,16 +247,37 @@ class ToolCatalog:))+ receipt = None+ if request_key is not None:+ try:+ receipt, created = await sync_to_async(mutations.claim, thread_sensitive=True)(+ context, name, request_key, payload.model_dump(mode="json")+ )+ except MCPError as error:+ return error_result(error)+ if not created:+ return types.CallToolResult.model_validate(receipt.result)try:result = entry.handler(payload, context)if inspect.isawaitable(result):result = await resultoutput = entry.definition.output_model.model_validate(result)except MCPError as error:- return error_result(error)+ failure = error_result(error)+ if receipt and error.data.retryable:+ await sync_to_async(mutations.release, thread_sensitive=True)(receipt)+ elif receipt:+ await sync_to_async(mutations.finish, thread_sensitive=True)(+ receipt, failure.model_dump(mode="json")+ )+ return failureexcept ValidationError:+ if receipt:+ await sync_to_async(mutations.mark_unknown, thread_sensitive=True)(receipt)return error_result(MCPError("invalid_output", "The tool returned an invalid result."))except Exception:+ if receipt:+ await sync_to_async(mutations.mark_unknown, thread_sensitive=True)(receipt)logger.exception("MCP tool %s failed for project %s", name, getattr(context.project, "id", None))@@ -249,7 +293,12 @@ class ToolCatalog:logger.exception("Could not retain MCP activity for %s", name)if entry.definition.project_scoped and context.token.scope.get("scope") == "account":structured = project_references(structured, context.project.pk)- return tool_result(structured)+ response = tool_result(structured)+ if receipt:+ await sync_to_async(mutations.finish, thread_sensitive=True)(+ receipt, response.model_dump(mode="json")+ )+ return response@staticmethoddef _visible(definition: ToolDefinition, permissions: frozenset[str]) -> bool:@@ -314,3 +363,11 @@ register_model_workflow_tools(CATALOG)from overbae.services.mcp.tools_signals import register_signal_tools # noqa: E402register_signal_tools(CATALOG)++from overbae.services.mcp.tools_inventory import register_inventory_tools # noqa: E402++register_inventory_tools(CATALOG)++from overbae.services.mcp.tools_monitoring import register_monitoring_tools # noqa: E402++register_monitoring_tools(CATALOG)diff --git a/overbae/services/mcp/contracts/evaluations.py b/overbae/services/mcp/contracts/evaluations.pyindex ab31ef85..4c1e18ef 100644--- a/overbae/services/mcp/contracts/evaluations.py+++ b/overbae/services/mcp/contracts/evaluations.py@@ -3,9 +3,11 @@from __future__ import annotationsimport json+from datetime import datetimefrom typing import Any, Literal+from uuid import UUID-from pydantic import AliasChoices, Field, field_validator+from pydantic import AliasChoices, AwareDatetime, Field, field_validatorfrom overbae.services.mcp.contracts.common import (DatasetCellContract,@@ -56,16 +58,20 @@ def _validate_safe_json(value: dict[str, Any], *, field: str) -> dict[str, Any]:return value+ROW_SOURCE_MAX_CHARS = 20_000++class EvalMatrixRowContract(MCPModel):id: strname: strtype: MatrixType- source: str = Field(max_length=20_000)+ source: str = Field(max_length=ROW_SOURCE_MAX_CHARS)definition_source: Literal["stock", "code", "config", "custom", "unknown"]capability: str | None = Nonespan_type: str = ""span_name: str = ""enabled: bool+ updated_at: datetimeclass CreateEvalMatrixRowInput(MCPModel):@@ -78,7 +84,7 @@ class CreateEvalMatrixRowInput(MCPModel):type: MatrixTypesource: str = Field(min_length=1,- max_length=20_000,+ max_length=ROW_SOURCE_MAX_CHARS,description=("deterministic: a script defining evaluate(span) returning a score in [0, 1], ""None to abstain, or {score, reason}. llm: one sentence the output must meet."@@ -323,3 +329,19 @@ class CompareEvaluationsOutput(MCPModel):metrics: list[MetricComparisonContract] = Field(max_length=200)trust: dict[str, Any] = Field(default_factory=dict)resource_links: list[ResourceLinkContract] = Field(max_length=2)+++class ReviseEvalMatrixInput(MCPModel):+ row: UUID+ expected_updated_at: AwareDatetime+ name: str | None = Field(default=None, min_length=1, max_length=255)+ type: MatrixType | None = None+ source: str | None = Field(+ default=None,+ min_length=1,+ max_length=ROW_SOURCE_MAX_CHARS,+ description="Complete replacement. A long row's resource returns its source in pages.",+ )+ span_type: Literal["", "llm_call", "tool_call", "retrieval", "workflow"] | None = None+ span_name: str | None = Field(default=None, max_length=255)+ enabled: bool | None = Nonediff --git a/overbae/services/mcp/contracts/inventory.py b/overbae/services/mcp/contracts/inventory.pynew file mode 100644index 00000000..1a642177--- /dev/null+++ b/overbae/services/mcp/contracts/inventory.py@@ -0,0 +1,152 @@+from datetime import datetime+from typing import Literal+from uuid import UUID++from pydantic import AwareDatetime, Field++from overbae.services.mcp.contracts.common import MCPModel, ResourceLinkContract++ObjectKind = Literal[+ "dataset_transfer",+ "inference_request",+ "training_preparation",+ "dataset_pipeline",+ "model_activation",+ "connector_sync",+ "decision_job",+ "checkpoint",+ "trained_model",+ "finetune",+ "deployment",+ "capability",+ "dataset",+ "eval_set",+ "eval_row",+ "eval_run",+ "optimizer",+ "data_exploration",+ "data_partition",+ "native_evaluation",+ "training_experiment",+ "training_plan",+ "decision_performance",+]+++class ListObjectsInput(MCPModel):+ kinds: list[ObjectKind] = Field(default_factory=list, max_length=24)+ search: str = Field(default="", max_length=255)+ status: str | None = Field(default=None, max_length=40)+ capability: UUID | None = None+ request_key: str | None = Field(default=None, max_length=128)+ since: AwareDatetime | None = None+ before: AwareDatetime | None = None+ ordering: Literal["newest", "oldest", "name"] = "newest"+ offset: int = Field(default=0, ge=0)+ limit: int = Field(default=20, ge=1, le=100)+++class ObjectSummary(MCPModel):+ kind: ObjectKind+ id: str+ project_id: str+ name: str+ status: str | None+ created_at: datetime+ updated_at: datetime | None = None+ capability_id: str | None = None+ base_model: str | None = None+ training_job_id: str | None = None+ deployment_id: str | None = None+ serving_model_id: str | None = None+ resource: ResourceLinkContract+ console_url: str+++class ListObjectsOutput(MCPModel):+ items: list[ObjectSummary] = Field(max_length=100)+ total: int+ offset: int+ next_offset: int | None+ observed_at: datetime+++class OverviewInput(MCPModel):+ pass+++class InventoryCount(MCPModel):+ kind: ObjectKind+ status: str | None+ count: int+++class OverviewOutput(MCPModel):+ project_id: str+ observed_at: datetime+ counts: list[InventoryCount]+ recent: ListObjectsOutput+ discovery_tool: Literal["list_objects"] = "list_objects"+++class LineageInput(MCPModel):+ training_job: UUID+ offset: int = Field(default=0, ge=0)+ limit: int = Field(default=20, ge=1, le=100)+++class LineageCell(MCPModel):+ role: str+ id: str+ dataset_id: str+ fingerprint: str+ rows: int | None+++class LineageOutput(MCPModel):+ training_job_id: str+ project_id: str+ observed_at: datetime+ base_model: str+ cells: list[LineageCell]+ preparation_id: str | None+ deployment: ObjectSummary | None+ evaluations: list[dict]+ evaluation_total: int+ next_offset: int | None+ active_capabilities: list[str]+ active_capabilities_total: int+ limitations: list[str]+ resource: ResourceLinkContract+++class DependenciesInput(MCPModel):+ kind: Literal["dataset", "deployment", "eval_set", "eval_row"]+ id: UUID+ offset: int = Field(default=0, ge=0)+ limit: int = Field(default=20, ge=1, le=100)+++class Dependency(MCPModel):+ kind: str+ id: str+ relationship: str+ resource: ResourceLinkContract+++class DependenciesOutput(MCPModel):+ project_id: str+ observed_at: datetime+ items: list[Dependency] = Field(max_length=100)+ total: int+ next_offset: int | None+ limitations: list[str]+++class SearchObjectsInput(ListObjectsInput):+ project_ids: list[UUID] = Field(min_length=1, max_length=8)+++class SearchObjectsOutput(ListObjectsOutput):+ inaccessible_project_ids: list[str] = Field(max_length=8)+ scope_complete: booldiff --git a/overbae/services/mcp/contracts/monitoring.py b/overbae/services/mcp/contracts/monitoring.pynew file mode 100644index 00000000..c9ea1302--- /dev/null+++ b/overbae/services/mcp/contracts/monitoring.py@@ -0,0 +1,49 @@+from datetime import datetime+from typing import Literal++from pydantic import Field++from overbae.services.mcp.contracts.common import MCPModel+from overbae.services.mcp.contracts.observability import GetJobOutput, JobKind+from overbae.services.mcp.errors import MCPErrorData+++class JobReference(MCPModel):+ kind: JobKind+ id: str = Field(min_length=1, max_length=255)+++class InspectJobsInput(MCPModel):+ view: Literal["summary", "full"] = "summary"+ jobs: list[JobReference] = Field(min_length=1, max_length=8)+ after: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")+ timeout_seconds: int = Field(default=0, ge=0, le=30)+++class JobObservation(MCPModel):+ kind: str+ id: str+ job: GetJobOutput | None = None+ error: MCPErrorData | None = None+++class InspectJobsOutput(MCPModel):+ jobs: list[JobObservation] = Field(max_length=8)+ cursor: str+ changed: bool+ observed_at: datetime+ poll_after_seconds: int = 5+++class InspectMutationInput(MCPModel):+ request_key: str = Field(min_length=1, max_length=128)+++class InspectMutationOutput(MCPModel):+ id: str+ tool: str+ state: str+ created_at: datetime+ updated_at: datetime+ result: dict+ guidance: strdiff --git a/overbae/services/mcp/contracts/observability.py b/overbae/services/mcp/contracts/observability.pyindex 22313607..4185b79f 100644--- a/overbae/services/mcp/contracts/observability.py+++ b/overbae/services/mcp/contracts/observability.py@@ -200,11 +200,21 @@ JobKind = Literal[class GetJobInput(MCPModel):+ view: Literal["summary", "full"] = "full"kind: JobKindid: str = Field(min_length=1, max_length=255)class GetJobOutput(MCPModel):+ view: Literal["summary", "full"] = "full"+ omitted_fields: list[str] = Field(default_factory=list)+ project_id: str+ stage: str | None = None+ last_heartbeat_at: datetime | None = None+ last_progress_at: datetime | None = None+ next_actions: list[str] = Field(default_factory=list, max_length=20)+ action_requirements: dict[str, Any] = Field(default_factory=dict)+ poll_after_seconds: int | None = Nonekind: strid: strstatus: strdiff --git a/overbae/services/mcp/contracts/projects.py b/overbae/services/mcp/contracts/projects.pyindex e22e14ca..733b47e9 100644--- a/overbae/services/mcp/contracts/projects.py+++ b/overbae/services/mcp/contracts/projects.py@@ -5,6 +5,7 @@ from __future__ import annotationsfrom datetime import datetimefrom decimal import Decimalfrom typing import Literal+from uuid import UUIDfrom pydantic import AwareDatetime, Field@@ -61,3 +62,35 @@ class GetCreditBalanceOutput(MCPModel):observed_at: datetimesince: datetime | Noneusage: CreditUsage+++class CreditAttributionInput(MCPModel):+ since: AwareDatetime | None = None+ before: AwareDatetime | None = None+ training_job: UUID | None = None+ training_experiment: UUID | None = None+ offset: int = Field(default=0, ge=0)+ limit: int = Field(default=20, ge=1, le=100)+++class CreditAttributionRow(MCPModel):+ service: str+ training_job_id: str | None+ spent_credits: Decimal+ entries: int+++class CreditAttributionOutput(MCPModel):+ project_id: str+ observed_at: datetime+ since: datetime | None+ before: datetime | None+ spent_credits: Decimal+ groups: list[CreditAttributionRow] = Field(max_length=100)+ total_groups: int+ next_offset: int | None+ credits_per_usd: Literal[100] = 100+ scope: Literal["connection_account_posted_project_charges"] = (+ "connection_account_posted_project_charges"+ )+ limitations: list[str]diff --git a/overbae/services/mcp/errors.py b/overbae/services/mcp/errors.pyindex 830f890a..c7453240 100644--- a/overbae/services/mcp/errors.py+++ b/overbae/services/mcp/errors.py@@ -15,6 +15,7 @@ from overbae.services.mcp.contracts.common import MCPModelfrom overbae.services.mcp.result_compat import tool_resultErrorCode = Literal[+ "request_in_progress","authentication_required","authentication_failed","project_required",@@ -96,6 +97,18 @@ class MCPErrorData(MCPModel):message: strretryable: bool = Falsefields: dict[str, str] = Field(default_factory=dict)+ next_actions: list[str] = Field(default_factory=list, max_length=4)+++_NEXT_ACTIONS = {+ "resource_not_found": ["list_objects"],+ "dataset_not_found": ["list_objects"],+ "request_key_conflict": ["list_objects", "inspect_mutation"],+ "request_in_progress": ["inspect_mutation", "list_objects"],+ "dataset_busy": ["inspect_dataset", "get_job"],+ "insufficient_credits": ["get_credit_balance"],+ "deployment_not_ready": ["get_job"],+}class MCPError(Exception):@@ -108,12 +121,14 @@ class MCPError(Exception):*,retryable: bool = False,fields: dict[str, str] | None = None,+ next_actions: list[str] | None = None,) -> None:self.data = MCPErrorData(code=code,message=message,retryable=retryable,fields=fields or {},+ next_actions=_NEXT_ACTIONS.get(code, []) if next_actions is None else next_actions,)super().__init__(message)diff --git a/overbae/services/mcp/inventory.py b/overbae/services/mcp/inventory.pynew file mode 100644index 00000000..0b7fffe1--- /dev/null+++ b/overbae/services/mcp/inventory.py@@ -0,0 +1,531 @@+from dataclasses import dataclass++from django.conf import settings+from django.db.models import CharField, Count, DateTimeField, F, Q, Value+from django.db.models.functions import Cast, Coalesce, Collate, NullIf+from django.utils import timezone++from overbae.models import (+ Capability,+ ConnectorCredential,+ Dataset,+ DatasetPipelineBinding,+ DatasetPipelineRun,+ DatasetTransfer,+ DecisionJob,+ DeployedModel,+ EvalMatrix,+ EvalRun,+ EvalSet,+ FinetuningJob,+ InferenceRequest,+ ModelActivation,+ OptimizerExperiment,+ TrainingCheckpoint,+ TrainingPreparation,+)+from overbae.services import model_workflows+from overbae.services.mcp.contracts.inventory import (+ DependenciesOutput,+ LineageOutput,+ ListObjectsInput,+ ListObjectsOutput,+ ObjectSummary,+ OverviewOutput,+)+from overbae.services.mcp.errors import MCPError+++@dataclass(frozen=True)+class Collection:+ model: type+ name: str+ status: str | None+ resource: str+ route: str+ capability: str | None = "capability_id"+ project: str = "project_id"+ created: str = "created_at"+++COLLECTIONS = {+ "checkpoint": Collection(+ TrainingCheckpoint,+ "key",+ "state",+ "checkpoints",+ "training",+ "job__capability_id",+ "job__project_id",+ ),+ "dataset_transfer": Collection(+ DatasetTransfer, "request_key", "state", "jobs/dataset_transfer", "datasets", None+ ),+ "inference_request": Collection(+ InferenceRequest, "request_key", "state", "jobs/inference_request", "inference", None+ ),+ "training_preparation": Collection(+ TrainingPreparation,+ "signature",+ "state",+ "jobs/training_preparation",+ "training",+ "cell__dataset__capability_id",+ "cell__dataset__project_id",+ ),+ "dataset_pipeline": Collection(+ DatasetPipelineRun,+ "request_key",+ "state",+ "jobs/dataset_pipeline",+ "datasets",+ "dataset__capability_id",+ "dataset__project_id",+ ),+ "model_activation": Collection(+ ModelActivation,+ "capability__name",+ "stage",+ "jobs/model_activation",+ "inference",+ "capability_id",+ "capability__project_id",+ "started_at",+ ),+ "connector_sync": Collection(+ ConnectorCredential, "name", "sync_status", "connectors", "observability", None+ ),+ "decision_job": Collection(+ DecisionJob,+ "finetuning_job__name",+ "finetuning_job__status",+ "jobs/decision_job",+ "training",+ "finetuning_job__capability_id",+ "finetuning_job__project_id",+ ),+ "trained_model": Collection(FinetuningJob, "name", "status", "finetunes", "training"),+ "finetune": Collection(FinetuningJob, "name", "status", "finetunes", "training"),+ "deployment": Collection(+ DeployedModel,+ "model_id",+ "status",+ "deployments",+ "inference",+ "finetuning_job__capability_id",+ ),+ "capability": Collection(Capability, "name", "status", "capabilities", "capabilities", "id"),+ "dataset": Collection(Dataset, "name", "state", "datasets", "datasets"),+ "eval_set": Collection(EvalSet, "name", None, "eval-sets", "evaluations"),+ "eval_row": Collection(EvalMatrix, "name", None, "eval-rows", "evaluations"),+ "eval_run": Collection(+ EvalRun, "name", "status", "eval-runs", "evaluations", "dataset__capability_id"+ ),+ "optimizer": Collection(+ OptimizerExperiment, "capability__name", "status", "optimizer-runs", "optimiser"+ ),+ **{+ kind: Collection(model, "name", "state", f"jobs/{kind}", "training", None)+ for kind, model in model_workflows.MODELS.items()+ },+}+++def queryset(project, kind, payload):+ spec = COLLECTIONS[kind]+ query = (+ spec.model.objects.filter(**{f"{spec.project}__in": [item.pk for item in project]})+ if isinstance(project, list)+ else spec.model.objects.filter(**{spec.project: project.pk})+ )+ if kind == "trained_model":+ query = query.filter(status=FinetuningJob.Status.SUCCEEDED)+ if kind == "capability":+ query = query.exclude(status="deleted")+ if payload.search:+ condition = Q(**{f"{spec.name}__icontains": payload.search})+ if kind in {"finetune", "trained_model"}:+ condition |= Q(base_model__icontains=payload.search) | Q(+ output_model_name__icontains=payload.search+ )+ query = query.filter(condition)+ if payload.status:+ if spec.status is None:+ return query.none()+ query = query.filter(**{spec.status: payload.status})+ if payload.capability:+ if spec.capability is None:+ return query.none()+ query = query.filter(**{spec.capability: payload.capability})+ if payload.request_key:+ if kind == "decision_job":+ query = query.filter(finetuning_job__request_key=payload.request_key)+ elif any(field.name == "request_key" for field in spec.model._meta.fields):+ query = query.filter(request_key=payload.request_key)+ else:+ return query.none()+ if payload.since:+ query = query.filter(**{f"{spec.created}__gte": payload.since})+ if payload.before:+ query = query.filter(**{f"{spec.created}__lt": payload.before})+ return query+++def deployment_summary(row):+ identifier, project = str(row["id"]), str(row["project_id"])+ name = row["model_id"] or "deployment"+ capability = row["finetuning_job__capability_id"]+ training_job = row["finetuning_job_id"]+ return ObjectSummary(+ kind="deployment",+ id=identifier,+ project_id=project,+ name=name,+ status=row["status"],+ created_at=row["created_at"],+ capability_id=str(capability) if capability else None,+ base_model=row["base_model_id"],+ training_job_id=str(training_job) if training_job else None,+ deployment_id=identifier,+ serving_model_id=row["model_id"],+ resource={+ "uri": f"overmind://deployments/{identifier}?project_id={project}",+ "title": name[:160],+ },+ console_url=f"{settings.FRONTEND_URL.rstrip('/')}/inference?projectId={project}",+ )+++def list_objects(project, payload):+ kinds = payload.kinds or [kind for kind in COLLECTIONS if kind != "trained_model"]+ queries = []+ for kind in dict.fromkeys(kinds):+ spec = COLLECTIONS[kind]+ query = queryset(project, kind, payload).order_by()+ training = (+ "id"+ if kind in {"finetune", "trained_model"}+ else "finetuning_job_id"+ if kind in {"deployment", "decision_job"}+ else "job_id"+ if kind == "checkpoint"+ else None+ )+ deployment = (+ "deployed_model__id"+ if kind in {"finetune", "trained_model"}+ else "id"+ if kind == "deployment"+ else None+ )+ base = (+ "base_model"+ if kind in {"finetune", "trained_model"}+ else "base_model_id"+ if kind == "deployment"+ else None+ )++ def text_field(field):+ return Cast(F(field), CharField()) if field else Value(None, output_field=CharField())++ queries.append(+ query.annotate(+ inventory_kind=Value(kind, output_field=CharField()),+ inventory_id=text_field("id"),+ inventory_project=text_field(spec.project),+ inventory_name=Collate(+ Coalesce(+ NullIf(F(spec.name), Value("")), Value(kind), output_field=CharField()+ ),+ "C",+ ),+ inventory_created=F(spec.created),+ inventory_updated=F("updated_at")+ if any(field.name == "updated_at" for field in spec.model._meta.fields)+ else Value(None, output_field=DateTimeField()),+ inventory_status=text_field(spec.status),+ inventory_capability=text_field(spec.capability),+ inventory_base=text_field(base),+ inventory_training=text_field(training),+ inventory_deployment=text_field(deployment),+ inventory_serving=text_field(+ "model_id"+ if kind == "deployment"+ else "deployed_model__model_id"+ if kind in {"finetune", "trained_model"}+ else None+ ),+ ).values(+ "inventory_kind",+ "inventory_id",+ "inventory_project",+ "inventory_name",+ "inventory_created",+ "inventory_updated",+ "inventory_status",+ "inventory_capability",+ "inventory_base",+ "inventory_training",+ "inventory_deployment",+ "inventory_serving",+ )+ )+ combined = queries[0].union(*queries[1:], all=True)+ ordering = (+ ("inventory_name", "inventory_kind", "inventory_id")+ if payload.ordering == "name"+ else ("inventory_created", "inventory_kind", "inventory_id")+ )+ if payload.ordering == "newest":+ ordering = tuple(f"-{field}" for field in ordering)+ total = combined.count()+ end = payload.offset + payload.limit+ items = []+ for row in combined.order_by(*ordering)[payload.offset : end]:+ kind, identifier, project_id = (+ row["inventory_kind"],+ row["inventory_id"],+ row["inventory_project"],+ )+ spec = COLLECTIONS[kind]+ items.append(+ ObjectSummary(+ kind=kind,+ id=identifier,+ project_id=project_id,+ name=row["inventory_name"],+ status=row["inventory_status"],+ created_at=row["inventory_created"],+ updated_at=row["inventory_updated"],+ capability_id=row["inventory_capability"],+ base_model=row["inventory_base"],+ training_job_id=row["inventory_training"],+ deployment_id=row["inventory_deployment"],+ serving_model_id=row["inventory_serving"],+ resource={+ "uri": f"overmind://{spec.resource}/{identifier}?project_id={project_id}",+ "title": row["inventory_name"][:160],+ },+ console_url=f"{settings.FRONTEND_URL.rstrip('/')}/{spec.route}?projectId={project_id}",+ )+ )+ return ListObjectsOutput(+ items=items,+ total=total,+ offset=payload.offset,+ next_offset=end if end < total else None,+ observed_at=timezone.now(),+ )+++def overview(project, payload):+ counts = []+ for kind, spec in COLLECTIONS.items():+ query = queryset(project, kind, ListObjectsInput())+ if spec.status:+ counts.extend(+ {"kind": kind, "status": row[spec.status], "count": row["count"]}+ for row in query.values(spec.status)+ .annotate(count=Count("pk"))+ .order_by(spec.status)+ )+ else:+ counts.append({"kind": kind, "status": None, "count": query.count()})+ return OverviewOutput(+ project_id=str(project.pk),+ observed_at=timezone.now(),+ counts=counts,+ recent=list_objects(project, ListObjectsInput(limit=10)),+ )+++def lineage(project, payload):+ job = (+ FinetuningJob.objects.filter(project=project, pk=payload.training_job)+ .select_related("cell", "validation_cell", "eval_cell")+ .first()+ )+ if job is None:+ raise MCPError("resource_not_found", "Training job not found in this project.")+ cells = [+ {+ "role": role,+ "id": str(cell.pk),+ "dataset_id": str(cell.dataset_id),+ "fingerprint": cell.fingerprint,+ "rows": cell.rows,+ }+ for role, cell in (+ ("train", job.cell),+ ("validation", job.validation_cell),+ ("evaluation", job.eval_cell),+ )+ if cell+ ]+ deployment = (+ DeployedModel.objects.filter(project=project, finetuning_job=job)+ .values(+ "id",+ "project_id",+ "model_id",+ "status",+ "created_at",+ "base_model_id",+ "finetuning_job_id",+ "finetuning_job__capability_id",+ )+ .first()+ )+ active = (+ Capability.objects.filter(project=project, active_model_id=deployment["id"]).order_by("pk")+ if deployment+ else Capability.objects.none()+ )+ evaluations = job.job_evals.order_by("created_at", "id")+ total = evaluations.count()+ end = payload.offset + payload.limit+ records = [+ {+ "id": str(row.pk),+ "kind": row.kind,+ "status": row.status,+ "eval_run_id": str(row.eval_run_id) if row.eval_run_id else None,+ "resource_uri": f"overmind://eval-runs/{row.eval_run_id}?project_id={project.pk}"+ if row.eval_run_id+ else None,+ }+ for row in evaluations[payload.offset : end]+ ]+ return LineageOutput(+ training_job_id=str(job.pk),+ project_id=str(project.pk),+ observed_at=timezone.now(),+ base_model=job.base_model,+ cells=cells,+ preparation_id=str(job.preparation_id) if job.preparation_id else None,+ deployment=deployment_summary(deployment) if deployment else None,+ evaluations=records,+ evaluation_total=total,+ next_offset=end if end < total else None,+ active_capabilities=[str(pk) for pk in active.values_list("pk", flat=True)[:100]],+ active_capabilities_total=active.count(),+ limitations=[+ "Missing pinned cells are unknown, not the dataset's current active cell.",+ "Deployment readiness and active routing do not establish worker warmth or application traffic.",+ "Active capability IDs are bounded to 100; list_objects(kind capability) and capability resources expose the full routing state.",+ ],+ resource={+ "uri": f"overmind://finetunes/{job.pk}?project_id={project.pk}",+ "title": "Training recipe and checkpoint evidence",+ },+ )+++def dependencies(project, payload):+ spec = COLLECTIONS[payload.kind]+ if not spec.model.objects.filter(project=project, pk=payload.id).exists():+ raise MCPError("resource_not_found", "The object was not found in this project.")+ identifier = payload.id+ if payload.kind == "dataset":+ related = [+ (+ "finetune",+ "training/validation/evaluation data",+ FinetuningJob.objects.filter(project=project).filter(+ Q(dataset_id=identifier)+ | Q(validation_dataset_id=identifier)+ | Q(eval_dataset_id=identifier)+ ),+ "finetunes",+ ),+ (+ "eval_run",+ "evaluation data",+ EvalRun.objects.filter(project=project, dataset_id=identifier),+ "eval-runs",+ ),+ (+ "optimizer",+ "optimization data",+ OptimizerExperiment.objects.filter(project=project, dataset_id=identifier),+ "optimizer-runs",+ ),+ (+ "dataset_binding",+ "scheduled preparation target",+ DatasetPipelineBinding.objects.filter(project=project, dataset_id=identifier),+ "dataset-pipeline-bindings",+ ),+ ]+ elif payload.kind == "deployment":+ related = [+ (+ "capability",+ "active or benchmark routing",+ Capability.objects.filter(project=project).filter(+ Q(active_model_id=identifier) | Q(benchmark_model_id=identifier)+ ),+ "capabilities",+ )+ ]+ elif payload.kind == "eval_set":+ related = [+ (+ "capability",+ "active evaluation set",+ Capability.objects.filter(project=project, active_eval_set_id=identifier),+ "capabilities",+ ),+ (+ "eval_run",+ "evaluation history",+ EvalRun.objects.filter(project=project, eval_set_id=identifier),+ "eval-runs",+ ),+ (+ "finetune",+ "training evaluation set",+ FinetuningJob.objects.filter(project=project, eval_set_id=identifier),+ "finetunes",+ ),+ ]+ else:+ related = [+ (+ "eval_set",+ "set membership",+ EvalSet.objects.filter(project=project, rows__id=identifier),+ "eval-sets",+ )+ ]+ total, items = 0, []+ start, end = payload.offset, payload.offset + payload.limit+ for kind, relationship, query, resource in related:+ count = query.count()+ local_start, local_end = max(0, start - total), min(count, end - total)+ if local_end > local_start:+ items.extend(+ {+ "kind": kind,+ "id": str(pk),+ "relationship": relationship,+ "resource": {+ "uri": f"overmind://{resource}/{pk}?project_id={project.pk}",+ "title": relationship,+ },+ }+ for pk in query.order_by("pk").values_list("pk", flat=True)[local_start:local_end]+ )+ total += count+ return DependenciesOutput(+ project_id=str(project.pk),+ observed_at=timezone.now(),+ items=items,+ total=total,+ next_offset=end if end < total else None,+ limitations=[+ "Recorded direct consumers and routing only. External application references and indirect pipeline lineage are not inferred.",+ "This inspection does not authorize removal or routing changes; recheck before mutation.",+ ],+ )diff --git a/overbae/services/mcp/mutations.py b/overbae/services/mcp/mutations.pynew file mode 100644index 00000000..16f23d2b--- /dev/null+++ b/overbae/services/mcp/mutations.py@@ -0,0 +1,69 @@+import hashlib+import json++from django.db import transaction+from django.utils import timezone++from overbae.models import MCPMutation+from overbae.services.mcp.errors import MCPError+++def claim(context, tool, request_key, payload):+ fingerprint = hashlib.sha256(+ json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()+ ).hexdigest()+ with transaction.atomic():+ receipt, created = MCPMutation.objects.get_or_create(+ project=context.project,+ request_key=request_key,+ defaults={"user": context.user, "tool": tool, "fingerprint": fingerprint},+ )+ if receipt.user_id != context.user.pk:+ raise MCPError("permission_denied", "This request identity belongs to another account.")+ if receipt.tool != tool or receipt.fingerprint != fingerprint:+ raise MCPError(+ "request_key_conflict",+ "This request key already identifies a different operation. Inspect the original receipt or use a new key for new work.",+ )+ if not created and receipt.state != "completed":+ raise MCPError(+ "request_in_progress",+ "The original operation may have executed. Inspect its receipt and related jobs; do not resubmit with a new key while acknowledgement is unresolved.",+ fields={"receipt": str(receipt.pk), "state": receipt.state},+ )+ return receipt, created+++def finish(receipt, result):+ MCPMutation.objects.filter(pk=receipt.pk).update(+ state="completed", result=result, updated_at=timezone.now()+ )+++def release(receipt):+ MCPMutation.objects.filter(pk=receipt.pk).delete()+++def mark_unknown(receipt):+ MCPMutation.objects.filter(pk=receipt.pk).update(state="unknown", updated_at=timezone.now())+++def inspect(context, request_key):+ receipt = MCPMutation.objects.filter(+ project=context.project, user=context.user, request_key=request_key+ ).first()+ if receipt is None:+ raise MCPError(+ "resource_not_found",+ "No mutation receipt exists for this account, project and request key.",+ next_actions=[],+ )+ return {+ "id": str(receipt.pk),+ "tool": receipt.tool,+ "state": receipt.state,+ "created_at": receipt.created_at,+ "updated_at": receipt.updated_at,+ "result": receipt.result,+ "guidance": "Completed receipts recover the original response. Pending or unknown receipts must be reconciled with discovered jobs before any new submission. Native request-key tools retain their own workflow receipts.",+ }diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.pyindex 52f48899..f5ea46dd 100644--- a/overbae/services/mcp/resources.py+++ b/overbae/services/mcp/resources.py@@ -46,6 +46,7 @@ from overbae.models import (SignalEvent,SignalSubscription,Span,+ TrainingCheckpoint,TrainingPreparation,)from overbae.services import (@@ -1539,6 +1540,70 @@ def _read_resource_sync(project, raw_uri: str) -> dict:raise _not_found("resource", raw_uri)segments = [unquote(part) for part in parsed.path.split("/") if part]host = parsed.netloc+ if host == "checkpoints" and len(segments) == 1:+ checkpoint = TrainingCheckpoint.objects.filter(+ job__project=project, pk=uuid_reference(segments[0])+ ).first()+ if checkpoint is None:+ raise _not_found("checkpoint", segments[0])+ return {+ "uri": raw_uri,+ "id": str(checkpoint.pk),+ "training_job_id": str(checkpoint.job_id),+ "identity": checkpoint.identity,+ "state": checkpoint.state,+ "step": checkpoint.step,+ "attempt": checkpoint.attempt,+ "selected": checkpoint.selected,+ "created_at": checkpoint.created_at,+ "training_resource_uri": f"overmind://finetunes/{checkpoint.job_id}?project_id={project.pk}",+ }+ if host == "eval-rows" and len(segments) == 1:+ row = EvalMatrix.objects.filter(project=project, pk=uuid_reference(segments[0])).first()+ if row is None:+ raise _not_found("eval row", segments[0])+ params = parse_qs(parsed.query)+ try:+ offset = int(params.get("offset", [0])[0])+ limit = int(params.get("limit", [20])[0])+ source_offset = int(params.get("source_offset", [0])[0])+ if offset < 0 or source_offset < 0 or not 1 <= limit <= 100:+ raise ValueError+ except ValueError:+ raise MCPError("invalid_input", "Use nonnegative offsets and limit 1–100.") from None+ definition = {**row.snapshot(), "enabled": row.enabled, "updated_at": row.updated_at}+ if params.get("revision"):+ revision = row.revisions.filter(pk=uuid_reference(params["revision"][0])).first()+ if revision is None:+ raise _not_found("eval revision", params["revision"][0])+ definition = dict(revision.definition)+ source = definition["source"]+ definition["source"] = source[source_offset : source_offset + 12000]+ revisions = row.revisions.order_by("-created_at", "-pk")+ total = revisions.count()+ return {+ "uri": raw_uri,+ "id": str(row.pk),+ "project_id": str(project.pk),+ **definition,+ "source_page": {+ "offset": source_offset,+ "total": len(source),+ "next_offset": source_offset + 12000+ if source_offset + 12000 < len(source)+ else None,+ },+ "revisions": [+ {+ "id": str(revision.pk),+ "created_at": revision.created_at,+ "resource_uri": f"overmind://eval-rows/{row.pk}?project_id={project.pk}&revision={revision.pk}",+ }+ for revision in revisions[offset : offset + limit]+ ],+ "revision_total": total,+ "next_offset": offset + limit if offset + limit < total else None,+ }if host == "activity" and not segments:params = parse_qs(parsed.query, keep_blank_values=True)try:@@ -1809,6 +1874,8 @@ def resource_templates() -> list[types.ResourceTemplate]:"overmind://pipeline-diagnostics/{id}","Untrusted script diagnostics; step, channel, offset and limit",),+ ("checkpoint", "overmind://checkpoints/{id}", "Retained checkpoint identity"),+ ("eval-row", "overmind://eval-rows/{row}", "Evaluation row definition"),("eval-run", "overmind://eval-runs/{eval_run}", "Evaluation run status"),("eval-set",diff --git a/overbae/services/mcp/server.py b/overbae/services/mcp/server.pyindex 5c5102ff..1d60e030 100644--- a/overbae/services/mcp/server.py+++ b/overbae/services/mcp/server.py@@ -56,7 +56,7 @@ mcp_server = Server("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. "- "Account connections require project_id on each project tool and resource URI; "+ "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; "diff --git a/overbae/services/mcp/tools_evaluations.py b/overbae/services/mcp/tools_evaluations.pyindex db18fe7a..5a32e32e 100644--- a/overbae/services/mcp/tools_evaluations.py+++ b/overbae/services/mcp/tools_evaluations.py@@ -21,6 +21,7 @@ from overbae.innermind import comparison, runsfrom overbae.innermind.definitions import definition_sourcefrom overbae.models import Capability, Dataset, EvalMatrix, EvalRun, EvalSetfrom overbae.services.datasets.contract import public_intent+from overbae.services.evaluation_revisions import revisefrom overbae.services.mcp.context import MCPContextfrom overbae.services.mcp.contracts.evaluations import (CheckEvaluationReadinessInput,@@ -39,6 +40,7 @@ from overbae.services.mcp.contracts.evaluations import (EvaluationDatasetContract,EvaluationRunContract,EvaluationScopeInput,+ ReviseEvalMatrixInput,RunEvaluationInput,RunEvaluationOutput,)@@ -183,6 +185,7 @@ def _row_contract(row: EvalMatrix) -> EvalMatrixRowContract:span_type=row.span_type,span_name=row.span_name,enabled=row.enabled,+ updated_at=row.updated_at,)@@ -397,9 +400,35 @@ def _async_handler(function):return handler+def revise_row_sync(payload, context):+ row = revise(context.project, context.user, payload)+ return CreateEvalMatrixRowOutput(+ summary="Evaluator revised; set membership and historical run snapshots are preserved.",+ row=_row_contract(row),+ resource_links=[resource_link("eval-rows", str(row.pk), row.name)],+ )++def register_evaluation_tools(catalog) -> None:from overbae.services.mcp.catalog import ToolDefinition+ catalog.register(+ ToolDefinition(+ name="revise_eval_matrix_row",+ title="Revise evaluation row",+ description="Revise an evaluator with expected_updated_at from list_objects or its resource. Omitted fields keep their values. Retains previous definitions and set membership; historical run snapshots stay immutable. The capability cannot change.",+ input_model=ReviseEvalMatrixInput,+ output_model=CreateEvalMatrixRowOutput,+ read_only=False,+ idempotent=False,+ open_world=False,+ required_scopes=frozenset({"overmind:evaluate"}),+ cost_class="free",+ async_mode="sync",+ ),+ _async_handler(revise_row_sync),+ )+definitions = [("create_eval_matrix_row",diff --git a/overbae/services/mcp/tools_inventory.py b/overbae/services/mcp/tools_inventory.pynew file mode 100644index 00000000..1932fc6c--- /dev/null+++ b/overbae/services/mcp/tools_inventory.py@@ -0,0 +1,115 @@+from asgiref.sync import sync_to_async++from overbae.services.mcp import inventory+from overbae.services.mcp.context import accessible_projects+from overbae.services.mcp.contracts.inventory import (+ DependenciesInput,+ DependenciesOutput,+ LineageInput,+ LineageOutput,+ ListObjectsInput,+ ListObjectsOutput,+ OverviewInput,+ OverviewOutput,+ SearchObjectsInput,+ SearchObjectsOutput,+)+++async def list_objects(payload, context):+ return await sync_to_async(inventory.list_objects, thread_sensitive=True)(+ context.project, payload+ )+++async def inspect_model_lineage(payload, context):+ return await sync_to_async(inventory.lineage, thread_sensitive=True)(context.project, payload)+++async def inspect_dependencies(payload, context):+ return await sync_to_async(inventory.dependencies, thread_sensitive=True)(+ context.project, payload+ )+++async def project_overview(payload, context):+ return await sync_to_async(inventory.overview, thread_sensitive=True)(context.project, payload)+++@sync_to_async(thread_sensitive=True)+def search_objects(payload, context):+ projects = list(accessible_projects(context).filter(pk__in=payload.project_ids))+ found = {project.pk for project in projects}+ missing = [str(pk) for pk in dict.fromkeys(payload.project_ids) if pk not in found]+ result = inventory.list_objects(projects, payload)+ return SearchObjectsOutput(+ **result.model_dump(), inaccessible_project_ids=missing, scope_complete=not missing+ )+++def register_inventory_tools(catalog):+ from overbae.services.mcp.catalog import ToolDefinition++ catalog.register(+ ToolDefinition(+ name="search_objects",+ title="Search accessible projects",+ description="Search up to eight explicit accessible projects with globally ordered pagination. Inaccessible project IDs are reported as partial coverage; permissions are never widened.",+ input_model=SearchObjectsInput,+ output_model=SearchObjectsOutput,+ read_only=True,+ idempotent=True,+ open_world=False,+ required_scopes=frozenset({"overmind:read"}),+ cost_class="free",+ async_mode="sync",+ project_scoped=False,+ ),+ search_objects,+ )+ for name, description, input_model, output_model, handler in (+ (+ "inspect_dependencies",+ "Page recorded direct consumers, evaluation memberships and routing for a dataset, deployment, eval set or row. Read-only impact inspection; external/indirect references remain unknown.",+ DependenciesInput,+ DependenciesOutput,+ inspect_dependencies,+ ),+ (+ "inspect_model_lineage",+ "Read pinned training cells, preparation, evaluation references, deployment and active routing. Page evaluations; missing lineage remains unknown. Full recipe/checkpoint evidence is linked.",+ LineageInput,+ LineageOutput,+ inspect_model_lineage,+ ),+ (+ "list_objects",+ "Discover/search project models, jobs, deployments, capabilities, datasets and evaluations. trained_model includes successful chat/decision jobs without deployments. Filter request_key to recover work. Page until next_offset is null; names may be ambiguous.",+ ListObjectsInput,+ ListObjectsOutput,+ list_objects,+ ),+ (+ "get_project_overview",+ "Read project inventory counts by status and recent objects. No provider work; use list_objects for complete filtered pages.",+ OverviewInput,+ OverviewOutput,+ project_overview,+ ),+ ):+ catalog.register(+ ToolDefinition(+ name=name,+ title=name.replace("_", " ").capitalize(),+ description=description,+ input_model=input_model,+ output_model=output_model,+ read_only=True,+ idempotent=True,+ open_world=False,+ required_scopes=frozenset({"overmind:read"}),+ cost_class="free",+ async_mode="sync",+ ),+ handler,+ )diff --git a/overbae/services/mcp/tools_monitoring.py b/overbae/services/mcp/tools_monitoring.pynew file mode 100644index 00000000..d2f6128d--- /dev/null+++ b/overbae/services/mcp/tools_monitoring.py@@ -0,0 +1,100 @@+import asyncio+import hashlib+import json+import time++from asgiref.sync import sync_to_async+from django.utils import timezone++from overbae.services.mcp import mutations+from overbae.services.mcp.contracts.monitoring import (+ InspectJobsInput,+ InspectJobsOutput,+ InspectMutationInput,+ InspectMutationOutput,+ JobObservation,+)+from overbae.services.mcp.contracts.observability import GetJobInput+from overbae.services.mcp.errors import MCPError+from overbae.services.mcp.tools_observability import get_job_sync+++def observations(payload, context):+ rows = []+ for reference in payload.jobs:+ try:+ rows.append(+ JobObservation(+ kind=reference.kind,+ id=reference.id,+ job=get_job_sync(+ GetJobInput(kind=reference.kind, id=reference.id, view=payload.view),+ context,+ ),+ )+ )+ except MCPError as error:+ rows.append(JobObservation(kind=reference.kind, id=reference.id, error=error.data))+ return rows+++async def inspect_jobs(payload, context):+ deadline = time.monotonic() + payload.timeout_seconds+ while True:+ rows = await sync_to_async(observations, thread_sensitive=True)(payload, context)+ encoded = json.dumps(+ [row.model_dump(mode="json") for row in rows], sort_keys=True, separators=(",", ":")+ )+ cursor = hashlib.sha256(encoded.encode()).hexdigest()+ changed = cursor != payload.after+ remaining = deadline - time.monotonic()+ if changed or remaining <= 0:+ return InspectJobsOutput(+ jobs=rows, cursor=cursor, changed=changed, observed_at=timezone.now()+ )+ await asyncio.sleep(min(5, remaining))+++async def inspect_mutation(payload, context):+ return InspectMutationOutput(+ **await sync_to_async(mutations.inspect, thread_sensitive=True)(+ context, payload.request_key+ )+ )+++def register_monitoring_tools(catalog):+ from overbae.services.mcp.catalog import ToolDefinition++ catalog.register(+ ToolDefinition(+ name="inspect_mutation",+ title="Inspect mutation receipt",+ description="Recover this account's generic project mutation receipt by request_key. Native request-key workflows use list_objects/get_job. Pending/unknown never authorizes replay.",+ input_model=InspectMutationInput,+ output_model=InspectMutationOutput,+ read_only=True,+ idempotent=True,+ open_world=False,+ required_scopes=frozenset({"overmind:read"}),+ cost_class="free",+ async_mode="sync",+ ),+ inspect_mutation,+ )+ catalog.register(+ ToolDefinition(+ name="inspect_jobs",+ title="Inspect or wait for jobs",+ description="Inspect up to eight project jobs; optionally wait up to 30 seconds for a cursor change. Per-job errors remain explicit. Passive: never retries, resumes or starts provider work.",+ input_model=InspectJobsInput,+ output_model=InspectJobsOutput,+ read_only=True,+ idempotent=True,+ open_world=False,+ required_scopes=frozenset({"overmind:read"}),+ cost_class="free",+ async_mode="sync",+ ),+ inspect_jobs,+ )diff --git a/overbae/services/mcp/tools_observability.py b/overbae/services/mcp/tools_observability.pyindex 71f15d48..ca0c6a71 100644--- a/overbae/services/mcp/tools_observability.py+++ b/overbae/services/mcp/tools_observability.py@@ -333,7 +333,7 @@ def _job_uuid(ref: str):return None-def _get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:+def get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:kind = _JOB_ALIASES.get(payload.kind, payload.kind)ref = payload.idnormalized_id = _job_uuid(ref)@@ -612,7 +612,29 @@ def _get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:if operation:details["operation"] = operationunderlying.append(_link("operations", operation["id"], "Operational timeline"))+ guidance = model_workflows.guidance(kind, job) if kind in model_workflows.MODELS else {}+ next_actions = (+ model_workflows.next_actions(kind, job) if kind in model_workflows.MODELS else ["get_job"]+ )+ terminal = status in {+ "succeeded",+ "completed",+ "complete",+ "failed",+ "cancelled",+ "ready",+ "deleted",+ }return GetJobOutput(+ view=payload.view,+ omitted_fields=["progress", "details"] if payload.view == "summary" else [],+ project_id=str(context.project.pk),+ stage=operation.get("stage") if operation else None,+ last_heartbeat_at=operation.get("last_heartbeat_at") if operation else None,+ last_progress_at=operation.get("last_progress_at") if operation else None,+ next_actions=next_actions,+ action_requirements=guidance.get("action_requirements", {}),+ poll_after_seconds=guidance.get("poll_after_seconds", None if terminal else 5),kind=kind,id=str(job.id),status=status,@@ -621,8 +643,8 @@ def _get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:created_at=created_at,updated_at=updated_at,completed_at=completed_at,- progress=progress,- details=details,+ progress=progress if payload.view == "full" else None,+ details=details if payload.view == "full" else {},resource=primary,resource_links=[primary, *underlying],summary=f"{label[: 237 - len(status)]}: {status}.",@@ -701,7 +723,7 @@ def register_observability_tools(catalog) -> None:"row examples and preview samples, without starting work.",GetJobInput,GetJobOutput,- _get_job_sync,+ get_job_sync,"free",),]diff --git a/overbae/services/mcp/tools_projects.py b/overbae/services/mcp/tools_projects.pyindex 97bc7ea9..b88bf6a9 100644--- a/overbae/services/mcp/tools_projects.py+++ b/overbae/services/mcp/tools_projects.py@@ -8,13 +8,15 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom overbae.models import APITokenfrom overbae.models.iam import delegation_denialfrom overbae.services import activity-from overbae.services.billing_ledger import credit_report+from overbae.services.billing_ledger import credit_report, project_credit_reportfrom overbae.services.billing_provider import get_billingfrom overbae.services.mcp.context import accessible_projectsfrom overbae.services.mcp.contracts.activity import ReportOnboardingInput, ReportOnboardingOutputfrom overbae.services.mcp.contracts.projects import (CreateApiKeyInput,CreateApiKeyOutput,+ CreditAttributionInput,+ CreditAttributionOutput,GetCreditBalanceInput,GetCreditBalanceOutput,)@@ -134,6 +136,22 @@ def report_onboarding_progress(payload, context):def register_project_tools(catalog):from overbae.services.mcp.catalog import ToolDefinition+ catalog.register(+ ToolDefinition(+ name="get_credit_usage",+ title="Get project credit usage",+ description="Page posted account-owned project charges by service and recorded training job. Pass the first page's observed_at as before on later pages. Null job attribution is unknown. Excludes unposted charges and estimates; does not enforce budgets.",+ input_model=CreditAttributionInput,+ output_model=CreditAttributionOutput,+ read_only=True,+ idempotent=True,+ open_world=False,+ required_scopes=frozenset({"overmind:read"}),+ cost_class="free",+ async_mode="sync",+ ),+ get_credit_usage,+ )catalog.register(ToolDefinition(name="create_api_key",@@ -208,3 +226,12 @@ def register_project_tools(catalog):),report_onboarding_progress,)+++@sync_to_async(thread_sensitive=True)+def get_credit_usage(payload, context):+ if payload.since and payload.before and payload.since >= payload.before:+ raise MCPError("invalid_input", "since must precede before.")+ return CreditAttributionOutput(+ **project_credit_report(context.user, context.project, **payload.model_dump())+ )diff --git a/overmind/.claude-plugin/plugin.json b/overmind/.claude-plugin/plugin.jsonindex 3bca38e2..c6f2af2c 100644--- a/overmind/.claude-plugin/plugin.json+++ b/overmind/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "overmind",- "version": "1.2.9",+ "version": "1.2.10","description": "Overmind skills — agent observability, tracing, and platform workflows for coding agents.","author": {"name": "Overmind",diff --git a/overmind/.codex-plugin/plugin.json b/overmind/.codex-plugin/plugin.jsonindex 291b6e6e..78852081 100644--- a/overmind/.codex-plugin/plugin.json+++ b/overmind/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "overmind",- "version": "1.2.9",+ "version": "1.2.10","description": "Investigate agent failures, prepare datasets, evaluate models, and manage training and serving with Overmind.","author": {"name": "Overmind",diff --git a/overmind/.cursor-plugin/plugin.json b/overmind/.cursor-plugin/plugin.jsonindex 919f936a..cbc92535 100644--- a/overmind/.cursor-plugin/plugin.json+++ b/overmind/.cursor-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "overmind","displayName": "Overmind",- "version": "1.2.9",+ "version": "1.2.10","description": "Overmind skills and MCP — agent observability, tracing, and platform tools for coding agents.","author": {"name": "Overmind",diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex e4611492..2e6be629 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.115"+__version__ = "0.1.116"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/overmind/skills_db.py b/overmind/overmind/skills_db.pyindex 6aa771f1..a69d9e4e 100644--- a/overmind/overmind/skills_db.py+++ b/overmind/overmind/skills_db.py@@ -1,7 +1,7 @@from dataclasses import dataclass# Every plugin manifest (.claude-plugin, .codex-plugin, .cursor-plugin) carries this version.-SKILLS_VERSION = "1.2.9"+SKILLS_VERSION = "1.2.10"@dataclassdiff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex 9c286de7..ef91b325 100644--- a/overmind/pyproject.toml+++ b/overmind/pyproject.toml@@ -46,7 +46,7 @@ license = { text = "MIT" }name = "overmind"readme = "README.md"requires-python = ">=3.10,<4" # todo; remove the upper bound-version = "0.1.115"+version = "0.1.116"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/skills/overmind-evaluations/SKILL.md b/overmind/skills/overmind-evaluations/SKILL.mdindex 9dd3a8e1..ffe63980 100644--- a/overmind/skills/overmind-evaluations/SKILL.md+++ b/overmind/skills/overmind-evaluations/SKILL.md@@ -51,9 +51,12 @@ repository, edit the decorator's `expectations` or the toml entry and run`overmind sync`. Without the repository, or for a rule no catalog checkexpresses, use `create_eval_matrix_row` (an llm row is one checkable sentence;a deterministic row is an audited `evaluate(span)` check) and add it to the-active set with `create_eval_set(..., activate=True)`. A row cannot be edited:-`delete_eval_matrix_row`, then create the replacement. Preserve existing-evaluation semantics unless the user asks to change them.+active set with `create_eval_set(..., activate=True)`. Revise a row with `revise_eval_matrix_row`, passing only+the fields that change and `expected_updated_at` from `list_objects(kinds=["eval_row"])` or its+`overmind://eval-rows/{id}` resource. `source` replaces the whole definition, and the resource+returns long sources in pages: follow `source_page.next_offset` before you edit one. Prior+definitions and set membership are retained. Preserve existing evaluation semantics unless the+user asks to change them.Over a dataset, rows whose `span_type` is blank or `llm_call` score each row'sanswer whatever their `span_name`; tool, timing and cost checks abstain.diff --git a/overmind/skills/overmind-training/SKILL.md b/overmind/skills/overmind-training/SKILL.mdindex 46bf785a..ca4a7280 100644--- a/overmind/skills/overmind-training/SKILL.md+++ b/overmind/skills/overmind-training/SKILL.md@@ -137,8 +137,7 @@ changed rows only.1. After confirmation, call `create_eval_matrix_row` per metric with no`capability`, then `create_eval_set` with those row ids and no capability.Pass the set as `eval_set` to `check_finetune_readiness`, `estimate_finetune`- and `start_finetune`. Rows cannot be edited: `delete_eval_matrix_row`, then- create the replacement.+ and `start_finetune`. Use `revise_eval_matrix_row` with the row's current `updated_at` for versioned edits.Held-out eval data is still required for the chat evaluations the user selects;confirming metrics does not replace it, and held-out data does not replace metrics.diff --git a/overmind/skills/overmind/SKILL.md b/overmind/skills/overmind/SKILL.mdindex 8f9242a9..d5e8defa 100644--- a/overmind/skills/overmind/SKILL.md+++ b/overmind/skills/overmind/SKILL.md@@ -118,16 +118,12 @@ The catalog exposes deliberate lifecycle operations including `cancel_dataset`,1. **Discover the connected product.** Read `overmind://interface/current`, select an authorized project, and use named MCP operations. Keep platform-owned training, evaluation and serving on their named tools. The native agent authors dataset transformations as staged Python packages; use the upload/export CLI for local file transport. Draft comparisons and experiments do not submit paid work; preparation returns a background receipt, and launch records the authorized saved scope. Check actual schemas rather than assuming an installed skill has the newest catalog.1. **One skill per workflow.** Open the surface skill for the task beforeimplementing. This file holds only conventions that apply everywhere.-1. **Discover, then pass the id the schema asks for.** There are no- `list_capabilities`, `list_traces`, `get_trace`, `get_capability`,- `list_eval_sets`, `list_eval_runs`, `list_finetune_jobs`,- `list_deployed_models`, or `job_status` tools. Use `list_datasets`,- `query_*`, `inspect_*`, `get_job`, and resource reads. Never paste raw- UUIDs to the user when a name/slug exists.- Dataset names are not unique: `list_datasets` then pass that UUID to- `inspect_dataset` / `query_dataset` (those two reject names). Fine-tune,- eval, and optimizer tools also accept a unique dataset name.- Capability tools accept name, slug, or id.+1. **Discover, then pass the id the schema asks for.** Use `list_objects`+ for project-wide search and inventory, including `kinds=["trained_model"]`+ for successful chat and decision jobs without requiring a deployment.+ Page through `next_offset`; ambiguous names remain separate candidates.+ Use returned scoped resource links and explicit IDs for follow-up work.+ `list_datasets` remains the dataset-specific inventory.1. **Contracts gate dataset consumption.** Fine-tuning needs a `train`version; eval runs and optimizer experiments need `eval`; `pending` isrefused. See [Datasets: intent and contracts](../overmind-datasets/SKILL.md#intent-and-contracts).@@ -141,11 +137,20 @@ The catalog exposes deliberate lifecycle operations including `cancel_dataset`,## Conventions-- **List first.** `list_datasets` for datasets. Everything else:- `inspect_capability_health`, `query_traces`, `query_failures`, or a- resource read. Read `overmind://capabilities/{capability}` for capability- `id` and `active_model`.-- **Async jobs.** Poll returned job references with `get_job(kind, id)`.+- **List first.** `get_project_overview` gives counts and recent objects;+ `list_objects` searches names and filters kinds, status, capability, time,+ or native request keys. `inspect_dependencies` pages direct consumers and+ routing; indirect/external references remain unknown.+- **Recovery.** For mutations exposing an optional catalogue `request_key`,+ reuse it unchanged and inspect `inspect_mutation` after a disconnect.+ Pending/unknown receipts do not authorize replay. A retryable error releases+ the key, so retry with the same key. Any other refusal stays on its receipt;+ fix the cause and use a new key. Native request-key workflows retain their+ own receipts and are discoverable with `list_objects`.+- **Lineage.** `inspect_model_lineage` joins pinned cells, preparation,+ evaluation references, deployment and active routing. Follow its training+ resource for recipe/checkpoint details; absent pins remain unknown.+- **Async jobs.** Poll returned job references with `get_job(kind, id)`, or inspect up to eight with `inspect_jobs`. Pass its cursor as `after` with `timeout_seconds` (0–30) to wait for changes.Source landing uses `kind=dataset_run`; transformations use the returned `kind=dataset_pipeline` and run ID. Other supported kinds include`eval_run`, `finetune_job`, `deployment`, `model_activation`, and `optimizer_experiment`.- `inspect_operation` reads a linked operational receipt, with `after`/`limit`@@ -162,15 +167,17 @@ The catalog exposes deliberate lifecycle operations including `cancel_dataset`,Use only these implemented names and inspect their schemas at call time. Eachgroup's owning skill carries its workflow.+- Discovery: `search_objects` searches up to eight explicit accessible projects and reports partial coverage; `list_objects`, `get_project_overview`, `inspect_dependencies`, `inspect_model_lineage`.+- Recovery: `inspect_jobs`, `inspect_mutation`.- Observability: `inspect_capability_health`, `query_failures`, `query_traces`, `get_job`.- Signals: `list_signals`, `set_signal_subscription`.-- Credits: `get_credit_balance` reports account balance and usage by service, with `since` for task budgets. Read the `credit_reporting` field of `overmind://interface/current` for scope and budget limits.+- Credits: `get_credit_usage` pages account-owned posted project charges by service and recorded training job; experiment filters cover linked training charges only. Null attribution and unposted charges remain unknown. `get_credit_balance` reports account balance and usage by service, with `since` for task budgets. Read the `credit_reporting` field of `overmind://interface/current` for scope and budget limits.- Instrumentation: `get_instrumentation_plan`, `verify_instrumentation`.- Datasets: `list_datasets`, `inspect_dataset`, `query_dataset`,`start_dataset`, `create_dataset_from_traces`, `create_dataset_from_llm_calls`,`inspect_dataset_workbench`, `save_dataset_pipeline`, `run_dataset_pipeline`,`import_dataset_version`, `update_dataset`, `cancel_dataset`.-- Evaluations: `check_evaluation_readiness`, `create_eval_matrix_row`, `delete_eval_matrix_row`,+- Evaluations: `check_evaluation_readiness`, `create_eval_matrix_row`, `revise_eval_matrix_row`, `delete_eval_matrix_row`,`create_eval_set`, `run_evaluation`, `compare_evaluations`.- Training: `get_model_catalog`, `check_finetune_readiness`, `estimate_finetune`,`start_finetune`, `save_training_plan`, `create_training_experiment`.@@ -221,6 +228,8 @@ The implemented resource templates are:- `overmind://traces/{trace_id}`- `overmind://sessions/{session}`- `overmind://datasets/{dataset}`+- `overmind://checkpoints/{id}`+- `overmind://eval-rows/{row}`- `overmind://eval-runs/{eval_run}`- `overmind://eval-sets/{eval_set}`- `overmind://signal-events`@@ -256,3 +265,7 @@ return the ordinary link. Do not add plugin-only presentation parameters orbuild another UI. Verify the browser project matches the MCP project beforecombining their evidence. Console navigation is optional; continue platformwork through MCP when no browser is available.++Retained intermediate checkpoints are discoverable with `list_objects(kinds=["checkpoint"])`,+including checkpoints from jobs that later failed. Follow the returned checkpoint resource+for its identity and training-job reference. Discovery does not certify serving readiness.diff --git a/overmind/uv.lock b/overmind/uv.lockindex a38811a4..ab6b2c1d 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.115"+version = "0.1.116"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/tests/journeys/test_train.py b/tests/journeys/test_train.pyindex f2e83abd..59897fdb 100644--- a/tests/journeys/test_train.py+++ b/tests/journeys/test_train.py@@ -112,6 +112,15 @@ def test_train(until(beat, benchmarked, PREPARE, TRAIN, DEPLOY)state = finetune()+ inventory = workshop.call(+ "list_objects", {"kinds": ["trained_model"], "request_key": "train-support-model"}+ )+ assert [item["id"] for item in inventory["items"]] == [job]+ lineage = workshop.call("inspect_model_lineage", {"training_job": job})+ assert next(cell["id"] for cell in lineage["cells"] if cell["role"] == "train") == state["cell"]+ observed = workshop.call("inspect_jobs", {"jobs": [{"kind": "finetune", "id": job}]})+ assert observed["jobs"][0]["job"]["status"] == "succeeded"+ assert observed["jobs"][0]["job"]["omitted_fields"] == ["progress", "details"]assert [p["train_loss"] for p in state["loss"]] == [1.0, 0.5]evals = {e["kind"]: e for e in state["progress"]["judge_evals"]}assert evals["final"]["aggregate_score"] > evals["model_before"]["aggregate_score"]diff --git a/tests/mcp_fixtures.py b/tests/mcp_fixtures.pyindex 8b766d40..739ded8c 100644--- a/tests/mcp_fixtures.py+++ b/tests/mcp_fixtures.py@@ -12,12 +12,21 @@ from overbae.models import APIToken, Capability, EvalMatrix, EvalSetfrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContext-MAX_MANIFEST_BYTES = 93 * 1024+MAX_MANIFEST_BYTES = 110 * 1024# The ASGI MCP app serves requests on another thread with its own connection,# so it sees only committed rows.asgi_db = pytest.mark.django_db(transaction=True)EXPECTED_TOOL_NAMES = {+ "search_objects",+ "inspect_dependencies",+ "revise_eval_matrix_row",+ "inspect_mutation",+ "inspect_model_lineage",+ "get_credit_usage",+ "inspect_jobs",+ "list_objects",+ "get_project_overview","start_dataset_preparation","update_dataset_preparation","report_onboarding_progress",diff --git a/tests/test_mcp_inventory.py b/tests/test_mcp_inventory.pynew file mode 100644index 00000000..595a7f8b--- /dev/null+++ b/tests/test_mcp_inventory.py@@ -0,0 +1,414 @@+from dataclasses import replace+from decimal import Decimal+from pathlib import Path+from uuid import uuid4++import pytest+from django.utils import timezone+from mcp_fixtures import call_tool, mcp_context++from overbae.models import (+ APIToken,+ BillingTelemetry,+ Capability,+ ConnectorCredential,+ ConnectorSyncConfig,+ Dataset,+ DecisionJob,+ DeployedModel,+ EvalMatrix,+ EvalSet,+ FinetuningJob,+ MCPMutation,+ ProjectMembership,+ TrainingCheckpoint,+)+from overbae.services.mcp.contracts.evaluations import CreateEvalMatrixRowInput+from overbae.services.mcp.inventory import COLLECTIONS+from overbae.services.mcp.mutations import claim++pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]+++def call(context, tool="list_objects", **arguments):+ result = call_tool(tool, arguments, context)+ assert not result.isError, result+ return result.structuredContent+++def test_inventory_discovers_undeployed_models_and_pages_without_cross_project_leakage():+ context, other = mcp_context(), mcp_context()+ for project in (context.project, other.project):+ dataset = Dataset.objects.create(project=project, name="data")+ for index in range(3):+ FinetuningJob.objects.create(+ project=project,+ dataset=dataset,+ name=f"support {index}",+ base_model="base",+ status="succeeded",+ )+ FinetuningJob.objects.create(+ project=project, dataset=dataset, name="failed", base_model="base", status="failed"+ )+ seen = []+ offset = 0+ while True:+ page = call(context, kinds=["trained_model"], search="support", limit=1, offset=offset)+ assert page["total"] == 3+ seen.extend(page["items"])+ offset = page["next_offset"]+ if offset is None:+ break+ assert len({item["id"] for item in seen}) == 3+ assert all(+ item["project_id"] == str(context.project.pk) and item["deployment_id"] is None+ for item in seen+ )+ job = call(context, kinds=["finetune"], status="failed")["items"][0]+ assert job["name"] == "failed"+ overview = call(context, "get_project_overview")+ assert next(row["count"] for row in overview["counts"] if row["kind"] == "trained_model") == 3+++def test_inventory_search_preserves_ambiguous_names_and_request_identity():+ context = mcp_context()+ Capability.objects.create(project=context.project, name="support", slug="support")+ job = FinetuningJob.objects.create(+ dataset=Dataset.objects.create(project=context.project, name="data"),+ project=context.project,+ name="support",+ base_model="base",+ request_key="original",+ )+ assert call(context, search="support")["total"] == 2+ assert call(context, request_key="original")["items"][0]["id"] == str(job.pk)+ decision = DecisionJob.objects.create(finetuning_job=job)+ found = call(context, kinds=["decision_job"], request_key="original")["items"]+ assert [item["id"] for item in found] == [str(decision.pk)]+ assert call(context, status="missing")["total"] == 0+++def test_batch_status_cursor_reports_changes_and_isolated_errors():+ context, other = mcp_context(), mcp_context()+ jobs = [+ FinetuningJob.objects.create(+ project=ctx.project,+ dataset=Dataset.objects.create(project=ctx.project, name="data"),+ base_model="base",+ )+ for ctx in (context, other)+ ]+ refs = [{"kind": "finetune", "id": str(job.pk)} for job in jobs]+ first = call(context, "inspect_jobs", jobs=refs)+ assert first["changed"]+ assert first["jobs"][1]["error"]["code"] == "resource_not_found"+ second = call(context, "inspect_jobs", jobs=refs, after=first["cursor"])+ assert not second["changed"]+ FinetuningJob.objects.filter(pk=jobs[0].pk).update(status="failed")+ third = call(context, "inspect_jobs", jobs=refs, after=first["cursor"])+ assert third["changed"]+ assert third["jobs"][0]["job"]["status"] == "failed"+++def test_project_spend_preserves_unattributed_charges_and_account_isolation():+ job_id = str(uuid4())++ context, other = mcp_context(), mcp_context()+ for user, project, amount, metadata in [+ (context.user, context.project, "-2", {"job_id": job_id}),+ (context.user, context.project, "-3", {}),+ (other.user, context.project, "-100", {}),+ (context.user, other.project, "-100", {}),+ ]:+ BillingTelemetry.objects.create(+ user=user,+ project=project,+ amount=Decimal(amount),+ service="finetuning-job",+ metadata=metadata,+ )+ result = call(context, "get_credit_usage", limit=1)+ assert Decimal(result["spent_credits"]) == 500+ assert result["total_groups"] == 2+ assert result["next_offset"] == 1+ filtered = call(context, "get_credit_usage", training_job=job_id)+ assert Decimal(filtered["spent_credits"]) == 200+++def test_lineage_keeps_missing_pins_unknown_and_returns_deployment_identity():+ context = mcp_context()+ dataset = Dataset.objects.create(project=context.project, name="data")+ job = FinetuningJob.objects.create(+ project=context.project, dataset=dataset, base_model="base", status="succeeded"+ )+ deployment = DeployedModel.objects.create(+ project=context.project, finetuning_job=job, model_id="test-lineage", status="ready"+ )+ result = call(context, "inspect_model_lineage", training_job=str(job.pk))+ assert result["cells"] == []+ assert result["deployment"]["id"] == str(deployment.pk)+ assert result["deployment"]["training_job_id"] == str(job.pk)+ assert result["active_capabilities"] == []+++def test_mutation_replay_conflict_and_versioned_evaluator_edit():+ context = mcp_context(["read", "write"])+ args = {+ "name": "answer",+ "type": "llm",+ "source": "Answer the question.",+ "request_key": "create-answer",+ }+ original = call(context, "create_eval_matrix_row", **args)+ repeated = call(context, "create_eval_matrix_row", **args)+ assert original == repeated+ assert EvalMatrix.objects.filter(project=context.project).count() == 1+ conflict = call_tool("create_eval_matrix_row", {**args, "source": "Changed"}, context)+ assert (+ conflict.isError and conflict.structuredContent["error"]["code"] == "request_key_conflict"+ )+ receipt = call(context, "inspect_mutation", request_key="create-answer")+ assert receipt["state"] == "completed"+ row = EvalMatrix.objects.get(pk=original["row"]["id"])+ eval_set = EvalSet.objects.create(project=context.project, name="checks")+ eval_set.rows.add(row)+ old_snapshot = row.snapshot()+ revision = {+ "row": str(row.pk),+ "expected_updated_at": row.updated_at.isoformat(),+ "name": row.name,+ "type": row.type,+ "source": "Answer accurately.",+ "request_key": "revise-answer",+ }+ call(context, "revise_eval_matrix_row", **revision)+ row.refresh_from_db()+ assert row.source == "Answer accurately."+ assert eval_set.rows.get().pk == row.pk+ assert row.revisions.get().definition["source"] == old_snapshot["source"]+ stale = call_tool("revise_eval_matrix_row", {**revision, "request_key": "stale-edit"}, context)+ assert stale.isError and stale.structuredContent["error"]["code"] == "revision_conflict"+++def test_cross_project_search_reports_partial_scope_and_dependencies_page():+ context, other = mcp_context(), mcp_context()+ dataset = Dataset.objects.create(project=context.project, name="data")+ for index in range(2):+ FinetuningJob.objects.create(+ project=context.project, dataset=dataset, base_model="base", name=f"job-{index}"+ )+ results = call(+ context,+ "search_objects",+ project_ids=[str(context.project.pk), str(other.project.pk)],+ kinds=["finetune"],+ )+ assert results["total"] == 2+ assert not results["scope_complete"]+ assert results["inaccessible_project_ids"] == [str(other.project.pk)]+ dependencies = call(+ context, "inspect_dependencies", kind="dataset", id=str(dataset.pk), limit=1+ )+ assert dependencies["total"] == 2+ assert dependencies["next_offset"] == 1+ more = call(+ context, "inspect_dependencies", kind="dataset", id=str(dataset.pk), limit=1, offset=1+ )+ assert more["items"][0]["id"] != dependencies["items"][0]["id"]+++def test_unresolved_mutation_never_replays_and_failed_job_checkpoint_is_discoverable():+ context = mcp_context(["read", "write"])+ payload = CreateEvalMatrixRowInput(name="pending", type="llm", source="Answer accurately.")+ claim(context, "create_eval_matrix_row", "lost-ack", payload.model_dump(mode="json"))+ result = call_tool(+ "create_eval_matrix_row", {**payload.model_dump(), "request_key": "lost-ack"}, context+ )+ assert result.isError and result.structuredContent["error"]["code"] == "request_in_progress"+ assert not EvalMatrix.objects.filter(project=context.project).exists()+ job = FinetuningJob.objects.create(+ project=context.project,+ dataset=Dataset.objects.create(project=context.project, name="data"),+ base_model="base",+ status="failed",+ )+ checkpoint = TrainingCheckpoint.objects.create(+ job=job, key="step-10", attempt=1, step=10, state="verified", identity="a" * 64+ )+ records = call(context, kinds=["checkpoint"])+ assert records["items"][0]["id"] == str(checkpoint.pk)+ assert records["items"][0]["resource"]["uri"].startswith("overmind://checkpoints/")++[email protected]("tenancy")+def test_account_search_pages_tied_names_across_projects_and_object_kinds():+ context, second = mcp_context(), mcp_context()+ ProjectMembership.objects.create(project=second.project, user=context.user)+ context = replace(+ context,+ project=None,+ token=APIToken(user=context.user, scope={"scope": "account", "permission": ["read"]}),+ )+ instant = timezone.now()+ expected = set()+ projects = list(ProjectMembership.objects.filter(user=context.user).select_related("project"))+ for membership in projects:+ project = membership.project+ dataset = Dataset.objects.create(project=project, name="Same")+ job = FinetuningJob.objects.create(+ project=project, dataset=dataset, name="Same", base_model="base"+ )+ Dataset.objects.filter(pk=dataset.pk).update(created_at=instant)+ FinetuningJob.objects.filter(pk=job.pk).update(created_at=instant)+ expected.update({("dataset", str(dataset.pk)), ("finetune", str(job.pk))})+ for ordering in ("name", "newest", "oldest"):+ seen, offset = [], 0+ while True:+ page = call(+ context,+ "search_objects",+ project_ids=[str(m.project_id) for m in projects],+ kinds=["dataset", "finetune"],+ ordering=ordering,+ limit=1,+ offset=offset,+ )+ assert page["scope_complete"]+ seen.extend((item["kind"], item["id"]) for item in page["items"])+ offset = page["next_offset"]+ if offset is None:+ break+ assert len(seen) == len(expected) and set(seen) == expected+++def test_revision_changes_only_the_fields_it_names():+ context = mcp_context(["read", "write"])+ row = EvalMatrix.objects.create(+ project=context.project,+ name="scoped",+ type="llm",+ source="Answer well.",+ enabled=False,+ span_type="tool_call",+ span_name="search",+ )+ listed = call(context, kinds=["eval_row"])["items"][0]+ revised = call(+ context,+ "revise_eval_matrix_row",+ row=str(row.pk),+ expected_updated_at=listed["updated_at"],+ source="Answer accurately.",+ )["row"]+ assert (revised["source"], revised["enabled"]) == ("Answer accurately.", False)+ assert (revised["span_type"], revised["span_name"]) == ("tool_call", "search")+ assert revised["updated_at"] > listed["updated_at"]+ row.refresh_from_db()+ assert row.revisions.get().definition["source"] == "Answer well."+ moved = call_tool(+ "revise_eval_matrix_row",+ {+ "row": str(row.pk),+ "expected_updated_at": revised["updated_at"],+ "capability": "support",+ },+ context,+ )+ assert moved.isError and moved.structuredContent["error"]["code"] == "invalid_input"+++def test_revision_refuses_a_change_of_nothing_and_an_oversized_retained_source():+ context = mcp_context(["read", "write"])+ row = EvalMatrix.objects.create(project=context.project, name="r", type="llm", source="Same.")+ stamp = {"row": str(row.pk), "expected_updated_at": row.updated_at.isoformat()}+ for unchanged in ({}, {"name": "r", "source": " Same. ", "enabled": True}):+ result = call_tool("revise_eval_matrix_row", {**stamp, **unchanged}, context)+ assert result.isError and result.structuredContent["error"]["code"] == "invalid_input"+ row.refresh_from_db()+ assert row.updated_at.isoformat() == stamp["expected_updated_at"]+ assert not row.revisions.exists()++ long = EvalMatrix.objects.create(+ project=context.project, name="long", type="deterministic", source="#" * 20_001+ )+ renamed = call_tool(+ "revise_eval_matrix_row",+ {"row": str(long.pk), "expected_updated_at": long.updated_at.isoformat(), "name": "longer"},+ context,+ )+ assert renamed.structuredContent["error"]["fields"].keys() == {"source"}+ long.refresh_from_db()+ assert long.name == "long" and not long.revisions.exists()+++def test_revision_rename_conflict_reports_the_name_field():+ context = mcp_context(["read", "write"])+ EvalMatrix.objects.create(project=context.project, name="taken", type="llm", source="One.")+ row = EvalMatrix.objects.create(project=context.project, name="free", type="llm", source="Two.")+ result = call_tool(+ "revise_eval_matrix_row",+ {"row": str(row.pk), "expected_updated_at": row.updated_at.isoformat(), "name": "taken"},+ context,+ )+ error = result.structuredContent["error"]+ assert result.isError and error["code"] == "eval_matrix_row_invalid"+ assert "name" in error["fields"]+ row.refresh_from_db()+ assert row.name == "free" and not row.revisions.exists()+++def test_retryable_failure_releases_the_request_key_and_a_refusal_keeps_it(monkeypatch):+ context = mcp_context(["read", "write"])+ connector = ConnectorCredential.objects.create(+ project=context.project,+ name="Langfuse",+ connector_type=ConnectorCredential.ConnectorType.LANGFUSE,+ api_key="provider-key",+ api_secret="provider-secret",+ verified_at=timezone.now(),+ capability_mapping_confirmed=True,+ )+ ConnectorSyncConfig.objects.create(+ credential=connector,+ version=1,+ source_project_id="source-project",+ lookback_days=7,+ effective_from=timezone.now(),+ )+ args = {"connector": str(connector.pk), "request_key": "sync-once"}++ def broker_down(*_, **__):+ raise ConnectionError++ target = "overbae.tasks.connector_sync.sync_connector_chunk.apply_async"+ monkeypatch.setattr(target, broker_down)+ failed = call_tool("sync_connector", args, context)+ assert failed.structuredContent["error"]["retryable"]+ assert not MCPMutation.objects.filter(request_key="sync-once").exists()++ queued = []+ monkeypatch.setattr(target, lambda args, **_: queued.append(args[0]))+ assert not call_tool("sync_connector", args, context).isError+ assert not call_tool("sync_connector", args, context).isError+ assert queued == [str(connector.pk)]++ refused = {"name": "bad", "type": "deterministic", "source": "x =", "request_key": "bad-check"}+ first = call_tool("create_eval_matrix_row", refused, context)+ assert first.isError and not first.structuredContent["error"]["retryable"]+ replayed = call_tool("create_eval_matrix_row", refused, context)+ assert replayed.structuredContent == first.structuredContent+ assert MCPMutation.objects.get(request_key="bad-check").state == "completed"+++def test_missing_receipt_names_no_recovery_tool():+ result = call_tool("inspect_mutation", {"request_key": "unknown"}, mcp_context())+ error = result.structuredContent["error"]+ assert error["code"] == "resource_not_found" and error["next_actions"] == []+++def test_inventory_console_links_name_console_routes():+ routes = Path(__file__).parents[1] / "frontend/src/routes/_auth"+ for kind, spec in COLLECTIONS.items():+ stem = spec.route.replace("/", ".")+ assert (routes / f"{stem}.tsx").exists() or (routes / f"{stem}.index.tsx").exists(), kinddiff --git a/tests/test_mcp_migrations.py b/tests/test_mcp_migrations.pynew file mode 100644index 00000000..cf461a62--- /dev/null+++ b/tests/test_mcp_migrations.py@@ -0,0 +1,55 @@+import pytest+from django.db import IntegrityError, transaction+from django.db.migrations.executor import MigrationExecutor+from migration_replay import scratch_database++pytestmark = pytest.mark.covers("migrations")+++def test_mcp_receipt_migration_preserves_evaluators_and_enforces_unique_request_keys(+ django_db_blocker,+):+ before = [("overbae", "0055_activity_task_index")]+ after = [("overbae", "0056_mcp_mutations_and_eval_revisions")]+ with scratch_database(django_db_blocker) as database:+ executor = MigrationExecutor(database)+ executor.migrate(before)+ apps = executor.loader.project_state(before).apps+ project = apps.get_model("overbae", "Project").objects.create(+ name="Migration", slug="migration"+ )+ user = apps.get_model("overbae", "User").objects.create(email="[email protected]")+ row = apps.get_model("overbae", "EvalMatrix").objects.create(+ project=project, name="Existing", type="llm", source="Original definition"+ )+ executor = MigrationExecutor(database)+ executor.migrate(after)+ apps = executor.loader.project_state(after).apps+ assert (+ apps.get_model("overbae", "EvalMatrix").objects.get(pk=row.pk).source+ == "Original definition"+ )+ receipts = apps.get_model("overbae", "MCPMutation")+ payload = dict(+ project_id=project.pk,+ user_id=user.pk,+ tool="create_eval_matrix_row",+ request_key="same-key",+ fingerprint="a" * 64,+ )+ receipts.objects.create(**payload)+ with pytest.raises(IntegrityError), transaction.atomic():+ receipts.objects.create(**payload)+ revision = apps.get_model("overbae", "EvalMatrixRevision").objects.create(+ row_id=row.pk, definition={"source": "Original definition"}, created_by_id=user.pk+ )+ assert revision.definition["source"] == "Original definition"+ executor = MigrationExecutor(database)+ executor.migrate(before)+ assert (+ executor.loader.project_state(before)+ .apps.get_model("overbae", "EvalMatrix")+ .objects.get(pk=row.pk)+ .source+ == "Original definition"+ )diff --git a/tests/test_mcp_mutation_races.py b/tests/test_mcp_mutation_races.pynew file mode 100644index 00000000..ef88e982--- /dev/null+++ b/tests/test_mcp_mutation_races.py@@ -0,0 +1,56 @@+from concurrent.futures import ThreadPoolExecutor+from threading import Barrier++import pytest+from mcp_fixtures import asgi_db+from starlette.testclient import TestClient+from test_mcp_account_access import account, rpc++from overbae.models import EvalMatrix, MCPMutation, ProjectMembership+from overbae.services.mcp.server import create_mcp_application++pytestmark = [asgi_db, pytest.mark.covers("work-once")]+++def test_concurrent_retries_create_once_and_revoked_membership_cannot_replay():+ user, projects, key = account()+ arguments = {+ "project_id": str(projects[0].pk),+ "name": "Concurrent check",+ "type": "llm",+ "source": "Answer accurately.",+ "request_key": "concurrent-create",+ }+ gate = Barrier(2)+ with TestClient(create_mcp_application()) as client:++ def submit():+ gate.wait(timeout=10)+ return rpc(+ client,+ key,+ "tools/call",+ {"name": "create_eval_matrix_row", "arguments": arguments},+ )["result"]++ with ThreadPoolExecutor(max_workers=2) as pool:+ results = list(pool.map(lambda _: submit(), range(2)))+ successes = [result for result in results if not result.get("isError")]+ assert successes+ assert all(+ result["structuredContent"]["error"]["code"] == "request_in_progress"+ for result in results+ if result.get("isError")+ )+ assert EvalMatrix.objects.filter(project=projects[0]).count() == 1+ assert MCPMutation.objects.filter(project=projects[0]).count() == 1+ replay = rpc(+ client, key, "tools/call", {"name": "create_eval_matrix_row", "arguments": arguments}+ )["result"]+ assert replay == successes[0]+ ProjectMembership.objects.filter(project=projects[0], user=user).delete()+ denied = rpc(+ client, key, "tools/call", {"name": "create_eval_matrix_row", "arguments": arguments}+ )["result"]+ assert denied["isError"]+ assert denied["structuredContent"]["error"]["code"] == "project_required"diff --git a/tests/test_mcp_resources.py b/tests/test_mcp_resources.pyindex ed15482a..97a8697b 100644--- a/tests/test_mcp_resources.py+++ b/tests/test_mcp_resources.py@@ -147,6 +147,8 @@ def test_resource_templates_cover_the_public_resource_surface():"overmind://dataset-pipeline-packages/{id}","overmind://dataset-pipeline-bindings/{id}","overmind://pipeline-diagnostics/{id}",+ "overmind://checkpoints/{id}",+ "overmind://eval-rows/{row}","overmind://eval-runs/{eval_run}","overmind://eval-sets/{eval_set}","overmind://finetunes/{job_id}",