python-wrap 0.2.1__py3-none-any.whl → 0.4.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.
Files changed (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/mcp.py ADDED
@@ -0,0 +1,490 @@
1
+ """A dependency-free, read-only Model Context Protocol server: ``python -m python_wrap mcp``.
2
+
3
+ It speaks MCP over stdio (JSON-RPC 2.0, one JSON message per line) and exposes tools a
4
+ coding agent can call while it writes code that uses python-wrap:
5
+
6
+ ======================== ==========================================================
7
+ ``explain_policy`` Layers and findings of a policy or decorated function.
8
+ ``doctor`` The same lint with ``idempotent`` / ``multiprocess`` flags.
9
+ ``migrate_preview`` Dry-run of the tenacity/backoff codemod on source text.
10
+ ``search_api`` Search public names and docstrings.
11
+ ``get_symbol`` Signature, parameters, raises and example of one name.
12
+ ``recipe`` Map a plain-language need to the right API.
13
+ ``guide`` The "how to use python-wrap correctly" guide.
14
+ ======================== ==========================================================
15
+
16
+ Security: the server never writes files, opens sockets or runs subprocesses, and never
17
+ calls the code it inspects. ``import_path`` arguments (``package.module:attribute``) must
18
+ name a module that is already importable in the server's environment; importing it runs
19
+ that module's top-level code, exactly like ``python -m python_wrap doctor``. Start the
20
+ server only in a project you trust, and pass ``--allow PREFIX`` to restrict imports to
21
+ your own packages. Anything printed while importing goes to stderr, never into the
22
+ protocol stream.
23
+
24
+ Example:
25
+ ```python
26
+ from python_wrap.mcp import Server
27
+
28
+ server = Server()
29
+ reply = server.handle({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
30
+ assert reply is not None
31
+ names = [tool["name"] for tool in reply["result"]["tools"]]
32
+ assert "doctor" in names and "get_symbol" in names
33
+ ```
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import argparse
39
+ import contextlib
40
+ import difflib
41
+ import importlib
42
+ import importlib.util
43
+ import json
44
+ import re
45
+ import sys
46
+ from collections.abc import Callable, Mapping, Sequence
47
+ from dataclasses import dataclass
48
+ from typing import IO, Any
49
+
50
+ __all__ = ["PROTOCOL_VERSIONS", "Server", "main"]
51
+
52
+ #: Protocol revisions this server understands, newest first.
53
+ PROTOCOL_VERSIONS: tuple[str, ...] = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
54
+
55
+ PARSE_ERROR = -32700
56
+ INVALID_REQUEST = -32600
57
+ METHOD_NOT_FOUND = -32601
58
+ INVALID_PARAMS = -32602
59
+ INTERNAL_ERROR = -32603
60
+
61
+ _MAX_LINE = 1 << 20 # bytes per message
62
+ _MAX_SOURCE = 1 << 20 # characters for migrate_preview
63
+ _IMPORT_PATH = re.compile(
64
+ r"^(?P<module>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*):(?P<attr>[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)$"
65
+ )
66
+ _INSTRUCTIONS = (
67
+ "Read-only helpers for python-wrap (resilience decorators). Call `guide` once before "
68
+ "writing code, `recipe` or `search_api` to choose an API, `get_symbol` for exact "
69
+ "parameters, and `doctor` on the policy or function you wrote."
70
+ )
71
+
72
+
73
+ class ToolError(Exception):
74
+ """A tool failed in a way the caller should see (reported with ``isError: true``)."""
75
+
76
+
77
+ class _InvalidParams(Exception):
78
+ pass
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class _Tool:
83
+ name: str
84
+ description: str
85
+ properties: Mapping[str, Mapping[str, Any]]
86
+ required: tuple[str, ...]
87
+ handler: Callable[..., Any]
88
+
89
+ def schema(self) -> dict[str, Any]:
90
+ return {
91
+ "name": self.name,
92
+ "description": self.description,
93
+ "inputSchema": {
94
+ "type": "object",
95
+ "properties": dict(self.properties),
96
+ "required": list(self.required),
97
+ "additionalProperties": False,
98
+ },
99
+ "annotations": {
100
+ "readOnlyHint": True,
101
+ "destructiveHint": False,
102
+ "idempotentHint": True,
103
+ "openWorldHint": False,
104
+ },
105
+ }
106
+
107
+
108
+ _TYPES: Mapping[str, tuple[type, ...]] = {
109
+ "string": (str,),
110
+ "boolean": (bool,),
111
+ "integer": (int,),
112
+ }
113
+
114
+
115
+ def _json_safe(value: Any) -> Any:
116
+ if value is None or isinstance(value, (bool, int, float, str)):
117
+ return value
118
+ if isinstance(value, Mapping):
119
+ return {str(key): _json_safe(item) for key, item in value.items()}
120
+ if isinstance(value, (list, tuple)):
121
+ return [_json_safe(item) for item in value]
122
+ from python_wrap.introspect import _render_value
123
+
124
+ return _render_value(value)
125
+
126
+
127
+ class Server:
128
+ """The MCP request handler; `serve` runs it over a pair of byte streams.
129
+
130
+ Args:
131
+ allow: Module prefixes ``import_path`` may name (``"myapp"`` allows ``myapp`` and
132
+ ``myapp.clients``). Empty means any module importable in this environment.
133
+ """
134
+
135
+ def __init__(self, allow: Sequence[str] = ()) -> None:
136
+ self.allow = tuple(prefix.strip(".") for prefix in allow if prefix.strip("."))
137
+ self.initialized = False
138
+ target = {
139
+ "type": "string",
140
+ "description": "package.module:attribute of a Policy or decorated function",
141
+ }
142
+ self._tools = {
143
+ tool.name: tool
144
+ for tool in (
145
+ _Tool(
146
+ "explain_policy",
147
+ "Describe a python-wrap Policy or decorated function: its layers "
148
+ "outermost first with settings, the canonical layer order, and findings.",
149
+ {"import_path": target},
150
+ ("import_path",),
151
+ self._explain_policy,
152
+ ),
153
+ _Tool(
154
+ "doctor",
155
+ "Lint a python-wrap Policy or decorated function (codes PW001-PW019). "
156
+ "Set idempotent=false for payments, emails and other side effects; "
157
+ "multiprocess=true when it runs in several worker processes.",
158
+ {
159
+ "import_path": target,
160
+ "idempotent": {"type": "boolean", "default": True},
161
+ "multiprocess": {"type": "boolean", "default": False},
162
+ },
163
+ ("import_path",),
164
+ self._doctor,
165
+ ),
166
+ _Tool(
167
+ "migrate_preview",
168
+ "Dry-run the python-wrap codemod on Python source text: tenacity/backoff "
169
+ "decorators and hand-rolled LLM retry loops. Returns a unified diff, "
170
+ "notes and suggestions; never writes files.",
171
+ {
172
+ "source": {"type": "string", "description": "Python source code"},
173
+ "filename": {"type": "string", "default": "<source>"},
174
+ },
175
+ ("source",),
176
+ self._migrate_preview,
177
+ ),
178
+ _Tool(
179
+ "search_api",
180
+ "Search python-wrap public names and docstrings.",
181
+ {
182
+ "query": {"type": "string"},
183
+ "limit": {"type": "integer", "default": 10, "minimum": 1},
184
+ },
185
+ ("query",),
186
+ self._search_api,
187
+ ),
188
+ _Tool(
189
+ "get_symbol",
190
+ "Signature, summary, parameters, raises and a minimal example for one "
191
+ "public name, such as 'retry', 'presets.http_client' or "
192
+ "'CircuitBreaker.reset'.",
193
+ {"name": {"type": "string"}},
194
+ ("name",),
195
+ self._get_symbol,
196
+ ),
197
+ _Tool(
198
+ "recipe",
199
+ "Map a plain-language need ('retry http calls', 'stop duplicate "
200
+ "emails') to the python-wrap API, with a runnable snippet and pitfalls.",
201
+ {
202
+ "need": {"type": "string"},
203
+ "limit": {"type": "integer", "default": 3, "minimum": 1},
204
+ },
205
+ ("need",),
206
+ self._recipe,
207
+ ),
208
+ _Tool(
209
+ "guide",
210
+ "How to use python-wrap correctly: layer order, idempotency rules, what "
211
+ "never to retry, common mistakes, doctor usage.",
212
+ {},
213
+ (),
214
+ self._guide,
215
+ ),
216
+ )
217
+ }
218
+
219
+ # ------------------------------------------------------------------ tools
220
+
221
+ def _resolve(self, import_path: str) -> Any:
222
+ match = _IMPORT_PATH.match(import_path.strip())
223
+ if not match:
224
+ raise ToolError(f"expected package.module:attribute, got {import_path!r}")
225
+ module_name, attr = match.group("module"), match.group("attr")
226
+ if any(part.startswith("__") for part in attr.split(".")):
227
+ raise ToolError("dunder attributes are not allowed")
228
+ if self.allow and not any(
229
+ module_name == prefix or module_name.startswith(prefix + ".") for prefix in self.allow
230
+ ):
231
+ raise ToolError(f"module {module_name!r} is outside --allow {list(self.allow)}")
232
+ try:
233
+ spec = importlib.util.find_spec(module_name)
234
+ except (ImportError, ValueError) as exc:
235
+ raise ToolError(f"module {module_name!r} is not importable: {exc}") from None
236
+ if spec is None:
237
+ raise ToolError(f"module {module_name!r} is not importable in this environment")
238
+ try:
239
+ obj: Any = importlib.import_module(module_name)
240
+ except Exception as exc:
241
+ raise ToolError(f"importing {module_name!r} failed: {type(exc).__name__}") from None
242
+ for part in attr.split("."):
243
+ if not hasattr(obj, part):
244
+ raise ToolError(f"{module_name}:{attr} not found ({part!r} missing)")
245
+ obj = getattr(obj, part)
246
+ return obj
247
+
248
+ def _report(self, import_path: str, idempotent: bool, multiprocess: bool) -> dict[str, Any]:
249
+ from python_wrap.doctor import explain
250
+
251
+ target = self._resolve(import_path)
252
+ if not callable(target): # a Policy is callable too
253
+ raise ToolError(f"{import_path} is not a Policy or a decorated function")
254
+ report = explain(target, idempotent=idempotent, multiprocess=multiprocess)
255
+ return {
256
+ "target": report.target,
257
+ "ok": report.ok,
258
+ "layers": [
259
+ {"role": layer.role, "settings": _json_safe(dict(layer.settings))}
260
+ for layer in report.layers
261
+ ],
262
+ "findings": [
263
+ {"code": item.code, "severity": item.severity, "message": item.message}
264
+ for item in report.findings
265
+ ],
266
+ "report": str(report),
267
+ }
268
+
269
+ def _explain_policy(self, import_path: str) -> dict[str, Any]:
270
+ from python_wrap.policy import ROLES
271
+
272
+ data = self._report(import_path, True, False)
273
+ data["canonical_order"] = list(ROLES)
274
+ return data
275
+
276
+ def _doctor(
277
+ self, import_path: str, idempotent: bool = True, multiprocess: bool = False
278
+ ) -> dict[str, Any]:
279
+ return self._report(import_path, idempotent, multiprocess)
280
+
281
+ def _migrate_preview(self, source: str, filename: str = "<source>") -> dict[str, Any]:
282
+ from python_wrap.migrate import migrate_source
283
+
284
+ if len(source) > _MAX_SOURCE:
285
+ raise ToolError(f"source is larger than {_MAX_SOURCE} characters")
286
+ result = migrate_source(source, filename)
287
+ diff = "".join(
288
+ difflib.unified_diff(
289
+ source.splitlines(keepends=True),
290
+ result.text.splitlines(keepends=True),
291
+ f"a/{filename}",
292
+ f"b/{filename}",
293
+ )
294
+ )
295
+ return {
296
+ "changed": result.text != source,
297
+ "diff": diff,
298
+ "changes": [
299
+ {
300
+ "line": item.line,
301
+ "before": item.before,
302
+ "after": item.after,
303
+ "notes": list(item.notes),
304
+ }
305
+ for item in result.changes
306
+ ],
307
+ "unsupported": [
308
+ {"line": item.line, "message": item.message} for item in result.unsupported
309
+ ],
310
+ }
311
+
312
+ def _search_api(self, query: str, limit: int = 10) -> dict[str, Any]:
313
+ from python_wrap.introspect import search
314
+
315
+ found = search(query, limit=min(limit, 50))
316
+ return {"results": [entry.to_dict(full=False) for entry in found]}
317
+
318
+ def _get_symbol(self, name: str) -> dict[str, Any]:
319
+ from python_wrap.introspect import get_symbol, search
320
+
321
+ entry = get_symbol(name)
322
+ if entry is None:
323
+ hints = [item.name for item in search(name, limit=5)]
324
+ raise ToolError(f"unknown symbol {name!r}; closest: {hints}")
325
+ data = entry.to_dict()
326
+ data.pop("doc")
327
+ return data
328
+
329
+ def _recipe(self, need: str, limit: int = 3) -> dict[str, Any]:
330
+ from python_wrap.introspect import find_recipes, search
331
+
332
+ found = find_recipes(need, limit=min(limit, 20))
333
+ related = [] if found else [e.to_dict(full=False) for e in search(need, limit=5)]
334
+ return {"recipes": [item.to_dict() for item in found], "related_apis": related}
335
+
336
+ def _guide(self) -> str:
337
+ from python_wrap.introspect import guide_text
338
+
339
+ return guide_text()
340
+
341
+ # ------------------------------------------------------------------ protocol
342
+
343
+ def _call_tool(self, params: Mapping[str, Any]) -> dict[str, Any]:
344
+ name = params.get("name")
345
+ tool = self._tools.get(name) if isinstance(name, str) else None
346
+ if tool is None:
347
+ raise _InvalidParams(f"Unknown tool: {name!r}")
348
+ arguments = params.get("arguments") or {}
349
+ if not isinstance(arguments, Mapping):
350
+ raise _InvalidParams("arguments must be an object")
351
+ for key, value in arguments.items():
352
+ spec = tool.properties.get(key)
353
+ if spec is None:
354
+ raise _InvalidParams(f"unexpected argument {key!r} for {tool.name}")
355
+ expected = _TYPES[spec["type"]]
356
+ if not isinstance(value, expected) or (
357
+ spec["type"] == "integer" and isinstance(value, bool)
358
+ ):
359
+ raise _InvalidParams(f"argument {key!r} must be a {spec['type']}")
360
+ if spec["type"] == "integer" and value < spec.get("minimum", value):
361
+ raise _InvalidParams(f"argument {key!r} must be >= {spec['minimum']}")
362
+ missing = [key for key in tool.required if key not in arguments]
363
+ if missing:
364
+ raise _InvalidParams(f"missing required argument(s) {missing} for {tool.name}")
365
+ try:
366
+ with contextlib.redirect_stdout(sys.stderr):
367
+ output = tool.handler(**arguments)
368
+ except ToolError as exc:
369
+ return {"content": [{"type": "text", "text": str(exc)}], "isError": True}
370
+ except Exception as exc: # report, never crash the server
371
+ message = f"{tool.name} failed: {type(exc).__name__}: {exc}"
372
+ return {"content": [{"type": "text", "text": message}], "isError": True}
373
+ if isinstance(output, str):
374
+ return {"content": [{"type": "text", "text": output}], "isError": False}
375
+ return {
376
+ "content": [{"type": "text", "text": json.dumps(output, indent=2)}],
377
+ "structuredContent": output,
378
+ "isError": False,
379
+ }
380
+
381
+ def _initialize(self, params: Mapping[str, Any]) -> dict[str, Any]:
382
+ from python_wrap import __version__
383
+
384
+ requested = params.get("protocolVersion")
385
+ version = requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
386
+ return {
387
+ "protocolVersion": version,
388
+ "capabilities": {"tools": {"listChanged": False}},
389
+ "serverInfo": {"name": "python-wrap", "title": "python-wrap", "version": __version__},
390
+ "instructions": _INSTRUCTIONS,
391
+ }
392
+
393
+ def handle(self, message: Any) -> dict[str, Any] | None:
394
+ """Handle one decoded JSON-RPC message; return the response, or None for a notification."""
395
+ if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
396
+ return _error(None, INVALID_REQUEST, "Invalid Request")
397
+ request_id = message.get("id")
398
+ method = message.get("method")
399
+ is_notification = "id" not in message
400
+ if not isinstance(method, str):
401
+ if is_notification or "result" in message or "error" in message:
402
+ return None # a response to a request we never send: ignore it
403
+ return _error(request_id, INVALID_REQUEST, "Invalid Request: missing method")
404
+ if not is_notification and (
405
+ request_id is None
406
+ or isinstance(request_id, bool)
407
+ or not isinstance(request_id, (str, int))
408
+ ):
409
+ return _error(None, INVALID_REQUEST, "Invalid Request: id must be a string or integer")
410
+ params = message.get("params", {})
411
+ if params is None:
412
+ params = {}
413
+ if not isinstance(params, dict):
414
+ if is_notification:
415
+ return None
416
+ return _error(request_id, INVALID_PARAMS, "params must be an object")
417
+ if is_notification:
418
+ if method == "notifications/initialized":
419
+ self.initialized = True
420
+ return None
421
+ try:
422
+ if method == "initialize":
423
+ result: dict[str, Any] = self._initialize(params)
424
+ elif method == "ping":
425
+ result = {}
426
+ elif method == "tools/list":
427
+ result = {"tools": [tool.schema() for tool in self._tools.values()]}
428
+ elif method == "tools/call":
429
+ result = self._call_tool(params)
430
+ else:
431
+ return _error(request_id, METHOD_NOT_FOUND, f"Method not found: {method}")
432
+ except _InvalidParams as exc:
433
+ return _error(request_id, INVALID_PARAMS, str(exc))
434
+ except Exception as exc:
435
+ return _error(request_id, INTERNAL_ERROR, f"Internal error: {type(exc).__name__}")
436
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
437
+
438
+ def serve(self, stdin: IO[bytes], stdout: IO[bytes]) -> None:
439
+ """Read newline-delimited JSON-RPC from ``stdin`` until EOF, answering on ``stdout``."""
440
+ while True:
441
+ line = stdin.readline(_MAX_LINE + 1)
442
+ if not line:
443
+ return
444
+ if len(line) > _MAX_LINE and not line.endswith(b"\n"):
445
+ while True: # discard the rest of the oversized message
446
+ rest = stdin.readline(_MAX_LINE)
447
+ if not rest or rest.endswith(b"\n"):
448
+ break
449
+ reply: dict[str, Any] | None = _error(None, INVALID_REQUEST, "message too large")
450
+ elif not line.strip():
451
+ continue
452
+ else:
453
+ try:
454
+ message = json.loads(line)
455
+ except (ValueError, UnicodeDecodeError):
456
+ reply = _error(None, PARSE_ERROR, "Parse error")
457
+ else:
458
+ if isinstance(message, list):
459
+ reply = _error(None, INVALID_REQUEST, "batches are not supported")
460
+ else:
461
+ reply = self.handle(message)
462
+ if reply is not None:
463
+ stdout.write(json.dumps(reply, separators=(",", ":")).encode("utf-8") + b"\n")
464
+ stdout.flush()
465
+
466
+
467
+ def _error(request_id: Any, code: int, message: str) -> dict[str, Any]:
468
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
469
+
470
+
471
+ def main(argv: Sequence[str] | None = None) -> int:
472
+ """``python -m python_wrap mcp [--allow PREFIX]...``: serve MCP over stdio until EOF."""
473
+ parser = argparse.ArgumentParser(
474
+ prog="python -m python_wrap mcp",
475
+ description="Read-only Model Context Protocol server for python-wrap (stdio).",
476
+ )
477
+ parser.add_argument(
478
+ "--allow",
479
+ action="append",
480
+ default=[],
481
+ metavar="PREFIX",
482
+ help="only import modules under this package (repeatable); default: any importable",
483
+ )
484
+ args = parser.parse_args(argv)
485
+ if "" not in sys.path:
486
+ sys.path.insert(0, "")
487
+ out = sys.stdout.buffer
488
+ with contextlib.redirect_stdout(sys.stderr): # stray prints must not corrupt the stream
489
+ Server(args.allow).serve(sys.stdin.buffer, out)
490
+ return 0