longcall 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,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-12-01)
4
+
5
+ First release.
6
+
7
+ - `longcall proxy [--timeout SECONDS] [--tool NAME=SECONDS|off] [--mode background|error]
8
+ [--cancel-after SECONDS] [--wait SECONDS] [--keep N] [--result-tool NAME] [--quiet]
9
+ [--log FILE] -- <server command>`: a stdio proxy for any MCP server. A tool call still
10
+ running at its timeout is answered with a job id and keeps running; the model fetches the
11
+ result with the added `longcall_result` tool. `--mode error` cancels the call instead and
12
+ returns an error result that names the timeout.
13
+ - `longcall.run()` and `longcall.Keeper` for use from Python.
longcall-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,181 @@
1
+ Metadata-Version: 2.5
2
+ Name: longcall
3
+ Version: 0.1.0
4
+ Summary: Fix MCP tool calls that time out ("MCP error -32001: Request timed out", Claude Desktop's 4-minute limit): a stdio proxy for any MCP server that answers slow calls with a job id and lets the model fetch the result later, or cancels them with an error the model can read, with per-tool timeouts
5
+ Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/longcall
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/longcall/CHANGELOG.md
9
+ Author: Sri Krishna Lingamaneni
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: -32001,agents,async tool calls,background jobs,claude code,claude desktop,codex,cursor,llm,long-running tools,mcp,mcp proxy,mcp server,model context protocol,per-tool timeout,request timed out,timeout,tool calling
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
+ # longcall
27
+
28
+ MCP clients give up on a tool call after a fixed time: 60 seconds in many clients built on the
29
+ TypeScript SDK (`MCP error -32001: Request timed out`), 4 minutes in Claude Desktop
30
+ (`No result received from the Claude Desktop app after waiting 4 minutes`), and most of them have
31
+ no per-tool setting. Tools that run a long query, a build, a scan or a backup fail every time,
32
+ though the server is fine and would have answered.
33
+
34
+ longcall is a stdio proxy that sits in front of any MCP server and answers a slow call before the
35
+ client gives up. The call keeps running on the server; the model gets a job id and fetches the
36
+ real result later with a `longcall_result` tool that the proxy adds. Or, with `--mode error`, the
37
+ call is cancelled and the model gets an error it can read and act on, instead of a broken session.
38
+ No change to the server or the client, any language.
39
+
40
+ ```bash
41
+ pip install longcall
42
+ ```
43
+
44
+ ## Quick start
45
+
46
+ Put `longcall proxy --` in front of the server command in your client's config:
47
+
48
+ ```json
49
+ {
50
+ "mcpServers": {
51
+ "warehouse": {
52
+ "command": "longcall",
53
+ "args": ["proxy", "--timeout", "50", "--", "npx", "-y", "@acme/warehouse-mcp"]
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["longcall", "proxy", "--", ...]`.
60
+
61
+ What the model sees when `run_report` takes three minutes:
62
+
63
+ ```text
64
+ > run_report {"quarter": "Q3"}
65
+ The tool run_report is still running (over 50s), so its result is not here yet. Get it by
66
+ calling the tool longcall_result with job_id "job-5f0c2a91". Each call waits up to 50s for the
67
+ result; call it again if the job is still running. Don't start run_report again for the same
68
+ request.
69
+
70
+ > longcall_result {"job_id": "job-5f0c2a91"}
71
+ Job job-5f0c2a91 (run_report) is still running (100s so far). Call longcall_result again ...
72
+
73
+ > longcall_result {"job_id": "job-5f0c2a91"}
74
+ <run_report's own result, exactly as the server sent it>
75
+ ```
76
+
77
+ Each step is reported on stderr (most clients show it in their MCP log):
78
+
79
+ ```text
80
+ longcall: run_report still running after 50s; answered with job job-5f0c2a91
81
+ longcall: run_report finished after 183.2s (job job-5f0c2a91)
82
+ ```
83
+
84
+ Calls that finish within the timeout are passed on unchanged, so fast tools behave exactly as
85
+ before.
86
+
87
+ ## Options
88
+
89
+ | Option | What it does |
90
+ |---|---|
91
+ | `--timeout SECONDS` | Answer a call still running after this long. Default `50`, under the 60-second timeout of many clients. Set it a little under your client's limit. |
92
+ | `--tool NAME=SECONDS` | A different timeout for one tool. `--tool NAME=off` passes that tool's calls through untouched. Repeatable. |
93
+ | `--mode error` | Don't keep the call: tell the server to cancel it (`notifications/cancelled`) and give the model an error result that says it timed out after N seconds. Use this for per-tool timeouts the model can understand, with no extra tool. |
94
+ | `--cancel-after SECONDS` | Background mode: cancel a call that is still running after this long in all. Default: never. |
95
+ | `--wait SECONDS` | Longest time one `longcall_result` call waits for the result. Default and maximum: `--timeout`, so the wait never trips the client's timeout either. |
96
+ | `--keep N` | Finished results kept for the model to fetch. Default `100`. Running jobs are always kept. |
97
+ | `--result-tool NAME` | Name of the added tool. Default `longcall_result`. |
98
+ | `--quiet` | Don't report on stderr. |
99
+ | `--log FILE` | Append reports to a file instead of stderr. |
100
+
101
+ Example: a database server whose `export` tool takes minutes, while every other tool should fail
102
+ fast with a clear error:
103
+
104
+ ```bash
105
+ longcall proxy --mode error --timeout 20 --tool export=off -- python -m my_db_server
106
+ ```
107
+
108
+ ## From Python
109
+
110
+ ```python
111
+ from longcall import run
112
+
113
+ run(["npx", "-y", "@acme/warehouse-mcp"], timeout=50, tools={"export": 600, "ping": None})
114
+ ```
115
+
116
+ `longcall.Keeper` holds the message logic on its own (`to_server`, `to_client` hooks and
117
+ `send_client`, `send_server` callbacks) if you relay MCP messages yourself.
118
+
119
+ ## How it works
120
+
121
+ - Each `tools/call` goes to the server under an id of the proxy's own, so the proxy can answer the
122
+ client and still recognise the server's late reply. A deadline starts with it.
123
+ - Answer in time: the client gets it with its own id. Progress notifications pass through while
124
+ the client waits.
125
+ - Deadline first (background mode): the client gets a "still running" result with a job id
126
+ (also in `_meta.longcall`), and later progress notifications for that call are dropped. The
127
+ server's result is stored when it arrives, and `longcall_result` returns it as the server sent
128
+ it, `structuredContent` and `isError` included. A JSON-RPC error from the server comes back as
129
+ an error result with its message.
130
+ - `longcall_result` is appended to the last page of `tools/list`, marked read-only and
131
+ idempotent. If the server already has a tool by that name, nothing is added and a warning is
132
+ printed: pick another name with `--result-tool`.
133
+ - Deadline first (error mode): the server gets `notifications/cancelled` for the call, the client
134
+ gets an `isError` result naming the timeout.
135
+ - A client that cancels a call it is still waiting for cancels it on the server too.
136
+ - Results to clients on the 2026-07-28 protocol carry `resultType: "complete"`.
137
+
138
+ ## Limits
139
+
140
+ - stdio servers only. For a remote (Streamable HTTP) server, run it through a local stdio bridge
141
+ first.
142
+ - Jobs live in the proxy's memory: when the client restarts the server, running jobs and their
143
+ results are lost.
144
+ - For tools that declare an `outputSchema`, the "still running" answer is marked `isError`,
145
+ because clients reject a normal result without `structuredContent`. The text still tells the
146
+ model to fetch the result.
147
+ - The model has to follow the instruction to call `longcall_result`. A model that ignores it will
148
+ report the job as pending, so the text is written to be followed.
149
+ - It does not change a client's own timeout. It only answers before that timeout runs out, so
150
+ set `--timeout` below it.
151
+ - Servers built on old releases of the MCP Python SDK (1.10 to 1.12 tested; 1.25 is fine) stop
152
+ answering after any cancelled request, so with those use background mode without
153
+ `--cancel-after`.
154
+ - A call answered with a job id keeps running on the server. Tools with side effects still take
155
+ effect, even if the model never fetches the result. Use `--mode error` or `--cancel-after` when
156
+ that is not what you want.
157
+
158
+ ## Why this exists
159
+
160
+ Long tool calls failing on a client timeout is one of the most reported MCP problems, and most
161
+ clients have one global timeout or none you can set:
162
+
163
+ - [anthropics/claude-code#65643](https://github.com/anthropics/claude-code/issues/65643): Claude
164
+ Desktop ends any call after 4 minutes, and the bridge wedges after a few timeouts.
165
+ - [modelcontextprotocol/typescript-sdk#245](https://github.com/modelcontextprotocol/typescript-sdk/issues/245):
166
+ the client times out after 60 seconds whatever the timeout option says.
167
+ - [anthropics/claude-code#16837](https://github.com/anthropics/claude-code/issues/16837):
168
+ `MCP_TIMEOUT` over 60 seconds is ignored.
169
+ - [kirodotdev/Kiro#126](https://github.com/kirodotdev/Kiro/issues/126): MCP request timeouts.
170
+ - [livekit/agents#8523](https://github.com/livekit/agents/issues/8523) and
171
+ [QwenLM/qwen-code#18323](https://github.com/QwenLM/qwen-code/issues/18323): per-tool timeouts,
172
+ and timeouts the model and the caller can tell apart from other failures.
173
+ - [infiniflow/ragflow#23003](https://github.com/infiniflow/ragflow/issues/23003): a tool timeout
174
+ should reach the model as a result, not fail the whole run.
175
+
176
+ The MCP Tasks extension solves this properly for clients and servers that support it. longcall
177
+ is for the many that don't yet.
178
+
179
+ ## License
180
+
181
+ MIT
@@ -0,0 +1,156 @@
1
+ # longcall
2
+
3
+ MCP clients give up on a tool call after a fixed time: 60 seconds in many clients built on the
4
+ TypeScript SDK (`MCP error -32001: Request timed out`), 4 minutes in Claude Desktop
5
+ (`No result received from the Claude Desktop app after waiting 4 minutes`), and most of them have
6
+ no per-tool setting. Tools that run a long query, a build, a scan or a backup fail every time,
7
+ though the server is fine and would have answered.
8
+
9
+ longcall is a stdio proxy that sits in front of any MCP server and answers a slow call before the
10
+ client gives up. The call keeps running on the server; the model gets a job id and fetches the
11
+ real result later with a `longcall_result` tool that the proxy adds. Or, with `--mode error`, the
12
+ call is cancelled and the model gets an error it can read and act on, instead of a broken session.
13
+ No change to the server or the client, any language.
14
+
15
+ ```bash
16
+ pip install longcall
17
+ ```
18
+
19
+ ## Quick start
20
+
21
+ Put `longcall proxy --` in front of the server command in your client's config:
22
+
23
+ ```json
24
+ {
25
+ "mcpServers": {
26
+ "warehouse": {
27
+ "command": "longcall",
28
+ "args": ["proxy", "--timeout", "50", "--", "npx", "-y", "@acme/warehouse-mcp"]
29
+ }
30
+ }
31
+ }
32
+ ```
33
+
34
+ Or with `uvx`, nothing to install first: `"command": "uvx", "args": ["longcall", "proxy", "--", ...]`.
35
+
36
+ What the model sees when `run_report` takes three minutes:
37
+
38
+ ```text
39
+ > run_report {"quarter": "Q3"}
40
+ The tool run_report is still running (over 50s), so its result is not here yet. Get it by
41
+ calling the tool longcall_result with job_id "job-5f0c2a91". Each call waits up to 50s for the
42
+ result; call it again if the job is still running. Don't start run_report again for the same
43
+ request.
44
+
45
+ > longcall_result {"job_id": "job-5f0c2a91"}
46
+ Job job-5f0c2a91 (run_report) is still running (100s so far). Call longcall_result again ...
47
+
48
+ > longcall_result {"job_id": "job-5f0c2a91"}
49
+ <run_report's own result, exactly as the server sent it>
50
+ ```
51
+
52
+ Each step is reported on stderr (most clients show it in their MCP log):
53
+
54
+ ```text
55
+ longcall: run_report still running after 50s; answered with job job-5f0c2a91
56
+ longcall: run_report finished after 183.2s (job job-5f0c2a91)
57
+ ```
58
+
59
+ Calls that finish within the timeout are passed on unchanged, so fast tools behave exactly as
60
+ before.
61
+
62
+ ## Options
63
+
64
+ | Option | What it does |
65
+ |---|---|
66
+ | `--timeout SECONDS` | Answer a call still running after this long. Default `50`, under the 60-second timeout of many clients. Set it a little under your client's limit. |
67
+ | `--tool NAME=SECONDS` | A different timeout for one tool. `--tool NAME=off` passes that tool's calls through untouched. Repeatable. |
68
+ | `--mode error` | Don't keep the call: tell the server to cancel it (`notifications/cancelled`) and give the model an error result that says it timed out after N seconds. Use this for per-tool timeouts the model can understand, with no extra tool. |
69
+ | `--cancel-after SECONDS` | Background mode: cancel a call that is still running after this long in all. Default: never. |
70
+ | `--wait SECONDS` | Longest time one `longcall_result` call waits for the result. Default and maximum: `--timeout`, so the wait never trips the client's timeout either. |
71
+ | `--keep N` | Finished results kept for the model to fetch. Default `100`. Running jobs are always kept. |
72
+ | `--result-tool NAME` | Name of the added tool. Default `longcall_result`. |
73
+ | `--quiet` | Don't report on stderr. |
74
+ | `--log FILE` | Append reports to a file instead of stderr. |
75
+
76
+ Example: a database server whose `export` tool takes minutes, while every other tool should fail
77
+ fast with a clear error:
78
+
79
+ ```bash
80
+ longcall proxy --mode error --timeout 20 --tool export=off -- python -m my_db_server
81
+ ```
82
+
83
+ ## From Python
84
+
85
+ ```python
86
+ from longcall import run
87
+
88
+ run(["npx", "-y", "@acme/warehouse-mcp"], timeout=50, tools={"export": 600, "ping": None})
89
+ ```
90
+
91
+ `longcall.Keeper` holds the message logic on its own (`to_server`, `to_client` hooks and
92
+ `send_client`, `send_server` callbacks) if you relay MCP messages yourself.
93
+
94
+ ## How it works
95
+
96
+ - Each `tools/call` goes to the server under an id of the proxy's own, so the proxy can answer the
97
+ client and still recognise the server's late reply. A deadline starts with it.
98
+ - Answer in time: the client gets it with its own id. Progress notifications pass through while
99
+ the client waits.
100
+ - Deadline first (background mode): the client gets a "still running" result with a job id
101
+ (also in `_meta.longcall`), and later progress notifications for that call are dropped. The
102
+ server's result is stored when it arrives, and `longcall_result` returns it as the server sent
103
+ it, `structuredContent` and `isError` included. A JSON-RPC error from the server comes back as
104
+ an error result with its message.
105
+ - `longcall_result` is appended to the last page of `tools/list`, marked read-only and
106
+ idempotent. If the server already has a tool by that name, nothing is added and a warning is
107
+ printed: pick another name with `--result-tool`.
108
+ - Deadline first (error mode): the server gets `notifications/cancelled` for the call, the client
109
+ gets an `isError` result naming the timeout.
110
+ - A client that cancels a call it is still waiting for cancels it on the server too.
111
+ - Results to clients on the 2026-07-28 protocol carry `resultType: "complete"`.
112
+
113
+ ## Limits
114
+
115
+ - stdio servers only. For a remote (Streamable HTTP) server, run it through a local stdio bridge
116
+ first.
117
+ - Jobs live in the proxy's memory: when the client restarts the server, running jobs and their
118
+ results are lost.
119
+ - For tools that declare an `outputSchema`, the "still running" answer is marked `isError`,
120
+ because clients reject a normal result without `structuredContent`. The text still tells the
121
+ model to fetch the result.
122
+ - The model has to follow the instruction to call `longcall_result`. A model that ignores it will
123
+ report the job as pending, so the text is written to be followed.
124
+ - It does not change a client's own timeout. It only answers before that timeout runs out, so
125
+ set `--timeout` below it.
126
+ - Servers built on old releases of the MCP Python SDK (1.10 to 1.12 tested; 1.25 is fine) stop
127
+ answering after any cancelled request, so with those use background mode without
128
+ `--cancel-after`.
129
+ - A call answered with a job id keeps running on the server. Tools with side effects still take
130
+ effect, even if the model never fetches the result. Use `--mode error` or `--cancel-after` when
131
+ that is not what you want.
132
+
133
+ ## Why this exists
134
+
135
+ Long tool calls failing on a client timeout is one of the most reported MCP problems, and most
136
+ clients have one global timeout or none you can set:
137
+
138
+ - [anthropics/claude-code#65643](https://github.com/anthropics/claude-code/issues/65643): Claude
139
+ Desktop ends any call after 4 minutes, and the bridge wedges after a few timeouts.
140
+ - [modelcontextprotocol/typescript-sdk#245](https://github.com/modelcontextprotocol/typescript-sdk/issues/245):
141
+ the client times out after 60 seconds whatever the timeout option says.
142
+ - [anthropics/claude-code#16837](https://github.com/anthropics/claude-code/issues/16837):
143
+ `MCP_TIMEOUT` over 60 seconds is ignored.
144
+ - [kirodotdev/Kiro#126](https://github.com/kirodotdev/Kiro/issues/126): MCP request timeouts.
145
+ - [livekit/agents#8523](https://github.com/livekit/agents/issues/8523) and
146
+ [QwenLM/qwen-code#18323](https://github.com/QwenLM/qwen-code/issues/18323): per-tool timeouts,
147
+ and timeouts the model and the caller can tell apart from other failures.
148
+ - [infiniflow/ragflow#23003](https://github.com/infiniflow/ragflow/issues/23003): a tool timeout
149
+ should reach the model as a result, not fail the whole run.
150
+
151
+ The MCP Tasks extension solves this properly for clients and servers that support it. longcall
152
+ is for the many that don't yet.
153
+
154
+ ## License
155
+
156
+ MIT
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "longcall"
7
+ version = "0.1.0"
8
+ description = "Fix MCP tool calls that time out (\"MCP error -32001: Request timed out\", Claude Desktop's 4-minute limit): a stdio proxy for any MCP server that answers slow calls with a job id and lets the model fetch the result later, or cancels them with an error the model can read, with per-tool timeouts"
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", "timeout", "request timed out",
16
+ "-32001", "long-running tools", "background jobs", "async tool calls", "per-tool timeout",
17
+ "tool calling", "claude desktop", "claude code", "cursor", "codex", "llm", "agents",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Developers",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3 :: Only",
25
+ "Topic :: Software Development :: Libraries",
26
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
27
+ ]
28
+ dependencies = []
29
+
30
+ [project.optional-dependencies]
31
+ test = ["pytest>=7", "mcp>=1.10; python_version >= '3.10'"]
32
+
33
+ [project.scripts]
34
+ longcall = "longcall.cli:main"
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/srikrishnaL/kitforge/tree/main/packages/longcall"
38
+ Source = "https://github.com/srikrishnaL/kitforge"
39
+ Issues = "https://github.com/srikrishnaL/kitforge/issues"
40
+ Changelog = "https://github.com/srikrishnaL/kitforge/blob/main/packages/longcall/CHANGELOG.md"
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/longcall"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
@@ -0,0 +1,13 @@
1
+ """Keep slow MCP tool calls from failing on the client's timeout."""
2
+
3
+ from .keeper import RESULT_TOOL, Keeper
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["Keeper", "RESULT_TOOL", "run", "__version__"]
7
+
8
+
9
+ def run(command, **options): # type: ignore[no-untyped-def]
10
+ """Run ``command`` (a stdio MCP server) behind the proxy; see :func:`longcall.proxy.run`."""
11
+ from .proxy import run as _run
12
+
13
+ return _run(command, **options)
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,160 @@
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
+ :meth:`Relay.send_client` and :meth:`Relay.send_server` send a message at any other time
7
+ (from a timer, for example).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import shutil
15
+ import signal
16
+ import subprocess
17
+ import sys
18
+ import threading
19
+ from typing import Any, BinaryIO, Callable, Iterator, List, Optional, Tuple
20
+
21
+ # A hook gets one message and returns (message to pass on or None, replies to send back).
22
+ Hook = Callable[[dict], Tuple[Optional[dict], List[dict]]]
23
+
24
+
25
+ def _dump(msg: Any) -> bytes:
26
+ return json.dumps(msg, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n"
27
+
28
+
29
+ def _lines(stream: BinaryIO) -> Iterator[bytes]:
30
+ """Lines from ``stream``, read from its file descriptor when it has one.
31
+
32
+ A thread blocked inside a buffered reader holds the reader's lock, and Python aborts at
33
+ exit if a daemon thread still holds it; ``os.read`` takes no lock.
34
+ """
35
+ try:
36
+ fd = stream.fileno()
37
+ read: Callable[[int], bytes] = lambda n: os.read(fd, n) # noqa: E731
38
+ except (AttributeError, OSError, ValueError):
39
+ read = getattr(stream, "read1", stream.read)
40
+ buf = b""
41
+ while True:
42
+ try:
43
+ chunk = read(65536)
44
+ except (OSError, ValueError):
45
+ break
46
+ if not chunk:
47
+ break
48
+ buf += chunk
49
+ while b"\n" in buf:
50
+ line, buf = buf.split(b"\n", 1)
51
+ yield line + b"\n"
52
+ if buf:
53
+ yield buf
54
+
55
+
56
+ class Relay:
57
+ def __init__(self, command: List[str], *, to_server: Hook, to_client: Hook,
58
+ stdin: Optional[BinaryIO] = None, stdout: Optional[BinaryIO] = None,
59
+ name: str = "proxy") -> None:
60
+ if not command:
61
+ raise ValueError("no server command given")
62
+ exe = shutil.which(command[0]) # finds npx.cmd and friends on Windows
63
+ self.command = [exe or command[0]] + list(command[1:])
64
+ self.name = name
65
+ self.to_server = to_server
66
+ self.to_client = to_client
67
+ self.stdin = stdin or sys.stdin.buffer
68
+ self.stdout = stdout or sys.stdout.buffer
69
+ self._lock = threading.Lock()
70
+ self.proc: Optional[subprocess.Popen] = None
71
+
72
+ def _write(self, stream: BinaryIO, data: bytes) -> None:
73
+ with self._lock:
74
+ try:
75
+ stream.write(data)
76
+ stream.flush()
77
+ except (BrokenPipeError, OSError, ValueError):
78
+ pass
79
+
80
+ def send_client(self, msg: dict) -> None:
81
+ self._write(self.stdout, _dump(msg))
82
+
83
+ def send_server(self, msg: dict) -> None:
84
+ if self.proc is not None and self.proc.stdin is not None:
85
+ self._write(self.proc.stdin, _dump(msg))
86
+
87
+ def _handle(self, line: bytes, hook: Hook, forward: BinaryIO, back: BinaryIO) -> None:
88
+ line = line if line.endswith(b"\n") else line + b"\n"
89
+ try:
90
+ msg = json.loads(line)
91
+ except ValueError:
92
+ self._write(forward, line)
93
+ return
94
+ batch = isinstance(msg, list)
95
+ out: List[Any] = []
96
+ replies: List[dict] = []
97
+ changed = False
98
+ for item in (msg if batch else [msg]):
99
+ if not isinstance(item, dict):
100
+ out.append(item)
101
+ continue
102
+ try:
103
+ new, extra = hook(item)
104
+ except Exception as exc: # never break the connection over a rewrite
105
+ print(f"{self.name}: {type(exc).__name__}: {exc}", file=sys.stderr)
106
+ new, extra = item, []
107
+ if new is not item:
108
+ changed = True
109
+ if new is not None:
110
+ out.append(new)
111
+ replies += extra
112
+ if out:
113
+ self._write(forward, _dump(out if batch else out[0]) if changed else line)
114
+ for reply in replies:
115
+ self._write(back, _dump(reply))
116
+
117
+ def _pump_server(self) -> None:
118
+ assert self.proc and self.proc.stdout and self.proc.stdin
119
+ for line in _lines(self.proc.stdout):
120
+ if line.strip():
121
+ self._handle(line, self.to_client, self.stdout, self.proc.stdin)
122
+
123
+ def _pump_client(self) -> None:
124
+ assert self.proc and self.proc.stdin
125
+ for line in _lines(self.stdin):
126
+ if line.strip():
127
+ self._handle(line, self.to_server, self.proc.stdin, self.stdout)
128
+ try:
129
+ self.proc.stdin.close()
130
+ except OSError:
131
+ pass
132
+
133
+ def run(self) -> int:
134
+ try:
135
+ self.proc = subprocess.Popen(self.command, stdin=subprocess.PIPE,
136
+ stdout=subprocess.PIPE, bufsize=0)
137
+ except OSError as exc:
138
+ print(f"{self.name}: can't start {self.command[0]}: {exc}", file=sys.stderr)
139
+ return 127
140
+ pump = threading.Thread(target=self._pump_server, daemon=True)
141
+ pump.start()
142
+ threading.Thread(target=self._pump_client, daemon=True).start()
143
+
144
+ previous = None
145
+ if hasattr(signal, "SIGTERM") and threading.current_thread() is threading.main_thread():
146
+ def forward(signum, frame): # pass a shutdown request on to the server
147
+ if self.proc and self.proc.poll() is None:
148
+ self.proc.terminate()
149
+ previous = signal.signal(signal.SIGTERM, forward)
150
+ try:
151
+ try:
152
+ code = self.proc.wait()
153
+ except KeyboardInterrupt:
154
+ self.proc.terminate()
155
+ code = self.proc.wait()
156
+ pump.join(timeout=5)
157
+ finally:
158
+ if previous is not None:
159
+ signal.signal(signal.SIGTERM, previous)
160
+ return 128 - code if code < 0 else code