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
@@ -0,0 +1,357 @@
1
+ """Timeouts, retries and per-server circuit breakers around MCP tool calls.
2
+
3
+ An agent that calls tools on Model Context Protocol servers inherits their failure modes:
4
+ a server that hangs holds the whole agent turn, a crashed server is called again on every
5
+ turn, and a blind retry repeats a tool that already wrote something. `mcp_guard` wraps the
6
+ call path without importing any MCP SDK:
7
+
8
+ * a ``call_tool(name, arguments)`` function (sync or ``async def``), or
9
+ * any object with a ``call_tool`` method (an MCP ``ClientSession``, an agent framework's
10
+ MCP server object): you get a proxy whose ``call_tool`` is guarded and whose other
11
+ attributes are the original's.
12
+
13
+ Each call is admitted by the server's `CircuitBreaker` (one per server name, shared by
14
+ every guard for that server), retried only for tools you mark safe to repeat, limited by a
15
+ per-attempt timeout, and stops cooperatively: the current `CancelToken` (an enclosing
16
+ `timeout`, a `RunGuard` that ran out of time or was cancelled) is checked before every
17
+ attempt, and an in-flight ``async`` call is cancelled as soon as the token fires.
18
+
19
+ `python_wrap.doctor` reports a guard without a timeout (PW020) and a guard that retries
20
+ every tool, side effects included (PW021).
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import asyncio
26
+ import fnmatch
27
+ import functools
28
+ import threading
29
+ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
30
+ from typing import Any, cast
31
+
32
+ from python_wrap import _core
33
+ from python_wrap._runtime import seconds as _parse_seconds
34
+ from python_wrap.circuit import CircuitBreaker
35
+ from python_wrap.timeouts import _current_token, checkpoint
36
+
37
+ __all__ = ["MCPGuard", "mcp_breaker", "mcp_guard"]
38
+
39
+ _LAYER_ATTR = "__python_wrap_layer__"
40
+ _BREAKERS: dict[str, CircuitBreaker] = {}
41
+ _BREAKERS_LOCK = threading.Lock()
42
+ _DEFAULT_RETRY_ON: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError)
43
+
44
+
45
+ def mcp_breaker(server: str, **options: Any) -> CircuitBreaker:
46
+ """The shared `CircuitBreaker` of MCP server ``server`` (created on first use).
47
+
48
+ Every `mcp_guard` for the same server name uses this breaker, so one dead server is
49
+ detected once for the whole process. ``options`` (`CircuitBreaker` arguments) apply
50
+ only when the breaker is created.
51
+
52
+ Example:
53
+ >>> mcp_breaker("docs") is mcp_breaker("docs")
54
+ True
55
+ """
56
+ if not server:
57
+ raise ValueError("server must be a non-empty name")
58
+ with _BREAKERS_LOCK:
59
+ found = _BREAKERS.get(server)
60
+ if found is None:
61
+ settings: dict[str, Any] = {"failure_threshold": 5, "recovery_timeout": 30.0}
62
+ settings.update(options)
63
+ settings.setdefault("name", f"mcp:{server}")
64
+ found = _BREAKERS[server] = CircuitBreaker(**settings)
65
+ return found
66
+
67
+
68
+ def _server_name(target: Any, given: str | None) -> str:
69
+ if given:
70
+ return given
71
+ for attr in ("name", "server_name"):
72
+ value = getattr(target, attr, None)
73
+ if isinstance(value, str) and value:
74
+ return value
75
+ owner = getattr(target, "__self__", None)
76
+ if owner is not None:
77
+ return _server_name(owner, None)
78
+ return getattr(target, "__qualname__", type(target).__qualname__)
79
+
80
+
81
+ def _globs(value: Iterable[str] | str | Callable[[str], bool] | None) -> Any:
82
+ if value is None or callable(value):
83
+ return value
84
+ patterns = (value,) if isinstance(value, str) else tuple(value)
85
+ return lambda name: any(fnmatch.fnmatchcase(name, p) for p in patterns)
86
+
87
+
88
+ def _retry_decorator(retry: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]] | None:
89
+ if retry is None or retry is False:
90
+ return None
91
+ if isinstance(retry, bool) or (isinstance(retry, int) and retry < 1):
92
+ raise ValueError("retry must be a positive number of attempts or a retry decorator")
93
+ if isinstance(retry, int):
94
+ from python_wrap.retry import retry as make_retry
95
+
96
+ return cast(
97
+ Callable[[Callable[..., Any]], Callable[..., Any]],
98
+ make_retry(max_attempts=retry, delay=0.2, backoff=2.0, on=_DEFAULT_RETRY_ON),
99
+ )
100
+ if callable(retry):
101
+ return cast(Callable[[Callable[..., Any]], Callable[..., Any]], retry)
102
+ raise TypeError("retry must be None, a number of attempts or a retry decorator")
103
+
104
+
105
+ def _tool_name(args: Sequence[Any], kwargs: Mapping[str, Any]) -> str:
106
+ name = kwargs.get("name", kwargs.get("tool_name", args[0] if args else None))
107
+ return name if isinstance(name, str) else "?"
108
+
109
+
110
+ async def _cancellable(awaitable: Awaitable[Any], label: str) -> Any:
111
+ """Await ``awaitable``; cancel it as soon as the current `CancelToken` fires."""
112
+ token = _current_token.get()
113
+ if token is None:
114
+ return await awaitable
115
+ task = asyncio.ensure_future(awaitable)
116
+ try:
117
+ while True:
118
+ done, _ = await asyncio.wait({task}, timeout=0.02)
119
+ if done:
120
+ return task.result()
121
+ if token.cancelled:
122
+ task.cancel()
123
+ await asyncio.gather(task, return_exceptions=True)
124
+ _core.emit("mcp.cancelled", label)
125
+ token.raise_if_cancelled()
126
+ except BaseException:
127
+ if not task.done():
128
+ task.cancel()
129
+ await asyncio.gather(task, return_exceptions=True)
130
+ raise
131
+
132
+
133
+ class MCPGuard:
134
+ """A guarded MCP client: ``call_tool`` goes through breaker, retry and timeout.
135
+
136
+ Built by `mcp_guard` from an object with a ``call_tool`` method; every other
137
+ attribute (``list_tools``, ``initialize``...) is forwarded unchanged.
138
+
139
+ Attributes:
140
+ server: The server name (its breaker is ``mcp_breaker(server)``).
141
+ breaker: The breaker in use, or None.
142
+ timeout: Per-attempt timeout in seconds, or None.
143
+ wrapped: The original object.
144
+ """
145
+
146
+ def __init__(self, target: Any, call: Callable[..., Any], settings: dict[str, Any]) -> None:
147
+ self.wrapped = target
148
+ self._call = call
149
+ self.server: str = settings["server"]
150
+ self.timeout: float | None = settings["timeout"]
151
+ self.breaker: CircuitBreaker | None = settings.pop("_breaker")
152
+ setattr(self, _LAYER_ATTR, ("mcp_guard", settings))
153
+
154
+ @property
155
+ def call_tool(self) -> Callable[..., Any]:
156
+ """The guarded ``call_tool`` (same signature and sync/async kind as the original)."""
157
+ return self._call
158
+
159
+ def __getattr__(self, name: str) -> Any:
160
+ return getattr(self.wrapped, name)
161
+
162
+ def __repr__(self) -> str:
163
+ return f"MCPGuard(server={self.server!r}, timeout={self.timeout!r})"
164
+
165
+
166
+ def mcp_guard(
167
+ target: Any,
168
+ *,
169
+ timeout: float | str | None = 30.0,
170
+ retry: int | Callable[[Callable[..., Any]], Callable[..., Any]] | None = None,
171
+ retry_tools: Iterable[str] | str | Callable[[str], bool] | None = None,
172
+ breaker: bool | CircuitBreaker | Mapping[str, Any] | None = True,
173
+ server: str | None = None,
174
+ ) -> Any:
175
+ """Guard an MCP tool-call path with a timeout, retries and a per-server breaker.
176
+
177
+ Args:
178
+ target: A ``call_tool(name, arguments=None, ...)`` function (sync or async), or
179
+ an object with such a ``call_tool`` method (then an `MCPGuard` proxy is
180
+ returned).
181
+ timeout: Per-attempt limit in seconds (or ``"30s"``); None disables it, which
182
+ `doctor` reports as PW020.
183
+ retry: Attempts per call (an int, retrying ``ConnectionError``, ``TimeoutError``
184
+ and ``OSError`` with backoff), or a decorator such as
185
+ ``retry(max_attempts=3, on=...)``. None never retries.
186
+ retry_tools: Which tools may be retried: glob patterns or a predicate on the tool
187
+ name. MCP tools can have side effects, so mark only those safe to repeat;
188
+ None retries every tool (PW021).
189
+ breaker: True uses the shared per-server breaker (`mcp_breaker`); a mapping
190
+ creates it with those options on first use; a `CircuitBreaker` is used as
191
+ is; False or None disables it. A tool result with ``isError`` set is a tool
192
+ answer, not a server failure: it is returned and counts as a success.
193
+ server: The server name for the breaker; read from ``target.name`` (or the
194
+ function name) by default.
195
+
196
+ Returns:
197
+ The guarded function, or an `MCPGuard` for an object.
198
+
199
+ Example:
200
+ ```python
201
+ from python_wrap import mcp_guard
202
+
203
+ calls = []
204
+
205
+ def call_tool(name: str, arguments: dict | None = None) -> dict:
206
+ calls.append(name)
207
+ if len(calls) == 1:
208
+ raise ConnectionError("server restarting")
209
+ return {"content": [{"type": "text", "text": "42"}], "isError": False}
210
+
211
+ guarded = mcp_guard(
212
+ call_tool, server="calc", timeout=5, retry=2, retry_tools=["get_*"], breaker=False
213
+ )
214
+ assert guarded("get_answer", {})["content"][0]["text"] == "42"
215
+ assert calls == ["get_answer", "get_answer"]
216
+ ```
217
+ """
218
+ limit = None if timeout is None else _parse_seconds(timeout)
219
+ if limit is not None and limit <= 0:
220
+ raise ValueError("timeout must be positive or None")
221
+ decorate = _retry_decorator(retry)
222
+ may_retry = _globs(retry_tools)
223
+ method = getattr(target, "call_tool", None)
224
+ is_object = callable(method)
225
+ if not is_object and not callable(target):
226
+ raise TypeError("mcp_guard expects a call_tool function or an object with call_tool")
227
+ call = cast(Callable[..., Any], method if is_object else target)
228
+ name = _server_name(target, server)
229
+ chosen: CircuitBreaker | None
230
+ if breaker is True:
231
+ chosen = mcp_breaker(name)
232
+ elif isinstance(breaker, CircuitBreaker):
233
+ chosen = breaker
234
+ elif isinstance(breaker, Mapping):
235
+ chosen = mcp_breaker(name, **dict(breaker))
236
+ elif breaker is None or breaker is False:
237
+ chosen = None
238
+ else:
239
+ raise TypeError("breaker must be True, False, None, a CircuitBreaker or a mapping")
240
+ settings: dict[str, Any] = {
241
+ "server": name,
242
+ "timeout": limit,
243
+ "retried": decorate is not None,
244
+ "retry_tools": retry_tools is not None,
245
+ "breaker": chosen is not None,
246
+ "_breaker": chosen,
247
+ }
248
+ guarded = _build(call, name, limit, decorate, may_retry, chosen)
249
+ if is_object:
250
+ return MCPGuard(target, guarded, settings)
251
+ settings.pop("_breaker")
252
+ setattr(guarded, _LAYER_ATTR, ("mcp_guard", settings))
253
+ return guarded
254
+
255
+
256
+ def _build(
257
+ call: Callable[..., Any],
258
+ server: str,
259
+ limit: float | None,
260
+ decorate: Callable[[Callable[..., Any]], Callable[..., Any]] | None,
261
+ may_retry: Callable[[str], bool] | None,
262
+ breaker: CircuitBreaker | None,
263
+ ) -> Callable[..., Any]:
264
+ from python_wrap.concurrency import timeout as make_timeout
265
+
266
+ is_async = _core.is_async(call)
267
+ label = f"mcp:{server}"
268
+
269
+ if is_async:
270
+
271
+ async def attempt_async(*args: Any, **kwargs: Any) -> Any:
272
+ checkpoint()
273
+ return await _cancellable(call(*args, **kwargs), label)
274
+
275
+ if limit is not None:
276
+ attempt_async = make_timeout(limit)(attempt_async)
277
+ retried_async = decorate(attempt_async) if decorate is not None else attempt_async
278
+
279
+ async def through_async(*args: Any, **kwargs: Any) -> Any:
280
+ tool = _tool_name(args, kwargs)
281
+ runner = (
282
+ retried_async
283
+ if decorate is not None and (may_retry is None or may_retry(tool))
284
+ else attempt_async
285
+ )
286
+ if breaker is None:
287
+ return await runner(*args, **kwargs)
288
+ return await breaker.call(runner, *args, **kwargs)
289
+
290
+ @functools.wraps(call)
291
+ async def guarded_async(*args: Any, **kwargs: Any) -> Any:
292
+ checkpoint()
293
+ return await through_async(*args, **kwargs)
294
+
295
+ return guarded_async
296
+
297
+ def attempt(*args: Any, **kwargs: Any) -> Any:
298
+ checkpoint()
299
+ return call(*args, **kwargs)
300
+
301
+ if limit is not None:
302
+ attempt = make_timeout(limit)(attempt)
303
+ retried = decorate(attempt) if decorate is not None else attempt
304
+
305
+ @functools.wraps(call)
306
+ def guarded(*args: Any, **kwargs: Any) -> Any:
307
+ checkpoint()
308
+ tool = _tool_name(args, kwargs)
309
+ runner = (
310
+ retried if decorate is not None and (may_retry is None or may_retry(tool)) else attempt
311
+ )
312
+ if breaker is None:
313
+ return runner(*args, **kwargs)
314
+ return breaker.call(runner, *args, **kwargs)
315
+
316
+ return guarded
317
+
318
+
319
+ # ----------------------------------------------------------------------------- doctor
320
+
321
+
322
+ def doctor_findings(layers: Sequence[Any]) -> list[Any]:
323
+ """PW020 (MCP/framework tool call without a timeout) and PW021 (blanket MCP retry)."""
324
+ from python_wrap.doctor import Finding
325
+
326
+ found: list[Finding] = []
327
+ for layer in layers:
328
+ settings = layer.settings
329
+ if layer.role in ("mcp_guard", "framework_tool") and settings.get("timeout") is None:
330
+ what = (
331
+ f"MCP server {settings.get('server')!r}"
332
+ if layer.role == "mcp_guard"
333
+ else f"{settings.get('framework')} tool {settings.get('name')!r}"
334
+ )
335
+ found.append(
336
+ Finding(
337
+ "PW020",
338
+ "warning",
339
+ f"{what} is called without a timeout: a hung server or tool holds the "
340
+ "agent turn (and its run budget) forever. Pass timeout= (seconds).",
341
+ )
342
+ )
343
+ if (
344
+ layer.role == "mcp_guard"
345
+ and settings.get("retried")
346
+ and not settings.get("retry_tools")
347
+ ):
348
+ found.append(
349
+ Finding(
350
+ "PW021",
351
+ "warning",
352
+ f"mcp_guard for {settings.get('server')!r} retries every tool: MCP tools "
353
+ "can have side effects, so a retried write may run twice. List the "
354
+ "tools that are safe to repeat with retry_tools=[...].",
355
+ )
356
+ )
357
+ return found
python_wrap/metrics.py CHANGED
@@ -4,12 +4,11 @@ from __future__ import annotations
4
4
 
5
5
  import functools
6
6
  import math
7
- import threading
8
7
  from collections import deque
9
8
  from collections.abc import Callable
10
9
  from typing import Any, Concatenate, ParamSpec, Protocol, TypeVar, cast, overload
11
10
 
12
- from python_wrap import _core
11
+ from python_wrap import _core, _fork
13
12
 
14
13
  __all__ = ["CallStats", "Counted", "count_calls"]
15
14
 
@@ -50,12 +49,16 @@ class CallStats:
50
49
 
51
50
  def __init__(self, window: int) -> None:
52
51
  self._window = window
53
- self._lock = threading.Lock()
52
+ self._lock = _fork.ForkSafeLock()
54
53
  self._durations: deque[float] = deque(maxlen=window)
55
54
  self._calls = 0
56
55
  self._errors = 0
57
56
  self._in_flight = 0
58
57
  self._last = 0.0
58
+ _fork.register(self)
59
+
60
+ def _reset_after_fork(self) -> None:
61
+ self._in_flight = 0
59
62
 
60
63
  def _begin(self) -> None:
61
64
  with self._lock: