|
10 | 10 | from opentelemetry import context, propagate
|
11 | 11 | from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
|
12 | 12 | from opentelemetry.instrumentation.utils import unwrap
|
13 |
| -from opentelemetry.trace import get_tracer |
| 13 | +from opentelemetry.trace import get_tracer, Tracer |
14 | 14 | from wrapt import ObjectProxy, register_post_import_hook, wrap_function_wrapper
|
15 | 15 | from opentelemetry.trace.status import Status, StatusCode
|
16 | 16 | from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
17 |
| -from opentelemetry.trace.propagation import set_span_in_context |
18 | 17 | from opentelemetry.semconv_ai import SpanAttributes
|
19 | 18 | from opentelemetry.semconv.attributes.error_attributes import ERROR_TYPE
|
20 | 19 |
|
@@ -159,38 +158,30 @@ def traced_method(
|
159 | 158 |
|
160 | 159 | return traced_method
|
161 | 160 |
|
162 |
| - def patch_mcp_client(self, tracer): |
| 161 | + def patch_mcp_client(self, tracer: Tracer): |
163 | 162 | @dont_throw
|
164 | 163 | async def traced_method(wrapped, instance, args, kwargs):
|
165 |
| - import mcp.types |
166 |
| - |
167 |
| - if len(args) < 1: |
168 |
| - return |
169 | 164 | meta = None
|
170 | 165 | method = None
|
171 | 166 | params = None
|
172 |
| - if hasattr(args[0].root, "method"): |
| 167 | + if len(args) > 0 and hasattr(args[0].root, "method"): |
173 | 168 | method = args[0].root.method
|
174 |
| - if hasattr(args[0].root, "params"): |
| 169 | + if len(args) > 0 and hasattr(args[0].root, "params"): |
175 | 170 | params = args[0].root.params
|
176 |
| - if params is None: |
177 |
| - args[0].root.params = mcp.types.RequestParams() |
178 |
| - meta = mcp.types.RequestParams.Meta() |
179 |
| - else: |
| 171 | + if params: |
180 | 172 | if hasattr(args[0].root.params, "meta"):
|
181 | 173 | meta = args[0].root.params.meta
|
182 |
| - if meta is None: |
183 |
| - meta = mcp.types.RequestParams.Meta() |
184 | 174 |
|
185 | 175 | with tracer.start_as_current_span(f"{method}.mcp") as span:
|
186 | 176 | span.set_attribute(
|
187 | 177 | SpanAttributes.TRACELOOP_ENTITY_INPUT, f"{serialize(args[0])}"
|
188 | 178 | )
|
189 |
| - ctx = set_span_in_context(span) |
190 |
| - parent_span = {} |
191 |
| - TraceContextTextMapPropagator().inject(parent_span, ctx) |
192 |
| - meta.traceparent = parent_span["traceparent"] |
193 |
| - args[0].root.params.meta = meta |
| 179 | + |
| 180 | + if meta and len(args) > 0: |
| 181 | + carrier = {} |
| 182 | + TraceContextTextMapPropagator().inject(carrier) |
| 183 | + meta.traceparent = carrier["traceparent"] |
| 184 | + args[0].root.params.meta = meta |
194 | 185 | try:
|
195 | 186 | result = await wrapped(*args, **kwargs)
|
196 | 187 | span.set_attribute(
|
|
0 commit comments