Skip to main content
Glama
README.md
# V5 - Weiwu Render Service

> Powerful server-side rendering service for charts, tables, KPI metrics, and combined reports — TypeScript OOP version with MCP AI integration

## Features

### Core Capabilities

- **Chart Rendering** — Based on G2-SSR, supporting 12 chart types
  - `bar` / `column` — horizontal/vertical bar charts, multi-metric support
  - `line` / `area` — trend charts, multi-series support
  - `pie` — proportion/donut chart
  - `scatter` — correlation plot with group dimension
  - `radar` — multi-dimension comparison
  - `waterfall` — cumulative change (finance / P&L bridge)
  - `funnel` — conversion funnel, auto-sorted descending
  - `heatmap` — density matrix over two categorical axes
  - `dualaxis` — bar + line combo with two y-axes
  - `gauge` — KPI progress ring vs target

- **Table Rendering** — Office-style HTML tables
  - Simple mode / Excel-like mode
  - Cell merging (auto / manual)

- **KPI Metric Cards** — HTML dashboard cards
  - Single or multi-card layout
  - Auto colour-coded change indicator (↑ green / ↓ red / — grey)
  - Period comparison with percentage change

- **Combined Reports** — One-stop generation of tables + charts + text

### Technical Highlights

| Feature | Description |
|---------|-------------|
| **TypeScript** | Complete type definitions, intelligent autocompletion |
| **Object-Oriented** | Factory pattern, inheritance, encapsulation |
| **Type Safety** | Compile-time error checking |
| **Modular Design** | Clear responsibilities, easy to extend |
| **MCP Integration** | AI-callable tools via Model Context Protocol |
| **Zero Frontend Dependencies** | Server-side rendering, outputs complete HTML/PNG |

## Quick Start

### 1. Install dependencies

```bash
npm install
```

> `check:env` runs automatically after install. It detects your platform, Node version,
> and Canvas status, then prints specific installation guidance.

### 2. Install Canvas (chart rendering)

Canvas is required for chart output. Tables and metric cards work without it.

