Skip to content

fix(mcp): add pagination envelopes and structured resource errors (#819) - #897

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/mcp-pagination-819
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/mcp-pagination-819

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Add pagination envelopes to list_conversations and search MCP tools, and standardize structured error handling across all resource handlers.

Problem

  • list_conversations and search returned bare JSON arrays with no total/limit/offset metadata, making client-side pagination impossible.
  • Resource handlers had inconsistent error patterns: some returned plain strings, some had no error handling at all, and errors were not machine-readable.
  • MCPErrorPayload lacked an explicit is_error field.

Solution

Payloads (polylogue/mcp/payloads.py):

  • Added is_error: Literal[True] to MCPErrorPayload.
  • Added MCPPaginatedQueryResultPayload (items, total, limit, offset, diagnostics) and MCPPaginatedSearchResultPayload (hits, total, limit, offset, diagnostics).
  • Updated conversation_query_result_payload() and conversation_search_result_payload() to produce paginated envelopes with total/limit/offset.

Tools (polylogue/mcp/server_tools.py):

  • search and list_conversations now compute clamped limit/offset, call spec.count() for total, and wrap results in paginated envelopes.

Resources (polylogue/mcp/server_resources.py):

  • Added code="not_found" to conversation and messages resource not-found error returns.
  • Wrapped stats, conversations, tags, session-tree, and provider/recent resource handlers with try/except returning structured internal_error payloads.
  • readiness resource already had structured error handling.

Verification

Deferred to wave batch per #852 policy.

Refs #819 #852.

- Add MCPPaginatedQueryResultPayload/MCPPaginatedSearchResultPayload
  with items/hits, total, limit, offset, and optional diagnostics.
- Update conversation_query_result_payload() and
  conversation_search_result_payload() to produce paginated envelopes.
- Wire total via spec.count() in list_conversations and search tools.
- Add is_error: Literal[True] to MCPErrorPayload for machine-readable
  error detection.
- Add code="not_found" to conversation and messages resource
  not-found error returns.
- Wrap 5 resource handlers with try/except returning structured
  internal_error payloads (stats, conversations, tags, session-tree,
  provider/recent).

Ref #819 #852.

Verification: deferred to wave batch per #852 policy.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 08:58
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 54 minutes and 36 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 36d3c543-ba90-457a-92a4-09482ab2608c

📥 Commits

Reviewing files that changed from the base of the PR and between 57b8785 and 95289cd.

📒 Files selected for processing (3)
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_resources.py
  • polylogue/mcp/server_tools.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/mcp-pagination-819

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 and usage tips.

@Sinity
Sinity merged commit 4893f98 into master May 7, 2026
5 checks passed
@Sinity
Sinity deleted the feature/fix/mcp-pagination-819 branch May 7, 2026 08:59

@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: 95289cd596

ℹ️ 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/server_tools.py Resolved
Comment thread polylogue/mcp/server_tools.py Resolved

Copilot AI 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.

Pull request overview

This PR updates the MCP surface to support client-side pagination for conversation listing and search results, and to standardize machine-readable error payloads across MCP resources.

Changes:

  • Wrap list_conversations and search tool responses in paginated envelopes including total, limit, and offset.
  • Add is_error: True to MCPErrorPayload and introduce paginated payload models for MCP query/search results.
  • Add structured internal_error handling (and not_found codes) to multiple MCP resource handlers.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 10 comments.

File Description
polylogue/mcp/server_tools.py Clamp limit/offset, compute totals, and return paginated envelopes for search and list_conversations.
polylogue/mcp/server_resources.py Add structured error payloads for resource failures and not_found codes for missing conversations/messages.
polylogue/mcp/payloads.py Extend error payload schema and add paginated response payload models for MCP list/search tools.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread polylogue/mcp/payloads.py
Comment on lines +23 to +33
from polylogue.mcp.context_pack import (
ContextPackActionSummary as MCPContextPackActionSummary,
ContextPackConversation as MCPContextPackConversation,
ContextPackDateRange as MCPContextPackDateRange,
ContextPackMessage as MCPContextPackMessage,
ContextPackPayload as MCPContextPackPayload,
ContextPackProject as MCPContextPackProject,
ContextPackProvenance as MCPContextPackProvenance,
ContextPackQueryContext as MCPContextPackQueryContext,
ContextPackUnresolvedWork as MCPContextPackUnresolvedWork,
)
Comment thread polylogue/mcp/payloads.py
Comment on lines 439 to +457
"MCPArchiveStatsPayload",
"MCPContextPackActionSummary",
"MCPContextPackConversation",
"MCPContextPackDateRange",
"MCPContextPackMessage",
"MCPContextPackPayload",
"MCPContextPackProject",
"MCPContextPackProvenance",
"MCPContextPackQueryContext",
"MCPContextPackUnresolvedWork",
"MCPContextPackActionSummary",
"MCPContextPackConversation",
"MCPContextPackDateRange",
"MCPContextPackMessage",
"MCPContextPackPayload",
"MCPContextPackProject",
"MCPContextPackProvenance",
"MCPContextPackQueryContext",
"MCPContextPackUnresolvedWork",
Comment on lines 125 to 130
message_type=message_type,
offset=offset,
offset=clamped_offset,
).build_spec(hooks.clamp_limit)
results = await ops.search_conversation_hits(spec)
total = await spec.count(hooks.get_query_store())
diagnostics = await ops.diagnose_query_miss(spec) if not results else None
Comment on lines 128 to +139
results = await ops.search_conversation_hits(spec)
total = await spec.count(hooks.get_query_store())
diagnostics = await ops.diagnose_query_miss(spec) if not results else None
return hooks.json_payload(conversation_search_result_payload(results, diagnostics=diagnostics))
return hooks.json_payload(
conversation_search_result_payload(
results,
total=total,
limit=clamped_limit,
offset=clamped_offset,
diagnostics=diagnostics,
)
)
Comment on lines 228 to +244
conversations = await ops.query_conversations(spec)
total = await spec.count(hooks.get_query_store())
diagnostics = None
if not conversations:
try:
diagnostics = await ops.diagnose_query_miss(spec)
except ConfigError:
diagnostics = None
return hooks.json_payload(conversation_query_result_payload(conversations, diagnostics=diagnostics))
return hooks.json_payload(
conversation_query_result_payload(
conversations,
total=total,
limit=clamped_limit,
offset=clamped_offset,
diagnostics=diagnostics,
)
)
Comment on lines +28 to +35
try:
archive_stats = await hooks.get_archive_ops().storage_stats()
except Exception as exc:
return hooks.error_json(
f"Failed to retrieve archive stats: {exc}",
code="internal_error",
detail=type(exc).__name__,
)
Comment on lines +47 to +54
try:
convs = await MCPConversationQueryRequest().build_spec(hooks.clamp_limit).list(hooks.get_query_store())
except Exception as exc:
return hooks.error_json(
f"Failed to list conversations: {exc}",
code="internal_error",
detail=type(exc).__name__,
)
Comment on lines +73 to +80
try:
tags = await hooks.get_tag_store().list_tags()
except Exception as exc:
return hooks.error_json(
f"Failed to list tags: {exc}",
code="internal_error",
detail=type(exc).__name__,
)
Comment on lines +105 to +112
try:
tree = await hooks.get_archive_ops().get_session_tree(conv_id)
except Exception as exc:
return hooks.error_json(
f"Failed to get session tree for {conv_id}: {exc}",
code="internal_error",
detail=type(exc).__name__,
)
Comment on lines +117 to +125
try:
spec = MCPConversationQueryRequest(provider=name, sort="date", limit=10).build_spec(hooks.clamp_limit)
convs = await spec.list(hooks.get_query_store())
except Exception as exc:
return hooks.error_json(
f"Failed to list recent conversations for provider {name}: {exc}",
code="internal_error",
detail=type(exc).__name__,
)
Sinity added a commit that referenced this pull request May 7, 2026
Closes the narrowed scope of #819. `list_conversations` and
`search` returned bare JSON arrays with no `total`/`limit`/
`offset` metadata, blocking client-side pagination; resource
handlers had inconsistent error patterns and `MCPErrorPayload`
had no explicit `is_error` field.

- `polylogue/mcp/payloads.py`: adds
  `is_error: Literal[True]` to `MCPErrorPayload`. Adds
  `MCPPaginatedQueryResultPayload` and
  `MCPPaginatedSearchResultPayload` with `items` /
  `hits`, `total`, `limit`, `offset`, `diagnostics`.
  Updates `conversation_query_result_payload()` and
  `conversation_search_result_payload()` to produce the
  paginated envelopes.
- `polylogue/mcp/server_tools.py`: `search` and
  `list_conversations` clamp limit/offset, call
  `spec.count()` for total, and wrap results in the new
  envelopes.
- `polylogue/mcp/server_resources.py`: adds
  `code="not_found"` to conversation/messages not-found
  paths; wraps stats / conversations / tags / session-tree /
  provider/recent handlers with try/except returning
  structured `internal_error` payloads.

Refs #819
Sinity added a commit that referenced this pull request May 7, 2026
- #819 (MCP envelopes): `polylogue/mcp/payloads.py` returns a
  populated `next_offset` cursor on paginated responses so MCP
  clients can iterate without recomputing offsets, completing
  the pagination contract introduced in PR #897.
- #820 (storage integrity): `storage/sqlite/schema_ddl_archive.py`
  switches the message-FK policy from implicit to explicit
  `ON DELETE NO ACTION`, matching the documented invariant in
  the schema docstrings rather than relying on SQLite's default.

Refs #819, #820
Sinity added a commit that referenced this pull request May 7, 2026
Closes the narrowed scope of #819. `list_conversations` and
`search` returned bare JSON arrays with no `total`/`limit`/
`offset` metadata, blocking client-side pagination; resource
handlers had inconsistent error patterns and `MCPErrorPayload`
had no explicit `is_error` field.

- `polylogue/mcp/payloads.py`: adds
  `is_error: Literal[True]` to `MCPErrorPayload`. Adds
  `MCPPaginatedQueryResultPayload` and
  `MCPPaginatedSearchResultPayload` with `items` /
  `hits`, `total`, `limit`, `offset`, `diagnostics`.
  Updates `conversation_query_result_payload()` and
  `conversation_search_result_payload()` to produce the
  paginated envelopes.
- `polylogue/mcp/server_tools.py`: `search` and
  `list_conversations` clamp limit/offset, call
  `spec.count()` for total, and wrap results in the new
  envelopes.
- `polylogue/mcp/server_resources.py`: adds
  `code="not_found"` to conversation/messages not-found
  paths; wraps stats / conversations / tags / session-tree /
  provider/recent handlers with try/except returning
  structured `internal_error` payloads.

Refs #819
Sinity added a commit that referenced this pull request May 7, 2026
- #819 (MCP envelopes): `polylogue/mcp/payloads.py` returns a
  populated `next_offset` cursor on paginated responses so MCP
  clients can iterate without recomputing offsets, completing
  the pagination contract introduced in PR #897.
- #820 (storage integrity): `storage/sqlite/schema_ddl_archive.py`
  switches the message-FK policy from implicit to explicit
  `ON DELETE NO ACTION`, matching the documented invariant in
  the schema docstrings rather than relying on SQLite's default.

Refs #819, #820
@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.F021 / P1: fixed-already at the checked revision: polylogue/api/archive.py:584-585 removes both limit and offset from post-filter candidates, and line 723 counts all survivors with needed=None. The ordinary count path also strips offset at lines 725-726, so page offsets no longer reduce reported totals.

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.F037 / P2: fixed-already at the checked revision: polylogue/mcp/archive_support.py:459-461 explicitly reports total=None for semantic, similar-session and hybrid ranked results. It no longer manufactures an exact semantic total by counting a default ten-result retrieval window.

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.

2 participants