Skip to content

Phase 3a: NEMAR's context, MCP images, and a live contract guard - #449

Merged
neuromechanist merged 20 commits into
feature/issue-429-epic-browser-executionfrom
feature/issue-432-phase3-environments
Sep 23, 2026
Merged

neuromechanist merged 20 commits into
feature/issue-429-epic-browser-executionfrom
feature/issue-432-phase3-environments

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

The first of two OSA pull requests for phase 3 of the browser-execution epic. It brings NEMAR's assistant up to date with what NEMAR now serves (#370), lets nemar_render_overview's image reach the model, and adds a guard that goes red when NEMAR's live contract stops matching what OSA ships. The second, which re-vendors eegprep-lean 0.1.0.dev2 and closes #432 and #424, follows.

What ships

NEMAR's prompt teaches the read that composes. Phase 2 told the model to start from nemar_read_window's python_browser snippet and then plot_window(window), but that snippet read raw digital counts, which plot_window does not take, and which plot like EEG while being wrong. The prompt now carries one canonical snippet (read_index, index.store(path), read_window(..., group=store.group(name)), plot_window(window).figure), says where each value comes from, and says an open_array read returns stored counts. The execute_code description says the same.

The prompt, section by section. It explains on versus nm identifiers. The cost ladder says search_datasets' filters often answer outright. render_overview says the model sees the image, and what to say when it was not attached. Three sections were removed: "Using Tools Strategically" (folded into the ladder), "Common Research Use Cases" (repeated the ladder), and "Citation and Licensing" (stale, and it contradicted "Presenting datasets").

The prompt is executable. frontend/test-data-lane.js extracts the snippet from config.yaml and runs it verbatim on the real Pyodide 0.29.5 through the prelude's real transport, against a loopback index and store: values in physical units, labels, one PNG. widget_e2e.py --nemar gained a prompt script that does the same in Chrome against the live archive.

MCP images reach the model, on the Anthropic path only. _content_of in src/tools/mcp_client.py turns a PNG ImageContent into the Anthropic-native block ToolResultImage.to_content_block builds, within MAX_IMAGES, MAX_IMAGE_BYTES and MAX_IMAGE_EDGE_PX, with its dimensions read from the IHDR chunk. Any refused image becomes a line saying why. ProviderChoice.takes_native_blocks is now the one answer to "does this path take Anthropic's blocks", for citations, MCP images and browser figures alike. OSA_MCP_IMAGES_DISABLED is a kill switch read on every call.

Browser figures follow the same gate. /chat/resume resolves the provider before it claims the parked call, and build_live_tool_message now requires the decision, with no default. On a non-Anthropic path each figure arrives as "not attached: images are not sent to this model", and the prompt tells the model to say it could not see the figure rather than describe it. The previous behavior sent images down a path nothing had shown accepts them.

No base64 in history or the stream. ChatSession.replace_history runs scrub_stored_images, which closes a leak phase 2 shipped: a run that parked a second browser call stored the first call's live figure. tool_end events now stream only text blocks and name every other block, so a block spelling nobody has written yet is withheld, not printed.

A guard that can go red. tests/test_assistants/test_nemar_contract_live.py checks production mcp.nemar.org for the fields the prompt depends on (path, groups[].name, sample_slice, how_to.python_browser), and checks that the live recipe fits the vendored wheel: every eegprep_lean name it uses is exported, and every keyword it passes is a parameter, read statically from the wheel's source. .github/workflows/nemar-mcp-contract.yml runs it daily, and opens, comments on or closes a labeled issue, including when setup fails before the checks run.

The seam this guard exists for

nemar-cli #1487 (merged to dev, not yet in production) makes python_browser lead with read_index(id, index_url=<contract_base>index.json), which needs eegprep-lean 0.1.0.dev2. OSA still vendors dev1. Run against that recipe, the new check reports eegprep_lean.read_index takes no keyword 'index_url' on dev1 and nothing on dev2. That is safe today because the browser lane is not live anywhere, which is the condition ADR 0071 sets. The next PR re-vendors dev2 and must land before this epic finalizes. It also adds a verbatim CPython run of the live recipe against the vendored wheel.

Test plan

  • uv run pytest -m "not network": 2664 passed, 50 skipped. The one failure is test_version_shows_version fails locally and passes in CI, because rich colorizes on a TTY #434. ruff check and ruff format --check are clean.
  • The network tests, run locally against production mcp.nemar.org: the contract file (18) and the MCP client's production class pass, including render_overview returning an image block through OSA's client.
  • Every bun suite, and build-runtime-bundle.js --check. chrome.js: 40 checks on nemarlike; control fails to boot, as it must.
  • In Chrome, widget_e2e.py --nemar ran the prompt's snippet on live nm000103 under nemar.org's CSP: a (4, 500) window in µV at 250 Hz, labeled E1 to E4, one figure drawn, and run 2 received it.
  • Mutation-checked: each new guard was loosened or removed in turn, and a test failed each time. That covered the discovery cache key, the factory's provider gate, the resume route's gate (inverted and dropped), the kill switch read at wrap time, scrubbing while trimming, fail-closed tool_end, the keyword check, and naming every cap.
  • actionlint is clean on the new workflow. A scheduled or dispatched run is only possible once the workflow reaches the default branch.

Reviewed locally by seven Sonnet agents. How each finding was addressed is in a comment below.

Closes #370.
Part of #432 and epic #429.

The browser lane told the model to start from the recipe's open_array
read, whose window is stored digital counts, and then to plot it with
plot_window, which takes read_window's Window. The prompt now carries
one snippet (read_index, index.store, read_window, plot_window) and
says where each value comes from. It also says on datasets are
imported from OpenNeuro and nm are NEMAR's own, lets search filters
answer directly, and drops three sections that restated the ladder or
contradicted the citation rule.

Tested: pytest tests/test_assistants.
test-data-lane.js now extracts the one canonical python snippet from
config.yaml's system_prompt (the first fence after "## Running code in
the reader's browser"), fills its placeholders whole-word, and runs it
unchanged through eegprep-lean's real read_index/read_window against a
loopback format-3 index.json served by the existing store. Asserts
shape, unit, rate, labels, physical values against digital*scale+offset,
and exactly one PNG in the result, then reads window.data again from a
follow-up run() in the same namespace.

Tested: bun frontend/test-data-lane.js (49/49). Mutation-checked by hand
(not committed): swapping read_window for a raw open_array/getitem read
fails 9 of the new assertions with AttributeError on window.unit; removing
the heading or the fence makes the extraction guard fail with its message
in both cases.
_wrap_tool's _call now returns a content-block list (text plus one
Anthropic-native image block per accepted PNG) when an MCP result carries
ImageContent, so nemar_render_overview's picture can reach the model
instead of being silently dropped. Images are capped by MAX_IMAGES,
MAX_IMAGE_BYTES and MAX_IMAGE_EDGE_PX (width/height read from the PNG's
own IHDR chunk), gated to image/png only, and refused images become a
text line naming why.

The provider decision is threaded in, not sniffed: CommunityAssistant
gets a new allow_mcp_images flag (mirroring citations), passed to
_load_mcp_tools -> discover_mcp_tools -> _wrap_tool at wrap time. The
router sets it from provider_choice.provider == 'anthropic'. The MCP
tool-discovery cache key now includes allow_images, so the same server
discovered for an Anthropic request and an OpenRouter request does not
share one wrapped tool list. A live kill switch, OSA_MCP_IMAGES_DISABLED,
is checked fresh on every call rather than baked in at wrap time.

The same gate now applies to phase 2's client-tool images:
build_live_tool_message takes allow_images, and the /chat/resume handler
resolves the provider (best-effort; a resolution failure defaults to no
images rather than changing which status code the endpoint returns) to
decide it before building the live message it hands to _stream_chat_response.

Two more leaks closed:
- ChatSession.replace_history now runs scrub_stored_images over whatever
  a graph run's final state hands back, replacing every image content
  block (any of the four spellings the payload-transport tests cover)
  with a text placeholder. This is what actually fixes the leak where a
  run that parks a second browser call adopts the graph's state whole,
  which still carries the first call's LIVE tool message from
  initial_messages, and the leak where a real MCP ToolMessage with an
  image (built by LangGraph's ToolNode, never through
  build_history_tool_message) is stored as-is.
