longcall 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
longcall/__init__.py ADDED
@@ -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)
longcall/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
longcall/_relay.py ADDED
@@ -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
longcall/cli.py ADDED
@@ -0,0 +1,105 @@
1
+ """longcall: keep slow MCP tool calls from failing on the client's timeout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+ from typing import Dict, List, Optional
9
+
10
+ from . import __version__
11
+ from .keeper import RESULT_TOOL
12
+
13
+
14
+ def _seconds(text: str) -> float:
15
+ try:
16
+ value = float(text)
17
+ except ValueError:
18
+ raise argparse.ArgumentTypeError(f"not a number of seconds: {text!r}")
19
+ if value <= 0:
20
+ raise argparse.ArgumentTypeError("must be more than 0 seconds")
21
+ return value
22
+
23
+
24
+ def _tools(specs: List[str], parser: argparse.ArgumentParser) -> Dict[str, Optional[float]]:
25
+ out: Dict[str, Optional[float]] = {}
26
+ for spec in specs:
27
+ name, sep, value = spec.rpartition("=")
28
+ if not sep or not name:
29
+ parser.error(f"--tool wants NAME=SECONDS or NAME=off, got {spec!r}")
30
+ if value.strip().lower() == "off":
31
+ out[name] = None
32
+ continue
33
+ try:
34
+ out[name] = _seconds(value)
35
+ except argparse.ArgumentTypeError as exc:
36
+ parser.error(f"--tool {spec}: {exc}")
37
+ return out
38
+
39
+
40
+ def main(argv: Optional[List[str]] = None) -> int:
41
+ argv = list(sys.argv[1:] if argv is None else argv)
42
+ command: List[str] = []
43
+ if "--" in argv:
44
+ at = argv.index("--")
45
+ argv, command = argv[:at], argv[at + 1:]
46
+ parser = argparse.ArgumentParser(
47
+ prog="longcall",
48
+ description="Keep slow MCP tool calls from failing on the client's timeout "
49
+ "(\"MCP error -32001: Request timed out\", \"No result received ... after "
50
+ "waiting 4 minutes\").")
51
+ parser.add_argument("--version", action="version", version=f"longcall {__version__}")
52
+ sub = parser.add_subparsers(dest="command", required=True)
53
+ p = sub.add_parser(
54
+ "proxy", help="run a stdio MCP server and answer slow tool calls before the client "
55
+ "gives up",
56
+ description="Start the MCP server given after -- and sit between it and the client. "
57
+ "A tool call still running after --timeout seconds is answered with a job "
58
+ f"id; the model gets the real result later from the {RESULT_TOOL} tool "
59
+ "the proxy adds. With --mode error the call is cancelled and the model "
60
+ "gets an error that names the timeout instead. "
61
+ "Example: longcall proxy --timeout 50 -- npx -y @acme/server")
62
+ p.add_argument("--timeout", type=_seconds, default=50.0, metavar="SECONDS",
63
+ help="answer a call still running after this long (default 50, under the "
64
+ "60-second request timeout of many clients)")
65
+ p.add_argument("--tool", action="append", default=[], metavar="NAME=SECONDS|off",
66
+ help="a different timeout for one tool, or off to pass its calls through "
67
+ "untouched (repeatable)")
68
+ p.add_argument("--mode", choices=("background", "error"), default="background",
69
+ help="background (default): keep the call running and return a job id; "
70
+ "error: cancel it and return an error the model can read")
71
+ p.add_argument("--cancel-after", type=_seconds, metavar="SECONDS",
72
+ help="background mode: cancel a call still running after this long in all "
73
+ "(default: never)")
74
+ p.add_argument("--wait", type=_seconds, metavar="SECONDS",
75
+ help=f"longest time one {RESULT_TOOL} call waits for a result "
76
+ "(default and maximum: --timeout)")
77
+ p.add_argument("--keep", type=int, default=100, metavar="N",
78
+ help="finished results to keep for the model to fetch (default 100)")
79
+ p.add_argument("--result-tool", default=RESULT_TOOL, metavar="NAME",
80
+ help=f"name of the added tool (default {RESULT_TOOL})")
81
+ p.add_argument("--quiet", action="store_true", help="don't report on stderr")
82
+ p.add_argument("--log", metavar="FILE", help="append reports to FILE, not stderr")
83
+ args = parser.parse_args(argv)
84
+
85
+ if not command:
86
+ parser.error("proxy needs the server command after --, e.g. "
87
+ "longcall proxy -- npx -y @acme/server")
88
+ if args.keep < 1:
89
+ parser.error("--keep must be at least 1")
90
+ tools = _tools(args.tool, parser)
91
+ log = None
92
+ if args.log:
93
+ try:
94
+ log = open(os.path.expanduser(args.log), "a", encoding="utf-8", buffering=1)
95
+ except OSError as exc:
96
+ parser.error(f"can't open {args.log}: {exc.strerror}")
97
+ from .proxy import run
98
+
99
+ try:
100
+ return run(command, timeout=args.timeout, tools=tools, mode=args.mode,
101
+ cancel_after=args.cancel_after, wait=args.wait, keep=args.keep,
102
+ result_tool=args.result_tool, quiet=args.quiet, log=log)
103
+ finally:
104
+ if log is not None:
105
+ log.close()
longcall/keeper.py ADDED
@@ -0,0 +1,465 @@
1
+ """The message hooks of ``longcall proxy``: answer slow tool calls before the client gives up.
2
+
3
+ Every ``tools/call`` the client sends gets a deadline (``timeout``, or a per-tool value). The
4
+ call goes on to the server under an id of the proxy's own, so the proxy can answer the client
5
+ itself and still recognise the server's late reply.
6
+
7
+ * If the server answers before the deadline, the client gets that answer, unchanged except for
8
+ its own request id.
9
+ * If the deadline passes first, in ``background`` mode (the default) the client gets a short
10
+ result saying the call is still running, with a job id. The call keeps running on the
11
+ server. The model fetches the real result later with an extra tool (``longcall_result``)
12
+ that the proxy adds to the server's tool list. In ``error`` mode the client instead gets an
13
+ error result that names the timeout, and the server is told to cancel the call.
14
+
15
+ Nothing else changes: every other message passes through as it is.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import secrets
21
+ import sys
22
+ import threading
23
+ import time
24
+ from collections import OrderedDict
25
+ from typing import Any, Callable, Dict, List, Optional, TextIO, Tuple
26
+
27
+ RESULT_TOOL = "longcall_result"
28
+ ID_PREFIX = "longcall-"
29
+ MODES = ("background", "error")
30
+ PROTOCOL_META = "io.modelcontextprotocol/protocolVersion"
31
+ STATELESS_SINCE = "2026-07-28" # revisions from here on want resultType on every result
32
+
33
+ Send = Callable[[dict], None]
34
+
35
+
36
+ def _key(value: Any) -> str:
37
+ return repr(value) # ids may be numbers or strings; 1 and "1" are different requests
38
+
39
+
40
+ def _fmt(seconds: float) -> str:
41
+ return f"{seconds:g}s"
42
+
43
+
44
+ class _Call:
45
+ __slots__ = ("pid", "client_id", "name", "started", "timeout", "state", "job", "outcome",
46
+ "token", "stateless", "timer", "hard_timer", "waiters")
47
+
48
+ def __init__(self, pid: str, client_id: Any, name: str, timeout: float,
49
+ token: Any, stateless: bool) -> None:
50
+ self.pid = pid
51
+ self.client_id = client_id
52
+ self.name = name
53
+ self.started = time.monotonic()
54
+ self.timeout = timeout
55
+ # waiting: the client is still waiting; background: the client got a job id;
56
+ # done: the result is in (kept for longcall_result); dropped: nobody wants it.
57
+ self.state = "waiting"
58
+ self.job: Optional[str] = None
59
+ self.outcome: Optional[dict] = None # the server's response (result or error)
60
+ self.token = token
61
+ self.stateless = stateless
62
+ self.timer: Optional[threading.Timer] = None
63
+ self.hard_timer: Optional[threading.Timer] = None
64
+ self.waiters: List["_Waiter"] = []
65
+
66
+
67
+ class _Waiter:
68
+ __slots__ = ("client_id", "stateless", "timer")
69
+
70
+ def __init__(self, client_id: Any, stateless: bool) -> None:
71
+ self.client_id = client_id
72
+ self.stateless = stateless
73
+ self.timer: Optional[threading.Timer] = None
74
+
75
+
76
+ class Keeper:
77
+ """Keeps slow MCP tool calls from failing on the client's timeout.
78
+
79
+ ``send_client`` and ``send_server`` are used for messages the proxy sends on its own
80
+ (from a timer). :meth:`to_server` and :meth:`to_client` are the relay hooks.
81
+ """
82
+
83
+ def __init__(self, *, timeout: float = 50.0, tools: Optional[Dict[str, Optional[float]]] = None,
84
+ mode: str = "background", cancel_after: Optional[float] = None,
85
+ wait: Optional[float] = None, keep: int = 100, result_tool: str = RESULT_TOOL,
86
+ quiet: bool = False, log: Optional[TextIO] = None,
87
+ send_client: Optional[Send] = None, send_server: Optional[Send] = None) -> None:
88
+ if timeout <= 0:
89
+ raise ValueError("timeout must be more than 0 seconds")
90
+ if mode not in MODES:
91
+ raise ValueError(f"mode must be one of {', '.join(MODES)}")
92
+ if cancel_after is not None and cancel_after <= 0:
93
+ raise ValueError("cancel_after must be more than 0 seconds")
94
+ if keep < 1:
95
+ raise ValueError("keep must be at least 1")
96
+ for name, value in (tools or {}).items():
97
+ if value is not None and value <= 0:
98
+ raise ValueError(f"timeout for {name} must be more than 0 seconds")
99
+ self.timeout = float(timeout)
100
+ self.tools = dict(tools or {})
101
+ self.mode = mode
102
+ self.cancel_after = cancel_after
103
+ # longcall_result waits at most this long, so it never trips the client's timeout either
104
+ self.wait = min(float(wait), self.timeout) if wait is not None else self.timeout
105
+ self.keep = keep
106
+ self.result_tool = result_tool
107
+ self.quiet = quiet
108
+ self.log = log or sys.stderr
109
+ self.send_client: Send = send_client or (lambda msg: None)
110
+ self.send_server: Send = send_server or (lambda msg: None)
111
+
112
+ self.calls: Dict[str, _Call] = {} # by proxy id, until the server answers
113
+ self.by_client: Dict[str, str] = {} # client id -> proxy id, while it waits
114
+ self.jobs: "OrderedDict[str, _Call]" = OrderedDict() # job id -> call
115
+ self.output_schema: Dict[str, bool] = {} # tool name -> declares an outputSchema
116
+ self.waiting_lists: set = set() # client tools/list ids
117
+ self.result_waits: Dict[str, Tuple[_Call, _Waiter]] = {} # client id -> wait
118
+ self.backgrounded = 0
119
+ self.clash = False # the server has a tool with the result tool's name
120
+ self._next = 0
121
+ self._lock = threading.RLock()
122
+
123
+ # -- configuration ------------------------------------------------------------------
124
+
125
+ def timeout_for(self, name: str) -> Optional[float]:
126
+ """The deadline for a tool, or None when its calls are passed through untouched."""
127
+ if name in self.tools:
128
+ return self.tools[name]
129
+ return self.timeout
130
+
131
+ # -- client -> server -----------------------------------------------------------------
132
+
133
+ def to_server(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
134
+ method = msg.get("method")
135
+ if method == "tools/list" and "id" in msg:
136
+ with self._lock:
137
+ self.waiting_lists.add(_key(msg["id"]))
138
+ return msg, []
139
+ if method == "notifications/cancelled":
140
+ return self._client_cancelled(msg)
141
+ if method != "tools/call" or "id" not in msg or not isinstance(msg.get("params"), dict):
142
+ return msg, []
143
+ params = msg["params"]
144
+ name = params.get("name")
145
+ if not isinstance(name, str):
146
+ return msg, []
147
+ stateless = _stateless(params)
148
+ if name == self.result_tool and self.mode == "background" and not self.clash:
149
+ return None, self._result_call(msg["id"], params.get("arguments"), stateless)
150
+ timeout = self.timeout_for(name)
151
+ if timeout is None:
152
+ return msg, []
153
+ meta = params.get("_meta")
154
+ token = meta.get("progressToken") if isinstance(meta, dict) else None
155
+ with self._lock:
156
+ self._next += 1
157
+ pid = f"{ID_PREFIX}{self._next}"
158
+ call = _Call(pid, msg["id"], name, timeout, token, stateless)
159
+ self.calls[pid] = call
160
+ self.by_client[_key(msg["id"])] = pid
161
+ call.timer = self._timer(timeout, self._deadline, pid)
162
+ return dict(msg, id=pid), []
163
+
164
+ def _client_cancelled(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
165
+ params = msg.get("params")
166
+ if not isinstance(params, dict) or "requestId" not in params:
167
+ return msg, []
168
+ key = _key(params["requestId"])
169
+ with self._lock:
170
+ wait = self.result_waits.pop(key, None)
171
+ if wait is not None: # a longcall_result wait: the proxy owns it, the server never saw it
172
+ call, waiter = wait
173
+ _stop(waiter.timer)
174
+ if waiter in call.waiters:
175
+ call.waiters.remove(waiter)
176
+ return None, []
177
+ pid = self.by_client.pop(key, None)
178
+ if pid is None:
179
+ return msg, []
180
+ call = self.calls.get(pid)
181
+ if call is not None and call.state == "waiting":
182
+ call.state = "dropped"
183
+ _stop(call.timer)
184
+ self.calls.pop(pid, None)
185
+ return dict(msg, params=dict(params, requestId=pid)), []
186
+
187
+ # -- server -> client -----------------------------------------------------------------
188
+
189
+ def to_client(self, msg: dict) -> Tuple[Optional[dict], List[dict]]:
190
+ """Returns (message for the client, messages for the server)."""
191
+ if "method" in msg:
192
+ if msg.get("method") == "notifications/progress":
193
+ return self._progress(msg), []
194
+ return msg, []
195
+ if "id" not in msg:
196
+ return msg, []
197
+ msg_id = msg["id"]
198
+ if isinstance(msg_id, str) and msg_id.startswith(ID_PREFIX):
199
+ return self._call_answered(msg), []
200
+ with self._lock:
201
+ key = _key(msg_id)
202
+ if key not in self.waiting_lists:
203
+ return msg, []
204
+ self.waiting_lists.discard(key)
205
+ return self._tool_list(msg), []
206
+
207
+ def _progress(self, msg: dict) -> Optional[dict]:
208
+ params = msg.get("params")
209
+ token = params.get("progressToken") if isinstance(params, dict) else None
210
+ if token is None:
211
+ return msg
212
+ with self._lock:
213
+ for call in self.calls.values():
214
+ if call.token == token and call.state != "waiting":
215
+ return None # the client already has its answer; the token is spent
216
+ return msg
217
+
218
+ def _call_answered(self, msg: dict) -> Optional[dict]:
219
+ with self._lock:
220
+ call = self.calls.pop(msg["id"], None)
221
+ if call is None:
222
+ return None
223
+ _stop(call.timer)
224
+ _stop(call.hard_timer)
225
+ self.by_client.pop(_key(call.client_id), None)
226
+ if call.state == "waiting":
227
+ call.state = "done"
228
+ return dict(msg, id=call.client_id)
229
+ if call.state != "background":
230
+ return None
231
+ call.state = "done"
232
+ call.outcome = msg
233
+ took = time.monotonic() - call.started
234
+ self._say(f"{call.name} finished after {_fmt(round(took, 1))} (job {call.job})")
235
+ waiters, call.waiters = call.waiters, []
236
+ for waiter in waiters:
237
+ self._finish_wait(call, waiter)
238
+ return None
239
+
240
+ def _tool_list(self, msg: dict) -> dict:
241
+ result = msg.get("result")
242
+ if not isinstance(result, dict) or not isinstance(result.get("tools"), list):
243
+ return msg
244
+ tools = result["tools"]
245
+ for tool in tools:
246
+ if isinstance(tool, dict) and isinstance(tool.get("name"), str):
247
+ self.output_schema[tool["name"]] = isinstance(tool.get("outputSchema"), dict)
248
+ if self.mode != "background" or result.get("nextCursor"):
249
+ return msg
250
+ if any(isinstance(t, dict) and t.get("name") == self.result_tool for t in tools):
251
+ self.clash = True
252
+ self._say(f"the server already has a tool named {self.result_tool}; slow calls "
253
+ f"can't be fetched later until you pick another name with --result-tool")
254
+ return msg
255
+ return dict(msg, result=dict(result, tools=tools + [self.result_tool_definition()]))
256
+
257
+ # -- deadlines ------------------------------------------------------------------------
258
+
259
+ def _deadline(self, pid: str) -> None:
260
+ with self._lock:
261
+ call = self.calls.get(pid)
262
+ if call is None or call.state != "waiting":
263
+ return
264
+ self.by_client.pop(_key(call.client_id), None)
265
+ if self.mode == "error":
266
+ call.state = "dropped"
267
+ self.calls.pop(pid, None)
268
+ self._say(f"{call.name} timed out after {_fmt(call.timeout)}; cancelled it")
269
+ reply = self._answer(call.client_id, call.stateless, self._text(
270
+ f"The tool {call.name} timed out after {_fmt(call.timeout)} and was "
271
+ f"cancelled. It may have done part of its work. Try again with a smaller "
272
+ f"request, or tell the user it takes too long.", error=True))
273
+ cancel = _cancel(pid, f"timed out after {_fmt(call.timeout)}")
274
+ else:
275
+ call.state = "background"
276
+ call.job = self._new_job(call)
277
+ self.backgrounded += 1
278
+ self._say(f"{call.name} still running after {_fmt(call.timeout)}; "
279
+ f"answered with job {call.job}")
280
+ reply = self._answer(call.client_id, call.stateless, self._text(
281
+ f"The tool {call.name} is still running (over {_fmt(call.timeout)}), so its "
282
+ f"result is not here yet. Get it by calling the tool {self.result_tool} "
283
+ f"with job_id \"{call.job}\". Each call waits up to {_fmt(self.wait)} for "
284
+ f"the result; call it again if the job is still running. Don't start "
285
+ f"{call.name} again for the same request.",
286
+ # A result without structuredContent would fail the client's outputSchema
287
+ # check, so for such tools the placeholder is marked as an error.
288
+ error=self.output_schema.get(call.name, False),
289
+ meta={"job_id": call.job, "status": "running"}))
290
+ cancel = None
291
+ if self.cancel_after is not None:
292
+ left = max(self.cancel_after - (time.monotonic() - call.started), 0.0)
293
+ call.hard_timer = self._timer(left, self._give_up, pid)
294
+ self.send_client(reply)
295
+ if cancel is not None:
296
+ self.send_server(cancel)
297
+
298
+ def _give_up(self, pid: str) -> None:
299
+ with self._lock:
300
+ call = self.calls.pop(pid, None)
301
+ if call is None or call.state != "background":
302
+ return
303
+ call.state = "done"
304
+ text = (f"The tool {call.name} was cancelled after running for "
305
+ f"{_fmt(self.cancel_after or 0)} without a result.")
306
+ call.outcome = {"jsonrpc": "2.0", "id": pid,
307
+ "result": self._text(text, error=True)}
308
+ self._say(f"{call.name} (job {call.job}) cancelled after "
309
+ f"{_fmt(self.cancel_after or 0)}")
310
+ waiters, call.waiters = call.waiters, []
311
+ self.send_server(_cancel(pid, f"no result after {_fmt(self.cancel_after or 0)}"))
312
+ for waiter in waiters:
313
+ self._finish_wait(call, waiter)
314
+
315
+ def _new_job(self, call: _Call) -> str:
316
+ job = f"job-{secrets.token_hex(4)}"
317
+ while job in self.jobs:
318
+ job = f"job-{secrets.token_hex(4)}"
319
+ self.jobs[job] = call
320
+ # forget the oldest finished jobs; running ones are always kept
321
+ finished = [j for j, c in self.jobs.items() if c.state == "done"]
322
+ for old in finished[:max(len(finished) - self.keep, 0)]:
323
+ del self.jobs[old]
324
+ return job
325
+
326
+ # -- longcall_result ------------------------------------------------------------------
327
+
328
+ def result_tool_definition(self) -> dict:
329
+ return {
330
+ "name": self.result_tool,
331
+ "title": "Get a delayed tool result",
332
+ "description": (
333
+ "Get the result of a tool call that was still running when it first answered. "
334
+ "Such an answer says the tool is still running and gives a job_id; pass that "
335
+ f"job_id here. Waits up to {_fmt(self.wait)} (or wait_seconds) for the result. "
336
+ "If the job is still running after that, call this tool again."),
337
+ "inputSchema": {
338
+ "type": "object",
339
+ "properties": {
340
+ "job_id": {"type": "string",
341
+ "description": "The job_id from the 'still running' answer."},
342
+ "wait_seconds": {"type": "number", "minimum": 0,
343
+ "description": f"How long to wait for the result, at most "
344
+ f"{self.wait:g}. 0 checks without waiting."},
345
+ },
346
+ "required": ["job_id"],
347
+ "additionalProperties": False,
348
+ },
349
+ "annotations": {"readOnlyHint": True, "destructiveHint": False,
350
+ "idempotentHint": True, "openWorldHint": False},
351
+ }
352
+
353
+ def _result_call(self, client_id: Any, arguments: Any, stateless: bool) -> List[dict]:
354
+ args = arguments if isinstance(arguments, dict) else {}
355
+ job = args.get("job_id")
356
+ wait = args.get("wait_seconds", self.wait)
357
+ if isinstance(wait, str):
358
+ try:
359
+ wait = float(wait)
360
+ except ValueError:
361
+ wait = self.wait
362
+ if not isinstance(wait, (int, float)) or isinstance(wait, bool):
363
+ wait = self.wait
364
+ wait = min(max(float(wait), 0.0), self.wait)
365
+ with self._lock:
366
+ call = self.jobs.get(job) if isinstance(job, str) else None
367
+ if call is None:
368
+ known = ", ".join(self.jobs) or "none"
369
+ return [self._answer(client_id, stateless, self._text(
370
+ f"No job {job!r}. Jobs this proxy knows: {known}. Results are lost when the "
371
+ f"MCP server restarts, and only the last {self.keep} finished jobs are kept.",
372
+ error=True))]
373
+ if call.state == "done" or wait == 0:
374
+ return [self._job_answer(call, client_id, stateless)]
375
+ waiter = _Waiter(client_id, stateless)
376
+ call.waiters.append(waiter)
377
+ self.result_waits[_key(client_id)] = (call, waiter)
378
+ waiter.timer = self._timer(wait, self._wait_over, call, waiter)
379
+ return []
380
+
381
+ def _wait_over(self, call: _Call, waiter: _Waiter) -> None:
382
+ with self._lock:
383
+ if waiter not in call.waiters:
384
+ return
385
+ call.waiters.remove(waiter)
386
+ self._finish_wait(call, waiter)
387
+
388
+ def _finish_wait(self, call: _Call, waiter: _Waiter) -> None:
389
+ with self._lock:
390
+ _stop(waiter.timer)
391
+ if self.result_waits.pop(_key(waiter.client_id), None) is None:
392
+ return # already answered, or the client cancelled it
393
+ reply = self._job_answer(call, waiter.client_id, waiter.stateless)
394
+ self.send_client(reply)
395
+
396
+ def _job_answer(self, call: _Call, client_id: Any, stateless: bool) -> dict:
397
+ if call.state != "done" or call.outcome is None:
398
+ running = time.monotonic() - call.started
399
+ return self._answer(client_id, stateless, self._text(
400
+ f"Job {call.job} ({call.name}) is still running ({_fmt(round(running))} so "
401
+ f"far). Call {self.result_tool} again with job_id \"{call.job}\" to keep waiting.",
402
+ meta={"job_id": call.job, "status": "running"}))
403
+ outcome = call.outcome
404
+ if isinstance(outcome.get("result"), dict):
405
+ result = dict(outcome["result"])
406
+ result.pop("resultType", None)
407
+ return self._answer(client_id, stateless, result)
408
+ error = outcome.get("error") if isinstance(outcome.get("error"), dict) else {}
409
+ message = error.get("message") or "unknown error"
410
+ return self._answer(client_id, stateless, self._text(
411
+ f"The tool {call.name} failed: {message} (code {error.get('code')})", error=True))
412
+
413
+ # -- helpers --------------------------------------------------------------------------
414
+
415
+ def _text(self, text: str, *, error: bool = False, meta: Optional[dict] = None) -> dict:
416
+ result: Dict[str, Any] = {"content": [{"type": "text", "text": text}]}
417
+ if error:
418
+ result["isError"] = True
419
+ if meta:
420
+ result["_meta"] = {"longcall": meta}
421
+ return result
422
+
423
+ @staticmethod
424
+ def _answer(client_id: Any, stateless: bool, result: dict) -> dict:
425
+ if stateless:
426
+ result = dict(result, resultType="complete")
427
+ return {"jsonrpc": "2.0", "id": client_id, "result": result}
428
+
429
+ def _timer(self, seconds: float, fn: Callable[..., None], *args: Any) -> threading.Timer:
430
+ timer = threading.Timer(seconds, fn, args)
431
+ timer.daemon = True
432
+ timer.start()
433
+ return timer
434
+
435
+ def _say(self, text: str) -> None:
436
+ if not self.quiet:
437
+ try:
438
+ print(f"longcall: {text}", file=self.log, flush=True)
439
+ except (OSError, ValueError):
440
+ pass
441
+
442
+ def close(self) -> None:
443
+ """Stop every timer (for tests and shutdown)."""
444
+ with self._lock:
445
+ for call in list(self.calls.values()) + list(self.jobs.values()):
446
+ _stop(call.timer)
447
+ _stop(call.hard_timer)
448
+ for waiter in call.waiters:
449
+ _stop(waiter.timer)
450
+
451
+
452
+ def _stateless(params: dict) -> bool:
453
+ meta = params.get("_meta")
454
+ version = meta.get(PROTOCOL_META) if isinstance(meta, dict) else None
455
+ return isinstance(version, str) and version >= STATELESS_SINCE
456
+
457
+
458
+ def _cancel(pid: str, reason: str) -> dict:
459
+ return {"jsonrpc": "2.0", "method": "notifications/cancelled",
460
+ "params": {"requestId": pid, "reason": reason}}
461
+
462
+
463
+ def _stop(timer: Optional[threading.Timer]) -> None:
464
+ if timer is not None:
465
+ timer.cancel()
longcall/proxy.py ADDED
@@ -0,0 +1,27 @@
1
+ """``longcall proxy``: run a stdio MCP server behind a :class:`~longcall.keeper.Keeper`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, BinaryIO, List, Optional
6
+
7
+ from ._relay import Relay
8
+ from .keeper import Keeper
9
+
10
+
11
+ def run(command: List[str], *, stdin: Optional[BinaryIO] = None,
12
+ stdout: Optional[BinaryIO] = None, **options: Any) -> int:
13
+ """Start ``command`` and relay stdio between it and the client until either side ends.
14
+
15
+ ``options`` are :class:`Keeper` arguments (``timeout``, ``tools``, ``mode``,
16
+ ``cancel_after``, ``wait``, ``keep``, ``result_tool``, ``quiet``, ``log``).
17
+ Returns the server's exit code.
18
+ """
19
+ keeper = Keeper(**options)
20
+ relay = Relay(command, to_server=keeper.to_server, to_client=keeper.to_client,
21
+ stdin=stdin, stdout=stdout, name="longcall proxy")
22
+ keeper.send_client = relay.send_client
23
+ keeper.send_server = relay.send_server
24
+ try:
25
+ return relay.run()
26
+ finally:
27
+ keeper.close()
@@ -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,11 @@
1
+ longcall/__init__.py,sha256=IB1gF4uGnB5oX99QcEOIuBX20YMawQihHMGWVgiCbbM,423
2
+ longcall/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ longcall/_relay.py,sha256=QIN-oZEDaovq0BsXMybdpBdnDikE1Biw_lF0BxRG3QI,6024
4
+ longcall/cli.py,sha256=gccg1TSNUZUm1aWHzz2oEHO4CysO1LIe8Wa7MeNqct0,4964
5
+ longcall/keeper.py,sha256=cr6qT1ydjUIlN2vYkqddHglcZrdP_vwwuYV90-8Pck0,21592
6
+ longcall/proxy.py,sha256=R1pO3f37W2tiScMdlhSnghFv6W-gKWfDPjj4-5VFBso,1004
7
+ longcall-0.1.0.dist-info/METADATA,sha256=snbK_8g0rHGwr2dlMEuq2eEYhmYxRocKC3VYbhBIrW4,9277
8
+ longcall-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ longcall-0.1.0.dist-info/entry_points.txt,sha256=PZjKpGIqJW9WMezoohLyakvlio2nvVT3H3pLOzuvRTM,47
10
+ longcall-0.1.0.dist-info/licenses/LICENSE,sha256=fl9U1idgeyJw-8GWneEYxVzZM_C29cBR63IAlNv7KjE,1080
11
+ longcall-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ longcall = longcall.cli:main
@@ -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.