md-chunk-lite 1.0.0__py3-none-any.whl

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,236 @@
1
+ Metadata-Version: 2.4
2
+ Name: md-chunk-lite
3
+ Version: 1.0.0
4
+ Summary: Split Markdown into chunks by heading. Each chunk keeps its heading path and line numbers. CLI and MCP server. Runs locally.
5
+ Author: Tidy Byte Tools
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/tidybytetools/md-chunk-lite
8
+ Project-URL: Source, https://github.com/tidybytetools/md-chunk-lite
9
+ Project-URL: Issues, https://github.com/tidybytetools/md-chunk-lite/issues
10
+ Project-URL: Changelog, https://github.com/tidybytetools/md-chunk-lite/blob/main/CHANGELOG.md
11
+ Keywords: markdown,chunking,text-splitter,rag,llm,embeddings,headings,jsonl,cli,mcp,mcp-server
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
23
+ Classifier: Topic :: Text Processing :: Indexing
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: mcp<2,>=1.10
29
+ Dynamic: license-file
30
+
31
+ <p>
32
+ <a href="https://github.com/tidybytetools">
33
+ <picture>
34
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tidybytetools/md-chunk-lite/main/assets/tidybytetools-lockup-dark.png">
35
+ <img alt="Tidy Byte Tools" src="https://raw.githubusercontent.com/tidybytetools/md-chunk-lite/main/assets/tidybytetools-lockup-light.png" height="44">
36
+ </picture>
37
+ </a>
38
+ </p>
39
+
40
+ # md-chunk-lite
41
+
42
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/tidybytetools/md-chunk-lite/blob/main/LICENSE)
43
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
44
+ [![MCP server](https://img.shields.io/badge/MCP-stdio-purple.svg)](#use-it-from-claude-desktop-or-cursor-mcp)
45
+ [![Tests](https://github.com/tidybytetools/md-chunk-lite/actions/workflows/tests.yml/badge.svg)](https://github.com/tidybytetools/md-chunk-lite/actions/workflows/tests.yml)
46
+
47
+ Free tool that splits Markdown into chunks by heading. Every chunk knows its heading path and the line numbers it came from.
48
+ Need PDF, Word or web page files turned into chunks (with page numbers for PDFs), or whole folders? The paid doc2md does that: **[doc2md on Gumroad](https://tidybyte.gumroad.com/l/frlkv)**
49
+
50
+ Good for AI search (RAG), embeddings, and docs bots. Plain code, not AI, so the same file always gives the same chunks. Runs on your own computer. MIT license. Python 3.10 or newer, on Windows, Mac and Linux.
51
+
52
+ <!-- mcp-name: io.github.tidybytetools/md-chunk-lite -->
53
+
54
+ ## Install
55
+
56
+ ```
57
+ pip install md-chunk-lite
58
+ ```
59
+
60
+ Or use pipx, which keeps it in its own space:
61
+
62
+ ```
63
+ pipx install md-chunk-lite
64
+ ```
65
+
66
+ Want the newest code from GitHub instead?
67
+
68
+ ```
69
+ pip install git+https://github.com/tidybytetools/md-chunk-lite
70
+ ```
71
+
72
+ ## Use it
73
+
74
+ ```
75
+ md-chunk-lite guide.md # writes guide.chunks.jsonl
76
+ md-chunk-lite docs/*.md -o all.jsonl # many files into one file
77
+ md-chunk-lite guide.md -o - # print the chunks on screen
78
+ md-chunk-lite guide.md --max-chars 800 # smaller chunks
79
+ md-chunk-lite guide.md --outline # just show the headings
80
+ cat guide.md | md-chunk-lite - # read from stdin
81
+ ```
82
+
83
+ Example run:
84
+
85
+ ```
86
+ Saved: guide.chunks.jsonl (7 chunks, biggest 151 chars)
87
+ ```
88
+
89
+ Each line of the `.jsonl` file is one chunk:
90
+
91
+ ```json
92
+ {
93
+ "id": "guide.md#3",
94
+ "source": "guide.md",
95
+ "index": 3,
96
+ "heading_path": ["Garden Guide", "Planting", "Tomatoes"],
97
+ "heading_level": 3,
98
+ "anchor": "tomatoes",
99
+ "start_line": 16,
100
+ "end_line": 24,
101
+ "part": 1,
102
+ "parts": 1,
103
+ "chars": 151,
104
+ "text": "### Tomatoes\n\nPlant tomatoes after the last frost. Give them sun.\n\n```python\n..."
105
+ }
106
+ ```
107
+
108
+ - `heading_path`: all the headings above this chunk, from the top.
109
+ - `anchor`: the `#link` GitHub makes for that heading, so you can link straight to it.
110
+ - `start_line` and `end_line`: where the chunk is in the file (the first line is 1).
111
+ - `part` and `parts`: a big section is split into parts. `part 2, parts 3` means the 2nd of 3.
112
+ - `chars`: how long `text` is.
113
+
114
+ `--outline` prints the headings:
115
+
116
+ ```
117
+ Garden Guide [line 8, #garden-guide, 14 chars]
118
+ Tools [line 10, #tools, 47 chars]
119
+ Planting [line 14, #planting, 11 chars]
120
+ Tomatoes [line 16, #tomatoes, 151 chars]
121
+ ```
122
+
123
+ When you run it in a terminal it ends with one short line about the paid doc2md. `--quiet` turns it off, and it never shows when output is piped or redirected.
124
+
125
+ ## How it splits
126
+
127
+ 1. Each heading starts a new section. A chunk never mixes two sections, so every chunk has one clear heading path.
128
+ 2. A small section becomes one chunk. Its text is copied straight from your file, so the line numbers match.
129
+ 3. A big section is split at blank lines. Lists, tables and code blocks stay whole when they fit.
130
+ 4. A table that is too big is split by rows, and each part gets the header row again.
131
+ 5. A code block that is too big is split by lines, and each part gets its own ``` fence again, with the same language.
132
+ 6. A very long line is cut at the end of a sentence, then at a space if it has to be.
133
+ 7. A heading with no text of its own (just more headings under it) does not get its own chunk, but it still shows in the `heading_path` of the chunks under it.
134
+
135
+ It knows `#` headings and underlined headings (`===` and `---`). It skips headings inside code blocks and YAML front matter (the `---` block at the very top).
136
+
137
+ Options:
138
+
139
+ - `--max-chars N`: biggest chunk, in characters (default 1500, smallest 200). About 4 characters make 1 token in English.
140
+ - `--overlap-chars N`: when a section is split, start each part with up to N characters from the end of the part before it (default 0). It is never added inside a code block or table, and never between two different sections.
141
+ - `--prefix-path`: start each chunk's text with its heading path, like `Garden Guide > Planting > Tomatoes`. This often helps search. It counts toward `--max-chars`.
142
+ - `--json`: print one JSON object for scripts and AI agents instead of saving a file.
143
+
144
+ ## Known limits
145
+
146
+ - **Sizes are characters, not tokens.** It does not load a tokenizer.
147
+ - **Markdown and plain text only.** PDF, Word and HTML are not read. The paid doc2md turns those into chunks (with page numbers for PDFs).
148
+ - **No folders.** Give it files (your shell can expand `docs/*.md`). The paid doc2md walks whole folders.
149
+ - **Not a full Markdown parser.** A heading inside an HTML block, or an underlined heading that spans more than one line, may be handled wrong.
150
+ - **Overlap uses whole words** from the part before, so it can be a little shorter than you asked for.
151
+
152
+ ## Lite vs paid
153
+
154
+ | | md-chunk-lite (free) | [doc2md](https://tidybyte.gumroad.com/l/frlkv) (paid) |
155
+ |---|---|---|
156
+ | Reads | Markdown and text files | PDF, Word (.docx) and HTML |
157
+ | Chunks with the heading path | yes | yes |
158
+ | Line numbers and anchors | yes | no (page numbers for PDFs instead) |
159
+ | Rough token count on each chunk | no | yes |
160
+ | Whole folders, sub-folders too | no | yes |
161
+ | MCP server | yes | no |
162
+
163
+ ## Other good free tools
164
+
165
+ Pick what fits you. If you already use LangChain, its `MarkdownHeaderTextSplitter` also splits by heading. [Chonkie](https://github.com/feyninc/chonkie) and [semchunk](https://github.com/isaacus-dev/semchunk) split any text by token count. md-chunk-lite is small, MIT, has no AI or tokenizer parts, gives you line numbers and anchors, and has an MCP server built in.
166
+
167
+ ## Use it from Claude Desktop or Cursor (MCP)
168
+
169
+ There is a small free MCP server built in. It needs [uv](https://docs.astral.sh/uv/).
170
+
171
+ Run it by hand to check it starts (it waits quietly for an app to talk to it):
172
+
173
+ ```
174
+ uvx md-chunk-lite mcp
175
+ ```
176
+
177
+ Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
178
+
179
+ ```json
180
+ {
181
+ "mcpServers": {
182
+ "md-chunk-lite": {
183
+ "command": "uvx",
184
+ "args": ["md-chunk-lite", "mcp"]
185
+ }
186
+ }
187
+ }
188
+ ```
189
+
190
+ `uvx --from md-chunk-lite md-chunk-lite-mcp` starts the same server.
191
+
192
+ Tools (each one takes a file `path` or Markdown `text`):
193
+
194
+ | Tool | What it does | Changes files? |
195
+ |---|---|---|
196
+ | `chunk_markdown` | Splits into chunks. Returns 100 at a time; use `start` for more. | No |
197
+ | `outline_markdown` | Lists the headings with line numbers and anchors. | No |
198
+ | `get_section` | Gets one section by heading or anchor. | No |
199
+ | `save_chunks_jsonl` | Saves the chunks to a `.jsonl` file. | Writes one `.jsonl` file (replaces it if it is there) |
200
+
201
+ None of them use the internet.
202
+
203
+ ## For AI agents
204
+
205
+ - **Use when:** you have a Markdown or text file (docs, notes, a README) and need chunks with heading paths and line numbers for search, embeddings or citing sources. Use `outline_markdown` and `get_section` to read just one part of a long file.
206
+ - **Don't use when:** the file is PDF, Word or HTML (convert it first), or you need token-exact sizes.
207
+ - **Input:** a file path or Markdown text, plus `max_chars` (default 1500), `overlap_chars` (default 0) and `prefix_path` (default false).
208
+ - **Output:** chunks with `id`, `source`, `index`, `heading_path`, `heading_level`, `anchor`, `start_line`, `end_line`, `part`, `parts`, `chars`, `text`.
209
+ - CLI exit code is 0 on success and 1 on error (message on stderr, or `{"ok": false, "error": ...}` with `--json`). See also [`llms.txt`](https://github.com/tidybytetools/md-chunk-lite/blob/main/llms.txt).
210
+
211
+ ## Python
212
+
213
+ ```python
214
+ from md_chunk_lite import chunk_file, chunk_markdown, outline, get_section
215
+
216
+ chunks = chunk_file("guide.md", max_chars=1000)
217
+ for c in chunks:
218
+ print(c["heading_path"], c["start_line"], c["end_line"])
219
+
220
+ install = get_section(open("README.md").read(), heading="Install")
221
+ ```
222
+
223
+ The chunker file uses only Python's standard library. Installing with pip also adds the `mcp` package for the MCP server.
224
+
225
+ ## Tests
226
+
227
+ ```
228
+ pip install "mcp>=1.10,<2"
229
+ python3 -m unittest discover -s tests
230
+ ```
231
+
232
+ The MCP tests are skipped if `mcp` is not installed.
233
+
234
+ ## License
235
+
236
+ MIT. See `LICENSE`.
@@ -0,0 +1,8 @@
1
+ md_chunk_lite.py,sha256=U_OVObUiTsbsKOjhSTxwcw9mGxZFDqQtDc3jBqfBtlc,22027
2
+ md_chunk_lite_mcp.py,sha256=3y6XcmPchEaq4cVohjJZMrUIhcyn4h02Eq1mfD-MQY0,8000
3
+ md_chunk_lite-1.0.0.dist-info/licenses/LICENSE,sha256=IpHMoXz-sReyVcPkfbf_wfCz9SMBH18CuE2B6ALlrbI,1065
4
+ md_chunk_lite-1.0.0.dist-info/METADATA,sha256=1gZtHeQtv3_QX2pigPiyw-Oi4ln0KaB-PhqEh_XCWgI,10262
5
+ md_chunk_lite-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ md_chunk_lite-1.0.0.dist-info/entry_points.txt,sha256=AOQUeGazlSOMEbH_0bLeT4H6OBnVXaZjWDEpH3tI8eI,96
7
+ md_chunk_lite-1.0.0.dist-info/top_level.txt,sha256=0FPNK9J9E-c1J2X33D6F9hK94jbIz2WdyZsEN7xRf-k,32
8
+ md_chunk_lite-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ md-chunk-lite = md_chunk_lite:main
3
+ md-chunk-lite-mcp = md_chunk_lite_mcp:main
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tidybyte
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,2 @@
1
+ md_chunk_lite
2
+ md_chunk_lite_mcp
md_chunk_lite.py ADDED
@@ -0,0 +1,535 @@
1
+ #!/usr/bin/env python3
2
+ """md-chunk-lite (MIT): split Markdown into chunks by heading.
3
+
4
+ Every chunk keeps its heading path (like ["Guide", "Install", "Windows"]) and the
5
+ first and last line numbers it came from, so you can always find it again.
6
+ This file uses only the Python standard library. The MCP server
7
+ (md_chunk_lite_mcp.py) needs the mcp package.
8
+ """
9
+ import argparse, json, os, re, sys, unicodedata
10
+
11
+ __version__ = "1.0.0"
12
+ PRO_URL = "https://tidybyte.gumroad.com/l/frlkv"
13
+ PRO_LINE = f"Tip: need PDF, Word or HTML files turned into chunks, or whole folders? doc2md (paid): {PRO_URL}"
14
+
15
+ DEFAULT_MAX = 1500
16
+ MIN_ROOM = 40 # smallest space we will pack text into
17
+
18
+ _FENCE_OPEN = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
19
+ _ATX = re.compile(r"^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$")
20
+ _SETEXT = re.compile(r"^ {0,3}(=+|-+)[ \t]*$")
21
+ _TABLE_SEP = re.compile(r"^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$")
22
+ _NOT_SETEXT_TEXT = re.compile(r"^ {0,3}([-*+>|#]|\d+[.)]\s|```|~~~)")
23
+
24
+
25
+ # ---------------------------------------------------------------- reading the page
26
+
27
+ def _front_matter_end(lines):
28
+ """Index of the first line after YAML front matter (0 if there is none)."""
29
+ if lines and lines[0].strip() == "---":
30
+ for i in range(1, len(lines)):
31
+ if lines[i].strip() in ("---", "..."):
32
+ return i + 1
33
+ return 0
34
+
35
+
36
+ def _clean_title(raw):
37
+ """Heading text without closing #s, link targets, or * and ` marks."""
38
+ t = re.sub(r"[ \t]+#+[ \t]*$", "", " " + raw).strip()
39
+ if re.fullmatch(r"#+", t):
40
+ t = ""
41
+ t = re.sub(r"!?\[([^\]]*)\]\([^)]*\)", r"\1", t) # [text](url) -> text
42
+ t = re.sub(r"<[^>]+>", "", t) # inline html tags
43
+ t = t.replace("`", "").replace("**", "").replace("__", "")
44
+ t = re.sub(r"(?<!\w)[*_]([^*_]+)[*_](?!\w)", r"\1", t)
45
+ return " ".join(t.split())
46
+
47
+
48
+ def slugify(title):
49
+ """GitHub-style anchor: lower case, keep letters, numbers, - and _, spaces become -."""
50
+ s = unicodedata.normalize("NFKC", title).lower()
51
+ s = "".join(ch for ch in s if ch.isalnum() or ch in " -_")
52
+ return s.replace(" ", "-")
53
+
54
+
55
+ def scan(text):
56
+ """Find headings and code fences.
57
+
58
+ Returns (lines, body_start, headings, fences). Each heading is a dict with
59
+ level, title, line (0-based index of its first line) and size (1 or 2 lines).
60
+ fences is a dict {open line index: end index (exclusive)} for each code fence.
61
+ """
62
+ lines = text.splitlines()
63
+ start = _front_matter_end(lines)
64
+ headings, fences = [], {}
65
+ fence = None # (char, length, open index)
66
+ i = start
67
+ while i < len(lines):
68
+ line = lines[i]
69
+ if fence:
70
+ m = re.match(r"^ {0,3}(`{3,}|~{3,})[ \t]*$", line)
71
+ if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= fence[1]:
72
+ fences[fence[2]] = i + 1
73
+ fence = None
74
+ i += 1
75
+ continue
76
+ m = _FENCE_OPEN.match(line)
77
+ if m and not (m.group(1)[0] == "`" and "`" in m.group(2)):
78
+ fence = (m.group(1)[0], len(m.group(1)), i)
79
+ i += 1
80
+ continue
81
+ m = _ATX.match(line)
82
+ if m:
83
+ headings.append({"level": len(m.group(1)), "title": _clean_title(m.group(2) or ""), "line": i, "size": 1})
84
+ i += 1
85
+ continue
86
+ if (i + 1 < len(lines) and line.strip() and not _NOT_SETEXT_TEXT.match(line)
87
+ and not line.startswith((" ", "\t"))
88
+ and (i == start or not lines[i - 1].strip() or (headings and headings[-1]["line"] + headings[-1]["size"] == i))
89
+ and _SETEXT.match(lines[i + 1])):
90
+ level = 1 if lines[i + 1].strip()[0] == "=" else 2
91
+ headings.append({"level": level, "title": _clean_title(line), "line": i, "size": 2})
92
+ i += 2
93
+ continue
94
+ i += 1
95
+ if fence: # never closed: it runs to the end
96
+ fences[fence[2]] = len(lines)
97
+ return lines, start, headings, fences
98
+
99
+
100
+ def sections(text):
101
+ """Split the page into sections. Each heading starts one; text before the first heading is section 0.
102
+
103
+ Each section: level, title, path, anchor, start (0-based first line), end (0-based,
104
+ exclusive, before the next heading of any level), heading_size, sub_end (end
105
+ including sub-sections).
106
+ """
107
+ lines, start, heads, fence = scan(text)
108
+ out, stack, seen = [], [], {}
109
+ first = heads[0]["line"] if heads else len(lines)
110
+ if any(l.strip() for l in lines[start:first]):
111
+ out.append({"level": 0, "title": "", "path": [], "anchor": "", "start": start,
112
+ "end": first, "heading_size": 0, "sub_end": first})
113
+ for n, h in enumerate(heads):
114
+ while stack and stack[-1][0] >= h["level"]:
115
+ stack.pop()
116
+ stack.append((h["level"], h["title"]))
117
+ base = slugify(h["title"])
118
+ count = seen.get(base, 0)
119
+ seen[base] = count + 1
120
+ anchor = base if count == 0 else f"{base}-{count}"
121
+ end = heads[n + 1]["line"] if n + 1 < len(heads) else len(lines)
122
+ sub_end = len(lines)
123
+ for later in heads[n + 1:]:
124
+ if later["level"] <= h["level"]:
125
+ sub_end = later["line"]
126
+ break
127
+ out.append({"level": h["level"], "title": h["title"], "path": [t for _, t in stack],
128
+ "anchor": anchor, "start": h["line"], "end": end,
129
+ "heading_size": h["size"], "sub_end": sub_end})
130
+ return lines, out, fence
131
+
132
+
133
+ # ---------------------------------------------------------------- blocks and pieces
134
+ # A "unit" is one line (or one cut piece of a long line): (line_no or None, text, tag).
135
+ # tag is "line", "cut" (a piece of a longer line), or "wrap" (a fence or table
136
+ # header we repeat). line_no is 1-based; None means "added by us, not in the file".
137
+
138
+ def _blocks(lines, lo, hi, fences):
139
+ """Group lines lo..hi-1 into blocks: (kind, [indexes]). kind is gap, code, table or text."""
140
+ blocks, i = [], lo
141
+ while i < hi:
142
+ if i in fences:
143
+ j = min(fences[i], hi)
144
+ blocks.append(("code", list(range(i, j))))
145
+ i = j
146
+ continue
147
+ if not lines[i].strip():
148
+ blocks.append(("gap", [i]))
149
+ i += 1
150
+ continue
151
+ j = i
152
+ while j < hi and lines[j].strip() and j not in fences:
153
+ j += 1
154
+ idx = list(range(i, j))
155
+ is_table = len(idx) >= 2 and lines[i].lstrip().startswith("|") and _TABLE_SEP.match(lines[i + 1])
156
+ blocks.append(("table" if is_table else "text", idx))
157
+ i = j
158
+ return blocks
159
+
160
+
161
+ def _is_close(line):
162
+ return bool(re.match(r"^ {0,3}(`{3,}|~{3,})[ \t]*$", line))
163
+
164
+
165
+ def _cut(text, room):
166
+ """Cut one long line into pieces of at most `room` chars: at sentence ends, then spaces, then anywhere."""
167
+ def pack(parts, sep):
168
+ out, cur = [], ""
169
+ for p in parts:
170
+ cand = p if not cur else cur + sep + p
171
+ if len(cand) <= room:
172
+ cur = cand
173
+ else:
174
+ if cur:
175
+ out.append(cur)
176
+ cur = p
177
+ if cur:
178
+ out.append(cur)
179
+ return out
180
+ pieces = pack(re.split(r"(?<=[.!?])\s+", text.strip()), " ")
181
+ final = []
182
+ for p in pieces:
183
+ if len(p) <= room:
184
+ final.append(p)
185
+ continue
186
+ for w in pack(p.split(" "), " "):
187
+ if len(w) <= room:
188
+ final.append(w)
189
+ else:
190
+ final.extend(w[k:k + room] for k in range(0, len(w), room))
191
+ return final
192
+
193
+
194
+ def _ulen(units):
195
+ return sum(len(u[1]) for u in units) + _seps(units)
196
+
197
+
198
+ def _seps(units):
199
+ return max(0, len(units) - 1)
200
+
201
+
202
+ def _join(units):
203
+ out = ""
204
+ for k, (ln, t, tag) in enumerate(units):
205
+ if k:
206
+ prev = units[k - 1]
207
+ same_line = tag == "cut" and prev[2] == "cut" and prev[0] == ln and ln is not None
208
+ out += " " if same_line else "\n"
209
+ out += t
210
+ return out
211
+
212
+
213
+ def _line_units(lines, idx, room):
214
+ units = []
215
+ for i in idx:
216
+ t = lines[i]
217
+ if len(t) <= room:
218
+ units.append((i + 1, t, "line"))
219
+ else:
220
+ units.extend((i + 1, p, "cut") for p in _cut(t, room))
221
+ return units
222
+
223
+
224
+ def _pack(units, room):
225
+ """Greedy: fill each group up to `room` chars."""
226
+ groups, cur = [], []
227
+ for u in units:
228
+ if cur and _ulen(cur + [u]) > room:
229
+ groups.append(cur)
230
+ cur = []
231
+ cur.append(u)
232
+ if cur:
233
+ groups.append(cur)
234
+ return groups
235
+
236
+
237
+ def _split_block(kind, lines, idx, room):
238
+ """Split one block that is bigger than `room` into groups of units, each at most `room`."""
239
+ if kind == "code" and len(idx) >= 2:
240
+ open_i = idx[0]
241
+ close_i = idx[-1] if _is_close(lines[idx[-1]]) else None
242
+ inner = idx[1:-1] if close_i is not None else idx[1:]
243
+ opener = lines[open_i]
244
+ closer = lines[close_i] if close_i is not None else re.match(r"^ {0,3}(`{3,}|~{3,})", opener).group(1)
245
+ wrap = len(opener) + len(closer) + 2
246
+ if wrap <= room // 2:
247
+ groups = _pack(_line_units(lines, inner, room - wrap), room - wrap)
248
+ out = []
249
+ for g, grp in enumerate(groups):
250
+ head = (open_i + 1, opener, "line") if g == 0 else (None, opener, "wrap")
251
+ last = g == len(groups) - 1
252
+ tail = (close_i + 1, closer, "line") if (last and close_i is not None) else (None, closer, "wrap")
253
+ out.append([head] + grp + [tail])
254
+ return out
255
+ if kind == "table":
256
+ header = idx[:2]
257
+ hlen = len(lines[header[0]]) + len(lines[header[1]]) + 2
258
+ if hlen <= room // 2:
259
+ groups = _pack(_line_units(lines, idx[2:], room - hlen), room - hlen)
260
+ out = []
261
+ for g, grp in enumerate(groups):
262
+ if g == 0:
263
+ head = [(i + 1, lines[i], "line") for i in header]
264
+ else:
265
+ head = [(None, lines[i], "wrap") for i in header]
266
+ out.append(head + grp)
267
+ return out
268
+ return _pack(_line_units(lines, idx, room), room)
269
+
270
+
271
+ def _trim(units):
272
+ while units and units[0][2] == "line" and not units[0][1].strip():
273
+ units = units[1:]
274
+ while units and units[-1][2] == "line" and not units[-1][1].strip():
275
+ units = units[:-1]
276
+ return units
277
+
278
+
279
+ def _section_parts(lines, sec, fence, room):
280
+ """Cut one section into parts (lists of units). Parts never cross into another section."""
281
+ body_lo = sec["start"] + sec["heading_size"]
282
+ blocks = _blocks(lines, body_lo, sec["end"], fence)
283
+ if sec["heading_size"]:
284
+ # the heading line(s) come first and stay glued to what follows
285
+ blocks = [("heading", list(range(sec["start"], body_lo)))] + blocks
286
+ whole = _trim([(i + 1, lines[i], "line") for i in range(sec["start"], sec["end"])])
287
+ if not whole:
288
+ return []
289
+ if _ulen(whole) <= room:
290
+ return [whole]
291
+ parts, cur, gap, only_heading = [], [], [], False
292
+ for kind, idx in blocks:
293
+ if kind == "gap":
294
+ if cur:
295
+ gap.append((idx[0] + 1, "", "line"))
296
+ continue
297
+ units = [(i + 1, lines[i], "line") for i in idx]
298
+ if _ulen(units) > room:
299
+ head = cur + gap if only_heading else []
300
+ if head and room - _ulen(head) - 1 >= MIN_ROOM:
301
+ # keep the heading on top of the first piece instead of alone
302
+ groups = _split_block(kind, lines, idx, room - _ulen(head) - 1)
303
+ groups[0] = head + groups[0]
304
+ else:
305
+ if cur:
306
+ parts.append(cur)
307
+ groups = _split_block(kind, lines, idx, room)
308
+ only_heading = False
309
+ parts.extend(groups[:-1])
310
+ cur, gap = list(groups[-1]), []
311
+ continue
312
+ if cur and _ulen(cur + gap + units) > room:
313
+ parts.append(cur)
314
+ cur, gap = [], []
315
+ cur = cur + gap + units if cur else units
316
+ gap = []
317
+ only_heading = kind == "heading"
318
+ if cur:
319
+ parts.append(cur)
320
+ return [p for p in (_trim(p) for p in parts) if p]
321
+
322
+
323
+ def _overlap(prev, nxt, n):
324
+ """Up to n chars from the end of prev, as units, to put before nxt. Never inside code or tables."""
325
+ if n <= 0 or not prev or not nxt or prev[-1][2] == "wrap" or nxt[0][2] == "wrap":
326
+ return []
327
+ if _FENCE_OPEN.match(nxt[0][1]) or nxt[0][1].lstrip().startswith("|"):
328
+ return [] # the next part starts a code block or table: keep it clean
329
+ taken, room = [], n - 1 # 1 for the line break or space before nxt
330
+ for u in reversed(prev):
331
+ if u[2] == "wrap" or _FENCE_OPEN.match(u[1]) or u[1].lstrip().startswith("|"):
332
+ break
333
+ need = len(u[1]) + (1 if taken else 0)
334
+ if need <= room:
335
+ taken.insert(0, u)
336
+ room -= need
337
+ continue
338
+ avail = room - (1 if taken else 0)
339
+ tail = u[1][-avail:] if avail > 0 else ""
340
+ sp = tail.find(" ")
341
+ tail = tail[sp + 1:] if sp >= 0 else "" # start at a whole word
342
+ if tail.strip():
343
+ taken.insert(0, (u[0], tail, "cut"))
344
+ break
345
+ return _trim(taken)
346
+
347
+
348
+ # ---------------------------------------------------------------- public API
349
+
350
+ def chunk_markdown(text, max_chars=DEFAULT_MAX, overlap_chars=0, source="", prefix_path=False):
351
+ """Split Markdown text into chunks. Returns a list of dicts (see README for the fields)."""
352
+ if not isinstance(max_chars, int) or max_chars < 200:
353
+ raise ValueError("max_chars must be a whole number, 200 or more")
354
+ if not isinstance(overlap_chars, int) or overlap_chars < 0 or overlap_chars > max_chars // 2:
355
+ raise ValueError("overlap_chars must be between 0 and half of max_chars")
356
+ lines, secs, fence = sections(text)
357
+ chunks = []
358
+ name = os.path.basename(source) if source else "text"
359
+ for sec in secs:
360
+ prefix = (" > ".join(sec["path"]) + "\n\n") if (prefix_path and sec["path"]) else ""
361
+ room = max_chars - len(prefix)
362
+ whole = _trim([(i + 1, lines[i], "line") for i in range(sec["start"], sec["end"])])
363
+ if not whole or (sec["heading_size"] and len(whole) <= sec["heading_size"]):
364
+ continue # empty, or only a heading: it still shows in the paths below it
365
+ if _ulen(whole) > room:
366
+ room -= overlap_chars
367
+ if room < MIN_ROOM:
368
+ raise ValueError("max_chars is too small for this heading path; make it bigger")
369
+ parts = _section_parts(lines, sec, fence, room)
370
+ for k, units in enumerate(parts):
371
+ if k:
372
+ units = _overlap(parts[k - 1], units, overlap_chars) + units
373
+ nums = [u[0] for u in units if u[0] is not None]
374
+ body = prefix + _join(units)
375
+ chunks.append({
376
+ "id": "", "source": source, "index": 0,
377
+ "heading_path": list(sec["path"]), "heading_level": sec["level"],
378
+ "anchor": sec["anchor"], "start_line": min(nums), "end_line": max(nums),
379
+ "part": k + 1, "parts": len(parts), "chars": len(body), "text": body,
380
+ })
381
+ for n, c in enumerate(chunks, 1):
382
+ c["index"] = n
383
+ c["id"] = f"{name}#{n}"
384
+ return chunks
385
+
386
+
387
+ def outline(text):
388
+ """List the headings: level, title, path, anchor, line, end_line and chars (own text, no sub-sections)."""
389
+ lines, secs, _ = sections(text)
390
+ out = []
391
+ for s in secs:
392
+ if not s["level"]:
393
+ continue
394
+ body = _trim([(i + 1, lines[i], "line") for i in range(s["start"], s["end"])])
395
+ out.append({"level": s["level"], "title": s["title"], "path": s["path"], "anchor": s["anchor"],
396
+ "line": s["start"] + 1, "end_line": body[-1][0] if body else s["start"] + 1,
397
+ "chars": _ulen(body)})
398
+ return out
399
+
400
+
401
+ def get_section(text, heading="", anchor="", include_subsections=True):
402
+ """Return one section by its anchor (exact) or heading title (not case sensitive)."""
403
+ lines, secs, _ = sections(text)
404
+ heads = [s for s in secs if s["level"]]
405
+ if anchor:
406
+ found = [s for s in heads if s["anchor"] == anchor.lstrip("#").lower()]
407
+ elif heading:
408
+ want = " ".join(_clean_title(heading.lstrip("#").strip()).split()).lower()
409
+ found = [s for s in heads if s["title"].lower() == want]
410
+ else:
411
+ raise ValueError("give a heading or an anchor")
412
+ if not found:
413
+ names = ", ".join(f'"{s["title"]}" (#{s["anchor"]})' for s in heads[:30]) or "none"
414
+ raise ValueError(f"no heading matches. Headings here: {names}")
415
+ s = found[0]
416
+ end = s["sub_end"] if include_subsections else s["end"]
417
+ units = _trim([(i + 1, lines[i], "line") for i in range(s["start"], end)])
418
+ body = _join(units)
419
+ return {"title": s["title"], "heading_path": s["path"], "level": s["level"], "anchor": s["anchor"],
420
+ "start_line": units[0][0], "end_line": units[-1][0], "chars": len(body),
421
+ "matches": len(found), "text": body}
422
+
423
+
424
+ def read_text(path, max_bytes=None):
425
+ """Read a UTF-8 text file (a byte-order mark is fine)."""
426
+ if not os.path.isfile(path):
427
+ raise FileNotFoundError(f"file not found: {path}")
428
+ if max_bytes and os.path.getsize(path) > max_bytes:
429
+ raise ValueError(f"file is bigger than {max_bytes // 1_000_000} MB")
430
+ try:
431
+ with open(path, encoding="utf-8-sig") as f:
432
+ return f.read()
433
+ except UnicodeDecodeError:
434
+ raise ValueError(f"{path} is not UTF-8 text") from None
435
+
436
+
437
+ def chunk_file(path, max_chars=DEFAULT_MAX, overlap_chars=0, prefix_path=False):
438
+ return chunk_markdown(read_text(path), max_chars, overlap_chars, source=path, prefix_path=prefix_path)
439
+
440
+
441
+ def to_jsonl(chunks):
442
+ return "".join(json.dumps(c, ensure_ascii=False) + "\n" for c in chunks)
443
+
444
+
445
+ def default_output(path):
446
+ base = path[:-len(os.path.splitext(path)[1])] if os.path.splitext(path)[1] else path
447
+ return base + ".chunks.jsonl"
448
+
449
+
450
+ # ---------------------------------------------------------------- command line
451
+
452
+ def run_mcp():
453
+ try:
454
+ import md_chunk_lite_mcp
455
+ except ImportError as e:
456
+ print(f"error: the MCP server needs the mcp package ({e}). Run: pip install md-chunk-lite", file=sys.stderr)
457
+ return 1
458
+ md_chunk_lite_mcp.main()
459
+ return 0
460
+
461
+
462
+ def main(argv=None):
463
+ argv = sys.argv[1:] if argv is None else argv
464
+ if argv == ["mcp"]:
465
+ return run_mcp()
466
+ p = argparse.ArgumentParser(
467
+ prog="md-chunk-lite",
468
+ description="Split Markdown into chunks by heading. Each chunk keeps its heading path and line numbers. "
469
+ "Run `md-chunk-lite mcp` to start the MCP server (to read a file named mcp, use ./mcp).",
470
+ epilog=PRO_LINE)
471
+ p.add_argument("files", nargs="+", help="Markdown files, or - to read from stdin")
472
+ p.add_argument("-o", "--output", help="where to save the JSONL (default: NAME.chunks.jsonl next to each file; - prints it)")
473
+ p.add_argument("--max-chars", type=int, default=DEFAULT_MAX, help=f"biggest chunk size in characters (default {DEFAULT_MAX})")
474
+ p.add_argument("--overlap-chars", type=int, default=0, help="repeat this many characters from the end of one part at the start of the next, when a section is split (default 0)")
475
+ p.add_argument("--prefix-path", action="store_true", help='start each chunk text with its heading path, like "Guide > Install"')
476
+ p.add_argument("--outline", action="store_true", help="just list the headings with line numbers")
477
+ p.add_argument("--json", action="store_true", help="print one JSON object for scripts and AI agents (does not save files)")
478
+ p.add_argument("-q", "--quiet", action="store_true", help="no summary or tip line")
479
+ p.add_argument("--version", action="version", version=f"md-chunk-lite {__version__}")
480
+ a = p.parse_args(argv)
481
+ tip = not a.quiet and not a.json and sys.stderr.isatty()
482
+ try:
483
+ results = []
484
+ for f in a.files:
485
+ text = sys.stdin.read() if f == "-" else read_text(f)
486
+ src = "" if f == "-" else f
487
+ if a.outline:
488
+ results.append((f, outline(text)))
489
+ else:
490
+ results.append((f, chunk_markdown(text, a.max_chars, a.overlap_chars, src, a.prefix_path)))
491
+ except (OSError, ValueError) as e:
492
+ if a.json:
493
+ print(json.dumps({"ok": False, "error": str(e)}))
494
+ else:
495
+ print(f"error: {e}", file=sys.stderr)
496
+ return 1
497
+
498
+ if a.json:
499
+ key = "headings" if a.outline else "chunks"
500
+ items = [x for _, r in results for x in r]
501
+ out = {"ok": True, "files": [f for f, _ in results], key: items, "count": len(items)}
502
+ print(json.dumps(out, ensure_ascii=False, indent=2))
503
+ return 0
504
+
505
+ if a.outline:
506
+ for f, heads in results:
507
+ if len(results) > 1:
508
+ print(f"== {f}")
509
+ for h in heads:
510
+ print(f'{" " * (h["level"] - 1)}{h["title"] or "(empty heading)"} [line {h["line"]}, #{h["anchor"]}, {h["chars"]} chars]')
511
+ return 0
512
+
513
+ if a.output == "-" or (a.files == ["-"] and not a.output):
514
+ sys.stdout.write("".join(to_jsonl(c) for _, c in results))
515
+ elif a.output:
516
+ with open(a.output, "w", encoding="utf-8") as fh:
517
+ fh.write("".join(to_jsonl(c) for _, c in results))
518
+ if not a.quiet:
519
+ n = sum(len(c) for _, c in results)
520
+ print(f"Saved: {a.output} ({n} chunks from {len(results)} file{'s' if len(results) > 1 else ''})")
521
+ else:
522
+ for f, c in results:
523
+ dest = default_output(f)
524
+ with open(dest, "w", encoding="utf-8") as fh:
525
+ fh.write(to_jsonl(c))
526
+ if not a.quiet:
527
+ big = max((x["chars"] for x in c), default=0)
528
+ print(f"Saved: {dest} ({len(c)} chunks, biggest {big} chars)")
529
+ if tip:
530
+ print(PRO_LINE, file=sys.stderr)
531
+ return 0
532
+
533
+
534
+ if __name__ == "__main__":
535
+ sys.exit(main())
md_chunk_lite_mcp.py ADDED
@@ -0,0 +1,164 @@
1
+ """Free MCP server for md-chunk-lite (stdio).
2
+
3
+ Run: uvx md-chunk-lite mcp
4
+ or: uvx --from md-chunk-lite md-chunk-lite-mcp
5
+ """
6
+ import os
7
+ from typing import Annotated
8
+ from pydantic import Field
9
+ from mcp.server.fastmcp import FastMCP
10
+ from mcp.types import ToolAnnotations
11
+ import md_chunk_lite as lite
12
+
13
+ MAX_BYTES = 10_000_000 # 10 MB
14
+
15
+ mcp = FastMCP("md-chunk-lite")
16
+
17
+ READ_ONLY = dict(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)
18
+
19
+ Path = Annotated[str, Field(description="Full path to a local Markdown or text file (UTF-8, up to 10 MB). Leave empty if you pass text.")]
20
+ Text = Annotated[str, Field(description="Markdown text to use instead of a file. Leave empty if you pass path.")]
21
+ MaxChars = Annotated[int, Field(ge=200, le=100_000, description="Biggest chunk size in characters (not tokens). Default 1500.")]
22
+ Overlap = Annotated[int, Field(ge=0, description="Characters repeated from the end of one part at the start of the next, only when a section is split. Must be at most half of max_chars. Default 0.")]
23
+ Prefix = Annotated[bool, Field(description='If true, each chunk text starts with its heading path, like "Guide > Install".')]
24
+
25
+
26
+ def _load(path, text):
27
+ if bool(path) == bool(text):
28
+ raise ValueError("give exactly one of path or text")
29
+ if path:
30
+ p = os.path.expanduser(path)
31
+ return lite.read_text(p, MAX_BYTES), p
32
+ return text, ""
33
+
34
+
35
+ @mcp.tool(title="Split Markdown into chunks", annotations=ToolAnnotations(title="Split Markdown into chunks", **READ_ONLY))
36
+ def chunk_markdown(
37
+ path: Path = "",
38
+ text: Text = "",
39
+ max_chars: MaxChars = lite.DEFAULT_MAX,
40
+ overlap_chars: Overlap = 0,
41
+ prefix_path: Prefix = False,
42
+ start: Annotated[int, Field(ge=1, description="First chunk number to return (1 = the first). Use next_start from the last call to get more.")] = 1,
43
+ limit: Annotated[int, Field(ge=1, le=500, description="Most chunks to return in one call. Default 100.")] = 100,
44
+ ) -> dict:
45
+ """Split a Markdown file or Markdown text into chunks by heading, for search, embeddings or RAG.
46
+
47
+ Use this when you need a long Markdown document (docs, notes, a README) broken
48
+ into pieces that each know where they came from. A chunk never mixes two
49
+ sections. Each chunk has heading_path (like ["Guide", "Install"]), anchor
50
+ (the GitHub-style #link), start_line and end_line (1-based, in the file), part
51
+ and parts (when a big section had to be split), chars and text. Code blocks and
52
+ tables are kept whole when they fit; when they don't, each piece gets the fence
53
+ or table header again. Plain code, not AI: same input, same chunks.
54
+
55
+ Do not use it for PDF or Word files (convert them to Markdown first), to just
56
+ see the headings (use outline_markdown), or to read one section (use
57
+ get_section). Sizes are characters, not tokens.
58
+
59
+ Returns {"source", "total", "start", "chunks": [...], "next_start"}. next_start
60
+ is null when there are no more chunks.
61
+ """
62
+ body, src = _load(path, text)
63
+ chunks = lite.chunk_markdown(body, max_chars, overlap_chars, src, prefix_path)
64
+ page = chunks[start - 1:start - 1 + limit]
65
+ nxt = start + len(page)
66
+ return {"source": src, "total": len(chunks), "start": start, "chunks": page,
67
+ "next_start": nxt if nxt <= len(chunks) else None}
68
+
69
+
70
+ @mcp.tool(title="List Markdown headings", annotations=ToolAnnotations(title="List Markdown headings", **READ_ONLY))
71
+ def outline_markdown(path: Path = "", text: Text = "") -> dict:
72
+ """List every heading in a Markdown file or text, with its level, path, anchor, line number and size.
73
+
74
+ Use this when you want a quick map of a long document before you read or chunk
75
+ it, or to find the exact heading or anchor to pass to get_section. Headings
76
+ inside code blocks and YAML front matter are ignored. Both "# Title" and
77
+ underlined (=== / ---) headings are found.
78
+
79
+ Do not use it to get the text itself (use get_section or chunk_markdown).
80
+
81
+ Returns {"source", "count", "headings": [{"level", "title", "path", "anchor",
82
+ "line", "end_line", "chars"}]}. chars is the size of that heading's own text,
83
+ not counting the sections under it.
84
+ """
85
+ body, src = _load(path, text)
86
+ heads = lite.outline(body)
87
+ return {"source": src, "count": len(heads), "headings": heads}
88
+
89
+
90
+ @mcp.tool(title="Get one Markdown section", annotations=ToolAnnotations(title="Get one Markdown section", **READ_ONLY))
91
+ def get_section(
92
+ path: Path = "",
93
+ text: Text = "",
94
+ heading: Annotated[str, Field(description='Heading title to find, like "Install". Not case sensitive. Leave empty if you pass anchor.')] = "",
95
+ anchor: Annotated[str, Field(description='Anchor to find, like "install" or "install-1" for the second "Install". Wins over heading.')] = "",
96
+ include_subsections: Annotated[bool, Field(description="If true (default), include the smaller headings under it.")] = True,
97
+ ) -> dict:
98
+ """Return the text of one section of a Markdown file or text, found by heading title or anchor.
99
+
100
+ Use this when you only need one part of a long document, like the "Install"
101
+ section of a README, so you don't have to read the whole file. If two headings
102
+ have the same title, the first one is returned and "matches" tells you how many
103
+ there are; use the anchor (from outline_markdown) to pick another.
104
+
105
+ Do not use it to split the whole document (use chunk_markdown).
106
+
107
+ Returns {"title", "heading_path", "level", "anchor", "start_line", "end_line",
108
+ "chars", "matches", "text"}. If nothing matches, the error lists the headings.
109
+ """
110
+ body, _ = _load(path, text)
111
+ return lite.get_section(body, heading, anchor, include_subsections)
112
+
113
+
114
+ @mcp.tool(
115
+ title="Save chunks to a JSONL file",
116
+ annotations=ToolAnnotations(
117
+ title="Save chunks to a JSONL file",
118
+ readOnlyHint=False, # writes one .jsonl file
119
+ destructiveHint=True, # replaces that file if it is already there
120
+ idempotentHint=True, # same input writes the same file
121
+ openWorldHint=False,
122
+ ),
123
+ )
124
+ def save_chunks_jsonl(
125
+ path: Annotated[str, Field(description="Full path to the local Markdown file to split (UTF-8, up to 10 MB).")],
126
+ output_path: Annotated[str, Field(description="Where to save. Must end in .jsonl. Default: next to the input, as NAME.chunks.jsonl.")] = "",
127
+ max_chars: MaxChars = lite.DEFAULT_MAX,
128
+ overlap_chars: Overlap = 0,
129
+ prefix_path: Prefix = False,
130
+ ) -> dict:
131
+ """Split a Markdown file into chunks and save them as a JSONL file (one chunk per line).
132
+
133
+ Use this when the chunks are going into a search index, vector database or
134
+ another program, and you want a file instead of a long chat reply. The chunks
135
+ are the same as chunk_markdown gives. It writes only the one .jsonl file and
136
+ replaces it if it is already there. It never changes the Markdown file.
137
+
138
+ Do not use it to look at chunks in the chat (use chunk_markdown).
139
+
140
+ Returns {"output_path", "chunks", "bytes", "biggest_chunk_chars"}.
141
+ """
142
+ src = os.path.abspath(os.path.expanduser(path))
143
+ body = lite.read_text(src, MAX_BYTES)
144
+ out = os.path.abspath(os.path.expanduser(output_path)) if output_path else lite.default_output(src)
145
+ if not out.lower().endswith(".jsonl"):
146
+ raise ValueError("output_path must end in .jsonl")
147
+ if os.path.exists(out) and os.path.samefile(out, src):
148
+ raise ValueError("output_path cannot be the input file")
149
+ if not os.path.isdir(os.path.dirname(out)):
150
+ raise ValueError(f"folder not found: {os.path.dirname(out)}")
151
+ chunks = lite.chunk_markdown(body, max_chars, overlap_chars, src, prefix_path)
152
+ data = lite.to_jsonl(chunks).encode("utf-8")
153
+ with open(out, "wb") as f:
154
+ f.write(data)
155
+ return {"output_path": out, "chunks": len(chunks), "bytes": len(data),
156
+ "biggest_chunk_chars": max((c["chars"] for c in chunks), default=0)}
157
+
158
+
159
+ def main():
160
+ mcp.run()
161
+
162
+
163
+ if __name__ == "__main__":
164
+ main()