flatresult 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-27)
4
+
5
+ First release.
6
+
7
+ - `flatten(result, keep=False, read=None, max_text=100_000)` rewrites a `tools/call` result for
8
+ clients that only handle text and image blocks: `structuredContent` without a text block gets
9
+ one with its JSON; `resource_link` becomes a text line naming it, plus the resource's contents
10
+ when `read` can fetch them; embedded text resources become text; image blobs become `image`
11
+ blocks; other blobs and `audio` become a short note. `keep=True` keeps the original blocks.
12
+ Returns the same object when nothing needs rewriting. `links(result)` lists the link uris.
13
+ - `flatresult proxy [--keep] [--no-inline] [--max-links N] [--max-text CHARS]
14
+ [--timeout SECONDS] [--quiet] [--log FILE] -- <server command>`: stdio proxy for any MCP
15
+ server. Rewrites only the results of the client's `tools/call` requests, reads linked
16
+ resources with the server's own `resources/read` (copying the 2026-07-28 request envelope
17
+ from the client's call), and holds the result until they arrive or the timeout passes.
18
+ - `flatresult check [FILE]`: rewrite one result or JSON-RPC response from the command line;
19
+ exit code 2 when something was rewritten.
@@ -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,171 @@
1
+ Metadata-Version: 2.5
2
+ Name: flatresult
3
+ Version: 0.1.0
4
+ Summary: Fix MCP tool results that clients show as empty or reject ("Unsupported response item type: resource_link"): turns structuredContent-only results, resource_link blocks, embedded resources and audio into text and image blocks every client reads, as a stdio proxy for any MCP server or one function
5
+ Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/flatresult
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/flatresult/CHANGELOG.md
9
+ Author: Sri Krishna Lingamaneni
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: agents,claude,content blocks,cursor,dify,embedded resource,empty result,figma mcp,goose,kiro,librechat,llm,mcp,mcp proxy,mcp server,model context protocol,no response,resource_link,structuredContent,tool results,unsupported response item type
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: mcp>=1.10; (python_version >= '3.10') and extra == 'test'
23
+ Requires-Dist: pytest>=7; extra == 'test'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # flatresult
27
+
28
+ MCP tools can return more than text: `structuredContent`, `resource_link` blocks, embedded
29
+ resources and audio. Many clients only handle text and image blocks, so the result shows up
30
+ empty, gets dropped, prints as a raw struct, or fails the whole call with
31
+ `Unsupported response item type: resource_link`.
32
+
33
+ flatresult rewrites tool results into text and image blocks every client reads. It puts the
34
+ JSON of `structuredContent` in a text block when the server sent none, reads linked resources
35
+ from the server and puts their contents inline, and turns embedded resources into text (or an
36
+ image). Use it as a stdio proxy around any MCP server (no code changes, any language) or as one
37
+ function. No dependencies.
38
+
39
+ ```bash
40
+ pip install flatresult
41
+ ```
42
+
43
+ ## Quick start: any stdio server
44
+
45
+ Put `flatresult proxy --` in front of the server command in your client's config:
46
+
47
+ ```json
48
+ {
49
+ "mcpServers": {
50
+ "my-server": {
51
+ "command": "flatresult",
52
+ "args": ["proxy", "--", "npx", "-y", "@acme/mcp-server"]
53
+ }
54
+ }
55
+ }
56
+ ```
57
+
58
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["flatresult", "proxy", "--", ...]`.
59
+
60
+ For a remote (HTTP) server, wrap a stdio bridge such as `mcp-remote`:
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "figma": {
66
+ "command": "uvx",
67
+ "args": ["flatresult", "proxy", "--", "npx", "-y", "mcp-remote", "https://mcp.figma.com/mcp"]
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+ Each rewrite is reported on stderr (most clients show it in their MCP log):
74
+
75
+ ```text
76
+ flatresult: content[0]: resource_link -> inline contents: text block
77
+ flatresult: structuredContent: structuredContent -> text block (412 chars)
78
+ ```
79
+
80
+ ### Proxy options
81
+
82
+ | Option | What it does |
83
+ |---|---|
84
+ | `--keep` | Keep the original blocks and add the text after them, for clients that skip unknown blocks instead of failing on them. |
85
+ | `--no-inline` | Don't read linked resources; turn each link into a text line naming it. |
86
+ | `--max-links N` | Read at most N linked resources per result (default 5). The rest become text lines. |
87
+ | `--max-text CHARS` | Cut resource text put inline after CHARS characters (default 100,000), with a note saying how much was left out. |
88
+ | `--timeout SECONDS` | If the server has not answered `resources/read` by then, send the result with the links as text (default 10). |
89
+ | `--quiet` / `--log FILE` | Don't report rewrites, or append them to a file instead of stderr. |
90
+
91
+ Only the results of the client's own `tools/call` requests are touched. Everything else passes
92
+ through byte for byte. Linked resources are read with the server's own `resources/read`, so
93
+ the proxy needs no credentials of its own; the client never sees those requests. If the server
94
+ says it has no `resources` capability, links become text lines.
95
+
96
+ ## What gets rewritten
97
+
98
+ | The server sends | The client gets |
99
+ |---|---|
100
+ | `structuredContent` with no text block | a text block with its JSON (`structuredContent` is kept), as the spec asks servers to do |
101
+ | `resource_link` | `Resource: <name> <uri> (mime type, size)` and its description, plus the resource's contents when the server can read it |
102
+ | embedded text resource (`type: "resource"`, `text`) | a text block: `<uri> (<mime type>):` and the text |
103
+ | embedded image blob | an `image` block |
104
+ | other embedded blobs, `audio` | a short note: `[binary resource file:///r.pdf: application/pdf, 52,113 bytes, not shown]` |
105
+ | `text`, `image`, unknown block types | unchanged |
106
+
107
+ ## In your own client or server: one function
108
+
109
+ ```python
110
+ from flatresult import flatten
111
+
112
+ result = {"content": [], "structuredContent": {"temp": 21.5, "unit": "C"}}
113
+ flat = flatten(result)
114
+ flat.result["content"] # [{"type": "text", "text": '{"temp": 21.5, "unit": "C"}'}]
115
+ [str(c) for c in flat.changes]
116
+ # ['structuredContent: structuredContent -> text block (27 chars)']
117
+ ```
118
+
119
+ `flatten(result, keep=False, read=None, max_text=100_000)` takes a `tools/call` result (a
120
+ dict) and returns `Flattened(result, changes)`. It never changes its input, and returns the same
121
+ object when nothing needs rewriting. Pass `read`, a function from a uri to the `contents` list
122
+ of a `resources/read` result (or `None`), to put linked resources inline. `links(result)` lists
123
+ the uris to read.
124
+
125
+ To see what a result would look like, there's a command too (exit code 2 when it rewrote
126
+ something):
127
+
128
+ ```bash
129
+ echo '{"content": [{"type": "resource_link", "uri": "file:///r.txt", "name": "report"}]}' \
130
+ | flatresult check
131
+ ```
132
+
133
+ ## Limits
134
+
135
+ - It fixes what the client is given, not how the client shows it. A client that already reads
136
+ `structuredContent` or resource links gets the same data twice with `--keep`, and as text
137
+ instead of its own UI without it. Use it for clients that show nothing.
138
+ - Links are read only from the server behind the proxy. An `https://` link the server can't
139
+ read stays a text line; the proxy never fetches URLs itself.
140
+ - Binary resources other than images are not decoded (a PDF stays a note with its size).
141
+ - The proxy speaks stdio. For a remote server, put a stdio bridge such as `mcp-remote` behind it.
142
+
143
+ ## Why this exists
144
+
145
+ The spec says a tool that returns `structuredContent` SHOULD also return the JSON as text, and
146
+ that clients should handle every content type. In practice both sides skip it, and users of
147
+ one client lose the data another client shows:
148
+
149
+ - [microsoft/work-iq#240](https://github.com/microsoft/work-iq/issues/240): the hosted Work IQ
150
+ server returns `fetch` results only in `structuredContent`; Cursor shows them blank.
151
+ - [kirodotdev/Kiro#9439](https://github.com/kirodotdev/Kiro/issues/9439): every Figma MCP tool
152
+ failed with `Unsupported response item type: resource_link` (4 upvotes).
153
+ - [langgenius/dify#43451](https://github.com/langgenius/dify/issues/43451): resource_link-only
154
+ tool results are discarded.
155
+ - [anthropics/claude-ai-mcp#1086](https://github.com/anthropics/claude-ai-mcp/issues/1086) and
156
+ [anthropics/claude-code#93946](https://github.com/anthropics/claude-code/issues/93946): blobs in
157
+ embedded-resource results are dropped or rejected.
158
+ - [charmbracelet/crush#3846](https://github.com/charmbracelet/crush/issues/3846): embedded
159
+ resources render as a raw Go struct pointer.
160
+ - [microsoft/copilot-sdk#2816](https://github.com/microsoft/copilot-sdk/issues/2816),
161
+ [agentscope-ai/agentscope#2798](https://github.com/agentscope-ai/agentscope/issues/2798),
162
+ [tobi/qmd#959](https://github.com/tobi/qmd/issues/959): more clients that drop or garble
163
+ resource blocks.
164
+
165
+ Some clients have closed their reports one by one (LibreChat#15198, goose#13182, Cherry
166
+ Studio#23290), each on its own schedule. flatresult works in front of any client today, with
167
+ servers you don't control.
168
+
169
+ ## License
170
+
171
+ MIT
@@ -0,0 +1,146 @@
1
+ # flatresult
2
+
3
+ MCP tools can return more than text: `structuredContent`, `resource_link` blocks, embedded
4
+ resources and audio. Many clients only handle text and image blocks, so the result shows up
5
+ empty, gets dropped, prints as a raw struct, or fails the whole call with
6
+ `Unsupported response item type: resource_link`.
7
+
8
+ flatresult rewrites tool results into text and image blocks every client reads. It puts the
9
+ JSON of `structuredContent` in a text block when the server sent none, reads linked resources
10
+ from the server and puts their contents inline, and turns embedded resources into text (or an
11
+ image). Use it as a stdio proxy around any MCP server (no code changes, any language) or as one
12
+ function. No dependencies.
13
+
14
+ ```bash
15
+ pip install flatresult
16
+ ```
17
+
18
+ ## Quick start: any stdio server
19
+
20
+ Put `flatresult proxy --` in front of the server command in your client's config:
21
+
22
+ ```json
23
+ {
24
+ "mcpServers": {
25
+ "my-server": {
26
+ "command": "flatresult",
27
+ "args": ["proxy", "--", "npx", "-y", "@acme/mcp-server"]
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["flatresult", "proxy", "--", ...]`.
34
+
35
+ For a remote (HTTP) server, wrap a stdio bridge such as `mcp-remote`:
36
+
37
+ ```json
38
+ {
39
+ "mcpServers": {
40
+ "figma": {
41
+ "command": "uvx",
42
+ "args": ["flatresult", "proxy", "--", "npx", "-y", "mcp-remote", "https://mcp.figma.com/mcp"]
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ Each rewrite is reported on stderr (most clients show it in their MCP log):
49
+
50
+ ```text
51
+ flatresult: content[0]: resource_link -> inline contents: text block
52
+ flatresult: structuredContent: structuredContent -> text block (412 chars)
53
+ ```
54
+
55
+ ### Proxy options
56
+
57
+ | Option | What it does |
58
+ |---|---|
59
+ | `--keep` | Keep the original blocks and add the text after them, for clients that skip unknown blocks instead of failing on them. |
60
+ | `--no-inline` | Don't read linked resources; turn each link into a text line naming it. |
61
+ | `--max-links N` | Read at most N linked resources per result (default 5). The rest become text lines. |
62
+ | `--max-text CHARS` | Cut resource text put inline after CHARS characters (default 100,000), with a note saying how much was left out. |
63
+ | `--timeout SECONDS` | If the server has not answered `resources/read` by then, send the result with the links as text (default 10). |
64
+ | `--quiet` / `--log FILE` | Don't report rewrites, or append them to a file instead of stderr. |
65
+
66
+ Only the results of the client's own `tools/call` requests are touched. Everything else passes
67
+ through byte for byte. Linked resources are read with the server's own `resources/read`, so
68
+ the proxy needs no credentials of its own; the client never sees those requests. If the server
69
+ says it has no `resources` capability, links become text lines.
70
+
71
+ ## What gets rewritten
72
+
73
+ | The server sends | The client gets |
74
+ |---|---|
75
+ | `structuredContent` with no text block | a text block with its JSON (`structuredContent` is kept), as the spec asks servers to do |
76
+ | `resource_link` | `Resource: <name> <uri> (mime type, size)` and its description, plus the resource's contents when the server can read it |
77
+ | embedded text resource (`type: "resource"`, `text`) | a text block: `<uri> (<mime type>):` and the text |
78
+ | embedded image blob | an `image` block |
79
+ | other embedded blobs, `audio` | a short note: `[binary resource file:///r.pdf: application/pdf, 52,113 bytes, not shown]` |
80
+ | `text`, `image`, unknown block types | unchanged |
81
+
82
+ ## In your own client or server: one function
83
+
84
+ ```python
85
+ from flatresult import flatten
86
+
87
+ result = {"content": [], "structuredContent": {"temp": 21.5, "unit": "C"}}
88
+ flat = flatten(result)
89
+ flat.result["content"] # [{"type": "text", "text": '{"temp": 21.5, "unit": "C"}'}]
90
+ [str(c) for c in flat.changes]
91
+ # ['structuredContent: structuredContent -> text block (27 chars)']
92
+ ```
93
+
94
+ `flatten(result, keep=False, read=None, max_text=100_000)` takes a `tools/call` result (a
95
+ dict) and returns `Flattened(result, changes)`. It never changes its input, and returns the same
96
+ object when nothing needs rewriting. Pass `read`, a function from a uri to the `contents` list
97
+ of a `resources/read` result (or `None`), to put linked resources inline. `links(result)` lists
98
+ the uris to read.
99
+
100
+ To see what a result would look like, there's a command too (exit code 2 when it rewrote
101
+ something):
102
+
103
+ ```bash
104
+ echo '{"content": [{"type": "resource_link", "uri": "file:///r.txt", "name": "report"}]}' \
105
+ | flatresult check
106
+ ```
107
+
108
+ ## Limits
109
+
110
+ - It fixes what the client is given, not how the client shows it. A client that already reads
111
+ `structuredContent` or resource links gets the same data twice with `--keep`, and as text
112
+ instead of its own UI without it. Use it for clients that show nothing.
113
+ - Links are read only from the server behind the proxy. An `https://` link the server can't
114
+ read stays a text line; the proxy never fetches URLs itself.
115
+ - Binary resources other than images are not decoded (a PDF stays a note with its size).
116
+ - The proxy speaks stdio. For a remote server, put a stdio bridge such as `mcp-remote` behind it.
117
+
118
+ ## Why this exists
119
+
120
+ The spec says a tool that returns `structuredContent` SHOULD also return the JSON as text, and
121
+ that clients should handle every content type. In practice both sides skip it, and users of
122
+ one client lose the data another client shows:
123
+
124
+ - [microsoft/work-iq#240](https://github.com/microsoft/work-iq/issues/240): the hosted Work IQ
125
+ server returns `fetch` results only in `structuredContent`; Cursor shows them blank.
126
+ - [kirodotdev/Kiro#9439](https://github.com/kirodotdev/Kiro/issues/9439): every Figma MCP tool
127
+ failed with `Unsupported response item type: resource_link` (4 upvotes).
128
+ - [langgenius/dify#43451](https://github.com/langgenius/dify/issues/43451): resource_link-only
129
+ tool results are discarded.
130
+ - [anthropics/claude-ai-mcp#1086](https://github.com/anthropics/claude-ai-mcp/issues/1086) and
131
+ [anthropics/claude-code#93946](https://github.com/anthropics/claude-code/issues/93946): blobs in
132
+ embedded-resource results are dropped or rejected.
133
+ - [charmbracelet/crush#3846](https://github.com/charmbracelet/crush/issues/3846): embedded
134
+ resources render as a raw Go struct pointer.
135
+ - [microsoft/copilot-sdk#2816](https://github.com/microsoft/copilot-sdk/issues/2816),
136
+ [agentscope-ai/agentscope#2798](https://github.com/agentscope-ai/agentscope/issues/2798),
137
+ [tobi/qmd#959](https://github.com/tobi/qmd/issues/959): more clients that drop or garble
138
+ resource blocks.
139
+
140
+ Some clients have closed their reports one by one (LibreChat#15198, goose#13182, Cherry
141
+ Studio#23290), each on its own schedule. flatresult works in front of any client today, with
142
+ servers you don't control.
143
+
144
+ ## License
145
+
146
+ MIT
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "flatresult"
7
+ version = "0.1.0"
8
+ description = "Fix MCP tool results that clients show as empty or reject (\"Unsupported response item type: resource_link\"): turns structuredContent-only results, resource_link blocks, embedded resources and audio into text and image blocks every client reads, 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 results",
16
+ "structuredContent", "resource_link", "embedded resource", "content blocks",
17
+ "unsupported response item type", "empty result", "no response", "figma mcp",
18
+ "kiro", "cursor", "librechat", "goose", "dify", "claude", "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", "mcp>=1.10; python_version >= '3.10'"]
33
+
34
+ [project.scripts]
35
+ flatresult = "flatresult.cli:main"
36
+
37
+ [project.urls]
38
+ Homepage = "https://github.com/srikrishnaL/kitforge/tree/main/packages/flatresult"
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/flatresult/CHANGELOG.md"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ packages = ["src/flatresult"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
@@ -0,0 +1,6 @@
1
+ """Make MCP tool results readable by clients that only show text and image blocks."""
2
+
3
+ from .core import Change, Flattened, flatten, links, needs_flattening
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["Change", "Flattened", "flatten", "links", "needs_flattening", "__version__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,155 @@
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 send_to_client(self, msg: Any) -> None:
79
+ """Send a message to the client from outside a hook (a timer, say)."""
80
+ self._write(self.stdout, _dump(msg))
81
+
82
+ def _handle(self, line: bytes, hook: Hook, forward: BinaryIO, back: BinaryIO) -> None:
83
+ line = line if line.endswith(b"\n") else line + b"\n"
84
+ try:
85
+ msg = json.loads(line)
86
+ except ValueError:
87
+ self._write(forward, line)
88
+ return
89
+ batch = isinstance(msg, list)
90
+ out: List[Any] = []
91
+ replies: List[dict] = []
92
+ changed = False
93
+ for item in (msg if batch else [msg]):
94
+ if not isinstance(item, dict):
95
+ out.append(item)
96
+ continue
97
+ try:
98
+ new, extra = hook(item)
99
+ except Exception as exc: # never break the connection over a rewrite
100
+ print(f"{self.name}: {type(exc).__name__}: {exc}", file=sys.stderr)
101
+ new, extra = item, []
102
+ if new is not item:
103
+ changed = True
104
+ if new is not None:
105
+ out.append(new)
106
+ replies += extra
107
+ if out:
108
+ self._write(forward, _dump(out if batch else out[0]) if changed else line)
109
+ for reply in replies:
110
+ self._write(back, _dump(reply))
111
+
112
+ def _pump_server(self) -> None:
113
+ assert self.proc and self.proc.stdout and self.proc.stdin
114
+ for line in _lines(self.proc.stdout):
115
+ if line.strip():
116
+ self._handle(line, self.to_client, self.stdout, self.proc.stdin)
117
+
118
+ def _pump_client(self) -> None:
119
+ assert self.proc and self.proc.stdin
120
+ for line in _lines(self.stdin):
121
+ if line.strip():
122
+ self._handle(line, self.to_server, self.proc.stdin, self.stdout)
123
+ try:
124
+ self.proc.stdin.close()
125
+ except OSError:
126
+ pass
127
+
128
+ def run(self) -> int:
129
+ try:
130
+ self.proc = subprocess.Popen(self.command, stdin=subprocess.PIPE,
131
+ stdout=subprocess.PIPE, bufsize=0)
132
+ except OSError as exc:
133
+ print(f"{self.name}: can't start {self.command[0]}: {exc}", file=sys.stderr)
134
+ return 127
135
+ pump = threading.Thread(target=self._pump_server, daemon=True)
136
+ pump.start()
137
+ threading.Thread(target=self._pump_client, daemon=True).start()
138
+
139
+ previous = None
140
+ if hasattr(signal, "SIGTERM") and threading.current_thread() is threading.main_thread():
141
+ def forward(signum, frame): # pass a shutdown request on to the server
142
+ if self.proc and self.proc.poll() is None:
143
+ self.proc.terminate()
144
+ previous = signal.signal(signal.SIGTERM, forward)
145
+ try:
146
+ try:
147
+ code = self.proc.wait()
148
+ except KeyboardInterrupt:
149
+ self.proc.terminate()
150
+ code = self.proc.wait()
151
+ pump.join(timeout=5)
152
+ finally:
153
+ if previous is not None:
154
+ signal.signal(signal.SIGTERM, previous)
155
+ return 128 - code if code < 0 else code