diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 9b3b087f30..8b6ea3ca59 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -19,5 +19,6 @@ "python/instrumentation/openinference-instrumentation-autogen": "0.1.8", "python/instrumentation/openinference-instrumentation-openai-agents": "0.1.8", "python/instrumentation/openinference-instrumentation-portkey": "0.1.0", - "python/instrumentation/openinference-instrumentation-beeai": "0.1.1" + "python/instrumentation/openinference-instrumentation-beeai": "0.1.1", + "python/instrumentation/openinference-instrumentation-mcp": "1.0.0" } \ No newline at end of file diff --git a/python/instrumentation/openinference-instrumentation-mcp/LICENSE b/python/instrumentation/openinference-instrumentation-mcp/LICENSE new file mode 100644 index 0000000000..1525436c1c --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright The OpenInference Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/python/instrumentation/openinference-instrumentation-mcp/README.md b/python/instrumentation/openinference-instrumentation-mcp/README.md new file mode 100644 index 0000000000..f65fde707e --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/README.md @@ -0,0 +1,16 @@ +# OpenInference MCP Instrumentation + +[![pypi](https://badge.fury.io/py/openinference-instrumentation-mcp.svg)](https://pypi.org/project/openinference-instrumentation-mcp/) + +Python auto-instrumentation library for MCP's python SDK. Currently, it only enables context propagation so that the span active +when making an MCP tool call can be connected to those generated when executing it. It does not generate any telemetry. + +## Installation + +```shell +pip install openinference-instrumentation-mcp +``` + +## More Info + +* [More info on OpenInference and Phoenix](https://docs.arize.com/phoenix) diff --git a/python/instrumentation/openinference-instrumentation-mcp/pyproject.toml b/python/instrumentation/openinference-instrumentation-mcp/pyproject.toml new file mode 100644 index 0000000000..f71a24aefe --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/pyproject.toml @@ -0,0 +1,94 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "openinference-instrumentation-mcp" +dynamic = ["version"] +description = "OpenInference MCP Instrumentation" +readme = "README.md" +license = "Apache-2.0" +requires-python = ">=3.10, <3.14" +authors = [ + { name = "OpenInference Authors", email = "oss@arize.com" }, +] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +dependencies = [ + "opentelemetry-api", + "openinference-instrumentation>=0.1.27", + "opentelemetry-instrumentation>=0.49b0", + "wrapt", +] + +[project.optional-dependencies] +instruments = [ + "mcp >= 1.3.0", +] + +[project.entry-points.opentelemetry_instrumentor] +mcp = "openinference.instrumentation.mcp:MCPInstrumentor" + +[project.entry-points.openinference_instrumentor] +mcp = "openinference.instrumentation.mcp:MCPInstrumentor" + +[project.urls] +Homepage = "https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-mcp" + +[tool.hatch.version] +path = "src/openinference/instrumentation/mcp/version.py" + +[tool.hatch.build.targets.sdist] +include = [ + "/src", +] + +[tool.hatch.build.targets.wheel] +packages = ["src/openinference"] + +[tool.pytest.ini_options] +asyncio_mode = "auto" +pythonpath = [ + "src", + ".", +] +testpaths = [ + "tests", +] + +[tool.mypy] +strict = true +explicit_package_bases = true +exclude = [ + "examples", + "dist", + "sdist", +] + +[[tool.mypy.overrides]] +ignore_missing_imports = true +module = [ + "wrapt", +] + +[tool.ruff] +line-length = 100 +target-version = "py38" + +[tool.ruff.lint.per-file-ignores] +"*.ipynb" = ["E402", "E501"] + +[tool.ruff.lint] +select = ["E", "F", "W", "I"] + +[tool.ruff.lint.isort] +force-single-line = false diff --git a/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/__init__.py b/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/__init__.py new file mode 100644 index 0000000000..d103e2039a --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/__init__.py @@ -0,0 +1,69 @@ +from typing import Any, Awaitable, Callable, Collection, TypeVar, cast + +from opentelemetry import context, propagate +from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore +from opentelemetry.instrumentation.utils import unwrap +from wrapt import register_post_import_hook, wrap_function_wrapper + +from openinference.instrumentation.mcp.package import _instruments + +T = TypeVar("T") + + +class MCPInstrumentor(BaseInstrumentor): # type: ignore + """ + An instrumenter for MCP. + """ + + def instrumentation_dependencies(self) -> Collection[str]: + return _instruments + + def _instrument(self, **kwargs: Any) -> None: + register_post_import_hook(self._patch, "mcp") + + def _patch(self, module: Any) -> None: + wrap_function_wrapper( + "mcp.client.session", + "ClientSession.send_request", + self._client_request_wrapper, + ) + wrap_function_wrapper( + "mcp.server.lowlevel.server", + "Server._handle_request", + self._server_request_wrapper, + ) + + def _uninstrument(self, **kwargs: Any) -> None: + unwrap("mcp.client.session.ClientSession", "send_request") + unwrap("mcp.server.lowlevel.server", "_handle_request") + + def _client_request_wrapper( + self, wrapped: Callable[..., T], instance: Any, args: Any, kwargs: Any + ) -> T: + from mcp.types import JSONRPCMessage, Request, RequestParams + + message = cast(JSONRPCMessage, args[0]) + request = cast(Request[RequestParams, Any], message.root) + if not request.params: + request.params = RequestParams() + if not request.params.meta: + request.params.meta = RequestParams.Meta() + propagate.get_global_textmap().inject(request.params.meta.__pydantic_extra__) + return wrapped(*args, **kwargs) + + async def _server_request_wrapper( + self, wrapped: Callable[..., Awaitable[T]], instance: Any, args: Any, kwargs: Any + ) -> T: + from mcp.types import Request, RequestParams + + request = cast(Request[RequestParams, Any], args[1]) + if hasattr(request, "params") and hasattr(request.params, "meta"): + meta = request.params.meta + if meta and hasattr(meta, "__pydantic_extra__"): + ctx = propagate.extract(meta.__pydantic_extra__) + restore = context.attach(ctx) + try: + return await wrapped(*args, **kwargs) + finally: + context.detach(restore) + return await wrapped(*args, **kwargs) diff --git a/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/package.py b/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/package.py new file mode 100644 index 0000000000..0b3ae1af0b --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/package.py @@ -0,0 +1 @@ +_instruments = ("mcp >= 1.3.0",) diff --git a/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/version.py b/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/version.py new file mode 100644 index 0000000000..5becc17c04 --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/src/openinference/instrumentation/mcp/version.py @@ -0,0 +1 @@ +__version__ = "1.0.0" diff --git a/python/instrumentation/openinference-instrumentation-mcp/test-requirements.txt b/python/instrumentation/openinference-instrumentation-mcp/test-requirements.txt new file mode 100644 index 0000000000..890e64accd --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/test-requirements.txt @@ -0,0 +1,9 @@ +mcp==1.3.0 + +httpx +opentelemetry-exporter-otlp-proto-http +opentelemetry-proto +opentelemetry-sdk +respx +starlette +uvicorn diff --git a/python/instrumentation/openinference-instrumentation-mcp/tests/collector.py b/python/instrumentation/openinference-instrumentation-mcp/tests/collector.py new file mode 100644 index 0000000000..aed3e29676 --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/tests/collector.py @@ -0,0 +1,42 @@ +from dataclasses import dataclass, field +from http.server import BaseHTTPRequestHandler, HTTPServer +from urllib.parse import urlparse + +from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest +from opentelemetry.proto.trace.v1.trace_pb2 import ResourceSpans + + +@dataclass +class Telemetry: + traces: list[ResourceSpans] = field(default_factory=list) + + def clear(self) -> None: + self.traces.clear() + + +class OTLPServer(HTTPServer): + def __init__(self, server_address: tuple[str, int], telemetry: Telemetry): + super().__init__(server_address, OTLPHandler, True) + self.telemetry = telemetry + + +class OTLPHandler(BaseHTTPRequestHandler): + server: OTLPServer + + def do_POST(self) -> None: + request_url = urlparse(self.path) + match request_url.path: + case "/v1/traces": + self._handle_traces() + case _: + self.send_response(404) + self.end_headers() + + def _handle_traces(self) -> None: + content_length = int(self.headers["Content-Length"]) + body = self.rfile.read(content_length) + request = ExportTraceServiceRequest() + request.ParseFromString(body) + self.server.telemetry.traces.extend(request.resource_spans) + self.send_response(200, "OK") + self.end_headers() diff --git a/python/instrumentation/openinference-instrumentation-mcp/tests/conftest.py b/python/instrumentation/openinference-instrumentation-mcp/tests/conftest.py new file mode 100644 index 0000000000..856f2be135 --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/tests/conftest.py @@ -0,0 +1,58 @@ +from threading import Thread +from typing import Generator + +import pytest +from opentelemetry import trace as trace_api +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.sdk import trace as trace_sdk +from opentelemetry.sdk.trace.export import SimpleSpanProcessor + +from openinference.instrumentation.mcp import MCPInstrumentor +from tests.collector import OTLPServer, Telemetry + + +@pytest.fixture(scope="session") +def telemetry() -> Telemetry: + return Telemetry() + + +@pytest.fixture(scope="session") +def otlp_collector(telemetry: Telemetry) -> Generator[OTLPServer, None, None]: + server = OTLPServer(("localhost", 0), telemetry) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server + finally: + server.shutdown() + thread.join() + + +@pytest.fixture(scope="session") +def tracer_provider(otlp_collector: OTLPServer) -> Generator[trace_api.TracerProvider, None, None]: + span_exporter = OTLPSpanExporter(f"http://localhost:{otlp_collector.server_port}/v1/traces") + tracer_provider = trace_sdk.TracerProvider() + span_processor = SimpleSpanProcessor(span_exporter) + tracer_provider.add_span_processor(span_processor) + try: + yield tracer_provider + finally: + tracer_provider.shutdown() + + +@pytest.fixture(scope="session") +def tracer(tracer_provider: trace_api.TracerProvider) -> trace_api.Tracer: + return tracer_provider.get_tracer("mcp-test-client") + + +@pytest.fixture(autouse=True) +def instrument( + tracer_provider: trace_api.TracerProvider, telemetry: Telemetry +) -> Generator[None, None, None]: + instrumenter = MCPInstrumentor() + instrumenter.instrument(tracer_provider=tracer_provider) + try: + yield + finally: + instrumenter.uninstrument() + telemetry.clear() diff --git a/python/instrumentation/openinference-instrumentation-mcp/tests/mcpserver.py b/python/instrumentation/openinference-instrumentation-mcp/tests/mcpserver.py new file mode 100644 index 0000000000..e0c6ca2b20 --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/tests/mcpserver.py @@ -0,0 +1,34 @@ +import os +from typing import Literal, cast + +from mcp.server.fastmcp import FastMCP +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.sdk import trace as trace_sdk +from opentelemetry.sdk.trace.export import SimpleSpanProcessor + +from openinference.instrumentation.mcp import MCPInstrumentor + +transport = cast(Literal["sse", "stdio"], os.environ.get("MCP_TRANSPORT")) +otlp_endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") +span_exporter = OTLPSpanExporter(f"{otlp_endpoint}/v1/traces") +tracer_provider = trace_sdk.TracerProvider() +span_processor = SimpleSpanProcessor(span_exporter) +tracer_provider.add_span_processor(span_processor) + +tracer = tracer_provider.get_tracer("mcp-test-server") + +MCPInstrumentor().instrument(tracer_provider=tracer_provider) + +server = FastMCP(port=0) + + +@server.tool() +def hello() -> str: + with tracer.start_as_current_span("hello"): + return "World!" + + +try: + server.run(transport=transport) +finally: + tracer_provider.shutdown() diff --git a/python/instrumentation/openinference-instrumentation-mcp/tests/test_instrumenter.py b/python/instrumentation/openinference-instrumentation-mcp/tests/test_instrumenter.py new file mode 100644 index 0000000000..126c305874 --- /dev/null +++ b/python/instrumentation/openinference-instrumentation-mcp/tests/test_instrumenter.py @@ -0,0 +1,89 @@ +import asyncio +import subprocess +import sys +from contextlib import asynccontextmanager +from pathlib import Path +from typing import AsyncGenerator + +import pytest +from mcp import ClientSession +from mcp.client.sse import sse_client +from mcp.client.stdio import StdioServerParameters, stdio_client +from mcp.types import TextContent +from opentelemetry.trace import Tracer + +from tests.collector import OTLPServer, Telemetry + + +# The way MCP SDK creates async tasks means we need this to be called inline with the test, +# not as a fixture. +@asynccontextmanager +async def mcp_client(transport: str, otlp_endpoint: str) -> AsyncGenerator[ClientSession, None]: + server_script = str(Path(__file__).parent / "mcpserver.py") + match transport: + case "stdio": + async with stdio_client( + StdioServerParameters( + command=sys.executable, + args=[server_script], + env={"MCP_TRANSPORT": "stdio", "OTEL_EXPORTER_OTLP_ENDPOINT": otlp_endpoint}, + ) + ) as (reader, writer), ClientSession(reader, writer) as client: + await client.initialize() + yield client + case "sse": + proc = await asyncio.create_subprocess_exec( + sys.executable, + server_script, + env={"MCP_TRANSPORT": "sse", "OTEL_EXPORTER_OTLP_ENDPOINT": otlp_endpoint}, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + try: + stderr = proc.stderr + assert stderr is not None + for i in range(100): + line = str(await stderr.readline()) + if "Uvicorn running on http://0.0.0.0:" in line: + _, rest = line.split("http://0.0.0.0:", 1) + port, _ = rest.split(" ", 1) + async with sse_client(f"http://localhost:{port}/sse") as ( + reader, + writer, + ), ClientSession(reader, writer) as client: + await client.initialize() + yield client + break + finally: + proc.kill() + await proc.wait() + + +@pytest.mark.parametrize("transport", ["sse", "stdio"]) +async def test_hello( + transport: str, tracer: Tracer, telemetry: Telemetry, otlp_collector: OTLPServer +) -> None: + async with mcp_client(transport, f"http://localhost:{otlp_collector.server_port}/") as client: + with tracer.start_as_current_span("root"): + tools_res = await client.list_tools() + assert len(tools_res.tools) == 1 + assert tools_res.tools[0].name == "hello" + tool_res = await client.call_tool("hello") + content = tool_res.content[0] + assert isinstance(content, TextContent) + assert content.text == "World!" + + assert len(telemetry.traces) == 2 + for resource_spans in telemetry.traces: + assert len(resource_spans.scope_spans) == 1 + for scope_spans in resource_spans.scope_spans: + assert len(scope_spans.spans) == 1 + match scope_spans.scope.name: + case "mcp-test-client": + client_span = scope_spans.spans[0] + case "mcp-test-server": + server_span = scope_spans.spans[0] + assert client_span.name == "root" + assert server_span.name == "hello" + assert server_span.trace_id == client_span.trace_id + assert server_span.parent_span_id == client_span.span_id diff --git a/python/tox.ini b/python/tox.ini index 855595255c..814b2cc883 100644 --- a/python/tox.ini +++ b/python/tox.ini @@ -24,6 +24,7 @@ envlist = py3{11,13}-ci-{beeai,beeai-latest} py3{9,13}-ci-{portkey,portkey-latest} py39-mypy-langchain_core + py3{10,13}-ci-{mcp,mcp-latest} [testenv] package = wheel @@ -53,6 +54,7 @@ changedir = autogen: instrumentation/openinference-instrumentation-autogen/ beeai: instrumentation/openinference-instrumentation-beeai/ portkey: instrumentation/openinference-instrumentation-portkey/ + mcp: instrumentation/openinference-instrumentation-mcp/ commands_pre = bedrock: uv pip install --reinstall {toxinidir}/instrumentation/openinference-instrumentation-bedrock[test] bedrock-latest: uv pip install -U boto3 anthropic @@ -113,6 +115,11 @@ commands_pre = instrumentation: uv pip install --reinstall {toxinidir}/openinference-instrumentation[test] uv pip install --reinstall {toxinidir}/openinference-semantic-conventions # reinstall comes last to ensure it is installed from source beeai: uv pip install --reinstall {toxinidir}/instrumentation/openinference-instrumentation-beeai[test] + mcp: uv pip uninstall -r test-requirements.txt + mcp: uv pip install --reinstall-package openinference-instrumentation-mcp . + mcp: python -c 'import openinference.instrumentation.mcp' + mcp: uv pip install -r test-requirements.txt + mcp-latest: uv pip install -U mcp commands = ruff: ruff format . ruff: ruff check --fix . diff --git a/release-please-config.json b/release-please-config.json index 43c37eee21..45321ec3b7 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -86,6 +86,11 @@ "python/instrumentation/openinference-instrumentation-portkey": { "package-name": "python-openinference-instrumentation-portkey", "release-type": "python" + }, + "python/instrumentation/openinference-instrumentation-mcp": { + "package-name": "python-openinference-instrumentation-mcp", + "release-type": "python" } + } }