Skip to content

fix: make MCP package import optional to prevent errors when not installed#1096

Merged
MervinPraison merged 1 commit intoMervinPraison:mainfrom
majiayu000:fix/issue-1091-mcp-optional-import
Dec 30, 2025
Merged

fix: make MCP package import optional to prevent errors when not installed#1096
MervinPraison merged 1 commit intoMervinPraison:mainfrom
majiayu000:fix/issue-1091-mcp-optional-import

Conversation

@majiayu000
Copy link
Copy Markdown
Contributor

@majiayu000 majiayu000 commented Dec 30, 2025

User description

Summary

  • Wrap mcp imports in try/except blocks in mcp.py, mcp_sse.py, and mcp_http_stream.py
  • Add MCP_AVAILABLE flag to check availability at runtime
  • Raise clear ImportError with installation instructions when MCP is used without the package installed

Test plan

  • Verify basic agent code works without mcp installed
  • Verify clear error message when trying to use MCP without package

Closes #1091


PR Type

Bug fix


Description

  • Wrap MCP imports in try/except blocks across three modules

  • Add MCP_AVAILABLE flag for runtime availability checking

  • Raise clear ImportError with installation instructions when MCP instantiated without package

  • Add comprehensive test suite for optional MCP import functionality


Diagram Walkthrough

flowchart LR
  A["MCP Imports"] -->|try/except| B["MCP_AVAILABLE Flag"]
  B -->|False| C["Raise ImportError"]
  C -->|Installation Instructions| D["User Guidance"]
  B -->|True| E["Normal Operation"]
  F["Test Suite"] -->|Validates| B
Loading

File Walkthrough

Relevant files
Error handling
mcp.py
Add optional MCP import with runtime validation                   

src/praisonai-agents/praisonaiagents/mcp/mcp.py

  • Wrapped mcp and mcp.client.stdio imports in try/except block
  • Added MCP_AVAILABLE flag to track import success
  • Set imported symbols to None on import failure
  • Added runtime check in __init__ to raise clear ImportError with
    installation instructions
  • Fixed trailing whitespace formatting
+17/-3   
mcp_sse.py
Add optional MCP SSE import with runtime validation           

src/praisonai-agents/praisonaiagents/mcp/mcp_sse.py

  • Wrapped mcp.ClientSession and mcp.client.sse imports in try/except
    block
  • Added MCP_AVAILABLE flag to track import success
  • Set imported symbols to None on import failure
  • Added runtime check in __init__ to raise clear ImportError with
    installation instructions
  • Fixed trailing whitespace formatting
+16/-3   
mcp_http_stream.py
Add optional MCP HTTP stream import with dual validation 

src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py

  • Wrapped mcp.ClientSession import in try/except block
  • Added MCP_AVAILABLE flag to track import success
  • Changed aiohttp import failure from raising to setting to None
  • Added runtime checks in __init__ for both MCP and aiohttp availability
  • Raise clear ImportError with installation instructions when
    dependencies missing
  • Fixed trailing whitespace formatting
+23/-3   
Tests
test_mcp_optional_import.py
Add test suite for optional MCP import functionality         

src/praisonai-agents/tests/test_mcp_optional_import.py

  • Created new test file with comprehensive test suite for optional MCP
    imports
  • Tests basic package imports without MCP installed
  • Tests module-level imports don't crash with try/except blocks
  • Tests agent creation without MCP tools
  • Validates MCP_AVAILABLE flag presence in modules
  • Covers issue when running basic reptitive agent code #1091 fix validation
+71/-0   

Summary by CodeRabbit

  • New Features

    • Made MCP dependencies optional; the system now operates without MCP installed and provides clear error messages when MCP features are accessed without MCP available.
  • Tests

    • Added comprehensive test coverage for optional MCP import behavior, ensuring core functionality works independently of MCP availability.

✏️ Tip: You can customize this high-level summary in your review settings.

…alled

Wrap mcp imports in try/except blocks in mcp.py, mcp_sse.py, and
mcp_http_stream.py. Add MCP_AVAILABLE flag to check availability at runtime.
When MCP class is instantiated without the mcp package installed, raise a
clear ImportError with installation instructions.

Closes MervinPraison#1091

Signed-off-by: majiayu000 <1835304752@qq.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Dec 30, 2025

📝 Walkthrough

Walkthrough

This change makes MCP (Model Context Protocol) dependencies optional by introducing defensive import wrappers across three MCP-related modules, adding availability flags, and inserting pre-flight checks in initialization methods to raise helpful ImportError messages when MCP is unavailable.

Changes

Cohort / File(s) Summary
MCP Import Guards
src/praisonai-agents/praisonaiagents/mcp/mcp.py, src/praisonai-agents/praisonaiagents/mcp/mcp_sse.py, src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py
Added MCP_AVAILABLE module-level flag set via try/except wrapper around MCP imports. Inserted pre-flight ImportError checks in initialization methods (MCPToolRunner, SSEMCPTool, SSEMCPClient, HTTPStreamMCPClient) that raise with guidance when MCP is unavailable. Defensive handling of aiohttp dependency in mcp_http_stream.py.
Optional Import Tests
src/praisonai-agents/tests/test_mcp_optional_import.py
New test module verifying package and Agent imports succeed without MCP, lazy loading behavior of MCP, crash-free module imports with availability checks, and basic Agent creation without MCP tools. Seven test methods covering core optional dependency scenarios.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

Review effort 4/5

Poem

🐰 When MCP went missing, the code would crash and fall,
But now with guards defensive, we handle it all!
Optional imports hop lightly, errors caught with care,
Agents run without stumbling—freedom everywhere! 🌿

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: making MCP package imports optional to prevent errors when not installed.
Linked Issues check ✅ Passed The PR successfully addresses issue #1091 by wrapping MCP imports in try/except blocks, adding MCP_AVAILABLE flag, and raising clear ImportError with installation guidance when MCP functionality is used without the package.
Out of Scope Changes check ✅ Passed All changes directly support the objective of making MCP optional. The defensive imports in three modules and comprehensive test coverage are all in-scope and necessary for the feature.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ 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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @majiayu000, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses an issue where the praisonaiagents library would fail to import if the mcp (Model Context Protocol) package was not installed, even if mcp functionality was not being used. By making mcp an optional dependency, the library can now be used in environments where mcp is not required, improving flexibility and preventing unnecessary ImportError exceptions during initial import. The changes ensure that the mcp package is only strictly required when its specific features are actively invoked.

Highlights

  • Optional MCP Import: The mcp package imports are now wrapped in try/except ImportError blocks across mcp.py, mcp_sse.py, and mcp_http_stream.py to make it an optional dependency.
  • Availability Flag: A new MCP_AVAILABLE flag has been introduced to check the presence of the mcp package at runtime, allowing for conditional logic.
  • Clear Error Messages: If mcp functionality is attempted without the package installed, a clear ImportError is now raised with instructions on how to install it.
  • New Test File: A new test file, test_mcp_optional_import.py, has been added to ensure that praisonaiagents can be imported and basic agents created without mcp installed, and that mcp modules can be imported without crashing.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@qodo-code-review
Copy link
Copy Markdown

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #1091
🟢 MCP-related functionality should fail with a clear, actionable error message when a user
tries to use MCP without having installed the MCP extra/dependency.
Running the Customer Support System “repetitive agent” example (and other basic code)
should not error with No module named 'mcp' when mcp is not installed.
Confirm the exact documentation example at
https://docs.praison.ai/docs/features/repetitive now runs end-to-end in a clean
environment without mcp installed (i.e., no other import paths in the example still import
MCP eagerly).
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate SSE client availability

In SSEMCPClient.init, add a check to ensure sse_client is not None and raise
an ImportError if it is, preventing a TypeError at runtime.

src/praisonai-agents/praisonaiagents/mcp/mcp_sse.py [178-183]

 # Check if MCP is available
 if not MCP_AVAILABLE:
     raise ImportError(
         "MCP (Model Context Protocol) package is not installed. "
         "Install it with: pip install praisonaiagents[mcp]"
     )
