Skip to content

Refactor codebase and configuration capabilities#9

Merged
Agent-Hellboy merged 7 commits intomasterfrom
issue#7
Jul 3, 2025
Merged

Refactor codebase and configuration capabilities#9
Agent-Hellboy merged 7 commits intomasterfrom
issue#7

Conversation

@Agent-Hellboy
Copy link
Owner

@Agent-Hellboy Agent-Hellboy commented Jul 3, 2025

fixes #8

Summary by CodeRabbit

  • New Features

    • Introduced a flexible middleware configuration system, allowing customization of CORS, logging, compression, and custom middleware via a dedicated configuration object.
    • Added an application factory function for dynamic app creation with configurable middleware options.
    • Provided a utility for handling specific JSON-RPC methods.
  • Documentation

    • Added comprehensive documentation and guides on middleware configuration and best practices.
    • Updated README with detailed middleware setup instructions and examples.
  • Refactor

    • Refactored server initialization to use an application factory and modular middleware setup.
    • Streamlined route handling and moved method-specific logic to utility functions.
  • Tests

    • Updated server test fixtures to use the new app creation approach.

@coderabbitai
Copy link

coderabbitai bot commented Jul 3, 2025

Warning

Rate limit exceeded

@Agent-Hellboy has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 38 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c34d04b and 07e9b2d.

📒 Files selected for processing (4)
  • pymcp/middleware.py (1 hunks)
  • tests/test_middleware.py (1 hunks)
  • tests/test_server.py (3 hunks)
  • tox.ini (2 hunks)

Walkthrough

A middleware configuration system was introduced for the MCP server, including a MiddlewareConfig class and related setup logic. Application instantiation now uses a factory function (create_app) that applies middleware settings. Documentation and examples were updated to reflect these changes, and server code was refactored to use routers and delegate method handling.

Changes

File(s) Change Summary
pymcp/middleware.py, pymcp/applications.py Added MiddlewareConfig class, middleware setup logic, and create_app factory function for app instantiation.
example/config.py Added example middleware configuration using MiddlewareConfig.
example/run_server.py, example/web-based/run_mcp_with_api_call.py, tests/test_server.py Updated to use create_app for dynamic app instantiation with middleware configuration.
pymcp/server.py Refactored to use APIRouter instead of FastAPI app, removed inline middleware setup, delegated method handling.
pymcp/utils.py Added handle_rpc_method async function for JSON-RPC method processing.
README.md, guide.md Added/updated documentation for middleware configuration and usage.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Uvicorn
    participant run_server.py
    participant config.py
    participant pymcp.applications
    participant pymcp.middleware
    participant FastAPIApp

    User->>Uvicorn: Start server
    Uvicorn->>run_server.py: Execute main block
    run_server.py->>config.py: Import middleware_config
    run_server.py->>pymcp.applications: Call create_app(middleware_config)
    pymcp.applications->>pymcp.middleware: setup_middleware(app, middleware_config)
    pymcp.middleware->>FastAPIApp: Add middleware (CORS, Logging, etc.)
    pymcp.applications->>run_server.py: Return configured app
    run_server.py->>Uvicorn: Run app
Loading

Assessment against linked issues

Objective Addressed Explanation
Add logging inside framework (#7)
Enhance README with logging and middleware configuration details (#7)
Update example scripts to use logging configuration and dynamic app instantiation (#7)

Poem

In fields of code where rabbits hop,
Middleware blooms—no need to stop!
CORS and logging, compression too,
All configured, shiny and new.
Now apps are built with factory flair,
And bunnies debug with utmost care!
🐇✨

✨ 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.

@codecov-commenter
Copy link

codecov-commenter commented Jul 3, 2025

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

Attention: Patch coverage is 98.14815% with 1 line in your changes missing coverage. Please review.

Project coverage is 88.11%. Comparing base (8da6e51) to head (07e9b2d).

Files with missing lines Patch % Lines
pymcp/middleware.py 94.44% 1 Missing ⚠️

❗ Your organization needs to install the Codecov GitHub app to enable full functionality.

Additional details and impacted files
@@             Coverage Diff             @@
##           master       #9       +/-   ##
===========================================
+ Coverage   74.80%   88.11%   +13.30%     
===========================================
  Files           2        5        +3     
  Lines         127      143       +16     
===========================================
+ Hits           95      126       +31     
+ Misses         32       17       -15     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

🔭 Outside diff range comments (1)
pymcp/server.py (1)

74-108: Consider refactoring to reduce code duplication.

The tools/call handling logic is duplicated between this file and pymcp/utils.py. Consider creating a shared function to handle tool execution.

Create a shared function in utils.py:

async def execute_tool(tool_name, args, rpc_id):
    """Execute a tool and return the JSON-RPC response."""
    tools = tool_registry.get_tools()
    if tool_name not in tools:
        return {
            "jsonrpc": "2.0",
            "id": rpc_id,
            "error": {"code": -32601, "message": f"No such tool '{tool_name}'"},
        }
    
    try:
        result_text = tools[tool_name]["function"](**args)
        return {
            "jsonrpc": "2.0",
            "id": rpc_id,
            "result": {"content": [{"type": "text", "text": result_text}]},
        }
    except Exception as e:
        logging.error(f"Error executing tool '{tool_name}': {str(e)}", exc_info=True)
        return {
            "jsonrpc": "2.0",
            "id": rpc_id,
            "error": {
                "code": -32603,
                "message": f"Error executing tool '{tool_name}': {str(e)}",
            },
        }

Then use it in both places to avoid duplication.

🧹 Nitpick comments (7)
pymcp/middleware.py (1)

55-55: Complete the error handling implementation.

The comment suggests error handling should be implemented but provides no implementation.

Would you like me to generate a basic error handling middleware implementation or create an issue to track this task?

tests/test_server.py (1)

14-14: Fix import order issue.

The static analysis tool flagged that module-level imports should be at the top of the file. The import on line 14 should be moved up with other imports.

Move the import to the top of the file:

 import os
 import sys
 
 import pytest
 import requests
+from pymcp.applications import create_app
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 import time
 from threading import Thread
 
 import uvicorn
 
 from pymcp.registry import tool_registry
-from pymcp.applications import create_app
pymcp/applications.py (1)

13-24: Well-designed application factory with excellent separation of concerns.

The factory function correctly implements the application creation pattern and provides good flexibility through optional configuration or kwargs.

Consider adding return type annotation for better type safety:

-def create_app(middleware_config: Optional[MiddlewareConfig] = None, **kwargs):
+def create_app(middleware_config: Optional[MiddlewareConfig] = None, **kwargs) -> FastAPI:
example/web-based/run_mcp_with_flask_call.py (2)

11-11: Consider making the Flask API URL configurable.

The hardcoded URL could be extracted to a configuration variable or environment variable for better flexibility.

+FLASK_API_URL = os.environ.get("FLASK_API_URL", "http://127.0.0.1:5005")
+
 @tool_registry.register
 def callFlaskHelloTool() -> str:
     """Calls the /hello endpoint of the Flask API server running on port 5005 and returns the message."""
     try:
-        resp = requests.get("http://127.0.0.1:5005/hello", timeout=2)
+        resp = requests.get(f"{FLASK_API_URL}/hello", timeout=2)

Don't forget to import os at the top of the file.


25-25: Security consideration: Server is exposed on all interfaces.

Running on 0.0.0.0 exposes the server to all network interfaces. Consider using 127.0.0.1 for local development or make it configurable.

-    uvicorn.run(create_app(middleware_config=None), host="0.0.0.0", port=8088)
+    uvicorn.run(create_app(middleware_config=None), host="127.0.0.1", port=8088)
pymcp/utils.py (2)

52-69: Enhance error logging for better debugging.

When tool execution fails, logging the full exception traceback would help with debugging.

 except Exception as e:
+    logging.error(f"Error executing tool '{tool_name}': {str(e)}", exc_info=True)
     error = {
         "jsonrpc": "2.0",
         "id": rpc_id,
         "error": {
             "code": -32603,
             "message": f"Error executing tool '{tool_name}': {str(e)}",
         },
     }

10-14: Consider adding session validation.

The function assumes the session exists but doesn't validate it. While the caller should ensure this, defensive programming would add a check.

 async def handle_rpc_method(method, data, session_id, rpc_id, sessions):
     """
     Handle JSON-RPC methods for the MCP server.
     """
+    if session_id not in sessions:
+        logging.error(f"Session {session_id} not found")
+        return
     queue = sessions[session_id]["queue"]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 84be8ec and d6e9e0f.

📒 Files selected for processing (10)
  • README.md (1 hunks)
  • example/config.py (1 hunks)
  • example/run_server.py (2 hunks)
  • example/web-based/run_mcp_with_flask_call.py (1 hunks)
  • guide.md (1 hunks)
  • pymcp/applications.py (1 hunks)
  • pymcp/middleware.py (1 hunks)
  • pymcp/server.py (2 hunks)
  • pymcp/utils.py (1 hunks)
  • tests/test_server.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
example/config.py (1)
pymcp/middleware.py (1)
  • MiddlewareConfig (11-32)
example/run_server.py (1)
pymcp/applications.py (1)
  • create_app (13-24)
pymcp/utils.py (1)
pymcp/registry.py (1)
  • get_tools (34-35)
tests/test_server.py (1)
pymcp/applications.py (1)
  • create_app (13-24)
pymcp/applications.py (1)
pymcp/middleware.py (2)
  • MiddlewareConfig (11-32)
  • setup_middleware (35-55)
example/web-based/run_mcp_with_flask_call.py (2)
pymcp/applications.py (1)
  • create_app (13-24)
pymcp/registry.py (1)
  • register (8-32)
pymcp/server.py (1)
pymcp/utils.py (1)
  • handle_rpc_method (10-83)
🪛 Flake8 (7.2.0)
tests/test_server.py

[error] 14-14: module level import not at top of file

(E402)

pymcp/server.py

[error] 16-16: expected 2 blank lines, found 1

(E302)


[error] 21-21: expected 2 blank lines, found 1

(E302)


[error] 25-25: expected 2 blank lines, found 1

(E302)


[error] 49-49: expected 2 blank lines, found 1

(E302)

🔇 Additional comments (3)
example/config.py (1)

1-20: Well-structured middleware configuration.

The configuration demonstrates good security practices by restricting CORS to specific origins and provides a clear example of how to use the middleware system. The structure is clean and well-documented.

tests/test_server.py (1)

24-24: Good adoption of the new application factory pattern.

The change to use create_app(middleware_config=None) correctly adopts the new application factory pattern and maintains test functionality.

example/run_server.py (1)

44-44: Excellent adoption of the new application factory pattern.

The use of create_app(middleware_config=middleware_config) correctly implements the new architecture and provides clean separation of concerns.

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: 1

♻️ Duplicate comments (1)
pymcp/middleware.py (1)

24-29: Acknowledge past security discussion.

I see the CORS security concern was previously discussed and you mentioned exploring environment-aware configuration later. The current permissive defaults remain a security consideration for production use.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d6e9e0f and c34d04b.

📒 Files selected for processing (10)
  • README.md (1 hunks)
  • example/config.py (1 hunks)
  • example/run_server.py (2 hunks)
  • example/web-based/run_mcp_with_api_call.py (2 hunks)
  • guide.md (1 hunks)
  • pymcp/applications.py (1 hunks)
  • pymcp/middleware.py (1 hunks)
  • pymcp/server.py (3 hunks)
  • pymcp/utils.py (1 hunks)
  • tests/test_server.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (7)
  • example/config.py
  • example/run_server.py
  • pymcp/applications.py
  • README.md
  • pymcp/utils.py
  • guide.md
  • pymcp/server.py
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/test_server.py (1)
pymcp/applications.py (1)
  • create_app (14-25)
🪛 Ruff (0.11.9)
pymcp/middleware.py

57-57: Using hasattr(x, "__call__") to test if x is callable is unreliable. Use callable(x) for consistent results.

Replace with callable()

(B004)

🪛 Flake8 (7.2.0)
tests/test_server.py

[error] 14-14: module level import not at top of file

(E402)

🔇 Additional comments (5)
pymcp/middleware.py (1)

39-60: LGTM - Clean middleware setup implementation.

The setup function properly applies middleware configurations to the FastAPI app. The CORS configuration is applied correctly, compression is conditionally enabled, and custom middleware validation (once fixed) provides good error handling.

example/web-based/run_mcp_with_api_call.py (2)

3-3: LGTM - Correct import for new factory pattern.

The import change from pymcp.server to pymcp.applications.create_app aligns with the new application factory pattern introduced in the refactor.


25-25: LGTM - Proper app instantiation using factory.

The uvicorn.run call correctly uses create_app(middleware_config=None) to create the app instance dynamically, which is consistent with the new architecture.

tests/test_server.py (2)

14-14: Import placement is intentional and correct.

The import is placed after the sys.path manipulation, which is the correct pattern for adding local modules to the path before importing them. The static analysis flag is a false positive in this context.


24-24: LGTM - Test server correctly uses new factory pattern.

The server thread properly uses create_app(middleware_config=None) to create the app instance, ensuring tests use the same application factory pattern as the main application.

@Agent-Hellboy Agent-Hellboy merged commit c101a50 into master Jul 3, 2025
7 checks passed
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.

Basic Enhancement 1

2 participants