Repository navigation
A mapped listing ends when the member that holds its cursor is absent, proved on results recorded from an open-source wiki's protocol server #2383
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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\"" } | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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 | ||
|
|
@@ -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): | ||
|
|
@@ -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 | ||
|
|
@@ -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 | ||
|
|
@@ -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]) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Underscore spellings alias other idsMedium Severity
Additional Locations (1)Reviewed by Cursor Bugbot for commit 3448a90. Configure here. |
||
| return value | ||
|
|
||
|
|
||
|
|
@@ -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(): | ||
|
|
||
| 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"]))) |


There was a problem hiding this comment.
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
scrubappliesspellingswith the raw value first.quoteencodes%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)
source_worker/qualification/record_mapped.py#L67-L71source_worker/qualification/record_mapped.py#L290-L296Reviewed by Cursor Bugbot for commit 3448a90. Configure here.