Skip to content

feat(mcp): bound agent response payloads - #2790

Merged
Sinity merged 10 commits into
masterfrom
feature/fanout/mcp-ergonomics
Jul 13, 2026
Merged

Sinity merged 10 commits into
masterfrom
feature/fanout/mcp-ergonomics

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026 •

Copy link
Copy Markdown
Owner

Summary

Bounds MCP responses for agent use, makes search affordances opt-in, adds message body caps/excerpts, turns get_session_summary into a bounded orientation payload, and completes the response-envelope/pagination ergonomics with actionable query errors, distinct list rows, and zero-hit diagnostics.

Problem

Live MCP searches and message reads could return response bodies far beyond an agent context budget. Search carried the full affordance catalog on every response, session summaries contained metadata only, invalid filters gave agents no recovery set, list search could repeat a session for each matching block, and an AND-style search miss could not explain its terms.

Solution

  • Add a shared 25 KB serializer budget that replaces oversized payloads with metadata plus a replayable narrower MCP call descriptor.
  • Make search(include_affordances=true) the explicit opt-in for its affordance catalog.
  • Add max_chars_per_message and head/tail excerpt handling to get_messages.
  • Add counts, phase count, top tools, and first/last authored-user excerpts to get_session_summary.
  • Map QuerySpecError into an invalid_query envelope with field, tool, and valid-values metadata.
  • Coalesce block-level list_sessions results into distinct session rows with match_count, using the existing distinct-session count and only the raw hits needed for the requested page.
  • Include filtered per-term counts only when a multi-term search has zero total matches; exhausted result pages remain ordinary empty pages.

Verification

  • nix develop --command devtools test tests/unit/mcp/test_tool_contracts.py -k 'multi_term or coalesces or invalid_sort' — 3 passed.
  • nix develop --command devtools test tests/unit/mcp/test_query_tool_schema_derivation.py tests/unit/mcp/test_tool_contracts.py -k 'supported_request_fields or stops_after_requested or exhausted_page or multi_term or coalesces or invalid_sort' — 6 passed.
  • nix develop --command devtools test tests/unit/mcp -k 'envelope or pagination or summary' — 178 passed, 473 deselected (1:55).
  • Each pushed commit passed the pre-push quick gate: format, lint, mypy, render, topology, layering, schema roundtrip, manifests, and MCP test-infrastructure checks.

Acceptance status

Ref polylogue-rsad.

  • Satisfied: opt-in affordances; shared response-budget envelopes across the covered read and mutable-list paths; per-message cap/match-aware excerpt behavior; content-bearing session summaries; direct and search-DSL invalid-value envelopes; distinct session-list rows with match_count; and zero-hit per-term diagnostics.
  • Remaining polylogue-rsad scope: query_units must use the shared valid-values error shape and preserve replay arguments; archive_search_sessions must preserve replay arguments. These are documented in adversarial iteration 5; the bead remains open.
  • Excluded: recall/context tool changes remain owned by the hermes-wedge lane.

Test evidence

The tests invoke registered MCP handlers against real seeded archive rows, not test-only validators:

  • Removing the QuerySpecError mapper or its valid-values mapping breaks the invalid-sort test.
  • Removing the archive search-result coalescing or match_count projection breaks the repeated-block session-list test.
  • Removing the distinct-page bound makes the coalescing test fetch an unnecessary second raw FTS batch.
  • Emitting diagnostics based on an empty page rather than zero total breaks the exhausted-page test.
  • Existing lane tests similarly exercise the shared budget serializer/context, affordance opt-in pass-through, message projection cap, and summary enrichment.

Sinity added 2 commits July 12, 2026 23:00
Problem: MCP search and message reads could flood an agent context with\nrepeated affordance metadata or oversized message bodies, while session\nsummaries exposed only identifiers and counts.\n\nWhat changed: add a shared 25 KB response budget with metadata-only\nreplay descriptors; make search affordances opt-in; add per-message\ncharacter caps and excerpts; and enrich session summaries with bounded\ncontent orientation.\n\nCompatibility: normal responses preserve their existing typed envelope;\nonly oversized responses use the new bounded envelope.\n\nCo-Authored-By: Claude <[email protected]>
Correct the response-envelope helper annotations so the pre-push\nstrict mypy gate accepts the affordance and continuation contracts.\n\nCo-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 31 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 29103ed4-62c2-4c64-9165-3e75d9764cb3

📥 Commits

Reviewing files that changed from the base of the PR and between 901825e and 8635af3.

📒 Files selected for processing (11)
  • polylogue/mcp/archive_support.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/query_contracts.py
  • polylogue/mcp/server.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/mcp/server_resources.py
  • polylogue/mcp/server_support.py
  • polylogue/mcp/server_tools.py
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/mcp/test_query_tool_schema_derivation.py
  • tests/unit/mcp/test_tool_contracts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fanout/mcp-ergonomics

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Sinity added 2 commits July 12, 2026 23:16
Problem: malformed MCP query values previously surfaced without a
machine-readable recovery set.

