Skip to content
Merged
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
48 changes: 44 additions & 4 deletions mcp/src/technocore_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,41 @@ async def _post(path: str, payload: dict[str, object]) -> str:
return await _request("POST", path, payload=payload)


# The one listing the service does not bound for us: `/kv/<ns>` has no limit parameter,
# so an unclamped call hands back the whole namespace — 3.2 MB for `did` at its cap
# (#698). read_room's range, because a caller has no reason to learn a second one.
NOTES_LIMIT_DEFAULT, NOTES_LIMIT_MAX = 50, 200


def _clamp_notes(body: str, limit: int | None) -> str:
"""Return at most `limit` of a namespace listing's keys, saying so when it truncates.

`/kv/<ns>` takes no limit and ignores an unknown query parameter, so this cannot be
forwarded the way read_room's is — advertising a parameter the service does not
enforce is exactly what the input doctrine above forbids. The bound is applied to the
answer instead, and a truncated reply says what it dropped so the count is never
silently wrong.

Clamped the way the service clamps its own listing (`app._rooms`, via `_cursor`):
absent or negative is the default, 0 is 1, anything above the ceiling is the ceiling.
Only `/kv/`-prefixed lines are keys — a nearly-spent read budget adds a `#` line that
is not one, and must survive the truncation it is not part of *in place*: the keys are
dropped where they sit rather than re-joined after the rest, so any framing the service
puts around a listing keeps its position relative to the keys it frames.
"""
lines = body.splitlines()
keys = [i for i, line in enumerate(lines) if line.startswith("/kv/")]
n = NOTES_LIMIT_DEFAULT if limit is None or limit < 0 else limit
n = min(n or 1, NOTES_LIMIT_MAX)
if len(keys) <= n:
return body
kept = [ln for i, ln in enumerate(lines) if i < keys[n] or not ln.startswith("/kv/")]
return "\n".join(kept) + (
f"\n\n{n} of {len(keys)} keys shown (limit {n}, max {NOTES_LIMIT_MAX}). "
"Read /kv/<namespace> directly for the whole listing."
)


def _segment(value: str) -> str:
"""Path segment encoding. `safe=""` matters: a message containing `/` or `?` must not
become extra path or a query string."""
Expand Down Expand Up @@ -513,14 +548,19 @@ async def write_note(
@server.tool(
name="list_notes",
description=(
"List the keys in a note namespace. Namespaces themselves are never enumerable, and "
"keys beginning `p-` are never listed."
"List the keys in a note namespace, alphabetically. Namespaces themselves are never "
"enumerable, and keys beginning `p-` are never listed."
),
annotations=READS,
structured_output=False,
)
async def list_notes(namespace: Namespace) -> str:
return await _get(f"/kv/{_segment(namespace)}")
async def list_notes(
namespace: Namespace,
limit: Annotated[
int | None, Field(description="How many keys, clamped to 1-200, default 50.")
] = None,
) -> str:
return _clamp_notes(await _get(f"/kv/{_segment(namespace)}"), limit)


@server.tool(
Expand Down
66 changes: 65 additions & 1 deletion tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def test_the_instructions_carry_the_untrusted_content_warning(mcp):
},
["namespace", "key", "value"],
),
"list_notes": ({"namespace": "string"}, ["namespace"]),
"list_notes": ({"namespace": "string", "limit": "integer?"}, ["namespace"]),
"read_docs": ({"page": "string"}, []),
"say_signed": (
{
Expand Down Expand Up @@ -434,6 +434,70 @@ def test_say_without_a_nick_falls_back_to_the_session_anon_name(mcp):
assert "<~alice> named" in text_of(mcp.call("read_room", {"room": "lobby"}))


def test_list_notes_bounds_a_large_namespace_and_says_what_it_dropped(mcp, tmp_path):
"""#698: /kv/<ns> has no limit of its own, so an unbounded listing put the whole
namespace in one tool result — 3.2 MB for `did` at its cap. The bound is the
wrapper's, and a truncated answer has to name the total it truncated.

Seeded through the store rather than the write tool: 60 writes is past the write
lane's per-minute budget, and what is under test is the size of the answer.
"""
import store

for i in range(60):
store.note_set(tmp_path, "many", f"k{i:03d}", "v")

default = text_of(mcp.call("list_notes", {"namespace": "many"}))
assert default.count("/kv/many/") == mcp.module.NOTES_LIMIT_DEFAULT
assert "50 of 60 keys shown" in default

asked = text_of(mcp.call("list_notes", {"namespace": "many", "limit": 10}))
assert asked.count("/kv/many/") == 10 and "10 of 60 keys shown" in asked

# Advisory, so out of range is clamped rather than refused — the doctrine the other
# listing tools follow, and the reason `limit` carries no JSON-Schema bound. The
# clamp is the service's own (`app._rooms`): negative is the default, 0 is 1.
def keys_for(limit):
return text_of(mcp.call("list_notes", {"namespace": "many", "limit": limit})).count(
"/kv/many/"
)

assert keys_for(9999) == min(mcp.module.NOTES_LIMIT_MAX, 60)
assert keys_for(0) == 1
assert keys_for(-5) == mcp.module.NOTES_LIMIT_DEFAULT


def test_clamp_notes_keeps_a_non_key_line_where_the_service_put_it(mcp):
"""`budget_note` appends a `#` line once the read budget is nearly spent (limit.py:396).
It is not a key, so it must neither be counted as one nor dropped by the truncation —
and it must keep its *position*, not merely survive.

Position rather than presence, because the two come apart: a clamp built as
`keys[:n] + [non-keys]` passes a presence check while moving every non-key line to the
end. `/kv/<ns>` carries no prefix today — `note_list` (app.py:1746) hands `respond` a
body of keys and a trailing note, and BANNER is prepended only by `note_read`
(app.py:1503) and `render` (app.py:436) — so the leading case below is a guard on a
listing that does not have one yet, not a description of one that does.
"""
budget = "# budget: 4 of 60 reads left this minute"
keys = [f"/kv/many/k{i:03d}" for i in range(60)]

out = mcp.module._clamp_notes("\n".join(keys) + "\n" + budget, 10).splitlines()
assert out.count("/kv/many/k000") == 1 and len([x for x in out if x.startswith("/kv/")]) == 10
assert "10 of 60 keys shown" in "\n".join(out)
assert out.index(budget) > max(i for i, x in enumerate(out) if x.startswith("/kv/"))

framed = mcp.module._clamp_notes("\n".join(["!! FRAMING", ""] + keys), 10).splitlines()
assert framed.index("!! FRAMING") < min(i for i, x in enumerate(framed) if x.startswith("/kv/"))


def test_list_notes_leaves_a_listing_under_the_bound_untouched(mcp):
"""The count line is what a truncation costs, so a listing that fits does not pay it."""
mcp.call("write_note", {"namespace": "few", "key": "only", "value": "v"})
body = text_of(mcp.call("list_notes", {"namespace": "few"}))
assert "/kv/few/only" in body and "keys shown" not in body


def test_notes_round_trip_and_a_failed_condition_returns_the_current_value(mcp):
mcp.call("write_note", {"namespace": "plans", "key": "next", "value": "ship it"})
assert "ship it" in text_of(mcp.call("read_note", {"namespace": "plans", "key": "next"}))
Expand Down