+# Check if SSE client is available
+if sse_client is None:
+    raise ImportError(
+        "MCP SSE client is not available. Install it with: pip install praisonaiagents[mcp]"
+    )
  • Apply / Chat
Suggestion importance[1-10]: 8

__

Why: This suggestion fixes a bug where using SSEMCPClient without the mcp package would cause a TypeError instead of the intended ImportError, improving error handling and robustness.

Medium
High-level
Centralize the optional dependency check

To avoid code duplication, centralize the mcp package availability check. Define
the try/except block and MCP_AVAILABLE flag in one location and import it into
the modules that need it.

Examples:

src/praisonai-agents/praisonaiagents/mcp/mcp.py [14-22]
try:
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    ClientSession = None
    StdioServerParameters = None
    stdio_client = None
src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py [19-24]
try:
    from mcp import ClientSession
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    ClientSession = None

Solution Walkthrough:

Before:

# In praisonaiagents/mcp/mcp.py
try:
    from mcp import ClientSession, StdioServerParameters
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    # ... set imports to None

# In praisonaiagents/mcp/mcp_http_stream.py
try:
    from mcp import ClientSession
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    ClientSession = None

# In praisonaiagents/mcp/mcp_sse.py
try:
    from mcp import ClientSession
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False
    # ... set imports to None

After:

# In a central file, e.g., praisonaiagents/mcp/availability.py
try:
    import mcp
    MCP_AVAILABLE = True
except ImportError:
    MCP_AVAILABLE = False

# In praisonaiagents/mcp/mcp.py
from .availability import MCP_AVAILABLE
if MCP_AVAILABLE:
    from mcp import ClientSession, StdioServerParameters
    # ... other imports
else:
    # ... set imports to None

# In praisonaiagents/mcp/mcp_http_stream.py
from .availability import MCP_AVAILABLE
if MCP_AVAILABLE:
    from mcp import ClientSession
else:
    ClientSession = None
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies duplicated logic for checking the optional mcp dependency across three files and proposes a centralized solution, which improves code maintainability and adheres to the DRY principle.

Medium
General
Assert lazy-load instantiation error

Complete the test_mcp_lazy_loading test by adding pytest.raises(ImportError) to
assert that instantiating MCP() fails as expected when the dependency is
missing.

src/praisonai-agents/tests/test_mcp_optional_import.py [23-28]

 def test_mcp_lazy_loading(self):
     """Test that MCP is lazily loaded."""
     from praisonaiagents import MCP
-    # MCP should either be available or None (not raise ImportError on access)
-    # The actual ImportError should only be raised when trying to instantiate
-    # if mcp package is not installed
+    # Accessing the class should not raise
+    assert MCP is not None
+    # Instantiating should raise if the MCP package isn't installed
+    with pytest.raises(ImportError):
+        MCP()
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that the test is incomplete and adds an assertion to verify the core behavior of raising an ImportError on instantiation, making the test effective.

Medium
Remove unnecessary try-except from test

Remove the unnecessary try...except ImportError block from the
test_mcp_module_import_no_crash test, as the import is designed not to fail.

src/praisonai-agents/tests/test_mcp_optional_import.py [30-39]

 def test_mcp_module_import_no_crash(self):
     """Test that mcp module can be imported without crashing."""
     # This tests that the try/except in mcp.py works correctly
-    try:
-        from praisonaiagents.mcp import mcp as mcp_module
-        assert hasattr(mcp_module, 'MCP_AVAILABLE')
-    except ImportError:
-        # If import fails, it should be because of missing mcp,
-        # not because of a syntax error
-        pass
+    from praisonaiagents.mcp import mcp as mcp_module
+    assert hasattr(mcp_module, 'MCP_AVAILABLE')
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies that the try...except block in the test is redundant and could mask real errors, thus improving the test's reliability.