- Both tool_end SSE handlers in community.py now render tool_output
  through _sse_safe_tool_output instead of a bare str(), so a tool
  output that is a content-block list never streams its image's base64
  in the SSE event.

Tested: uv run pytest tests/test_api tests/test_assistants tests/test_tools
tests/test_core -m 'not network' (1544 passed, 17 skipped, 21 deselected).
uv run ruff check and ruff format clean on the four changed files.
…gate

Adds tests/helpers/images.tiny_png (an exact-size real PNG, for tests
that need to know dimensions in advance rather than derive them from a
chart). Covers png_dimensions against real IHDR bytes and malformed
input, image_block_placeholder and ToolResultImage.placeholder sharing
one format, scrub_stored_images across all four known image-block
spellings plus non-image and string content, and
build_live_tool_message's new allow_images gate.

Tested: uv run pytest tests/test_api/test_tool_results.py (51 passed).
Mutation-checked by hand: removing png_dimensions's signature/IHDR
guards fails 3 of 5 TestPngDimensions tests; dropping image_url from
_is_image_block's recognized types lets base64 leak past
test_the_data_url_block_is_replaced_too. Both restored after confirming
the failure.
_build_server() gains render_overview (real ImageContent), many_images
(exercises MAX_IMAGES), undecodable_image, and wrong_mime_image; the
exact tool-set assertion and the two tool-count assertions are updated.

New TestImages class invokes through a ToolCall dict (name/args/id/type)
rather than a bare args dict, so LangChain actually builds a ToolMessage
via _format_output -- the path that matters, since a malformed block in
the returned list would get stringified there instead of proving the
list survives. Covers: an accepted image lands as a real content block;
allow_images=False and the OSA_MCP_IMAGES_DISABLED kill switch both
withdraw it; a non-PNG mime and undecodable PNG data are refused by
name; MAX_IMAGES caps how many of one result's images are attached.

Added a network test to TestAgainstProductionNemar:
render_overview on nm000103 (recording path from a real
list_recordings call) reaches a real ToolMessage as an image block.

Tested: uv run pytest tests/test_tools/test_mcp_client.py (25 passed,
including the 4 network tests, run against the live NEMAR MCP server).
_content_of's output feeds a real ToolMessage through both real payload
builders: an accepted image survives CachingChatAnthropic._get_request_payload
(the same proof the existing tests use, on MCP-shaped input this time), and
a gated result reaches ChatLiteLLM._create_message_dicts as text only. A
third test is the control: the same accepted content, sent to LiteLLM
anyway, shows that transport forwards an image block unexamined -- which is
the concrete reason allow_images gates construction rather than trusting
LiteLLM to reject it.

Tested: uv run pytest tests/test_core/test_tool_result_image_transport.py
(12 passed).
_sse_safe_tool_output had to change from what was committed: on_tool_end's
output is the ToolMessage LangGraph's ToolNode built, not a tool's raw
return value, so str() on it prints .content in full regardless. The
real test caught this immediately (str(ToolMessage) embedded the base64
that a bare list check let through undetected). Fixed to read
.content off the output when present, and to only take the special path
when that content is a list containing an actual image block, so a
plain-string tool's event renders through the exact same str(tool_output)
it always has.

Added render_with_image, a real server-executed tool returning the same
content-block shape src.tools.mcp_client._wrap_tool returns for an
accepted image, to exercise both the tool_end sanitizer and the history
scrub against a real LangGraph ToolNode round trip. New tests: tool_end
never carries render_with_image's base64 (with a plain-string control);
a batch combining that tool with a parked execute_code stores no base64
in session history; a second parked call still scrubs the first call's
live image out of stored history.

Tested: uv run pytest tests/test_api/test_client_tool_streaming.py
(32 passed) and tests/test_api -m 'not network' (608 passed).
Mutation-checked by hand: disabling the image-block guard in
_sse_safe_tool_output makes test_the_image_becomes_a_placeholder_not_its_base64
fail with the base64 string present in the event; restored after
confirming.
One paragraph after the existing image-in-history rule: MCP images are
gated to the Anthropic path via allow_mcp_images, re-sent with every
later model call within a run, never kept in stored history
(scrub_stored_images), and can be withdrawn live via
OSA_MCP_IMAGES_DISABLED.