What changed: map QuerySpec errors to a stable invalid_query envelope
with field, tool, and valid_values metadata.
Problem: block-level search duplicated sessions in MCP list responses,
and empty multi-term searches gave no indication of which term missed.

What changed: list sessions now emits one row per session with an
exact match_count; empty multi-term search responses include filtered
per-term counts. Tests invoke registered MCP tools against archive data.
@Sinity
Sinity marked this pull request as ready for review July 12, 2026 21:27

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 780782be38

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/mcp/query_contracts.py Resolved
Comment thread polylogue/mcp/archive_support.py Resolved
Comment thread polylogue/mcp/archive_support.py Resolved
Sinity added 2 commits July 12, 2026 23:50
Problem: query-tool schema drifted for a search-only option, exhausted
search pages were misdiagnosed as misses, and text list pagination scanned
the full raw result set.

What changed: document the schema exception, gate diagnostics on total
zero, and stop FTS coalescing once the requested distinct page is known.
Focused MCP tests cover each production route.
Problem: oversized non-query session reads lacked replay arguments,
bounded list coalescing could overstate match cardinality, and deeply
nested fallback metadata could exceed the response budget.

What changed: safe calls now carry session replay identifiers, match
counts disclose exactness, fallback metadata has a depth bound, and the
affordance catalog is available as an MCP resource. Focused tests cover
each route.
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 1

Findings:

  • Real gap: oversized session-scoped non-query reads could fall back without replay arguments.
  • Real gap: a bounded lexical coalescing page could report a partial raw-match count as if it were exact.
  • Real gap: recursively nested fallback metadata could itself exceed the 25 KB budget.
  • Borderline: the ratified affordance shape asked for a one-time MCP resource; the existing tool met the original AC but not that exact shape.
  • Borderline: this implementation fixes the shared response budget at 25 KB. The bead’s “configured budget” wording is interpreted here as that shared server policy; adding a user-configurable setting would require a config-surface decision outside this lane.

Fixes in 0a42f249b:

  • Safe-call wrappers now provide session-scoped replay identifiers; an oversized archive_get_session response returns a resolvable continuation.
  • match_count_is_exact distinguishes fully scanned counts from page-bounded observed counts.
  • Budget metadata compaction now has a depth limit, preserving the hard response bound for nested models.
  • Added polylogue://capabilities/action-affordances, reusing the existing catalog without reintroducing search boilerplate.

What survived scrutiny:

  • Per-message cap/excerpt behavior, sort valid-values errors, zero-total diagnostics, normal distinct-page traversal, and the 25 KB replay envelope all remain covered by production-route tests.
  • Focused verification: 5 passed for the iteration-specific regressions; pre-push quick gate passed.
  • No Bead state changed; Ref polylogue-rsad.

Problem: archive-session, correction-list, and message-resource budget
fallbacks could either repeat the oversized request or offer no callable
next action.

What changed: archive sessions and message resources replay through capped
message reads; corrections now use the shared serializer with pagination
and per-item caps. Tests invoke every advertised continuation.
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 2

Findings:

  • Real gap: the archive_get_session continuation repeated the same unbounded call.
  • Real gap: list_corrections bypassed the shared serializer and had no bounded retrieval path.
  • Real gap: the messages resource had no callable continuation when its fixed resource page exceeded the budget.
  • Borderline retained: 25 KB is a fixed shared server policy in this implementation, not an operator-configurable setting.

Fixes in d55ad14fa:

  • archive_get_session now falls back to capped get_messages.
  • list_corrections now uses the shared serializer, exposes limit/offset, and caps correction text on fallback replay.
  • polylogue://messages/{conv_id} now falls back to capped get_messages.

What survived scrutiny:

  • Three end-to-end tests invoke each advertised continuation and verify it returns a non-fallback bounded response.
  • Focused verification: 3 passed, with POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-pytest; pre-push quick gate passed.
  • No Bead state changed; Ref polylogue-rsad.

Problem:
Adversarial review found an unbounded tag-count map with a non-replayable
fallback, excerpts that could omit the search evidence an agent needs, and
unknown MCP origin filters silently normalized to unknown-export.

What changed:
Page tag maps deterministically with replay context, center bounded message
excerpts on an optional match query, and reject unknown query-origin tokens
with the existing valid-values error contract. Production-route MCP tests
exercise all three behavior changes.

Ref polylogue-rsad.

Co-Authored-By: Claude <[email protected]>
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 3

Findings:

  • Real gap: list_tags could still exceed the response budget without a size-limited, replayable call.
  • Real gap: excerpt mode retained only head/tail text, so it could omit the matched evidence that prompted a read.
  • Real gap: unknown origin query filters silently normalized to unknown-export instead of returning the established valid-values error.

Fixes in 252d182d8:

  • list_tags now has deterministic limit/offset paging and records its arguments for a bounded replay continuation.
  • get_messages(match_query=...) centers a bounded excerpt on the first requested match span and keeps that query in replay arguments.
  • MCP query construction rejects unknown origin and exclude_origin tokens through the typed invalid_query envelope.