Low
  • More

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request correctly makes the mcp package an optional dependency by wrapping imports in try-except blocks and raising an ImportError at runtime if the package is not installed. This is a good approach that improves the user experience for those not using MCP features. The changes are applied consistently across all relevant modules. However, the new test suite is incomplete. While it verifies that the application doesn't crash on import, it fails to test the new error-raising mechanism when the optional dependencies are missing. I've added suggestions to include these crucial tests to ensure the feature is robust and works as described in the test plan.

Comment on lines +23 to +29
def test_mcp_lazy_loading(self):
"""Test that MCP is lazily loaded."""
from praisonaiagents import MCP
# MCP should either be available or None (not raise ImportError on access)
# The actual ImportError should only be raised when trying to instantiate
# if mcp package is not installed

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The test_mcp_lazy_loading test is currently a placeholder without any assertions. It's crucial to verify that instantiating the MCP-related classes correctly raises an ImportError when their dependencies are missing. This suggestion replaces the placeholder with comprehensive tests for this behavior, covering MCP, SSEMCPClient, and HTTPStreamMCPClient.

    def test_mcp_instantiation_raises_error_if_mcp_unavailable(self):
        """Test that instantiating MCP classes raises ImportError if mcp is not installed."""
        from unittest.mock import patch
        with patch.dict('sys.modules', {'mcp': None, 'mcp.client.stdio': None, 'mcp.client.sse': None}):
            import importlib

            # Test MCP class
            from praisonaiagents.mcp import mcp
            importlib.reload(mcp)
            assert not mcp.MCP_AVAILABLE
            with pytest.raises(ImportError, match="MCP .* not installed"):
                mcp.MCP("some command")
            importlib.reload(mcp)  # Restore

            # Test SSEMCPClient class
            from praisonaiagents.mcp import mcp_sse
            importlib.reload(mcp_sse)
            assert not mcp_sse.MCP_AVAILABLE
            with pytest.raises(ImportError, match="MCP .* not installed"):
                mcp_sse.SSEMCPClient("http://localhost/sse")
            importlib.reload(mcp_sse)  # Restore

            # Test HTTPStreamMCPClient class for MCP
            from praisonaiagents.mcp import mcp_http_stream
            importlib.reload(mcp_http_stream)
            assert not mcp_http_stream.MCP_AVAILABLE
            with pytest.raises(ImportError, match="MCP .* not installed"):
                mcp_http_stream.HTTPStreamMCPClient("http://localhost/stream")
            importlib.reload(mcp_http_stream)  # Restore

    def test_http_stream_instantiation_raises_error_if_aiohttp_unavailable(self):
        """Test that instantiating HTTPStreamMCPClient raises ImportError if aiohttp is not installed."""
        from unittest.mock import patch
        with patch.dict('sys.modules', {'aiohttp': None}):
            import importlib
            from praisonaiagents.mcp import mcp_http_stream
            importlib.reload(mcp_http_stream)
            
            with pytest.raises(ImportError, match="aiohttp is required"):
                mcp_http_stream.HTTPStreamMCPClient("http://localhost/stream")
            
            importlib.reload(mcp_http_stream)  # Restore

Comment on lines +5 to +6
import sys
import pytest
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

To properly test for missing optional dependencies by mocking imports, we need to use patch from unittest.mock. Please add this import.

Suggested change
import sys
import pytest
import sys
import pytest
from unittest.mock import patch

Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (3)
src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py (1)

516-528: Clear error handling for missing dependencies.

The preflight checks correctly raise ImportError with helpful installation instructions when MCP or aiohttp packages are unavailable. This ensures users get clear guidance rather than cryptic errors.

Note: Static analysis suggests using custom exception classes for long messages (TRY003), but the current inline approach is clear and appropriate for this use case.

src/praisonai-agents/tests/test_mcp_optional_import.py (2)

23-28: Consider enhancing the lazy loading test.

The test currently only imports the MCP class but doesn't verify the lazy loading behavior (i.e., that ImportError is raised on instantiation, not on import, when MCP is unavailable). Consider adding a test that attempts to instantiate MCP and verifies the error behavior.

Example enhancement
 def test_mcp_lazy_loading(self):
     """Test that MCP is lazily loaded."""
     from praisonaiagents import MCP
-    # MCP should either be available or None (not raise ImportError on access)
-    # The actual ImportError should only be raised when trying to instantiate
-    # if mcp package is not installed
+    
+    # Import should succeed even if MCP package is not installed
+    assert MCP is not None
+    
+    # Try to instantiate - this should raise ImportError if MCP not available
+    try:
+        from praisonaiagents.mcp.mcp import MCP_AVAILABLE
+        if not MCP_AVAILABLE:
+            with pytest.raises(ImportError, match="MCP.*not installed"):
+                MCP("test command")
+    except ImportError:
+        pass  # MCP module itself couldn't be imported

30-55: Module import tests are functional.

These tests effectively verify that MCP-related modules can be imported and expose the MCP_AVAILABLE flag. The tests correctly handle both scenarios (MCP available or not).

As an optional improvement, consider adding assertions about the exception type or message when ImportError is caught, to distinguish between missing MCP dependencies and potential syntax errors in the modules themselves.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf3fdd1 and 98c5e8f.

📒 Files selected for processing (4)
  • src/praisonai-agents/praisonaiagents/mcp/mcp.py
  • src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py
  • src/praisonai-agents/praisonaiagents/mcp/mcp_sse.py
  • src/praisonai-agents/tests/test_mcp_optional_import.py
🧰 Additional context used
🧬 Code graph analysis (1)
src/praisonai-agents/tests/test_mcp_optional_import.py (1)
src/praisonai-agents/praisonaiagents/mcp/mcp.py (1)
  • MCP (150-653)
🪛 Ruff (0.14.10)
src/praisonai-agents/praisonaiagents/mcp/mcp.py

208-211: Avoid specifying long messages outside the exception class

(TRY003)

src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py

518-521: Avoid specifying long messages outside the exception class

(TRY003)


525-528: Avoid specifying long messages outside the exception class

(TRY003)

src/praisonai-agents/praisonaiagents/mcp/mcp_sse.py

180-183: Avoid specifying long messages outside the exception class

(TRY003)

🔇 Additional comments (7)
src/praisonai-agents/praisonaiagents/mcp/mcp_http_stream.py (1)

19-29: LGTM! Optional imports correctly implemented.

The try/except blocks properly guard MCP and aiohttp imports, setting appropriate flags and None values when packages are unavailable. This enables the module to be imported without these dependencies installed.

src/praisonai-agents/praisonaiagents/mcp/mcp.py (2)

14-22: LGTM! Optional MCP imports correctly implemented.

The try/except block properly guards all MCP imports, enabling the module to be imported without the MCP package installed while setting appropriate availability flags.


206-211: Clear error handling when MCP is unavailable.

The preflight check correctly raises ImportError with installation instructions when attempting to use MCP functionality without the package installed, aligning with the PR objective.

src/praisonai-agents/praisonaiagents/mcp/mcp_sse.py (2)

14-21: LGTM! Optional MCP imports correctly implemented.

The try/except block properly guards MCP SSE client imports, maintaining consistency with the optional import pattern used across all MCP modules.


178-183: Clear error handling maintains consistency.

The preflight check in SSEMCPClient follows the same pattern as other MCP modules, providing clear error messages when the MCP package is unavailable.

src/praisonai-agents/tests/test_mcp_optional_import.py (2)

12-21: LGTM! Basic import tests are well-structured.

These tests effectively verify that the core praisonaiagents package and Agent class can be imported without MCP installed, directly addressing the issue from #1091.


57-67: LGTM! Test effectively validates the fix for issue #1091.

This test directly addresses the original issue by verifying that basic agent code works without MCP installed, which was the main objective of the PR.

@MervinPraison MervinPraison merged commit e59be8f into MervinPraison:main Dec 30, 2025
2 checks passed
@majiayu000 majiayu000 deleted the fix/issue-1091-mcp-optional-import branch December 30, 2025 16:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

when running basic reptitive agent code

2 participants