csv-mcp
Version:
A Model Context Protocol (MCP) server for powerful CSV file operations - read, write, query, transform, analyze CSV data with formulas and charts.
493 lines (391 loc) โข 13.3 kB
Markdown
# CSV MCP Server
[](https://www.npmjs.com/package/csv-mcp)
[](https://www.npmjs.com/package/csv-mcp)
A Model Context Protocol (MCP) server that provides AI assistants with powerful CSV file operations. This server enables natural language interactions with CSV data through comprehensive reading, writing, querying, transformation, and analysis tools.
## ๐ Quick Install
### NPX (Recommended - No Installation Required)
```bash
# Setup CSV MCP in Claude Desktop (no configuration needed!)
npx csv-mcp init
# Check status
npx csv-mcp status
```
### Global Installation
```bash
# Install globally for repeated use
npm install -g csv-mcp
csv-mcp init
csv-mcp status
```
Restart Claude Desktop after setup.
**โจ New:** Use with NPX - no installation required! Just run `npx csv-mcp init` once.
**๐ก No directory configuration needed!** Simply specify CSV file paths naturally in your requests:
- "Read /path/to/data.csv"
- "Analyze ~/Documents/sales.csv"
- "Query ./data/customers.csv where age > 30"
## โจ Features
### ๐ **CSV File Operations**
- **Read CSV files** - Load and parse CSV data with various options
- **Write CSV files** - Create new CSV files or overwrite existing ones
- **Append data** - Add rows to existing CSV files
- **File information** - Get metadata about CSV files
### ๐ **Powerful Querying**
- **SELECT columns** - Choose specific columns to retrieve
- **WHERE clauses** - Filter rows with complex conditions
- **ORDER BY** - Sort data by multiple columns
- **LIMIT & OFFSET** - Paginate through large datasets
- **DISTINCT** - Get unique rows only
### ๐ง **Data Transformation**
- **Add columns** - Create new columns with computed values
- **Remove columns** - Delete unnecessary columns
- **Rename columns** - Change column names
- **Transform values** - Apply functions to transform data
- **Filter rows** - Remove rows based on conditions
### ๐ **Data Analysis**
- **Statistics** - Get min, max, mean, median, mode, standard deviation
- **Column analysis** - Analyze individual columns
- **Data type detection** - Automatic type inference
- **Top values** - Find most common values
- **Null counts** - Track missing data
- **Unique counts** - Count distinct values
### ๐ **Advanced Operations**
- **Merge CSV files** - Join two CSV files (inner, left, right, outer joins)
- **Aggregate data** - GROUP BY with SUM, AVG, COUNT, MIN, MAX
- **Search** - Full-text search across columns
- **Export** - Convert to different formats
## ๐ ๏ธ Installation
### Prerequisites
- Node.js (v16 or higher)
- Claude Desktop or any MCP-compatible AI client
### Quick Setup (NPX - Recommended)
1. **Run the init command:**
```bash
npx csv-mcp init
```
2. **Restart Claude Desktop** and you're ready!
3. **Start using it naturally:**
- "Read /Users/john/data.csv"
- "Analyze ~/Documents/sales-2024.csv"
- "Query ./customers.csv where age > 30"
### Alternative Installation Methods
**Install globally:**
```bash
npm install -g csv-mcp
csv-mcp init
```
**Use from source:**
```bash
git clone https://github.com/nitaiaharoni1/csv-mcp.git
cd csv-mcp
npm install
npm run build
```
## ๐ฏ Available Tools
The CSV MCP server provides 18 powerful tools for CSV operations:
### File Operations
- **`read_csv`** - Read a CSV file and return its contents
- **`write_csv`** - Write data to a CSV file
- **`append_csv`** - Append rows to an existing CSV file
- **`get_csv_info`** - Get information about a CSV file
### Query & Filter
- **`query_csv`** - Query CSV with SQL-like operations (SELECT, WHERE, ORDER BY, LIMIT)
- **`search_csv`** - Search for text across columns
### Transformation
- **`transform_csv`** - Transform CSV data (add/remove/rename columns, filter rows)
- **`merge_csv`** - Merge two CSV files based on a common key
### Data Updates
- **`update_cell`** - Update a specific cell value by row index and column name
- **`update_row`** - Update multiple fields in a specific row
- **`update_column`** - Update all values in a column (with value or formula)
- **`update_cells_conditional`** - Update cells matching a condition
- **`delete_rows`** - Delete rows by index or condition
### Analysis & Statistics
- **`analyze_csv`** - Get statistics and analysis of CSV file
- **`aggregate_csv`** - Aggregate data with GROUP BY operations
- **`calculate_stats`** - Calculate advanced statistics (mean, median, stddev, percentiles, etc.)
### Formulas & Calculations
- **`apply_formula`** - Apply mathematical formulas to CSV columns (e.g., column1 * column2)
### Data Visualization
- **`generate_chart`** - Generate chart data for bar, line, pie, scatter, and histogram charts
## ๐ฅ๏ธ CLI Commands
The csv-mcp package provides several command-line tools for easy configuration:
### Setup Commands
- **`csv-mcp init`** - Initialize CSV MCP in Claude Desktop
```bash
npx csv-mcp init
```
### Management Commands
- **`csv-mcp status`** - Show current configuration
```bash
csv-mcp status
```
### Information Commands
- **`csv-mcp --help/-h`** - Show help information
- **`csv-mcp --version/-v`** - Show version information
- **`csv-mcp --find-config`** - Show Claude Desktop config file location
## ๐ก Usage Examples
### Basic File Operations
```
"Read the /path/to/customers.csv file"
"Write this data to ~/output.csv: [data]"
"Show me information about ./sales.csv"
```
### Querying Data
```
"Query /data/products.csv and select name, price where price > 100"
"Show me the first 10 rows of ~/users.csv sorted by age"
"Get unique values from the category column in ./products.csv"
```
### Data Transformation
```
"Add a new column 'total' to ~/orders.csv by multiplying quantity and price"
"Remove the 'id' column from ./users.csv"
"Rename 'email' to 'email_address' in /data/contacts.csv"
```
### Analysis
```
"Analyze the ~/sales.csv file and show me statistics"
"What's the average price in /data/products.csv?"
"Show me the top 10 most common values in the category column"
"Calculate mean, median, and standard deviation for the amount column in ~/sales.csv"
"Show me percentiles for the price column"
```
### Formulas & Calculations
```
"Apply formula 'price * quantity' to /data/orders.csv and save result as 'total'"
"Calculate 'revenue - cost' for each row in ~/financials.csv"
"Add a column that multiplies column1 by 1.15 (15% increase)"
"Create a 'profit_margin' column using formula '(revenue - cost) / revenue * 100'"
```
### Charts & Visualization
```
"Generate a bar chart from ~/sales.csv with month on X-axis and revenue on Y-axis"
"Create a pie chart showing sales distribution by category"
"Make a line chart of temperature data over time"
"Generate a scatter plot of height vs weight data"
"Create a histogram of age distribution in /data/customers.csv"
```
### Cell/Row/Column Updates
```
"Update cell at row 5, column 'status' to 'completed' in tasks.csv"
"Update row 3 in customers.csv, set name to 'John' and email to 'john@example.com'"
"Update the 'price' column in products.csv using formula 'price * 1.15'"
"Update all cells in 'status' column to 'active' where category is 'premium'"
"Delete rows 2, 5, and 7 from data.csv"
"Delete all rows where status is 'inactive' from users.csv"
```
### Advanced Operations
```
"Merge /data/customers.csv and /data/orders.csv on customer_id"
"Group ~/sales.csv by category and sum the amounts"
"Search for 'john' in ./contacts.csv"
```
### CLI Management Examples
```bash
# Initial setup (one-time)
npx csv-mcp init
# Check configuration
npx csv-mcp status
# Find config file location
npx csv-mcp --find-config
```
## ๐ง Configuration
No configuration needed! CSV MCP works with any file path you specify.
### Setup (One-time)
Simply run:
```bash
npx csv-mcp init
```
This adds CSV MCP to your Claude Desktop configuration:
```json
{
"mcpServers": {
"csv-mcp": {
"command": "npx",
"args": ["-y", "csv-mcp"]
}
}
}
```
### Usage
Just specify file paths naturally in your requests:
- **Absolute paths**: `/Users/john/data.csv`, `C:\Users\John\data.csv`
- **Home directory**: `~/Documents/data.csv`
- **Relative paths**: `./data.csv`, `../data/file.csv`
## ๐ Tool Details
### read_csv
Read a CSV file and return its contents.
**Parameters:**
- `filepath` (required): Path to the CSV file
- `limit` (optional): Limit number of rows to read
- `offset` (optional): Number of rows to skip
**Example:**
```json
{
"filepath": "customers.csv",
"limit": 100,
"offset": 0
}
```
### query_csv
Query a CSV file with SQL-like operations.
**Parameters:**
- `filepath` (required): Path to the CSV file
- `select` (optional): Array of column names to select
- `where` (optional): Filter conditions object
- `orderBy` (optional): Array of sort conditions
- `limit` (optional): Limit number of rows
- `offset` (optional): Skip number of rows
- `distinct` (optional): Return unique rows only
**Example:**
```json
{
"filepath": "products.csv",
"select": ["name", "price", "category"],
"where": {
"column": "price",
"operator": "gt",
"value": 100
},
"orderBy": [
{ "column": "price", "direction": "desc" }
],
"limit": 10
}
```
### transform_csv
Transform CSV data by adding, removing, or renaming columns.
**Parameters:**
- `filepath` (required): Path to the CSV file
- `outputPath` (optional): Path for output file
- `addColumn` (optional): Add a new column
- `removeColumn` (optional): Remove a column
- `renameColumn` (optional): Rename a column
**Example:**
```json
{
"filepath": "orders.csv",
"outputPath": "orders_with_total.csv",
"addColumn": {
"name": "total",
"value": 0
}
}
```
### analyze_csv
Get statistics and analysis of a CSV file.
**Parameters:**
- `filepath` (required): Path to the CSV file
- `column` (optional): Specific column to analyze
**Example:**
```json
{
"filepath": "sales.csv",
"column": "amount"
}
```
### merge_csv
Merge two CSV files based on a common key.
**Parameters:**
- `leftFile` (required): Path to the left CSV file
- `rightFile` (required): Path to the right CSV file
- `leftKey` (required): Column name to join on in left file
- `rightKey` (required): Column name to join on in right file
- `type` (required): Type of join (inner, left, right, outer)
- `outputPath` (required): Path for output merged file
**Example:**
```json
{
"leftFile": "customers.csv",
"rightFile": "orders.csv",
"leftKey": "customer_id",
"rightKey": "customer_id",
"type": "inner",
"outputPath": "customer_orders.csv"
}
```
### aggregate_csv
Aggregate CSV data with GROUP BY operations.
**Parameters:**
- `filepath` (required): Path to the CSV file
- `groupBy` (required): Array of columns to group by
- `aggregations` (required): Array of aggregation functions
- `outputPath` (optional): Path for output file
**Example:**
```json
{
"filepath": "sales.csv",
"groupBy": ["category", "region"],
"aggregations": [
{ "column": "amount", "func": "sum", "alias": "total_sales" },
{ "column": "amount", "func": "avg", "alias": "avg_sale" },
{ "column": "order_id", "func": "count", "alias": "order_count" }
],
"outputPath": "sales_summary.csv"
}
```
## ๐งช Testing
The CSV MCP server includes comprehensive testing:
```bash
# Run all tests
npm test
# Run only unit tests
npm run test:unit
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode (development)
npm run test:watch
# Test CLI functionality
npm run test:cli
```
## ๐๏ธ Development
### Local Development Setup
1. **Clone the repository:**
```bash
git clone https://github.com/nitaiaharoni1/csv-mcp.git
cd csv-mcp
```
2. **Install dependencies:**
```bash
npm install
```
3. **Build the project:**
```bash
npm run build
```
4. **Test locally:**
```bash
npm run dev
```
### Project Structure
```
csv-mcp/
โโโ src/
โ โโโ csv/
โ โ โโโ manager.ts # CSV file operations
โ โ โโโ utils.ts # CSV data manipulation utilities
โ โโโ tools/
โ โ โโโ csv-tools.ts # MCP tool definitions
โ โ โโโ index.ts # Tool registry
โ โโโ types/
โ โ โโโ csv.ts # CSV type definitions
โ โ โโโ mcp.ts # MCP type definitions
โ โโโ cli.ts # CLI interface
โโโ server.ts # MCP server entry point
โโโ package.json
```
## ๐ License
MIT License - See LICENSE file for details.
## ๐โโ๏ธ Support
- **GitHub Issues**: [Report bugs or request features](https://github.com/nitaiaharoni1/csv-mcp/issues)
- **Documentation**: This README and inline code documentation
- **Community**: Contributions and discussions welcome!
## ๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
---
**Made with โค๏ธ for the AI and data community**