Skip to content

A mapped reader lists, fetches and reports removals through a protocol server's tools - #2216

Open
zlareb1 wants to merge 1 commit into
mainfrom
feat/source-worker-mapped-reader
Open

zlareb1 wants to merge 1 commit into
mainfrom
feat/source-worker-mapped-reader

Conversation

@zlareb1

@zlareb1 zlareb1 commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Part of: #1189
Part of: #1190

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

None: the reader is a library of the source worker package with no caller.

Why

A worker that reaches an upstream only through tool calls needs one mapping format for listing a source, fetching a document and learning that one was removed. The live read's tool mapping (MCPToolMapping) reads one document, needs the document to echo its id as JSON, and admits a tool only when its schema uses a small keyword set (no anyOf, $ref or $defs). A hosted server that lists through a nested argument, uses those keywords and returns a page as plain text cannot be mapped with it.

This change adds the format and its reader, and proves them on a recording before any server code depends on them.

Scope and risk

Every file is new except one paragraph in docs/architecture/mcp-source-client.md. The live read, MCPToolMapping and its schema check are unchanged, and nothing in the worker calls the reader.

The design in brief. A mapping is JSON, parsed by a model that refuses any key it does not name. It differs from the live mapping in three ways and no others:

  1. A tool is pinned by definition_sha256, the SHA-256 of the canonical JSON of {name, inputSchema, outputSchema, readOnlyHint}. The reader never interprets a schema, so any JSON Schema keyword is admitted. The description is left out because it changes without changing the call.
  2. arguments is a template. A member {"$value": "document_id" | "cursor" | "since" | "scope"} is replaced at any depth; a placeholder with no value drops its key. Nothing else in a call comes from the upstream or the registration.
  3. result is structured, json_text or text. A text result is the document, between text_frame markers when set. A listing is never text.

The alternative was to widen MCPToolMapping: admit more schema keywords and add a text result. That keeps schema interpretation on the read path and grows with every keyword a server uses; a digest pin needs no interpreter and refuses any change to what a call depends on.

New modules, all under source_worker/:

  • loom_source_worker/sync_types.py: Listed, Page, SyncDocument, ToolDefinition, ToolResult, the protocols ToolCaller and SourceReader, and ReaderError with its eleven codes.
  • loom_source_worker/mapping.py: Mapping (extra="forbid"), load, digest, definition_digest, fill.
  • loom_source_worker/readers/mcp_mapped.py: MappedReader(mapping, caller, *, items, scope).
  • qualification/record_mapped.py: the recorder, and Replay, which answers a reader from a recording and refuses any other call.
  • tests/fixtures/mapped/example/: a recording built by hand for a made-up server, in the layout the recorder writes: a nested listing argument whose schema uses anyOf, $ref and $defs, a cursor-paged listing returned as JSON text, and a page returned as plain text.

Decisions the format left open, each tested:

  • The checkpoint holds since, cursor and a third time, newest. A listing that stops at max_pages_per_turn resumes in a later turn, and the newest modified time may be on a page of an earlier turn; without carrying it, the next since would be computed from the last turn's pages only.
  • While a cursor is pending, since is the filter that cursor was issued under. A full call restarts a pending filtered listing without the filter.
  • A listing filtered by time is never complete, whatever the mapping declares, so it can never be read as naming every document.
  • removed answers gone only after the scope answered the same reader with a non-empty listing page or a fetched document. A server may answer for what a connection can no longer see as for what is not there.
  • removed raises nothing: every failure, including a changed tool definition, is unknown.
  • A fetch whose result is the mapped not-found answer raises protocol; removed is the call that reports the id gone. An error result of the listing tool raises denied when it matches the denial and protocol otherwise.
  • A string the upstream does not give is empty. A modified time is kept as written and must parse as a time with an offset.
  • load refuses a mapping that cannot work as written: a fetch without a document_id placeholder, a cursor path without a cursor placeholder (or the reverse), changed_since without a since placeholder and a modified path, paths on a text result, a title pattern without exactly one group, and not_found and denied matchers that could match the same result.
  • The reader bounds every call by its deadline itself, and reads the tool list under the same deadline.

Risk. None to a running deployment: no route, op, worker or stored row uses the new code. source_worker/tests/conftest.py adds source_worker/qualification to the import path of the worker's tests so they read a recording through the module that writes it.

Left out. The sync engine, the claim and the upload; a resources reader; moving the live read to this format. The proof on a recording of a real hosted server is a later change that adds only data: the recorder ships here and that recording does not exist yet.

Compatibility, rollout and rollback

  • Wire: none. No op, field, table, migration or setting is added or changed.
  • Operator steps: none.
  • Rollback: reverting removes the new files. Nothing is stored.

Tests

The worker checks ran in a virtualenv built as the mcp-source-worker workflow builds it (the locked dependencies, pytest==9.2.0, pytest-asyncio==1.5.0, ruff==0.16.9, mypy==2.3.1), with the package installed editable.

  • python -m pytest -q source_worker/tests: 461 passed, 17 subtests passed. The four new files hold 63 of them:
    • test_mapping_proof.py replays the recording: the recorded definitions match the mapping and an unhinted tool is refused; a full listing yields every id across pages with the first page's cursor, and a turn bounded to one page resumes; the cursor, the time and the scope reach a call only at their placeholder; a fetch returns the recorded document and drops a link outside link_origins; a missing id is gone and a denial, a cut document, another error, a not-found text without the error flag, a stalled call and a mapping without a removal check are unknown; one changed property of either definition (name, input schema, output schema, read-only hint) stops listing, fetch and removal before any call; a cut document and a result or text over its bound are too_large; nine unreadable results are protocol; an error that matches no matcher is protocol; no fixture holds an id outside the neutral form.
    • test_reader_contract.py runs over every reader kind, the mapped reader first: gone needs the scope to stay readable; a reader without a complete listing reports no absence (page bound, undeclared completeness, selected items, no items); the mapping digest ignores key order, whitespace and explicit nulls; a checkpoint holds no document text and stays within 4,096 bytes; a cursor too long for the checkpoint is refused; a listing resumes across turns and then filters by the carried time; a fetched document echoes the requested id.
    • test_mapping.py: template filling, the definition digest, and 26 mappings load refuses.
    • test_record_mapped.py runs the recorder against a scripted server with UUID ids in three spellings, a cursor and two names, then replays what it wrote.
  • Removing each of three guards in turn (the read-only check, the scope evidence for gone, the filter check on complete) fails its own test.
  • ruff check source_worker: All checks passed!. ruff format --check source_worker docs: 275 files already formatted. mypy --strict source_worker/loom_source_worker: Success: no issues found in 15 source files.
  • make typecheck: mypy-gate: 0 error(s) in 0 file(s), Success: no issues found in 71 source files.
  • python -m pytest -q -n 2 tests/unit/test_package_contracts.py tests/unit/test_op_transport_contract.py tests/unit/test_tunable_constants.py tests/unit/test_store_names_refused.py tests/unit/test_degraded_unnoted.py tests/unit/test_public_copy.py tests/unit/test_doc_links.py tests/unit/test_agent_instructions.py tests/analyzer: 601 passed, 12 skipped (the skips need a ClickHouse; no statement changed).
  • python scripts/gates/check_no_secrets.py: no secrets found. The formatter checks pass on the new JSON fixtures and the two docs pages.

No ClickHouse, server, generator or benchmark is involved: the change has no statement, op, setting or migration. The full unit suite and the worker's 3.14 leg are left to CI.

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code. Checked by running the tests above, by reading the diff once against the repository's invariants and the worker's existing modules, and by removing three guards to see their tests fail.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • Local format, lint, type checks and focused tests pass. The full make test-unit and applicable integration results are reported by CI; a full local run is not required before pushing.
  • No generated file is affected: no op, setting, table or plugin file changed.
  • No migration.
  • No plugin-shipped file changed.
  • No frontend change.
  • Docs under docs/ describe the system as it now is (docs/architecture/source-mapping.md, linked from docs/architecture/mcp-source-client.md), and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.
  • I signed the Contributor License Agreement (CLA) if CLA assistant requested a signature.

🤖 Generated with Claude Code


Note

Low Risk
New library and tests only; live MCP client and worker dispatch are unchanged, with no wire or stored-schema impact until integration.

Overview
Introduces a separate JSON read-mapping format and a MappedReader in source_worker so document sources can be listed, fetched, and checked for removal via MCP tools without the live client's restricted schema validation.

Unlike MCPToolMapping, mappings pin tools by SHA-256 of advertised definitions (not full schema parsing), build calls from $value argument templates, and support structured, JSON-in-text, and plain-text fetch results—including schemas with $ref/anyOf. load rejects unknown keys; MappedReader enforces size limits, verifies read-only pinned tools before calls, never returns partial documents, and exposes removed as gone/present/unknown with conservative evidence rules.

record_mapped.py plus Replay fixtures record and replay real server behavior for CI; architecture docs add source-mapping.md and link it from mcp-source-client.md. No worker routes or live read paths call the new reader yet.

Reviewed by Cursor Bugbot for commit af5a7ec. Bugbot is set up for automated code reviews on this repo. Configure here.

…l server's tools

A worker that reaches an upstream only through tool calls needs one mapping
format for listing, fetching and removal. The live read's tool mapping reads
one document, needs the document to echo its id as JSON, and admits a tool
only when its schema uses a small keyword set.

The read mapping pins a tool by the digest of its advertised definition, so
the reader never interprets a schema; builds each call from an argument
template with four placeholders; and reads a result as structured content,
JSON text or plain text. The reader refuses a changed definition before any
call, a result cut short, and a result the mapping cannot read. It reports a
removal only for the mapped not-found answer while its scope still reads.

The reader is a library of the worker package with no caller. The recorder
writes a server's definitions and results as fixtures through a tool channel,
with every upstream id, cursor and name replaced; the tests replay a recording
built by hand for a made-up server.

Signed-off-by: Mohammad Lareb Zafar <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@vercel

vercel Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
loom-docs Ready Ready Preview Dec 5, 2026 6:08am UTC
loom-telemetry Ready Ready Preview Dec 5, 2026 6:08am UTC

Request Review

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit af5a7ec. Configure here.

nothing = MappedReader(mapping, tape, items=[], scope=empty_scope)
if any([page.items async for page in nothing.list_since(None, full=True, deadline=deadline)]):
raise SystemExit("the empty scope lists a document")
files["list_empty"] = tape.calls[before]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recorder drops extra listing pages

Medium Severity

record requires the main scope to take two pages, but it stores only tape.calls[2] as list_changed and tape.calls[before] as list_empty. Later pages of a changed or empty listing stay on the tape and are never written, so the fixture cannot replay the listing it just recorded.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit af5a7ec. Configure here.

if fetch.result == "structured":
read = [canonical(result.structured).decode()]
if any(marker in text for text in read):
raise ReaderError("too_large")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Truncation marker misses structured results

High Severity

For a structured fetch, the truncation check searches canonical JSON instead of result.texts and the decoded fields. A marker in a text block, or one whose quotes or spaces JSON encoding changes, is not found, so a cut document is returned instead of too_large.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit af5a7ec. Configure here.

This branch has not been deployed

No deployments
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