TinyPivot
OfficialLoads ClickHouse query results (via CLI export or piped stdin) into TinyPivot's interactive chart, pivot table, drill-through and data grid views.
Loads Databricks query results (via CLI export or piped stdin) into TinyPivot's interactive chart, pivot table, drill-through and data grid views.
Loads DuckDB query results into the data IDE (piping duckdb -csv output, or via load_file) and backs the embedded AI analyst's SQL querying over DuckDB WASM.
Loads MySQL query results (via CLI export or piped stdin) into TinyPivot's interactive chart, pivot table, drill-through and data grid views.
Loads PostgreSQL data into the data IDE and optionally runs AST-validated read-only queries directly through a built-in connector (Pro), with configurable database URL and allowed tables.
Provides a React <DataGrid /> component with Excel-like grid, pivot tables, chart builder, filtering, sorting, search, pagination, drill-through and CSV/Excel export for embedding in React apps.
Loads Snowflake query results (via CLI export or piped stdin) into TinyPivot's interactive chart, pivot table, drill-through and data grid views.
Loads SQLite query results (via CLI export or piped stdin) into TinyPivot's interactive chart, pivot table, drill-through and data grid views.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
TinyPivot
The Interactive Data IDE for AI Agents (MCP) — plus Lightweight React & Vue 3 Data Grids, Pivot Tables, Charts & Embedded AI Analyst.
TinyPivot MCP · Docs · Live Demo · Pricing · npm (@smallwebco/tinypivot-mcp)
⭐ If you find TinyPivot useful, please consider giving it a star! It helps others discover the project.
One Engine, Three Ways to Use TinyPivot
Who it's for | Package | What it does |
AI Users & Data Analysts |
| Interactive Charts, Pivot Tables, Terminal Cards, Live Ghostty TUI, Drill-Through & Excel inside Antigravity, Claude Code / Desktop (native Plugin), Cursor, OpenCode, Codex CLI & pi ( |
Frontend & SaaS Engineers |
| Lightweight Excel-like |
Product Teams | Embedded AI Data Analyst (BYOK) | Natural-language SQL querying inside your web app using your own OpenAI/Anthropic key over DuckDB WASM or Postgres |
Try the UI library online:

In-Agent Analytics (TinyPivot MCP App & Claude Plugin)
Turn any AI agent into a real Data IDE. Instead of reading truncated markdown tables, burning tokens re-prompting for chart tweaks, or trusting LLM arithmetic, @smallwebco/tinypivot-mcp renders an interactive Chart, Pivot Table, Drill-Through, and Data Grid directly inside your AI harness (Antigravity, Claude Code, Claude Desktop, Cursor, OpenCode, Codex CLI, pi, or any SEP-1865 MCP Apps client).
1-Command Multi-Harness Setup + Native Claude Plugin: Run
npx @smallwebco/tinypivot-mcp@latest initto auto-detect and configure all installed AI harnesses, or install the bundled Claude Code / Desktop plugin (.claude-plugin/plugin.json+.mcp.json+skills/tinypivot/SKILL.md).Screenshot-Ready Terminal Cards & Live Ghostty TUI: In terminal harnesses (Claude Code, Ghostty, OpenCode, pi, Codex CLI), TinyPivot prints crisp rounded-border Unicode charts (sub-block bars, stacked legends, 2x4 Braille line charts) and sparkline pivot tables directly in scrollback, supports direct stdin piping, and includes a live SSE-updating split-pane TUI (
npx @smallwebco/tinypivot-mcp@latest tui) plus localhost Companion Data IDE.Generous Free Tier (Core Charts Included): Free includes Core Charts (
bar,stackedBar,line,area,pie,donut), Basic Pivot (sum),Codetheme, Terminal Cards, Live Ghostty TUI, Companion Data IDE, and up to 2,500 rows (with unmistakable UI + LLM warnings whenever a larger dataset is truncated — never silent truncation).Real, Cache-Aware Token Savings:
load_file(and optional directquery_postgres) send only a ~200-token schema & summary to the LLM and stream full rows locally to the UI at 0 tokens — and every local click (Chart ↔ Pivot ↔ Data, sort, filter, drill-through) costs$0.Works With Any Database (Not Postgres-Only): Query BigQuery, Snowflake, MySQL, DuckDB, Databricks, SQLite, ClickHouse, or PostgreSQL via CLI export to
load_file, stdin pipe (... | tinypivot-mcp --open), or MCP/API piping toload_data(zero intermediate CSV needed for<500in-memory rows) — plus an optional AST-validated read-only direct PostgreSQL connector (query_postgreson Pro).Pro / Team (
$19/mo,$149/yr,$399Local Lifetime, or$79/moTeam 5-Seat): Unlocks unlimited rows, all 10 visual themes (Code,Phosphor,Nord,Thermal,Mono,Paper,Greenbar,1-Bit,Amber CRT,Green CRT), double-click Drill-Through, all 9+ aggregations, styled.xlsxexports, watermark-free UI/terminal cards, and optional directquery_postgres(uses dedicatedTP-MCP*keys).
Quick Setup for AI Harnesses
# 1. Auto-detect & wire Claude Code, Claude Desktop, Cursor, Antigravity, OpenCode, Codex CLI, and pi
npx @smallwebco/tinypivot-mcp@latest init
# 2. Or install as a native Claude Code plugin (includes .claude-plugin/plugin.json, .mcp.json & SKILL.md)
claude plugin install ./packages/mcp
# (or test for a single session without installing: claude --plugin-dir ./packages/mcp)
# 3. Attach the live Ghostty / split-pane TUI alongside your running AI agent
npx @smallwebco/tinypivot-mcp@latest tui
# 4. Or pipe any SQL CLI / CSV / JSON directly from stdin
duckdb -csv -c "SELECT * FROM 'sales.parquet'" | npx @smallwebco/tinypivot-mcp@latest --openPrivacy & Optional Env Vars: Row data, column names, SQL, and file paths never leave your machine. Disable minimal anonymous telemetry anytime with
TINYPIVOT_TELEMETRY=0orDO_NOT_TRACK=1. SetTINYPIVOT_LICENSE_KEYfor Pro/Team features and optionallyDATABASE_URL(+TINYPIVOT_ALLOWED_TABLES) for direct read-only PostgreSQL (query_postgres). See the full In-Agent Analytics (MCP) Guide andpackages/mcp/README.md.
Related MCP server: Unterm
Why TinyPivot?
Focused: A batteries-included analytics grid without adopting a broad enterprise suite
Free Pivot Tables: Sum aggregations, totals, and calculated fields included out of the box
Pro Upgrade: Advanced aggregations, charts, AI Data Analyst, and no watermark
AI Data Analyst (Pro): Natural language queries with BYOK — use your own OpenAI/Anthropic key
Framework Support: First-class Vue 3 and React packages
Lifetime License: No subscriptions — buy once, use forever
Features
Feature | Free | Pro |
Excel-like data grid | ✅ | ✅ |
Column filtering & sorting | ✅ | ✅ |
Global search | ✅ | ✅ |
CSV export | ✅ | ✅ |
Pagination | ✅ | ✅ |
Column resizing | ✅ | ✅ |
Clipboard (Ctrl+C) | ✅ | ✅ |
Dark mode | ✅ | ✅ |
Keyboard navigation | ✅ | ✅ |
Pivot table with Sum aggregation | ✅ | ✅ |
Row/column totals | ✅ | ✅ |
Calculated fields with formulas | ✅ | ✅ |
Pivot row group expand/collapse | ✅ | ✅ |
Axis value filters (filter row/column items) | ✅ | ✅ |
Pivot drill-through (double-click to inspect source rows) | ❌ | ✅ |
Excel (XLSX) Export (styled, multi-level pivot headers, lazy-loaded) | ❌ | ✅ |
AI Data Analyst (natural language queries, BYOK) | ❌ | ✅ |
Chart Builder (6 chart types, drag-and-drop) | ❌ | ✅ |
All aggregations (Count, Avg, Min, Max, Unique, Median, Std Dev, %) | ❌ | ✅ |
No watermark | ❌ | ✅ |
Installation
Vue 3
pnpm add @smallwebco/tinypivot-vueReact
pnpm add @smallwebco/tinypivot-reactQuick Start
Vue 3
<script setup lang="ts">
import { DataGrid } from '@smallwebco/tinypivot-vue'
import '@smallwebco/tinypivot-vue/style.css'
const data = [
{ id: 1, region: 'North', product: 'Widget A', sales: 12500, units: 150 },
{ id: 2, region: 'North', product: 'Widget B', sales: 8300, units: 95 },
{ id: 3, region: 'South', product: 'Widget A', sales: 15200, units: 180 },
{ id: 4, region: 'South', product: 'Widget B', sales: 9800, units: 110 },
]
</script>
<template>
<DataGrid
:data="data"
:enable-export="true"
:enable-search="true"
:enable-pagination="true"
:page-size="100"
:enable-column-resize="true"
:enable-clipboard="true"
theme="light"
export-filename="my-data.csv"
/>
</template>React
import { DataGrid } from '@smallwebco/tinypivot-react'
import '@smallwebco/tinypivot-react/style.css'
const data = [
{ id: 1, region: 'North', product: 'Widget A', sales: 12500, units: 150 },
{ id: 2, region: 'North', product: 'Widget B', sales: 8300, units: 95 },
{ id: 3, region: 'South', product: 'Widget A', sales: 15200, units: 180 },
{ id: 4, region: 'South', product: 'Widget B', sales: 9800, units: 110 },
]
export default function App() {
return (
<DataGrid
data={data}
enableExport={true}
enableSearch={true}
enablePagination={true}
pageSize={100}
enableColumnResize={true}
enableClipboard={true}
theme="light"
exportFilename="my-data.csv"
/>
)
}Props
Prop | Type | Default | Description |
|
| required | Array of data objects |
|
|
| Show loading spinner |
|
|
| Font size preset |
|
|
| Show pivot toggle |
|
|
| Show the Export dropdown menu (CSV free / Excel .xlsx Pro) |
|
|
| Show global search |
|
|
| Enable pagination |
|
|
| Rows per page |
|
|
| Drag to resize columns |
|
|
| Ctrl+C to copy cells |
|
|
| Color theme — see Theming for the full list (22 presets) |
|
|
| Number display format |
|
|
| Date display format |
|
|
| Override auto-detected chart field roles |
|
|
| Alternating row colors |
|
|
| CSV filename |
|
|
| Enable pivot row group expand/collapse chevrons |
|
|
| Enable double-click drill-through on pivot cells (Pro feature) |
|
|
| Row layout for multi-field pivots: |
Data Shape
TinyPivot accepts an array of flat objects. Each object represents a row, and keys become column headers.
// ✅ Correct - flat objects with consistent keys
const data = [
{ id: 1, name: 'Alice', sales: 1500, region: 'North' },
{ id: 2, name: 'Bob', sales: 2300, region: 'South' },
{ id: 3, name: 'Carol', sales: 1800, region: 'North' },
]
// ❌ Avoid - nested objects (won't display correctly)
const badData = [
{ id: 1, user: { name: 'Alice' }, metrics: { sales: 1500 } }
]Supported Value Types
Type | Example | Display |
|
| As-is |
|
| Formatted per |
|
|
|
|
| Empty cell |
|
| Formatted per |
Number & Date Formatting
Control how numbers and dates are displayed using the numberFormat and dateFormat props.
Number Formats
Format | Example | Description |
|
| US format with comma separators |
|
| European format with period separators |
|
| No formatting or separators |
Date Formats
Format | Example | Description |
|
| ISO 8601 (YYYY-MM-DD) |
|
| US format (MM/DD/YYYY) |
|
| European format (DD/MM/YYYY) |
Date columns also support date range filtering. When a column is detected as date type, the filter UI shows date range inputs (From/To) with the appropriate format placeholder.
<!-- Vue -->
<DataGrid :data="data" number-format="eu" date-format="eu" />{/* React */}
<DataGrid data={data} numberFormat="eu" dateFormat="eu" />Events
Vue
Event | Payload | Description |
|
| Cell clicked |
|
| Selection changed |
|
| CSV exported |
|
| Cells copied |
|
| Pivot row groups collapsed/expanded (array of collapsed path keys) |
|
| Pivot cell double-clicked and drill-through opened (Pro) |
<template>
<DataGrid
:data="data"
@cell-click="({ rowData }) => console.log(rowData)"
@export="({ rowCount }) => console.log(`Exported ${rowCount} rows`)"
/>
</template>React
Prop | Type | Description |
|
| Cell clicked |
|
| Selection changed |
|
| CSV exported |
|
| Cells copied |
|
| Pivot row groups collapsed/expanded |
|
| Pivot cell double-clicked and drill-through opened (Pro) |
<DataGrid
data={data}
onCellClick={({ rowData }) => console.log(rowData)}
onExport={({ rowCount }) => console.log(`Exported ${rowCount} rows`)}
/>Keyboard Shortcuts
Shortcut | Action |
| Copy selected cells |
| Focus search input |
| Navigate cells |
| Extend selection |
| Clear selection/search |
Aggregation Functions
TinyPivot includes 9 built-in aggregation functions plus support for custom calculations:
Function | Symbol | Description |
Sum | Σ | Total of all values |
Count | # | Number of values |
Average | x̄ | Mean of all values |
Min | ↓ | Minimum value |
Max | ↑ | Maximum value |
Unique | ◇ | Count of distinct values |
Median | M̃ | Middle value (outlier-resistant) |
Std Dev | σ | Standard deviation (spread measure) |
% of Total | %Σ | Percentage contribution to grand total |
Custom | ƒ | Your own aggregation function |
AI Data Analyst (Pro)
TinyPivot Pro includes an optional AI Data Analyst that lets users explore data using natural language. Ask questions like "What's the return rate by category?" or "Show me sales trends over time" and get instant SQL-generated results.

Want to try it? See the complete working example in
examples/ai-analyst-demo/with PostgreSQL backend and DuckDB WASM for client-side queries.
Requirements
To enable the AI Data Analyst, you need:
Pro License: Call
setLicenseKey('YOUR_LICENSE_KEY')at app startupAI Config: Pass the
aiAnalystprop withenabled: trueData Sources: For client-side data, configure
dataSourcesanddataSourceLoaderAPI Endpoint: A server endpoint to proxy AI requests (keeps your API key secure)
Key Benefits
Bring Your Own Key (BYOK): Use your own OpenAI, Anthropic, or OpenRouter API key — full control over costs and rate limits
Privacy-First: Your data never passes through TinyPivot servers
Natural Language: Ask questions in plain English — no SQL knowledge required for end users
Simple Setup: One endpoint handles everything
How It Works
User types a natural language question
AI generates a SQL query based on your data schema
Query executes against your data
Results display in the grid, ready for pivot/chart analysis
Cross-Table JOINs
The AI Analyst automatically understands relationships between your tables and can generate JOIN queries when needed. Ask questions like:
"Show me sales with customer names" (joins sales → customers)
"What products are selling best by category?" (joins sales → products)
"List orders with product details and customer info" (multi-table join)
The AI sees all available table schemas and identifies foreign key relationships (columns ending in _id) to construct proper JOINs.
Setup
Environment Variables
# .env
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
AI_API_KEY=sk-... # OpenAI, Anthropic, or OpenRouter key
# Optional: Override the default model
AI_MODEL=claude-sonnet-4-20250514The AI provider is auto-detected from your API key format:
sk-ant-...→ Anthropic (defaults toclaude-3-haiku-20240307)sk-or-...→ OpenRouter (defaults toanthropic/claude-3-haiku)sk-...→ OpenAI (defaults togpt-4o-mini)
Default models are cheap/fast. Set AI_MODEL for better quality.
Option A: PostgreSQL (Recommended)
One unified endpoint handles table discovery, schema, queries, and AI chat:
// Backend: app/api/tinypivot/route.ts (Next.js App Router)
import { createTinyPivotHandler } from '@smallwebco/tinypivot-server'
export const POST = createTinyPivotHandler({
tables: {
include: ['sales', 'customers', 'products'], // Only expose these tables
descriptions: {
sales: 'Sales transactions with revenue data',
}
}
})<!-- Frontend: Vue -->
<script setup lang="ts">
import { DataGrid, setLicenseKey } from '@smallwebco/tinypivot-vue'
import '@smallwebco/tinypivot-vue/style.css'
// Activate Pro license
setLicenseKey('YOUR_LICENSE_KEY')
const aiAnalystConfig = {
enabled: true,
endpoint: '/api/tinypivot',
}
</script>
<template>
<DataGrid
:data="[]"
:ai-analyst="aiAnalystConfig"
/>
</template>// Frontend: React
import { DataGrid, setLicenseKey } from '@smallwebco/tinypivot-react'
import '@smallwebco/tinypivot-react/style.css'
// Activate Pro license
setLicenseKey('YOUR_LICENSE_KEY')
function App() {
return (
<DataGrid
data={[]}
aiAnalyst={{ enabled: true, endpoint: '/api/tinypivot' }}
/>
)
}Option B: Client-Side Data (In-Memory)
For client-side data that's already loaded in the browser, you must configure dataSources and dataSourceLoader to make your data available to the AI Analyst:
<!-- Vue 3 -->
<script setup lang="ts">
import { ref } from 'vue'
import { DataGrid, setLicenseKey } from '@smallwebco/tinypivot-vue'
import '@smallwebco/tinypivot-vue/style.css'
// Activate Pro license
setLicenseKey('YOUR_LICENSE_KEY')
// Your data
const salesData = ref([
{ id: 1, region: 'North', product: 'Widget A', sales: 12500, units: 150 },
{ id: 2, region: 'South', product: 'Widget B', sales: 8300, units: 95 },
// ... more data
])
// Helper to infer schema from data
function inferSchema(data: Record<string, unknown>[]) {
if (!data.length) return []
const sample = data[0]
return Object.entries(sample).map(([name, value]) => ({
name,
type: typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'string',
}))
}
// AI Analyst configuration
const aiAnalystConfig = {
enabled: true, // Required: explicitly enable
endpoint: '/api/ai-chat', // Your AI proxy endpoint
dataSources: [ // Required: define available data sources
{
id: 'sales',
table: 'sales',
name: 'Sales Data',
description: 'Sales transactions with region, product, sales amount, and units',
},
],
dataSourceLoader: async (id: string) => { // Required: return data + schema
if (id === 'sales') {
return {
data: salesData.value,
schema: inferSchema(salesData.value),
}
}
throw new Error(`Unknown data source: ${id}`)
},
persistToLocalStorage: true, // Optional: save conversations
sessionId: 'my-session', // Optional: conversation ID
}
</script>
<template>
<DataGrid
:data="salesData"
:ai-analyst="aiAnalystConfig"
/>
</template>// React
import { useState } from 'react'
import { DataGrid, setLicenseKey } from '@smallwebco/tinypivot-react'
import '@smallwebco/tinypivot-react/style.css'
// Activate Pro license
setLicenseKey('YOUR_LICENSE_KEY')
function inferSchema(data: Record<string, unknown>[]) {
if (!data.length) return []
const sample = data[0]
return Object.entries(sample).map(([name, value]) => ({
name,
type: typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'string',
}))
}
function App() {
const [salesData] = useState([
{ id: 1, region: 'North', product: 'Widget A', sales: 12500, units: 150 },
{ id: 2, region: 'South', product: 'Widget B', sales: 8300, units: 95 },
// ... more data
])
const aiAnalystConfig = {
enabled: true,
endpoint: '/api/ai-chat',
dataSources: [
{
id: 'sales',
table: 'sales',
name: 'Sales Data',
description: 'Sales transactions with region, product, sales amount, and units',
},
],
dataSourceLoader: async (id: string) => {
if (id === 'sales') {
return {
data: salesData,
schema: inferSchema(salesData),
}
}
throw new Error(`Unknown data source: ${id}`)
},
persistToLocalStorage: true,
sessionId: 'my-session',
}
return (
<DataGrid
data={salesData}
aiAnalyst={aiAnalystConfig}
/>
)
}Option C: Client-Side Queries (DuckDB WASM)
For browser-based SQL execution with DuckDB WASM, add a queryExecutor:
const aiConfig = {
enabled: true,
endpoint: '/api/ai-proxy', // Server endpoint for AI chat
queryExecutor: async (sql, table) => {
// Execute SQL via DuckDB WASM (client-side)
const result = await duckdb.query(sql)
return { data: result.toArray(), rowCount: result.numRows }
},
dataSources: [
{ id: 'sales', table: 'sales', name: 'Sales Data', description: '...' }
],
dataSourceLoader: async (id) => {
// Load data into DuckDB and return schema
const data = await fetchData(id)
await duckdb.loadTable(id, data)
return { data, schema: inferSchema(data) }
}
}Conversation Persistence
const aiConfig = {
endpoint: '/api/tinypivot',
sessionId: 'user-123',
persistToLocalStorage: true, // Auto-save conversations
}Security
The server handler includes built-in protections:
Parser-based SQL Validation: Only SELECT queries allowed; every table reference (including subqueries and CTEs) is checked against the allowlist
Read-only session: Queries run on a connection opened
READ ONLY, so writes cannot succeed even if validation is bypassedTable Whitelisting: Only configured tables are queryable
Function Denylist: File, network, and session-config functions (
pg_read_file,dblink,set_config, ...) are rejectedError Sanitization: Connection strings stripped from errors
The handler does not authenticate callers — put it behind your own auth and rate limiting.
See @smallwebco/tinypivot-server for full documentation
Complete Example
For a complete working example with PostgreSQL backend, see the AI Analyst Demo:
cd examples/ai-analyst-demo
cp .env.example .env
# Edit .env with your DATABASE_URL and AI_API_KEY
pnpm install
pnpm dev:allChart Builder (Pro)
TinyPivot Pro includes a drag-and-drop chart builder with 6 chart types. Simply drag fields to configure your visualization — dimensions go to the X-axis and measures to the Y-axis.
Supported Chart Types
Chart Type | Best For |
Bar | Comparing categories, rankings |
Line | Trends over time, continuous data |
Area | Volume trends, stacked comparisons |
Pie | Part-to-whole proportions |
Donut | Proportions with center metric |
Radar | Multi-metric comparison |
How It Works
Click the Chart button in the view toggle
Select a chart type from the type bar
Drag a dimension field (text/date) to the X-Axis
Drag a measure field (number) to the Y-Axis
Optionally add a field to Color/Series for grouped charts
Charts automatically respect any filters applied in Grid view — filter your data, then visualize the subset.
Field Role Detection
The Chart Builder automatically classifies each column as a dimension (category/grouping), measure (aggregatable number), or temporal (date/time) using heuristics on your data.
How it works:
Columns where values are native JS
numbertypes are classified as measures — if your data layer has already cast values to numbers, TinyPivot trusts that intent regardless of cardinalityNumeric strings with high cardinality (many unique values) are classified as measures
Numeric strings with low cardinality (e.g.,
"1","2","3") are classified as dimensions (they could be category IDs)Date-like strings are classified as temporal
Everything else is classified as dimensions
Overriding field roles:
When the auto-detection doesn't match your intent, use fieldRoleOverrides to explicitly set roles:
<!-- Vue -->
<DataGrid
:data="data"
:field-role-overrides="{
'Answer Score': 'measure',
'Question Order': 'dimension',
'Company Size': 'measure',
}"
/>{/* React */}
<DataGrid
data={data}
fieldRoleOverrides={{
"Answer Score": "measure",
"Question Order": "dimension",
"Company Size": "measure",
}}
/>Available roles: 'dimension' | 'measure' | 'temporal'
This is useful when:
Low-cardinality numbers (like Likert scores 1-5) arrive as strings and get classified as dimensions
You want to force a numeric column to be used as a grouping axis (dimension) instead of an aggregated value
A column should be treated as temporal but isn't in a recognizable date format
Export
When enableExport is true (the default), the toolbar shows a single Export dropdown button. Clicking it opens a menu with two items:
CSV — always available (free). Downloads a
.csvfile of the current view (grid or pivot).Excel (.xlsx) — Pro only. Free users see this item disabled with a Pro badge. Pro users get a styled
.xlsxdownload.exceljs(~250 KB) is loaded lazily via dynamic import and is never part of your main bundle.
CSV Export (Free)
Programmatic API:
import { exportToCSV, exportPivotToCSV } from '@smallwebco/tinypivot-vue' // or -react
exportToCSV(data, columns, { filename: 'my-data.csv' })Excel (XLSX) Export (Pro)
Styled .xlsx downloads for both the flat grid and the pivot table. Both functions are async and trigger a browser download:
import { exportToXLSX, exportPivotToXLSX } from '@smallwebco/tinypivot-vue' // or -react
import type { XlsxExportOptions } from '@smallwebco/tinypivot-vue'
// Flat grid
await exportToXLSX(data, columns, {
filename: 'report.xlsx',
sheetName: 'Sales',
numberFormats: { revenue: '#,##0.00', units: '#,##0' },
})
// Pivot table
await exportPivotToXLSX(pivotData, rowFields, columnFields, valueFields, {
filename: 'pivot-report.xlsx',
sheetName: 'Pivot',
})XlsxExportOptions extends ExportOptions and adds sheetName?: string and numberFormats?: Record<string, string>.
Pivot XLSX: two-sheet workbook
When exporting a pivot table to Excel, TinyPivot produces a two-sheet workbook:
Pivot — the styled pivot summary (merged column headers, bold totals row, frozen header, auto-sized columns).
Source Data — the underlying source rows written as an interactive Excel Table (
TableStyleMedium2with filter/sort dropdowns on every column). In Excel, select any cell in this table and go to Insert → PivotTable to build a native Excel PivotTable in two clicks.
Note: TinyPivot does not generate a native Excel PivotTable object — the library used (exceljs) does not support writing pivot table XML. The Source Data sheet is the practical alternative: it gives users full access to the raw rows inside Excel so they can create a PivotTable themselves.
Pivot Drill-Down
TinyPivot supports two complementary pivot drill-down capabilities:
Row Group Expand/Collapse (Free)
When a pivot has two or more row fields, each group row displays a ▸/▾ chevron. Click to collapse or expand that group. Alt-click collapses/expands every group at the same depth at once. Collapsed groups still show correct aggregated values (sum, median, stdDev, etc.) over all rows in the group.
By default (pivotLayout="grouped"), the parent row value is rendered once as a vertically spanning cell across its children, making the hierarchy immediately readable. Set pivotLayout="tabular" to repeat the parent value on every row instead.
Controlled with the enableDrillDown prop (default true).
<!-- Vue -->
<DataGrid
:data="data"
@collapse-change="(collapsedPaths) => console.log('Collapsed:', collapsedPaths)"
/>// React
<DataGrid
data={data}
onCollapseChange={(collapsedPaths) => console.log('Collapsed:', collapsedPaths)}
/>Drill-Through to Source Rows (Pro)
Double-click any pivot value cell (including totals) to open a modal showing the underlying source rows that contributed to that cell. The modal includes a header with the slice description, paginated rows (50/page), and a CSV export of the drill-through result.
Requires a Pro license. Controlled with the enableDrillThrough prop (default true).
<!-- Vue -->
<DataGrid
:data="data"
@drill-through="({ rows, descriptor }) => console.log(`${descriptor.rowCount} rows for ${descriptor.rowPath.join(' > ')}`)"
/>// React
<DataGrid
data={data}
onDrillThrough={({ rows, descriptor }) =>
console.log(`${descriptor.rowCount} rows for ${descriptor.rowPath.join(' > ')}`)
}
/>TypeScript Types
import type { DrillThroughResult, DrillThroughDescriptor, PivotRowMeta } from '@smallwebco/tinypivot-vue'
// or '@smallwebco/tinypivot-react'
// DrillThroughResult — payload of the drill-through event
interface DrillThroughResult {
rows: Record<string, unknown>[] // Source rows matching the clicked cell's slice
descriptor: DrillThroughDescriptor
}
interface DrillThroughDescriptor {
rowPath: string[] // e.g. ['West', 'Widgets']
columnPath: string[] // e.g. ['Q3']
valueField: string // e.g. 'sales'
aggregation: AggregationFunction
formattedValue: string // Pre-formatted result, e.g. '1,234'
rowCount: number
}Custom Calculations
TinyPivot supports three types of custom calculations:
1. Custom Aggregation Functions (Developer API)
Pass your own aggregation logic via the customFn property:
// Vue
const valueFields = ref([
{
field: 'sales',
aggregation: 'custom',
customFn: (values) => {
// 90th percentile
const sorted = [...values].sort((a, b) => a - b)
return sorted[Math.floor(sorted.length * 0.9)]
},
customLabel: '90th Percentile',
customSymbol: 'P90'
}
])// React
const valueFields = [
{
field: 'sales',
aggregation: 'custom',
customFn: (values) => {
// Interquartile mean
const sorted = [...values].sort((a, b) => a - b)
const q1 = Math.floor(sorted.length * 0.25)
const q3 = Math.floor(sorted.length * 0.75)
const middle = sorted.slice(q1, q3)
return middle.reduce((a, b) => a + b, 0) / middle.length
},
customLabel: 'IQR Mean',
customSymbol: 'IQM'
}
]2. Calculated Fields (UI-Based)
Create fields that compute values from other aggregations using a formula builder:
Click the + button in the "Calculated" section
Enter a name (e.g., "Profit Margin %")
Build a formula like
SUM(profit) / SUM(revenue) * 100Choose format (Number, Percent, Currency)
Supported functions in formulas:
SUM(field)- Sum of valuesAVG(field)- Average of valuesMIN(field)- Minimum valueMAX(field)- Maximum valueCOUNT(field)- Count of valuesMEDIAN(field)- Median value
Example formulas:
SUM(profit) / SUM(revenue) * 100 → Profit margin %
SUM(revenue) / SUM(units) → Average price per unit
(MAX(sales) - MIN(sales)) / AVG(sales) → Coefficient of variation3. Programmatic Calculated Fields
Add calculated fields via props:
// Vue
const calculatedFields = ref([
{
id: 'margin',
name: 'Profit Margin %',
formula: 'SUM(profit) / SUM(revenue) * 100',
formatAs: 'percent',
decimals: 1
},
{
id: 'avg_price',
name: 'Avg Price',
formula: 'SUM(revenue) / SUM(units)',
formatAs: 'currency',
decimals: 2
}
])TypeScript Types
import type {
CalculatedField,
CustomAggregationFn,
PivotValueField
} from '@smallwebco/tinypivot-vue'
// Custom aggregation function signature
type CustomAggregationFn = (
values: number[],
allFieldValues?: Record<string, number[]>
) => number | null
// Calculated field definition
interface CalculatedField {
id: string
name: string
formula: string
formatAs?: 'number' | 'percent' | 'currency'
decimals?: number
}Pro License
Unlock advanced aggregations, charts, AI Data Analyst, and remove the watermark with a Pro license.
TinyPivot Pro uses a lifetime license — buy once, set your key, and keep shipping.
Activate License
Vue
import { setLicenseKey } from '@smallwebco/tinypivot-vue'
// Call once at app startup
setLicenseKey('YOUR_LICENSE_KEY')React
import { setLicenseKey } from '@smallwebco/tinypivot-react'
// Call once at app startup
setLicenseKey('YOUR_LICENSE_KEY')Pricing
Plan | Price | Use Case |
Single Project | $49 | One application |
Unlimited Projects | $149 | All your projects |
Team License | $399 | Up to 10 developers |
Purchase at tiny-pivot.com/pricing
Styling
TinyPivot uses scoped styles and won't conflict with your app. Import the base styles:
// Vue
import '@smallwebco/tinypivot-vue/style.css'
// React
import '@smallwebco/tinypivot-react/style.css'Theming
TinyPivot ships 27 themes — 2 neutral (light, dark), 10 brand themes each with a light and dark variant, and 5 unified themes that style the grid and its charts together. Themes are applied via the theme prop on DataGrid.
<!-- Vue -->
<DataGrid :data="data" theme="slate-dark" />{/* React */}
<DataGrid data={data} theme="slate-dark" />theme="auto" resolves to 'light' or 'dark' based on the user's system preference.
Available themes
Theme | Accent | Vibe |
| indigo / violet | Default — neutral cool grays |
|
| Linear / Stripe — cool neutral |
| near-mono | Vercel / Anthropic — minimalist |
|
| Premium SaaS |
|
| Data viz / AI tools |
|
| Fintech / finance |
|
| Productivity / airy |
|
| Friendly / creator |
|
| Energy / wellness |
|
| Solarized — warm cream + dark teal |
|
| Editorial — pure grayscale |
Unified themes
A unified theme styles the grid, pivot table and charts as one. Set it once on theme; charts pick up the matching palette and rendering style automatically (pass chartTheme to override).
Theme | Surface | Charts |
| Warm paper, black ink, orange accent | Flat fills, square bars |
| Ledger printer paper with green stripes | Flat fills, square bars |
| One ink, square corners, hard shadow | Pattern fills instead of colour |
| Dark amber phosphor with scanlines | Flat marks with glow |
| Dark green phosphor with scanlines | Flat marks with glow |
The same five ids are valid chartTheme values, so <DataGrid theme="slate" chartTheme="paper" /> also works. The MCP widget and terminal output use the same names.
Custom themes
Each theme redefines ~30 CSS custom property tokens at the grid root. Override them in your own CSS for a custom theme:
.vpg-data-grid.my-brand {
--vpg-accent: #ff6b35;
--vpg-accent-hover: #e55426;
--vpg-surface-bg: #fafaf7;
--vpg-surface-panel: #f0eee7;
/* …override any other token */
}<!-- Vue -->
<DataGrid :data="data" theme="light" class="my-brand" />{/* React */}
<DataGrid data={data} theme="light" className="my-brand" />Token reference:
Surfaces:
--vpg-surface-bg,--vpg-surface-panel,--vpg-surface-elevated,--vpg-surface-hover,--vpg-surface-selected,--vpg-surface-stripedText:
--vpg-text-primary,--vpg-text-secondary,--vpg-text-muted,--vpg-text-inverseBorders:
--vpg-border-default,--vpg-border-strong,--vpg-border-subtleAccent:
--vpg-accent,--vpg-accent-hover,--vpg-accent-soft-bg,--vpg-accent-soft-text,--vpg-focus-ringStates:
--vpg-state-error,--vpg-state-warning,--vpg-state-success,--vpg-state-infoPivot dimensions:
--vpg-dim-row-*,--vpg-dim-col-*,--vpg-dim-value-*,--vpg-dim-calc-*(each with-bg,-text,-border)Highlights:
--vpg-highlight-bg,--vpg-highlight-text,--vpg-highlight-borderScrollbar:
--vpg-scrollbar-thumb,--vpg-scrollbar-track
Custom theme classes layer on top of any preset, so you can start from theme="dark" and tweak just the accent.
TypeScript
Full TypeScript support included. Import types as needed:
// React
import type {
AggregationFunction,
DataGridProps,
FieldRole,
FieldRoleOverrides,
PivotConfig,
} from '@smallwebco/tinypivot-react'
// Vue
import type {
AggregationFunction,
CellClickEvent,
DataGridProps,
FieldRole,
FieldRoleOverrides,
PivotConfig,
SelectionChangeEvent,
} from '@smallwebco/tinypivot-vue'Browser Support
Chrome 80+
Firefox 75+
Safari 14+
Edge 80+
License
Free Tier: MIT License for core grid and pivot features
Pro Features: Commercial license required
See LICENSE.md for details.
GitHub Topics
This repository uses the following topics for discoverability:
ai-data-analyst, embedded-analytics, conversational-bi, natural-language-query, text-to-sql, byok, llm-integration, vue, vue3, react, data-grid, pivot-table, chart-builder, data-visualization, excel, spreadsheet, datagrid, table-component, aggregation, csv-export
Built with ❤️ by Small Web, LLC
License
TinyPivot is licensed under the MIT License. See LICENSE.md for details.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Interactive data visualization and executive PDF dashboards for ChatGPT, Claude, and Cursor.
The all-in-one data stack for agents. Upload files, run SQL, evolve tables, and render charts.
Charts and dashboards as images for AI agents. No browser, same data same bytes. Local and free.
Clean messy tabular data and render publication-ready PNG charts from your AI assistant.
Related MCP Servers
- AlicenseAqualityDmaintenanceTurn any CSV into a stunning interactive dashboard with one command — works as CLI, MCP server, or AI skill114MIT
- FlicenseNot gradedqualityAmaintenanceThe terminal AI agents can drive: a cross-platform desktop terminal (macOS/Linux/Windows, MIT) that runs a local MCP server. Spawn tabs/panes, run commands with structured output, read screens and full scrollback, take scrolling screenshots, record sessions with secret redaction, switch identity profiles. Auto-registers with Claude Code / Codex / Gemini CLI on install.24-
- AlicenseNot gradedqualityDmaintenanceMCP server that turns coding agents into data analysts: attach CSV/Parquet/JSON/XLSX or databases, profile data, run read-only SQL, and render Vega-Lite charts as SVG files.1MIT
- AlicenseAqualityBmaintenanceYour coding agent answers with dashboards, not paragraphs. An MCP server for Claude Code, Codex, Cursor, Gemini CLI and more: charts and tables from read-only SQL on Postgres, SQLite, Excel or CSV, in your browser, your app or a terminal pane. 2.7× cheaper than Claude Code making the charts itself.87MIT