Local Business Data & Report Analyst
by AamnaAnsari
README.md
# Local Business Data & Report Analyst (Custom MCP Server)
> A Python [Model Context Protocol](https://modelcontextprotocol.io) server that gives Claude Desktop secure, read-only access to local sales data, so business questions are answered with exact calculations instead of guesses.



**Demo video:** [Watch Project Video](Video/FinalTesting2.mp4)
[Watch GIF](docs/demo.gif)
---
## Table of Contents
1. [Overview](#overview)
2. [Key Features](#key-features)
3. [Architecture](#architecture)
4. [Tool Reference](#tool-reference)
5. [Quick Start](#quick-start)
6. [Example Questions](#example-questions)
7. [Sample Results](#sample-results)
8. [Security Design](#security-design)
9. [Testing](#testing)
10. [Achievements](#achievements)
11. [Challenges & Solutions](#challenges--solutions)
12. [Known Limitations](#known-limitations)
13. [Future Improvements](#future-improvements)
14. [Tech Stack](#tech-stack)
---
## Overview
Business teams often copy and paste spreadsheet rows into chat tools, which is slow, error-prone, and risky for sensitive data. This project exposes local CSV, Excel, and SQLite files to Claude through custom MCP tools. Claude discovers the tools on its own, runs them locally, and writes the final explanation from verified numbers.
**Problems solved**
| Problem | How this project addresses it |
|---|---|
| Private data should not be uploaded to third-party services | The server runs locally over stdio. Files never leave the machine. |
| LLMs can hallucinate arithmetic | All totals, rates, and trends are computed in pandas/sqlite3 inside the tools. Claude only interprets results. |
| Reporting is repetitive | A one-click MCP prompt runs a multi-tool workflow and produces a structured executive report. |
---
## Key Features
- **10 analytics and data tools** exposed through FastMCP, each typed and documented so Claude can choose them correctly.
- **Gross vs. Net separation.** Every figure is labeled as gross (all orders) or net (excluding refunded orders).
- **Target tracking.** Compares regional net revenue and margin against `regional_targets.xlsx` with pro-rating by date range.
- **Period comparison.** Compares regions against an explicit, equal-length prior window, or H1 vs. H2 for the full period, and prints the exact date ranges used.
- **MCP Prompt** (`monthly_executive_report`) that generates a fixed-structure executive report.
- **MCP Resource** (`schema://datasets`) that exposes dataset schemas up front.
- **Multi-format support:** CSV, Excel (`.xlsx`), and SQLite.
- **Layered security:** read-only database connection, SQL validation, path sandboxing, input validation, and row limits.
- **Automated tests** that verify calculations against known values and confirm the security guards.
---
## Architecture
```
┌────────────────┐ JSON-RPC over stdio ┌─────────────────────┐ ┌────────────────────┐
│ Claude Desktop │ ◄─────────────────────► │ MCP Server │ ─────► │ Local data (data/)│
│ (MCP client) │ │ (FastMCP, Python) │ │ sales.csv │
└────────────────┘ │ │ │ business.db │
│ DataSecurityGuard │ │ regional_targets │
│ BusinessAnalyst │ │ .xlsx │
│ Service (pandas) │ └────────────────────┘
└─────────────────────┘
```
**Code structure**
- `DataSecurityGuard`: path sandboxing, date validation, SQL validation, row limits.
- `BusinessAnalystService`: analytics logic (pure Python methods, easy to unit test).
- FastMCP wiring: thin `@mcp.tool()`, `@mcp.resource()`, and `@mcp.prompt()` wrappers around the service.
Keeping the logic in a service class means tests can call it directly without running the MCP protocol.
```
business-analyst-mcp/
├── server.py
├── generate_sample_data.py
├── test_server.py
├── quick_check.py
├── requirements.txt
├── claude_desktop_config.example.json
├── data/
│ ├── sales.csv
│ ├── business.db
│ └── regional_targets.xlsx
└── docs/
```
---
## Tool Reference
| Tool | Purpose | Key parameters |
|---|---|---|
| `list_datasets` | Lists files in `data/` with their columns | none |
| `describe_data` | Row count, date range, column types, null counts | `dataset` |
| `preview_dataset` | First N rows of any supported file (max 100) | `dataset`, `n` |
| `sales_summary` | Gross/net revenue, gross/net profit and margin, orders, units, AOV | `start_date`, `end_date` |
| `top_products` | Ranks products by revenue, net revenue, units, or profit | `metric`, `n`, dates |
| `refund_analysis` | Refund rate per product and top refund reasons | dates |
| `monthly_trend` | Month-over-month totals and % change | `metric` |
| `compare_regions` | Regional net/gross revenue, net margin, AOV, refund rate, period shift | dates |
| `target_vs_actual` | Net revenue and margin vs. targets with variance, attainment %, pro-rating | `region`, dates, `prorate` |
| `run_sql_query` | Read-only `SELECT` against `business.db` (max 100 rows) | `query` |
**Prompt:** `monthly_executive_report(month)`
**Resource:** `schema://datasets`
---
## Quick Start
**Requirements:** Python 3.10+, Claude Desktop, Node.js (only for the optional MCP Inspector).
```bash
git clone https://github.com/<YOUR_USERNAME>/business-analyst-mcp.git
cd business-analyst-mcp
python -m venv venv
# Windows: venv\Scripts\activate
# macOS/Linux: source venv/bin/activate
pip install -r requirements.txt
python generate_sample_data.py
pytest -v
```
**Connect to Claude Desktop.** Edit `claude_desktop_config.json`:
- macOS: `~/Library/Application Support/Claude/`
- Windows: `%APPDATA%\Claude\`
```json
{
"mcpServers": {
"business-analyst": {
"command": "/ABSOLUTE/PATH/TO/venv/bin/python",
"args": ["/ABSOLUTE/PATH/TO/server.py"]
}
}
}
```
On Windows, use the full path to `venv\Scripts\python.exe` and escape backslashes (`\\`).
Then **fully quit** Claude Desktop (system tray / Cmd+Q, not just closing the window), reopen it, and start a **new chat**. The tools appear in the tools menu.
**Run without Claude (offline):**
```bash
mcp dev server.py # opens MCP Inspector in the browser
python quick_check.py # prints key tool outputs in the terminal
pytest -v # runs the test suite
```
---
## Example Questions
- "What datasets do we have? Describe `regional_targets.xlsx`."
- "Compare Karachi's net revenue against its pro-rated annual target."
- "Which product had the highest refund rate in November 2026?"
- "Compare regions for the first half vs. the second half. Show the exact date ranges."
- "What is Karachi's profit margin for November, and which revenue basis did you use?"
- "Generate the monthly executive report for November 2026." (uses the registered prompt)
---
## Sample Results
The repository ships with a **synthetic** dataset: 2,000 orders, 8 products, 4 regions, from 2025-12-06 to 2026-11-30. Two patterns were deliberately planted so the analysis has something to find.
| Insight | Result | Source tool |
|---|---|---|
| Karachi vs. pro-rated target (360/365 days) | $128,706 net vs. $147,945 target, **87.0% attainment** | `target_vs_actual` |
| Faisalabad, H2 vs. H1 net revenue | **-58.3%** (orders fell from 198 to 90) | `compare_regions` |
| Other regions, H2 vs. H1 | Islamabad +37.9%, Karachi +27.2%, Lahore +17.3% | `compare_regions` |
| Highest refund rate, Nov 2026 | **Bluetooth Earbuds, 34.8%** (8 of 23 orders) | `refund_analysis` |
| November net revenue | $33,142 (+15.6% vs. October) | `monthly_trend` |
The executive report prompt produces these sections in a fixed order: Headline, Key metrics, Regional performance vs. target, Structural trends, Refund analysis, Risks (max 5, by severity), and exactly 3 Action items.
---
## Security Design
Security is layered so that no single check is the only defense.
| Layer | Protection |
|---|---|
| **Read-only database connection** | SQLite is opened with `mode=ro`. This is the **primary** protection: even if validation were bypassed, the database cannot be written. |
| **SQL validation** | Only `SELECT`/`WITH` statements are accepted. Multiple statements, SQL comments, and write/schema keywords (`DROP`, `DELETE`, `UPDATE`, `INSERT`, `ALTER`, `CREATE`, `ATTACH`, `DETACH`, `PRAGMA`, `REPLACE`, `VACUUM`) are rejected. String literals are stripped first so legitimate filters such as `WHERE refund_reason = 'Defective'` are not falsely blocked. |
| **Path sandboxing** | Dataset names are resolved and must stay inside `data/`. Traversal attempts like `../../secrets.txt` return "Access denied". |
| **Input validation** | Dates must be valid `YYYY-MM-DD` and in chronological order. Metrics are checked against an allow-list. |
| **Output limits** | Results are capped at 100 rows to protect Claude's context window. |
| **Safe logging** | Logs go to stderr only. Writing to stdout would corrupt the MCP stdio channel. |
| **Errors as text** | Failures return clear messages instead of crashing the server. |
**Tested bypass attempts:** plain `DROP`, stacked queries (`SELECT 1; DROP ...`), CTE-wrapped writes (`WITH x AS (...) DELETE ...`), case variation (`dRoP`), comment obfuscation, `ATTACH DATABASE`, `PRAGMA writable_schema`, and path traversal.
---
## Testing
```bash
pytest -v
```
The suite checks calculations against known values and verifies the guards:
| Test | Verifies |
|---|---|
| Faisalabad decline | H1 vs. H2 shift reports -58.3% |
| Karachi attainment | 87.0% attainment and $147,945.21 pro-rated target |
| November net revenue | $33,142.00 |
| SQL write blocking | Six write/bypass patterns are rejected |
| Legitimate SELECT | Valid queries are allowed |
| Path traversal | Access denied outside `data/` |
| Invalid date | Clear validation error |
`quick_check.py` prints the same tool outputs for manual inspection without running Claude.
---
## Achievements
- Built and deployed a working MCP server integrated with Claude Desktop, with 10 tools, 1 prompt, and 1 resource.
- Delivered exact, reproducible calculations: results were cross-checked by hand (for example, regional net revenue summing to the company total of $33,142, and attainment math verified).
- Implemented target-vs-actual analysis that reads an Excel targets file with date-based pro-rating.
- Separated gross and net metrics consistently across every tool and report.
- Designed a layered security model and verified it against multiple bypass attempts.
- Created a one-click executive report with a fixed structure, risk cap, and exactly three action items.
- The report surfaces a structural decline (Faisalabad, -58.3%) that a single-month view would hide behind a +102% month-over-month jump on a very small base.
- Added an automated test suite and an offline verification workflow (`pytest`, `quick_check.py`, MCP Inspector) that needs no API usage.
- Ran at **$0 cost**: Claude Desktop free plan, open-source libraries, no API keys.
---
## Challenges & Solutions
| Challenge | Root cause | Solution |
|---|---|---|
| **Targets file unreadable** | Early tools profiled structure only, and SQL reached only `business.db`. | Added `preview_dataset` and `target_vs_actual` with Excel support. |
| **Gross vs. net ambiguity** | Refunded orders were included in revenue, so the right comparison against targets was unclear. | Added net revenue/profit columns, labeled every output as gross or net, and defined net margin on net revenue. |
| **Misleading period-shift numbers** | The period-comparison logic did not use a clearly defined prior window. | Rewrote `compare_regions` to use an explicit equal-length prior window (or H1 vs. H2) and to print both date ranges. Verified results by hand. |
| **Fixed code, old behavior** | Claude Desktop keeps the MCP server process running. Closing the window does not restart it, so new code was not loaded. | Established the rule: edit code, fully quit Claude Desktop, reopen, start a new chat. Validated logic offline first. |
| **Stale results in reused chats** | Claude reused earlier tool results in the same conversation instead of calling tools again. | Test each change in a fresh chat. |
| **Token waste during testing** | Repeated Claude Desktop runs consumed usage. | Built `quick_check.py`, `pytest`, and MCP Inspector for free offline verification. |
| **Report ignored rules** | Free-form prompts produced extra action items, missing sections, and unsupported claims. | Tightened the registered prompt: fixed section order, max 5 risks, exactly 3 actions, mandatory H1-vs-H2 call, and "no claims outside tool output". |
| **Small-sample noise** | A +102% month-over-month change on 11 orders looked like recovery. | Prompt rule: do not describe changes on a base under 20 orders as growth or recovery. |
| **SQL guard false positives** | Naive keyword matching can block legitimate queries. | Strip quoted literals before keyword checks, and rely on `mode=ro` as the real protection. |
| **Protocol corruption risk** | Any write to stdout breaks the stdio channel. | All logging goes to stderr; no `print()` in the server. |
| **Inspector connection timeout** | First-time `npx` download and heavy imports exceeded 30 seconds. | Increased the request timeout, verified `python server.py` starts, and warmed up the Inspector before recording. |
---
## Known Limitations
- **Margin basis:** gross margin is `(gross revenue - cost) / gross revenue`. Net margin uses non-refunded orders only. Returned-goods recovery and refund fees are not modeled.
- **Prior window:** the "previous period" is an equal-length window immediately before the current one, not the calendar month. For November it is 2 Oct to 31 Oct.
- **Small samples:** percentage changes on a few orders are noisy. Treat product- and region-level monthly percentages as directional.
- **Scope:** analytics tools read `sales.csv`; `run_sql_query` reads `business.db` only. Both ship with identical sample data.
- **Keyword filter:** the `REPLACE` keyword is blocked, which also blocks the SQL `REPLACE()` function. This is a deliberate trade-off.
- **Synthetic data:** all figures in this repository come from generated sample data.
---
## Future Improvements
- Charts and visual summaries
- Scheduled or automated report generation
- PostgreSQL / MySQL connectors
- Configurable data directory and dataset registry
- Refund-reason breakdown per product
- CI pipeline running `pytest` on every push
- Cost-adjusted net profit that accounts for returned inventory
---
## Tech Stack
| Layer | Tool |
|---|---|
| Language | Python 3.10+ |
| MCP framework | Official `mcp` Python SDK (FastMCP) |
| Data processing | pandas, openpyxl, sqlite3 |
| Client | Claude Desktop (free plan) |
| Testing | pytest, MCP Inspector |
| Hosting | GitHub |
---
## License
This project is licensed under the [MIT License](LICENSE).
## DEVELOPED BY AAMNA ANSARI
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues