arcade-mcp/libs/tests/cli/test_formatter_edge_cases.py
jottakka 98fad93d21
Adding MCP Servers supports to Arcade Evals (#689)
# MCP Server Tool Evaluation Support

## Overview
Add support for evaluating tools from remote MCP servers without
requiring Python callables. Enables direct evaluation of any
MCP-compatible tool server.

## What's New

### Core Features
- **`MCPToolRegistry`**: Evaluate tools from a single MCP server
- **`CompositeMCPRegistry`**: Evaluate tools from multiple MCP servers
simultaneously
- **Automatic loaders**: `load_from_stdio()` and `load_from_http()` to
fetch tools from running servers
- **Automatic namespacing**: Tools prefixed with server name (e.g.,
`server_tool_name`)
- **Smart name resolution**: Use short names if unique, full names if
ambiguous
- **OpenAI strict mode**: Automatic schema conversion prevents parameter
hallucinations

### Usage

**Automatic Loading:**
```python
from arcade_evals import load_from_stdio, MCPToolRegistry

# Load tools automatically from MCP server
tools = load_from_stdio(["npx", "-y", "@modelcontextprotocol/server-github"])
registry = MCPToolRegistry(tools)
```

**Single MCP Server:**
```python
from arcade_evals import MCPToolRegistry, ExpectedToolCall

registry = MCPToolRegistry(mcp_tools)
suite = EvalSuite(catalog=registry)

suite.add_case(
    expected_tool_calls=[
        ExpectedToolCall(tool_name="tool_name", args={...})
    ]
)
```

**Multiple MCP Servers:**
```python
from arcade_evals import CompositeMCPRegistry, load_from_stdio

# Load from multiple servers
github_tools = load_from_stdio(["npx", "-y", "@modelcontextprotocol/server-github"])
slack_tools = load_from_stdio(["npx", "-y", "@modelcontextprotocol/server-slack"])

composite = CompositeMCPRegistry(
    tool_lists={
        "github": github_tools,
        "slack": slack_tools,
    }
)

suite = EvalSuite(catalog=composite)

suite.add_case(
    expected_tool_calls=[
        ExpectedToolCall(tool_name="github_list_issues", args={...})
    ]
)
```

## Implementation

### Files Changed
- **`libs/arcade-evals/arcade_evals/registry.py`** (NEW): Registry
abstractions and implementations
- **`libs/arcade-evals/arcade_evals/loaders.py`** (NEW): Automatic tool
loading from MCP servers
- **`libs/arcade-evals/arcade_evals/eval.py`** (MODIFIED): Enhanced
`ExpectedToolCall` and evaluation logic
- **`libs/arcade-evals/arcade_evals/__init__.py`** (MODIFIED): Exported
new registries and loaders

### Key Technical Details
- Added `BaseToolRegistry` interface for abstraction
- `MCPToolRegistry` handles single server tools
- `CompositeMCPRegistry` manages multiple servers with collision
detection
- `load_from_stdio()` and `load_from_http()` for automatic tool
discovery
- Fixed name normalization bug: MCP tools use underscores (not dots)
- Optimized tool copying: 2.5x faster via shallow copy

## Testing
-  41 tests passing (25 new tests added)
-  `test_eval_mcp_registry.py`: MCPToolRegistry functionality
-  `test_eval_composite_mcp.py`: CompositeMCPRegistry with multiple
servers
-  Verified backward compatibility with Python tools

## Backward Compatibility
 **100% backward compatible** - No breaking changes


## Breaking Changes
**None**


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> Adds end-to-end eval UX: examples, a robust CLI runner, and rich
outputs.
> 
> - **New examples**: `eval_arcade_gateway.py`,
`eval_stdio_mcp_server.py`, `eval_http_mcp_server.py`,
`eval_comprehensive_comparison.py` with timeouts, error handling, and
track-based comparisons; detailed `README.md`
> - **CLI runner**: `arcade_cli/evals_runner.py` to execute
evals/capture in parallel with progress, error isolation, failed-only
filtering, context inclusion, and multi-provider/model support
> - **Output formatters**: `arcade_cli/formatters/` (txt, md, html,
json) for evals and capture; comparative and multi-model HTML with tabs
and context rendering
> - **Display refactor**: `display.py` now supports writing multiple
formats, failed-only disclaimers, include-context, and improved console
summaries
> 
> <sup>Written by [Cursor
Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit
ff8acf9c34a6b61462a019a1ee9df081006517d0. This will update automatically
on new commits. Configure
[here](https://cursor.com/dashboard?tab=bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Francisco Liberal <francisco@arcade.dev>
Co-authored-by: Mateo Torres <torresmateo@gmail.com>
2026-01-07 20:26:23 -03:00

290 lines
11 KiB
Python

"""Additional edge case tests for formatters to ensure robustness."""
from arcade_cli.formatters import (
HtmlFormatter,
JsonFormatter,
MarkdownFormatter,
TextFormatter,
)
class MockEvaluation:
"""Mock EvaluationResult for testing."""
def __init__(
self,
passed: bool = True,
warning: bool = False,
score: float = 1.0,
failure_reason: str | None = None,
results: list[dict] | None = None,
):
self.passed = passed
self.warning = warning
self.score = score
self.failure_reason = failure_reason
self.results = results or []
def make_empty_results() -> list[list[dict]]:
"""Create empty evaluation results."""
return [[{"model": "gpt-4o", "suite_name": "empty_suite", "rubric": "Test", "cases": []}]]
class TestFormatterEdgeCases:
"""Test edge cases that might not be covered elsewhere."""
def test_empty_results_all_formatters(self) -> None:
"""All formatters should handle empty results gracefully."""
results = make_empty_results()
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
output = formatter.format(results)
assert output # Should produce some output
assert "0" in output or "Total: 0" in output.lower() or '"total_cases": 0' in output
def test_failed_only_with_zero_original_total(self) -> None:
"""Should handle original_counts with zero total without crashing."""
results = make_empty_results()
# Edge case: original_counts with 0 total (shouldn't happen in practice but should be safe)
original_counts = (0, 0, 0, 0)
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
# Should not raise ZeroDivisionError
output = formatter.format(results, failed_only=True, original_counts=original_counts)
assert output # Should produce some output
def test_failed_only_with_empty_results_but_nonzero_original(self) -> None:
"""Should handle case where filtered results are empty but original had cases."""
results = make_empty_results()
# All cases were filtered out, but there were originally 5 cases (all passed)
original_counts = (5, 5, 0, 0)
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
output = formatter.format(results, failed_only=True, original_counts=original_counts)
assert output
# Should show original counts
assert "5" in output
def test_all_formatters_handle_none_original_counts(self) -> None:
"""All formatters should handle None original_counts gracefully."""
results = [[{
"model": "gpt-4o",
"suite_name": "test",
"rubric": "Test",
"cases": [{
"name": "test_case",
"input": "test",
"evaluation": MockEvaluation(passed=False, score=0.0),
}],
}]]
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
# Should not crash with None original_counts
output = formatter.format(results, failed_only=True, original_counts=None)
assert output
def test_comparative_with_missing_track_data(self) -> None:
"""Comparative formatters should handle missing track gracefully."""
# Create comparative result where one track is missing data
results = [[
{
"model": "gpt-4o",
"suite_name": "Test Suite [track_a]",
"track_name": "track_a",
"rubric": None,
"cases": [{
"name": "test_case",
"input": "test",
"evaluation": MockEvaluation(passed=True, score=1.0),
}],
},
{
"model": "gpt-4o",
"suite_name": "Test Suite [track_b]",
"track_name": "track_b",
"rubric": None,
"cases": [], # Empty cases for this track
},
]]
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
output = formatter.format(results)
assert output
# Should mention both tracks
assert "track_a" in output
assert "track_b" in output
def test_html_formatter_escapes_all_special_chars(self) -> None:
"""HTML formatter must escape all special characters to prevent XSS."""
results = [[{
"model": "gpt-4o<script>alert('xss')</script>",
"suite_name": "Suite & Test",
"rubric": "Test",
"cases": [{
"name": "<img src=x onerror=alert(1)>",
"input": "test' OR '1'='1",
"evaluation": MockEvaluation(
passed=False,
score=0.0,
failure_reason="Error: <script>malicious</script>",
),
}],
}]]
formatter = HtmlFormatter()
output = formatter.format(results)
# Should NOT contain raw script tags or other unescaped HTML
assert "<script>" not in output
assert "onerror" not in output or "&" in output # Should be escaped
# Should contain escaped versions
assert "&lt;script&gt;" in output or "&lt;" in output
assert "&amp;" in output # & should be escaped
def test_json_formatter_produces_valid_json_for_all_cases(self) -> None:
"""JSON formatter must always produce valid JSON."""
import json
test_cases = [
make_empty_results(),
[[{
"model": "test",
"suite_name": "test",
"rubric": None,
"cases": [{
"name": "test",
"input": "test with \"quotes\" and \n newlines",
"evaluation": MockEvaluation(passed=True),
}],
}]],
]
formatter = JsonFormatter()
for results in test_cases:
output = formatter.format(results)
# Should be valid JSON (this will raise if invalid)
parsed = json.loads(output)
assert isinstance(parsed, dict)
assert "summary" in parsed
def test_formatters_with_suite_name_none(self) -> None:
"""Formatters should handle None suite_name gracefully."""
results = [[{
"model": "gpt-4o",
"suite_name": None, # Explicitly None
"rubric": "Test",
"cases": [{
"name": "test_case",
"input": "test",
"evaluation": MockEvaluation(passed=True),
}],
}]]
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
output = formatter.format(results)
assert output
# Should use fallback name
assert "Unnamed Suite" in output or "unnamed" in output.lower()
def test_pass_rate_calculation_edge_cases(self) -> None:
"""Test pass rate calculation in various edge cases."""
# Case 1: All passed
results_all_passed = [[{
"model": "gpt-4o",
"suite_name": "test",
"rubric": "Test",
"cases": [
{"name": f"case_{i}", "input": "test", "evaluation": MockEvaluation(passed=True)}
for i in range(5)
],
}]]
# Case 2: All failed
results_all_failed = [[{
"model": "gpt-4o",
"suite_name": "test",
"rubric": "Test",
"cases": [
{"name": f"case_{i}", "input": "test", "evaluation": MockEvaluation(passed=False, score=0.0)}
for i in range(5)
],
}]]
formatter = JsonFormatter()
# All passed should show 100% pass rate
output_passed = formatter.format(results_all_passed)
assert "100" in output_passed or "100.0" in output_passed
# All failed should show 0% pass rate
output_failed = formatter.format(results_all_failed)
assert '"pass_rate": 0' in output_failed or '"pass_rate": 0.0' in output_failed
def test_comparative_with_none_evaluation(self) -> None:
"""Comparative formatters should handle None evaluation gracefully."""
# Simulate a track result with missing evaluation (edge case)
# This could happen if there was an error during evaluation
# Note: In real usage, group_comparative_by_case would build the tracks dict
# from cases, so we need to test this at the formatting level where
# the track might not have evaluation data
results = [[
{
"model": "gpt-4o",
"suite_name": "Test Suite [track_a]",
"track_name": "track_a",
"rubric": None,
"cases": [{
"name": "test_case",
"input": "test",
"evaluation": MockEvaluation(passed=True, score=1.0, results=[
{
"field": "test",
"match": True,
"score": 1.0,
"weight": 1.0,
"expected": "test",
"actual": "test",
}
]),
}],
},
# track_b exists but has no cases (edge case where data is missing)
]]
# All formatters should handle missing track data without crashing
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
output = formatter.format(results)
# Should produce output
assert output
# Should show the track that exists
assert "track_a" in output or "Track" in output or "test_case" in output
def test_comparative_with_no_results_in_evaluation(self) -> None:
"""Comparative formatters should handle evaluation without results field."""
results = [[
{
"model": "gpt-4o",
"suite_name": "Test Suite [track_a]",
"track_name": "track_a",
"rubric": None,
"cases": [{
"name": "test_case",
"input": "test",
"evaluation": MockEvaluation(passed=True, score=1.0, results=[]), # Empty results
}],
},
]]
for formatter_class in [TextFormatter, MarkdownFormatter, HtmlFormatter, JsonFormatter]:
formatter = formatter_class()
# Should not crash with empty results
output = formatter.format(results, show_details=True)
assert output