unstring 0.1.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
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ node_modules/
11
+ coverage/
12
+ .DS_Store
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-24)
4
+
5
+ First release.
6
+
7
+ - `repair(arguments, schema)` decodes tool-call arguments sent as JSON strings where the
8
+ tool's `inputSchema` wants an array, object, integer, number, boolean or null, at any depth
9
+ (`$ref`, `anyOf`/`oneOf`/`allOf`, `additionalProperties`, `patternProperties`,
10
+ `prefixItems`). Never touches a value where the schema allows a string. Handles
11
+ double-encoded JSON, arrays sent as index-keyed objects
12
+ (`{"0": x, "1": y}`), Python literals (via `ast.literal_eval`) and a whole `arguments`
13
+ object sent as a string. Returns the repaired value and a list of fixes; `wrap=True` also
14
+ turns a single value into a list where an array is wanted.
15
+ - `unstring proxy [--wrap] [--quiet] [--log FILE] -- <server command>`: stdio proxy for any
16
+ MCP server. Learns schemas from `tools/list`, fetches the list itself (all pages) when a
17
+ call names a tool it has not seen, and holds that call until it can repair it.
18
+ - `unstring fix --schema FILE|JSON [--tool NAME] [ARGS]`: repair one set of arguments from
19
+ the command line; exit code 2 when something was repaired.
unstring-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sri Krishna Lingamaneni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,166 @@
1
+ Metadata-Version: 2.5
2
+ Name: unstring
3
+ Version: 0.1.0
4
+ Summary: Fix MCP tool calls that fail with "expected array, received string": repairs tool-call arguments that clients and models send as JSON strings (arrays, objects, numbers, booleans), guided by the tool's inputSchema, as a stdio proxy for any MCP server or one function
5
+ Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/unstring
6
+ Project-URL: Source, https://github.com/srikrishnaL/kitforge
7
+ Project-URL: Issues, https://github.com/srikrishnaL/kitforge/issues
8
+ Project-URL: Changelog, https://github.com/srikrishnaL/kitforge/blob/main/packages/unstring/CHANGELOG.md
9
+ Author: Sri Krishna Lingamaneni
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,claude code,claude desktop,coerce,expected array,function calling,invalid arguments,json schema,json string,llm,mcp,mcp proxy,mcp server,model context protocol,n8n,opencode,pydantic,received string,stringified,tool arguments,tool calling,zod
13
+ Classifier: Development Status :: 4 - Beta
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: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.9
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest>=7; extra == 'test'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # unstring
26
+
27
+ Some MCP clients and models send tool arguments as JSON strings: `"pages": "[{\"title\": \"A\"}]"`
28
+ where the tool's schema says array, `"limit": "5"` where it says integer. The server rejects
29
+ the call with `expected array, received string` (or `Input should be a valid list`), and the
30
+ agent retries, gives up, or writes nothing.
31
+
32
+ unstring repairs those arguments before the server sees them, guided by the tool's own
33
+ `inputSchema`. A value is decoded only where the schema does not allow a string, and only when
34
+ the decoded value has a type the schema does allow, so real strings are never touched. Use it
35
+ as a stdio proxy around any MCP server (no code changes, any language) or as one function.
36
+
37
+ ```bash
38
+ pip install unstring
39
+ ```
40
+
41
+ ## Quick start: any stdio server
42
+
43
+ Put `unstring proxy --` in front of the server command in your client's config:
44
+
45
+ ```json
46
+ {
47
+ "mcpServers": {
48
+ "notion": {
49
+ "command": "unstring",
50
+ "args": ["proxy", "--", "npx", "-y", "@notionhq/notion-mcp-server"]
51
+ }
52
+ }
53
+ }
54
+ ```
55
+
56
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["unstring", "proxy", "--", ...]`.
57
+
58
+ Each repair is reported on stderr (most clients show it in their MCP log):
59
+
60
+ ```text
61
+ unstring: create_pages: pages: string -> array; pages[0].position: string -> integer
62
+ ```
63
+
64
+ ### Proxy options
65
+
66
+ | Option | What it does |
67
+ |---|---|
68
+ | `--wrap` | Also turn a single value into a one-item list where the schema wants an array (`"ids": 4` becomes `[4]`). Off by default. |
69
+ | `--quiet` | Don't report repairs. |
70
+ | `--log FILE` | Append repair reports to a file instead of stderr. |
71
+
72
+ The proxy learns each tool's schema from the `tools/list` results the client asks for. If a
73
+ call names a tool it has not seen (the client cached the list), it asks the server for the
74
+ tool list itself, holds the call until the answer is in, and then sends it on, repaired. All
75
+ other messages pass through byte for byte.
76
+
77
+ ## In your own server or client: one function
78
+
79
+ ```python
80
+ from unstring import repair
81
+
82
+ schema = {
83
+ "type": "object",
84
+ "properties": {
85
+ "pages": {"type": "array", "items": {"type": "object", "properties": {
86
+ "title": {"type": "string"}, "position": {"type": "integer"}}}},
87
+ "query": {"type": "string"},
88
+ "limit": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
89
+ },
90
+ }
91
+ result = repair({"pages": '[{"title": "A", "position": "2"}]', "query": "[1, 2]",
92
+ "limit": "10"}, schema)
93
+
94
+ print(result.value)
95
+ # {'pages': [{'title': 'A', 'position': 2}], 'query': '[1, 2]', 'limit': 10}
96
+ print([str(f) for f in result.fixes])
97
+ # ['pages: string -> array', 'pages[0].position: string -> integer', 'limit: string -> integer']
98
+ ```
99
+
100
+ `query` stays a string: the schema says it is one. `repair_arguments(args, schema)` returns
101
+ only the value. Check one call from the command line:
102
+
103
+ ```console
104
+ $ unstring fix --schema tools.json --tool create_pages '{"pages": "[{\"title\": \"A\"}]"}'
105
+ repaired pages: string -> array
106
+ {
107
+ "pages": [
108
+ {
109
+ "title": "A"
110
+ }
111
+ ]
112
+ }
113
+ ```
114
+
115
+ `--schema` takes an `inputSchema`, a tool, or a saved `tools/list` result. The exit code is 2
116
+ when something was repaired, 0 when nothing needed it.
117
+
118
+ ## What gets repaired
119
+
120
+ - JSON text for arrays, objects, integers, numbers, booleans and `null` where the schema wants
121
+ those types, at any depth: inside arrays, nested objects, `$ref`/`$defs`, `anyOf`/`oneOf`/
122
+ `allOf`, `additionalProperties`, `patternProperties`, `prefixItems`.
123
+ - Double-encoded JSON (`"\"[1, 2]\""`).
124
+ - Python literals some bridges send (`"['a', 'b']"`, `"{'k': True}"`), parsed safely with
125
+ `ast.literal_eval`, never `eval`.
126
+ - Arrays that arrived as index-keyed objects (`{"0": x, "1": y}` where the schema wants an
127
+ array), as some HTTP bridges send them.
128
+ - `"True"`/`"FALSE"` for booleans, `"5.0"` for an integer field.
129
+ - The whole `arguments` object sent as one JSON string.
130
+
131
+ ## Limits
132
+
133
+ - Where the schema allows a string (`"type": ["string", "array"]`, an untyped field, `{}`),
134
+ the string is left alone, because there is no safe way to tell. Give the field a type if
135
+ you want it repaired.
136
+ - `unstring proxy` works with stdio servers. For a remote (Streamable HTTP) server, call
137
+ `repair` in the server where the arguments arrive.
138
+ - It fixes types, not values: a wrong enum, a missing required field or a bad date still
139
+ reaches the server and fails there, as it should.
140
+ - Strings like `"007"` or `"1,2"` are not valid JSON and are not guessed at.
141
+
142
+ ## Why this exists
143
+
144
+ Clients keep sending stringified arguments, intermittently, and every server works around it
145
+ on its own (`tryParseJson` helpers, `z.preprocess`, accept-a-string-too unions):
146
+
147
+ - [anthropics/claude-code#26094](https://github.com/anthropics/claude-code/issues/26094): Claude
148
+ Desktop serializes MCP object parameters as strings, breaking Notion MCP writes (21 upvotes).
149
+ - [makenotion/notion-mcp-server#215](https://github.com/makenotion/notion-mcp-server/issues/215):
150
+ `pages` array parameter received as a string.
151
+ - [anthropics/claude-code#86459](https://github.com/anthropics/claude-code/issues/86459): array
152
+ parameters silently stringified mid-call, breaking any tool expecting `List[str]`.
153
+ - [n8n-io/n8n#33864](https://github.com/n8n-io/n8n/issues/33864): typed tool parameters arrive as
154
+ strings, `expected array, received string`.
155
+ - [czlonkowski/n8n-mcp#814](https://github.com/czlonkowski/n8n-mcp/issues/814): nested arrays and
156
+ objects mis-serialized by HTTP MCP clients (strings, and arrays turned into `{"0": ..}`
157
+ objects); the server's `tryParseJson` misses cases.
158
+ - [continuedev/continue#13350](https://github.com/continuedev/continue/issues/13350) and
159
+ [exa-labs/exa-mcp-server#477](https://github.com/exa-labs/exa-mcp-server/issues/477): the same
160
+ error from Continue and Exa.
161
+ - [anomalyco/opencode#57023](https://github.com/anomalyco/opencode/issues/57023): the whole
162
+ `arguments` object passed as a string.
163
+
164
+ ## License
165
+
166
+ MIT
@@ -0,0 +1,142 @@
1
+ # unstring
2
+
3
+ Some MCP clients and models send tool arguments as JSON strings: `"pages": "[{\"title\": \"A\"}]"`
4
+ where the tool's schema says array, `"limit": "5"` where it says integer. The server rejects
5
+ the call with `expected array, received string` (or `Input should be a valid list`), and the
6
+ agent retries, gives up, or writes nothing.
7
+
8
+ unstring repairs those arguments before the server sees them, guided by the tool's own
9
+ `inputSchema`. A value is decoded only where the schema does not allow a string, and only when
10
+ the decoded value has a type the schema does allow, so real strings are never touched. Use it
11
+ as a stdio proxy around any MCP server (no code changes, any language) or as one function.
12
+
13
+ ```bash
14
+ pip install unstring
15
+ ```
16
+
17
+ ## Quick start: any stdio server
18
+
19
+ Put `unstring proxy --` in front of the server command in your client's config:
20
+
21
+ ```json
22
+ {
23
+ "mcpServers": {
24
+ "notion": {
25
+ "command": "unstring",
26
+ "args": ["proxy", "--", "npx", "-y", "@notionhq/notion-mcp-server"]
27
+ }
28
+ }
29
+ }
30
+ ```
31
+
32
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["unstring", "proxy", "--", ...]`.
33
+
34
+ Each repair is reported on stderr (most clients show it in their MCP log):
35
+
36
+ ```text
37
+ unstring: create_pages: pages: string -> array; pages[0].position: string -> integer
38
+ ```
39
+
40
+ ### Proxy options
41
+
42
+ | Option | What it does |
43
+ |---|---|
44
+ | `--wrap` | Also turn a single value into a one-item list where the schema wants an array (`"ids": 4` becomes `[4]`). Off by default. |
45
+ | `--quiet` | Don't report repairs. |
46
+ | `--log FILE` | Append repair reports to a file instead of stderr. |
47
+
48
+ The proxy learns each tool's schema from the `tools/list` results the client asks for. If a
49
+ call names a tool it has not seen (the client cached the list), it asks the server for the
50
+ tool list itself, holds the call until the answer is in, and then sends it on, repaired. All
51
+ other messages pass through byte for byte.
52
+
53
+ ## In your own server or client: one function
54
+
55
+ ```python
56
+ from unstring import repair
57
+
58
+ schema = {
59
+ "type": "object",
60
+ "properties": {
61
+ "pages": {"type": "array", "items": {"type": "object", "properties": {
62
+ "title": {"type": "string"}, "position": {"type": "integer"}}}},
63
+ "query": {"type": "string"},
64
+ "limit": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
65
+ },
66
+ }
67
+ result = repair({"pages": '[{"title": "A", "position": "2"}]', "query": "[1, 2]",
68
+ "limit": "10"}, schema)
69
+
70
+ print(result.value)
71
+ # {'pages': [{'title': 'A', 'position': 2}], 'query': '[1, 2]', 'limit': 10}
72
+ print([str(f) for f in result.fixes])
73
+ # ['pages: string -> array', 'pages[0].position: string -> integer', 'limit: string -> integer']
74
+ ```
75
+
76
+ `query` stays a string: the schema says it is one. `repair_arguments(args, schema)` returns
77
+ only the value. Check one call from the command line:
78
+
79
+ ```console
80
+ $ unstring fix --schema tools.json --tool create_pages '{"pages": "[{\"title\": \"A\"}]"}'
81
+ repaired pages: string -> array
82
+ {
83
+ "pages": [
84
+ {
85
+ "title": "A"
86
+ }
87
+ ]
88
+ }
89
+ ```
90
+
91
+ `--schema` takes an `inputSchema`, a tool, or a saved `tools/list` result. The exit code is 2
92
+ when something was repaired, 0 when nothing needed it.
93
+
94
+ ## What gets repaired
95
+
96
+ - JSON text for arrays, objects, integers, numbers, booleans and `null` where the schema wants
97
+ those types, at any depth: inside arrays, nested objects, `$ref`/`$defs`, `anyOf`/`oneOf`/
98
+ `allOf`, `additionalProperties`, `patternProperties`, `prefixItems`.
99
+ - Double-encoded JSON (`"\"[1, 2]\""`).
100
+ - Python literals some bridges send (`"['a', 'b']"`, `"{'k': True}"`), parsed safely with
101
+ `ast.literal_eval`, never `eval`.
102
+ - Arrays that arrived as index-keyed objects (`{"0": x, "1": y}` where the schema wants an
103
+ array), as some HTTP bridges send them.
104
+ - `"True"`/`"FALSE"` for booleans, `"5.0"` for an integer field.
105
+ - The whole `arguments` object sent as one JSON string.
106
+
107
+ ## Limits
108
+
109
+ - Where the schema allows a string (`"type": ["string", "array"]`, an untyped field, `{}`),
110
+ the string is left alone, because there is no safe way to tell. Give the field a type if
111
+ you want it repaired.
112
+ - `unstring proxy` works with stdio servers. For a remote (Streamable HTTP) server, call
113
+ `repair` in the server where the arguments arrive.
114
+ - It fixes types, not values: a wrong enum, a missing required field or a bad date still
115
+ reaches the server and fails there, as it should.
116
+ - Strings like `"007"` or `"1,2"` are not valid JSON and are not guessed at.
117
+
118
+ ## Why this exists
119
+
120
+ Clients keep sending stringified arguments, intermittently, and every server works around it
121
+ on its own (`tryParseJson` helpers, `z.preprocess`, accept-a-string-too unions):
122
+
123
+ - [anthropics/claude-code#26094](https://github.com/anthropics/claude-code/issues/26094): Claude
124
+ Desktop serializes MCP object parameters as strings, breaking Notion MCP writes (21 upvotes).
125
+ - [makenotion/notion-mcp-server#215](https://github.com/makenotion/notion-mcp-server/issues/215):
126
+ `pages` array parameter received as a string.
127
+ - [anthropics/claude-code#86459](https://github.com/anthropics/claude-code/issues/86459): array
128
+ parameters silently stringified mid-call, breaking any tool expecting `List[str]`.
129
+ - [n8n-io/n8n#33864](https://github.com/n8n-io/n8n/issues/33864): typed tool parameters arrive as
130
+ strings, `expected array, received string`.
131
+ - [czlonkowski/n8n-mcp#814](https://github.com/czlonkowski/n8n-mcp/issues/814): nested arrays and
132
+ objects mis-serialized by HTTP MCP clients (strings, and arrays turned into `{"0": ..}`
133
+ objects); the server's `tryParseJson` misses cases.
134
+ - [continuedev/continue#13350](https://github.com/continuedev/continue/issues/13350) and
135
+ [exa-labs/exa-mcp-server#477](https://github.com/exa-labs/exa-mcp-server/issues/477): the same
136
+ error from Continue and Exa.
137
+ - [anomalyco/opencode#57023](https://github.com/anomalyco/opencode/issues/57023): the whole
138
+ `arguments` object passed as a string.
139
+
140
+ ## License
141
+
142
+ MIT
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "unstring"
7
+ version = "0.1.0"
8
+ description = "Fix MCP tool calls that fail with \"expected array, received string\": repairs tool-call arguments that clients and models send as JSON strings (arrays, objects, numbers, booleans), guided by the tool's inputSchema, as a stdio proxy for any MCP server or one function"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [{ name = "Sri Krishna Lingamaneni" }]
14
+ keywords = [
15
+ "mcp", "model context protocol", "mcp server", "mcp proxy", "tool calling",
16
+ "function calling", "tool arguments", "stringified", "json string", "expected array",
17
+ "received string", "invalid arguments", "json schema", "coerce", "zod", "pydantic",
18
+ "claude code", "claude desktop", "opencode", "n8n", "llm", "agents",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 4 - Beta",
22
+ "Intended Audience :: Developers",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3 :: Only",
26
+ "Topic :: Software Development :: Libraries",
27
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
28
+ ]
29
+ dependencies = []
30
+
31
+ [project.optional-dependencies]
32
+ test = ["pytest>=7"]
33
+
34
+ [project.scripts]
35
+ unstring = "unstring.cli:main"
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/srikrishnaL/kitforge/tree/main/packages/unstring"
39
+ Source = "https://github.com/srikrishnaL/kitforge"
40
+ Issues = "https://github.com/srikrishnaL/kitforge/issues"
41
+ Changelog = "https://github.com/srikrishnaL/kitforge/blob/main/packages/unstring/CHANGELOG.md"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/unstring"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
@@ -0,0 +1,6 @@
1
+ """Repair MCP tool-call arguments that clients send as JSON strings."""
2
+
3
+ from .core import Fix, Result, repair, repair_arguments
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["Fix", "Result", "repair", "repair_arguments", "__version__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,151 @@
1
+ """A stdio relay between an MCP client and an MCP server, with hooks to rewrite messages.
2
+
3
+ MCP over stdio is one JSON-RPC message (or batch) per line. The relay starts the server,
4
+ copies lines both ways, and gives each parsed message to a hook that may change it, drop it,
5
+ or answer it directly. Lines that are not changed are passed on byte for byte.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ from typing import Any, BinaryIO, Callable, Iterator, List, Optional, Tuple
18
+
19
+ # A hook gets one message and returns (message to pass on or None, replies to send back).
20
+ Hook = Callable[[dict], Tuple[Optional[dict], List[dict]]]
21
+
22
+
23
+ def _dump(msg: Any) -> bytes:
24
+ return json.dumps(msg, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n"
25
+
26
+
27
+ def _lines(stream: BinaryIO) -> Iterator[bytes]:
28
+ """Lines from ``stream``, read from its file descriptor when it has one.
29
+
30
+ A thread blocked inside a buffered reader holds the reader's lock, and Python aborts at
31
+ exit if a daemon thread still holds it; ``os.read`` takes no lock.
32
+ """
33
+ try:
34
+ fd = stream.fileno()
35
+ read: Callable[[int], bytes] = lambda n: os.read(fd, n) # noqa: E731
36
+ except (AttributeError, OSError, ValueError):
37
+ read = getattr(stream, "read1", stream.read)
38
+ buf = b""
39
+ while True:
40
+ try:
41
+ chunk = read(65536)
42
+ except (OSError, ValueError):
43
+ break
44
+ if not chunk:
45
+ break
46
+ buf += chunk
47
+ while b"\n" in buf:
48
+ line, buf = buf.split(b"\n", 1)
49
+ yield line + b"\n"
50
+ if buf:
51
+ yield buf
52
+
53
+
54
+ class Relay:
55
+ def __init__(self, command: List[str], *, to_server: Hook, to_client: Hook,
56
+ stdin: Optional[BinaryIO] = None, stdout: Optional[BinaryIO] = None,
57
+ name: str = "proxy") -> None:
58
+ if not command:
59
+ raise ValueError("no server command given")
60
+ exe = shutil.which(command[0]) # finds npx.cmd and friends on Windows
61
+ self.command = [exe or command[0]] + list(command[1:])
62
+ self.name = name
63
+ self.to_server = to_server
64
+ self.to_client = to_client
65
+ self.stdin = stdin or sys.stdin.buffer
66
+ self.stdout = stdout or sys.stdout.buffer
67
+ self._lock = threading.Lock()
68
+ self.proc: Optional[subprocess.Popen] = None
69
+
70
+ def _write(self, stream: BinaryIO, data: bytes) -> None:
71
+ with self._lock:
72
+ try:
73
+ stream.write(data)
74
+ stream.flush()
75
+ except (BrokenPipeError, OSError, ValueError):
76
+ pass
77
+
78
+ def _handle(self, line: bytes, hook: Hook, forward: BinaryIO, back: BinaryIO) -> None:
79
+ line = line if line.endswith(b"\n") else line + b"\n"
80
+ try:
81
+ msg = json.loads(line)
82
+ except ValueError:
83
+ self._write(forward, line)
84
+ return
85
+ batch = isinstance(msg, list)
86
+ out: List[Any] = []
87
+ replies: List[dict] = []
88
+ changed = False
89
+ for item in (msg if batch else [msg]):
90
+ if not isinstance(item, dict):
91
+ out.append(item)
92
+ continue
93
+ try:
94
+ new, extra = hook(item)
95
+ except Exception as exc: # never break the connection over a rewrite
96
+ print(f"{self.name}: {type(exc).__name__}: {exc}", file=sys.stderr)
97
+ new, extra = item, []
98
+ if new is not item:
99
+ changed = True
100
+ if new is not None:
101
+ out.append(new)
102
+ replies += extra
103
+ if out:
104
+ self._write(forward, _dump(out if batch else out[0]) if changed else line)
105
+ for reply in replies:
106
+ self._write(back, _dump(reply))
107
+
108
+ def _pump_server(self) -> None:
109
+ assert self.proc and self.proc.stdout and self.proc.stdin
110
+ for line in _lines(self.proc.stdout):
111
+ if line.strip():
112
+ self._handle(line, self.to_client, self.stdout, self.proc.stdin)
113
+
114
+ def _pump_client(self) -> None:
115
+ assert self.proc and self.proc.stdin
116
+ for line in _lines(self.stdin):
117
+ if line.strip():
118
+ self._handle(line, self.to_server, self.proc.stdin, self.stdout)
119
+ try:
120
+ self.proc.stdin.close()
121
+ except OSError:
122
+ pass
123
+
124
+ def run(self) -> int:
125
+ try:
126
+ self.proc = subprocess.Popen(self.command, stdin=subprocess.PIPE,
127
+ stdout=subprocess.PIPE, bufsize=0)
128
+ except OSError as exc:
129
+ print(f"{self.name}: can't start {self.command[0]}: {exc}", file=sys.stderr)
130
+ return 127
131
+ pump = threading.Thread(target=self._pump_server, daemon=True)
132
+ pump.start()
133
+ threading.Thread(target=self._pump_client, daemon=True).start()
134
+
135
+ previous = None
136
+ if hasattr(signal, "SIGTERM") and threading.current_thread() is threading.main_thread():
137
+ def forward(signum, frame): # pass a shutdown request on to the server
138
+ if self.proc and self.proc.poll() is None:
139
+ self.proc.terminate()
140
+ previous = signal.signal(signal.SIGTERM, forward)
141
+ try:
142
+ try:
143
+ code = self.proc.wait()
144
+ except KeyboardInterrupt:
145
+ self.proc.terminate()
146
+ code = self.proc.wait()
147
+ pump.join(timeout=5)
148
+ finally:
149
+ if previous is not None:
150
+ signal.signal(signal.SIGTERM, previous)
151
+ return 128 - code if code < 0 else code