What survived scrutiny:

  • New production-route tests invoke the registered MCP handlers and actual response serializer. Removing tag slicing/context, match-span selection, or origin validation makes the corresponding test fail.
  • Focused regressions: 3 passed. Required MCP selection: 181 passed (tests/unit/mcp -k 'envelope or pagination or summary'), with pytest temp rooted at /realm/tmp/polylogue-pytest.
  • Push quick gate passed (format, lint, mypy, generated/layering checks). No Bead state changed.

Ref polylogue-rsad.

Sinity and others added 2 commits July 13, 2026 01:38
Problem:
Several mutable list tools and the tags resource could exceed the shared
MCP budget yet advertise an unchanged or absent continuation.

What changed:
Add limit/offset envelopes and bounded replay contexts to mutable list tools,
compact oversized saved item payloads during a replay, and route the tags
resource fallback through the paged list_tags tool.

Ref polylogue-rsad.

Co-Authored-By: Claude <[email protected]>
Problem:
Closed-vocabulary typos inside the query DSL bypassed the MCP invalid-query
envelope even though direct query filters returned valid recovery values.

What changed:
Route expression compilation errors through the shared query-error formatter,
preserving field metadata and valid values for closed query vocabularies.

Ref polylogue-rsad.

Co-Authored-By: Claude <[email protected]>
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 4

Findings:

  • Real gap: mutable list tools and polylogue://tags could still yield an unchanged or absent continuation after an oversized response.
  • Real gap: invalid closed values inside the query DSL bypassed the same valid-values envelope used by direct query parameters.

Fixes in 9415cd2ec and 8635af3f8:

  • Mutable list responses now carry limit/offset/next_offset, retain replay context, and use compact per-item output on bounded replay; the tags resource replays through paged list_tags.
  • ExpressionCompileError now maps to invalid_query, including the closed-vocabulary recovery values for DSL origin and action errors.

What survived scrutiny:

  • Registered-handler tests force both a large annotations list and a large tags resource through their advertised continuations (2 passed).
  • Registered search calls with bad DSL origins/actions return the typed recovery envelope (4 passed including direct-origin/sort coverage).
  • Both pushed commits passed the pre-push quick gate. No Bead state changed.

Ref polylogue-rsad.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 5 (loop cap reached)

Remaining real gaps:

  • query_units locally catches DSL compilation errors, so unknown closed values there bypass the shared invalid_query field/valid-values envelope. Correction-kind errors likewise remain an unknown_kind payload without the closed-vocabulary recovery set.
  • query_units and archive_search_sessions can overflow without preserving their required expression/query arguments in response context, producing a continuation that cannot be invoked.

No changes were made in this iteration. This is the fifth independent cold review, the adversarial-loop cap; I am stopping rather than claiming convergence.

Remaining polylogue-rsad work is therefore not complete. The current branch stays pushed and clean; no Bead state changed.

Ref polylogue-rsad.

@Sinity
Sinity merged commit 113d1af into master Jul 13, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the feature/fanout/mcp-ergonomics branch July 13, 2026 00:23
Sinity added a commit that referenced this pull request Jul 13, 2026
…807,2780,2790,2791,2795,2802,2806,2809

uwk3, jph5 (rigor-contracts #2783), bby.17 (web-cockpit #2793), dmp
(terminal-note #2801), ra3w (basetemp-fix #2807), r4no/bkff/r2kb
(extension-redesign #2780) fully satisfied — closed. nhjs (#2793), peo
(daemon-forensics #2802), 4g3n (#2780), 67ac/212.11 (demo-corpus #2795),
rsad (mcp-ergonomics #2790, real gaps remain per 5-iteration adversarial
cap), 9e5.8.4/jnj.7 (provider-origin #2806), mrxt/37t.12/p5g/rxdo.4
(annotation-judgment #2791), s7ae.8/20d.2 (live-performance-2 #2809)
partially satisfied — noted with disposition, left open.

Also discovered and documented the actual root cause of this session's
recurring bead-revert incidents: bd reimports the live database from
.beads/issues.jsonl on every CLI invocation, so a write not immediately
exported is lost the moment the next bd command runs. Every mutation in
this commit was individually export-verified against that behavior.

Co-Authored-By: Claude <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 68.F010 / P1: stale at the checked revision: The old list_sessions registration and its deleted schema-derivation test are not part of the pinned MCP surface. polylogue/mcp/server_cutover.py:1206-1222 defines the current query tool with an explicit signature, registered through the declaration-owned cutover registrar rather than the retired dataclass-field omission rule.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 69.F007 / P2: fixed-already at the checked revision: polylogue/mcp/archive_support.py:372 bounds coalescing by the unique sessions needed for the requested page. The loop at line 406 stops once that bound is reached and returns at lines 422-423, rather than exhausting every matching FTS hit before paging.
  • 69.F008 / P2: fixed-already at the checked revision: polylogue/mcp/archive_support.py:462-465 emits search-miss diagnostics only when total == 0. An empty page beyond a nonzero match total no longer reports that no session matched.

Only the rows listed above are dispositioned. Held findings remain open.

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