Skip to content

Conversation

@NVJKKartik
Copy link
Contributor

@NVJKKartik NVJKKartik commented May 30, 2025

Pull Request

Description

Describe the changes in this pull request:

  • What feature/bug does this PR address?
  • Provide any relevant links or screenshots.

Checklist

  • Code compiles correctly.
  • Created/updated tests.
  • Linting and formatting applied.
  • Documentation updated.

Related Issues

Closes #<issue_number>

Summary by CodeRabbit

  • New Features
    • Introduced OpenTelemetry-based instrumentation for MCP, enabling distributed tracing and context propagation across asynchronous MCP transports and sessions.
    • Added comprehensive support for tracing context in MCP client and server communications.
  • Documentation
    • Significantly expanded and reorganized the README for improved clarity, navigation, and user guidance, including new sections for features, supported frameworks, contributing, and resources.
  • Chores
    • Added configuration and metadata files for the new MCP instrumentation package, including versioning and dependency declarations.

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

Walkthrough

A new OpenTelemetry instrumentation module for the MCP protocol was introduced, including comprehensive context propagation logic, package metadata, versioning, and dependency declarations. The documentation was extensively updated for clarity, completeness, and community engagement, with no changes to core code entities outside the new MCP integration.

Changes

File(s) Change Summary
README.md Expanded and reorganized documentation: improved intro, added features, frameworks table, contributing, resources.
python/frameworks/mcp/pyproject.toml New Poetry-based package configuration for traceAI-mcp, specifying metadata and dependencies.
python/frameworks/mcp/traceai_mcp/init.py New MCP OpenTelemetry instrumentation module: context propagation, stream wrappers, instrumentor class.
python/frameworks/mcp/traceai_mcp/package.py Added _instruments tuple listing MCP and FutureAGI as dependencies.
python/frameworks/mcp/traceai_mcp/version.py Added __version__ = "0.1.0" for version tracking.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant MCPInstrumentor
    participant MCPClient
    participant InstrumentedStreamReader
    participant InstrumentedStreamWriter
    participant OpenTelemetry

    App->>MCPInstrumentor: instrument()
    MCPInstrumentor->>MCPClient: wrap transport functions
    MCPClient->>InstrumentedStreamReader: receive message
    InstrumentedStreamReader->>OpenTelemetry: extract context from metadata
    InstrumentedStreamReader->>App: yield message with context
    App->>InstrumentedStreamWriter: send message
    InstrumentedStreamWriter->>OpenTelemetry: inject context into metadata
    InstrumentedStreamWriter->>MCPClient: send message
Loading

Suggested reviewers

  • JayaSurya-27

Poem

In the land of code, a hop and a leap,
MCP now traces, context runs deep.
With streams wrapped tight and context in tow,
Distributed traces are ready to flow!
Docs now shine bright, for all to see—
A rabbit's delight in observability.
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@NVJKKartik NVJKKartik changed the base branch from main to dev May 30, 2025 14:41
@NVJKKartik NVJKKartik requested a review from JayaSurya-27 May 30, 2025 14:41
@NVJKKartik NVJKKartik changed the title mcp support python [Feature] MCP (Model Context Protocol) Instrumentation Support For Python SDK May 30, 2025
@JayaSurya-27 JayaSurya-27 merged commit 59f8b90 into dev May 30, 2025
1 check was pending
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
python/frameworks/mcp/pyproject.toml (1)

21-21: Remove trailing whitespace

-build-backend = "poetry.core.masonry.api"
-
+build-backend = "poetry.core.masonry.api"
README.md (1)

127-136: Format bare URLs properly

Bare URLs should be wrapped in angle brackets for proper markdown formatting.

