chuk-tool-processor 0.6.13__py3-none-any.whl → 0.9.7__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.

Potentially problematic release.


This version of chuk-tool-processor might be problematic. Click here for more details.

Files changed (35) hide show
  1. chuk_tool_processor/core/__init__.py +31 -0
  2. chuk_tool_processor/core/exceptions.py +218 -12
  3. chuk_tool_processor/core/processor.py +38 -7
  4. chuk_tool_processor/execution/strategies/__init__.py +6 -0
  5. chuk_tool_processor/execution/strategies/subprocess_strategy.py +2 -1
  6. chuk_tool_processor/execution/wrappers/__init__.py +42 -0
  7. chuk_tool_processor/execution/wrappers/caching.py +48 -13
  8. chuk_tool_processor/execution/wrappers/circuit_breaker.py +370 -0
  9. chuk_tool_processor/execution/wrappers/rate_limiting.py +31 -1
  10. chuk_tool_processor/execution/wrappers/retry.py +93 -53
  11. chuk_tool_processor/logging/metrics.py +2 -2
  12. chuk_tool_processor/mcp/mcp_tool.py +5 -5
  13. chuk_tool_processor/mcp/setup_mcp_http_streamable.py +44 -2
  14. chuk_tool_processor/mcp/setup_mcp_sse.py +44 -2
  15. chuk_tool_processor/mcp/setup_mcp_stdio.py +2 -0
  16. chuk_tool_processor/mcp/stream_manager.py +130 -75
  17. chuk_tool_processor/mcp/transport/__init__.py +10 -0
  18. chuk_tool_processor/mcp/transport/http_streamable_transport.py +193 -108
  19. chuk_tool_processor/mcp/transport/models.py +100 -0
  20. chuk_tool_processor/mcp/transport/sse_transport.py +155 -59
  21. chuk_tool_processor/mcp/transport/stdio_transport.py +58 -10
  22. chuk_tool_processor/models/__init__.py +20 -0
  23. chuk_tool_processor/models/tool_call.py +34 -1
  24. chuk_tool_processor/models/tool_spec.py +350 -0
  25. chuk_tool_processor/models/validated_tool.py +22 -2
  26. chuk_tool_processor/observability/__init__.py +30 -0
  27. chuk_tool_processor/observability/metrics.py +312 -0
  28. chuk_tool_processor/observability/setup.py +105 -0
  29. chuk_tool_processor/observability/tracing.py +345 -0
  30. chuk_tool_processor/plugins/discovery.py +1 -1
  31. chuk_tool_processor-0.9.7.dist-info/METADATA +1813 -0
  32. {chuk_tool_processor-0.6.13.dist-info → chuk_tool_processor-0.9.7.dist-info}/RECORD +34 -27
  33. chuk_tool_processor-0.6.13.dist-info/METADATA +0 -698
  34. {chuk_tool_processor-0.6.13.dist-info → chuk_tool_processor-0.9.7.dist-info}/WHEEL +0 -0
  35. {chuk_tool_processor-0.6.13.dist-info → chuk_tool_processor-0.9.7.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,345 @@
1
+ """
2
+ OpenTelemetry tracing integration for chuk-tool-processor.
3
+
4
+ Provides drop-in distributed tracing with standardized span names and attributes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from contextlib import contextmanager
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from chuk_tool_processor.logging import get_logger
13
+
14
+ if TYPE_CHECKING:
15
+ from opentelemetry.trace import Span, Tracer # type: ignore[import-not-found]
16
+
17
+ logger = get_logger("chuk_tool_processor.observability.tracing")
18
+
19
+ # Global tracer instance
20
+ _tracer: Tracer | None = None
21
+ _tracing_enabled = False
22
+
23
+
24
+ def init_tracer(service_name: str = "chuk-tool-processor") -> Tracer | NoOpTracer:
25
+ """
26
+ Initialize OpenTelemetry tracer with best-practice configuration.
27
+
28
+ Args:
29
+ service_name: Service name for tracing
30
+
31
+ Returns:
32
+ Configured OpenTelemetry tracer or NoOpTracer if initialization fails
33
+ """
34
+ global _tracer, _tracing_enabled
35
+
36
+ try:
37
+ from opentelemetry import trace # type: ignore[import-not-found]
38
+ from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import ( # type: ignore[import-not-found]
39
+ OTLPSpanExporter,
40
+ )
41
+ from opentelemetry.sdk.resources import Resource # type: ignore[import-not-found]
42
+ from opentelemetry.sdk.trace import TracerProvider # type: ignore[import-not-found]
43
+ from opentelemetry.sdk.trace.export import BatchSpanProcessor # type: ignore[import-not-found]
44
+
45
+ # Create resource with service name
46
+ resource = Resource.create({"service.name": service_name})
47
+
48
+ # Create tracer provider
49
+ provider = TracerProvider(resource=resource)
50
+
51
+ # Add OTLP exporter (exports to OTEL collector)
52
+ otlp_exporter = OTLPSpanExporter()
53
+ provider.add_span_processor(BatchSpanProcessor(otlp_exporter))
54
+
55
+ # Set as global tracer provider
56
+ trace.set_tracer_provider(provider)
57
+
58
+ _tracer = trace.get_tracer(__name__)
59
+ _tracing_enabled = True
60
+
61
+ logger.info(f"OpenTelemetry tracing initialized for service: {service_name}")
62
+ return _tracer
63
+
64
+ except ImportError as e:
65
+ logger.warning(f"OpenTelemetry packages not installed: {e}. Tracing disabled.")
66
+ _tracing_enabled = False
67
+ return NoOpTracer()
68
+
69
+
70
+ def get_tracer() -> Tracer | NoOpTracer:
71
+ """
72
+ Get the current tracer instance.
73
+
74
+ Returns:
75
+ OpenTelemetry tracer or no-op tracer if not initialized
76
+ """
77
+ if _tracer is None:
78
+ return NoOpTracer()
79
+ return _tracer
80
+
81
+
82
+ def is_tracing_enabled() -> bool:
83
+ """Check if tracing is enabled."""
84
+ return _tracing_enabled
85
+
86
+
87
+ @contextmanager
88
+ def trace_tool_execution(
89
+ tool: str,
90
+ namespace: str | None = None,
91
+ attributes: dict[str, Any] | None = None,
92
+ ):
93
+ """
94
+ Context manager for tracing tool execution.
95
+
96
+ Creates a span with name "tool.execute" and standard attributes.
97
+
98
+ Args:
99
+ tool: Tool name
100
+ namespace: Optional tool namespace
101
+ attributes: Additional span attributes
102
+
103
+ Example:
104
+ with trace_tool_execution("calculator", attributes={"operation": "add"}):
105
+ result = await tool.execute(a=5, b=3)
106
+ """
107
+ if not _tracing_enabled or _tracer is None:
108
+ yield None
109
+ return
110
+
111
+ span_name = "tool.execute"
112
+ span_attributes: dict[str, str | int | float | bool] = {
113
+ "tool.name": tool,
114
+ }
115
+
116
+ if namespace:
117
+ span_attributes["tool.namespace"] = namespace
118
+
119
+ if attributes:
120
+ # Flatten attributes with "tool." prefix
121
+ for key, value in attributes.items():
122
+ # Convert value to string for OTEL compatibility
123
+ if isinstance(value, (str, int, float, bool)):
124
+ span_attributes[f"tool.{key}"] = value
125
+ else:
126
+ span_attributes[f"tool.{key}"] = str(value)
127
+
128
+ with _tracer.start_as_current_span(span_name, attributes=span_attributes) as span:
129
+ yield span
130
+
131
+
132
+ @contextmanager
133
+ def trace_cache_operation(
134
+ operation: str,
135
+ tool: str,
136
+ hit: bool | None = None,
137
+ attributes: dict[str, Any] | None = None,
138
+ ):
139
+ """
140
+ Context manager for tracing cache operations.
141
+
142
+ Args:
143
+ operation: Cache operation (lookup, set, invalidate)
144
+ tool: Tool name
145
+ hit: Whether cache hit (for lookup operations)
146
+ attributes: Additional span attributes
147
+
148
+ Example:
149
+ with trace_cache_operation("lookup", "calculator", hit=True):
150
+ result = await cache.get(tool, key)
151
+ """
152
+ if not _tracing_enabled or _tracer is None:
153
+ yield None
154
+ return
155
+
156
+ span_name = f"tool.cache.{operation}"
157
+ span_attributes: dict[str, str | int | float | bool] = {
158
+ "tool.name": tool,
159
+ "cache.operation": operation,
160
+ }
161
+
162
+ if hit is not None:
163
+ span_attributes["cache.hit"] = hit
164
+
165
+ if attributes:
166
+ for key, value in attributes.items():
167
+ if isinstance(value, (str, int, float, bool)):
168
+ span_attributes[f"cache.{key}"] = value
169
+ else:
170
+ span_attributes[f"cache.{key}"] = str(value)
171
+
172
+ with _tracer.start_as_current_span(span_name, attributes=span_attributes) as span:
173
+ yield span
174
+
175
+
176
+ @contextmanager
177
+ def trace_retry_attempt(
178
+ tool: str,
179
+ attempt: int,
180
+ max_retries: int,
181
+ attributes: dict[str, Any] | None = None,
182
+ ):
183
+ """
184
+ Context manager for tracing retry attempts.
185
+
186
+ Args:
187
+ tool: Tool name
188
+ attempt: Current attempt number (0-indexed)
189
+ max_retries: Maximum retry attempts
190
+ attributes: Additional span attributes
191
+
192
+ Example:
193
+ with trace_retry_attempt("api_tool", attempt=1, max_retries=3):
194
+ result = await executor.execute([call])
195
+ """
196
+ if not _tracing_enabled or _tracer is None:
197
+ yield None
198
+ return
199
+
200
+ span_name = "tool.retry.attempt"
201
+ span_attributes: dict[str, str | int | float | bool] = {
202
+ "tool.name": tool,
203
+ "retry.attempt": attempt,
204
+ "retry.max_attempts": max_retries,
205
+ }
206
+
207
+ if attributes:
208
+ for key, value in attributes.items():
209
+ if isinstance(value, (str, int, float, bool)):
210
+ span_attributes[f"retry.{key}"] = value
211
+ else:
212
+ span_attributes[f"retry.{key}"] = str(value)
213
+
214
+ with _tracer.start_as_current_span(span_name, attributes=span_attributes) as span:
215
+ yield span
216
+
217
+
218
+ @contextmanager
219
+ def trace_circuit_breaker(
220
+ tool: str,
221
+ state: str,
222
+ attributes: dict[str, Any] | None = None,
223
+ ):
224
+ """
225
+ Context manager for tracing circuit breaker operations.
226
+
227
+ Args:
228
+ tool: Tool name
229
+ state: Circuit breaker state (CLOSED, OPEN, HALF_OPEN)
230
+ attributes: Additional span attributes
231
+
232
+ Example:
233
+ with trace_circuit_breaker("api_tool", state="OPEN"):
234
+ can_execute = await breaker.can_execute()
235
+ """
236
+ if not _tracing_enabled or _tracer is None:
237
+ yield None
238
+ return
239
+
240
+ span_name = "tool.circuit_breaker.check"
241
+ span_attributes: dict[str, str | int | float | bool] = {
242
+ "tool.name": tool,
243
+ "circuit.state": state,
244
+ }
245
+
246
+ if attributes:
247
+ for key, value in attributes.items():
248
+ if isinstance(value, (str, int, float, bool)):
249
+ span_attributes[f"circuit.{key}"] = value
250
+ else:
251
+ span_attributes[f"circuit.{key}"] = str(value)
252
+
253
+ with _tracer.start_as_current_span(span_name, attributes=span_attributes) as span:
254
+ yield span
255
+
256
+
257
+ @contextmanager
258
+ def trace_rate_limit(
259
+ tool: str,
260
+ allowed: bool,
261
+ attributes: dict[str, Any] | None = None,
262
+ ):
263
+ """
264
+ Context manager for tracing rate limiting.
265
+
266
+ Args:
267
+ tool: Tool name
268
+ allowed: Whether request was allowed
269
+ attributes: Additional span attributes
270
+
271
+ Example:
272
+ with trace_rate_limit("api_tool", allowed=True):
273
+ await rate_limiter.acquire()
274
+ """
275
+ if not _tracing_enabled or _tracer is None:
276
+ yield None
277
+ return
278
+
279
+ span_name = "tool.rate_limit.check"
280
+ span_attributes: dict[str, str | int | float | bool] = {
281
+ "tool.name": tool,
282
+ "rate_limit.allowed": allowed,
283
+ }
284
+
285
+ if attributes:
286
+ for key, value in attributes.items():
287
+ if isinstance(value, (str, int, float, bool)):
288
+ span_attributes[f"rate_limit.{key}"] = value
289
+ else:
290
+ span_attributes[f"rate_limit.{key}"] = str(value)
291
+
292
+ with _tracer.start_as_current_span(span_name, attributes=span_attributes) as span:
293
+ yield span
294
+
295
+
296
+ def add_span_event(span: Span | None, name: str, attributes: dict[str, Any] | None = None) -> None:
297
+ """
298
+ Add an event to the current span.
299
+
300
+ Args:
301
+ span: Span to add event to (can be None)
302
+ name: Event name
303
+ attributes: Event attributes
304
+ """
305
+ if span is None or not _tracing_enabled:
306
+ return
307
+
308
+ try:
309
+ span.add_event(name, attributes=attributes or {})
310
+ except Exception as e:
311
+ logger.debug(f"Error adding span event: {e}")
312
+
313
+
314
+ def set_span_error(span: Span | None, error: Exception | str) -> None:
315
+ """
316
+ Mark span as error and record exception details.
317
+
318
+ Args:
319
+ span: Span to mark as error (can be None)
320
+ error: Error to record
321
+ """
322
+ if span is None or not _tracing_enabled:
323
+ return
324
+
325
+ try:
326
+ from opentelemetry.trace import Status, StatusCode
327
+
328
+ span.set_status(Status(StatusCode.ERROR, str(error)))
329
+
330
+ if isinstance(error, Exception):
331
+ span.record_exception(error)
332
+ else:
333
+ span.add_event("error", {"error.message": str(error)})
334
+
335
+ except Exception as e:
336
+ logger.debug(f"Error setting span error: {e}")
337
+
338
+
339
+ class NoOpTracer:
340
+ """No-op tracer when OpenTelemetry is not available."""
341
+
342
+ @contextmanager
343
+ def start_as_current_span(self, _name: str, **_kwargs):
344
+ """No-op span context manager."""
345
+ yield None
@@ -121,7 +121,7 @@ class PluginDiscovery:
121
121
  # ------------------- Parser plugins -------------------------
122
122
  if issubclass(cls, ParserPlugin) and cls is not ParserPlugin:
123
123
  if not inspect.iscoroutinefunction(getattr(cls, "try_parse", None)):
124
- logger.warning("Skipping parser plugin %s: try_parse is not async", cls.__qualname__)
124
+ logger.debug("Skipping parser plugin %s: try_parse is not async", cls.__qualname__)
125
125
  else:
126
126
  try:
127
127
  self._registry.register_plugin("parser", cls.__name__, cls())