Repository navigation
test(contracts): expand MCP contract evidence coverage (#1060) - #1081
Conversation
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]>
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughThis PR standardizes MCP (Model Context Protocol) error responses by adding explicit ChangesMCP error code standardization and contract evidence
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (5)
polylogue/mcp/server_insight_tools.pypolylogue/mcp/server_maintenance_tools.pypolylogue/mcp/server_mutation_tools.pypolylogue/mcp/server_tools.pytests/unit/mcp/test_contract_evidence.py
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]>
## 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]>
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.pyforregistration 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:
MCPErrorPayloadshaperesults
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) wasreturning
MCPErrorPayloadwithoutcode="not_found", while the resourceside and the CLI envelope already used the explicit code. That drift was a
real coherence gap, not just a test gap.
Solution
tests/unit/mcp/test_contract_evidence.pywith 21 contract-markedtests across five families:
Draft202012Validator.check_schemaoverevery registered tool, plus resource-template parameter and prompt
callable assertions.
neighbor_candidateswithout args,get_conversation/get_conversation_summary/get_messages/raw_artifacts/export_conversationwith missing IDs, andbulk_tag_conversationsvalidation.search,list_conversations,neighbor_candidates, andget_session_treeon empty data; sync andasync invocation paths both covered.
internal_errorresponses preservecode/detail/no-traceback invariants;_safe_callsanitises rawexception payloads (postgres URIs, bearer tokens) before raising
PolylogueError.per run, plus role-scoped capability envelopes (read/write/admin).
record_contract_evidence.record(...)at the assertionboundary, emitting bounded JSON under
.cache/verification/evidence/sothe proof-pack aggregator finds it under the
mcpsurface.polylogue/mcp/server_tools.py,polylogue/mcp/server_maintenance_tools.py,polylogue/mcp/server_insight_tools.py, andpolylogue/mcp/server_mutation_tools.pyto passcode="not_found"toerror_jsonon missing-conversation paths so the documentedMCPErrorPayloadshape 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, andtest_mcp_edge_cases.pyremains theauthority for the behaviors it already pins.
Verification
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-specificfactsblock (here:
{"code": "not_found", "is_error": true}).Ref #1060
Ref #1058
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
Bug Fixes
Tests