Not tested (documentation only).
New tests/test_assistants/test_nemar_contract_live.py. Two pure ast-based
helpers, non-network and run in every CI sweep: eegprep_lean_exported_names
parses the vendored wheel's eegprep_lean/__init__.py (names imported from
submodules, plus the keys of _EXTRA_NAMES) without importing or executing
it; eegprep_lean_names_used parses a python snippet for the eegprep_lean
names it actually reads (from-imports and eegprep_lean.X attribute access),
ignoring comments and strings by construction.

Network tests (against https://mcp.nemar.org/mcp, deselected by default):
list_recordings gives every recording a path and named groups; read_window
returns a recipe with how_to.python_browser and the sample_slice
start/end fields the prompt's snippet needs; every eegprep_lean name the
live recipe uses is exported by the committed wheel -- the guard that
would go red if the server or the wheel drifted.

Tested: uv run pytest tests/test_assistants/test_nemar_contract_live.py
(12 passed: 9 non-network, 3 against production). Mutation-checked by
hand: dropping the _EXTRA_NAMES branch from eegprep_lean_exported_names
fails 2 of the wheel tests (open_array is only reachable through it);
restored after confirming.
Daily cron plus workflow_dispatch, modeled on widget-route-health.yml:
runs the three NEMAR network test targets (test_mcp_client.py's
TestAgainstProductionNemar, test_nemar_mcp_wiring.py -m network, and the
new test_nemar_contract_live.py), opens or comments on one issue labeled
nemar-mcp-contract on failure and fails the run, closes it with a
Recovered comment on the next green run.

Validated with actionlint (clean; the tool's other findings across the
repo are pre-existing and unrelated to this file). act is not installed
in this environment, so it could not be used.
build_live_tool_message now requires the provider decision, and a
withheld figure says it was never sent rather than not retained.
/chat/resume resolves the provider before claiming the parked call,
so nothing it raises can strand the session. Entry-point tests drive
the route with each provider's key; both mutations fail them.
MCP and browser placeholders share one phrase, and the prompt says
what it means. The kill-switch test now sets the switch after wrap
time, and the refusal and LiteLLM assertions pin exact text.
The contract test no longer names the dev1 wheel, so a re-vendor
needs no edit, and comments no longer cite a pre-squash commit.
widget_e2e.py --nemar gains a "prompt" script, read from NEMAR's
config, and stands in the Anthropic provider so run 2 still gets the
figure. Ran in Chrome on live nm000103: (4, 500) uV at 250 Hz,
labeled E1 to E4, one image reached run 2.
The aliased call in test_image_token_budget.py was the one site the
keyword-required allow_images still missed; the full suite found it.
ProviderChoice.takes_native_blocks now answers citations, MCP images and
browser figures alike. tool_end streams only text blocks and names any
other block. /chat/resume logs a swallowed provider error. A test pins
that replace_history scrubs images while it trims. Each change was
mutation-checked against its test.
Reading a result's images can no longer end the turn: a failure is
logged and the answer goes out without them. An image over both caps
names both. The discovery cache and the factory's provider gate each
have a test through real discovery, and the kill switches share one
env-flag helper.
A name check could not see read_index(index_url=...) on a wheel without
that parameter. The guard now reads each exported function's signature
from the vendored wheel. Against nemar-cli dev's recipe it reports
read_index takes no keyword 'index_url' on dev1 and nothing on dev2.
Production's recipe names read_window only in a comment, so step 3 now
says to use the prompt's own snippet when the recipe has no read_window
call.
A job that fails before the checks run is a failing check. The report
delimiter is random. actionlint is clean.
@github-actions

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-432-phase3-env-demo.osc.earth
Branch feature/issue-432-phase3-environments
Commit 6a509d9

This preview will be updated automatically when you push new commits.

@neuromechanist

Copy link
Copy Markdown
Member Author

Local review, and what was done with each finding

Seven Sonnet reviewers covered 4fbc5db..2f8e6f2: code, tests, error handling, comments and docs, types, simplification, and the seams with nemar-cli, eegprep-lean and the widget. Before that, the lead's own pass over the implementer's commits fixed six things: the contract test named the dev1 wheel's file, three comments cited a commit that a squash merge would orphan, the kill-switch test set the switch before wrapping the tool (so it could not tell a live read from a wrap-time one), an assertion was weakened with an or, a live test hardcoded a group name, and /chat/resume resolved the provider after claiming the parked call, inside the window its own comment says nothing may raise in. Every finding below is addressed except the two noted.

Seams

  • The contract guard could not see a keyword the wheel lacks (critical). nemar-cli dev's recipe calls read_index(..., index_url=...), which dev1 does not take, and a name check stays green on that. The guard now reads each exported function's parameters from the vendored wheel's source and checks every keyword a recipe passes. On nemar-cli dev's recipe it reports eegprep_lean.read_index takes no keyword 'index_url' against dev1 and nothing against a dev2 build. A second test cross-checks the verdict against the wheel's version. c96d64a
  • The wheel is still dev1 (critical). Not changed here: the next PR re-vendors dev2, built from the merged b4aa18bd with SOURCE_DATE_EPOCH set to the commit time, which makes the build byte-reproducible. The browser lane is not live anywhere, which is ADR 0071's condition, and the description records that the next PR must land before the epic finalizes.
  • Step 3 of the prompt said to use the recipe's read_window read, and production's recipe names it only in a comment. It now falls back to the prompt's own snippet. 928b871
  • Verified, no change: the snippet matches the vendored API; path, groups[].name, sample_slice and zarr match both production and nemar-cli dev; the widget never reads tool_end.output; render_overview's default image is well inside OSA's caps.

Tests

  • The discovery cache key had no test that it keeps the two paths apart; reverting it left 895 tests green. A test discovers one server both ways, in both orders. 988532e
  • The factory's provider gate for run 1 had no end-to-end test. Two tests build the assistant through create_community_assistant with each provider's key and invoke its own render_overview. 988532e
  • Nothing pinned that replace_history scrubs while it also trims. A test puts an image inside a history over the cap. 4888b9c
  • The byte and edge caps were never driven through the MCP path. A fixture returns one image over each cap and one over both. 988532e
  • Each was mutation-checked: the mutation the reviewer named now fails its test.

Error handling

  • _content_of ran outside the guarded call, so a malformed image could end the turn with no log line (critical). It is now guarded: the failure is logged and the answer goes out without its images. TypeError joins the base64 catch. 988532e
  • A failure in checkout, Python setup or uv sync opened no issue. The issue step now also runs on failure(), with a body saying nothing was checked. The multiline output delimiter is random. 2f8e6f2
  • tool_end redacted only the image spellings it knew. It now streams text blocks only and names every other block, so it fails closed. 4888b9c
  • A swallowed provider error on /chat/resume is logged. An image over both caps names both. 4888b9c, 988532e
  • The name check counts aliased imports. c96d64a

Types

  • provider == "anthropic" was repeated at four sites; three meant "takes Anthropic's native blocks". That is now ProviderChoice.takes_native_blocks. The fourth, which picks the LLM class, stays a provider comparison. 4888b9c
  • _accept_mcp_image returns dict | str instead of a pair of optionals. The placeholder reason is a Literal, pinned to its two constants by a test. TRUTHY is a frozenset. 988532e
  • The one src.tools to src.api import is documented at the import as one-way. Moving ToolResultImage out of the API module would change a phase 2 model for no current gain. 988532e

Comments and docs

  • A test cited the wrong file for "not been shown to accept"; _content_of's docstring said it matched _payload_of when an image is refused, and blamed LangChain for a choice that is ours; a comment cited "decision 7 of the phase plan". All corrected. 988532e, 4888b9c

Simplification

  • The two kill switches share one env_flag_set helper. The cache-key rationale is written once. 988532e
  • Deferred to the next PR, deliberately: extracting the issue open/close steps, now duplicated between widget-route-health.yml and this workflow, into a composite action. The next PR adds a third copy (the weekly eegprep-lean watcher), and one extraction there covers all three.

Gates

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant