Skip to content

feat: expose reader user state through MCP - #1052

Merged
Sinity merged 2 commits into
masterfrom
feature/feat/mcp-user-state-tools
May 15, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/feat/mcp-user-state-tools

Conversation

@Sinity

@Sinity Sinity commented May 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Expose the durable reader user-state substrate through write-role MCP tools for conversation marks and saved views, using typed payloads and existing Polylogue facade methods.

Problem

#867 user state was now available through daemon HTTP and the reader UI, but MCP clients still could not list or mutate marks or saved views. That left agent-facing recall workflows behind the web surface and kept the MCP wire schema stale relative to the product state now exposed elsewhere.

Solution

  • Add typed MCP payloads for user marks and saved views.
  • Register list_marks, add_mark, and remove_mark mutation tools.
  • Register list_saved_views, save_saved_view, and delete_saved_view mutation tools.
  • Resolve conversation IDs before mark mutations and validate saved-view query JSON through strict ConversationQuerySpec construction.
  • Classify the new tools in the MCP envelope contract and regenerate the committed tool-schema witness.
  • Move user-state MCP tests into a focused file so the existing broad MCP contract file stays under its file-size budget.

Remaining #867 scope: annotations, message/range targets, recall-pack MCP shape, and CLI parity.

Ref #867

Verification

  • pytest -q tests/unit/mcp/test_tool_contracts.py -k "mark or saved_view" -> 37 passed
  • pytest -q tests/unit/mcp/test_user_state_tools.py tests/unit/mcp/test_envelope_contracts.py tests/unit/mcp/test_tool_schema_witness.py -> 33 passed
  • pytest -q tests/unit/mcp -> 188 passed
  • ruff format --check polylogue/mcp/server_mutation_tools.py polylogue/mcp/payloads.py tests/unit/mcp/test_tool_contracts.py tests/unit/mcp/test_user_state_tools.py tests/unit/mcp/test_envelope_contracts.py -> 5 files already formatted
  • ruff check polylogue/mcp/server_mutation_tools.py polylogue/mcp/payloads.py tests/unit/mcp/test_tool_contracts.py tests/unit/mcp/test_user_state_tools.py tests/unit/mcp/test_envelope_contracts.py -> All checks passed
  • mypy polylogue/mcp/server_mutation_tools.py polylogue/mcp/payloads.py tests/unit/mcp/test_tool_contracts.py tests/unit/mcp/test_user_state_tools.py tests/unit/mcp/test_envelope_contracts.py -> Success
  • devtools verify --quick -> exit_code 0
  • devtools verify --affected --skip-slow -> exit_code 0; pytest affected count 8

Summary by CodeRabbit

Release Notes

  • New Features

    • Added MCP tools to manage conversation marks: create, remove, and list marks
    • Added MCP tools to manage saved query views: save, delete, and list views with proper validation
  • Tests

    • Added comprehensive unit tests validating user-state tools behavior
  • Documentation

    • Updated execution log documenting user-state parity launch roadmap

Review Change Stack

Problem: #867 durable user-state APIs were available to the daemon reader, but MCP write-role clients still had no typed way to list or mutate conversation marks or saved views. That kept agent-facing recall workflows behind the web surface.\n\nWhat changed: add typed MCP payloads plus list/add/remove mark tools and list/save/delete saved-view tools. Saved-view writes validate strict ConversationQuerySpec JSON before storing canonical query JSON. The MCP envelope registry and tool-schema witness are updated, and user-state tool tests live in a focused file to keep the large MCP contract test under budget.\n\nRemaining: annotations, message/range targets, recall-pack MCP shape, and CLI parity remain open under #867.
@coderabbitai

coderabbitai Bot commented May 15, 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 51 minutes and 35 seconds before requesting another review.

You’ve run out of usage credits. Purchase more 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: 60668750-e125-4807-aaa6-f715c6df88c0

📥 Commits

Reviewing files that changed from the base of the PR and between fd889a9 and 9b52a82.

📒 Files selected for processing (2)
  • polylogue/mcp/server_mutation_tools.py
  • tests/unit/mcp/test_user_state_tools.py
📝 Walkthrough

Walkthrough

This PR implements MCP mutation tools for user marks and saved views, enabling clients to list, create, modify, and delete conversation marks and saved-view definitions through the MCP interface.

Changes

MCP User-State Parity Launch

Layer / File(s) Summary
Execution Log & Scope
docs/plans/mk3-execution-log.md
Documents the MCP user-state parity launch, specifying that conversation marks and saved views tools will be implemented, with validation of saved-view query JSON against ConversationQuerySpec, mark ID resolution via the query store, and planned unit tests.
Payload Contracts for Marks & Saved Views
polylogue/mcp/payloads.py
Introduces new Pydantic payload models MCPUserMarkPayload, MCPUserMarkListPayload, MCPSavedViewPayload, and MCPSavedViewListPayload for serializing mark and view data, with corresponding __all__ exports.
Mutation Tool Registration & Implementation
polylogue/mcp/server_mutation_tools.py
Registers six new MCP mutation tools: list_marks and add_mark/remove_mark handle conversation marks with idempotency reporting; list_saved_views, save_saved_view, and delete_saved_view handle saved views with query JSON validation and ConversationQuerySpec compliance. Includes a helper for defensive query-JSON parsing and conversation ID resolution via the query store.
Test Contract Registry & Tool Schema Witness
tests/unit/mcp/test_envelope_contracts.py, tests/data/witnesses/mcp-tool-schemas.json
Updates the TOOL_CONTRACT matrix to classify new list tools as envelope-type and mutation tools as operation-result type. Adds complete JSON-schema parameter definitions for all six new tools.
Comprehensive Unit Tests
tests/unit/mcp/test_user_state_tools.py
Verifies list tool output, mark idempotency and type validation, saved-view query parsing and validation, conversation ID resolution, and correct async invocation of underlying polylogue facade methods across all six tools.

