Skip to content

test(contracts): expand MCP contract evidence coverage (#1060) - #1081

Merged
Sinity merged 2 commits into
masterfrom
feature/test/mcp-contract-evidence
May 16, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/test/mcp-contract-evidence

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Bring the MCP surface up to the pytest-first contract evidence model from
#1058. The first MCP evidence emitter landed in test_server_surfaces.py for
registration counts; the CLI machine-output family was completed in #1080.
This PR extends evidence coverage onto the remaining MCP families and fixes a
small not-found code drift discovered along the way.

Problem

Before this change, the MCP family in the proof-pack evidence aggregator had a
single recorder (the server-surfaces registration test) and no pytest evidence
for:

  • whether tool input schemas are themselves valid JSON Schema documents
  • tool error envelopes returning the documented MCPErrorPayload shape
  • search/list tools returning a classified items/total envelope on empty
    results
  • privacy of error payloads (no traceback, no secret leakage)
  • a stable surface inventory snapshot per run

While investigating, the tool-side not-found path (get_conversation,
get_conversation_summary, get_messages, raw_artifacts,
export_conversation, session_profile, and the mutation helper) was
returning MCPErrorPayload without code="not_found", while the resource
side and the CLI envelope already used the explicit code. That drift was a
real coherence gap, not just a test gap.

Solution

  • Added tests/unit/mcp/test_contract_evidence.py with 21 contract-marked
    tests across five families:
    1. Runtime schema inventory — Draft202012Validator.check_schema over
      every registered tool, plus resource-template parameter and prompt
      callable assertions.
    2. Error envelopes — neighbor_candidates without args,
      get_conversation/get_conversation_summary/get_messages/
      raw_artifacts/export_conversation with missing IDs, and
      bulk_tag_conversations validation.
    3. No-result envelopes — search, list_conversations,
      neighbor_candidates, and get_session_tree on empty data; sync and
      async invocation paths both covered.
    4. Privacy envelopes — resource internal_error responses preserve
      code/detail/no-traceback invariants; _safe_call sanitises raw
      exception payloads (postgres URIs, bearer tokens) before raising
      PolylogueError.
    5. Registration drift — full surface inventory captured as evidence
      per run, plus role-scoped capability envelopes (read/write/admin).
  • Each test calls record_contract_evidence.record(...) at the assertion
    boundary, emitting bounded JSON under .cache/verification/evidence/ so
    the proof-pack aggregator finds it under the mcp surface.
  • Tightened polylogue/mcp/server_tools.py,
    polylogue/mcp/server_maintenance_tools.py,
    polylogue/mcp/server_insight_tools.py, and
    polylogue/mcp/server_mutation_tools.py to pass code="not_found" to
    error_json on missing-conversation paths so the documented
    MCPErrorPayload shape is consistent across resources, tools, and the CLI.

No backwards-compat shims introduced. No new proof-row registry. Existing
coverage in test_server_surfaces.py, test_envelope_contracts.py,
test_tool_schema_witness.py, and test_mcp_edge_cases.py remains the
authority for the behaviors it already pins.

Verification

nix develop -c pytest tests/unit/mcp -q
# 218 passed (was 197 before; +21 new contract tests)

nix develop -c pytest tests/unit/mcp -m contract -q
# 25 passed in 10s

nix develop -c devtools verify --quick
# total_duration_s 24.36, exit_code 0

ls .cache/verification/evidence/ | grep -c '^mcp\.'
# 21 new artifacts named mcp.{tool,resource,role,surface,prompts}.*

A representative artifact (mcp.tool.get_conversation.not_found-*.json)
carries the standard envelope:

  • contract, surface: "mcp", test_nodeid, git_sha, dirty,
    timestamp, schema_version, and the family-specific facts
    block (here: {"code": "not_found", "is_error": true}).

Ref #1060
Ref #1058

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Standardized error responses across MCP server tools with explicit error codes when conversations are not found.
  • Tests

    • Added comprehensive contract test suite validating tool schemas, error response formats, privacy safeguards, result envelopes, and role-based access control.

Review Change Stack

Extend the pytest-first evidence model (#1058) onto the MCP surface with
five contract families that emit bounded JSON artifacts via
record_contract_evidence:

1. Runtime schema inventory — every registered tool exposes a
   Draft-2020-12-valid inputSchema; resource templates declare URI
   parameters; prompts are callable.
2. Error envelopes — get_conversation, get_conversation_summary,
   get_messages, raw_artifacts, export_conversation, session_profile,
   and the mutation helper return code="not_found" via MCPErrorPayload
   when a conversation is missing. The CLI/resource not_found contract
   already carried code="not_found"; the tool path silently omitted it,
   so the change tightens server_tools.py / server_maintenance_tools.py /
   server_insight_tools.py / server_mutation_tools.py to match.
3. No-result envelopes — search, list_conversations, neighbor_candidates,
   and get_session_tree return their classified items/hits envelope with
   total=0 (not a bare array or null) on empty results.
4. Privacy envelopes — resource internal_error responses never expose a
   raw traceback, and _safe_call sanitises raw exception payloads
   (postgres URIs, bearer tokens) before raising PolylogueError to the
   MCP client.
5. Registration drift detector — full surface inventory (tools,
   resources, resource templates, prompts) is captured as evidence on
   each run; the read/write/admin capability envelopes pin required and
   forbidden tools per role.

Ref #1060
Ref #1058

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

coderabbitai Bot commented May 16, 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 38 minutes and 42 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: 9f69923e-196a-437f-96ef-e2b1ec6e31ad

📥 Commits

Reviewing files that changed from the base of the PR and between 3006287 and 495b9d6.

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

Walkthrough

This PR standardizes MCP (Model Context Protocol) error responses by adding explicit code="not_found" fields to all tool handlers that report missing conversations, then validates the resulting error envelopes, result shapes, and privacy invariants through a comprehensive contract evidence test suite.

Changes

MCP error code standardization and contract evidence

Layer / File(s) Summary
Add 'not_found' error codes to all tool not-found responses
polylogue/mcp/server_insight_tools.py, polylogue/mcp/server_maintenance_tools.py, polylogue/mcp/server_mutation_tools.py, polylogue/mcp/server_tools.py
Seven not-found error branches across five tool handlers now call hooks.error_json(..., code="not_found") instead of omitting the code. Affected tools: session_profile, export_conversation, _resolve_or_error, get_conversation, get_conversation_summary, get_messages, raw_artifacts.
Contract evidence test suite for MCP server surface
tests/unit/mcp/test_contract_evidence.py
New module with six contract test classes: schema inventory validates all tool parameters are well-formed Draft 2020-12 JSON schemas; error envelopes assert structured payloads with expected codes for invalid and not-found cases; no-result envelopes verify list/search tools return classified shapes with totals; privacy envelopes confirm error responses and exceptions omit secrets/tracebacks/paths; registration drift detector captures full inventory and validates per-role tool capability inclusion/exclusion; async coverage ensures no-result envelope paths work via async invocation. Helper functions extract and parse structured error payloads and establish controlled empty-result conditions.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related issues

  • Sinity/polylogue#1060: Both changes address MCP error-envelope behavior; this PR standardizes "not_found" error codes in server tool handlers while the related issue/PR adds pytest evidence to assert and record those envelopes.

Possibly related PRs

  • Sinity/polylogue#764: The not-found error code changes in this PR align directly with that PR's MCP rewiring of conversation-not-found handling via ConversationNotFoundError, affecting the same tool error paths.

Suggested labels

area:mcp, area:qa

Poem

🐰 From tools to tests, the error codes now shine,
"Not found" is clear, in every call line.
Contract evidence stands tall and true,
Privacy safe, schemas checked through and through.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.63% 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 clearly and concisely describes the primary change: expanding MCP contract evidence coverage with new pytest tests.
Description check ✅ Passed The description comprehensively covers all template sections: Summary explains the change, Problem outlines gaps, Solution details the implementation, Verification provides commands and results, and Risks/Follow-ups is appropriately omitted as none exist.
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/test/mcp-contract-evidence

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.

@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_insight_tools.py`:
- Line 83: Add a test method (e.g.,
test_session_profile_missing_returns_not_found_envelope) to
TestToolErrorEnvelopes that patches polylogue.mcp.server._get_polylogue to
return a make_polylogue_mock() whose get_session_profile_insight is an AsyncMock
returning None; call invoke_surface on
mcp_server._tool_manager._tools["session_profile"].fn with
conversation_id="missing", then parse the result with _structured_error and
assert body.get("code") == "not_found"; finally call
record_contract_evidence.record with the key
"mcp.tool.session_profile.not_found" and the same surface/facts pattern used by
the other not_found tests.

In `@polylogue/mcp/server_mutation_tools.py`:
- Line 36: The error message string passed to hooks.error_json in the return
statement of the relevant mutation function should use title case to match the
rest of the codebase; replace "conversation not found" with "Conversation not
found" in the hooks.error_json call (keep the same code arguments like
code="not_found" and conversation_id=conversation_id) so error formatting
remains consistent with other files (see hooks.error_json usage in
server_insight_tools.py, server_maintenance_tools.py, server_tools.py).

In `@polylogue/mcp/server_tools.py`:
- Line 318: Add a unit test that asserts get_conversation_summary returns the
same not_found error envelope when poly.get_conversation_summary(id) returns
None: follow the pattern of
test_get_conversation_missing_returns_not_found_envelope (mock
poly.get_conversation_summary to return None, call the registered tool via
register_read_tools/get_conversation_summary, and assert the hooks.error_json
response equals the expected "Conversation not found: {id}" with code
"not_found"). Ensure the test exercises the
server_tools.get_conversation_summary path and uses the same id and assertion
style as the existing get_conversation test to provide contract coverage.
🪄 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: da6e6e94-1f20-40e4-a9ca-c0debfaf986f

📥 Commits

Reviewing files that changed from the base of the PR and between fc3c43f and 3006287.

📒 Files selected for processing (5)
  • polylogue/mcp/server_insight_tools.py
  • polylogue/mcp/server_maintenance_tools.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/mcp/server_tools.py
  • tests/unit/mcp/test_contract_evidence.py

Comment thread polylogue/mcp/server_insight_tools.py Resolved
Comment thread polylogue/mcp/server_mutation_tools.py Resolved
Comment thread polylogue/mcp/server_tools.py Resolved
CodeRabbit findings on PR #1081:
- server_mutation_tools.py:36 used lowercase "conversation not found"
  while every other MCP tool uses "Conversation not found". Fixed for
  envelope consistency.
- session_profile and get_conversation_summary had not_found error
  envelopes in the source but no contract test coverage. Added both,
  matching the existing get_conversation/get_messages/raw_artifacts
  pattern (mock the polylogue async surface to return None, invoke the
  tool, assert code=='not_found', record evidence artifact).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@Sinity
Sinity merged commit 0bf9574 into master May 16, 2026
4 checks passed
@Sinity
Sinity deleted the feature/test/mcp-contract-evidence branch May 16, 2026 11:30
Sinity added a commit that referenced this pull request May 16, 2026
## Summary

Six pre-existing test failures on master were blocking every newly
opened PR in the #1058 wave (#1081, #1086, #1087, #1088, #1089). All
trace to incomplete cleanup after earlier proof-runner retirement work.

## Problem

`pytest --ignore=tests/integration,benchmarks,fuzz` on
`origin/master@fc3c43f` exits with 6 failures:

-
`tests/unit/devtools/test_benchmark_campaign.py::test_compile_benchmark_campaigns_indexes_by_name`
-
`tests/unit/devtools/test_benchmark_campaign.py::test_benchmark_scenario_index_tracks_authored_catalog`
-
`tests/unit/devtools/test_scenario_projections.py::test_all_projection_operation_targets_are_declared`
-
`tests/proof/laws/completeness/test_every_command_has_help_claim.py::*`
-
`tests/proof/laws/completeness/test_every_json_command_has_envelope_claim.py::*`
-
`tests/proof/laws/anti_dead_code/test_every_subject_has_at_least_one_claim.py::test_every_subject_of_a_fully_bound_kind_is_selected[cli.command]`

Multiple parallel agents inherited and flagged these failures; they
cannot be cleared at PR scope because each PR is supposed to follow the
"no inherited debt" rule.

## Solution

1. **Benchmark catalog drift** — `BENCHMARK_SCENARIOS` grew to include
`reader-api` and `daemon-convergence` (real entries with pytest paths).
Two tests still asserted the old 3-element set, and the new
`operation_targets` (`benchmark.reader.api`,
`benchmark.daemon.convergence`) had no declared `OperationSpec`. Added
the two missing `OperationSpec` rows in `polylogue/operations/specs.py`
and updated the test assertions.

2. **Stale proof-law tests** —
`tests/proof/laws/completeness/test_every_command_has_help_claim.py` and
`test_every_json_command_has_envelope_claim.py` asserted the existence
of `cli.command.{help,no_traceback,plain_mode,json_envelope}` proof
claims. Those were intentionally retired in PRs #1069/#594 (proof-runner
cleanup) because the intent is now pinned by pytest contract evidence
tests under `tests/unit/cli/` (`test_json_envelope_contract.py`,
`test_plain_output_contract.py`, `test_help_contract.py`,
`test_cli_error_boundaries.py`). The law tests are stale debt — both
files deleted.

3. **\`_FULLY_BOUND_KINDS\` parametrize drift** — same retirement
removed all claims selecting `cli.command` / `cli.json_command`
subjects. Removed both kinds from `_FULLY_BOUND_KINDS` in
`test_every_subject_has_at_least_one_claim.py` — the CLI contract suites
cover the surface directly now.

4. **Generated docs** — `docs/test-quality-workflows.md` and
`docs/verification-catalog.md` regen as part of the new OperationSpec
rows.

## Verification

```
nix develop -c pytest --ignore=tests/integration --ignore=tests/benchmarks --ignore=tests/fuzz -q --no-header
# 6841 passed, 2 xfailed, 0 failed (was 6 failed before)
nix develop -c devtools verify --quick  # exit 0
```

Ref #1058 #594 #1069

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
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