-Website: https://www.futureagi.com/
-Documentation: https://docs.futureagi.com/
+Website: <https://www.futureagi.com/>
+Documentation: <https://docs.futureagi.com/>
 Cookbooks: [How-To-Implement-Observability](https://docs.futureagi.com/cookbook/cookbook8/How-To-Implement-Observability)

 ## Connect With Us

-LinkedIn: https://www.linkedin.com/company/futureagi
-Twitter: https://x.com/FutureAGI_
-Reddit: https://www.reddit.com/user/Future_AGI/submitted/
-Substack: https://substack.com/@futureagi
+LinkedIn: <https://www.linkedin.com/company/futureagi>
+Twitter: <https://x.com/FutureAGI_>
+Reddit: <https://www.reddit.com/user/Future_AGI/submitted/>
+Substack: <https://substack.com/@futureagi>
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

127-127: Bare URL used
null

(MD034, no-bare-urls)


128-128: Bare URL used
null

(MD034, no-bare-urls)


133-133: Bare URL used
null

(MD034, no-bare-urls)


134-134: Bare URL used
null

(MD034, no-bare-urls)


135-135: Bare URL used
null

(MD034, no-bare-urls)


136-136: Bare URL used
null

(MD034, no-bare-urls)

python/frameworks/mcp/traceai_mcp/__init__.py (1)

122-124: Consider moving imports to module level

Importing inside methods can impact performance, especially in async iterators that may be called frequently.

Move these imports to the top of the file:

from mcp.shared.message import SessionMessage
from mcp.types import JSONRPCRequest

This would improve performance and follow Python conventions for import placement.

Also applies to: 155-157

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 250cb84 and 82ea007.

📒 Files selected for processing (5)
  • README.md (3 hunks)
  • python/frameworks/mcp/pyproject.toml (1 hunks)
  • python/frameworks/mcp/traceai_mcp/__init__.py (1 hunks)
  • python/frameworks/mcp/traceai_mcp/package.py (1 hunks)
  • python/frameworks/mcp/traceai_mcp/version.py (1 hunks)
🧰 Additional context used
🪛 LanguageTool
README.md

[style] ~6-~6: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...hem to standardized trace attributes. traceAI is natively supported by Future AGI, bu...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~7-~7: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...enTelemetry-compatible backend as well. traceAI provides a set of instrumentations for ...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


[style] ~7-~7: Consider using a more concise synonym.
Context: ...machine learning SDKs and frameworks in a variety of languages like Langchain, OpenAI, Anthr...

(A_VARIETY_OF)


[style] ~118-~118: Using many exclamation marks might seem excessive (in this case: 18 exclamation marks for a text that’s 5232 characters long)
Context: ...welcome contributions from the community! To contribute: 1. Fork the repository. ...

(EN_EXCESSIVE_EXCLAMATION)

🪛 markdownlint-cli2 (0.17.2)
README.md

11-11: Link fragments should be valid
null

(MD051, link-fragments)


16-16: Link fragments should be valid
null

(MD051, link-fragments)


127-127: Bare URL used
null

(MD034, no-bare-urls)


128-128: Bare URL used
null

(MD034, no-bare-urls)


133-133: Bare URL used
null

(MD034, no-bare-urls)


134-134: Bare URL used
null

(MD034, no-bare-urls)


135-135: Bare URL used
null

(MD034, no-bare-urls)


136-136: Bare URL used
null

(MD034, no-bare-urls)

🪛 Ruff (0.11.9)
python/frameworks/mcp/traceai_mcp/__init__.py

108-110: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)


111-111: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)

🔇 Additional comments (2)
python/frameworks/mcp/traceai_mcp/version.py (1)

1-1: LGTM!

Standard version declaration following Python packaging best practices.

README.md (1)

106-106: Good catch on the typo fix!

Correcting "gpt-4-0" to "gpt-4o" ensures the correct OpenAI model name is used.

@@ -0,0 +1 @@
_instruments = ("mcp >= 0.1.0", "futureagi >= 0.0.1") No newline at end of file
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Version mismatch and missing dependency in pyproject.toml

The MCP version requirement here (>= 0.1.0) conflicts with the one in pyproject.toml (>= 1.8.1). Additionally, the futureagi dependency is not declared in pyproject.toml.

Apply this diff to align with pyproject.toml:

-_instruments = ("mcp >= 0.1.0", "futureagi >= 0.0.1")
+_instruments = ("mcp >= 1.8.1", "futureagi >= 0.0.1")

Additionally, ensure the futureagi dependency is added to pyproject.toml if it's required for instrumentation.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
_instruments = ("mcp >= 0.1.0", "futureagi >= 0.0.1")
_instruments = ("mcp >= 1.8.1", "futureagi >= 0.0.1")
🤖 Prompt for AI Agents
In python/frameworks/mcp/traceai_mcp/package.py at line 1, update the MCP
version requirement in the _instruments tuple to match the version specified in
pyproject.toml (>= 1.8.1) instead of >= 0.1.0. Also, verify that the futureagi
dependency is declared in pyproject.toml; if it is missing, add it with the
appropriate version to ensure consistency and proper dependency management.

