Skip to main content
Glama
Multi-API Benchmark MCP Server

Multi-API Benchmark MCP Server

by edujbarrios
README.md
# Multi-API Benchmark MCP Server

> A production-ready MCP server for benchmarking multiple model APIs concurrently, with a focus on free vision-capable models.

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Author**: Eduardo J. Barrios ([GitHub: @edujbarrios](https://github.com/edujbarrios))

---

## Overview

The Multi-API Benchmark MCP Server is a comprehensive benchmarking solution designed to test and compare vision-capable AI models across multiple providers simultaneously. Built with a focus on **free and free-tier APIs**, it enables developers and researchers to evaluate multimodal AI performance without incurring costs.

### Key Features

- šŸš€ **Concurrent Benchmarking**: Run tests across multiple providers and models in parallel
- šŸ–¼ļø **Vision Support**: Full support for image inputs (URLs, local files, base64)
- šŸ†“ **Free-Tier Focus**: MVP built around genuinely free APIs (llm7.io, Moondream)
- šŸ“Š **Comprehensive Metrics**: Track latency, tokens, costs, success rates, and responses
- šŸ’¾ **Persistent Storage**: SQLite-based storage for benchmark runs and results
- šŸ“¤ **Multiple Export Formats**: Export results as JSON, CSV, or Markdown
- šŸ”§ **MCP Integration**: Native Model Context Protocol support for Claude Desktop and Cursor
- ⚔ **Production-Ready**: Robust error handling, retries, timeouts, and logging

---

## Supported Providers (MVP)

The initial release focuses on **free vision-capable APIs**:

| Provider | Vision Support | Status | Notes |
|----------|---------------|--------|-------|
| **llm7.io** | āœ… Yes | Available | Free access to vision models including GPT-4o-mini, Claude 3.5 Sonnet |
| **Moondream** | āœ… Yes | Available | Specialized open vision model, free to use |

> **Future Expansion**: The architecture supports easy addition of new providers. Paid APIs  (OpenAI, Anthropic, Google, etc.) can be added later without code restructuring.

---

## Installation

### Prerequisites

- Python 3.10 or higher
- pip or uv package manager

### Setup

1. **Clone the repository**:
   ```bash
   git clone https://github.com/edujbarrios/multi-api-bench-mcp.git
   cd multi-api-bench-mcp
   ```

2. **Install dependencies**:
   ```bash
   pip install -e .
   # OR with uv:
   uv pip install -e .
   ```

3. **Configure environment**:
   ```bash
   cp .env.example .env
   ```
   
   Edit `.env` and add your API credentials:
   ```env
   LLM7_API_KEY=your_llm7_api_key_here
   MOONDREAM_API_KEY=your_moondream_key_if_needed
   ```

4. **Verify installation**:
   ```bash
   python -m pytest tests/
   ```

---

## Quick Start

### Running the MCP Server

```bash
python -m src.server.server
```

The server will start and communicate via stdio, ready to accept MCP tool calls.

### Basic Benchmark Example

Using the MCP `run_benchmark` tool:

```json
{
  "prompt": "What objects are visible in this image?",
  "image_urls": ["https://example.com/sample.jpg"],
  "providers": [
    {"provider": "llm7", "model": "gpt-4o-mini"},
    {"provider": "moondream", "model": "moondream-2"}
  ],
  "concurrency": 2,
  "timeout": 30
}
```

### Vision Benchmark Use Cases

- **OCR Testing**: Compare text extraction from receipts, documents, screenshots
- **Chart Analysis**: Test visual reasoning on graphs and data visualizations
- **UI Understanding**: Evaluate model comprehension of user interfaces
- **Receipt Processing**: Compare structured data extraction capabilities
- **Photo Description**: Test general image understanding and captioning

---

## MCP Tools

The server exposes 11 powerful tools via the Model Context Protocol:

### 1. `run_benchmark`
Run a benchmark with custom prompts and images against multiple providers.

**Parameters**:
- `prompt` (required): Text prompt to send
- `system_prompt` (optional): System-level instructions
- `image_urls` (optional): Array of image URLs
- `image_paths` (optional): Array of local file paths
- `providers` (required): Array of provider configs (provider, model, temperature, max_tokens)
- `concurrency` (optional): Concurrent request limit (default: 5)
- `timeout` (optional): Timeout per request in seconds (default: 30)
- `retries` (optional): Retry attempts (default: 2)
- `name` (optional): Name for this run
- `tags` (optional): Tags for categorization

**Returns**: Run ID and summary with latency, success rates, and responses

---

### 2. `run_benchmark_suite`
Execute a saved benchmark suite.

**Parameters**:
- `suite_id` (required): ID or name of the suite

**Returns**: Run summary with results across all cases

---

### 3. `list_providers`
List all configured providers and their availability status.

**Returns**: Provider names, status, vision support, API key configuration

---

### 4. `list_models`
List available models for a specific provider.

**Parameters**:
- `provider` (required): Provider name

**Returns**: Array of model identifiers

---

### 5. `save_benchmark_suite`
Save a reusable benchmark suite for repeated testing.

**Parameters**:
- `name` (required): Suite name
- `description` (optional): Description
- `cases` (required): Array of benchmark cases (prompt, images, tags)
- `providers` (required): Array of provider configurations

**Returns**: Suite ID

---

### 6. `list_benchmark_suites`
List all saved benchmark suites.

**Returns**: Array of suite summaries with IDs, names, and update times

---

### 7. `get_benchmark_run`
Retrieve detailed results from a previous benchmark run.

**Parameters**:
- `run_id` (required): Run identifier

**Returns**: Complete run data including all results, timings, and metadata

---

### 8. `list_benchmark_runs`
List recent benchmark runs with summaries.

**Parameters**:
- `limit` (optional): Maximum runs to return (default: 20)

**Returns**: Array of run summaries

---

### 9. `compare_runs`
Compare multiple benchmark runs side by side.

**Parameters**:
- `run_ids` (required): Array of run IDs to compare

**Returns**: Comparison analysis with best performers and provider statistics

---

### 10. `export_run`
Export a benchmark run to a file.

**Parameters**:
- `run_id` (required): Run ID
- `format` (required): Export format ('json', 'csv', 'markdown')
- `filename` (optional): Output filename

**Returns**: File path of exported data

---

### 11. `test_provider`
Test connectivity and configuration for a provider.

**Parameters**:
- `provider` (required): Provider name
- `model` (optional): Specific model to test

**Returns**: Connection test results

---

## Configuration

### Environment Variables

See `.env.example` for all configuration options:

```env
# Provider API Keys
LLM7_API_KEY=your_key_here
MOONDREAM_API_KEY=your_key_here

# Benchmark Defaults
DEFAULT_CONCURRENCY=5
DEFAULT_TIMEOUT=30
DEFAULT_RETRIES=2

# Storage
DATABASE_PATH=./benchmark_data.db

# Logging
LOG_LEVEL=INFO
LOG_FILE=./mcp-benchmark.log

# Export
EXPORT_DIR=./exports
```

---

## Claude Desktop Integration

Add to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json` on macOS):

```json
{
  "mcpServers": {
    "multi-api-bench": {
      "command": "python",
      "args": [
        "-m",
        "src.server.server"
      ],
      "cwd": "/absolute/path/to/multi-api-bench-mcp",
      "env": {
        "LLM7_API_KEY": "your_key_here",
        "MOONDREAM_API_KEY": "your_key_here"
      }
    }
  }
}
```

Restart Claude Desktop and the benchmark tools will be available.

---

## Cursor Integration

Add to your Cursor MCP settings (`.cursor/mcp.json`):

```json
{
  "mcpServers": {
    "multi-api-bench": {
      "command": "python",
      "args": ["-m", "src.server.server"],
      "cwd": "${workspaceFolder}/multi-api-bench-mcp",
      "env": {
        "LLM7_API_KEY": "${env:LLM7_API_KEY}",
        "MOONDREAM_API_KEY": "${env:MOONDREAM_API_KEY}"
      }
    }
  }
}
```

---

## Architecture

The project follows a modular, layered architecture:

```
src/
ā”œā”€ā”€ server/          # MCP server implementation
ā”œā”€ā”€ providers/       # Provider abstraction layer
│   ā”œā”€ā”€ base.py      # BaseProvider interface
│   ā”œā”€ā”€ llm7.py      # LLM7.io adapter
│   ā”œā”€ā”€ moondream.py # Moondream adapter
│   └── registry.py  # Provider registry
ā”œā”€ā”€ benchmarks/      # Benchmark orchestration
│   └── executor.py  # Concurrent execution logic
ā”œā”€ā”€ storage/         # SQLite persistence
│   └── database.py  # Database operations
ā”œā”€ā”€ schemas/         # Pydantic models
│   ā”œā”€ā”€ benchmark.py # Benchmark data models
│   └── provider.py  # Provider schemas
ā”œā”€ā”€ exports/         # Export and reporting
│   ā”œā”€ā”€ exporters.py # JSON/CSV/Markdown exporters
│   └── reports.py   # Comparison and analysis
ā”œā”€ā”€ config/          # Configuration management
│   └── settings.py  # Settings with env loading
└── utils/           # Utility functions
    └── helpers.py   # Common helpers
```

### Key Design Principles

1. **Provider Abstraction**: All providers implement `BaseProvider`, enabling easy addition of new APIs
2. **Async-First**: Full asyncio support with concurrency control
3. **Normalized Results**: Provider-specific responses normalized to common schema
4. **Graceful Degradation**: Partial failures don't break entire benchmark runs
5. **Type Safety**: Comprehensive Pydantic models for validation

---

## Adding New Providers

The architecture makes adding new providers straightforward:

1. **Create provider file** in `src/providers/`
2. **Inherit from `BaseProvider`**
3. **Implement required methods**:
   - `name`, `supports_vision`, `supports_system_prompt`, `default_model`
   - `list_models()`, `_make_request()`
4. **Register in `registry.py`**
5. **Add configuration** to `settings.py`

See `src/providers/llm7.py` or `src/providers/moondream.py` for examples.

---

## Example Benchmark Suite

Save this as `benchmark_suites/vision_ocr_suite.json`:

```json
{
  "name": "OCR and Document Vision Suite",
  "description": "Test vision models on text extraction and document understanding",
  "cases": [
    {
      "prompt": "Extract all visible text from this image",
      "image_urls": ["https://example.com/receipt.jpg"],
      "tags": ["ocr", "receipt"]
    },
    {
      "prompt": "What type of chart is this and what data does it show?",
      "image_urls": ["https://example.com/chart.png"],
      "tags": ["chart", "reasoning"]
    },
    {
      "prompt": "Describe the UI elements and layout of this screenshot",
      "image_urls": ["https://example.com/ui_screenshot.png"],
      "tags": ["ui", "layout"]
    }
  ],
  "providers": [
    {"provider": "llm7", "model": "gpt-4o-mini"},
    {"provider": "moondream", "model": "moondream-2"}
  ]
}
```

---

## Troubleshooting

### Provider Authentication Errors

**Issue**: `Provider authentication failed`

**Solution**:
1. Verify API keys in `.env` file
2. Check provider status with `test_provider` tool
3. Ensure no extra whitespace in API key values

### Image Loading Failures

**Issue**: `Invalid image file`

**Solution**:
1. Verify file exists and path is correct
2. Check image format (PNG, JPG, JPEG, WebP supported)
3. Ensure file is not corrupted (try opening manually)

### Timeout Errors

**Issue**: Requests timing out

**Solution**:
1. Increase timeout in configuration
2. Check internet connectivity
3. Verify provider service is operational

### Database Locked

**Issue**: `database is locked`

**Solution**:
1. Close any other processes accessing the database
2. Check file permissions
3. Consider using a different database path

---

## Security Considerations

- **API Keys**: Never commit `.env` file or expose credentials
- **Logging**: API keys are automatically masked in logs
- **Local Storage**: Benchmark data stored locally in SQLite
- **Network**: All provider requests use HTTPS
- **Input Validation**: Pydantic models validate all inputs

---

## Performance Tips

1. **Concurrency**: Adjust `DEFAULT_CONCURRENCY` based on provider rate limits
2. **Timeouts**: Set reasonable timeouts for vision models (30-60s recommended)
3. **Batching**: Use benchmark suites for efficient repeated testing
4. **Storage**: Periodically archive old benchmark data
5. **Exports**: Export large runs to files rather than keeping in memory

---

## Roadmap

### v0.2.0 (Planned)
- [ ] Add more free-tier providers (Replicate free models, HuggingFace Inference API)
- [ ] Web UI for visualizing benchmark results
- [ ] Streaming response support
- [ ] Advanced comparison analytics

### v0.3.0 (Planned)
- [ ] Paid provider support (OpenAI, Anthropic, Google)
- [ ] Cost optimization recommendations
- [ ] Automated provider health checks
- [ ] Benchmark scheduling

---

## Contributing

Contributions are welcome! Areas of interest:

- New free provider implementations
- Enhanced reporting and visualization
- Performance optimizations
- Test coverage improvements
- Documentation enhancements

Please open an issue before starting major changes.

---

## License

MIT License - see LICENSE file for details.

---

## Acknowledgments

- Built with [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol)
- Inspired by the need for comprehensive multimodal AI benchmarking
- Thanks to providers offering free API access for research and development

---

## Contact

**Eduardo J. Barrios**
- GitHub: [@edujbarrios](https://github.com/edujbarrios)
- Project: [multi-api-bench-mcp](https://github.com/edujbarrios/multi-api-bench-mcp)

For questions, issues, or contributions, please use GitHub Issues.

---

**Happy Benchmarking! šŸš€**