arcade-mcp/libs/arcade-evals/arcade_evals/_evalsuite/_providers.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

151 lines
6.3 KiB
Python

"""Provider abstractions and message conversion utilities.
This module contains:
- ProviderName type for supported LLM providers
- Message conversion utilities for different provider formats
Anthropic has different message format requirements than OpenAI:
- Only "user" and "assistant" roles (system is a separate parameter)
- tool_use/tool_result content blocks instead of tool_calls/tool role
"""
from __future__ import annotations
import json
import logging
from typing import Any, Literal
logger = logging.getLogger(__name__)
# Supported LLM providers for evaluations
ProviderName = Literal["openai", "anthropic"]
def convert_messages_to_anthropic(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""
Convert OpenAI-format messages to Anthropic format.
Anthropic only supports "user" and "assistant" roles (system is a separate parameter).
Key differences handled:
- "system" -> skipped (handled separately in Anthropic API)
- "user" -> "user" (pass through)
- "assistant" -> "assistant" (pass through)
- "assistant" with "tool_calls" -> "assistant" with tool_use content blocks
- "tool" -> "user" with tool_result content block
- "function" (legacy) -> "user" with tool_result content block
Args:
messages: List of OpenAI-format messages
Returns:
List of Anthropic-format messages
"""
anthropic_messages: list[dict[str, Any]] = []
for msg in messages:
role = msg.get("role", "")
if role == "system":
# Skip system messages - Anthropic API takes system as a separate parameter.
# In _run_anthropic(), we pass system=case.system_message to client.messages.create().
# This is the correct approach per Anthropic's API design.
continue
elif role == "user":
# User messages convert directly
content = msg.get("content", "")
if content:
anthropic_messages.append({"role": "user", "content": content})
elif role == "assistant":
if "tool_calls" in msg and msg.get("tool_calls"):
# Convert OpenAI tool_calls to Anthropic tool_use blocks
# Anthropic supports mixed content: text blocks + tool_use blocks
content_blocks: list[dict[str, Any]] = []
# Include text content if present (assistant can say something before using tools)
text_content = msg.get("content")
if text_content:
content_blocks.append({"type": "text", "text": text_content})
# Add tool_use blocks
for tool_call in msg.get("tool_calls", []):
function = tool_call.get("function")
if not function:
continue # Skip malformed tool calls
# Parse arguments JSON
arguments_str = function.get("arguments", "{}")
try:
arguments = json.loads(arguments_str) if arguments_str else {}
except json.JSONDecodeError as e:
logger.warning(
"Failed to parse tool arguments JSON for '%s': %s. Using empty dict.",
function.get("name", "unknown"),
e,
)
arguments = {}
content_blocks.append({
"type": "tool_use",
"id": tool_call.get("id", ""),
"name": function.get("name", ""),
"input": arguments,
})
if content_blocks:
anthropic_messages.append({"role": "assistant", "content": content_blocks})
else:
# Regular assistant message (no tool calls)
content = msg.get("content", "")
if content:
anthropic_messages.append({"role": "assistant", "content": content})
elif role == "tool":
# Convert OpenAI tool response to Anthropic tool_result block
tool_result_block = {
"type": "tool_result",
"tool_use_id": msg.get("tool_call_id", ""),
"content": msg.get("content", ""),
}
# Batch consecutive tool results into the last user message
if anthropic_messages and anthropic_messages[-1]["role"] == "user":
# Add to existing user message's content array
last_content = anthropic_messages[-1]["content"]
if isinstance(last_content, list):
last_content.append(tool_result_block)
else:
# Convert string content to array with both blocks
anthropic_messages[-1]["content"] = [
{"type": "text", "text": last_content},
tool_result_block,
]
else:
# Start new user message with tool result
anthropic_messages.append({"role": "user", "content": [tool_result_block]})
elif role == "function":
# Legacy OpenAI function role (deprecated) - same as tool
tool_result_block = {
"type": "tool_result",
"tool_use_id": msg.get("name", ""), # function uses "name" not "tool_call_id"
"content": msg.get("content", ""),
}
# Batch consecutive tool results into the last user message
if anthropic_messages and anthropic_messages[-1]["role"] == "user":
# Add to existing user message's content array
last_content = anthropic_messages[-1]["content"]
if isinstance(last_content, list):
last_content.append(tool_result_block)
else:
# Convert string content to array with both blocks
anthropic_messages[-1]["content"] = [
{"type": "text", "text": last_content},
tool_result_block,
]
else:
# Start new user message with tool result
anthropic_messages.append({"role": "user", "content": [tool_result_block]})
return anthropic_messages