Comment on lines +12 to +16
[tool.poetry.dependencies]
python = ">3.9, <4.0"
fi-instrumentation-otel = "0.1.6"
mcp = ">=1.8.1"

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Missing futureagi dependency

The package.py file references "futureagi >= 0.0.1" as a required dependency, but it's not declared here.

If futureagi is required for the instrumentation to work correctly, add it to the dependencies:

 [tool.poetry.dependencies]
 python = ">3.9, <4.0"
 fi-instrumentation-otel = "0.1.6"
 mcp = ">=1.8.1"
+futureagi = ">=0.0.1"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[tool.poetry.dependencies]
python = ">3.9, <4.0"
fi-instrumentation-otel = "0.1.6"
mcp = ">=1.8.1"
[tool.poetry.dependencies]
python = ">3.9, <4.0"
fi-instrumentation-otel = "0.1.6"
mcp = ">=1.8.1"
futureagi = ">=0.0.1"
🤖 Prompt for AI Agents
In python/frameworks/mcp/pyproject.toml around lines 12 to 16, the dependency
"futureagi >= 0.0.1" is missing but required by package.py. Add the line
futureagi = ">=0.0.1" under [tool.poetry.dependencies] to declare this
dependency properly.

Comment on lines +10 to +17
## Table of Contents
- [Introduction](#introduction)
- [Features](#features)
- [Supported Frameworks](#supported-frameworks)
- [Quickstart](#quickstart)
- [Contributing](#contributing)
- [License](#license)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix missing link fragments in Table of Contents

The links to #introduction and #license sections are broken as these sections don't exist in the document.

Either add the missing sections or update the Table of Contents:

 ## Table of Contents
-- [Introduction](#introduction)
 - [Features](#features)
 - [Supported Frameworks](#supported-frameworks)
 - [Quickstart](#quickstart)
 - [Contributing](#contributing)
-- [License](#license)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
## Table of Contents
- [Introduction](#introduction)
- [Features](#features)
- [Supported Frameworks](#supported-frameworks)
- [Quickstart](#quickstart)
- [Contributing](#contributing)
- [License](#license)
## Table of Contents
- [Features](#features)
- [Supported Frameworks](#supported-frameworks)
- [Quickstart](#quickstart)
- [Contributing](#contributing)
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

11-11: Link fragments should be valid
null

(MD051, link-fragments)


16-16: Link fragments should be valid
null

(MD051, link-fragments)

🤖 Prompt for AI Agents
In README.md around lines 10 to 17, the Table of Contents includes links to
#introduction and #license sections that do not exist in the document. To fix
this, either add the missing Introduction and License sections with appropriate
content to the README or remove/update these entries in the Table of Contents to
only include existing sections, ensuring all links point to valid headers.

Comment on lines +105 to +111
reader = getattr(instance, "_incoming_message_stream_reader", None)
writer = getattr(instance, "_incoming_message_stream_writer", None)
if reader and writer:
setattr(
instance, "_incoming_message_stream_reader", ContextAttachingStreamReader(reader)
)
setattr(instance, "_incoming_message_stream_writer", ContextSavingStreamWriter(writer))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Use direct assignment instead of setattr

Static analysis correctly identifies that using setattr with constant strings is unnecessary and less readable than direct assignment.

 reader = getattr(instance, "_incoming_message_stream_reader", None)
 writer = getattr(instance, "_incoming_message_stream_writer", None)
 if reader and writer:
-    setattr(
-        instance, "_incoming_message_stream_reader", ContextAttachingStreamReader(reader)
-    )
-    setattr(instance, "_incoming_message_stream_writer", ContextSavingStreamWriter(writer))
+    instance._incoming_message_stream_reader = ContextAttachingStreamReader(reader)
+    instance._incoming_message_stream_writer = ContextSavingStreamWriter(writer)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
reader = getattr(instance, "_incoming_message_stream_reader", None)
writer = getattr(instance, "_incoming_message_stream_writer", None)
if reader and writer:
setattr(
instance, "_incoming_message_stream_reader", ContextAttachingStreamReader(reader)
)
setattr(instance, "_incoming_message_stream_writer", ContextSavingStreamWriter(writer))
reader = getattr(instance, "_incoming_message_stream_reader", None)
writer = getattr(instance, "_incoming_message_stream_writer", None)
if reader and writer:
instance._incoming_message_stream_reader = ContextAttachingStreamReader(reader)
instance._incoming_message_stream_writer = ContextSavingStreamWriter(writer)
🧰 Tools
🪛 Ruff (0.11.9)

108-110: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)


111-111: Do not call setattr with a constant attribute value. It is not any safer than normal property access.

Replace setattr with assignment

(B010)

🤖 Prompt for AI Agents
In python/frameworks/mcp/traceai_mcp/__init__.py around lines 105 to 111,
replace the setattr calls used to assign to _incoming_message_stream_reader and
_incoming_message_stream_writer with direct attribute assignment on the instance
object, as the attribute names are constant strings and direct assignment
improves readability and satisfies static analysis.

Comment on lines +79 to +81
def _uninstrument(self, **kwargs: Any) -> None:
unwrap("mcp.client.stdio", "stdio_client")
unwrap("mcp.server.stdio", "stdio_server")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Incomplete uninstrumentation implementation

The _uninstrument method only unwraps stdio transports but leaves HTTP, SSE, and session instrumentation in place.

Add the missing unwrap calls:

 def _uninstrument(self, **kwargs: Any) -> None:
+    unwrap("mcp.client.streamable_http", "streamablehttp_client")
+    unwrap("mcp.server.streamable_http", "StreamableHTTPServerTransport.connect")
+    unwrap("mcp.client.sse", "sse_client")
+    unwrap("mcp.server.sse", "SseServerTransport.connect_sse")
     unwrap("mcp.client.stdio", "stdio_client")
     unwrap("mcp.server.stdio", "stdio_server")
+    unwrap("mcp.server.session", "ServerSession.__init__")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _uninstrument(self, **kwargs: Any) -> None:
unwrap("mcp.client.stdio", "stdio_client")
unwrap("mcp.server.stdio", "stdio_server")
def _uninstrument(self, **kwargs: Any) -> None:
unwrap("mcp.client.streamable_http", "streamablehttp_client")
unwrap("mcp.server.streamable_http", "StreamableHTTPServerTransport.connect")
unwrap("mcp.client.sse", "sse_client")
unwrap("mcp.server.sse", "SseServerTransport.connect_sse")
unwrap("mcp.client.stdio", "stdio_client")
unwrap("mcp.server.stdio", "stdio_server")
unwrap("mcp.server.session", "ServerSession.__init__")
🤖 Prompt for AI Agents
In python/frameworks/mcp/traceai_mcp/__init__.py around lines 79 to 81, the
_uninstrument method currently only unwraps stdio transports but does not unwrap
HTTP, SSE, and session instrumentation. To fix this, add unwrap calls for the
HTTP client and server, SSE client and server, and session instrumentation to
fully revert all instrumentations applied.

Comment on lines +134 to +144
if request.params:
meta = request.params.get("_meta")
if meta:
ctx = propagate.extract(meta)
restore = context.attach(ctx)
try:
yield item
continue
finally:
context.detach(restore)
yield item
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding error handling for context operations

The context extraction and attachment operations could fail, potentially causing unhandled exceptions in the async iterator.

Consider wrapping context operations in try-except blocks:

 if request.params:
     meta = request.params.get("_meta")
     if meta:
-        ctx = propagate.extract(meta)
-        restore = context.attach(ctx)
         try:
+            ctx = propagate.extract(meta)
+            restore = context.attach(ctx)
             yield item
             continue
+        except Exception as e:
+            # Log the error but continue processing
+            # Consider using a logger here
+            yield item
+            continue
         finally:
-            context.detach(restore)
+            if 'restore' in locals():
+                context.detach(restore)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if request.params:
meta = request.params.get("_meta")
if meta:
ctx = propagate.extract(meta)
restore = context.attach(ctx)
try:
yield item
continue
finally:
context.detach(restore)
yield item
if request.params:
meta = request.params.get("_meta")
if meta:
try:
ctx = propagate.extract(meta)
restore = context.attach(ctx)
yield item
continue
except Exception as e:
# Log the error but continue processing
# Consider using a logger here
yield item
continue
finally:
if 'restore' in locals():
context.detach(restore)
yield item
🤖 Prompt for AI Agents
In python/frameworks/mcp/traceai_mcp/__init__.py around lines 134 to 144, the
context extraction and attachment code can raise exceptions that are currently
unhandled. To fix this, wrap the context extraction, attachment, and detachment
logic inside try-except blocks to catch and handle any exceptions gracefully,
ensuring the async iterator continues to function without interruption.

@nik13 nik13 deleted the feature/mcp branch July 1, 2025 19:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants