Repository navigation
Phase 3a: NEMAR's context, MCP images, and a live contract guard - #449
Conversation
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.
Preview Deployment
This preview will be updated automatically when you push new commits. |
Local review, and what was done with each findingSeven Sonnet reviewers covered Seams
Tests
Error handling
Types
Comments and docs
Simplification
Gates
|
b5038a8
into
feature/issue-429-epic-browser-execution
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'spython_browsersnippet and thenplot_window(window), but that snippet read raw digital counts, whichplot_windowdoes 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 anopen_arrayread returns stored counts. Theexecute_codedescription says the same.The prompt, section by section. It explains
onversusnmidentifiers. The cost ladder sayssearch_datasets' filters often answer outright.render_overviewsays 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.jsextracts the snippet fromconfig.yamland 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 --nemargained apromptscript that does the same in Chrome against the live archive.MCP images reach the model, on the Anthropic path only.
_content_ofinsrc/tools/mcp_client.pyturns a PNGImageContentinto the Anthropic-native blockToolResultImage.to_content_blockbuilds, withinMAX_IMAGES,MAX_IMAGE_BYTESandMAX_IMAGE_EDGE_PX, with its dimensions read from the IHDR chunk. Any refused image becomes a line saying why.ProviderChoice.takes_native_blocksis now the one answer to "does this path take Anthropic's blocks", for citations, MCP images and browser figures alike.OSA_MCP_IMAGES_DISABLEDis a kill switch read on every call.Browser figures follow the same gate.
/chat/resumeresolves the provider before it claims the parked call, andbuild_live_tool_messagenow 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_historyrunsscrub_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_endevents 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.pychecks productionmcp.nemar.orgfor 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: everyeegprep_leanname it uses is exported, and every keyword it passes is a parameter, read statically from the wheel's source..github/workflows/nemar-mcp-contract.ymlruns 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) makespython_browserlead withread_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 reportseegprep_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 checkandruff format --checkare clean.mcp.nemar.org: the contract file (18) and the MCP client's production class pass, includingrender_overviewreturning an image block through OSA's client.bunsuite, andbuild-runtime-bundle.js --check.chrome.js: 40 checks onnemarlike;controlfails to boot, as it must.widget_e2e.py --nemarran 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.tool_end, the keyword check, and naming every cap.actionlintis 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.