json-repair-lite 1.0.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
+ # Changelog
2
+
3
+ What changed in json-repair-lite, newest first.
4
+
5
+ ## 1.0.0 - 2026-11-10
6
+
7
+ - First release.
8
+ - Repairs broken or incomplete JSON, including output from language models. Already-valid JSON is reported honestly.
9
+ - Optional `--json-lines` treats each non-empty line as its own document.
10
+ - `--json` gives one clean object for scripts and AI agents. `--quiet` hides the tip line.
11
+ - A free MCP server with two read-only tools: `repair_json_text` and `repair_json_file`.
12
+ - Needs Python 3.10 or newer, plus the json-repair library.
@@ -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,4 @@
1
+ include CHANGELOG.md
2
+ include llms.txt
3
+ include server.json
4
+ recursive-include tests *.py *.json *.jsonl
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.4
2
+ Name: json-repair-lite
3
+ Version: 1.0.0
4
+ Summary: Repair broken or incomplete JSON, including output from language models. Local CLI and MCP server. No API key.
5
+ Author: Tidy Byte Tools
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/tidybytetools/json-repair-lite
8
+ Project-URL: Documentation, https://github.com/tidybytetools/json-repair-lite#readme
9
+ Project-URL: Source, https://github.com/tidybytetools/json-repair-lite
10
+ Project-URL: Issues, https://github.com/tidybytetools/json-repair-lite/issues
11
+ Project-URL: Changelog, https://github.com/tidybytetools/json-repair-lite/blob/main/CHANGELOG.md
12
+ Project-URL: Apify, https://apify.com/tidybytetools/json-repair
13
+ Keywords: json,json-repair,jsonl,llm,cli,mcp,mcp-server,data-cleaning
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: End Users/Desktop
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Text Processing
26
+ Classifier: Topic :: Utilities
27
+ Requires-Python: >=3.10
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: mcp<2,>=1.10
31
+ Requires-Dist: json-repair<1,>=0.64.9
32
+ Dynamic: license-file
33
+
34
+ <p>
35
+ <a href="https://github.com/tidybytetools">
36
+ <picture>
37
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tidybytetools/json-repair-lite/main/assets/tidybytetools-lockup-dark.png">
38
+ <img alt="Tidy Byte Tools" src="https://raw.githubusercontent.com/tidybytetools/json-repair-lite/main/assets/tidybytetools-lockup-light.png" height="44">
39
+ </picture>
40
+ </a>
41
+ </p>
42
+
43
+ # json-repair-lite
44
+
45
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/tidybytetools/json-repair-lite/blob/main/LICENSE)
46
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
47
+ [![MCP server](https://img.shields.io/badge/MCP-stdio-purple.svg)](#use-it-from-claude-desktop-or-cursor-mcp)
48
+ [![Tests](https://github.com/tidybytetools/json-repair-lite/actions/workflows/tests.yml/badge.svg)](https://github.com/tidybytetools/json-repair-lite/actions/workflows/tests.yml)
49
+
50
+ Free tool that repairs broken or incomplete JSON, including output from language models. Runs offline. No API key.
51
+
52
+ Need it at scale or from an AI agent? Use the Apify version: **[json-repair on Apify](https://apify.com/tidybytetools/json-repair)**
53
+
54
+ Plain code, not AI, so the same input always gives the same output. Runs on your own computer. MIT license. Works with Python 3.10 and newer, on Windows, Mac and Linux.
55
+
56
+ ## Links
57
+
58
+ - **[Apify (no-install cloud version)](https://apify.com/tidybytetools/json-repair)** — pay only for what you use, about $0.001 per document. Empty or unreadable input is free. (This listing goes public this week.)
59
+
60
+ <!-- mcp-name: io.github.tidybytetools/json-repair-lite -->
61
+
62
+ ## Before and after
63
+
64
+ Before (not valid JSON: unquoted keys, single quotes, trailing comma):
65
+
66
+ ```
67
+ {name: 'Ada', ok: true, trailing: 'comma',}
68
+ ```
69
+
70
+ After:
71
+
72
+ ```json
73
+ {"name": "Ada", "ok": true, "trailing": "comma"}
74
+ ```
75
+
76
+ Already-valid JSON is left alone and reported honestly as `wasValid: true`.
77
+
78
+ ## Install
79
+
80
+ ```
81
+ pip install git+https://github.com/tidybytetools/json-repair-lite
82
+ ```
83
+
84
+ Or use pipx, which keeps it in its own space:
85
+
86
+ ```
87
+ pipx install git+https://github.com/tidybytetools/json-repair-lite
88
+ ```
89
+
90
+ This also installs the [json-repair](https://pypi.org/project/json-repair/) library, which does the repair work, and the `mcp` package for the MCP server.
91
+
92
+ ## Use it
93
+
94
+ ```
95
+ printf "{name: 'Ada', ok: true,}" | json-repair-lite
96
+ json-repair-lite broken.json
97
+ json-repair-lite data.jsonl --json-lines
98
+ json-repair-lite broken.json --json # {"ok": true, "count": 1, "failed": 0, "documents": [...]}
99
+ ```
100
+
101
+ Without `--json-lines`, the whole text is tried as one JSON value first. If that cannot be repaired and there are several lines, each line is then tried on its own. With `--json-lines`, each non-empty line is its own document, and each result is printed as one line of JSON.
102
+
103
+ From Python:
104
+
105
+ ```python
106
+ from json_repair_lite import repair_one
107
+ repair_one("{name: 'Ada',}")["value"] # {'name': 'Ada'}
108
+ ```
109
+
110
+ When you run it in a terminal it prints one short line about the Apify version to stderr after the result. It never goes into your JSON output, it only shows when you are looking at a terminal, and `--quiet` turns it off.
111
+
112
+ ## Known limits
113
+
114
+ - **This is a repair step, not a language model.** It can close missing brackets and fix common syntax issues. It cannot invent the data you meant to write.
115
+ - **Some text cannot be repaired.** Those runs exit with an error.
116
+ - **Local files only.** This free tool does not fetch file links from the internet. The Apify version does.
117
+ - **5 MB cap in the MCP file tool.** The command line will read a larger local file, but very large jobs are a better fit for Apify.
118
+
119
+ ## Lite vs Apify
120
+
121
+ | | lite (free, this repo) | [json-repair on Apify](https://apify.com/tidybytetools/json-repair) |
122
+ |---|---|---|
123
+ | Repair broken or incomplete JSON | yes, on your computer | yes, in the cloud |
124
+ | JSON Lines | yes | yes |
125
+ | Fetch file links | no | yes |
126
+ | Many documents in one run | yes, from one file or stdin | yes, including file links |
127
+ | MCP server for local AI apps | yes | use Apify MCP for the cloud tool |
128
+ | Price | free | $0.001 per document, including JSON that was already valid. Empty input is free |
129
+
130
+ ## Use it from Claude Desktop or Cursor (MCP)
131
+
132
+ There is a small free MCP server built in. It gives your AI app two tools. Both only read. They never write or change files, and they never use the internet. It needs [uv](https://docs.astral.sh/uv/).
133
+
134
+ Run it by hand to check it starts (it waits quietly for an app to talk to it):
135
+
136
+ ```
137
+ uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp
138
+ ```
139
+
140
+ Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
141
+
142
+ ```json
143
+ {
144
+ "mcpServers": {
145
+ "json-repair-lite": {
146
+ "command": "uvx",
147
+ "args": ["--from", "git+https://github.com/tidybytetools/json-repair-lite", "json-repair-lite", "mcp"]
148
+ }
149
+ }
150
+ }
151
+ ```
152
+
153
+ `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite-mcp` starts the same server.
154
+
155
+ Tools:
156
+
157
+ - `repair_json_text(text, json_lines=false)`: for JSON in the chat.
158
+ - `repair_json_file(path, json_lines=false)`: for a local `.json` or `.jsonl` file, up to 5 MB.
159
+
160
+ For one document, both return `{"wasValid", "repaired", "value", "text"}`. For several documents, they return `{"count", "failed", "documents": [...]}`.
161
+
162
+ ## For AI agents
163
+
164
+ - **Use when:** you have JSON that may be missing quotes, have trailing commas, or be cut off, including output from a language model.
165
+ - **Don't use when:** you need to fetch a file from a URL, or the file is bigger than 5 MB in MCP. Use the Apify version for those jobs. Do not use it to invent missing data.
166
+ - **Input:** text on stdin or a file path. Optional `--json-lines`.
167
+ - **MCP:** `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp` gives two read-only tools, `repair_json_text` and `repair_json_file`.
168
+ - **Output:** with `--json`, one object: `{"ok": true, "count": 1, "failed": 0, "documents": [...]}`. On error `ok` is false. Exit code 0 ok, 1 error.
169
+ - Hint lines go to stderr only, and only in a terminal, so stdout is always clean JSON. See also [`llms.txt`](https://github.com/tidybytetools/json-repair-lite/blob/main/llms.txt).
170
+
171
+ ## Tests
172
+
173
+ ```
174
+ pip install "mcp>=1.10,<2" "json-repair>=0.64.9,<1"
175
+ python3 -m unittest discover tests
176
+ ```
177
+
178
+ The MCP tests are skipped if `mcp` is not installed.
179
+
180
+ ## FAQ
181
+
182
+ **What input does it take?**
183
+ One JSON value, or several JSON Lines. Text on stdin, or a local file.
184
+
185
+ **Do my files leave my computer?**
186
+ No. The tool runs on your computer and never uses the internet.
187
+
188
+ **Do you call an AI model?**
189
+ No. The repair runs offline.
190
+
191
+ **How is this different from the Apify version?**
192
+ The Apify version runs in the cloud, can fetch file links, and is built for many documents in one run. This lite tool is free and local.
193
+
194
+ **Does it work with AI apps?**
195
+ Yes. It includes a free MCP server. No API key.
196
+
197
+ ## License
198
+
199
+ MIT. See `LICENSE`.
@@ -0,0 +1,166 @@
1
+ <p>
2
+ <a href="https://github.com/tidybytetools">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tidybytetools/json-repair-lite/main/assets/tidybytetools-lockup-dark.png">
5
+ <img alt="Tidy Byte Tools" src="https://raw.githubusercontent.com/tidybytetools/json-repair-lite/main/assets/tidybytetools-lockup-light.png" height="44">
6
+ </picture>
7
+ </a>
8
+ </p>
9
+
10
+ # json-repair-lite
11
+
12
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/tidybytetools/json-repair-lite/blob/main/LICENSE)
13
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
14
+ [![MCP server](https://img.shields.io/badge/MCP-stdio-purple.svg)](#use-it-from-claude-desktop-or-cursor-mcp)
15
+ [![Tests](https://github.com/tidybytetools/json-repair-lite/actions/workflows/tests.yml/badge.svg)](https://github.com/tidybytetools/json-repair-lite/actions/workflows/tests.yml)
16
+
17
+ Free tool that repairs broken or incomplete JSON, including output from language models. Runs offline. No API key.
18
+
19
+ Need it at scale or from an AI agent? Use the Apify version: **[json-repair on Apify](https://apify.com/tidybytetools/json-repair)**
20
+
21
+ Plain code, not AI, so the same input always gives the same output. Runs on your own computer. MIT license. Works with Python 3.10 and newer, on Windows, Mac and Linux.
22
+
23
+ ## Links
24
+
25
+ - **[Apify (no-install cloud version)](https://apify.com/tidybytetools/json-repair)** — pay only for what you use, about $0.001 per document. Empty or unreadable input is free. (This listing goes public this week.)
26
+
27
+ <!-- mcp-name: io.github.tidybytetools/json-repair-lite -->
28
+
29
+ ## Before and after
30
+
31
+ Before (not valid JSON: unquoted keys, single quotes, trailing comma):
32
+
33
+ ```
34
+ {name: 'Ada', ok: true, trailing: 'comma',}
35
+ ```
36
+
37
+ After:
38
+
39
+ ```json
40
+ {"name": "Ada", "ok": true, "trailing": "comma"}
41
+ ```
42
+
43
+ Already-valid JSON is left alone and reported honestly as `wasValid: true`.
44
+
45
+ ## Install
46
+
47
+ ```
48
+ pip install git+https://github.com/tidybytetools/json-repair-lite
49
+ ```
50
+
51
+ Or use pipx, which keeps it in its own space:
52
+
53
+ ```
54
+ pipx install git+https://github.com/tidybytetools/json-repair-lite
55
+ ```
56
+
57
+ This also installs the [json-repair](https://pypi.org/project/json-repair/) library, which does the repair work, and the `mcp` package for the MCP server.
58
+
59
+ ## Use it
60
+
61
+ ```
62
+ printf "{name: 'Ada', ok: true,}" | json-repair-lite
63
+ json-repair-lite broken.json
64
+ json-repair-lite data.jsonl --json-lines
65
+ json-repair-lite broken.json --json # {"ok": true, "count": 1, "failed": 0, "documents": [...]}
66
+ ```
67
+
68
+ Without `--json-lines`, the whole text is tried as one JSON value first. If that cannot be repaired and there are several lines, each line is then tried on its own. With `--json-lines`, each non-empty line is its own document, and each result is printed as one line of JSON.
69
+
70
+ From Python:
71
+
72
+ ```python
73
+ from json_repair_lite import repair_one
74
+ repair_one("{name: 'Ada',}")["value"] # {'name': 'Ada'}
75
+ ```
76
+
77
+ When you run it in a terminal it prints one short line about the Apify version to stderr after the result. It never goes into your JSON output, it only shows when you are looking at a terminal, and `--quiet` turns it off.
78
+
79
+ ## Known limits
80
+
81
+ - **This is a repair step, not a language model.** It can close missing brackets and fix common syntax issues. It cannot invent the data you meant to write.
82
+ - **Some text cannot be repaired.** Those runs exit with an error.
83
+ - **Local files only.** This free tool does not fetch file links from the internet. The Apify version does.
84
+ - **5 MB cap in the MCP file tool.** The command line will read a larger local file, but very large jobs are a better fit for Apify.
85
+
86
+ ## Lite vs Apify
87
+
88
+ | | lite (free, this repo) | [json-repair on Apify](https://apify.com/tidybytetools/json-repair) |
89
+ |---|---|---|
90
+ | Repair broken or incomplete JSON | yes, on your computer | yes, in the cloud |
91
+ | JSON Lines | yes | yes |
92
+ | Fetch file links | no | yes |
93
+ | Many documents in one run | yes, from one file or stdin | yes, including file links |
94
+ | MCP server for local AI apps | yes | use Apify MCP for the cloud tool |
95
+ | Price | free | $0.001 per document, including JSON that was already valid. Empty input is free |
96
+
97
+ ## Use it from Claude Desktop or Cursor (MCP)
98
+
99
+ There is a small free MCP server built in. It gives your AI app two tools. Both only read. They never write or change files, and they never use the internet. It needs [uv](https://docs.astral.sh/uv/).
100
+
101
+ Run it by hand to check it starts (it waits quietly for an app to talk to it):
102
+
103
+ ```
104
+ uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp
105
+ ```
106
+
107
+ Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
108
+
109
+ ```json
110
+ {
111
+ "mcpServers": {
112
+ "json-repair-lite": {
113
+ "command": "uvx",
114
+ "args": ["--from", "git+https://github.com/tidybytetools/json-repair-lite", "json-repair-lite", "mcp"]
115
+ }
116
+ }
117
+ }
118
+ ```
119
+
120
+ `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite-mcp` starts the same server.
121
+
122
+ Tools:
123
+
124
+ - `repair_json_text(text, json_lines=false)`: for JSON in the chat.
125
+ - `repair_json_file(path, json_lines=false)`: for a local `.json` or `.jsonl` file, up to 5 MB.
126
+
127
+ For one document, both return `{"wasValid", "repaired", "value", "text"}`. For several documents, they return `{"count", "failed", "documents": [...]}`.
128
+
129
+ ## For AI agents
130
+
131
+ - **Use when:** you have JSON that may be missing quotes, have trailing commas, or be cut off, including output from a language model.
132
+ - **Don't use when:** you need to fetch a file from a URL, or the file is bigger than 5 MB in MCP. Use the Apify version for those jobs. Do not use it to invent missing data.
133
+ - **Input:** text on stdin or a file path. Optional `--json-lines`.
134
+ - **MCP:** `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp` gives two read-only tools, `repair_json_text` and `repair_json_file`.
135
+ - **Output:** with `--json`, one object: `{"ok": true, "count": 1, "failed": 0, "documents": [...]}`. On error `ok` is false. Exit code 0 ok, 1 error.
136
+ - Hint lines go to stderr only, and only in a terminal, so stdout is always clean JSON. See also [`llms.txt`](https://github.com/tidybytetools/json-repair-lite/blob/main/llms.txt).
137
+
138
+ ## Tests
139
+
140
+ ```
141
+ pip install "mcp>=1.10,<2" "json-repair>=0.64.9,<1"
142
+ python3 -m unittest discover tests
143
+ ```
144
+
145
+ The MCP tests are skipped if `mcp` is not installed.
146
+
147
+ ## FAQ
148
+
149
+ **What input does it take?**
150
+ One JSON value, or several JSON Lines. Text on stdin, or a local file.
151
+
152
+ **Do my files leave my computer?**
153
+ No. The tool runs on your computer and never uses the internet.
154
+
155
+ **Do you call an AI model?**
156
+ No. The repair runs offline.
157
+
158
+ **How is this different from the Apify version?**
159
+ The Apify version runs in the cloud, can fetch file links, and is built for many documents in one run. This lite tool is free and local.
160
+
161
+ **Does it work with AI apps?**
162
+ Yes. It includes a free MCP server. No API key.
163
+
164
+ ## License
165
+
166
+ MIT. See `LICENSE`.
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.4
2
+ Name: json-repair-lite
3
+ Version: 1.0.0
4
+ Summary: Repair broken or incomplete JSON, including output from language models. Local CLI and MCP server. No API key.
5
+ Author: Tidy Byte Tools
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/tidybytetools/json-repair-lite
8
+ Project-URL: Documentation, https://github.com/tidybytetools/json-repair-lite#readme
9
+ Project-URL: Source, https://github.com/tidybytetools/json-repair-lite
10
+ Project-URL: Issues, https://github.com/tidybytetools/json-repair-lite/issues
11
+ Project-URL: Changelog, https://github.com/tidybytetools/json-repair-lite/blob/main/CHANGELOG.md
12
+ Project-URL: Apify, https://apify.com/tidybytetools/json-repair
13
+ Keywords: json,json-repair,jsonl,llm,cli,mcp,mcp-server,data-cleaning
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: End Users/Desktop
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Text Processing
26
+ Classifier: Topic :: Utilities
27
+ Requires-Python: >=3.10
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: mcp<2,>=1.10
31
+ Requires-Dist: json-repair<1,>=0.64.9
32
+ Dynamic: license-file
33
+
34
+ <p>
35
+ <a href="https://github.com/tidybytetools">
36
+ <picture>
37
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tidybytetools/json-repair-lite/main/assets/tidybytetools-lockup-dark.png">
38
+ <img alt="Tidy Byte Tools" src="https://raw.githubusercontent.com/tidybytetools/json-repair-lite/main/assets/tidybytetools-lockup-light.png" height="44">
39
+ </picture>
40
+ </a>
41
+ </p>
42
+
43
+ # json-repair-lite
44
+
45
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/tidybytetools/json-repair-lite/blob/main/LICENSE)
46
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
47
+ [![MCP server](https://img.shields.io/badge/MCP-stdio-purple.svg)](#use-it-from-claude-desktop-or-cursor-mcp)
48
+ [![Tests](https://github.com/tidybytetools/json-repair-lite/actions/workflows/tests.yml/badge.svg)](https://github.com/tidybytetools/json-repair-lite/actions/workflows/tests.yml)
49
+
50
+ Free tool that repairs broken or incomplete JSON, including output from language models. Runs offline. No API key.
51
+
52
+ Need it at scale or from an AI agent? Use the Apify version: **[json-repair on Apify](https://apify.com/tidybytetools/json-repair)**
53
+
54
+ Plain code, not AI, so the same input always gives the same output. Runs on your own computer. MIT license. Works with Python 3.10 and newer, on Windows, Mac and Linux.
55
+
56
+ ## Links
57
+
58
+ - **[Apify (no-install cloud version)](https://apify.com/tidybytetools/json-repair)** — pay only for what you use, about $0.001 per document. Empty or unreadable input is free. (This listing goes public this week.)
59
+
60
+ <!-- mcp-name: io.github.tidybytetools/json-repair-lite -->
61
+
62
+ ## Before and after
63
+
64
+ Before (not valid JSON: unquoted keys, single quotes, trailing comma):
65
+
66
+ ```
67
+ {name: 'Ada', ok: true, trailing: 'comma',}
68
+ ```
69
+
70
+ After:
71
+
72
+ ```json
73
+ {"name": "Ada", "ok": true, "trailing": "comma"}
74
+ ```
75
+
76
+ Already-valid JSON is left alone and reported honestly as `wasValid: true`.
77
+
78
+ ## Install
79
+
80
+ ```
81
+ pip install git+https://github.com/tidybytetools/json-repair-lite
82
+ ```
83
+
84
+ Or use pipx, which keeps it in its own space:
85
+
86
+ ```
87
+ pipx install git+https://github.com/tidybytetools/json-repair-lite
88
+ ```
89
+
90
+ This also installs the [json-repair](https://pypi.org/project/json-repair/) library, which does the repair work, and the `mcp` package for the MCP server.
91
+
92
+ ## Use it
93
+
94
+ ```
95
+ printf "{name: 'Ada', ok: true,}" | json-repair-lite
96
+ json-repair-lite broken.json
97
+ json-repair-lite data.jsonl --json-lines
98
+ json-repair-lite broken.json --json # {"ok": true, "count": 1, "failed": 0, "documents": [...]}
99
+ ```
100
+
101
+ Without `--json-lines`, the whole text is tried as one JSON value first. If that cannot be repaired and there are several lines, each line is then tried on its own. With `--json-lines`, each non-empty line is its own document, and each result is printed as one line of JSON.
102
+
103
+ From Python:
104
+
105
+ ```python
106
+ from json_repair_lite import repair_one
107
+ repair_one("{name: 'Ada',}")["value"] # {'name': 'Ada'}
108
+ ```
109
+
110
+ When you run it in a terminal it prints one short line about the Apify version to stderr after the result. It never goes into your JSON output, it only shows when you are looking at a terminal, and `--quiet` turns it off.
111
+
112
+ ## Known limits
113
+
114
+ - **This is a repair step, not a language model.** It can close missing brackets and fix common syntax issues. It cannot invent the data you meant to write.
115
+ - **Some text cannot be repaired.** Those runs exit with an error.
116
+ - **Local files only.** This free tool does not fetch file links from the internet. The Apify version does.
117
+ - **5 MB cap in the MCP file tool.** The command line will read a larger local file, but very large jobs are a better fit for Apify.
118
+
119
+ ## Lite vs Apify
120
+
121
+ | | lite (free, this repo) | [json-repair on Apify](https://apify.com/tidybytetools/json-repair) |
122
+ |---|---|---|
123
+ | Repair broken or incomplete JSON | yes, on your computer | yes, in the cloud |
124
+ | JSON Lines | yes | yes |
125
+ | Fetch file links | no | yes |
126
+ | Many documents in one run | yes, from one file or stdin | yes, including file links |
127
+ | MCP server for local AI apps | yes | use Apify MCP for the cloud tool |
128
+ | Price | free | $0.001 per document, including JSON that was already valid. Empty input is free |
129
+
130
+ ## Use it from Claude Desktop or Cursor (MCP)
131
+
132
+ There is a small free MCP server built in. It gives your AI app two tools. Both only read. They never write or change files, and they never use the internet. It needs [uv](https://docs.astral.sh/uv/).
133
+
134
+ Run it by hand to check it starts (it waits quietly for an app to talk to it):
135
+
136
+ ```
137
+ uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp
138
+ ```
139
+
140
+ Claude Desktop (`claude_desktop_config.json`) or Cursor (`~/.cursor/mcp.json`):
141
+
142
+ ```json
143
+ {
144
+ "mcpServers": {
145
+ "json-repair-lite": {
146
+ "command": "uvx",
147
+ "args": ["--from", "git+https://github.com/tidybytetools/json-repair-lite", "json-repair-lite", "mcp"]
148
+ }
149
+ }
150
+ }
151
+ ```
152
+
153
+ `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite-mcp` starts the same server.
154
+
155
+ Tools:
156
+
157
+ - `repair_json_text(text, json_lines=false)`: for JSON in the chat.
158
+ - `repair_json_file(path, json_lines=false)`: for a local `.json` or `.jsonl` file, up to 5 MB.
159
+
160
+ For one document, both return `{"wasValid", "repaired", "value", "text"}`. For several documents, they return `{"count", "failed", "documents": [...]}`.
161
+
162
+ ## For AI agents
163
+
164
+ - **Use when:** you have JSON that may be missing quotes, have trailing commas, or be cut off, including output from a language model.
165
+ - **Don't use when:** you need to fetch a file from a URL, or the file is bigger than 5 MB in MCP. Use the Apify version for those jobs. Do not use it to invent missing data.
166
+ - **Input:** text on stdin or a file path. Optional `--json-lines`.
167
+ - **MCP:** `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp` gives two read-only tools, `repair_json_text` and `repair_json_file`.
168
+ - **Output:** with `--json`, one object: `{"ok": true, "count": 1, "failed": 0, "documents": [...]}`. On error `ok` is false. Exit code 0 ok, 1 error.
169
+ - Hint lines go to stderr only, and only in a terminal, so stdout is always clean JSON. See also [`llms.txt`](https://github.com/tidybytetools/json-repair-lite/blob/main/llms.txt).
170
+
171
+ ## Tests
172
+
173
+ ```
174
+ pip install "mcp>=1.10,<2" "json-repair>=0.64.9,<1"
175
+ python3 -m unittest discover tests
176
+ ```
177
+
178
+ The MCP tests are skipped if `mcp` is not installed.
179
+
180
+ ## FAQ
181
+
182
+ **What input does it take?**
183
+ One JSON value, or several JSON Lines. Text on stdin, or a local file.
184
+
185
+ **Do my files leave my computer?**
186
+ No. The tool runs on your computer and never uses the internet.
187
+
188
+ **Do you call an AI model?**
189
+ No. The repair runs offline.
190
+
191
+ **How is this different from the Apify version?**
192
+ The Apify version runs in the cloud, can fetch file links, and is built for many documents in one run. This lite tool is free and local.
193
+
194
+ **Does it work with AI apps?**
195
+ Yes. It includes a free MCP server. No API key.
196
+
197
+ ## License
198
+
199
+ MIT. See `LICENSE`.
@@ -0,0 +1,19 @@
1
+ CHANGELOG.md
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ json_repair_lite.py
6
+ json_repair_lite_mcp.py
7
+ llms.txt
8
+ pyproject.toml
9
+ server.json
10
+ json_repair_lite.egg-info/PKG-INFO
11
+ json_repair_lite.egg-info/SOURCES.txt
12
+ json_repair_lite.egg-info/dependency_links.txt
13
+ json_repair_lite.egg-info/entry_points.txt
14
+ json_repair_lite.egg-info/requires.txt
15
+ json_repair_lite.egg-info/top_level.txt
16
+ tests/test_lite.py
17
+ tests/test_mcp.py
18
+ tests/fixtures/broken.json
19
+ tests/fixtures/lines.jsonl
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ json-repair-lite = json_repair_lite:main
3
+ json-repair-lite-mcp = json_repair_lite_mcp:main
@@ -0,0 +1,2 @@
1
+ mcp<2,>=1.10
2
+ json-repair<1,>=0.64.9
@@ -0,0 +1,2 @@
1
+ json_repair_lite
2
+ json_repair_lite_mcp
@@ -0,0 +1,163 @@
1
+ #!/usr/bin/env python3
2
+ """json-repair-lite (MIT): repair broken or incomplete JSON, including output from language models.
3
+
4
+ The converter uses the json-repair library and the Python standard library. The MCP
5
+ server (json_repair_lite_mcp.py) also needs the mcp package.
6
+
7
+ Need it at scale or from an AI agent? Use the Apify version:
8
+ https://apify.com/tidybytetools/json-repair
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+
16
+ from json_repair import repair_json
17
+
18
+ __version__ = "1.0.0"
19
+ APIFY_URL = "https://apify.com/tidybytetools/json-repair"
20
+ PRO_LINE = f"Need it at scale or from an AI agent? Use the Apify version: {APIFY_URL}"
21
+
22
+
23
+ def _loads_ok(text: str):
24
+ try:
25
+ return True, json.loads(text)
26
+ except Exception:
27
+ return False, None
28
+
29
+
30
+ def repair_one(text: str) -> dict:
31
+ raw = text.strip()
32
+ if not raw:
33
+ raise ValueError("The JSON text is empty.")
34
+ if raw.startswith("\ufeff"):
35
+ raw = raw.lstrip("\ufeff")
36
+ ok, value = _loads_ok(raw)
37
+ if ok:
38
+ return {
39
+ "wasValid": True,
40
+ "repaired": False,
41
+ "value": value,
42
+ "text": json.dumps(value, ensure_ascii=False),
43
+ }
44
+ try:
45
+ fixed = repair_json(raw, return_objects=False, ensure_ascii=False)
46
+ except Exception as e:
47
+ raise ValueError(f"Could not repair this JSON: {e}") from e
48
+ if not str(fixed).strip():
49
+ raise ValueError("Could not repair this JSON.")
50
+ ok2, value = _loads_ok(str(fixed))
51
+ if not ok2:
52
+ raise ValueError("The repair step did not produce valid JSON.")
53
+ return {
54
+ "wasValid": False,
55
+ "repaired": True,
56
+ "value": value,
57
+ "text": json.dumps(value, ensure_ascii=False),
58
+ }
59
+
60
+
61
+ def split_documents(text: str, force_lines: bool) -> list[str]:
62
+ raw = (text or "").strip()
63
+ if not raw:
64
+ return []
65
+ if raw.startswith("\ufeff"):
66
+ raw = raw.lstrip("\ufeff")
67
+ if force_lines:
68
+ return [ln.strip() for ln in raw.splitlines() if ln.strip()]
69
+ ok, _ = _loads_ok(raw)
70
+ if ok:
71
+ return [raw]
72
+ # A single broken object may span many lines — try the whole text first.
73
+ try:
74
+ repair_one(raw)
75
+ return [raw]
76
+ except ValueError:
77
+ lines = [ln.strip() for ln in raw.splitlines() if ln.strip()]
78
+ if len(lines) > 1:
79
+ return lines
80
+ return [raw]
81
+
82
+
83
+ def repair_text(text: str, json_lines: bool = False) -> dict:
84
+ docs = split_documents(text, json_lines)
85
+ if not docs:
86
+ raise ValueError("The JSON text is empty.")
87
+ results = []
88
+ errors = 0
89
+ for i, doc in enumerate(docs, start=1):
90
+ try:
91
+ rec = repair_one(doc)
92
+ rec["ok"] = True
93
+ rec["index"] = i
94
+ results.append(rec)
95
+ except Exception as e:
96
+ errors += 1
97
+ results.append({"ok": False, "index": i, "error": str(e)})
98
+ return {
99
+ "count": len(results),
100
+ "failed": errors,
101
+ "documents": results,
102
+ }
103
+
104
+
105
+ def run_mcp():
106
+ """Start the stdio MCP server (needs the mcp package, which pip installs for you)."""
107
+ try:
108
+ import json_repair_lite_mcp
109
+ except ImportError as e:
110
+ print(f"error: the MCP server needs the mcp package ({e}). Run: pip install git+https://github.com/tidybytetools/json-repair-lite", file=sys.stderr)
111
+ return 1
112
+ json_repair_lite_mcp.main()
113
+ return 0
114
+
115
+
116
+ def main(argv=None):
117
+ argv = sys.argv[1:] if argv is None else argv
118
+ if argv == ["mcp"]:
119
+ return run_mcp()
120
+ p = argparse.ArgumentParser(
121
+ prog="json-repair-lite",
122
+ description="Repair broken or incomplete JSON, including output from language models. Run `json-repair-lite mcp` to start the MCP server (to read a file named mcp, use ./mcp).",
123
+ epilog=PRO_LINE,
124
+ )
125
+ p.add_argument("file", nargs="?", help="input file (default: stdin)")
126
+ p.add_argument("--json-lines", action="store_true", help="treat each non-empty line as its own JSON document")
127
+ p.add_argument("--json", action="store_true", help="machine-readable envelope: {ok, count, failed, documents}")
128
+ p.add_argument("--indent", type=int, default=2)
129
+ p.add_argument("-q", "--quiet", action="store_true", help="don't print the one-line note about the Apify version")
130
+ p.add_argument("--version", action="version", version=__version__)
131
+ a = p.parse_args(argv)
132
+ try:
133
+ text = open(a.file, encoding="utf-8-sig").read() if a.file else sys.stdin.read()
134
+ bundle = repair_text(text, json_lines=a.json_lines)
135
+ failed = bundle["failed"]
136
+ if a.json:
137
+ out = {"ok": failed == 0, **bundle}
138
+ print(json.dumps(out, indent=a.indent, ensure_ascii=False))
139
+ elif bundle["count"] == 1:
140
+ rec = bundle["documents"][0]
141
+ if not rec.get("ok"):
142
+ raise ValueError(rec["error"])
143
+ print(json.dumps(rec["value"], indent=a.indent, ensure_ascii=False))
144
+ else:
145
+ # JSON Lines: one compact document per line
146
+ for rec in bundle["documents"]:
147
+ if rec.get("ok"):
148
+ print(rec["text"])
149
+ else:
150
+ print(json.dumps({"ok": False, "index": rec["index"], "error": rec["error"]}, ensure_ascii=False))
151
+ if not a.quiet and not a.json and sys.stderr.isatty():
152
+ print(PRO_LINE, file=sys.stderr)
153
+ return 1 if failed else 0
154
+ except Exception as e:
155
+ if getattr(a, "json", False):
156
+ print(json.dumps({"ok": False, "error": str(e)}))
157
+ return 1
158
+ print(f"error: {e}", file=sys.stderr)
159
+ return 1
160
+
161
+
162
+ if __name__ == "__main__":
163
+ sys.exit(main())
@@ -0,0 +1,108 @@
1
+ """Free MCP server for json-repair-lite (stdio).
2
+
3
+ Run: uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp
4
+ or: uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-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 json_repair_lite as lite
12
+
13
+ MAX_BYTES = 5_000_000 # 5 MB is plenty for JSON documents
14
+
15
+ mcp = FastMCP("json-repair-lite")
16
+
17
+ READ_ONLY = dict(
18
+ readOnlyHint=True, # only reads; never writes or changes anything
19
+ destructiveHint=False,
20
+ idempotentHint=True, # same input always gives the same JSON
21
+ openWorldHint=False, # no network; works on the text or local file you give it
22
+ )
23
+
24
+ JSON_LINES_HELP = (
25
+ "json_lines: if true, each non-empty line is a separate document. If false (default), "
26
+ "the whole text is tried as one JSON value first. If that cannot be repaired and there "
27
+ "are several lines, each line is then tried on its own."
28
+ )
29
+
30
+
31
+ def _check_file(path: str) -> str:
32
+ path = os.path.expanduser(path)
33
+ if not os.path.isfile(path):
34
+ raise FileNotFoundError(f"file not found: {path}")
35
+ if os.path.getsize(path) > MAX_BYTES:
36
+ raise ValueError("file is bigger than 5 MB")
37
+ with open(path, encoding="utf-8-sig") as f:
38
+ return f.read()
39
+
40
+
41
+ def _bundle_or_raise(text: str, json_lines: bool) -> dict:
42
+ bundle = lite.repair_text(text, json_lines=json_lines)
43
+ if bundle["count"] == 1:
44
+ rec = bundle["documents"][0]
45
+ if not rec.get("ok"):
46
+ raise ValueError(rec["error"])
47
+ return {k: rec[k] for k in ("wasValid", "repaired", "value", "text")}
48
+ return bundle
49
+
50
+
51
+ @mcp.tool(
52
+ title="Repair broken JSON text",
53
+ annotations=ToolAnnotations(title="Repair broken JSON text", **READ_ONLY),
54
+ )
55
+ def repair_json_text(
56
+ text: Annotated[str, Field(description="The JSON text to repair. May be one value, or several JSON Lines.")],
57
+ json_lines: Annotated[bool, Field(description="If true, treat each non-empty line as its own JSON document.")] = False,
58
+ ) -> dict:
59
+ """Repair broken or incomplete JSON, including output from language models.
60
+
61
+ Use this when you have JSON in the conversation that may be missing quotes,
62
+ have trailing commas, or be cut off. It is plain code, not an AI model: it
63
+ can close missing brackets and fix common syntax issues, but it cannot invent
64
+ the data you meant to write. Already-valid JSON is returned as-is, with
65
+ wasValid true and repaired false. Do not use it for a file on disk (use
66
+ repair_json_file for files).
67
+
68
+ json_lines: if true, each non-empty line is a separate document. If false
69
+ (default), the whole text is tried as one JSON value first. If that cannot be
70
+ repaired and there are several lines, each line is then tried on its own.
71
+
72
+ For one document, returns {"wasValid", "repaired", "value", "text"}. For
73
+ several documents, returns {"count", "failed", "documents": [...]}.
74
+ """
75
+ return _bundle_or_raise(text, json_lines)
76
+
77
+
78
+ @mcp.tool(
79
+ title="Repair JSON in a local file",
80
+ annotations=ToolAnnotations(title="Repair JSON in a local file", **READ_ONLY),
81
+ )
82
+ def repair_json_file(
83
+ path: Annotated[str, Field(description="Full path to a UTF-8 .json or .jsonl file, up to 5 MB.")],
84
+ json_lines: Annotated[bool, Field(description="If true, treat each non-empty line as its own JSON document.")] = False,
85
+ ) -> dict:
86
+ """Read a local JSON file and repair it if it is broken or incomplete.
87
+
88
+ Use this when the JSON is in a file on this computer, so you don't have to
89
+ paste it. The file is only read, never changed. Files larger than 5 MB are
90
+ rejected; use the Apify version for bigger jobs. Do not use it for files that
91
+ are not JSON text.
92
+
93
+ path: full path to a UTF-8 text file, up to 5 MB.
94
+ json_lines: if true, each non-empty line is a separate document. If false
95
+ (default), the whole text is tried as one JSON value first.
96
+
97
+ Returns the same object as repair_json_text.
98
+ """
99
+ text = _check_file(path)
100
+ return _bundle_or_raise(text, json_lines)
101
+
102
+
103
+ def main():
104
+ mcp.run()
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
@@ -0,0 +1,18 @@
1
+ # json-repair-lite
2
+
3
+ > Free, MIT-licensed, Python tool (uses the json-repair library; the MCP server also needs the mcp package) that repairs broken or incomplete JSON, including output from language models. Already-valid JSON is left as-is and reported honestly. Runs offline. No API key.
4
+
5
+ - Install: `pip install git+https://github.com/tidybytetools/json-repair-lite`
6
+ - CLI: `json-repair-lite file`. Reads stdin if no file. `--json-lines` treats each non-empty line as its own document. `--json` prints `{"ok": true, "count": 1, "failed": 0, "documents": [...]}`. Exit 0 ok, 1 error.
7
+ - Python: `from json_repair_lite import repair_one; repair_one("{name: 'Ada',}")`.
8
+ - MCP: `uvx --from git+https://github.com/tidybytetools/json-repair-lite json-repair-lite mcp` exposes two read-only tools: `repair_json_text(text, json_lines=false)` and `repair_json_file(path, json_lines=false)` for local UTF-8 files up to 5 MB.
9
+
10
+ ## Use when
11
+ - You have JSON that may be missing quotes, have trailing commas, or be cut off, including output from a language model.
12
+
13
+ ## Don't use when
14
+ - You need the tool to invent missing data (it cannot). You need to fetch a file from a URL, or the file is bigger than 5 MB in MCP. Use the Apify version: https://apify.com/tidybytetools/json-repair
15
+
16
+ ## Links
17
+ - [README](https://github.com/tidybytetools/json-repair-lite/blob/main/README.md)
18
+ - [Apify version](https://apify.com/tidybytetools/json-repair)
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "json-repair-lite"
7
+ version = "1.0.0"
8
+ description = "Repair broken or incomplete JSON, including output from language models. Local CLI and MCP server. No API key."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{name = "Tidy Byte Tools"}]
13
+ requires-python = ">=3.10"
14
+ dependencies = [
15
+ "mcp>=1.10,<2",
16
+ "json-repair>=0.64.9,<1",
17
+ ]
18
+ keywords = ["json", "json-repair", "jsonl", "llm", "cli", "mcp", "mcp-server", "data-cleaning"]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Environment :: Console",
22
+ "Intended Audience :: Developers",
23
+ "Intended Audience :: End Users/Desktop",
24
+ "Operating System :: OS Independent",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Programming Language :: Python :: 3.10",
28
+ "Programming Language :: Python :: 3.11",
29
+ "Programming Language :: Python :: 3.12",
30
+ "Programming Language :: Python :: 3.13",
31
+ "Topic :: Text Processing",
32
+ "Topic :: Utilities",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/tidybytetools/json-repair-lite"
37
+ Documentation = "https://github.com/tidybytetools/json-repair-lite#readme"
38
+ Source = "https://github.com/tidybytetools/json-repair-lite"
39
+ Issues = "https://github.com/tidybytetools/json-repair-lite/issues"
40
+ Changelog = "https://github.com/tidybytetools/json-repair-lite/blob/main/CHANGELOG.md"
41
+ Apify = "https://apify.com/tidybytetools/json-repair"
42
+
43
+ [project.scripts]
44
+ json-repair-lite = "json_repair_lite:main"
45
+ json-repair-lite-mcp = "json_repair_lite_mcp:main"
46
+
47
+ [tool.setuptools]
48
+ py-modules = ["json_repair_lite", "json_repair_lite_mcp"]
@@ -0,0 +1,31 @@
1
+ {
2
+ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
+ "name": "io.github.tidybytetools/json-repair-lite",
4
+ "title": "json-repair-lite",
5
+ "description": "Repair broken or incomplete JSON, including output from language models. Local CLI and MCP server. No API key.",
6
+ "repository": {
7
+ "url": "https://github.com/tidybytetools/json-repair-lite",
8
+ "source": "github"
9
+ },
10
+ "websiteUrl": "https://github.com/tidybytetools/json-repair-lite",
11
+ "version": "1.0.0",
12
+ "packages": [
13
+ {
14
+ "registryType": "pypi",
15
+ "registryBaseUrl": "https://pypi.org",
16
+ "identifier": "json-repair-lite",
17
+ "version": "1.0.0",
18
+ "runtimeHint": "uvx",
19
+ "transport": {
20
+ "type": "stdio"
21
+ },
22
+ "packageArguments": [
23
+ {
24
+ "type": "positional",
25
+ "value": "mcp",
26
+ "description": "Starts the MCP server instead of the command-line tool."
27
+ }
28
+ ]
29
+ }
30
+ ]
31
+ }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ {name: 'Ada', ok: true, trailing: 'comma',}
@@ -0,0 +1,2 @@
1
+ {"a": 1}
2
+ {b: 2,}
@@ -0,0 +1,120 @@
1
+ import io, os, sys, tempfile, unittest
2
+ from contextlib import redirect_stdout, redirect_stderr
3
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
4
+ import json_repair_lite as jr
5
+
6
+ class T(unittest.TestCase):
7
+ def test_already_valid(self):
8
+ r = jr.repair_one('{"a": 1}')
9
+ self.assertTrue(r["wasValid"])
10
+ self.assertFalse(r["repaired"])
11
+ self.assertEqual(r["value"], {"a": 1})
12
+
13
+ def test_trailing_comma_and_quotes(self):
14
+ r = jr.repair_one("{name: 'Ada', ok: true,}")
15
+ self.assertFalse(r["wasValid"])
16
+ self.assertTrue(r["repaired"])
17
+ self.assertEqual(r["value"]["name"], "Ada")
18
+ self.assertTrue(r["value"]["ok"])
19
+
20
+ def test_truncated(self):
21
+ r = jr.repair_one('{"items": [1, 2, 3')
22
+ self.assertTrue(r["repaired"])
23
+ self.assertEqual(r["value"]["items"], [1, 2, 3])
24
+
25
+ def test_empty(self):
26
+ with self.assertRaises(ValueError):
27
+ jr.repair_one(" ")
28
+
29
+ def test_split_single(self):
30
+ docs = jr.split_documents('{"a": 1}', False)
31
+ self.assertEqual(len(docs), 1)
32
+
33
+ def test_split_lines(self):
34
+ docs = jr.split_documents('{"a": 1}\n{"b": 2}\n', True)
35
+ self.assertEqual(len(docs), 2)
36
+
37
+ def test_repair_text_one(self):
38
+ bundle = jr.repair_text("{name: 'Ada',}")
39
+ self.assertEqual(bundle["count"], 1)
40
+ self.assertEqual(bundle["failed"], 0)
41
+ self.assertEqual(bundle["documents"][0]["value"]["name"], "Ada")
42
+
43
+ def test_repair_text_lines(self):
44
+ bundle = jr.repair_text('{"a": 1}\n{b: 2,}', json_lines=True)
45
+ self.assertEqual(bundle["count"], 2)
46
+ self.assertEqual(bundle["failed"], 0)
47
+ self.assertEqual(bundle["documents"][1]["value"]["b"], 2)
48
+
49
+ def test_bom(self):
50
+ r = jr.repair_one('\ufeff{"a": 1}')
51
+ self.assertTrue(r["wasValid"])
52
+ self.assertEqual(r["value"], {"a": 1})
53
+
54
+ def run_main(self, argv, stdin=""):
55
+ out, err = io.StringIO(), io.StringIO()
56
+ old = sys.stdin
57
+ sys.stdin = io.StringIO(stdin)
58
+ try:
59
+ with redirect_stdout(out), redirect_stderr(err):
60
+ code = jr.main(argv)
61
+ finally:
62
+ sys.stdin = old
63
+ return code, out.getvalue(), err.getvalue()
64
+
65
+ def test_cli_json_envelope(self):
66
+ code, out, err = self.run_main(["--json"], "{name: 'Ada', ok: true,}")
67
+ self.assertEqual(code, 0)
68
+ self.assertIn('"ok": true', out)
69
+ self.assertIn('"repaired": true', out)
70
+ self.assertIn("Ada", out)
71
+ self.assertNotIn("apify.com", out)
72
+
73
+ def test_cli_pretty_valid(self):
74
+ code, out, err = self.run_main([], '{"a": 1}')
75
+ self.assertEqual(code, 0)
76
+ self.assertIn('"a": 1', out)
77
+
78
+ def test_cli_json_lines(self):
79
+ code, out, err = self.run_main(["--json-lines"], '{"a": 1}\n{b: 2,}\n')
80
+ self.assertEqual(code, 0)
81
+ lines = [ln for ln in out.splitlines() if ln.strip()]
82
+ self.assertEqual(len(lines), 2)
83
+ self.assertIn('"a": 1', lines[0])
84
+ self.assertIn('"b": 2', lines[1])
85
+
86
+ def test_cli_help_has_apify_link(self):
87
+ out = io.StringIO()
88
+ with redirect_stdout(out), self.assertRaises(SystemExit):
89
+ jr.main(["--help"])
90
+ self.assertIn("https://apify.com/tidybytetools/json-repair", out.getvalue())
91
+
92
+ def test_bad_file(self):
93
+ code, out, err = self.run_main(["--json", "/nope/missing.json"], "")
94
+ self.assertEqual(code, 1)
95
+ self.assertIn('"ok": false', out)
96
+
97
+ def test_cli_file(self):
98
+ with tempfile.TemporaryDirectory() as td:
99
+ path = os.path.join(td, "broken.json")
100
+ with open(path, "w", encoding="utf-8") as f:
101
+ f.write("{name: 'Ada',}")
102
+ code, out, err = self.run_main([path])
103
+ self.assertEqual(code, 0)
104
+ self.assertIn("Ada", out)
105
+
106
+ def test_empty_stdin_json(self):
107
+ code, out, err = self.run_main(["--json"], " ")
108
+ self.assertEqual(code, 1)
109
+ self.assertIn('"ok": false', out)
110
+
111
+ def test_version(self):
112
+ out = io.StringIO()
113
+ with redirect_stdout(out), self.assertRaises(SystemExit) as ctx:
114
+ jr.main(["--version"])
115
+ self.assertIn(ctx.exception.code, (0, None))
116
+ self.assertIn("1.0.0", out.getvalue())
117
+
118
+
119
+ if __name__ == "__main__":
120
+ unittest.main()
@@ -0,0 +1,71 @@
1
+ """Starts the MCP server over stdio (both ways it can start), lists tools, and calls them."""
2
+ import asyncio, json, os, sys, unittest
3
+ HERE = os.path.dirname(os.path.abspath(__file__))
4
+ ROOT = os.path.dirname(HERE)
5
+
6
+ try:
7
+ from mcp import ClientSession, StdioServerParameters
8
+ from mcp.client.stdio import stdio_client
9
+ except ImportError:
10
+ ClientSession = None
11
+
12
+ READ_ONLY = {"readOnlyHint": True, "destructiveHint": False, "idempotentHint": True, "openWorldHint": False}
13
+
14
+
15
+ def _data(res):
16
+ """The tool result as Python data (structured content if present, else the JSON text)."""
17
+ if res.structuredContent is not None:
18
+ sc = res.structuredContent
19
+ return sc.get("result", sc) if set(sc) == {"result"} else sc
20
+ return json.loads(res.content[0].text)
21
+
22
+
23
+ async def _session(args, fn):
24
+ params = StdioServerParameters(command=sys.executable, args=args, cwd=ROOT)
25
+ async with stdio_client(params) as (r, w):
26
+ async with ClientSession(r, w) as s:
27
+ await s.initialize()
28
+ return await fn(s)
29
+
30
+
31
+ @unittest.skipIf(ClientSession is None, "mcp not installed")
32
+ class MCP(unittest.TestCase):
33
+ def test_tools_and_annotations(self):
34
+ async def go(s):
35
+ return (await s.list_tools()).tools
36
+ tools = asyncio.run(_session([os.path.join(ROOT, "json_repair_lite_mcp.py")], go))
37
+ self.assertEqual(sorted(t.name for t in tools), ["repair_json_file", "repair_json_text"])
38
+ for t in tools:
39
+ self.assertTrue(t.title)
40
+ self.assertIn("Use this when", t.description)
41
+ for k, v in READ_ONLY.items():
42
+ self.assertIs(getattr(t.annotations, k), v, f"{t.name} {k}")
43
+
44
+ def test_calls(self):
45
+ async def go(s):
46
+ one = await s.call_tool("repair_json_text", {"text": "{name: 'Ada', ok: true,}"})
47
+ valid = await s.call_tool("repair_json_text", {"text": '{"a": 1}'})
48
+ lines = await s.call_tool("repair_json_text", {"text": '{"a": 1}\n{b: 2,}', "json_lines": True})
49
+ f = await s.call_tool("repair_json_file", {"path": os.path.join(HERE, "fixtures", "broken.json")})
50
+ missing = await s.call_tool("repair_json_file", {"path": "/nope/missing.json"})
51
+ empty = await s.call_tool("repair_json_text", {"text": " "})
52
+ return one, valid, lines, f, missing, empty
53
+ one, valid, lines, f, missing, empty = asyncio.run(_session([os.path.join(ROOT, "json_repair_lite_mcp.py")], go))
54
+ self.assertEqual(_data(one)["value"]["name"], "Ada")
55
+ self.assertTrue(_data(one)["repaired"])
56
+ self.assertTrue(_data(valid)["wasValid"])
57
+ self.assertFalse(_data(valid)["repaired"])
58
+ self.assertEqual(_data(lines)["count"], 2)
59
+ self.assertEqual(_data(f)["value"]["name"], "Ada")
60
+ self.assertTrue(missing.isError)
61
+ self.assertTrue(empty.isError)
62
+
63
+ def test_cli_mcp_subcommand_starts_server(self):
64
+ async def go(s):
65
+ return [t.name for t in (await s.list_tools()).tools]
66
+ names = asyncio.run(_session([os.path.join(ROOT, "json_repair_lite.py"), "mcp"], go))
67
+ self.assertIn("repair_json_text", names)
68
+
69
+
70
+ if __name__ == "__main__":
71
+ unittest.main()