Skip to content

fix(mcp): bound list_notes so one namespace is not 3.2 MB of tool result (#698) - #713

Merged
sv merged 4 commits into
flop-labs:mainfrom
WIZARDspace:fix/mcp-list-notes-bound
Sep 6, 2026
Merged

sv merged 4 commits into
flop-labs:mainfrom
WIZARDspace:fix/mcp-list-notes-bound

Conversation

@WIZARDspace

Copy link
Copy Markdown
Contributor

Resolves #698, finding 1. Findings 2 and 3 are deliberately out of scope: #703 has finding 3, and the reporter notes finding 2 is "arguably a service-side decision about /kv/<ns> rather than an MCP one".

What

list_notes was the only listing tool with no bound. read_room takes since and limit; list_rooms takes limit. Measured on mcp.technocore.chat (0.11.1):

GET /kv/did   status=200 bytes=3277014

3.28 MB in one tool result, into a model's context. #510 reports did sitting at its 131,072 cap, so that is steady state rather than a spike.

Why the bound is not forwarded

/kv/<ns> takes no limit and ignores an unknown query parameter — note_list (app.py:1710-1719) reads only path_params, and store.list_notes (store.py:2543-2546) returns the whole sorted list. Forwarding one the way list_rooms does would advertise a parameter the service does not enforce, which is what the module docstring's input doctrine forbids ("Whatever is advertised is enforced, and nothing else").

So the bound is applied to the answer, and three things keep that honest:

  • Clamped the way the service clamps its own listing. app._rooms is min(_cursor(q.get("limit"), 50) or 1, MAX_LIMIT), so absent or negative is the default, 0 is 1, and anything above the ceiling is the ceiling. _clamp_notes mirrors that rather than inventing a second rule.
  • A truncated reply names the total it dropped, so the count is never silently wrong — the "hallucinated success" shape finding 2 is about.
  • Only /kv/-prefixed lines are keys. Once the read budget is nearly spent, budget_note (limit.py:396) appends a # line that is not a key; it must neither be counted as one nor dropped by a truncation it is not part of. Pinned by a direct test.

A listing that fits under the bound is returned byte-for-byte as before.

Judgment call worth flagging

The default of 50 changes what an existing caller gets back for a namespace over 50 keys. That is the bound the issue asks for, but it is a behaviour change — happy to leave the default unbounded and clamp only when limit is passed, if you would rather.

A server-side ?limit= on /kv/<ns> is the larger fix and is not attempted here: it is new public API surface, and core/app.py is at 1019 of its 1020-line cap.

Checks

  • uv run ruff check . — All checks passed
  • uv run ruff format --check . — 83 files already formatted
  • uv run ty check — All checks passed
  • env -u TECHNOCORE_SIGNING_KEY uv run pytest tests -q — 667 passed, 1 skipped
  • uv run python sz.py --caps — unchanged from main (sz.py:44-45 scopes the policy to src/*.py, so mcp/ adds no cap pressure)

Three new tests: the bound and what it reports, a listing under the bound left untouched, and the budget-line case above.

list_notes was the only listing tool with no bound. read_room takes since
and limit; list_rooms takes limit. Measured on mcp.technocore.chat (0.11.1),
GET /kv/did is 3,277,014 bytes -- one tool result, into a model's context.

The bound is not forwarded: /kv/<ns> takes no limit and ignores an unknown
query parameter, so advertising one would break the input doctrine's
"whatever is advertised is enforced, and nothing else". It is applied to the
answer instead, clamped the way the service clamps its own listing, and a
truncated reply names the total it dropped.

Refs flop-labs#698 (finding 1).
@WIZARDspace

Copy link
Copy Markdown
Contributor Author

Checked all three; none covers this, and one qualifies a sentence in the description above.

#703 — same issue, different finding, merges clean. It resolves #698 finding 3 (read_docs.page); this is finding 1 (list_notes unbounded). Same two files, so I test-merged rather than assumed: clean merge, no conflicts, and the combined suite is 71 passed. #703's new universal assertion — every published parameter carries a non-empty description — covers the limit parameter this PR adds and passes on it.

#568 — no overlap, but it qualifies one sentence here. It touches src/app.py, src/store.py, src/manifest.py and tests/http/; this touches mcp/ and tests/test_mcp.py. No shared file. The text lane is unchanged in shape, and ?keys=0 yields keys=[], which _clamp_notes passes through untouched, so the two compose.

The qualification: I wrote above that /kv/<ns> "ignores an unknown query parameter". That is true of main, but #568 adds ?keys=, honoured from manifest.KEYS and published in the contract. If #568 lands, a server-side ?limit= becomes the same pattern applied twice — advisory spelling, manifest-published, range in the description — and a natural follow-up. The wrapper-side clamp here is what callers of the current service need either way, and the two are compatible: the clamp is a no-op once the service bounds the listing itself.

#513 — src/patterns.md only. No code, no overlap.

Both #568 and #513 cite #510 because this PR cites it as well — as evidence for the 3.28 MB figure (did at its 131,072 cap), not as something it changes.

Copy link
Copy Markdown

_clamp_notes reorders the response framing on every truncated listing. The MCP module explicitly preserves the service's text/plain rendering because the leading untrusted-content banner is security-relevant, but the new code builds kept = keys[:n] + [all non-/kv/ lines]; that moves the banner (and any other prefix framing) from before the note keys to after them whenever len(keys) > n.

So the bounded result presents agent-written note keys before the warning that is supposed to frame them as untrusted, contrary to the module's own read-result invariant. The clamp can stay bounded without changing order by walking the original lines and dropping /kv/ lines only after the nth key; a regression should assert the banner remains before the first retained key on the truncation path.

@WIZARDspace

Copy link
Copy Markdown
Contributor Author

Checked this against the running service rather than the module docstring. The premise doesn't hold for this endpoint, but your criticism of the construction does, and the fix turns out to be free — so I'm taking it.

/kv/<ns> carries no banner. note_list (src/app.py:1746) hands respond (src/app.py:454) a body_text of key lines plus a trailing note, and respond returns text(body_text + note). BANNER is prepended in exactly two places, neither of them this one: note_read for /kv/<ns>/<key> (src/app.py:1503), and render for room bodies (src/app.py:436) — and respond reaches render only when body_text is None, which note_list never leaves it. The docstring line you're citing is true of read_room and read_note; a namespace listing is keys the server composed from filenames, and it goes out unbannered.

Probed rather than argued, since it's the load-bearing half — 60 notes seeded, real app in-process at 35e90cd:

/kv/many, full budget    BANNER present: False   non-key lines: []
/kv/many, spent budget   BANNER present: False   one non-key line, last of 61:
                                                 '# budget: 30 of 120 reads left this minute…'
/kv/one/only             '!! UNTRUSTED CONTENT — the lines below…'   ← where the banner lives

The only non-key line a listing can carry is budget_note (src/limit.py:396), which returns a leading-\n suffix and only once left * 4 <= per_min. Being trailing, it lands in the same place under keys[:n] + [non-keys] — I ran _clamp_notes over that real body and the ordering is byte-identical. Worth adding that session-level framing isn't at stake either: _instructions (mcp/src/technocore_mcp/server.py:124) tells the model at handshake to treat everything read through these tools as data. That is weaker than per-response framing, which is why the shape still matters.

Where you're right. The concatenation is order-destroying by construction and order-preserving only by accident of there being no prefix to move. A prefix added to note_list later would break this silently, and nothing in the file would object.

One correction to the regression you asked for, because I wrote it and it doesn't discriminate. Asserting the budget line's position passes under both implementations — a trailing line lands last either way:

OLD  trailing budget after last key: True   leading framing before first key: False
NEW  trailing budget after last key: True   leading framing before first key: True

The only assertion separating them concerns a prefix the endpoint does not emit. So the new case is labelled in the test as a guard on future framing, not a repro of a live defect — I'd rather it say that than imply I fixed an exploitable ordering bug.

The change, which is your walk at net zero code lines:

keys = [i for i, line in enumerate(lines) if line.startswith("/kv/")]
...
kept = [ln for i, ln in enumerate(lines) if i < keys[n] or not ln.startswith("/kv/")]

keys holds key positions, and the comprehension drops /kv/ lines only after the nth, keeping every non-key line where the service put it. len(keys) still feeds the count message. 71/71 in tests/test_mcp.py, 667 passed / 1 skipped for the full suite, ruff check and ruff format --diff clean. sz.py measures CORE_FILES and EXTRA_FILES only (sz.py:44) and sz-baseline.json tracks those six labels; the MCP module is in neither, so no size gate is touched. Going up on fix/mcp-list-notes-bound shortly.

Copy link
Copy Markdown

Confirmed. My previous comment overstated the live impact: /kv/<ns> listings do not currently carry the per-response untrusted-content banner, so the existing truncation path is not moving that security banner behind note keys today. The concrete current issue is therefore not an active framing violation; it is that _clamp_notes destroys relative ordering by construction, which would make any future prefix framing fragile. The order-preserving walk you described is the right narrow hardening, and I withdraw the claim that the current endpoint is already violating its banner invariant.

_clamp_notes built its result as `keys[:n] + [non-key lines]`, which re-joins
every non-key line after the retained keys. /kv/<ns> emits only a trailing
budget note (src/limit.py:396), so nothing moves today — verified against the
real app, where a truncated listing is byte-identical either way. But the
construction is order-destroying by shape, and a prefix added to note_list
later would silently land after the keys it frames.

Walk the lines instead and drop /kv/ lines only after the nth key. `keys` now
holds key positions; len(keys) still feeds the count message. Net zero code
lines.

The regression asserts position rather than presence, because the two come
apart: a presence check passes under both forms, and so does a position check
on the trailing budget line. Only a leading-framing case discriminates, so that
is what the test pins — explicitly a guard on framing /kv/<ns> does not emit
yet, not a repro of a live defect.
@WIZARDspace

Copy link
Copy Markdown
Contributor Author

Landed in c1a8aae, and thanks for checking it rather than defending the first read.

The walk is as described — keys holds key positions and the comprehension drops /kv/ lines only after the nth, so non-key lines stay where the service put them. The regression pins the leading-framing case, since that is the only one that separates the two forms. Green on c1a8aae: lint + tests + image, mcp worker bundles, openapi contract, protected-files.

@sv
sv merged commit 9861d01 into flop-labs:main Sep 6, 2026
6 checks passed
@sv sv mentioned this pull request Sep 7, 2026
5 tasks done
sv added a commit that referenced this pull request Sep 7, 2026
Fold [Unreleased] into a dated section, bump the version the service, the
MCP wrapper and the worker share, and re-ratchet sz-baseline.json: app.py
has been one line past the recorded count since #753, which is why main
has been red. MINOR rather than PATCH because #713 added a `limit`
parameter to the wrapper's list_notes tool and changed what a namespace
over 50 keys returns.
sv added a commit that referenced this pull request Sep 7, 2026
Fold [Unreleased] into a dated section, bump the version the service, the
MCP wrapper and the worker share, and re-ratchet sz-baseline.json: app.py
has been one line past the recorded count since #753, which is why main
has been red. MINOR rather than PATCH because #713 added a `limit`
parameter to the wrapper's list_notes tool and changed what a namespace
over 50 keys returns.
sv added a commit that referenced this pull request Sep 7, 2026
## What

Cuts **0.13.0**: folds `[Unreleased]` into a dated section, bumps the
version the service, the MCP wrapper and the worker share (the same
eight files as #723), and re-ratchets `sz-baseline.json`. Nothing a
caller sees changes until the tag.

## Why

Eleven commits since v0.12.1: fixes on the signed note lane, `/stats`,
`/humans` passkeys, the MCP wrapper and `_b58decode`; the POST upload
deadline and the slower sweep from #731; the shareable read footer from
#730; and the Technocore branding.

**MINOR rather than PATCH** because #713 gave the wrapper's `list_notes`
a `limit` parameter and changed what a namespace over 50 keys returns —
additive surface under the changelog's own rule. A reviewer could call
that a patch; the version files are one substitution away.

**The baseline refresh rides along.** `main` has failed `sz.py --check`
since #753 put `app.py` at 1020 code lines against a recorded 1019. Only
the measured `files` block moves; every cap is untouched. The
alternative was a separate chore PR as for 0.12.1; folding it in means
the tagged commit is green.

After merge, by hand and in this order: tag `v0.13.0` and `mcp-v0.13.0`
(lightweight, pushed to github.com directly), which builds the image and
publishes the wrapper; pull the image on the box; then `edge/deploy.sh`,
after the origin is up, so the snapshot carries the new `/humans` along
with the favicon.

## Checks

- [x] `uv run coverage run -m pytest tests -q && uv run coverage report`
— 764 passed, 1 skipped
- [x] `uv run ruff check . && uv run ruff format --check .` and `uv run
ty check`
- [x] `uv lock --check`, `uv run sz.py --check`, and both gates
`release.yml` runs before building
- [x] Docs that would now be wrong are updated: `CHANGELOG.md` is the
change; the manual and `/skill.md` need nothing
- [x] New surface on a world-writable service: nothing new
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.

mcp: three tool-surface fixes (list_notes bounds, empty success, read_docs description)

3 participants