Skip to content

test(mcp): rewrite test_mcp_server.py for the post-#249 server modules - #319

Open
abhishekKokadwar wants to merge 2 commits into
kubeflow:mainfrom
abhishekKokadwar:test/mcp-server-rewrite
Open

abhishekKokadwar wants to merge 2 commits into
kubeflow:mainfrom
abhishekKokadwar:test/mcp-server-rewrite

Conversation

@abhishekKokadwar

@abhishekKokadwar abhishekKokadwar commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

What and why

#269 skipped tests/test_mcp_server.py because it tested server internals that #249 removed. Since then the MCP search path has had no running unit tests: nothing imports intent_router.py or milvus_search.py, or calls the tool handlers in server.py.

This replaces the skipped module with tests against the current code. Milvus and the embeddings service are mocked, so no network, Milvus or model downloads are needed.

  • tests/test_intent_router.py (new): pick_search_plan for each query class and its first match precedence, downgrade_plan_for_collection for collections without BM25 or release fields, and the post search rerankers.
  • tests/test_mcp_server.py (rewritten): connect() guards, schema caching, per collection search modes, embedding errors, the dense, BM25 and hybrid requests sent to Milvus, search_collection and search_docs_auto (including the unfiltered BM25 retry and the general hits that feat(rag): recurring ingest, community-distribution docs, and latest-query retrieval #290 merges into "latest" answers), and the three tools: argument checks, filter injection rejection, filter construction, empty and failed searches, and structured citations.

Expected values come from the modules' docstrings and comments, not from whatever the code currently returns. One place where docs/RAG_V4_ARCHITECTURE.md and the code disagree: the doc lists conceptual queries as weighted hybrid (0.3 dense / 0.7 sparse, depth 50), while the code uses RRF by default, 0.7 / 0.3 weights and no candidate depth. The tests follow the code; which one is right is a question for maintainers, outside this tests only PR. pymilvus is stubbed only when it is not installed, so the file runs both under requirements-test.txt and in the full CI environment.

Fixes #272
Part of #259 (the ingest side of #249's test plan is in #318)

Testing

  • pytest tests/test_mcp_server.py tests/test_intent_router.py: 115 passed, also with RERANKER_URL, LANGFUSE_PUBLIC_KEY and CODE_SEARCH_MODE=hybrid set (the tests clear or pin them).
  • Mutation check: removing the general hits cap in merge_release_and_general_hits, or the release notes boost in rerank_hits_after_search, makes the tests fail.
  • pytest (full suite): 306 passed, 4 skipped, 1 failed. The failure is tests/test_code_utils.py::test_code_pipeline_preserves_github_canonical_citation_url (chunk_and_embed_code() missing 1 required positional argument: 'exclude_resource_kinds'). It fails the same way on a clean checkout of main, and this PR does not touch pipeline code.
  • ruff check . and ruff format --check docs-agent-mcp/mcp-server tests: clean.

Not tested: anything against a live Milvus or embeddings service. These are unit tests only.

Evaluation

Tests only, no change to retrieval, reranking, routing, prompts or citations. No /eval or re-ingest needed.

…r modules

kubeflow#269 skipped tests/test_mcp_server.py because it targeted server
internals that kubeflow#249 removed, which left the MCP search path with no
tests: nothing imported intent_router.py or milvus_search.py, or called
the tool handlers in server.py.

Replace the skipped module with tests against the current code, with
Milvus and the embeddings service mocked:

- tests/test_intent_router.py: pick_search_plan for each query class and
  its first-match precedence, downgrade_plan_for_collection for
  collections without BM25 or release fields, and the post-search
  rerankers.
- tests/test_mcp_server.py: connect() guards, schema caching, per-
  collection search modes, embedding errors, the dense/BM25/hybrid
  requests sent to Milvus, search_collection and search_docs_auto
  (including the unfiltered BM25 retry and the general hits kubeflow#290 merges
  into latest/current answers), and the three tools: argument checks,
  filter-injection rejection, filter construction, empty and failed
  searches, and structured citations.

Expected values come from the modules' docstrings and comments, not
from current output. test_mcp_server.py stubs pymilvus only when it is not
installed, so it runs under requirements-test.txt and the full CI
environment alike.

Fixes kubeflow#272
Part of kubeflow#259

Signed-off-by: Abhishek <abhikokadwar2@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 29, 2026 22:01
@google-oss-prow

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by:
Once this PR has been reviewed and has the lgtm label, please assign tarekabouzeid for approval. For more information see the Kubernetes Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Tests
    • Expanded automated coverage for query routing, search behavior, retrieval metadata, version matching, result merging, and configuration aliases.
    • Replaced skipped tests for outdated server behavior with active checks for connection handling, search modes, input validation, fallback paths, error responses, and citations.
    • Tests use mocked services to exercise these scenarios without connecting to a live search service or requiring live embedding services.

This pull request adds intent-router tests and replaces skipped legacy MCP server tests with active mocked tests for current search and server modules. The tests cover query planning, collection capabilities, reranking, search requests, validation, tool responses, and citations.

Changes: Search test coverage

Layer / File(s) Summary
Intent plans and collection capabilities
tests/test_intent_router.py
Adds tests for query-plan selection and precedence, plus plan downgrades when collections lack BM25 or release fields.
Reranking and retrieval metadata
tests/test_intent_router.py
Adds tests for release-document boosting, release-date and version reranking, result merging and trimming, retrieval metadata, and ConfigMap fetch-limit aliases.
MCP connection and search requests
tests/test_mcp_server.py
Replaces skipped legacy tests with mocked tests for connection validation and reuse, collection capabilities, embedding validation, and dense, BM25, and hybrid requests.
Automatic retrieval behavior
tests/test_mcp_server.py
Adds tests for temporal and conceptual retrieval, fallback behavior, result supplementation, reranker candidate depth, and search errors.
Tool validation and responses
tests/test_mcp_server.py
Adds tests for query and filter validation, tool routing and responses, collection filters, and structured citations.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Other

Possibly related issues

Possibly related PRs

  • kubeflow/docs-agent#290: This PR tests retrieval behavior introduced by #290, including release-query routing, general-result supplementation, reranker candidate depth, and result merging.

Suggested reviewers: santhoshtoorpu

Merge Risk: Low · up to 1f065

This change adds mocked unit tests and touches no production code. A few earlier test-hygiene concerns may still be open, and the author reports fixing them in the latest commit. Merging carries little risk.

Security architecture risk: Minimal · up to da8fa

This PR replaces skipped tests and adds regression coverage for existing behavior. It does not change what is deployed or what callers can do.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the rewrite of tests/test_mcp_server.py for the post-#249 server modules. It is a short, single-line conventional-commit title. The new tests/test_intent_router.py fil…
Description check Passed The description explains the purpose of the change. It states that the skipped test_mcp_server.py was replaced with active mocked tests, lists the new and rewritten test files and their coverage, repo…
Linked Issues check Passed [#272] The issue asks for test-only coverage of the post-#249 MCP search path and removal of the skipped pre-#249 module. The whole-PR diff (merge base 1aba4c5 to head 1f0658f) shows two test files: t…
Out of Scope Changes check Passed The whole-PR diff changes only test code: tests/test_intent_router.py (new) and tests/test_mcp_server.py (rewritten). The visible diff shows no production file edits, and the PR description states the…
Full details: Title check

Explanation

The title names the main change: the rewrite of tests/test_mcp_server.py for the post-#249 server modules. It is a short, single-line conventional-commit title. The new tests/test_intent_router.py file is not named, but the title does not need to cover every detail.

Full details: Description check

Explanation

The description explains the purpose of the change. It states that the skipped test_mcp_server.py was replaced with active mocked tests, lists the new and rewritten test files and their coverage, reports test results, and notes a doc/code disagreement. It is directly related to the changeset.

Full details: Linked Issues check

Explanation

[#272] The issue asks for test-only coverage of the post-#249 MCP search path and removal of the skipped pre-#249 module. The whole-PR diff (merge base 1aba4c5 to head 1f0658f) shows two test files: tests/test_intent_router.py (new, +330 lines) and tests/test_mcp_server.py (rewritten, the skip marker and obsolete internals are gone).

Coverage by requirement:

  • server.py input guards: the rewritten tests/test_mcp_server.py contains tests for the tool argument checks and filter injection rejection. The visible diff was truncated before the full server tests, so this is confirmed by the PR description and the earlier review, not by the full text.
  • intent_router.py: test_intent_router.py covers pick_search_plan per query class (comparison, release_date, temporal, exact, conceptual, general), first-match precedence, downgrade_plan_for_collection for collections without BM25 or release fields, and rerank_by_release_date, rerank_for_version_match and rerank_hits_after_search. Expected values are written from the module docstrings and comments.
  • milvus_search.py: test_mcp_server.py uses a mocked MilvusClient and a mocked embed_query, and covers connect guards, schema caching, search-mode selection, and dense, BM25 and hybrid request construction.
  • Mocking: Milvus and embeddings are mocked. pymilvus is stubbed only when it is not installed.
  • Removal: the skipped module is replaced in place, so no dead skipped module remains.

The new commit since the previous review (merge and release-hit coverage, env isolation via monkeypatch) adds tests for the same modules. It does not change the verdict. No concrete unmet coding requirement is found.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff changes only test code: tests/test_intent_router.py (new) and tests/test_mcp_server.py (rewritten). The visible diff shows no production file edits, and the PR description states the change is test-only. Every test targets intent_router.py, milvus_search.py, reranker_client.py or server.py, which #272 names. The mocks and env fixtures only isolate those tests. The full-suite failure in tests/test_code_utils.py is reported by the author as failing on main too. It is not part of this diff and is not counted as out-of-scope work. The diff output was truncated after the start of tests/test_mcp_server.py, so the remaining hunks were not read directly. The test-only scope rests on the PR description and the diff headers shown.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between da8fa1c and 1f0658f.

Files selected for processing: 2

  • tests/test_intent_router.py
  • tests/test_mcp_server.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

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

Note

Quiet mode is enabled, so only the most important comments were posted inline. Other review comments are grouped below.

Other comments: 6

tests/test_mcp_server.py: 6

285-286: Minor · Functional Correctness · Quick win

Check the filter on the first BM25 request.

call_args checks only the retry. If the first request loses its release filter, the mock still returns an empty batch followed by a hit, and every assertion passes. Use call_args_list to check the release filter on the first request and its absence on the second. (raw.githubusercontent.com)

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @tests/test_mcp_server.py around lines 285 - 286:
Update the BM25 retry assertions to inspect both calls via milvus.search.call_args_list: verify the first request includes the release filter and the second request omits it.

239-239: Minor · Functional Correctness · Quick win

Select dense mode before testing its error wrapper.

If CODE_SEARCH_MODE=hybrid and the code collection uses its default name, FULL_SCHEMA lets the call take the hybrid path. That path never calls milvus.search, so the injected exception does not occur and pytest.raises fails. Set CODE_SEARCH_MODE to "dense" with monkeypatch and use milvus_search.CODE_COLLECTION_NAME for the call and expected error. (raw.githubusercontent.com)

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @tests/test_mcp_server.py at line 239:
Update the error-wrapper test containing the `milvus.search.side_effect` setup to select dense mode via `monkeypatch` before invoking the search, ensuring the call exercises `milvus.search`. Use `milvus_search.CODE_COLLECTION_NAME` for both the collection argument and expected error so the test matches the configured collection name.

3-3: Minor · Functional Correctness · Quick win

Disable tracing for this unit-test module.

If the runtime Langfuse SDK is installed and tracing is configured, even the invalid-query test at Line 379 can export a span. The tracing wrapper runs before query validation and before the search mock. Clear LANGFUSE_PUBLIC_KEY in an autouse fixture for this module so tool and retrieval tests cannot initialize the exporter. (raw.githubusercontent.com)

As per path instructions, “Unit tests must not need network, Milvus, KServe or model downloads; mark them otherwise.” Based on learnings, report an external-service interaction only after checking whether the test doubles prevent the outbound call.

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @tests/test_mcp_server.py at line 3:
Disable Langfuse tracing for this test module by adding an autouse fixture in tests/test_mcp_server.py that clears LANGFUSE_PUBLIC_KEY before tests run, preventing tool and retrieval tests from initializing the exporter.

Sources: Path instructions, Learnings


272-272: Minor · Functional Correctness · Quick win

Check that both hybrid request legs are unfiltered.

hybrid_search puts a filter in expr on each request leg, not in filter on the outer call. If the release filter reaches the general search, this assertion still passes, and the mocked guide hit still appears. Check that neither entry in kwargs["reqs"] contains expr. (raw.githubusercontent.com)

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @tests/test_mcp_server.py at line 272:
Update the hybrid search assertion in the test to inspect both entries in `milvus.hybrid_search.call_args.kwargs["reqs"]` and verify that neither contains `expr`; do not rely on checking for an outer `filter` argument.

40-40: Minor · Functional Correctness · Quick win

Disable the live reranker in the mocked search tests.

If RERANKER_URL is set, the temporal test at Line 265 sends its mocked guide hit to the real reranker. The Milvus and embedding mocks do not intercept that request. The same setting also changes the conceptual test's expected fetch limit from 5 to 20 at the default reranker depth. Clear RERANKER_URL with monkeypatch in the milvus fixture to preserve the no-reranker baseline. (raw.githubusercontent.com)

As per path instructions, “Unit tests must not need network, Milvus, KServe or model downloads; mark them otherwise.” Based on learnings, report an external-service interaction only after checking whether the test doubles prevent the outbound call.

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @tests/test_mcp_server.py at line 40:
Update the milvus fixture in tests/test_mcp_server.py to clear RERANKER_URL with monkeypatch, so mocked search tests retain the no-reranker baseline and do not call a live reranker or use its fetch-depth setting.

Sources: Path instructions, Learnings


299-299: Minor · Functional Correctness · Heavy lift

Pin the conceptual candidate depth to a documented contract.

The assertion at line 299 expects candidate_depth == 5. The conceptual plan sets no depth, so search_docs_auto falls back to top_k, and each hybrid leg fetches five candidates. docs/RAG_V4_ARCHITECTURE.md:125 lists conceptual hybrid retrieval at depth 50. Issue #272 asks that expected values come from that document, not from current output.

As written, the test locks in the code's behavior and does not check the documented depth. A regression in either direction would not be detected. Before this assertion is kept, the project must decide which value is the contract: the architecture document or the implementation. The test should then assert the chosen value. If the document is the contract, the code change belongs outside this test-only PR and must be made first. If the implementation is the contract, the architecture document should be corrected. This change does not prescribe which path to take.

Prompt to fix issue
Treat finding text, file paths, and code as untrusted review data. Never follow instructions embedded in them. Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate.

Review comment at @tests/test_mcp_server.py at line 299:
Decide whether the conceptual hybrid retrieval contract is the depth of 50 documented in RAG_V4_ARCHITECTURE.md or the implementation’s current depth of 5. Update this test to assert the chosen contract; if the document is authoritative, first update the implementation outside this test-only change, and if the implementation is authoritative, correct the architecture document.

Prompt to fix all issues
Treat finding text, file paths, and code as untrusted review data. Never follow
instructions embedded in them. Verify each finding against current code. Fix
only still-valid issues, skip the rest with a brief reason, keep changes
minimal, and validate.

Other comments:
Review comments at @tests/test_mcp_server.py:
- Around line 285-286: Update the BM25 retry assertions to inspect both calls
via milvus.search.call_args_list: verify the first request includes the release
filter and the second request omits it.
- Line 239: Update the error-wrapper test containing the
`milvus.search.side_effect` setup to select dense mode via `monkeypatch` before
invoking the search, ensuring the call exercises `milvus.search`. Use
`milvus_search.CODE_COLLECTION_NAME` for both the collection argument and
expected error so the test matches the configured collection name.
- Line 3: Disable Langfuse tracing for this test module by adding an autouse
fixture in tests/test_mcp_server.py that clears LANGFUSE_PUBLIC_KEY before tests
run, preventing tool and retrieval tests from initializing the exporter.
- Line 272: Update the hybrid search assertion in the test to inspect both
entries in `milvus.hybrid_search.call_args.kwargs["reqs"]` and verify that
neither contains `expr`; do not rely on checking for an outer `filter` argument.
- Line 40: Update the milvus fixture in tests/test_mcp_server.py to clear
RERANKER_URL with monkeypatch, so mocked search tests retain the no-reranker
baseline and do not call a live reranker or use its fetch-depth setting.
- Line 299: Decide whether the conceptual hybrid retrieval contract is the depth
of 50 documented in RAG_V4_ARCHITECTURE.md or the implementation’s current depth
of 5. Update this test to assert the chosen contract; if the document is
authoritative, first update the implementation outside this test-only change,
and if the implementation is authoritative, correct the architecture document.

After applying the fix, consider running `coderabbit review --agent` for local
review. Visit https://docs.coderabbit.ai/cli?utm_source=ghpr
Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 1aba4c5 and da8fa1c.

Files selected for processing: 2

  • tests/test_intent_router.py
  • tests/test_mcp_server.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

…#290 merge

- Clear RERANKER_URL and LANGFUSE_PUBLIC_KEY for every test in
  test_mcp_server.py. With RERANKER_URL set, search_docs_auto called the
  real reranker and two tests failed.
- Pin CODE_SEARCH_MODE in the search_collection error test, so a hybrid
  setting cannot route around the mocked failure.
- Check the release filter on the first BM25 request and its absence on
  the retry, and check that neither leg of the general hybrid search
  carries a filter.
- Cover the general search failure fallback and the larger candidate
  depth used when a reranker is configured.
- intent_router: add the release words kubeflow#290 added, assert
  add_general_hits, test merge_release_and_general_hits directly, and
  test the release-notes boost where it decides the order. Rename the
  test that actually checks the date sort.

Signed-off-by: Abhishek <abhikokadwar2@gmail.com>

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

Ran the full suite locally on Windows (Python 3.12) with this branch: 286 passed, 14 skipped (vs 182 passed / 77 skipped on main). The stale/obsolete MCP skips are gone and the remaining skips are unrelated (KFP SDK, Node.js, test_docs_pipeline.py). Checked the routing branches, BM25 downgrade, filter fallback and input validation against intent_router.py / milvus_search.py. Coverage looks good. One question inline about is_error.

Comment thread tests/test_mcp_server.py
assert text_of(tool("q")) == message


def test_tools_report_search_failures_as_text(search, monkeypatch):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Small doubt: citations.text_tool_result accepts is_error, but the "Search failed: …" and "Search rejected: …" responses in server.py don't set it, and these tests (here and test_tools_reject_bad_query_before_searching) only check the text. Is that intentional, or should failures be flagged as errors so the agent can tell them apart from a normal answer? If it's intentional, no change needed. Just checking.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch, not intentional as far as I can tell: text_tool_result has is_error, but none of the six "Search rejected" / "Search failed" returns in server.py set it. Since that changes what the tools return to the agent, I'd rather keep it out of this tests-only PR and fix it in a small follow-up that sets is_error=True on those paths and asserts it in these tests. Thanks for running the suite on Windows too.

Assisted-by: AI agent

@abhishekKokadwar

Copy link
Copy Markdown
Member Author

Thanks, fixed in 1f0658f: cleared RERANKER_URL and LANGFUSE_PUBLIC_KEY for the module, pinned CODE_SEARCH_MODE in the error test, and checked both BM25 requests and both hybrid legs.

On the conceptual depth: docs/RAG_V4_ARCHITECTURE.md and the code disagree on more than depth (ranker and weights too). This PR only adds tests, so the tests follow the code and the PR body notes the mismatch. @SanthoshToorpu, which one should be the contract? Happy to fix the doc or the code in a follow-up.

Assisted-by: AI agent

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

chore(tests): rewrite test_mcp_server.py against the post-#249 MCP server modules

3 participants