Sequence Diagram

sequenceDiagram
  participant Client
  participant list_marks
  participant add_mark
  participant remove_mark
  participant list_saved_views
  participant save_saved_view
  participant delete_saved_view
  
  Client->>list_marks: mark_type?, conversation_id?
  list_marks-->>Client: MCPUserMarkListPayload {items, total}
  
  Client->>add_mark: conversation_id, mark_type
  add_mark-->>Client: MutationResultPayload {status: added|unchanged}
  
  Client->>remove_mark: conversation_id, mark_type
  remove_mark-->>Client: MutationResultPayload {status: removed|not_found}
  
  Client->>list_saved_views: (no params)
  list_saved_views-->>Client: MCPSavedViewListPayload {items, total}
  
  Client->>save_saved_view: name, query_json, view_id?
  save_saved_view-->>Client: MutationResultPayload {status: ok|error}
  
  Client->>delete_saved_view: view_id
  delete_saved_view-->>Client: MutationResultPayload {status: deleted|not_found}
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly Related PRs

  • Sinity/polylogue#764: Both PRs extend polylogue/mcp/server_mutation_tools.py to wire MCP mutation tools through the polylogue facade, with the main PR adding mark/saved-view mutations while the retrieved PR refactors existing mutations like tags to use the same delegation pattern.
  • Sinity/polylogue#1013: Both PRs update the MCP tool contract expectations in tests/unit/mcp/test_envelope_contracts.py::TOOL_CONTRACT, with the main PR extending it for new {items, total} envelope tools while the retrieved PR refactors the same matrix for schema consistency.
  • Sinity/polylogue#505: The main PR's new mutation tools and unit tests build directly on the MCP test-contract scaffolding and query-store ID resolution mocking patterns established in the retrieved PR.

Suggested Labels

area:mcp, area:qa

Poem

🐰 The Mark & View Parity Hop

New MCP tools for marks in flight,
Saved views now working left and right,
Payloads parsed, mutations done,
Query specs validated—tests are won!
MCP parity hops along at last. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: expose reader user state through MCP' directly and clearly summarizes the main change: exposing user-state substrate (marks and saved views) through MCP tools.
Description check ✅ Passed The pull request description comprehensively covers all required template sections: Summary, Problem, Solution, Verification, and appropriately omits Changelog and Risks sections per guidelines.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/mcp-user-state-tools

Warning

Review ran into problems

🔥 Problems

Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.


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.

@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: fd889a975d

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

@coderabbitai coderabbitai 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.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/mcp/server_mutation_tools.py`:
- Around line 228-231: The response currently mixes the save result (`created`
from save_view) with the subsequent lookup (`saved = get_view(saved_id)`),
causing contradictory values when save_view reports created but get_view returns
None; update the logic in the block that constructs the response so it is
consistent: either (A) treat a missing saved (saved is None) as an error—set
status="error" and detail="saved_view_not_found" when saved is None (override
created/outcome accordingly), or (B) remove the extra get_view(saved_id)
verification entirely and rely solely on the `created` boolean from save_view to
set status ("ok"/"unchanged") and outcome ("added"/"updated") and always leave
detail None; apply this change to the code that builds status/detail/outcome
using the symbols save_view, get_view, created, saved, saved_id, status, detail,
outcome.
- Around line 216-219: The except block for
ConversationQuerySpec.from_params(query, strict=True) currently returns only the
exception type; change it to include the exception message (or both type and
message) in the hooks.error_json detail so users see the specific validation
error (use the caught exc from the except clause and include str(exc) alongside
type(exc).__name__ in the detail passed to hooks.error_json).
- Around line 170-190: The remove_mark tool lacks the upfront mark_type
validation that add_mark performs; add the same validation check for mark_type
at the start of remove_mark (before calling _resolve_or_error or
poly.remove_mark) and return the same validation error payload/format used by
add_mark so callers get a clear validation error instead of a generic not_found;
update the remove_mark function (and its inner run closure if validation lives
there) to call the same validation helper or inline checks and return the
matching error response via hooks.json_payload/MutationResultPayload when
mark_type is invalid.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e965d63b-72d2-454c-959b-ae112db8e5c1

📥 Commits

Reviewing files that changed from the base of the PR and between 7c02d9b and fd889a9.

📒 Files selected for processing (6)
  • docs/plans/mk3-execution-log.md
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_mutation_tools.py
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/mcp/test_user_state_tools.py

Comment thread polylogue/mcp/server_mutation_tools.py Resolved
Comment thread polylogue/mcp/server_mutation_tools.py Resolved
Comment thread polylogue/mcp/server_mutation_tools.py Resolved
Problem: review found inconsistent saved-view mutation responses and asymmetric mark validation in the new MCP user-state tools.\n\nWhat changed: validate remove_mark mark types with the same path as add_mark, include the concrete query-spec validation message in error detail, generate collision-resistant default saved-view IDs, and return ok for successful saved-view updates. Tests now cover those paths.
@Sinity

Sinity commented May 15, 2026 •

Copy link
Copy Markdown
Owner Author

Review follow-up: the current branch validates mark_type in both add_mark and remove_mark through _mark_type_error; the remaining inline marker is attached to the async-safe-call return line after the fix. Query validation details, saved-view ID generation, and saved-view update status were also addressed in 9b52a82.

@Sinity
Sinity merged commit 2face55 into master May 15, 2026
4 checks passed
@Sinity
Sinity deleted the feature/feat/mcp-user-state-tools branch May 15, 2026 14:28
@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.

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.

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