# DocuClean Ledger MCP (`shulang-chen/docuclean-ledger-mcp`) Actor

Deterministic MCP server for statement-invoice reconciliation, PDF table extraction to XLSX, and CJK CSV mojibake repair.

- **URL**: https://apify.com/shulang-chen/docuclean-ledger-mcp.md
- **Developed by:** [Shulang Chen](https://apify.com/shulang-chen) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## DocuClean & LedgerClean MCP (`docuclean-ledger-mcp`)

[![CI](https://github.com/2848823170/docuclean-ledger-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/2848823170/docuclean-ledger-mcp/actions)
[![Node.js >= 20](https://img.shields.io/badge/node-%3E%3D20.0.0-339933?logo=node.js\&logoColor=white)](https://nodejs.org/)
[![MCP Ready](https://img.shields.io/badge/MCP-stdio%20%7C%20Streamable%20HTTP%20%7C%20SSE-0ea5e9)](https://github.com/2848823170/docuclean-ledger-mcp)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)

**Deterministic Financial Reconciliation, Multi-Page PDF-to-Excel Extraction & CJK CSV Mojibake Repair — Commercial MCP Server & Pay-Per-Event Apify Actor**

AI coding and finance agents routinely hallucinate arithmetic on bank statements, corrupt Chinese/Japanese/Korean (`GB18030` / `GBK` / `Big5` / `Shift_JIS`) CSV exports, or produce broken spreadsheets vulnerable to CSV/DDE formula injection. **`docuclean-ledger-mcp`** gives Claude Desktop, Cursor, Windsurf, Cline, n8n, and API workflows three deterministic, security-hardened tools with **zero external LLM API dependencies**:

1. **`reconcile_statements_and_invoices`** (`$0.02` / run) — Reconciles Alipay (`支付宝`), WeChat Pay (`微信支付`), Stripe, PayPal, and bank CSV/JSON statements against electronic invoices (China Digital e-Invoice `数电票` XML/PDF, UBL 2.1 XML, CSV, JSON) using exact `BigInt` micro-unit (`10,000n = 1.00`) arithmetic:
   - 1-to-1 Order-ID & Merchant-Ref matching
   - Counterparty entity alias + date-window matching (`滴滴` ↔ `北京小桔科技有限公司`, `阿里云` ↔ `阿里巴巴云计算`, etc.)
   - Cross-currency FX card spread matching (`USD`/`EUR`/`HKD` ↔ `CNY`)
   - Bounded combinatorial **N-to-1 subset-sum matching** (`合并开票凑单`, e.g., multiple ride-hail or cloud charges matching a single consolidated monthly tax invoice)
   - Duplicate transaction/invoice blocking + Buyer Tax-ID (`纳税人识别号`) compliance verification
   - Outputs structured JSON + OWASP formula-safe UTF-8 BOM CSV + Base64 **3-sheet OpenXML `.xlsx` Audit Workbook** (`01_Executive_Summary`, `02_Reconciled_Ledger`, `03_Anomalies_Checklist`)
2. **`extract_and_clean_pdf_tables_to_xlsx`** (`$0.02` / document) — Extracts tables from multi-page PDF binaries (`PyMuPDF` vector/spatial grid + pure-JS FlateDecode/CMap fallback), HTML (`rowspan`/`colspan` 2D expansion), Markdown, JSON/JSONL, or messy CSVs; stitches repeating headers across page breaks; strips illegal XML 1.0 control characters (`\x00–\x08`, `\x0B`, `\x0C`, `\x0E–\x1F`); keeps user cells strictly non-formula (`inlineStr`) while appending live `=SUM()` and `=AVERAGE()` summary rows; and outputs Base64 `.xlsx` + Markdown + UTF-8 BOM CSV.
3. **`repair_cjk_csv_mojibake`** (`$0.005` / file) — Detects and repairs garbled CJK CSV/TSV files from `GB18030`, `GBK`, `Big5`, `Shift_JIS`, `EUC-KR`, `UTF-16LE/BE`, and double-encoded `UTF-8-as-Latin1/Windows-1252` strings; heals unquoted currency thousands commas (`¥1,250.00`); armors 15+ digit IDs and leading zeros; and neutralizes OWASP CSV/DDE formula injection (`=`, `+`, `-`, `@`).

***

### Pay-Per-Event Pricing

| Event / Tool | Event Name | Flat Price (USD) | Typical Latency |
|---|---|---:|---:|
| `reconcile_statements_and_invoices` | `reconcile-statements-invoices` | **$0.020** | `30–180 ms` |
| `extract_and_clean_pdf_tables_to_xlsx` | `extract-pdf-tables-to-xlsx` | **$0.020** | `50–250 ms` |
| `repair_cjk_csv_mojibake` | `repair-cjk-csv-mojibake` | **$0.005** | `5–25 ms` |
| Batch Cold-Start Initialization *(Batch mode only)* | `actor-start` | **$0.001** | `<50 ms` |

*Failed or invalid tool calls are **never** charged.*

***

### Quick Connect — Hosted MCP (Apify Standby & MCPize)

#### 1. Streamable HTTP MCP (Claude Desktop / Cursor / Windsurf / Inspector)

```json
{
  "mcpServers": {
    "docuclean-ledger": {
      "type": "streamable-http",
      "url": "https://2848823170--docuclean-ledger-mcp.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer <YOUR_APIFY_API_TOKEN>"
      }
    }
  }
}
```

#### 2. Local `stdio` Mode (`npx` / Node 20+)

```json
{
  "mcpServers": {
    "docuclean-ledger": {
      "command": "node",
      "args": ["./src/main.mjs", "--stdio"]
    }
  }
}
```

***

### Tool Input Examples

#### `reconcile_statements_and_invoices`

```json
{
  "statements": [
    {
      "filename": "alipay_2026_11.csv",
      "content": "交易创建时间,交易对方,商品说明,收/支,金额（元）,交易状态,交易订单号\n2026-11-05,阿里云计算有限公司,ECS云服务器,支出,368.00,交易成功,202611050001"
    }
  ],
  "invoices": [
    {
      "filename": "einvoice_aliyun.xml",
      "content": "<ElectronicInvoice><InvoiceNumber>26312000000088990011</InvoiceNumber><IssueTime>2026-11-06</IssueTime><SellerInformation><SellerName>阿里云计算有限公司</SellerName></SellerInformation><TotalTax-includedAmount>368.00</TotalTax-includedAmount></ElectronicInvoice>"
    }
  ],
  "baseCurrency": "CNY"
}
```

#### `extract_and_clean_pdf_tables_to_xlsx`

```json
{
  "filename": "procurement_schedule.pdf",
  "contentBase64": "<BASE64_PDF_BYTES>",
  "mergePages": true,
  "dedupeRows": true,
  "injectFormulas": true
}
```

#### `repair_cjk_csv_mojibake`

```json
{
  "filename": "legacy_gbk_export.csv",
  "contentBase64": "<BASE64_GB18030_OR_BIG5_BYTES>"
}
```

***

### Local Development & Verification

```bash
## Run full unit, OpenXML openpyxl cross-validation, stdio MCP, HTTP Standby MCP & Batch Actor suite
npm test

## Start Streamable HTTP + SSE MCP server on http://localhost:8080/mcp
npm run start:http

## Start stdio MCP server
npm run start:stdio
```

# Actor input Schema

## `tool` (type: `string`):

Select which tool to invoke when running as an Apify batch job. In Standby mode, MCP clients call tools directly via /mcp.

## `statements` (type: `array`):

Array of payment statement objects ({ filename, content? | contentBase64? }) from Alipay, WeChat Pay, Stripe, PayPal, or bank CSV exports.

## `invoices` (type: `array`):

Array of invoice objects ({ filename, content? | contentBase64? }) in CN Digital e-Invoice XML/PDF, UBL 2.1 XML, CSV, or JSON format.

## `baseCurrency` (type: `string`):

3-letter ISO currency code for executive P\&L rollups (e.g. CNY, USD, EUR).

## `expectedBuyerName` (type: `string`):

Company or entity name expected in the Buyer field of incoming expense invoices.

## `expectedBuyerTaxId` (type: `string`):

18-character Unified Social Credit Code or VAT/EIN expected on incoming expense invoices.

## `filename` (type: `string`):

Filename hint with extension (e.g. statement.pdf, report.html, export.csv).

## `contentBase64` (type: `string`):

Base64-encoded raw file bytes for PDF extraction or raw legacy-encoded CSV repair.

## `content` (type: `string`):

Direct string payload when sending text, HTML tables, Markdown tables, JSON, or double-encoded mojibake text.

## `mergePages` (type: `boolean`):

Automatically stitch continuation tables across PDF pages that repeat identical headers.

## `dedupeRows` (type: `boolean`):

Remove exact duplicate rows while preserving original row order.

## `injectFormulas` (type: `boolean`):

Append live =SUM() and =AVERAGE() summary rows for numeric columns in generated .xlsx files.

## Actor input object example

```json
{
  "tool": "reconcile_statements_and_invoices",
  "statements": [],
  "invoices": [],
  "baseCurrency": "CNY",
  "expectedBuyerName": "",
  "expectedBuyerTaxId": "",
  "filename": "document.pdf",
  "contentBase64": "",
  "content": "",
  "mergePages": true,
  "dedupeRows": false,
  "injectFormulas": true
}
```

# Actor output Schema

## `datasetResults` (type: `string`):

No description

## `xlsxWorkbook` (type: `string`):

No description

## `cleanUtf8Csv` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("shulang-chen/docuclean-ledger-mcp").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("shulang-chen/docuclean-ledger-mcp").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call shulang-chen/docuclean-ledger-mcp --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,shulang-chen/docuclean-ledger-mcp"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ILlJIfMB2T5PVSafv/builds/pxLxgUVuGscYKYtBf/openapi.json
