Skip to content

AndrewPrimi/Excel-Agent

Repository files navigation

Chart Generation System

A streamlined chart generation system with conversational AI interface:

  1. Chart MCP Server - Provides chart generation tools via MCP protocol
  2. Chart Agent - Conversational AI agent (DeepSeek-V3) that uses MCP tools
  3. Visualization Module - Matplotlib-based chart rendering

⚡ Quick Start: See QUICKSTART.md for the fastest way to get started!

Architecture

┌──────────────────────────────────────────────────────────┐
│                    User Input (CLI)                      │
│            "Create a bar chart of sales data"            │
└────────────────────────┬─────────────────────────────────┘
                         ▼
              ┌──────────────────────┐
              │   Chart Agent        │
              │   (DeepSeek-V3)      │
              │   - No embedded tools│
              │   - Pure AI reasoning│
              └──────────┬───────────┘
                         │
                         │ MCP Protocol (HTTP)
                         ▼
              ┌──────────────────────┐
              │   Chart MCP Server   │
              │   Port: 8000         │
              │   - generate_chart   │
              └──────────┬───────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │   Chart Visualizer   │
              │   (Matplotlib)       │
              └──────────┬───────────┘
                         │
                         ▼
              ┌──────────────────────┐
              │   PNG Chart Files    │
              │ ./generated_charts/  │
              └──────────────────────┘

Features

Phase 1: Custom MCP Server (Chart-Only)

  • ✅ Minimal FastMCP-based server focused solely on chart generation
  • /chart command handler with structured payload formatting
  • ✅ HTTP communication with Chart Agent

Phase 2: AI Agent Integration

  • ✅ Pydantic AI agent for intelligent chart analysis
  • ✅ Precise Pydantic request/response models
  • ✅ FastAPI endpoint for receiving MCP requests

Phase 3: Visualization Module

  • ✅ Data parsing for both single-series and multi-series data
  • ✅ Chart generation using Matplotlib
  • ✅ Support for bar, line, pie, scatter, area, and histogram charts
  • ✅ Configurable styling (dimensions, colors, legends, grid)
  • ✅ Automatic file saving to accessible location

Phase 4: End-to-End Integration

  • ✅ MCP server sends HTTP requests to AI Agent
  • ✅ Response handling with chart path display
  • ✅ System validation tests

Phase 5: Documentation

  • ✅ Comprehensive README files
  • ✅ Configuration examples
  • ✅ Integration test suite

Quick Start

Prerequisites

  • Python 3.10 or higher
  • pip package manager

Installation

  1. Clone or navigate to the project directory:
cd "/Users/aprim/Documents/CodeFolder/Excel Agent"
  1. Create and activate a virtual environment:
python -m venv venv
source venv/bin/activate  # On macOS/Linux
# or
venv\Scripts\activate  # On Windows
  1. Install dependencies:
# Install Chart Agent dependencies
pip install -r ChartAgent/requirements.txt

# Install Chart MCP dependencies
cd ChartMCP && pip install -e . && cd ..
  1. Configure environment variables:
cp .env.example .env
# Edit .env and add your OPEN_ROUTER_API_KEY

Running the System

📖 See QUICKSTART.md for detailed instructions and examples!

Option 1: Simple Manual Startup (Recommended)

Terminal 1 - Start MCP Server:

cd ChartMCP
python start_mcp.py

Terminal 2 - Start Chart Agent:

cd ChartAgent
python agent.py

Option 2: Using Automation Script

./start_chart_system.sh

This will:

  • Start the MCP server in the background
  • Launch the chart agent CLI
  • Auto-cleanup when you exit

Option 3: Using Module Syntax

Terminal 1 - MCP Server:

cd ChartMCP
python -m src.chart_mcp

Terminal 2 - Chart Agent:

cd ChartAgent
python agent.py

Testing

Run the integration tests:

python test_integration.py

This will test:

  • Health checks
  • Direct chart generation
  • Multi-series charts
  • AI analysis
  • All chart types

Usage

Via MCP Server

The Chart MCP Server exposes a generate_chart tool:

{
    "chart_type": "bar",
    "title": "Monthly Sales",
    "data_json": '[{"label": "Jan", "value": 1000}, {"label": "Feb", "value": 1500}]',
    "x_label": "Month",
    "y_label": "Sales ($)",
    "width": 10,
    "height": 6,
    "show_legend": true,
    "show_grid": true
}

Via Direct API

Single-series bar chart:

curl -X POST http://localhost:8001/generate-chart \
  -H "Content-Type: application/json" \
  -d '{
    "chart_type": "bar",
    "title": "Sales Data",
    "data": [
      {"label": "Q1", "value": 1000},
      {"label": "Q2", "value": 1500},
      {"label": "Q3", "value": 1800},
      {"label": "Q4", "value": 2200}
    ],
    "x_label": "Quarter",
    "y_label": "Sales ($)"
  }'

Multi-series line chart:

curl -X POST http://localhost:8001/generate-chart \
  -H "Content-Type: application/json" \
  -d '{
    "chart_type": "line",
    "title": "Revenue Comparison",
    "series": [
      {
        "name": "2023",
        "data": [
          {"label": "Q1", "value": 1000},
          {"label": "Q2", "value": 1500},
          {"label": "Q3", "value": 1800},
          {"label": "Q4", "value": 2200}
        ]
      },
      {
        "name": "2024",
        "data": [
          {"label": "Q1", "value": 1200},
          {"label": "Q2", "value": 1700},
          {"label": "Q3", "value": 2000},
          {"label": "Q4", "value": 2500}
        ]
      }
    ],
    "x_label": "Quarter",
    "y_label": "Revenue ($)"
  }'

Project Structure

Excel Agent/
├── ChartMCP/                  # MCP Server
│   ├── src/chart_mcp/
│   │   ├── __init__.py
│   │   ├── __main__.py
│   │   ├── server.py          # FastMCP server with tools
│   │   ├── config.py          # Configuration
│   │   ├── models.py          # Data models
│   │   └── visualizer.py      # Matplotlib chart generation
│   ├── start_mcp.py           # Simple launcher (NEW!)
│   ├── pyproject.toml
│   └── README.md
│
├── ChartAgent/                # AI Agent (Conversational CLI)
│   ├── __init__.py
│   ├── agent.py               # Main agent with MCP integration
│   ├── requirements.txt
│   └── README.md
│
├── generated_charts/          # Output directory for charts
├── test_integration.py        # Integration tests
├── start_chart_system.sh      # Automated startup script
├── .env                       # Environment configuration
├── .env.example               # Configuration template
├── QUICKSTART.md              # Quick start guide (NEW!)
├── CLAUDE.md                  # Project evaluation
└── README.md                  # This file

Key Changes (Phase 6 Cleanup):

  • ❌ Removed FastAPI server from ChartAgent (no longer needed)
  • ❌ Removed embedded tools from agent.py
  • ❌ Removed duplicate visualizer and models from ChartAgent
  • ✅ Added start_mcp.py for simple server startup
  • ✅ Agent now uses ONLY MCP server tools

Configuration

Environment Variables

Create a .env file based on .env.example:

# Chart Agent Configuration
OPEN_ROUTER_API_KEY=your-api-key-here
LLM_MODEL=openai/gpt-4-turbo-preview
CHART_OUTPUT_DIR=./generated_charts
AGENT_SERVER_HOST=0.0.0.0
AGENT_SERVER_PORT=8001
LOG_LEVEL=INFO
DEFAULT_DPI=100
DEFAULT_FORMAT=png

# Chart MCP Server Configuration
CHART_AGENT_URL=http://localhost:8001/generate-chart
MCP_SERVER_PORT=8000
MCP_SERVER_HOST=0.0.0.0

Supported Chart Types

Type Description Best For
bar Bar chart Comparing categories
line Line chart Trends over time
pie Pie chart Proportions/percentages
scatter Scatter plot Relationships between variables
area Area chart Cumulative data over time
histogram Histogram Distribution of values

API Reference

Chart Agent Endpoints

GET /health

Health check endpoint.

POST /generate-chart

Generate a chart from structured data.

Request: ChartRequest (see models) Response: ChartResponse with file path

POST /generate-chart-with-analysis

Generate a chart and get AI insights.

Response: Chart response + AI analysis

Data Models

ChartRequest

{
  "chart_type": str,          # Required: bar, line, pie, scatter, area, histogram
  "title": str,               # Required: Chart title
  "data": List[ChartDataPoint],     # Optional: Single-series data
  "series": List[ChartDataSeries],  # Optional: Multi-series data
  "x_label": str,             # Optional: X-axis label
  "y_label": str,             # Optional: Y-axis label
  "width": int,               # Optional: Width in inches (default: 10)
  "height": int,              # Optional: Height in inches (default: 6)
  "show_legend": bool,        # Optional: Show legend (default: true)
  "show_grid": bool           # Optional: Show grid (default: true)
}

ChartResponse

{
  "success": bool,            # Whether generation succeeded
  "chart_path": str,          # File path to generated chart
  "error": str,               # Error message if failed
  "metadata": {               # Additional information
    "chart_type": str,
    "data_points": int,
    "file_size_bytes": int,
    "dimensions": str,
    "format": str
  }
}

Development

Running Tests

# Start servers first (in separate terminals)
python -m ChartAgent
python -m chart_mcp

# Run integration tests
python test_integration.py

Adding New Chart Types

  1. Add enum to models.py:
class ChartType(str, Enum):
    NEW_TYPE = "new_type"
  1. Implement generator in visualizer.py:
def generate_new_type_chart(self, request: ChartRequest) -> str:
    # Implementation
    pass
  1. Register in generate_chart() method:
chart_generators = {
    ChartType.NEW_TYPE: self.generate_new_type_chart,
}

Troubleshooting

"HTTP client not initialized"

  • Ensure the MCP server is fully started
  • Check logs for initialization errors

"Failed to connect to AI Agent"

  • Verify Chart Agent is running on port 8001
  • Check CHART_AGENT_URL in configuration

Charts not generating

  • Check CHART_OUTPUT_DIR exists and is writable
  • Verify Matplotlib is installed correctly
  • Review logs in chart_agent.log

API Key Errors

  • Ensure OPEN_ROUTER_API_KEY is set in .env
  • Verify API key is valid and has credits

License

This project is for educational and development purposes.

Credits

  • FastMCP: MCP server framework
  • Pydantic AI: AI agent framework
  • FastAPI: Web framework
  • Matplotlib: Visualization library

About

Built an Agent that connects to an Excel MCP server and utilizes a create chart tool that an LLM uses prompt the user to create charts

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors