Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions docs/containers.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Container images

The canonical container namespace is **`ghcr.io/unipat-ai`**. Ten packages carry fifteen release
versions and one archived experimental runtime: sixteen versions in total, all
`linux/amd64`.
The canonical container namespace is **`ghcr.io/unipat-ai`**. The inventory records
current releases, retained historical versions, and explicitly archived experimental
runtimes. All listed runtime releases target `linux/amd64`.

[`resources/images.json`](../resources/images.json) records, for every version, the tag, the
immutable GHCR manifest digest, the config digest, the platform, the package URL, and the
Expand All @@ -17,13 +17,13 @@ The harness needs an **agent image** for the route being run, and for the extern
|---|---|---|
| Raw task files, Codex | [`sciencevision-codex`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-codex) | `server-20260930-h20` |
| Rendered views, Codex | [`sciencevision-codex-2d`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-codex-2d) | `server-20260930-h20` |
| Bundled MCP tools, Codex | [`sciencevision-codex-mcp`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-codex-mcp) | `server-20261014-h20` |
| Bundled MCP tools, Codex | [`sciencevision-codex-mcp`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-codex-mcp) | `server-20261125-sequence-h20` |
| MCP client, Codex | [`sciencevision-codex-mcp-client`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-codex-mcp-client) | `release-20260930-h20` |
| Raw task files, Claude Code | [`sciencevision-claude-code`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-claude-code) | `server-20261002-h20` |
| Rendered views, Claude Code | [`sciencevision-claude-code-2d`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-claude-code-2d) | `server-20261002-h20` |
| Bundled MCP tools, Claude Code | [`sciencevision-claude-code-mcp`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-claude-code-mcp) | `server-20261015-h20` |
| Bundled MCP tools, Claude Code | [`sciencevision-claude-code-mcp`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-claude-code-mcp) | `server-20261125-sequence-h20` |
| MCP client, Claude Code | [`sciencevision-claude-code-mcp-client`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-claude-code-mcp-client) | `release-20261002-h20` |
| External HTTP MCP worker | [`sciencevision-mcp-worker`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-mcp-worker) | `server-20260924-h20` |
| External HTTP MCP worker | [`sciencevision-mcp-worker`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-mcp-worker) | `server-20261125-sequence-h20` |
| Deterministic scorer | [`sciencevision-scorer`](https://github.com/orgs/UniPat-AI/packages/container/package/sciencevision-scorer) | `server-20261104-h20` |

The naming is positional, not generational. For each agent engine, the name without a suffix is
Expand All @@ -32,6 +32,13 @@ implementation, and `-mcp-client` connects a client-only wrapper to an external

## Bundled or external

The sequence-capable bundled Codex and Claude Code release is
`server-20261125-sequence-h20`; exact pullable digests and verification are in
[`resources/images.json`](../resources/images.json). These retain the previous
73 tools and add `sv3d_switch_sequence`. Use the explicit bundled-stdio task
generation described in [Medical sequence switching](medical-sequence-mcp.md).
The older tags below remain reproducibility references and are not rewritten.

There are two MCP layouts, and they are not interchangeable:

- **Bundled.** `sciencevision-*-mcp` carries the CLI and its MCP implementation in one image.
Expand Down
6 changes: 6 additions & 0 deletions docs/evaluation.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ A route ID is a label, not a permissions attestation. Reproducing a setting requ
contract and a runtime profile that actually enforce its intended access, with the evidence
recorded in the run receipt.

Medical multi-sequence tasks additionally use the declared public image manifest
and the sequence-capable runtime described in
[Medical sequence switching](medical-sequence-mcp.md). Regenerate task trees to
obtain their task-specific sequence enum and catalog; historical trees and
reported scores are unchanged.

## Running the harness

The entire evaluation harness is vendored under [`harness/`](../harness/), a copy of the
Expand Down
118 changes: 118 additions & 0 deletions docs/medical-sequence-mcp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Medical sequence switching in evaluation

`sv3d_switch_sequence` extends the evaluation MCP with the sequence-switching
capability introduced by [platform PR132](https://github.com/UniPat-AI/BabyVision-v2/pull/132).
It changes the active image inside one NIfTI session. Existing results and
frozen task trees retain their original tool surfaces.

The bundled Codex and Claude Code runtimes retain their existing 73 tools and
add one capability. The separate external HTTP worker retains its 58 tools and
adds one. These profiles have different existing tools and wire schemas; their
catalogs are recorded separately. A task with one public image hides the new
tool. Other viewer families retain their existing surfaces.

## Input contract

Declare each public image in the task's existing `assets` list, using one
`primary` role and any additional `sequence` roles. Each must reference an
actual `.nii` or `.nii.gz` image and use `viewer: "niivue"` when a viewer is
declared. The primary image opens first regardless of attachment order.
The generator stages these public assets and writes the existing
`sciencevision.mcp_task_assets.v1` manifest. Runtime discovery reads that
manifest; it never searches adjacent files or invents missing modalities.

The eval switch currently requires **3D images with the same NIfTI spatial
units** and a shared anatomical world coordinate system. It supports different
dimensions, voxel spacing and affine transforms when the current focus remains
within the target field of view. It does not provide temporal/4D frame switching,
DICOM-series import, or loading embedded JavaScript/base64 volumes from HTML.
The expert viewer's separate first-frame behavior is not an eval capability.

`mask`, reference and ground-truth assets are not sequences. Existing asset
visibility rules still apply: only an explicitly public overlay is staged for
the model. An `R`, `A` or `B` file existing on disk is insufficient to make it
public. Source task questions and answer boundaries are unchanged.

## Calls and state

Open the declared primary with `sv3d_open_scene`, then inspect
`sv3d_get_state`. Multi-image sessions report `sequence` and `sequences`.
Ordinary names come from filenames, for example `T1GD`, `T1`, `T2`, `FLAIR`.
Filename collisions use a deterministic `./` path-qualified identifier. Use
the names in state or the task-specific tool enum.

The wire call retains the runtime's existing `args` wrapper:

```json
{"args":{"session_id":"<opened-session>","sequence":"T2"}}
```

State reports `sequence_focus_world` as a continuous world anchor. Displayed
slice indices select the nearest voxels; this quantization does not move the
stored world anchor. Crosshair and subsequent per-axis slice changes update
the anchor. Camera, mode, clipping and overlay visibility persist. Each target
uses its original intensity window. Public masks are resampled from their
original source with nearest-neighbor labels when grids differ.

A missing, invalid or unavailable target returns an error without replacing
the session. Repeating the returned `replay_input` is deterministic. The
existing eval full reset remains close-and-reopen; this change does not add a
`viewer_reset` tool or invent persisted measurement annotations.

## Generate new bundled-stdio tasks

Use a published sequence-capable bundled image recorded in
[`resources/images.json`](../resources/images.json). Export its actual catalog
for the task's viewer family before generation:

```bash
IMAGE=ghcr.io/unipat-ai/sciencevision-codex-mcp@sha256:98b57812659434bb02393ff250aacdb0d9fce79f05bdec6f888ff189ffa33e2a
docker run --rm --entrypoint sciencevision-mcp "$IMAGE" \
--surface --viewer-family niivue.v1 > niivue-surface.json
cd harness
python -m scripts.harbor.qa_gen_to_tasks \
--jsonl approved-medical-tasks.jsonl --out new-stdio-tasks \
--containerized --agent-env codex-mcp \
--bundled-mcp-image "$IMAGE" --mcp-surface ../niivue-surface.json
```

`claude-code-mcp` uses the same opt-in flag with its own exact image catalog.
The generator emits the bundled Dockerfile, public asset manifest,
`environment/mcp.stdio.json` and `environment/mcp-runtime-profile.json`.
The profile carries the real image's task-specialized catalog and schema hashes.
Use the emitted stdio config with the native launcher. This is the existing
**3D + Scaffold + Vision MCP** source-access setting, not MCP-only isolation.
The matrix driver's default HTTP config is not silently changed by this opt-in.

Without `--bundled-mcp-image`, generation retains the external HTTP layout.
The default worker is
`ghcr.io/unipat-ai/sciencevision-mcp-worker@sha256:4c8a482d5cc1cce0d04eaa7861f463843fa50c95318100a0db877a828c843d4f`.
Use its own `--surface` output for that
profile. Public sources stay in the private worker, and the emitted per-task
manifest, enum and catalog hashes agree with the worker's actual `tools/list`.
Old worker tags are retained for reproduction and do not gain the new tool.

## Auditable image build inputs

The bundled overlay generator is
`harness/scripts/harbor/sequence_runtime_overlay.py`; it validates the source
fingerprints of the audited bundled base and emits only the changed files plus
`sequence-overlay.json`. `Dockerfile.sequence-overlay` merges these files into
that base without replacing its renderer, agent CLI, dependencies or 73 existing
wire schemas. Its two new shared modules are the same source used by the
external worker.

The exact reusable bundled bases are
`ghcr.io/unipat-ai/sciencevision-codex-mcp@sha256:4de6598960d745f408e8f91050b3b73234416dd5ae86d35bf26637094a32b7ca`
and
`ghcr.io/unipat-ai/sciencevision-claude-code-mcp@sha256:74a05ae987097140b97ca976a406cf272866c9edbb6fa2313e897a25dab36df5`.
The overlay source was built before its eventual Git commit: its content manifest
records the actual base and file hashes; the final source commit is not claimed
as the image's build revision.

The separate `Dockerfile.sequence-worker-overlay` updates the external worker's
reviewed source while retaining its non-root user, dependencies and healthcheck.
The standard full worker Dockerfile and allow-listed builder also include the
new capability when rebuilding from source. Release tags, digests and source
verification belong in the image inventory after an actual build and registry
readback; local candidates do not establish a pullable release.
5 changes: 4 additions & 1 deletion harness/sci3d_agent/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@
SYSTEM_PROMPT_MODE4_MEDICAL_MPR = (
"You are a medical 3D imaging analysis agent working with a CT/MRI "
"volume, just as a radiologist would in a multiplanar (MPR) viewer. "
"Start a session with `sv3d_open_scene`, then explore the volume: "
"Start a session with `sv3d_open_scene`, then explore the volume. "
"When its state lists multiple sequences, `sv3d_switch_sequence` changes "
"the public MRI sequence while keeping the world focus: "
"`sv3d_set_render_mode` switches between volume rendering and the "
"mpr_axial / mpr_sagittal / mpr_coronal planes; `sv3d_set_slice` scrubs "
"to a specific slice (with window/level); `sv3d_set_crosshair` aligns "
Expand All @@ -218,6 +220,7 @@
"sv3d_set_render_mode",
"sv3d_set_slice",
"sv3d_set_crosshair",
"sv3d_switch_sequence",
"sv3d_set_clip_plane",
"sv3d_set_opacity",
"sv3d_toggle_mask",
Expand Down
1 change: 1 addition & 0 deletions harness/sci3d_agent/mcp/parity/allowlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ class UnknownFamilyError(ValueError):
"sv3d_set_slice",
"sv3d_set_clip_plane",
"sv3d_set_crosshair",
"sv3d_switch_sequence",
"sv3d_segment_2d",
"sv3d_segment_3d_volume",
})
Expand Down
87 changes: 87 additions & 0 deletions harness/sci3d_agent/mcp/sequence_catalog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""One pure catalog specialization used by task generation and both runtimes."""
from __future__ import annotations

import hashlib
import json
from typing import Any


def digest(value) -> str:
return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest()


def wire_schema(schema):
return {"type": "object", "properties": {"args": schema},
"required": ["args"], "additionalProperties": False}


def specialize_catalog(catalog, assets):
"""Derive task receipts without opening container-only /data paths.

Existing entries retain their exact image-supplied hashes. A pre-extension
image is never silently upgraded by the generator.
"""
from .tools.vision3d.sequences import sequence_entries, TOOLS
names = [name for name, _ in sequence_entries(assets)]
entries = []
for raw in catalog.get("tools", ()):
entry = dict(raw)
if entry["name"] == "sv3d_switch_sequence":
if len(names) < 2:
continue
schema = {**TOOLS[0].input_schema,
"properties": {**TOOLS[0].input_schema["properties"],
"sequence": {"type": "string", "enum": names}}}
entry["schema_sha256"] = digest(wire_schema(schema))
entries.append(entry)
tool_names = [entry["name"] for entry in entries]
return {**catalog, "tools": entries, "tool_names": tool_names, "tool_count": len(entries),
"catalog_sha256": digest(tool_names), "schema_sha256": digest(entries)}


def runline_catalog(specs, family, parameters):
"""Fingerprint the unchanged 73-tool runtime's real wire registrations."""
entries = [{"name": spec.name, "schema_sha256": digest(parameters(spec))} for spec in specs]
names = [entry["name"] for entry in entries]
return {"schema_version": "sciencevision.mcp_surface.v1", "server": "sciencevision",
"viewer_family": family, "gated": bool(family), "tools": entries,
"tool_names": names, "tool_count": len(names),
"catalog_sha256": digest(names), "schema_sha256": digest(entries),
"extension": {"tool": "sv3d_switch_sequence", "platform_pr": "https://github.com/UniPat-AI/BabyVision-v2/pull/132",
"semantics": "continuous world focus, nearest displayed slice; only declared primary/sequence NIfTI"}}


def install_runline(namespace: dict[str, Any]) -> None:
"""Add this capability without replacing a run-line server or its schemas.

The bundled runtime has image blocks and tools absent from the external
worker. Retain its original register/dispatch functions verbatim.
"""
from .tools.vision3d.sequences import task_tools, TOOLS
original_specs = namespace["tool_specs"]
original_main = namespace["main"]

def tool_specs(family=None):
specs = list(original_specs(family))
if family not in (None, "niivue.v1"):
return tuple(specs)
if family in (None, "niivue.v1") and not any(s.name == TOOLS[0].name for s in specs):
specs.extend(TOOLS)
return tuple(task_tools(specs))

def main(argv=None):
import sys
args = list(sys.argv[1:] if argv is None else argv)
if "--surface" not in args:
return original_main(args)
try:
family = namespace["_viewer_family"](args)
result = runline_catalog(tool_specs(family), family, namespace["_advertised_parameters"])
result["legacy_surface"] = namespace["surface_for"](family, result["tool_names"]).as_dict()
print(json.dumps(result, sort_keys=True))
return 0
except ValueError as exc:
print(json.dumps({"error": str(exc)}), file=sys.stderr)
return 2

namespace.update(tool_specs=tool_specs, main=main)
21 changes: 21 additions & 0 deletions harness/sci3d_agent/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,33 @@ def list_tool_names(viewer_family: str | None = None) -> list[str]:
return [spec.name for spec in selected_tools(viewer_family, tools=ALL_TOOLS)]


def advertised_parameters(spec: ToolSpec) -> dict[str, Any]:
"""Export the existing wire shape without changing legacy registration."""
from fastmcp.tools import FunctionTool

if spec.name == "sv3d_switch_sequence":
from sci3d_agent.mcp.sequence_catalog import wire_schema
return wire_schema(spec.input_schema)
# mcp.tool(wrapped) performs this same signature-to-schema conversion.
return FunctionTool.from_function(
_safe_handler(spec), name=spec.name, description=spec.description
).parameters


def _build_fastmcp_server(viewer_family: str | None = None):
from fastmcp import FastMCP

mcp = FastMCP(SERVER_NAME)
for spec in selected_tools(viewer_family, tools=ALL_TOOLS):
wrapped = _safe_handler(spec)
if spec.name == "sv3d_switch_sequence":
# Preserve every legacy tool's wire schema. The new tool must
# advertise its actual inner args enum, rather than args: {}.
from fastmcp.tools import FunctionTool

tool = FunctionTool.from_function(wrapped, name=spec.name, description=spec.description)
mcp.add_tool(tool.model_copy(update={"parameters": advertised_parameters(spec)}))
continue
mcp.tool(
name=spec.name,
description=spec.description,
Expand Down
11 changes: 7 additions & 4 deletions harness/sci3d_agent/mcp/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,19 @@ def selected_tools(
) -> list[ToolSpec]:
"""Select the actual server surface; unknown families fail closed."""
source = list(ALL_TOOLS if tools is None else tools)
from sci3d_agent.mcp.tools.vision3d.sequences import task_tools
if not viewer_family:
return source
return task_tools(source)
from sci3d_agent.mcp.parity.allowlist import advertised_tools_for_family

return list(advertised_tools_for_family(viewer_family, source))
selected = list(advertised_tools_for_family(viewer_family, source))
return task_tools(selected) if viewer_family == "niivue.v1" else selected


def tool_schema_sha256(spec: ToolSpec) -> str:
"""Fingerprint the strict schema the MCP server itself advertises."""
return _sha256(spec.input_schema)
"""Fingerprint actual wire parameters, including the handler args wrapper."""
from .server import advertised_parameters
return _sha256(advertised_parameters(spec))


def surface_payload(
Expand Down
4 changes: 3 additions & 1 deletion harness/sci3d_agent/mcp/tools/vision3d/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@
from sci3d_agent.mcp.tools.vision3d.snapshot import TOOLS as _snapshot
from sci3d_agent.mcp.tools.vision3d.segment import TOOLS as _segment

TOOLS = [*_session, *_camera, *_state, *_snapshot, *_segment]
from sci3d_agent.mcp.tools.vision3d.sequences import TOOLS as _sequences

TOOLS = [*_session, *_camera, *_state, *_snapshot, *_segment, *_sequences]
2 changes: 2 additions & 0 deletions harness/sci3d_agent/mcp/tools/vision3d/_crosshair.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ def set_crosshair_handler(args: Mapping[str, Any]) -> Mapping[str, Any]:
level=s.slice.level,
)
replace_slice(sid, new_slice)
from .sequences import remember_crosshair
remember_crosshair(sid, planes)

applied_mode: Optional[str] = None
if set_mode:
Expand Down
13 changes: 13 additions & 0 deletions harness/sci3d_agent/mcp/tools/vision3d/_snapshot_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,19 @@ def _axis_for_mode(session: Session) -> str:

def _attach_slice_locator(args: dict[str, Any], session: Session) -> None:
"""Add either ``index`` or ``fraction`` to a primitive-args dict."""
if len(session.sequences) > 1:
import nibabel as nib
import numpy as np

from ._slice_math import _AXIS_TO_NP
from .sequences import _focus_world

image = nib.load(session.asset_path)
world = _focus_world(session, image)
voxel = np.linalg.solve(image.affine, [*world, 1])[:3]
axis = _AXIS_TO_NP[args["axis"]]
args["index"] = int(round(voxel[axis]))
return
if session.slice.index is not None:
args["index"] = int(session.slice.index)
elif session.slice.fraction is not None:
Expand Down
Loading
Loading