Skip to main content
Glama
anshveerturna

TallyPrime MCP Server

README.md
# TallyPrime MCP Server

A production-grade **Model Context Protocol (MCP)** server that gives AI models complete, native-level control over **TallyPrime ERP** — covering every functional module across 169+ tools.

## Architecture

```
                    ┌─ Stdio Transport (Claude Desktop / CLI)
AI Model ──► MCP ──┤
                    └─ StreamableHTTP (port 4000, remote clients)
                          │
                          ▼
                    TallyPrime XML Server (port 9000)
                          │
                    ├─ UTF-16LE encoded communication
                    ├─ Serial request queue (single-threaded safety)
                    ├─ Standard XML Export (Method A)
                    ├─ Inline TDL Queries (Method B)
                    ├─ XML Import (Method C)
                    ├─ TDL Actions (Method D)
                    └─ Object Export (Method E)
```

### Three-Layer System

| Layer | Purpose | Example |
|-------|---------|---------|
| **Standard XML API** | CRUD operations, report exports | Create ledger, fetch Trial Balance |
| **Inline TDL Queries** | Complex filtered queries built programmatically | "All debtors with balance > 1L in Maharashtra" |
| **Persistent TDL File** | Pre-built collections loaded on Tally startup | `MCP Ledgers`, `MCP StockItems`, `MCP FinancialSnapshot` |

## Quick Start

### Prerequisites
- **TallyPrime** running with XML Server enabled (port 9000)
- **Node.js** 20+

### Setup

```bash
# Clone & install
cd tally-mcp-server
npm install

# Configure
cp .env.example .env
# Edit .env with your Tally settings

# Run in development (HTTP mode)
npm run dev

# Run in Stdio mode (for Claude Desktop)
npm run dev:stdio

# Build & run production
npm run build
npm start          # HTTP mode
npm run start:stdio  # Stdio mode
```

### Docker

```bash
docker compose up -d
```

## Transport Modes

### Stdio (for Claude Desktop / CLI)

Add to your Claude Desktop config (`claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "tally": {
      "command": "node",
      "args": ["/path/to/tally-mcp-server/dist/index.js", "--stdio"]
    }
  }
}
```

Or set the environment variable:
```bash
MCP_TRANSPORT=stdio node dist/index.js
```

### StreamableHTTP (for remote / web clients)

```json
{
  "mcpServers": {
    "tally": {
      "url": "http://localhost:4000/mcp",
      "transport": "streamable-http"
    }
  }
}
```

## Configuration

| Variable | Default | Description |
|----------|---------|-------------|
| `TALLY_HOST` | `localhost` | TallyPrime hostname |
| `TALLY_PORT` | `9000` | TallyPrime XML server port |
| `TALLY_TIMEOUT_MS` | `30000` | Request timeout in ms |
| `TALLY_COMPANY` | *(auto)* | Force a specific company (optional) |
| `MCP_SERVER_PORT` | `4000` | HTTP transport port |
| `MCP_TRANSPORT` | `http` | Transport mode: `stdio` or `http` |
| `MASTER_CACHE_TTL_MS` | `300000` | Master cache TTL (5 min) |
| `LOG_LEVEL` | `info` | Winston log level |

## Tool Modules (169+ tools)

| # | Module | Tools | Description |
|---|--------|-------|-------------|
| 1 | **Masters** | 28 | Ledgers, groups, stock items, units, godowns, cost centres, currencies |
| 2 | **Vouchers** | 16 | Sales, purchases, receipts, payments, journals, contra, credit/debit notes |
| 3 | **Orders** | 10 | Sales/purchase orders, delivery/receipt notes, rejections |
| 4 | **Financial Reports** | 15 | Trial balance, P&L, balance sheet, cash flow, daybook, ratio analysis |
| 5 | **Inventory Reports** | 10 | Stock summary, movement, batch, expiry, reorder, valuation |
| 6 | **Outstanding** | 8 | Receivables, payables, ageing analysis, bill-wise, overdue |
| 7 | **GST** | 18 | GSTR-1/2A/2B/3B, HSN, e-Invoice, e-Way Bill, ITC, reconciliation |
| 8 | **TDS/TCS** | 12 | Computation, forms 26Q/27Q/16, challans, PAN verification |
| 9 | **Payroll** | 20 | Employees, pay heads, salary structures, payslips, PF/ESI/gratuity |
| 10 | **Manufacturing** | 14 | BOM, production, consumption, job costing, yield analysis |
| 11 | **Banking** | 10 | Bank reconciliation, cheque register, PDC, cash position |
| 12 | **Budgets** | 8 | Budget CRUD, variance, utilization, scenario reports |
| 13 | **Security** | 8 | Users, audit trail, altered/deleted voucher logs, exceptions |
| 14 | **Company** | 8 | Company info, connection test, cache refresh, feature status |
| 15 | **Bulk Operations** | 12 | Batch create/update/delete masters & vouchers |
| 16 | **TDL Query Engine** | 12 | Custom queries, inline TDL, functions, raw XML, search, reference |

## Key Technical Features

- **UTF-16LE encoding** — Correct wire encoding for Tally's XML server (supports Indian languages: Hindi, Tamil, etc.)
- **Serial request queue** — All requests are serialized to protect Tally's single-threaded XML server from concurrent request crashes
- **EXCEPTION/LINEERROR/STATUS detection** — Comprehensive error detection covering all Tally error response formats
- **Master name cache with TTL** — Fast ledger/stock/group name lookups without hitting Tally
- **Persistent TDL file** — Pre-built optimized collections loaded on Tally startup
- **Tally value parsers** — Correct parsing of Tally's date, amount, quantity, rate, and boolean formats
- **Input validation** — Zod schemas with GSTIN/PAN/date format validators
- **Structured logging** — Winston logger with configurable levels

## Persistent TDL File

Install `tdl/tally-mcp.tdl` in your TallyPrime TDL folder for optimized pre-built collections:

| Collection | Contents |
|-----------|----------|
| `MCP Ledgers` | All ledgers with key financial fields |
| `MCP StockItems` | All stock items with inventory fields |
| `MCP Groups` | All account groups |
| `MCP Vouchers` | All vouchers (date-filtered via SV) |
| `MCP Debtors` | Sundry Debtors with balances |
| `MCP Creditors` | Sundry Creditors with balances |
| `MCP BankAccounts` | Bank accounts with balances |
| `MCP CostCentres` | Cost centres |
| `MCP Employees` | All employees with details |
| `MCP CashBankSummary` | Cash + bank position |
| `MCP FinancialSnapshot` | Quick financial summary function |

## API Endpoints (HTTP mode only)

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/mcp` | POST | MCP StreamableHTTP transport |
| `/mcp` | GET | SSE stream (session-based) |
| `/mcp` | DELETE | Close session |
| `/health` | GET | Health check + cache stats |

## Project Structure

```
tally-mcp-server/
├── src/
│   ├── index.ts              # Entry point (Stdio + HTTP)
│   ├── server.ts             # MCP server factory
│   ├── tally/
│   │   ├── client.ts         # HTTP client (UTF-16LE, serial queue)
│   │   ├── xml-builder.ts    # XML request builders
│   │   ├── xml-parser.ts     # XML response parser + value helpers
│   │   ├── tdl-builder.ts    # Inline TDL builder
│   │   └── state.ts          # Master cache with TTL
│   ├── tools/                # 16 tool modules (169+ tools)
│   └── utils/
│       ├── logger.ts         # Winston logger
│       ├── validators.ts     # GSTIN/PAN/date validators
│       ├── date-utils.ts     # Date utilities
│       └── helpers.ts        # Shared result/error helpers
├── tdl/
│   └── tally-mcp.tdl        # Persistent TDL file
├── package.json
└── tsconfig.json
```

## License

MIT