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
51 changes: 42 additions & 9 deletions docs/architecture/source-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ replace.
([the host backend](mcp-source-worker-boundary.md#the-host-backend)).
- `source_worker/qualification/record_mapped.py`: the recorder, and `Replay`, which
answers a reader from a recording.
- `source_worker/qualification/stand_in_channel.py` (`Channel`, `Stdio`): a stand-in for
an account host's tool channel over a server started as a local process.
- `source_worker/mappings/wiki.json`: the reference mapping, for an open-source wiki's
protocol server.

## Invariants

Expand Down Expand Up @@ -93,13 +97,24 @@ sorted keys, no space after `:` or `,`, and each string JSON-escaped. A flag is
| `items_path` | The list of items in the result; empty when the result is the list |
| `id_path` | The id inside one item |
| `revision_path`, `modified_path`, `title_path`, `link_path` | Optional paths inside one item |
| `next_cursor_path` | The cursor of the next page; absent, `null` or empty on the last |
| `next_cursor_path` | The cursor of the next page; no page follows without one |
| `complete` | Whether a listing read to its end names every document |
| `changed_since` | Whether the tool can list only what changed since a time |

A result that is itself the list has no place for a cursor, so `load` refuses
`next_cursor_path` beside an empty `items_path`.

An optional path of an item (`revision_path`, `modified_path`, `title_path`,
`link_path`) reads as empty when its last key is absent or `null`. A member above the
last key that is absent, `null` or not an object refuses with `protocol`, and so does a
value that is not a string.

`next_cursor_path` is optional along its whole length. A member that is absent or
`null` at any depth means that no page follows, and so does an empty cursor: a server
may leave out the whole member that holds its cursor on a listing's last page. A member
that is present and is not an object where the path goes on, and a cursor that is not a
string, refuse with `protocol`.

A path is a list of object keys. `not_found` and `denied` are matchers: `is_error` and
`text_prefix`. A result matches when its error flag equals `is_error` and its one text
block starts with `text_prefix`. `load` refuses a mapping whose two matchers could match
Expand Down Expand Up @@ -346,14 +361,32 @@ SHA-256 of its text.

Before anything is written, every upstream id, every cursor and every name given with
`--name` is replaced by a neutral value such as `doc-0001`, the same wherever it recurs.
A UUID is found in either spelling; another id is replaced as written. The recorder
stops when a call still holds one of them. Tool definitions are written as advertised,
without their descriptions, because their digest is what a mapping pins. Run
`make format` on the written files before committing them.

`source_worker/tests/test_mapping_proof.py` replays the recording under
`source_worker/tests/fixtures/mapped/example/`, which is built by hand for a made-up
server, through `Replay`, which refuses a call the recording does not hold.
A UUID is found in either spelling. Any other value is replaced as written and as a
link spells it: percent-encoded, or with `_` for a space. A number is never replaced, so
a server that names its rows by number is recorded from a workspace made for the
recording. The recorder stops when a call still holds one of the values. Tool
definitions are written as advertised, parameter descriptions included and without the
tool's own description, because their digest is what a mapping pins. Run `make format`
on the written files before committing them.

`source_worker/tests/test_mapping_proof.py` replays two recordings through `Replay`,
which refuses a call the recording does not hold:

- `source_worker/tests/fixtures/mapped/example/` is built by hand for a made-up server.
- `source_worker/tests/fixtures/mapped/wiki/` holds what an open-source wiki's protocol
server answered for a wiki of made-up pages. `source_worker/mappings/wiki.json`, the
reference mapping, reads it. The directory's `README.md` says how to repeat the
recording.

`source_worker/qualification/stand_in_channel.py` is the `ToolCaller` of the second
recording. `Channel` stands between the reader and a server as an account host's
channel does: it lists the server's tools as advertised, and it raises `too_large` for
a result over its cap, `reconnect_required` when the account needs a sign-in,
`server_off` when the server is not enabled and `tool_not_allowed` for a tool the
host's policy refuses. `Stdio` starts the server as a local process. The proof test
puts `Channel` in each of those states over the recording, and the reader raises the
channel's code unchanged. The package never imports the module.

`source_worker/tests/test_reader_contract.py` holds the rules every reader keeps.

## Related
Expand Down
7 changes: 7 additions & 0 deletions docs/guides/document-worker-beside-a-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,13 @@ source whose `profile_digest` is the digest of a file there, so a mapping nobody
there reads nothing. The directory holds at most 64 mappings, and a file that is not a
mapping stops the run with a `ValueError`.

`source_worker/mappings/wiki.json` is the worked example: the reference mapping for an
open-source wiki's protocol server, which a test reads on results recorded from that
server. A deployment proves its own channel with the same
[recorder](../architecture/source-mapping.md#recording-fixtures): its operators run it
through the host's channel when the server or the host is upgraded, and replay the
recording before they approve the mapping's digest.

## 2. Assign the source

A namespace administrator, not the agent, assigns the source to the agent's subject with
Expand Down
15 changes: 14 additions & 1 deletion source_worker/loom_source_worker/readers/mcp_mapped.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@ def _optional(value: Any, path: tuple[str, ...] | None) -> str:
return found


def _cursor(value: Any, path: tuple[str, ...] | None) -> str:
"""The next page's cursor: as `_optional`, and empty too when a member above the
last key is absent or null. A server may leave out the whole member that holds
its cursor on a listing's last page."""
for key in (path or ())[:-1]:
if not isinstance(value, dict):
raise ReaderError("protocol")
value = value.get(key)
if value is None:
return ""
return _optional(value, path and path[-1:])


def _size(text: str) -> int:
"""The text's bytes; a string that is not UTF-8 text is refused."""
try:
Expand Down Expand Up @@ -297,7 +310,7 @@ async def list_since(
link=self._link(_optional(item, listing.link_path)),
)
)
following = _optional(value, listing.next_cursor_path) or None
following = _cursor(value, listing.next_cursor_path) or None
if following is not None and following == cursor:
raise ReaderError("protocol")
self._listed.update((item.id, item) for item in items)
Expand Down
39 changes: 39 additions & 0 deletions source_worker/mappings/wiki.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"version": 1,
"link_origins": ["https://wiki.example.test"],
"limits": { "max_result_bytes": 400000, "max_text_bytes": 100000, "max_pages_per_turn": 8 },
"fetch": {
"tool": "get-page",
"definition_sha256": "9e3cca2f72bb5b02e01ab1b1c1d2298bb8bea5ce1065a11b1518f2f0687a0390",
"arguments": { "title": { "$value": "document_id" }, "metadata": true },
"result": "structured",
"id_path": ["title"],
"title_path": ["title"],
"text_path": ["source"],
"link_path": ["url"],
"revision_path": ["latestRevisionTimestamp"],
"truncated_marker": "\"truncation\":{"
},
"list": {
"tool": "get-recent-changes",
"definition_sha256": "2bc201822fb95157d4785ef7de5735e11965d6c54b2c059a734e5202c920ba97",
"arguments": {
"user": { "$value": "scope" },
"since": { "$value": "since" },
"continue": { "$value": "cursor" }
},
"result": "structured",
"items_path": ["changes"],
"id_path": ["title"],
"revision_path": ["timestamp"],
"modified_path": ["timestamp"],
"title_path": ["title"],
"next_cursor_path": ["truncation", "continueWith", "value"],
"complete": false,
"changed_since": true
},
"removed": {
"mode": "fetch_not_found",
"not_found": { "is_error": true, "text_prefix": "{\"category\":\"not_found\"" }
}
}
23 changes: 17 additions & 6 deletions source_worker/qualification/record_mapped.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@

Every upstream id, every cursor and every given name is replaced by a neutral value,
the same wherever it recurs, so the second page is still asked for by the first page's
cursor. A UUID is found in either spelling; any other id is replaced as written. Tool
definitions are not rewritten: their digest is what a mapping pins.
cursor. A UUID is found in either spelling; any other value is replaced as written and
as a link spells it. A number is never replaced. Tool definitions are not rewritten:
their digest is what a mapping pins.
"""

from __future__ import annotations
Expand All @@ -33,6 +34,7 @@
from collections.abc import Sequence
from pathlib import Path
from typing import Any
from urllib.parse import quote

from loom_source_worker.mapping import PLACEHOLDER, Mapping, load
from loom_source_worker.readers.mcp_mapped import MappedReader
Expand Down Expand Up @@ -63,6 +65,12 @@ def upstream_ids(text: str) -> list[str]:
return [match.group(0) for match in _UUID.finditer(text)]


def spellings(value: str) -> list[str]:
"""A value as written and as a link spells it: percent-encoded, or with `_` for a
space."""
return list(dict.fromkeys((value, quote(value.replace(" ", "_")), quote(value))))


def placed(template: Any, arguments: Any) -> dict[str, Any]:
"""The value a call carries at each placeholder of its template, outside lists."""
if not isinstance(template, dict):
Expand All @@ -76,7 +84,8 @@ def placed(template: Any, arguments: Any) -> dict[str, Any]:
return found


def _definition(entry: dict[str, Any]) -> ToolDefinition:
def definition(entry: dict[str, Any]) -> ToolDefinition:
"""A tool as one entry of `tools/list` advertises it."""
hint = entry.get("annotations", {}).get("readOnlyHint")
return ToolDefinition(
entry["name"], entry["inputSchema"], entry.get("outputSchema"), hint is True
Expand Down Expand Up @@ -104,7 +113,7 @@ class Replay:
"""A `ToolCaller` that answers from a recording and refuses every other call."""

def __init__(self, directory: Path) -> None:
self.tools = [_definition(entry) for entry in _read(directory / "tools.json")]
self.tools = [definition(entry) for entry in _read(directory / "tools.json")]
self.recorded: dict[str, Any] = {
name: _read(directory / f"{name}.json")
for name in CALLS
Expand Down Expand Up @@ -180,7 +189,8 @@ def scrub(self, value: Any) -> Any:
return value
value = _UUID.sub(self._uuid, value)
for known in sorted(self._values, key=len, reverse=True):
value = value.replace(known, self._values[known])
for spelling in spellings(known):
value = value.replace(spelling, self._values[known])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Scrub splits percent-encoded values

Medium Severity

scrub applies spellings with the raw value first. quote encodes % as %25, so that raw value is a prefix of its percent-encoded spelling. The first replace tears the encoded form apart, the later spelling no longer matches, and the hold check looks only for the original spellings, so the recording keeps a broken link.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3448a90. Configure here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Underscore spellings alias other ids

Medium Severity

scrub still orders values by raw length, then replaces every spellings form, including space turned into _. A link spelling that is exactly some other upstream value is replaced with the first value's neutral id, so two different ids become one token in the recording.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3448a90. Configure here.

return value


Expand Down Expand Up @@ -278,10 +288,11 @@ async def record(

scrubbed = {name: neutral.scrub(call) for name, call in files.items()}
upstream = [scope, empty_scope, *fetches.values(), *names]
held = [spelling for value in upstream for spelling in spellings(value)]
for name, call in scrubbed.items():
text = json.dumps(call, ensure_ascii=False)
# Nothing is written while a call still holds what was to be replaced.
if upstream_ids(text) or any(value in text for value in upstream):
if upstream_ids(text) or any(spelling in text for spelling in held):
raise SystemExit(f"{name} still holds an upstream id or name")
_write(out / "tools.json", [_entry(tool) for tool in tools])
for name, call in scrubbed.items():
Expand Down
137 changes: 137 additions & 0 deletions source_worker/qualification/stand_in_channel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
"""A stand-in for an account host's tool channel, to record a protocol server on one machine.

Beside an account host the recorder's `ToolCaller` is the host's channel. `Channel`
stands in for it over a server that needs no credential, started as a local process:

RECORD_SERVER_COMMAND='["node", "server.js"]' \
python source_worker/qualification/record_mapped.py --caller stand_in_channel:local ...

It lists the server's tools as advertised, refuses a result over its size cap, and
refuses as a channel does when the account needs a sign-in, the server is not enabled
or a tool is not allowed. Each refusal is a `ReaderError` with the reader's code and no
text of any host. The package never imports this module.
"""

from __future__ import annotations

import atexit
import json
import os
import subprocess
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any

from loom_source_worker.mapping import canonical
from loom_source_worker.sync_types import ReaderError, ToolCaller, ToolDefinition, ToolResult
from record_mapped import definition

# The stand-in's cap on one result: its text blocks and its structured content.
MAX_RESULT_BYTES = 1_000_000


class Stdio:
"""`ToolCaller` over a protocol server started as a local process, which reads and
writes one JSON-RPC message a line. A call waits for its answer on the pipe, so no
deadline ends it. The process ends with the one that started it."""

def __init__(self, command: Sequence[str]) -> None:
self._command = list(command)
self._process: subprocess.Popen[bytes] | None = None
self._sent = 0

def _write(self, message: dict[str, Any]) -> None:
assert self._process is not None and self._process.stdin is not None
self._process.stdin.write(json.dumps(message).encode() + b"\n")
self._process.stdin.flush()

def _answer(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
if self._process is None:
self._process = subprocess.Popen(
self._command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
)
atexit.register(self._process.terminate)
client = {"name": "record-mapped", "version": "0"}
hello = {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": client}
self._answer("initialize", hello)
self._write({"jsonrpc": "2.0", "method": "notifications/initialized"})
assert self._process.stdout is not None
self._sent += 1
self._write({"jsonrpc": "2.0", "id": self._sent, "method": method, "params": params})
while line := self._process.stdout.readline():
try:
message = json.loads(line)
except ValueError:
continue
if isinstance(message, dict) and message.get("id") == self._sent:
result = message.get("result")
if not isinstance(result, dict):
# A JSON-RPC error is no tool result.
raise ReaderError("protocol")
return result
raise ReaderError("upstream_unavailable")

async def list_tools(self) -> list[ToolDefinition]:
tools: list[ToolDefinition] = []
params: dict[str, Any] = {}
while True:
page = self._answer("tools/list", params)
tools += map(definition, page["tools"])
if not page.get("nextCursor"):
return tools
params = {"cursor": page["nextCursor"]}

async def call_tool(
self, name: str, arguments: dict[str, Any], *, deadline: float
) -> ToolResult:
result = self._answer("tools/call", {"name": name, "arguments": arguments})
texts = [block["text"] for block in result.get("content", []) if block["type"] == "text"]
return ToolResult(result.get("structuredContent"), texts, result.get("isError") is True)


@dataclass
class Channel:
"""`ToolCaller` between a reader and `server`, as an account host's channel stands
between them. `signed_in`: the account has a credential the channel can add.
`enabled`: the server is turned on for the agent. `refused_tools`: the tools the
host's policy does not allow; they are still listed."""

server: ToolCaller
max_result_bytes: int = MAX_RESULT_BYTES
signed_in: bool = True
enabled: bool = True
refused_tools: frozenset[str] = frozenset()

def _admit(self) -> None:
if not self.enabled:
raise ReaderError("server_off")
if not self.signed_in:
raise ReaderError("reconnect_required")

async def list_tools(self) -> list[ToolDefinition]:
self._admit()
return await self.server.list_tools()

async def call_tool(
self, name: str, arguments: dict[str, Any], *, deadline: float
) -> ToolResult:
self._admit()
if name in self.refused_tools:
raise ReaderError("tool_not_allowed")
result = await self.server.call_tool(name, arguments, deadline=deadline)
size = sum(len(text.encode()) for text in result.texts)
if result.structured is not None:
size += len(canonical(result.structured))
if size > self.max_result_bytes:
# The channel carries no part of a result over its cap.
raise ReaderError("too_large")
return result


def local() -> Channel:
"""The channel over the server whose command line `RECORD_SERVER_COMMAND` holds,
as a JSON list. The server reads its own settings from the environment."""
return Channel(Stdio(json.loads(os.environ["RECORD_SERVER_COMMAND"])))
Loading
Loading