Skip to content

fix: datetime UTC, MCP filter wiring, export fields, paste role guard - #821

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/mcp-datetime-export-paste-fixes
May 4, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/mcp-datetime-export-paste-fixes

Conversation

@Sinity

@Sinity Sinity commented May 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes 4 bugs across datetime handling, export payloads, paste detection, and MCP filter instrumentation. Closes 3 issues fully and 1 partially.

Problem

  1. _iso_to_epoch interpreted naive ISO dates in local time — midnight UTC shifted hours when --since/--until filters ran against SQLite epoch values
  2. detect_paste() ran on all message roles — assistant code blocks were flagged as paste, inflating Codex paste rate to 92%
  3. ConversationMessagePayload serialized only id, role, text, timestamp, message_type — dropping content_blocks (thinking, tool_use, tool_result), provider_meta (API duration, model, usage), and parent_id from all JSON/YAML/JSONL exports
  4. 15+ filter dimensions from ConversationQuerySpec had zero MCP tool parameter instrumentation — defined in the query model but never activatable from any MCP client

Solution

  • filter_builder.py: Attach timezone.utc to naive datetimes before .timestamp()
  • materialization_runtime.py: Guard detect_paste() behind msg.role == "user"
  • surfaces/payloads.py: Add content_blocks, provider_meta, parent_id to ConversationMessagePayload
  • mcp/server_tools.py: Expose 17 missing filter params on both search and list_conversations tools
  • mcp/query_contracts.py: Add missing fields to MCPConversationQueryRequest, add has_paste → filter_has_paste alias
  • archive/query/fields.py: Add mcp_names to 13 field descriptors
  • tests/data/witnesses/: Regenerate MCP tool schema witness

Verification

ruff format --check → ok
ruff check → ok
mypy polylogue/mcp/ polylogue/surfaces/ polylogue/pipeline/ polylogue/storage/ polylogue/archive/ → ok
pytest -q --ignore=tests/integration → 5834 passed (4 more than master baseline of 5830)
devtools verify --quick → all checks passed

Ref #820, #801, #811, #819

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Expanded search and conversation listing with additional query filters: contains, exclude_text, exclude_provider, exclude_tag, has_type, conv_id, until, reverse, latest, max_messages, sample, and similar_text.
    • Added message context fields: content blocks, provider metadata, and parent message references.
  • Bug Fixes

    • Improved timestamp handling with proper timezone normalization.
    • Fixed paste detection logic to apply only to user messages.