| Platform | Command |
|----------|---------|
| **Windows** | Install [GTK3 Runtime](https://github.com/tschoonj/GTK-for-Windows-Runtime-Environment-Installer), then `npm run install:canvas` |
| **macOS** | `brew install pkg-config cairo pango libjpeg-turbo giflib librsvg && npm rebuild canvas` |
| **Linux (Debian/Ubuntu)** | `sudo apt-get install libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev && npm rebuild canvas` |
| **Linux (CentOS/RHEL)** | `sudo yum install cairo-devel pango-devel libjpeg-turbo-devel && npm rebuild canvas` |
| **Tables/metrics only** | `npm install --ignore-scripts` (skip Canvas entirely) |

`npm run install:canvas` auto-detects your Node ABI and downloads the matching
prebuilt binary from the node-canvas releases page. See [`scripts/README.md`](scripts/README.md)
for full details and troubleshooting.

### 3. Set up font for CJK support (optional)

Chart labels are rendered by Canvas using the font registered at startup.
Without a Unicode font, **CJK characters (Chinese/Japanese/Korean) appear as empty boxes**.

Place any `.ttf` file in the `fonts/` directory — the filename does not matter,
V5 picks the first one it finds:

```bash
mkdir -p fonts
cp /path/to/your/font.ttf fonts/
```

Recommended free fonts with full CJK coverage:

| Font | License | Download |
|------|---------|----------|
| **Noto Sans CJK** | SIL Open Font License | https://github.com/notofonts/noto-cjk/releases |
| **Source Han Sans** | SIL Open Font License | https://github.com/adobe-fonts/source-han-sans/releases |

> **Note**: `fonts/` is excluded from version control (`.gitignore`).
> Each deployment must supply its own font file.
> If `fonts/` is empty, V5 falls back to system fonts — Latin text renders
> correctly, CJK characters may appear as boxes on servers without CJK system fonts.

### 4. Build & run

```bash
npm run build    # compile TypeScript (output: dist/)
npm start        # HTTP server on port 3001
npm test         # run tests
```

## API Documentation

### 1. Health Check

```http
GET /health
```

**Response**:
```json
{
  "status": "ok",
  "service": "v5",
  "version": "1.0.0",
  "description": "Weiwu Render Service (TypeScript)",
  "supportedCharts": ["bar", "column", "line", "pie", "area", "scatter", "radar",
                      "waterfall", "funnel", "heatmap", "dualaxis", "gauge"]
}
```

---

### 2. Chart Rendering

```http
POST /
Content-Type: application/json

{
  "type": "chart",
  "data": {
    "chartType": "column",
    "axis": [
      { "type": "x", "value": "month", "name": "Month" },
      { "type": "y", "value": "amount", "name": "Amount" }
    ],
    "data": [
      { "month": "Jan", "amount": 1000 },
      { "month": "Feb", "amount": 1500 }
    ],
    "width": 640,
    "height": 480
  },
  "output": "base64"
}
```

**Response**:
```json
{
  "success": true,
  "base64": "iVBORw0KGgo...",
  "format": "png",
  "width": 640,
  "height": 480
}
```

---

### 3. Table Rendering

```http
POST /
Content-Type: application/json

{
  "type": "table",
  "data": {
    "title": "Sales Data",
    "columns": [
      { "field": "product", "name": "Product" },
      { "field": "sales",   "name": "Sales"   }
    ],
    "rows": [
      { "product": "Product A", "sales": 10000 },
      { "product": "Product B", "sales": 8500  }
    ]
  },
  "template": "excel-like"
}
```

#### Cell Merging

```json
{ "mergeConfig": { "type": "auto",   "fields": ["region"] } }
{ "mergeConfig": { "type": "manual", "cells": [{ "row": 0, "col": 0, "rowSpan": 2, "colSpan": 1 }] } }
```

---

### 4. KPI Metric Cards

```http
POST /
Content-Type: application/json

{
  "type": "metric",
  "data": {
    "title": "Q1 Summary",
    "items": [
      {
        "title": "Total Sales",
        "value": 128500,
        "unit": "USD",
        "previousValue": 112000,
        "compareLabel": "vs last quarter"
      },
      { "title": "Orders", "value": 3420, "previousValue": 3100 }
    ],
    "columns": 2
  }
}
```

**Response**:
```json
{ "success": true, "html": "<!DOCTYPE html>...", "format": "html", "itemCount": 2 }
```

---

### 5. Combined Report

```http
POST /
Content-Type: application/json

{
  "type": "report",
  "data": {
    "title": "Sales Report",
    "tables": [...],
    "charts": [...]
  }
}
```

## TypeScript Usage

```typescript
import { V5Service } from 'v5';

const service = new V5Service();

// Chart
const result = await service.render({
  type: 'chart',
  data: {
    chartType: 'column',
    axis: [
      { type: 'x', value: 'month', name: 'Month' },
      { type: 'y', value: 'amount', name: 'Amount' }
    ],
    data: [{ month: 'Jan', amount: 1000 }, { month: 'Feb', amount: 1500 }]
  },
  output: 'base64'
});

// KPI metrics
const metricResult = await service.render({
  type: 'metric',
  data: {
    items: [{ title: 'Revenue', value: 128500, unit: 'USD', previousValue: 112000 }]
  }
});
```

## AI Integration

V5 provides two complementary AI integration mechanisms:

### Agent Skill (Behavioral Guidance)

The `skills/SKILL.md` file provides comprehensive instructions for AI agents:
- **When** to use V5 capabilities
- **How** to configure each chart type and axis mapping
- **What** quality standards to meet

### MCP Server (Tool Interface)

The MCP server (`mcp/server.ts`) exposes V5 as callable tools via the Model Context Protocol.
All render tools **save output to a file** and return the file path.

| Tool | Output | Description |
|------|--------|-------------|
| `render_chart` | PNG file | Render any of the 12 chart types |
| `render_table` | HTML file | Render table with optional cell merging |
| `render_metric` | HTML file | Render KPI metric cards |
| `render_report` | HTML file | Generate combined table + chart report |
| `get_supported_chart_types` | JSON text | List all supported chart types |

**`outputPath` parameter** (all render tools): absolute path to save the output file.
If omitted, the file is saved to the system temp directory and the path is returned.

#### MCP Configuration

Build first, then add to your `.mcp.json` (project-level) or Claude Code settings:

```bash
npm run build
```

```json
{
  "mcpServers": {
    "v5-render": {
      "command": "node",
      "args": ["/absolute/path/to/v5/dist/mcp/server.js"]
    }
  }
}
```

## Architecture

```
V5Service
    ├── ChartRendererFactory
    │   └── ChartRenderer (abstract)
    │       ├── Bar / Column / Line / Area / Pie
    │       ├── Scatter / Radar
    │       └── Waterfall / Funnel / Heatmap / DualAxis / Gauge
    ├── TableRenderer
    ├── MetricRenderer
    └── ReportRenderer
```

## License

MIT