honest-mbank-parser-mcp 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ .DS_Store
6
+ .env
7
+
8
+ # Never commit user bank data
9
+ *.csv
10
+ !sample.csv
11
+ *.pdf
12
+ dist/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bartosz Kuć
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.5
2
+ Name: honest-mbank-parser-mcp
3
+ Version: 0.2.0
4
+ Summary: Local MCP server that parses mBank CSV operation exports — fully offline, no bank connection.
5
+ Project-URL: Homepage, https://github.com/bartosz-kuc/honest-mbank-parser-mcp
6
+ Project-URL: Repository, https://github.com/bartosz-kuc/honest-mbank-parser-mcp
7
+ Project-URL: Issues, https://github.com/bartosz-kuc/honest-mbank-parser-mcp/issues
8
+ Author-email: Bartosz Kuć <firma@bartosza.pl>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: csv,finance,mbank,mcp,offline,parsing
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: mcp<3.0.0,>=2.0.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # mbank-parser-mcp
26
+
27
+ <!-- mcp-name: io.github.bartosz-kuc/honest-mbank-parser-mcp -->
28
+
29
+ Local MCP server that parses **mBank CSV operation exports** — the exact file you can download from the mBank web app under "Historia" → "Eksportuj do CSV". Runs entirely offline. Nothing leaves your machine.
30
+
31
+ Part of the [honest-mcp family](https://github.com/bartosz-kuc?tab=repositories) of small, auditable, local-first MCP servers.
32
+
33
+ ## Why
34
+
35
+ Anyone using mBank in Poland — private, JDG, sp. z o.o. — does the same monthly ritual:
36
+
37
+ 1. Log into mBank, download the CSV.
38
+ 2. Open in Excel, squint at Polish-locale amounts (space-thousands, comma-decimals, ` PLN` suffix).
39
+ 3. Filter by date, sum by category for VAT / income tax reconciliation.
40
+
41
+ This server automates step 2 and 3 through your AI. You keep your bank data on disk; the AI just calls a tool that reads and filters it locally.
42
+
43
+ Zero network calls. The `requirements.txt` is one line — the MCP SDK. No dependency footprint to audit.
44
+
45
+ ## Features
46
+
47
+ Three tools:
48
+
49
+ - `read_statement_header` — quick preview of a file: client name, date range, listed accounts, inflow/outflow totals, operation count. No operation rows loaded.
50
+ - `list_operations` — parse + filter operations. Combine any of: `date_from`, `date_to`, `category`, `account`, `contains` (description substring), `min_amount`, `max_amount`, `limit`.
51
+ - `summarize_operations` — aggregate by `category`, `account`, or `month`. Returns count, inflow, outflow, net per bucket plus grand totals.
52
+
53
+ Amounts come back as signed floats (negative = expense), currency separate. Polish-locale numbers (`-3 283,33 PLN`) and non-breaking-space thousand separators are handled.
54
+
55
+ ## Supported files
56
+
57
+ - ✅ **CSV export** from mBank web banking ("Historia operacji" → "Eksportuj do CSV")
58
+ - ❌ PDF statements — mBank's layout varies too much per statement type for reliable parsing. Skipped intentionally.
59
+
60
+ ## Requirements
61
+
62
+ - Python 3.10+
63
+
64
+ ## Setup
65
+
66
+ ```bash
67
+ git clone https://github.com/bartosz-kuc/honest-mbank-parser-mcp.git
68
+ cd honest-mbank-parser-mcp
69
+ python3 -m venv venv
70
+ ./venv/bin/pip install -r requirements.txt
71
+ ```
72
+
73
+ On Windows use `python` instead of `python3`, and `venv\Scripts\pip` and `venv\Scripts\python` instead of `venv/bin/pip` and `venv/bin/python` (here and in the configs below).
74
+
75
+ Register with Claude Code:
76
+
77
+ ```bash
78
+ claude mcp add mbank /absolute/path/to/venv/bin/python /absolute/path/to/server.py
79
+ ```
80
+
81
+ Claude Desktop `claude_desktop_config.json`:
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "mbank": {
87
+ "command": "/absolute/path/to/venv/bin/python",
88
+ "args": ["/absolute/path/to/server.py"]
89
+ }
90
+ }
91
+ }
92
+ ```
93
+
94
+ ### Alternative: install from PyPI (`uvx`)
95
+
96
+ The server is also published on PyPI as `honest-mbank-parser-mcp`, so you can skip the clone and the venv. With [uv](https://docs.astral.sh/uv/) installed:
97
+
98
+ ```bash
99
+ claude mcp add mbank -- uvx honest-mbank-parser-mcp
100
+ ```
101
+
102
+ Claude Desktop `claude_desktop_config.json`:
103
+
104
+ ```json
105
+ {
106
+ "mcpServers": {
107
+ "mbank": {
108
+ "command": "uvx",
109
+ "args": ["honest-mbank-parser-mcp"]
110
+ }
111
+ }
112
+ }
113
+ ```
114
+
115
+ `pip install honest-mbank-parser-mcp` works too; it installs the `honest-mbank-parser-mcp` command.
116
+
117
+ ## Example usage
118
+
119
+ > "How much did I spend on 'Ubezpieczenia' in Q2?"
120
+
121
+ `summarize_operations(file_path=".../lista_operacji.csv", group_by="category", date_from="2026-04-01", date_to="2026-06-30")` → totals per category, including "Ubezpieczenia".
122
+
123
+ > "List all incoming transfers over 10 000 PLN this year."
124
+
125
+ `list_operations(file_path=".../lista_operacji.csv", min_amount=10000, date_from="2026-01-01")`
126
+
127
+ > "Show me every card purchase mentioning Anthropic."
128
+
129
+ `list_operations(file_path=".../lista_operacji.csv", contains="ANTHROPIC")`
130
+
131
+ ## Data flow
132
+
133
+ ```
134
+ Your AI client
135
+ ↕ MCP stdio
136
+ This server (Python, on your machine)
137
+ ↕ local filesystem
138
+ Your mBank CSV
139
+ ```
140
+
141
+ No HTTP, no external service — the server has no `requests` or `httpx` dependency at all.
142
+
143
+ ## Author
144
+
145
+ **Bartosz Kuć** — Warsaw-based developer, JDG owner running [skanfirmy.pl](https://skanfirmy.pl).
146
+
147
+ - GitHub: https://github.com/bartosz-kuc
148
+
149
+ - Email: firma@bartosza.pl
150
+
151
+ ## Consulting
152
+
153
+ Available for consulting on Polish tax and business integrations (KSeF, GUS/NFZ/GIOŚ APIs, mBank data), MCP server design, and AI-assisted tooling for JDGs and small teams. See **[skanfirmy.pl/uslugi](https://skanfirmy.pl/uslugi)** for productized packages (audit 3k PLN, setup 8-15k PLN, retainer 2-4k PLN/mo), or reach out via email.
154
+
155
+ ## License
156
+
157
+ MIT — see [LICENSE](LICENSE).
158
+
159
+ ## Related
160
+
161
+ - Part of the honest-mcp family — see the [family index](https://github.com/bartosz-kuc?tab=repositories).
@@ -0,0 +1,137 @@
1
+ # mbank-parser-mcp
2
+
3
+ <!-- mcp-name: io.github.bartosz-kuc/honest-mbank-parser-mcp -->
4
+
5
+ Local MCP server that parses **mBank CSV operation exports** — the exact file you can download from the mBank web app under "Historia" → "Eksportuj do CSV". Runs entirely offline. Nothing leaves your machine.
6
+
7
+ Part of the [honest-mcp family](https://github.com/bartosz-kuc?tab=repositories) of small, auditable, local-first MCP servers.
8
+
9
+ ## Why
10
+
11
+ Anyone using mBank in Poland — private, JDG, sp. z o.o. — does the same monthly ritual:
12
+
13
+ 1. Log into mBank, download the CSV.
14
+ 2. Open in Excel, squint at Polish-locale amounts (space-thousands, comma-decimals, ` PLN` suffix).
15
+ 3. Filter by date, sum by category for VAT / income tax reconciliation.
16
+
17
+ This server automates step 2 and 3 through your AI. You keep your bank data on disk; the AI just calls a tool that reads and filters it locally.
18
+
19
+ Zero network calls. The `requirements.txt` is one line — the MCP SDK. No dependency footprint to audit.
20
+
21
+ ## Features
22
+
23
+ Three tools:
24
+
25
+ - `read_statement_header` — quick preview of a file: client name, date range, listed accounts, inflow/outflow totals, operation count. No operation rows loaded.
26
+ - `list_operations` — parse + filter operations. Combine any of: `date_from`, `date_to`, `category`, `account`, `contains` (description substring), `min_amount`, `max_amount`, `limit`.
27
+ - `summarize_operations` — aggregate by `category`, `account`, or `month`. Returns count, inflow, outflow, net per bucket plus grand totals.
28
+
29
+ Amounts come back as signed floats (negative = expense), currency separate. Polish-locale numbers (`-3 283,33 PLN`) and non-breaking-space thousand separators are handled.
30
+
31
+ ## Supported files
32
+
33
+ - ✅ **CSV export** from mBank web banking ("Historia operacji" → "Eksportuj do CSV")
34
+ - ❌ PDF statements — mBank's layout varies too much per statement type for reliable parsing. Skipped intentionally.
35
+
36
+ ## Requirements
37
+
38
+ - Python 3.10+
39
+
40
+ ## Setup
41
+
42
+ ```bash
43
+ git clone https://github.com/bartosz-kuc/honest-mbank-parser-mcp.git
44
+ cd honest-mbank-parser-mcp
45
+ python3 -m venv venv
46
+ ./venv/bin/pip install -r requirements.txt
47
+ ```
48
+
49
+ On Windows use `python` instead of `python3`, and `venv\Scripts\pip` and `venv\Scripts\python` instead of `venv/bin/pip` and `venv/bin/python` (here and in the configs below).
50
+
51
+ Register with Claude Code:
52
+
53
+ ```bash
54
+ claude mcp add mbank /absolute/path/to/venv/bin/python /absolute/path/to/server.py
55
+ ```
56
+
57
+ Claude Desktop `claude_desktop_config.json`:
58
+
59
+ ```json
60
+ {
61
+ "mcpServers": {
62
+ "mbank": {
63
+ "command": "/absolute/path/to/venv/bin/python",
64
+ "args": ["/absolute/path/to/server.py"]
65
+ }
66
+ }
67
+ }
68
+ ```
69
+
70
+ ### Alternative: install from PyPI (`uvx`)
71
+
72
+ The server is also published on PyPI as `honest-mbank-parser-mcp`, so you can skip the clone and the venv. With [uv](https://docs.astral.sh/uv/) installed:
73
+
74
+ ```bash
75
+ claude mcp add mbank -- uvx honest-mbank-parser-mcp
76
+ ```
77
+
78
+ Claude Desktop `claude_desktop_config.json`:
79
+
80
+ ```json
81
+ {
82
+ "mcpServers": {
83
+ "mbank": {
84
+ "command": "uvx",
85
+ "args": ["honest-mbank-parser-mcp"]
86
+ }
87
+ }
88
+ }
89
+ ```
90
+
91
+ `pip install honest-mbank-parser-mcp` works too; it installs the `honest-mbank-parser-mcp` command.
92
+
93
+ ## Example usage
94
+
95
+ > "How much did I spend on 'Ubezpieczenia' in Q2?"
96
+
97
+ `summarize_operations(file_path=".../lista_operacji.csv", group_by="category", date_from="2026-04-01", date_to="2026-06-30")` → totals per category, including "Ubezpieczenia".
98
+
99
+ > "List all incoming transfers over 10 000 PLN this year."
100
+
101
+ `list_operations(file_path=".../lista_operacji.csv", min_amount=10000, date_from="2026-01-01")`
102
+
103
+ > "Show me every card purchase mentioning Anthropic."
104
+
105
+ `list_operations(file_path=".../lista_operacji.csv", contains="ANTHROPIC")`
106
+
107
+ ## Data flow
108
+
109
+ ```
110
+ Your AI client
111
+ ↕ MCP stdio
112
+ This server (Python, on your machine)
113
+ ↕ local filesystem
114
+ Your mBank CSV
115
+ ```
116
+
117
+ No HTTP, no external service — the server has no `requests` or `httpx` dependency at all.
118
+
119
+ ## Author
120
+
121
+ **Bartosz Kuć** — Warsaw-based developer, JDG owner running [skanfirmy.pl](https://skanfirmy.pl).
122
+
123
+ - GitHub: https://github.com/bartosz-kuc
124
+
125
+ - Email: firma@bartosza.pl
126
+
127
+ ## Consulting
128
+
129
+ Available for consulting on Polish tax and business integrations (KSeF, GUS/NFZ/GIOŚ APIs, mBank data), MCP server design, and AI-assisted tooling for JDGs and small teams. See **[skanfirmy.pl/uslugi](https://skanfirmy.pl/uslugi)** for productized packages (audit 3k PLN, setup 8-15k PLN, retainer 2-4k PLN/mo), or reach out via email.
130
+
131
+ ## License
132
+
133
+ MIT — see [LICENSE](LICENSE).
134
+
135
+ ## Related
136
+
137
+ - Part of the honest-mcp family — see the [family index](https://github.com/bartosz-kuc?tab=repositories).
@@ -0,0 +1,35 @@
1
+ # Security Policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ If you find a security issue in this MCP server, please email **firma@bartosza.pl**. Do **not** open a public GitHub issue.
6
+
7
+ - I aim to respond within 48 hours. This is a solo hobby project — there is no formal SLA — but security reports are the fastest path to my attention.
8
+ - Please include: version / commit hash affected, steps to reproduce, and the impact scenario.
9
+ - PGP key available on request. Otherwise, plain email is fine.
10
+
11
+ ## Scope
12
+
13
+ This server is one member of the [honest-mcp family](https://github.com/bartosz-kuc?tab=repositories). If your report affects the family pattern broadly, I will coordinate cross-repository disclosure.
14
+
15
+ **In scope:**
16
+ - Code execution paths in `server.py` that could be triggered by AI-client input
17
+ - Handling of authentication material (OAuth tokens, API keys, session state)
18
+ - Any path that could exfiltrate data past the documented "AI ↔ MCP server ↔ upstream API" trust boundary
19
+ - Dependency vulnerabilities that materially expand attack surface
20
+
21
+ **Not in scope:**
22
+ - Whatever your AI client itself can reach — that is the intended data flow. Trust boundaries are between your AI client and the external service the server wraps.
23
+ - Local credential files (e.g. `credentials.json`, `token.json`) that you generate on your own machine per the setup instructions. These are your responsibility; the shipped `.gitignore` prevents accidental commits.
24
+ - Denial-of-service via upstream rate limits (each server documents which public APIs it hits).
25
+
26
+ ## Supported versions
27
+
28
+ Only the current `main` branch is supported. Releases are tagged from `main` and any accepted security fix will be published as a new tagged patch release.
29
+
30
+ ## Automated safeguards enabled on this repo
31
+
32
+ - Dependabot alerts and version updates (weekly)
33
+ - Automated security fixes for published CVEs in dependencies
34
+ - Secret scanning + push protection (blocks accidental credential commits)
35
+ - CodeQL static analysis on push and PR
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "honest-mbank-parser-mcp"
7
+ version = "0.2.0"
8
+ description = "Local MCP server that parses mBank CSV operation exports — fully offline, no bank connection."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Bartosz Kuć", email = "firma@bartosza.pl" }]
13
+ keywords = ["mcp", "mbank", "csv", "parsing", "offline", "finance"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ ]
25
+ dependencies = [
26
+ "mcp>=2.0.0,<3.0.0",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/bartosz-kuc/honest-mbank-parser-mcp"
31
+ Repository = "https://github.com/bartosz-kuc/honest-mbank-parser-mcp"
32
+ Issues = "https://github.com/bartosz-kuc/honest-mbank-parser-mcp/issues"
33
+
34
+ [project.scripts]
35
+ honest-mbank-parser-mcp = "honest_mbank_parser_mcp:sync_main"
36
+ mbank-parser-mcp = "honest_mbank_parser_mcp:sync_main"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ sources = ["."]
40
+ only-include = ["server.py"]
41
+
42
+ [tool.hatch.build.targets.wheel.force-include]
43
+ "server.py" = "honest_mbank_parser_mcp.py"
44
+
45
+ [tool.hatch.build.targets.sdist]
46
+ include = ["server.py", "README.md", "LICENSE", "SECURITY.md", "pyproject.toml"]
@@ -0,0 +1,365 @@
1
+ """mbank-parser-mcp — MCP server for parsing mBank CSV exports.
2
+
3
+ Parses the CSV format that mBank's web banking exports for the "Lista
4
+ operacji" report. Everything is local: files stay on your disk, and this
5
+ server does no network I/O at all.
6
+
7
+ Primary use case: a Polish JDG (or personal accountant) doing monthly cost
8
+ reconciliation, VAT prep, or category-based expense summaries without
9
+ uploading bank data to any cloud service.
10
+
11
+ Tools: list_operations, summarize_operations, read_statement_header.
12
+
13
+ Note: PDF statements are not supported in v1 — mBank's PDF layout varies
14
+ across statement types and OCR-lite extraction is unreliable. Use the CSV
15
+ export from the mBank web app ("Historia" → "Eksportuj do CSV").
16
+
17
+ Author: Bartosz Kuć <firma@bartosza.pl>
18
+ Repo: https://github.com/bartosz-kuc/honest-mbank-parser-mcp
19
+ License: MIT
20
+ """
21
+
22
+ import asyncio
23
+ import csv
24
+ import io
25
+ import json
26
+ import os
27
+ import re
28
+ from collections import defaultdict
29
+ from decimal import Decimal, InvalidOperation
30
+ from typing import Any
31
+
32
+ from mcp import types
33
+ from mcp.server import Server
34
+ from mcp.server.stdio import stdio_server
35
+ from mcp.types import CallToolResult, ListToolsResult, TextContent, Tool
36
+
37
+ DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
38
+ AMOUNT_RE = re.compile(r"^\s*(-?)\s*([\d\s ]+),(\d{2})\s*([A-Z]{3})?\s*$")
39
+
40
+
41
+ def _read_text(path: str) -> str:
42
+ if not os.path.isfile(path):
43
+ raise FileNotFoundError(f"File not found: {path}")
44
+ with open(path, "rb") as fh:
45
+ raw = fh.read()
46
+ # mBank CSV exports are UTF-8 with BOM. Fall back to cp1250 for older exports.
47
+ for enc in ("utf-8-sig", "utf-8", "cp1250"):
48
+ try:
49
+ return raw.decode(enc)
50
+ except UnicodeDecodeError:
51
+ continue
52
+ raise ValueError(f"Cannot decode {path} as UTF-8 or cp1250")
53
+
54
+
55
+ def _parse_amount(raw: str) -> tuple[Decimal, str]:
56
+ """Parse '−3 283,33 PLN' → (Decimal('-3283.33'), 'PLN'). Non-breaking space is common in mBank exports."""
57
+ m = AMOUNT_RE.match(raw)
58
+ if not m:
59
+ raise ValueError(f"Cannot parse amount {raw!r}")
60
+ sign, ints, decs, currency = m.groups()
61
+ # Strip regular and non-breaking spaces from integer part
62
+ ints_clean = re.sub(r"[\s ]", "", ints)
63
+ try:
64
+ value = Decimal(f"{sign}{ints_clean}.{decs}")
65
+ except InvalidOperation as exc:
66
+ raise ValueError(f"Cannot parse amount {raw!r}: {exc}")
67
+ return value, currency or "PLN"
68
+
69
+
70
+ def _dequote(s: str) -> str:
71
+ s = s.strip()
72
+ if len(s) >= 2 and s[0] == '"' and s[-1] == '"':
73
+ s = s[1:-1]
74
+ # mBank pads with many trailing spaces inside the quotes; collapse
75
+ s = re.sub(r"\s+", " ", s).strip()
76
+ return s
77
+
78
+
79
+ def _parse_file(path: str) -> dict:
80
+ text = _read_text(path)
81
+ # mBank uses ';' as delimiter throughout, including headers.
82
+ reader = csv.reader(io.StringIO(text), delimiter=";", quotechar='"')
83
+ rows = [row for row in reader if any(cell.strip() for cell in row)]
84
+
85
+ header: dict[str, Any] = {
86
+ "klient": None,
87
+ "period_from": None,
88
+ "period_to": None,
89
+ "accounts": [],
90
+ "totals": {},
91
+ }
92
+
93
+ ops: list[dict] = []
94
+ in_ops = False
95
+ seen_ops_header = False
96
+ seen_currency_header = False
97
+
98
+ for row in rows:
99
+ first = row[0].strip() if row else ""
100
+
101
+ if not in_ops:
102
+ # Section markers vary in casing/prefix — probe fuzzily.
103
+ if first == "#Klient" and len(rows) > rows.index(row) + 1:
104
+ # next non-empty row is name; but we can also read the immediately following row here
105
+ continue
106
+ if header["klient"] is None and rows.index(row) > 0 and rows[rows.index(row) - 1][0].strip() == "#Klient":
107
+ header["klient"] = first
108
+ continue
109
+ if first == "#Za okres:":
110
+ # Next row has the two dates.
111
+ continue
112
+ if header["period_from"] is None and rows.index(row) > 0 and rows[rows.index(row) - 1][0].strip() == "#Za okres:":
113
+ # Format: dd.mm.yyyy;dd.mm.yyyy;
114
+ if len(row) >= 2:
115
+ header["period_from"] = row[0].strip()
116
+ header["period_to"] = row[1].strip()
117
+ continue
118
+ # Account rows are indented and contain " - <IBAN-like>"
119
+ if " - " in first and ("konto" in first.lower() or "rachunek" in first.lower() or re.search(r"\d{10,}", first)):
120
+ header["accounts"].append(first.strip())
121
+ continue
122
+ # Currency/totals header
123
+ if first == "#Waluta":
124
+ seen_currency_header = True
125
+ continue
126
+ if seen_currency_header and len(row) >= 3 and re.match(r"^[A-Z]{3}$", first):
127
+ header["totals"][first] = {
128
+ "inflow": row[1].strip(),
129
+ "outflow": row[2].strip(),
130
+ }
131
+ seen_currency_header = False
132
+ continue
133
+ # Operation header
134
+ if first == "#Data operacji":
135
+ seen_ops_header = True
136
+ in_ops = True
137
+ continue
138
+
139
+ if in_ops:
140
+ if len(row) < 5:
141
+ continue
142
+ date_str = row[0].strip()
143
+ if not DATE_RE.match(date_str):
144
+ continue
145
+ desc = _dequote(row[1])
146
+ account = _dequote(row[2])
147
+ category = _dequote(row[3])
148
+ amount_raw = row[4].strip()
149
+ try:
150
+ amount, currency = _parse_amount(amount_raw)
151
+ except ValueError:
152
+ # Skip malformed row rather than fail whole file
153
+ continue
154
+ ops.append({
155
+ "date": date_str,
156
+ "description": desc,
157
+ "account": account,
158
+ "category": category,
159
+ "amount": float(amount),
160
+ "currency": currency,
161
+ "amount_raw": amount_raw,
162
+ })
163
+
164
+ if not seen_ops_header:
165
+ raise ValueError("Could not locate '#Data operacji' header row. Is this really an mBank operations CSV export?")
166
+
167
+ return {"header": header, "operations": ops}
168
+
169
+
170
+ def _iso_or_none(d: str | None) -> str | None:
171
+ if d is None:
172
+ return None
173
+ d = d.strip()
174
+ if not DATE_RE.match(d):
175
+ raise ValueError(f"Date must be YYYY-MM-DD, got {d!r}")
176
+ return d
177
+
178
+
179
+ def _apply_filters(ops: list[dict], filters: dict) -> list[dict]:
180
+ date_from = _iso_or_none(filters.get("date_from"))
181
+ date_to = _iso_or_none(filters.get("date_to"))
182
+ category_sub = (filters.get("category") or "").strip().lower()
183
+ account_sub = (filters.get("account") or "").strip().lower()
184
+ contains_sub = (filters.get("contains") or "").strip().lower()
185
+ min_amount = filters.get("min_amount")
186
+ max_amount = filters.get("max_amount")
187
+
188
+ out: list[dict] = []
189
+ for op in ops:
190
+ if date_from and op["date"] < date_from:
191
+ continue
192
+ if date_to and op["date"] > date_to:
193
+ continue
194
+ if category_sub and category_sub not in op["category"].lower():
195
+ continue
196
+ if account_sub and account_sub not in op["account"].lower():
197
+ continue
198
+ if contains_sub and contains_sub not in op["description"].lower():
199
+ continue
200
+ if min_amount is not None and op["amount"] < float(min_amount):
201
+ continue
202
+ if max_amount is not None and op["amount"] > float(max_amount):
203
+ continue
204
+ out.append(op)
205
+ return out
206
+
207
+
208
+ server = Server("mbank-parser")
209
+
210
+
211
+ _FILTER_PROPERTIES = {
212
+ "date_from": {"type": "string", "description": "YYYY-MM-DD, inclusive"},
213
+ "date_to": {"type": "string", "description": "YYYY-MM-DD, inclusive"},
214
+ "category": {"type": "string", "description": "Substring match against mBank's assigned category (case-insensitive)"},
215
+ "account": {"type": "string", "description": "Substring match against account label (case-insensitive)"},
216
+ "contains": {"type": "string", "description": "Substring match against operation description (case-insensitive)"},
217
+ "min_amount": {"type": "number", "description": "Minimum amount (inclusive). Signed — negative for expenses."},
218
+ "max_amount": {"type": "number", "description": "Maximum amount (inclusive)"},
219
+ }
220
+
221
+
222
+ async def _list_tools() -> list[Tool]:
223
+ return [
224
+ Tool(
225
+ name="read_statement_header",
226
+ description=(
227
+ "Read only the header block of an mBank CSV export — client name, date range, listed accounts, "
228
+ "inflow/outflow totals — without loading the operation rows. Fast preview to confirm you have the right file."
229
+ ),
230
+ inputSchema={
231
+ "type": "object",
232
+ "properties": {
233
+ "file_path": {"type": "string", "description": "Absolute path to the mBank CSV file"},
234
+ },
235
+ "required": ["file_path"],
236
+ },
237
+ ),
238
+ Tool(
239
+ name="list_operations",
240
+ description=(
241
+ "Parse an mBank CSV operations export and return the operation rows (date, description, account, category, "
242
+ "signed amount, currency). All filters are optional; combine them freely. Amounts are already parsed to "
243
+ "floats (negative = expense). For big statements consider a `limit` to keep response size in check."
244
+ ),
245
+ inputSchema={
246
+ "type": "object",
247
+ "properties": {
248
+ "file_path": {"type": "string", "description": "Absolute path to the mBank CSV file"},
249
+ **_FILTER_PROPERTIES,
250
+ "limit": {"type": "integer", "description": "Max operations to return (default: all)"},
251
+ "include_header": {"type": "boolean", "default": False, "description": "If true, include the header block alongside operations"},
252
+ },
253
+ "required": ["file_path"],
254
+ },
255
+ ),
256
+ Tool(
257
+ name="summarize_operations",
258
+ description=(
259
+ "Aggregate operations by category, by account, or by month. Returns count, total inflow, total outflow, "
260
+ "net per bucket, plus the grand totals over the filtered set. Ideal for building a monthly expense report or "
261
+ "checking VAT-relevant categories."
262
+ ),
263
+ inputSchema={
264
+ "type": "object",
265
+ "properties": {
266
+ "file_path": {"type": "string", "description": "Absolute path to the mBank CSV file"},
267
+ "group_by": {"type": "string", "enum": ["category", "account", "month"], "default": "category"},
268
+ **_FILTER_PROPERTIES,
269
+ },
270
+ "required": ["file_path"],
271
+ },
272
+ ),
273
+ ]
274
+
275
+
276
+ async def _call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
277
+ if name == "read_statement_header":
278
+ parsed = _parse_file(arguments["file_path"])
279
+ header = dict(parsed["header"])
280
+ header["operation_count"] = len(parsed["operations"])
281
+ return [TextContent(type="text", text=json.dumps(header, ensure_ascii=False, indent=2))]
282
+
283
+ if name == "list_operations":
284
+ parsed = _parse_file(arguments["file_path"])
285
+ ops = _apply_filters(parsed["operations"], arguments)
286
+ limit = arguments.get("limit")
287
+ if limit is not None:
288
+ ops = ops[: int(limit)]
289
+ payload: dict[str, Any] = {"returned": len(ops), "operations": ops}
290
+ if arguments.get("include_header"):
291
+ payload["header"] = parsed["header"]
292
+ return [TextContent(type="text", text=json.dumps(payload, ensure_ascii=False, indent=2))]
293
+
294
+ if name == "summarize_operations":
295
+ parsed = _parse_file(arguments["file_path"])
296
+ ops = _apply_filters(parsed["operations"], arguments)
297
+ group_by = arguments.get("group_by", "category")
298
+
299
+ buckets: dict[str, dict] = defaultdict(lambda: {"count": 0, "inflow": 0.0, "outflow": 0.0})
300
+ for op in ops:
301
+ if group_by == "category":
302
+ key = op["category"] or "(no category)"
303
+ elif group_by == "account":
304
+ key = op["account"] or "(no account)"
305
+ elif group_by == "month":
306
+ key = op["date"][:7]
307
+ else:
308
+ raise ValueError(f"Unknown group_by: {group_by}")
309
+ b = buckets[key]
310
+ b["count"] += 1
311
+ if op["amount"] >= 0:
312
+ b["inflow"] += op["amount"]
313
+ else:
314
+ b["outflow"] += op["amount"]
315
+
316
+ summary = [
317
+ {
318
+ "key": k,
319
+ "count": v["count"],
320
+ "inflow": round(v["inflow"], 2),
321
+ "outflow": round(v["outflow"], 2),
322
+ "net": round(v["inflow"] + v["outflow"], 2),
323
+ }
324
+ for k, v in sorted(buckets.items(), key=lambda kv: (kv[1]["inflow"] + kv[1]["outflow"]))
325
+ ]
326
+ totals = {
327
+ "total_operations": len(ops),
328
+ "total_inflow": round(sum(o["amount"] for o in ops if o["amount"] >= 0), 2),
329
+ "total_outflow": round(sum(o["amount"] for o in ops if o["amount"] < 0), 2),
330
+ }
331
+ totals["net"] = round(totals["total_inflow"] + totals["total_outflow"], 2)
332
+
333
+ return [TextContent(type="text", text=json.dumps({
334
+ "group_by": group_by,
335
+ "buckets": summary,
336
+ "totals": totals,
337
+ }, ensure_ascii=False, indent=2))]
338
+
339
+ raise ValueError(f"Unknown tool: {name}")
340
+
341
+
342
+ async def on_list_tools(ctx, params) -> ListToolsResult:
343
+ return ListToolsResult(tools=await _list_tools())
344
+
345
+
346
+ async def on_call_tool(ctx, params) -> CallToolResult:
347
+ return CallToolResult(content=await _call_tool(params.name, params.arguments or {}))
348
+
349
+
350
+ server.add_request_handler("tools/list", types.PaginatedRequestParams, on_list_tools)
351
+ server.add_request_handler("tools/call", types.CallToolRequestParams, on_call_tool)
352
+
353
+
354
+ async def main():
355
+ async with stdio_server() as (read, write):
356
+ await server.run(read, write, server.create_initialization_options())
357
+
358
+
359
+ def sync_main():
360
+ """Sync entry point for console script."""
361
+ asyncio.run(main())
362
+
363
+
364
+ if __name__ == "__main__":
365
+ sync_main()