-
Notifications
You must be signed in to change notification settings - Fork 28
DA-1055 investigate automated testing for tools mcp server #86
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AayushTyagi1
merged 22 commits into
main
from
DA-1055-investigate-automated-testing-for-tools-mcp-server
Dec 10, 2025
Merged
Changes from 7 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
0525a28
DA-1055: Added: Added async MCP integration tests
AayushTyagi1 543f0fa
DA-1055 Added Server tests
AayushTyagi1 29a6bfc
DA-1055: Added Test cases config
AayushTyagi1 abf44aa
DA-1055: Added Test index tools
AayushTyagi1 89714a0
DA-1055: Added Test KV tools
AayushTyagi1 a400cef
DA-1055: Added Test Query tools
AayushTyagi1 cf6a100
DA-1055: Update Server tools test
AayushTyagi1 4b75bcc
DA-1055 Test utils
AayushTyagi1 ab94dec
DA-1055 Testing with no result
AayushTyagi1 7b6af75
DA-1055 Small readme fix
AayushTyagi1 5575657
DA-1055 Utils Test
AayushTyagi1 dd01eba
Merge branch 'main' into DA-1055-investigate-automated-testing-for-to…
AayushTyagi1 224b852
DA-1055: Added Tests for Performance Tools
AayushTyagi1 195c7a8
DA-1055 Added testing CI
AayushTyagi1 5ddad68
DA-1055 Added testing CI
AayushTyagi1 7326149
DA-1055 Added testing CI
AayushTyagi1 bdc2890
DA-1055 Testing Fix
AayushTyagi1 e70a219
DA-1055 Comment resolved
AayushTyagi1 4aa3da6
DA-1055 Comment resolved
AayushTyagi1 f9c8144
DA-1055 Test fixed
AayushTyagi1 e64eec5
DA-1055 Updated Version
AayushTyagi1 bd29e03
DA-1055 Test fixed
AayushTyagi1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| """ | ||
| Shared fixtures and utilities for MCP server integration tests. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
| import os | ||
| import sys | ||
| from collections.abc import AsyncIterator | ||
| from contextlib import asynccontextmanager | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import pytest | ||
| from mcp import ClientSession, StdioServerParameters, stdio_client | ||
|
|
||
| PROJECT_ROOT = Path(__file__).resolve().parents[1] | ||
| SRC_DIR = PROJECT_ROOT / "src" | ||
|
|
||
| # Tools we expect to be registered by the server | ||
| EXPECTED_TOOLS = { | ||
| "get_buckets_in_cluster", | ||
| "get_server_configuration_status", | ||
| "test_cluster_connection", | ||
| "get_scopes_and_collections_in_bucket", | ||
| "get_collections_in_scope", | ||
| "get_scopes_in_bucket", | ||
| "get_document_by_id", | ||
| "upsert_document_by_id", | ||
| "delete_document_by_id", | ||
| "get_schema_for_collection", | ||
| "run_sql_plus_plus_query", | ||
| "get_index_advisor_recommendations", | ||
| "list_indexes", | ||
| "get_cluster_health_and_services", | ||
| } | ||
|
|
||
| # Minimum configuration needed to talk to a demo cluster | ||
| REQUIRED_ENV_VARS = ("CB_CONNECTION_STRING", "CB_USERNAME", "CB_PASSWORD") | ||
|
|
||
| # Default timeout (seconds) to guard against hangs when the Couchbase cluster | ||
| # is unreachable or slow. Override with CB_MCP_TEST_TIMEOUT if needed. | ||
AayushTyagi1 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| DEFAULT_TIMEOUT = int(os.getenv("CB_MCP_TEST_TIMEOUT", "120")) | ||
|
|
||
|
|
||
| def _build_env() -> dict[str, str]: | ||
| """Build the environment passed to the test server process.""" | ||
| env = os.environ.copy() | ||
| missing = [var for var in REQUIRED_ENV_VARS if not env.get(var)] | ||
| if missing: | ||
| pytest.skip( | ||
| "Integration tests require demo cluster credentials. " | ||
| f"Missing env vars: {', '.join(missing)}" | ||
| ) | ||
|
|
||
| # Ensure the server module can be imported from the repo's src/ folder | ||
| existing_path = env.get("PYTHONPATH") | ||
| env["PYTHONPATH"] = ( | ||
| f"{SRC_DIR}{os.pathsep}{existing_path}" if existing_path else str(SRC_DIR) | ||
| ) | ||
|
|
||
| # Force stdio transport for the test server to match stdio_client | ||
| env["CB_MCP_TRANSPORT"] = "stdio" | ||
| # Ensure unbuffered output to avoid stdout/stderr buffering surprises | ||
| env.setdefault("PYTHONUNBUFFERED", "1") | ||
| return env | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def create_mcp_session() -> AsyncIterator[ClientSession]: | ||
| """Create a fresh MCP client session connected to the server over stdio.""" | ||
| env = _build_env() | ||
| params = StdioServerParameters( | ||
| command=sys.executable, | ||
| args=["-m", "mcp_server"], | ||
| env=env, | ||
| ) | ||
|
|
||
| async with asyncio.timeout(DEFAULT_TIMEOUT): | ||
| async with stdio_client(params) as (read_stream, write_stream): | ||
| async with ClientSession(read_stream, write_stream) as session: | ||
| await session.initialize() | ||
| yield session | ||
|
|
||
|
|
||
| def extract_payload(response: Any) -> Any: | ||
| """Extract a usable payload from a tool response. | ||
|
|
||
| MCP tool responses can return data in different formats: | ||
| - A single content block with JSON-encoded data (dict, list, etc.) | ||
| - Multiple content blocks, one per list item (for list returns) | ||
|
|
||
| This function handles both cases. | ||
| """ | ||
| content = getattr(response, "content", None) or [] | ||
| if not content: | ||
| return None | ||
|
|
||
| # If there are multiple content blocks, collect them all as a list | ||
| # (each item in a list return may be a separate content block) | ||
| if len(content) > 1: | ||
| items = [] | ||
| for block in content: | ||
| text = getattr(block, "text", None) | ||
| if text is not None: | ||
| try: | ||
| items.append(json.loads(text)) | ||
| except json.JSONDecodeError: | ||
| items.append(text) | ||
| return items if items else None | ||
|
|
||
| # Single content block - try to parse as JSON | ||
| first = content[0] | ||
| raw = getattr(first, "text", None) | ||
| if raw is None and hasattr(first, "data"): | ||
| raw = first.data | ||
|
|
||
| if isinstance(raw, str): | ||
| try: | ||
| return json.loads(raw) | ||
| except json.JSONDecodeError: | ||
| return raw | ||
|
|
||
| return raw | ||
|
|
||
|
|
||
| def get_test_bucket() -> str | None: | ||
| """Get the test bucket name from environment, or None if not set.""" | ||
| return os.getenv("CB_MCP_TEST_BUCKET") | ||
|
|
||
|
|
||
| def get_test_scope() -> str: | ||
| """Get the test scope name from environment, defaults to _default.""" | ||
| return os.getenv("CB_MCP_TEST_SCOPE", "_default") | ||
|
|
||
|
|
||
| def get_test_collection() -> str: | ||
| """Get the test collection name from environment, defaults to _default.""" | ||
| return os.getenv("CB_MCP_TEST_COLLECTION", "_default") | ||
|
|
||
|
|
||
| def require_test_bucket() -> str: | ||
| """Get the test bucket name, skipping test if not set.""" | ||
| bucket = get_test_bucket() | ||
| if not bucket: | ||
| pytest.skip("CB_MCP_TEST_BUCKET not set") | ||
| return bucket | ||
|
|
||
|
|
||
| def ensure_list(value: Any) -> list[Any]: | ||
| """Ensure the value is a list. | ||
|
|
||
| MCP can return single-item lists as just the item (not wrapped in a list). | ||
| This helper wraps single non-list values in a list for consistent handling. | ||
| """ | ||
| if value is None: | ||
| return [] | ||
| if isinstance(value, list): | ||
| return value | ||
| return [value] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| """ | ||
| Integration tests for index.py tools. | ||
|
|
||
| Tests for: | ||
| - list_indexes | ||
| - get_index_advisor_recommendations | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import pytest | ||
| from conftest import ( | ||
| create_mcp_session, | ||
| extract_payload, | ||
| get_test_collection, | ||
| get_test_scope, | ||
| require_test_bucket, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_indexes_all() -> None: | ||
| """Verify list_indexes returns all indexes in the cluster.""" | ||
| async with create_mcp_session() as session: | ||
| response = await session.call_tool("list_indexes", arguments={}) | ||
| payload = extract_payload(response) | ||
|
|
||
| # Payload can be None/empty if no indexes exist in the cluster | ||
| if payload is None: | ||
| return # No indexes in cluster, tool executed successfully | ||
|
|
||
| assert isinstance(payload, list), f"Expected list, got {type(payload)}" | ||
| # Each index should have required fields | ||
| if payload: | ||
| first_index = payload[0] | ||
| assert "name" in first_index | ||
| assert "definition" in first_index | ||
| assert "status" in first_index | ||
| assert "bucket" in first_index | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_indexes_filtered_by_bucket() -> None: | ||
| """Verify list_indexes can filter by bucket name.""" | ||
| bucket = require_test_bucket() | ||
|
|
||
| async with create_mcp_session() as session: | ||
| response = await session.call_tool( | ||
| "list_indexes", arguments={"bucket_name": bucket} | ||
| ) | ||
| payload = extract_payload(response) | ||
|
|
||
| # Payload can be None/empty list if no indexes exist for the bucket | ||
| if payload is None: | ||
| return # No indexes in bucket, which is valid | ||
|
|
||
| assert isinstance(payload, list), f"Expected list, got {type(payload)}" | ||
| # All returned indexes should belong to the specified bucket | ||
| for index in payload: | ||
| assert index.get("bucket") == bucket, ( | ||
| f"Index {index.get('name')} belongs to bucket {index.get('bucket')}, " | ||
| f"expected {bucket}" | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_indexes_filtered_by_scope() -> None: | ||
| """Verify list_indexes can filter by bucket and scope.""" | ||
| bucket = require_test_bucket() | ||
| scope = get_test_scope() | ||
|
|
||
| async with create_mcp_session() as session: | ||
| response = await session.call_tool( | ||
| "list_indexes", | ||
| arguments={"bucket_name": bucket, "scope_name": scope}, | ||
| ) | ||
| payload = extract_payload(response) | ||
|
|
||
| # Payload can be None/empty list if no indexes exist for the scope | ||
| if payload is None: | ||
| return # No indexes in scope, which is valid | ||
|
|
||
| assert isinstance(payload, list), f"Expected list, got {type(payload)}" | ||
| # All returned indexes should belong to the specified bucket and scope | ||
| for index in payload: | ||
| assert index.get("bucket") == bucket | ||
| assert index.get("scope") == scope | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_indexes_filtered_by_collection() -> None: | ||
| """Verify list_indexes can filter by bucket, scope, and collection.""" | ||
| bucket = require_test_bucket() | ||
| scope = get_test_scope() | ||
| collection = get_test_collection() | ||
|
|
||
| async with create_mcp_session() as session: | ||
| response = await session.call_tool( | ||
| "list_indexes", | ||
| arguments={ | ||
| "bucket_name": bucket, | ||
| "scope_name": scope, | ||
| "collection_name": collection, | ||
| }, | ||
| ) | ||
| payload = extract_payload(response) | ||
|
|
||
| # Payload can be None/empty list if no indexes exist for the collection | ||
| # This is valid - we just verify the tool executed successfully | ||
| if payload is None: | ||
| return # No indexes in collection, which is valid | ||
|
|
||
| assert isinstance(payload, list), f"Expected list, got {type(payload)}" | ||
| # All returned indexes should belong to the specified collection | ||
| for index in payload: | ||
| assert index.get("bucket") == bucket | ||
| assert index.get("scope") == scope | ||
| assert index.get("collection") == collection | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_list_indexes_with_raw_stats() -> None: | ||
| """Verify list_indexes can include raw index stats.""" | ||
| async with create_mcp_session() as session: | ||
| response = await session.call_tool( | ||
| "list_indexes", arguments={"include_raw_index_stats": True} | ||
| ) | ||
| payload = extract_payload(response) | ||
|
|
||
| assert isinstance(payload, list), f"Expected list, got {type(payload)}" | ||
| # When include_raw_index_stats is True, each index should have raw_index_stats | ||
| if payload: | ||
| first_index = payload[0] | ||
| assert "raw_index_stats" in first_index, ( | ||
| "Expected raw_index_stats when include_raw_index_stats=True" | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_get_index_advisor_recommendations() -> None: | ||
| """Verify get_index_advisor_recommendations returns recommendations.""" | ||
| bucket = require_test_bucket() | ||
| scope = get_test_scope() | ||
| collection = get_test_collection() | ||
|
|
||
| # A query that might benefit from an index (avoid single quotes - they break ADVISOR) | ||
| # Use a numeric comparison instead of string literal | ||
| query = f"SELECT * FROM `{collection}` WHERE id > 100" | ||
|
|
||
| async with create_mcp_session() as session: | ||
| response = await session.call_tool( | ||
| "get_index_advisor_recommendations", | ||
| arguments={ | ||
| "bucket_name": bucket, | ||
| "scope_name": scope, | ||
| "query": query, | ||
| }, | ||
| ) | ||
| payload = extract_payload(response) | ||
|
|
||
| assert isinstance(payload, dict), f"Expected dict, got {type(payload)}" | ||
| # Response should have the expected structure | ||
| assert "current_used_indexes" in payload | ||
| assert "recommended_indexes" in payload | ||
| assert "recommended_covering_indexes" in payload | ||
| # Summary should also be present | ||
| assert "summary" in payload | ||
| summary = payload["summary"] | ||
| assert "has_recommendations" in summary |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.