python-repl-mcp 0.2.5__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.
@@ -0,0 +1,549 @@
1
+ """Worker process: one persistent namespace, one cell at a time.
2
+
3
+ The launcher hands us the private request pipe on fd 0 and the reply pipe on
4
+ fd 1. Both are duplicated to non-inheritable descriptors before fd 1/2 are
5
+ redirected to per-cell capture files, so user code and its native children can
6
+ never write into the protocol stream. Windows keeps CRT descriptors and the
7
+ Win32 standard-handle table separate, so both are redirected together.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import ast
13
+ import builtins
14
+ import contextlib
15
+ import ctypes
16
+ import getpass
17
+ import json
18
+ import msvcrt
19
+ import os
20
+ import sys
21
+ import traceback
22
+ from ctypes import wintypes
23
+ from types import CodeType, TracebackType
24
+ from typing import Final
25
+
26
+ from python_repl_mcp.protocol import (
27
+ CAPTURE_BYTES,
28
+ MAX_CAPTURE_CHARS,
29
+ MAX_CONTEXT_CHARS,
30
+ MAX_ERROR_TYPE_CHARS,
31
+ MAX_MESSAGE_CHARS,
32
+ MAX_RESULT_CHARS,
33
+ MAX_RESULT_JSON_CHARS,
34
+ MAX_TRACEBACK_CHARS,
35
+ FrameReader,
36
+ ProtocolError,
37
+ Ready,
38
+ Reply,
39
+ Request,
40
+ WorkerError,
41
+ encode_frame,
42
+ parse_request,
43
+ )
44
+
45
+ _FILENAME: Final = "<cell>"
46
+ _READ_CHUNK: Final = 65_536
47
+ _STD_HANDLE: Final = {0: -10, 1: -11, 2: -12}
48
+
49
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
50
+ _kernel32.SetStdHandle.argtypes = [wintypes.DWORD, wintypes.HANDLE]
51
+ _kernel32.SetStdHandle.restype = wintypes.BOOL
52
+
53
+
54
+ class _WorkerFatal(Exception):
55
+ """Capture redirection is compromised; the worker must not serve again."""
56
+
57
+
58
+ class _Exit(Exception):
59
+ """Raised to leave the worker loop with a specific status."""
60
+
61
+ def __init__(self, status: int) -> None:
62
+ super().__init__(status)
63
+ self.status = status
64
+
65
+
66
+ class _InputRequired(Exception):
67
+ """Raised instead of blocking on a terminal the server does not have."""
68
+
69
+ def __init__(self, kind: str, prompt: object) -> None:
70
+ super().__init__(kind, prompt)
71
+ self.kind = kind
72
+ self.prompt = str(prompt)
73
+
74
+
75
+ def _install_input_guard() -> None:
76
+ def guarded_input(prompt: object = "") -> str:
77
+ raise _InputRequired("input", prompt)
78
+
79
+ def guarded_getpass(prompt: str = "Password: ", stream: object = None, *, echo_char: object = None) -> str:
80
+ raise _InputRequired("getpass", prompt)
81
+
82
+ builtins.input = guarded_input
83
+ getpass.getpass = guarded_getpass
84
+
85
+
86
+ def _sanitize(text: str) -> str:
87
+ """Replace lone surrogates at the source so every frame stays UTF-8 encodable."""
88
+ try:
89
+ text.encode("utf-8")
90
+ except UnicodeEncodeError:
91
+ return "".join("�" if 0xD800 <= ord(char) <= 0xDFFF else char for char in text)
92
+ return text
93
+
94
+
95
+ def _cap(text: str, limit: int) -> str:
96
+ return _sanitize(text)[:limit]
97
+
98
+
99
+ def _safe_type_name(value: object) -> str:
100
+ """Read ``type(value).__name__`` without trusting user-defined lookups."""
101
+ try:
102
+ name = type.__getattribute__(type(value), "__name__")
103
+ except BaseException:
104
+ return "object"
105
+ return _cap(name, MAX_ERROR_TYPE_CHARS) if isinstance(name, str) else "object"
106
+
107
+
108
+ def _exception_name(exc_type: type[BaseException]) -> str:
109
+ try:
110
+ name = type.__getattribute__(exc_type, "__name__")
111
+ except BaseException:
112
+ return "Exception"
113
+ return _cap(name, MAX_ERROR_TYPE_CHARS) if isinstance(name, str) else "Exception"
114
+
115
+
116
+ def _safe_repr_meta(value: object) -> tuple[str, bool]:
117
+ try:
118
+ text = _sanitize(repr(value))
119
+ except BaseException: # a failing repr must not crash the worker
120
+ return _cap(f"<unrepresentable {_safe_type_name(value)}>", MAX_RESULT_CHARS), False
121
+ truncated = len(text) > MAX_RESULT_CHARS
122
+ return text[:MAX_RESULT_CHARS], truncated
123
+
124
+
125
+ def _json_value(value: object) -> str | None:
126
+ """JSON text for a JSON-serialisable display value, or None."""
127
+ try:
128
+ encoded = json.dumps(value, ensure_ascii=True, allow_nan=False)
129
+ except BaseException:
130
+ return None
131
+ return encoded if len(encoded) <= MAX_RESULT_JSON_CHARS else None
132
+
133
+
134
+ def _attribute(exc: BaseException, name: str) -> object:
135
+ try:
136
+ return getattr(exc, name)
137
+ except BaseException:
138
+ return None
139
+
140
+
141
+ def _position(value: object) -> int | None:
142
+ # ``bool`` is an ``int`` subclass, but the strict wire model rejects it.
143
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
144
+
145
+
146
+ def _format_error(
147
+ exc_type: type[BaseException],
148
+ exc: BaseException,
149
+ tb: TracebackType | None,
150
+ ) -> WorkerError:
151
+ name = _exception_name(exc_type)
152
+ try:
153
+ message = str(exc) or name
154
+ except BaseException:
155
+ message = name
156
+ try:
157
+ rendered = "".join(traceback.format_exception(exc_type, exc, tb))
158
+ except BaseException:
159
+ rendered = f"{name}: {message}"
160
+ context = _attribute(exc, "text")
161
+ return WorkerError(
162
+ type=name,
163
+ message=_cap(message, MAX_MESSAGE_CHARS),
164
+ traceback=_cap(rendered, MAX_TRACEBACK_CHARS),
165
+ line=_position(_attribute(exc, "lineno")),
166
+ offset=_position(_attribute(exc, "offset")),
167
+ context=_cap(context.strip(), MAX_CONTEXT_CHARS) if isinstance(context, str) else None,
168
+ )
169
+
170
+
171
+ class _Namespace(dict[str, object]):
172
+ """Persistent globals that resolve the capture helper without storing it."""
173
+
174
+ def __init__(self, initial: dict[str, object]) -> None:
175
+ super().__init__(initial)
176
+ self._capture_name: str | None = None
177
+ self._capture: list[object] | None = None
178
+
179
+ def begin_capture(self, name: str, capture: list[object]) -> None:
180
+ self._capture_name = name
181
+ self._capture = capture
182
+
183
+ def end_capture(self) -> None:
184
+ self._capture_name = None
185
+ self._capture = None
186
+
187
+ def __missing__(self, key: str) -> object:
188
+ if self._capture is not None and key == self._capture_name:
189
+ return self._capture.append
190
+ raise KeyError(key)
191
+
192
+
193
+ def _is_lone_docstring(tree: ast.Module) -> bool:
194
+ if len(tree.body) != 1:
195
+ return False
196
+ statement = tree.body[0]
197
+ return (
198
+ isinstance(statement, ast.Expr)
199
+ and isinstance(statement.value, ast.Constant)
200
+ and isinstance(statement.value.value, str)
201
+ )
202
+
203
+
204
+ def _bound_names(tree: ast.AST) -> set[str]:
205
+ """Every name the cell could bind, so the capture helper stays fresh."""
206
+ names: set[str] = set()
207
+ for node in ast.walk(tree):
208
+ match node:
209
+ case ast.Name(id=name):
210
+ names.add(name)
211
+ case ast.arg(arg=name):
212
+ names.add(name)
213
+ case ast.alias(name=name, asname=asname):
214
+ names.add(asname or name.split(".")[0])
215
+ case ast.FunctionDef(name=name) | ast.AsyncFunctionDef(name=name) | ast.ClassDef(name=name):
216
+ names.add(name)
217
+ case ast.ExceptHandler(name=name) if name is not None:
218
+ names.add(name)
219
+ case ast.MatchAs(name=name) if name is not None:
220
+ names.add(name)
221
+ case ast.MatchStar(name=name) if name is not None:
222
+ names.add(name)
223
+ case ast.MatchMapping(rest=name) if name is not None:
224
+ names.add(name)
225
+ case _:
226
+ pass
227
+ return names
228
+
229
+
230
+ def _fresh_name(namespace: dict[str, object], bound: set[str]) -> str:
231
+ while True:
232
+ candidate = f"_repl_capture_{os.urandom(8).hex()}"
233
+ if candidate not in namespace and candidate not in bound:
234
+ return candidate
235
+
236
+
237
+ def _compile_cell(
238
+ code: str,
239
+ namespace: _Namespace,
240
+ filename: str,
241
+ *,
242
+ file_mode: bool,
243
+ ) -> tuple[CodeType, list[object] | None]:
244
+ """Compile the cell once; capture the tail with a temporary helper, not a binding.
245
+
246
+ The expression value is appended to a private list, so no display value is
247
+ ever stored under a user-visible name and no predicate can collide with it.
248
+ """
249
+ tree = ast.parse(code, filename=filename, mode="exec")
250
+ capture: list[object] | None = None
251
+ helper: str | None = None
252
+ if not file_mode and tree.body and isinstance(tree.body[-1], ast.Expr) and not _is_lone_docstring(tree):
253
+ capture = []
254
+ helper = _fresh_name(namespace, _bound_names(tree))
255
+ last = tree.body[-1]
256
+ call = ast.Expr(
257
+ value=ast.Call(
258
+ func=ast.Name(id=helper, ctx=ast.Load()),
259
+ args=[last.value],
260
+ keywords=[],
261
+ )
262
+ )
263
+ ast.copy_location(call, last)
264
+ tree.body[-1] = call
265
+ ast.fix_missing_locations(tree)
266
+ namespace.begin_capture(helper, capture)
267
+ try:
268
+ compiled = compile(tree, filename, "exec", dont_inherit=True)
269
+ except BaseException:
270
+ namespace.end_capture()
271
+ raise
272
+ return compiled, capture
273
+
274
+
275
+ _MISSING: Final = object()
276
+
277
+
278
+ def _run_cell(
279
+ code: str,
280
+ namespace: _Namespace,
281
+ *,
282
+ filename: str = _FILENAME,
283
+ argv: list[str] | None = None,
284
+ file_mode: bool = False,
285
+ ) -> tuple[str | None, WorkerError | None, str | None, bool, str | None]:
286
+ try:
287
+ compiled, capture = _compile_cell(code, namespace, filename, file_mode=file_mode)
288
+ except (SyntaxError, ValueError, RecursionError, MemoryError) as exc:
289
+ return None, _format_error(type(exc), exc, None), None, False, None
290
+
291
+ saved_file = namespace.get("__file__", _MISSING)
292
+ saved_name = namespace.get("__name__", _MISSING)
293
+ saved_argv = sys.argv
294
+ if file_mode:
295
+ namespace["__file__"] = filename
296
+ namespace["__name__"] = "__main__"
297
+ sys.argv = list(argv) if argv is not None else [filename]
298
+ try:
299
+ # Executing a submitted cell or file is the product, not an injection boundary.
300
+ exec(compiled, namespace) # nosec B102
301
+ except _InputRequired as exc:
302
+ prompt = _cap(exc.prompt, 500)
303
+ if exc.kind == "getpass":
304
+ guidance = (
305
+ "Use an approved local mechanism (an environment variable or a local "
306
+ "file) and keep the secret out of chat, Python cells and tool arguments."
307
+ )
308
+ else:
309
+ guidance = (
310
+ "Ask the user in chat only for non-secret input and re-run with the value "
311
+ "as an argument or literal. For secrets use an approved local mechanism."
312
+ )
313
+ message = _cap(f"{exc.kind}() requested {prompt!r}; this server has no TTY. {guidance}", MAX_MESSAGE_CHARS)
314
+ return None, WorkerError(type="InputRequired", message=message), None, False, None
315
+ except BaseException as exc:
316
+ # Drop this helper's own frame so the report starts at the cell/file.
317
+ traceback_obj = exc.__traceback__
318
+ return (
319
+ None,
320
+ _format_error(type(exc), exc, None if traceback_obj is None else traceback_obj.tb_next),
321
+ None,
322
+ False,
323
+ None,
324
+ )
325
+ finally:
326
+ namespace.end_capture()
327
+ if file_mode:
328
+ sys.argv = saved_argv
329
+ if saved_file is _MISSING:
330
+ namespace.pop("__file__", None)
331
+ else:
332
+ namespace["__file__"] = saved_file
333
+ if saved_name is _MISSING:
334
+ namespace.pop("__name__", None)
335
+ else:
336
+ namespace["__name__"] = saved_name
337
+ if capture is None or not capture:
338
+ return None, None, None, False, None
339
+ value = capture[0]
340
+ if value is None:
341
+ # A displayed None is not the same as a cell with no display value.
342
+ return None, None, "NoneType", False, "null"
343
+ text, truncated = _safe_repr_meta(value)
344
+ return text, None, _safe_type_name(value), truncated, _json_value(value)
345
+
346
+
347
+ def _flush_streams() -> bool:
348
+ """Best-effort user-level flush; a broken wrapper is not fatal."""
349
+ ok = True
350
+ for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
351
+ if stream is not None:
352
+ try:
353
+ stream.flush()
354
+ except BaseException:
355
+ ok = False
356
+ return ok
357
+
358
+
359
+ def _standard_handle(fd: int) -> int:
360
+ handle = msvcrt.get_osfhandle(fd)
361
+ if handle == -1:
362
+ raise OSError("descriptor has no OS handle")
363
+ return handle
364
+
365
+
366
+ def _set_std_handle(which: int, handle: int) -> None:
367
+ if not _kernel32.SetStdHandle(which & 0xFFFFFFFF, wintypes.HANDLE(handle)):
368
+ raise OSError(ctypes.get_last_error(), "SetStdHandle failed")
369
+
370
+
371
+ def _redirect(fd: int, which: int) -> None:
372
+ """Point CRT descriptor and Win32 standard handle at the same inheritable file."""
373
+ os.set_inheritable(fd, True)
374
+ os.dup2(fd, which)
375
+ _set_std_handle(_STD_HANDLE[which], _standard_handle(which))
376
+
377
+
378
+ def _restore(devnull: int) -> bool:
379
+ """Restore both descriptor tables; report whether user streams flushed."""
380
+ flushed = _flush_streams()
381
+ _redirect(devnull, 1)
382
+ _redirect(devnull, 2)
383
+ return flushed
384
+
385
+
386
+ def _open_capture(path: str) -> int:
387
+ return os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_BINARY, 0o600)
388
+
389
+
390
+ def _snapshot(path: str) -> tuple[str, bool, bool]:
391
+ """Bounded, sanitised snapshot; third value says whether the file was readable."""
392
+ try:
393
+ with open(path, "rb") as handle:
394
+ data = handle.read(CAPTURE_BYTES + 1)
395
+ except OSError:
396
+ return "", False, False
397
+ truncated = len(data) > CAPTURE_BYTES
398
+ if truncated:
399
+ data = data[:CAPTURE_BYTES]
400
+ text = data.decode("utf-8", "replace")
401
+ if len(text) > MAX_CAPTURE_CHARS:
402
+ return text[:MAX_CAPTURE_CHARS], True, True
403
+ return text, truncated, True
404
+
405
+
406
+ def _execute(request: Request, namespace: _Namespace, devnull: int) -> Reply:
407
+ out_fd = err_fd = None
408
+ try:
409
+ out_fd = _open_capture(request.stdout)
410
+ err_fd = _open_capture(request.stderr)
411
+ except OSError:
412
+ for descriptor in (out_fd, err_fd):
413
+ if descriptor is not None:
414
+ os.close(descriptor)
415
+ return Reply(
416
+ id=request.id,
417
+ ok=False,
418
+ capture_complete=False,
419
+ error=WorkerError(
420
+ type="CaptureError",
421
+ message="the worker could not create its capture files",
422
+ ),
423
+ )
424
+ try:
425
+ try:
426
+ _redirect(out_fd, 1)
427
+ _redirect(err_fd, 2)
428
+ except BaseException as exc:
429
+ with contextlib.suppress(BaseException):
430
+ _restore(devnull)
431
+ raise _WorkerFatal("capture redirection failed") from exc
432
+ flushed = True
433
+ try:
434
+ result, error, result_type, result_truncated, result_json = _run_cell(
435
+ request.code,
436
+ namespace,
437
+ filename=request.filename,
438
+ argv=request.argv if request.mode == "file" else None,
439
+ file_mode=request.mode == "file",
440
+ )
441
+ finally:
442
+ try:
443
+ # A Python-level flush failure loses the trailing user output but
444
+ # never the descriptors or the namespace.
445
+ flushed = _restore(devnull)
446
+ except BaseException as exc:
447
+ raise _WorkerFatal("capture redirection could not be restored") from exc
448
+ finally:
449
+ os.close(out_fd)
450
+ os.close(err_fd)
451
+ stdout, stdout_cut, stdout_ok = _snapshot(request.stdout)
452
+ stderr, stderr_cut, stderr_ok = _snapshot(request.stderr)
453
+ truncated = stdout_cut or stderr_cut
454
+ capture_complete = stdout_ok and stderr_ok and flushed
455
+ if error is not None:
456
+ return Reply(
457
+ id=request.id,
458
+ ok=False,
459
+ result=None,
460
+ result_type=None,
461
+ result_truncated=False,
462
+ result_json=None,
463
+ stdout=stdout,
464
+ stderr=stderr,
465
+ truncated=truncated,
466
+ capture_complete=capture_complete,
467
+ error=error,
468
+ )
469
+ return Reply(
470
+ id=request.id,
471
+ ok=True,
472
+ result=result,
473
+ result_type=result_type,
474
+ result_truncated=result_truncated,
475
+ result_json=result_json,
476
+ stdout=stdout,
477
+ stderr=stderr,
478
+ truncated=truncated,
479
+ capture_complete=capture_complete,
480
+ )
481
+
482
+
483
+ def _encode_reply(reply: Reply) -> bytes:
484
+ try:
485
+ return encode_frame(reply)
486
+ except Exception: # nosec B110 - the fallback envelope is fixed ASCII
487
+ fallback = Reply(
488
+ id=reply.id,
489
+ ok=False,
490
+ capture_complete=False,
491
+ error=WorkerError(type="InternalError", message="the worker could not encode its reply"),
492
+ )
493
+ return encode_frame(fallback)
494
+
495
+
496
+ def _write_all(fd: int, data: bytes) -> None:
497
+ view = memoryview(data)
498
+ while view:
499
+ written = os.write(fd, view)
500
+ if written <= 0:
501
+ raise _Exit(3)
502
+ view = view[written:]
503
+
504
+
505
+ def main() -> int:
506
+ control_in = os.dup(0)
507
+ control_out = os.dup(1)
508
+ os.set_inheritable(control_in, False)
509
+ os.set_inheritable(control_out, False)
510
+ devnull = os.open(os.devnull, os.O_RDWR)
511
+ for which in (0, 1, 2):
512
+ _redirect(devnull, which)
513
+
514
+ _install_input_guard()
515
+ namespace = _Namespace({"__name__": "__main__", "__builtins__": builtins})
516
+ reader = FrameReader()
517
+ try:
518
+ _write_all(control_out, encode_frame(Ready(type="ready")))
519
+ while True:
520
+ chunk = os.read(control_in, _READ_CHUNK)
521
+ if not chunk:
522
+ return 0
523
+ try:
524
+ frames = reader.feed(chunk)
525
+ requests = [parse_request(frame) for frame in frames]
526
+ except ProtocolError:
527
+ return 2
528
+ for request in requests:
529
+ try:
530
+ reply = _execute(request, namespace, devnull)
531
+ except _WorkerFatal:
532
+ return 3
533
+ except BaseException:
534
+ reply = Reply(
535
+ id=request.id,
536
+ ok=False,
537
+ capture_complete=False,
538
+ error=WorkerError(
539
+ type="InternalError",
540
+ message="the worker could not format its reply",
541
+ ),
542
+ )
543
+ _write_all(control_out, _encode_reply(reply))
544
+ except _Exit as exit_request:
545
+ return exit_request.status
546
+
547
+
548
+ if __name__ == "__main__":
549
+ sys.exit(main())