Problem:
- _iso_to_epoch interpreted naive datetimes in local time (not UTC),
  shifting --since/--until by the local offset (#820 item 1)
- detect_paste() ran on all messages, flagging assistant code blocks
  as paste and inflating Codex paste rate to 92% (#801 item 1)
- ConversationMessagePayload dropped content_blocks, provider_meta,
  and parent_id from JSON/YAML/JSONL exports (#811)
- 15+ filter dimensions from ConversationQuerySpec had zero MCP
  tool parameter instrumentation — defined but never activatable
  from any MCP client (#819 item 1)
- has_paste alias missing from MCP query param normalization,
  so MCP clients could never filter by paste (#819)

Solution:
- _iso_to_epoch: attach timezone.utc to naive datetimes before
  calling .timestamp() — dates are now UTC-correct
- materialization_runtime.py: guard detect_paste() behind
  msg.role == "user" so only user messages are paste-evaluated
- ConversationMessagePayload: add content_blocks, provider_meta,
  parent_id fields and populate from Message model
- MCP search + list_conversations: expose all missing filter params
  (contains, exclude_text, exclude_provider, exclude_tag, has_type,
  conv_id, until, latest, reverse, sample, has_paste, typed_only,
  max_messages, similar_text, since_session_id)
- query_contracts.py: add has_paste → filter_has_paste alias
- fields.py: add mcp_names to 13 field descriptors that lacked them
- Regenerate MCP tool schema witness to match expanded signatures

Fixes #820 (partial — FK and INSERT OR IGNORE deferred)
Fixes #801 (item 1 — role guard; ground-truth calibration deferred)
Fixes #811 (export field gaps)
Fixes #819 (item 1 — filter wiring; pagination + error handling next)

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

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR expands the MCP query interface with additional optional filter and constraint parameters (such as contains, exclude_text, has_type, conv_id, reverse, latest, sample, etc.), wires them through the request and tool contracts, updates field descriptor aliases, and makes targeted adjustments to message materialization, UTC datetime handling, and message payload serialization.

Changes

MCP Query Interface Expansion

Layer / File(s) Summary
Field Descriptor Aliases
polylogue/archive/query/fields.py
Adds mcp_names aliases to 13 QueryFieldDescriptor entries including contains_terms, exclude_text_terms, excluded_providers, excluded_tags, has_types, max_messages, similar_text, until, latest, reverse, sample, conversation_id, and since_session_id to expose shortened query parameter names.
Request Contract Expansion
polylogue/mcp/query_contracts.py
Extends MCPConversationQueryRequest with new optional fields: until, contains, exclude_text, exclude_provider, exclude_tag, has_type, conv_id, reverse, latest, max_messages, sample, similar_text, since_session_id, and has_paste. Updates build_spec() to pass all new fields into ConversationQuerySpec construction. Adds has_paste to _QUERY_PARAM_ALIASES.
Tool Wiring
polylogue/mcp/server_tools.py
Extends both search and list_conversations MCP tool parameter lists with the new filter, sorting, pagination, and constraint fields, and wires each parameter into MCPConversationQueryRequest for spec building.
Schema Documentation
tests/data/witnesses/mcp-tool-schemas.json
Updates MCP tool argument schemas for list_conversations and search to reflect all newly added optional query parameters and replaces since_session with since_session_id.

Paste Detection Scope Adjustment

Layer / File(s) Summary
Materialization Logic
polylogue/pipeline/materialization_runtime.py
Changes has_paste computation in materialize_conversation to apply detect_paste() only for user-role messages; non-user messages now set has_paste to 0.

UTC Timezone Normalization

Layer / File(s) Summary
ISO Datetime Parsing
polylogue/storage/sqlite/queries/filter_builder.py
Updates _iso_to_epoch to explicitly assign timezone.utc to naive datetimes parsed from ISO strings before converting to epoch seconds, ensuring consistent UTC interpretation.

Message Payload Enrichment

Layer / File(s) Summary
Payload Schema
polylogue/surfaces/payloads.py
Adds three optional fields to ConversationMessagePayload: content_blocks (default empty list), provider_meta (nullable dict), and parent_id (nullable string). Updates from_message() to populate these fields from the source Message object.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

A rabbit hops through query fields so fine,
With conv_id and filters in a line,
New aliases bloom, the MCP expands,
While paste detection takes its rightful stands—
🐰 For clarity, we trade a thousand names! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% 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 concisely summarizes the four main categories of fixes (datetime UTC, MCP filter wiring, export fields, paste role guard) that are comprehensively addressed in the changeset.
Description check ✅ Passed The PR description provides all required template sections: Summary (what changed), Problem (why necessary with concrete examples), Solution (key modules/changes), Verification (exact commands with results), and Risks/Follow-ups appropriately omitted.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/mcp-datetime-export-paste-fixes

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

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 fixes four archive/MCP surface regressions: UTC handling for date filters, paste detection scoping, richer exported message payloads, and missing MCP query filter wiring. It mainly tightens how existing query/export infrastructure exposes and serializes conversation data across storage, rendering, and MCP tool surfaces.

Changes:

  • Fixes naive ISO timestamp handling in SQLite filter pushdown and limits paste detection to user messages.
  • Expands conversation/message surface payloads and MCP query contracts to expose more stored fields and filters.
  • Regenerates the MCP tool-schema witness to match the updated public MCP tool parameters.

Reviewed changes

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

Show a summary per file
File Description
tests/data/witnesses/mcp-tool-schemas.json Updates the committed MCP tool JSON Schema witness for the expanded query parameters.
polylogue/surfaces/payloads.py Extends message payload serialization with structured blocks, provider metadata, and parent linkage.
polylogue/storage/sqlite/queries/filter_builder.py Fixes naive ISO datetime conversion to interpret unzoned timestamps as UTC.
polylogue/pipeline/materialization_runtime.py Restricts paste detection to user-authored messages during materialization.
polylogue/mcp/server_tools.py Adds many missing MCP query parameters to search and list_conversations.
polylogue/mcp/query_contracts.py Threads the new MCP parameters into query-spec construction and adds alias normalization.
polylogue/archive/query/fields.py Registers MCP-facing names for previously unwired query-field descriptors.

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

Comment on lines 155 to +157
sort: str | None = None,
reverse: bool = False,
latest: str | None = None,
Comment on lines +147 to +148
content_blocks=message.content_blocks,
provider_meta=message.provider_meta,
Comment on lines +65 to +67
sort: str | None = None,
reverse: bool = False,
latest: str | None = None,

@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: 6cbb49c5fd

ℹ️ 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

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/mcp/query_contracts.py`:
- Around line 69-70: The MCP contracts treat latest as a boolean presence flag
but are currently typed as str | None; change the latest field in
MCPConversationQueryRequest and MCPArchiveQueryRequest to be latest: bool =
False (not str | None) so generated schemas mark it as a boolean, and update the
corresponding function signatures in server_tools.py to accept latest: bool =
False (replace any str | None or Optional[str] usages) so callers and schema
coercion won't convert "false" strings into True. Ensure any related default
handling or docstrings still assume a boolean presence flag.
🪄 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: 5746cd84-9942-4550-b769-fad44e709ac2

📥 Commits

Reviewing files that changed from the base of the PR and between 896b0f5 and 6cbb49c.

📒 Files selected for processing (7)
  • polylogue/archive/query/fields.py
  • polylogue/mcp/query_contracts.py
  • polylogue/mcp/server_tools.py
  • polylogue/pipeline/materialization_runtime.py
  • polylogue/storage/sqlite/queries/filter_builder.py
  • polylogue/surfaces/payloads.py
  • tests/data/witnesses/mcp-tool-schemas.json

Comment on lines +69 to +70
reverse: bool = False
latest: str | None = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP --type=py '\blatest\s*:' polylogue/mcp/query_contracts.py polylogue/mcp/server_tools.py polylogue/archive/query/spec.py polylogue/archive/query/fields.py

Repository: Sinity/polylogue

Length of output: 380


🏁 Script executed:

#!/bin/bash
# Check lines 111-114 in query_contracts.py to see if there's another occurrence
head -115 polylogue/mcp/query_contracts.py | tail -20

Repository: Sinity/polylogue

Length of output: 849


🏁 Script executed:

#!/bin/bash
# Get more context around the latest usage in archive/query/spec.py
head -380 polylogue/archive/query/spec.py | tail -15

Repository: Sinity/polylogue

Length of output: 589


🏁 Script executed:

#!/bin/bash
# Search for how latest is used in the query modules
rg -B2 -A2 'latest' polylogue/archive/query/spec.py | head -50

Repository: Sinity/polylogue

Length of output: 675


🏁 Script executed:

#!/bin/bash
# Check what's at lines 111-114 in query_contracts.py to see the complete picture
sed -n '105,120p' polylogue/mcp/query_contracts.py

Repository: Sinity/polylogue

Length of output: 695


🏁 Script executed:

#!/bin/bash
# Verify server_tools.py occurrences at lines 67 and 157
rg -B3 -A3 'latest.*str.*None' polylogue/mcp/server_tools.py

Repository: Sinity/polylogue

Length of output: 553


Make latest a boolean flag across all MCP request types.

The query stack treats latest as a boolean presence switch, but MCP contracts expose it as str | None. This creates a type mismatch that generates incorrect MCP schemas and coerces string values like "false" to True when converted with bool().

Fix both MCPConversationQueryRequest (lines 69–70) and MCPArchiveQueryRequest (lines 111–114) in query_contracts.py, as well as the corresponding function signatures in server_tools.py:

Suggested fixes
-    latest: str | None = None
+    latest: bool = False

This change should be applied to:

  • polylogue/mcp/query_contracts.py:70 (MCPConversationQueryRequest)
  • polylogue/mcp/query_contracts.py:111-114 (MCPArchiveQueryRequest)
  • polylogue/mcp/server_tools.py:67 (function parameter)
  • polylogue/mcp/server_tools.py:157 (function parameter)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
reverse: bool = False
latest: str | None = None
reverse: bool = False
latest: bool = False
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/mcp/query_contracts.py` around lines 69 - 70, The MCP contracts
treat latest as a boolean presence flag but are currently typed as str | None;
change the latest field in MCPConversationQueryRequest and
MCPArchiveQueryRequest to be latest: bool = False (not str | None) so generated
schemas mark it as a boolean, and update the corresponding function signatures
in server_tools.py to accept latest: bool = False (replace any str | None or
Optional[str] usages) so callers and schema coercion won't convert "false"
strings into True. Ensure any related default handling or docstrings still
assume a boolean presence flag.

@Sinity
Sinity merged commit 4d60bde into master May 4, 2026
6 checks passed
@Sinity
Sinity deleted the feature/fix/mcp-datetime-export-paste-fixes branch May 4, 2026 08:33
@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.F016 / P2: fixed-already at the checked revision: polylogue/mcp/query_contracts.py:143 now declares latest as bool with default False. The cited string-typed MCP field no longer advertises string values that become truthy through bool("false").

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