fix: add missing HostedMCPServer class for MCP server implementations#816
fix: add missing HostedMCPServer class for MCP server implementations#816MervinPraison merged 8 commits intomainfrom
Conversation
- Created HostedMCPServer base class in mcp/hosted_server.py - Added HostedMCPServer to module exports in __init__.py - Added starlette>=0.27.0 to MCP optional dependencies - Fixes ImportError when using mcp_server_latency_example.py Resolves #813 Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
WalkthroughA new Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant HostedMCPServer
participant FastMCP
participant Starlette
participant Uvicorn
User->>HostedMCPServer: start() or start_async()
HostedMCPServer->>Starlette: create_app()
HostedMCPServer->>FastMCP: initialize MCP server
HostedMCPServer->>Uvicorn: run Starlette app
User->>HostedMCPServer: send request (via SSE or HTTP)
HostedMCPServer->>FastMCP: handle_request()
FastMCP-->>HostedMCPServer: response
HostedMCPServer-->>User: return response
Assessment against linked issues
Possibly related PRs
Suggested labels
Poem
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
@claude review this pull request and do a detailed analysis and fix this if the existing code doesn't have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again use multi agents to review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes. |
There was a problem hiding this comment.
Summary of Changes
Hello @MervinPraison, 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 introduces a new base class for implementing and hosting custom MCP (Multi-Agent Communication Protocol) servers within the praisonaiagents framework. The primary goal is to provide a robust and extensible foundation for server-side MCP operations, addressing a previous import issue and ensuring all necessary dependencies are correctly managed.
Highlights
- New Hosted MCP Server Base Class: Introduced a new abstract base class,
HostedMCPServer, located insrc/praisonai-agents/praisonaiagents/mcp/hosted_server.py. This class provides a foundational structure for building custom MCP servers, including capabilities for handling requests, defining tools, and supporting Server-Sent Events (SSE) transport. - Import Error Fix: Resolved an
ImportErrorthat occurred when attempting to importHostedMCPServerfrom thepraisonaiagents.mcpmodule. This was fixed by explicitly exporting the new class insrc/praisonai-agents/praisonaiagents/mcp/__init__.py. - Dependency Update: Added
starlette>=0.27.0to themcpoptional dependencies insrc/praisonai-agents/pyproject.toml. This ensures that the necessary web framework components for theHostedMCPServerare installed when thepraisonaiagents[mcp]extra is used.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| 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 issue 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 is currently in preview and 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 to provide feedback.
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
-
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. ↩
|
@claude review again and make sure the initial issue gets fixed with minimal code change. |
|
Claude finished @MervinPraison's task —— View job Todo List
Final Review Summary✅ PR Approved with Minor Improvements AppliedThis PR successfully fixes the ImportError from issue #813 by adding the missing Changes Made:
Multi-Agent Review Results:
Verification:
Recommendation:This PR is ready to merge. It provides the minimal fix needed for issue #813 without introducing breaking changes. Future enhancements (auth, better async handling, tests) can be addressed in separate PRs. The implementation provides a solid foundation for creating hosted MCP servers with SSE transport, enabling the example code and other use cases that require server-side MCP functionality. Commit: aaae248 |
|
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here. PR Reviewer Guide 🔍Here are some key observations to aid the review process:
|
|
Claude finished @MervinPraison's task —— View job Code Review SummaryI've thoroughly reviewed this PR to ensure it fixes issue #813 with minimal code changes. Here's my analysis: Todo List
✅ The PR Successfully Fixes the ImportErrorThe changes properly address the missing
📋 Review Findings✅ What's Working Well:
|
|
You are nearing your monthly Qodo Merge usage quota. For more information, please visit here. PR Code Suggestions ✨Explore these optional code suggestions:
|
|||||||||||||
There was a problem hiding this comment.
Code Review
This pull request introduces the HostedMCPServer class to fix an ImportError, providing a base for creating hosted MCP servers. The implementation is a good start, but I've identified a few areas for improvement. My main concerns are a critical bug that will cause a runtime error due to incorrect usage of the Starlette API, and a dependency on a private attribute of an external library, which could be fragile. I've also pointed out an apparently unused method and suggested using standard logging instead of print statements for better integration in larger applications.
| async def handle_sse(request: Request) -> None: | ||
| logger.debug(f"SSE connection from {request.client}") | ||
| async with sse.connect_sse( | ||
| request.scope, | ||
| request.receive, | ||
| request._send, | ||
| ) as (read_stream, write_stream): | ||
| await self._server.run( | ||
| read_stream, | ||
| write_stream, | ||
| self._server.create_initialization_options(), | ||
| ) |
There was a problem hiding this comment.
The handle_sse endpoint uses request._send, but the starlette.requests.Request object does not have a _send attribute. This will cause a runtime AttributeError. For low-level ASGI integrations like this, you should use a raw ASGI endpoint with the signature async def(scope, receive, send) instead of a Starlette Request object. The SseServerTransport.connect_sse method seems to expect the raw ASGI callables.
| async def handle_sse(request: Request) -> None: | |
| logger.debug(f"SSE connection from {request.client}") | |
| async with sse.connect_sse( | |
| request.scope, | |
| request.receive, | |
| request._send, | |
| ) as (read_stream, write_stream): | |
| await self._server.run( | |
| read_stream, | |
| write_stream, | |
| self._server.create_initialization_options(), | |
| ) | |
| async def handle_sse(scope, receive, send): | |
| logger.debug(f"SSE connection from {scope.get('client')}") | |
| async with sse.connect_sse( | |
| scope, | |
| receive, | |
| send, | |
| ) as (read_stream, write_stream): | |
| await self._server.run( | |
| read_stream, | |
| write_stream, | |
| self._server.create_initialization_options(), | |
| ) |
| Starlette application instance | ||
| """ | ||
| if not self._server: | ||
| self._server = self.mcp._mcp_server |
There was a problem hiding this comment.
Accessing the private attribute _mcp_server from the FastMCP instance makes this code fragile. This direct dependency on an internal implementation detail of the mcp library could cause this code to break with future updates to that library. A more robust approach would be to use a public API from FastMCP if one is available. If not, consider adding a comment to acknowledge this technical debt.
| def handle_request(self, request_data: Dict[str, Any]) -> Dict[str, Any]: | ||
| """ | ||
| Handle incoming MCP requests. | ||
|
|
||
| This method can be overridden in subclasses to add custom request handling, | ||
| such as latency tracking, authentication, or request modification. | ||
|
|
||
| Args: | ||
| request_data: The incoming request data | ||
|
|
||
| Returns: | ||
| Response data | ||
| """ | ||
| # Default implementation - can be overridden | ||
| method = request_data.get('method', '') | ||
| request_id = request_data.get('id', 'unknown') | ||
|
|
||
| logger.debug(f"Handling request {request_id}: {method}") | ||
|
|
||
| # Basic response structure | ||
| response = { | ||
| 'id': request_id, | ||
| 'jsonrpc': '2.0', | ||
| 'result': {} | ||
| } | ||
|
|
||
| return response |
| print(f"Starting {self.name} MCP server on {self.host}:{self.port}") | ||
| print(f"Available tools: {', '.join(self._tools.keys())}") | ||
| print(f"SSE endpoint: http://{self.host}:{self.port}/sse") |
There was a problem hiding this comment.
The start method uses print() to output server startup information. For a library, it's better to use the logging module. This gives consumers of your library control over log verbosity and output destination.
| print(f"Starting {self.name} MCP server on {self.host}:{self.port}") | |
| print(f"Available tools: {', '.join(self._tools.keys())}") | |
| print(f"SSE endpoint: http://{self.host}:{self.port}/sse") | |
| logger.info(f"Starting {self.name} MCP server on {self.host}:{self.port}") | |
| logger.info(f"Available tools: {', '.join(self._tools.keys())}") | |
| logger.info(f"SSE endpoint: http://{self.host}:{self.port}/sse") |
| async def start_async(self, debug: bool = False): | ||
| """ | ||
| Start the MCP server asynchronously. | ||
|
|
||
| Args: | ||
| debug: Enable debug mode | ||
| """ | ||
| app = self.create_app(debug=debug) | ||
|
|
||
| config = uvicorn.Config(app, host=self.host, port=self.port) | ||
| server = uvicorn.Server(config) | ||
|
|
||
| print(f"Starting {self.name} MCP server on {self.host}:{self.port}") | ||
| print(f"Available tools: {', '.join(self._tools.keys())}") | ||
|
|
||
| await server.serve() |
There was a problem hiding this comment.
The start_async method is inconsistent with the synchronous start method. It's missing support for **uvicorn_kwargs, uses print() instead of logging, and doesn't log the SSE endpoint. Aligning these would improve consistency and usability.
| async def start_async(self, debug: bool = False): | |
| """ | |
| Start the MCP server asynchronously. | |
| Args: | |
| debug: Enable debug mode | |
| """ | |
| app = self.create_app(debug=debug) | |
| config = uvicorn.Config(app, host=self.host, port=self.port) | |
| server = uvicorn.Server(config) | |
| print(f"Starting {self.name} MCP server on {self.host}:{self.port}") | |
| print(f"Available tools: {', '.join(self._tools.keys())}") | |
| await server.serve() | |
| async def start_async(self, debug: bool = False, **uvicorn_kwargs): | |
| """ | |
| Start the MCP server asynchronously. | |
| Args: | |
| debug: Enable debug mode | |
| **uvicorn_kwargs: Additional arguments to pass to uvicorn | |
| """ | |
| app = self.create_app(debug=debug) | |
| config = uvicorn.Config(app, host=self.host, port=self.port, **uvicorn_kwargs) | |
| server = uvicorn.Server(config) | |
| logger.info(f"Starting {self.name} MCP server on {self.host}:{self.port}") | |
| logger.info(f"Available tools: {', '.join(self._tools.keys())}") | |
| logger.info(f"SSE endpoint: http://{self.host}:{self.port}/sse") | |
| await server.serve() |
There was a problem hiding this comment.
Actionable comments posted: 3
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/praisonai-agents/praisonaiagents/mcp/__init__.py(1 hunks)src/praisonai-agents/praisonaiagents/mcp/hosted_server.py(1 hunks)src/praisonai-agents/pyproject.toml(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`src/praisonai-agents/praisonaiagents/mcp/**/*.py`: Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
src/praisonai-agents/praisonaiagents/mcp/**/*.py: Implement MCP server and SSE support for distributed execution and real-time communication inpraisonaiagents/mcp/.
📄 Source: CodeRabbit Inference Engine (src/praisonai-agents/CLAUDE.md)
List of files the instruction was applied to:
src/praisonai-agents/praisonaiagents/mcp/__init__.pysrc/praisonai-agents/praisonaiagents/mcp/hosted_server.py
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-06-30T10:06:17.673Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
src/praisonai-agents/praisonaiagents/mcp/__init__.py (2)
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-06-30T10:06:17.673Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-ts/.cursorrules:0-0
Timestamp: 2025-06-30T10:05:51.843Z
Learning: Applies to src/praisonai-ts/src/index.ts : The main entry point 'src/index.ts' should re-export key classes and functions (such as 'Agent', 'Agents', 'Task', etc.) for easy import by consumers.
src/praisonai-agents/pyproject.toml (1)
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-06-30T10:06:17.673Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
src/praisonai-agents/praisonaiagents/mcp/hosted_server.py (1)
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-06-30T10:06:17.673Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
🪛 Ruff (0.11.9)
src/praisonai-agents/praisonaiagents/mcp/hosted_server.py
11-11: abc.abstractmethod imported but unused
Remove unused import: abc.abstractmethod
(F401)
12-12: json imported but unused
Remove unused import: json
(F401)
23-26: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
31-31: HostedMCPServer is an abstract base class, but it has no abstract methods or properties
(B024)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Cursor BugBot
🔇 Additional comments (4)
src/praisonai-agents/pyproject.toml (1)
25-26: LGTM!The addition of Starlette dependency is appropriate for the new HostedMCPServer functionality.
src/praisonai-agents/praisonaiagents/mcp/__init__.py (1)
8-10: LGTM!Properly exports the new HostedMCPServer class as part of the MCP package's public API.
src/praisonai-agents/praisonaiagents/mcp/hosted_server.py (2)
87-112: Well-implemented tool registration.The method correctly handles both synchronous and asynchronous functions, properly preserving function metadata.
113-183: Excellent server lifecycle implementation.The server startup methods provide both synchronous and asynchronous options, with proper SSE transport configuration and helpful console output.
| try: | ||
| from mcp.server.fastmcp import FastMCP | ||
| from mcp.server import Server | ||
| from starlette.applications import Starlette | ||
| from starlette.requests import Request | ||
| from starlette.routing import Mount, Route | ||
| from mcp.server.sse import SseServerTransport | ||
| import uvicorn | ||
| except ImportError: | ||
| raise ImportError( | ||
| "MCP server dependencies not installed. " | ||
| "Please install with: pip install praisonaiagents[mcp]" | ||
| ) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Improve exception handling to preserve error context.
Use from err syntax to preserve the original exception context for better debugging.
Apply this diff to improve the error handling:
try:
from mcp.server.fastmcp import FastMCP
from mcp.server import Server
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.routing import Mount, Route
from mcp.server.sse import SseServerTransport
import uvicorn
-except ImportError:
+except ImportError as err:
raise ImportError(
"MCP server dependencies not installed. "
"Please install with: pip install praisonaiagents[mcp]"
- )
+ ) from err📝 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.
| try: | |
| from mcp.server.fastmcp import FastMCP | |
| from mcp.server import Server | |
| from starlette.applications import Starlette | |
| from starlette.requests import Request | |
| from starlette.routing import Mount, Route | |
| from mcp.server.sse import SseServerTransport | |
| import uvicorn | |
| except ImportError: | |
| raise ImportError( | |
| "MCP server dependencies not installed. " | |
| "Please install with: pip install praisonaiagents[mcp]" | |
| ) | |
| try: | |
| from mcp.server.fastmcp import FastMCP | |
| from mcp.server import Server | |
| from starlette.applications import Starlette | |
| from starlette.requests import Request | |
| from starlette.routing import Mount, Route | |
| from mcp.server.sse import SseServerTransport | |
| import uvicorn | |
| except ImportError as err: | |
| raise ImportError( | |
| "MCP server dependencies not installed. " | |
| "Please install with: pip install praisonaiagents[mcp]" | |
| ) from err |
🧰 Tools
🪛 Ruff (0.11.9)
23-26: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
🤖 Prompt for AI Agents
In src/praisonai-agents/praisonaiagents/mcp/hosted_server.py around lines 14 to
26, the ImportError raised in the except block does not preserve the original
exception context. Modify the except block to use "raise ImportError(...) from
err" where "err" is the caught ImportError exception, so the original error
context is preserved for better debugging.
- Remove unnecessary ABC inheritance and unused imports - Add proper error handling for uninitialized MCP server - Improve error messages for better debugging Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
|
@claude possible not to add as a core package, rather add it in the example folder wehre it is referred ? |
|
Claude finished @MervinPraison's task —— View job ✅ Task CompletedI've successfully moved the Changes Made:
Dependencies Note:I kept
This refactoring successfully transforms Branch: claude/issue-813-20250711_070340 |
- Move hosted_server.py to examples/python/custom_tools/ - Update import in mcp_server_latency_example.py to use local file - Remove HostedMCPServer from core package exports This keeps HostedMCPServer as an example implementation rather than a core package component, as requested. Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
- Add hosted_server.py to examples/python/custom_tools/ - Update documentation to clarify this is an example implementation - Keep starlette dependency as it's still used by Agent.launch() for MCP This makes HostedMCPServer an example implementation rather than a core package component. Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
|
@claude dont make any changes to pyproject.toml |
|
Claude finished @MervinPraison's task —— View job Todo List
AcknowledgmentUnderstood! I will not make any changes to The implementation has been successfully moved to the examples folder as requested earlier, and the dependency configuration in pyproject.toml appears to be correctly set up for the core package's needs. |
There was a problem hiding this comment.
Bug: Accessing Private Starlette Request Attributes
The code incorrectly accesses request._send, a private and non-standard attribute of the Starlette Request object. This makes the implementation fragile to Starlette updates and can lead to an AttributeError. The send callable should instead be obtained from the ASGI scope, for example, request.scope["send"].
examples/python/custom_tools/hosted_server.py#L139-L140
PraisonAI/examples/python/custom_tools/hosted_server.py
Lines 139 to 140 in 7cad644
Was this report helpful? Give feedback by reacting with 👍 or 👎
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
examples/python/custom_tools/hosted_server.py (3)
25-28: Improve exception chaining for better debugging.When re-raising exceptions, use
fromsyntax to preserve the original exception context.Apply this improvement:
-except ImportError: +except ImportError as e: raise ImportError( "MCP server dependencies not installed. " "Please install with: pip install praisonaiagents[mcp] starlette>=0.27.0" - ) + ) from e
140-140: Using private request attribute.The code accesses
request._sendwhich is a private attribute. This could break with Starlette updates.Consider using the public API if available, or document why the private attribute access is necessary.
186-188: Missing SSE endpoint in console output.The async start method doesn't print the SSE endpoint URL, unlike the synchronous version. This inconsistency could confuse users.
Add the SSE endpoint to match the sync version:
print(f"Starting {self.name} MCP server on {self.host}:{self.port}") print(f"Available tools: {', '.join(self._tools.keys())}") +print(f"SSE endpoint: http://{self.host}:{self.port}/sse")
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
examples/python/custom_tools/hosted_server.py(1 hunks)examples/python/custom_tools/mcp_server_latency_example.py(1 hunks)src/praisonai-agents/pyproject.toml(2 hunks)
✅ Files skipped from review due to trivial changes (1)
- examples/python/custom_tools/mcp_server_latency_example.py
🚧 Files skipped from review as they are similar to previous changes (1)
- src/praisonai-agents/pyproject.toml
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-06-30T10:06:17.673Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
examples/python/custom_tools/hosted_server.py (1)
Learnt from: CR
PR: MervinPraison/PraisonAI#0
File: src/praisonai-agents/CLAUDE.md:0-0
Timestamp: 2025-06-30T10:06:17.673Z
Learning: Applies to src/praisonai-agents/praisonaiagents/mcp/**/*.py : Implement MCP server and SSE support for distributed execution and real-time communication in `praisonaiagents/mcp/`.
🪛 Ruff (0.11.9)
examples/python/custom_tools/hosted_server.py
14-14: json imported but unused
Remove unused import: json
(F401)
25-28: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling
(B904)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
- GitHub Check: Cursor BugBot
- GitHub Check: Run tests and collect coverage
- GitHub Check: test-core (3.11)
- GitHub Check: quick-test
🔇 Additional comments (6)
examples/python/custom_tools/hosted_server.py (6)
33-60: Well-structured class initialization.The class definition and initialization are properly implemented with clear documentation, appropriate type hints, and sensible defaults.
61-88: Incomplete request handling implementation.The
handle_requestmethod appears to be a stub that doesn't actually process MCP requests or invoke registered tools. While the docstring mentions this can be overridden in subclasses, a base implementation should handle standard MCP protocol requests.Is this intentional as a placeholder for subclasses, or should this method implement actual MCP request handling? For a functional MCP server, this would need to:
- Parse and validate the JSON-RPC request
- Route to appropriate handlers based on the method
- Invoke registered tools when requested
- Return proper responses or errors
89-114: Proper tool registration implementation.The
add_toolmethod correctly handles both synchronous and asynchronous functions, properly wrapping sync functions for async compatibility while preserving metadata.
158-173: Clean server startup implementation.The synchronous start method is well-implemented with helpful console output and flexible uvicorn configuration support.
191-197: Useful utility methods.The getter methods provide clean access to tools list and endpoint URL.
129-131: Avoid relying on private FastMCP internalsI couldn’t find any public accessor for the underlying server in the codebase—using
self.mcp._mcp_serverremains fragile and may break with future FastMCP releases.• File: examples/python/custom_tools/hosted_server.py (lines 129–131)
if not hasattr(self.mcp, '_mcp_server'): raise RuntimeError("MCP server not properly initialized…") self._server = self.mcp._mcp_serverPlease verify with the FastMCP documentation or maintainers whether a supported public API exists to retrieve the server instance. If none is available, consider requesting or contributing a public getter in FastMCP to avoid direct access to private members.
| import asyncio | ||
| import logging | ||
| from typing import Dict, Any, Optional, List, Callable | ||
| import json |
There was a problem hiding this comment.
Remove unused import.
The json module is imported but never used in this file.
Remove the unused import:
-import json📝 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.
| import json |
🧰 Tools
🪛 Ruff (0.11.9)
14-14: json imported but unused
Remove unused import: json
(F401)
🤖 Prompt for AI Agents
In examples/python/custom_tools/hosted_server.py at line 14, the json module is
imported but not used anywhere in the file. Remove the line that imports json to
clean up the code and avoid unnecessary imports.
| """ | ||
| Hosted MCP Server implementation for PraisonAI Agents. | ||
|
|
||
| This module provides a base class for creating hosted MCP servers | ||
| that can handle requests and integrate with the MCP protocol. | ||
|
|
||
| Note: This is an example implementation. To use it, ensure you have installed: | ||
| pip install praisonaiagents[mcp] starlette>=0.27.0 | ||
| """ |
There was a problem hiding this comment.
💡 Verification agent
🧩 Analysis chain
File location doesn't match PR objectives.
According to the PR objectives, the HostedMCPServer class should be added to mcp/hosted_server.py in the core praisonaiagents package to fix the ImportError from praisonaiagents.mcp. However, this file is placed in the examples directory.
The docstring also states "This is an example implementation," which conflicts with the intended purpose of fixing a missing import in the core package.
Should this file be moved to src/praisonai-agents/praisonaiagents/mcp/hosted_server.py as originally intended? This would properly resolve the ImportError mentioned in issue #813.
🏁 Script executed:
#!/bin/bash
echo "Verifying placement of hosted_server.py files"
[ -f examples/python/custom_tools/hosted_server.py ] && echo "✔ examples/python/custom_tools/hosted_server.py exists" || echo "✖ examples/python/custom_tools/hosted_server.py missing"
[ -f src/praisonai-agents/praisonaiagents/mcp/hosted_server.py ] && echo "✔ src/praisonai-agents/praisonaiagents/mcp/hosted_server.py exists" || echo "✖ src/praisonai-agents/praisonaiagents/mcp/hosted_server.py missing"Length of output: 494
Action Required: Move Hosted MCP Server to Core Package & Clean Up Code
Please address the following in hosted_server.py:
-
Relocate the file from
examples/python/custom_tools/hosted_server.py
to
src/praisonai-agents/praisonaiagents/mcp/hosted_server.py
so thatpraisonaiagents.mcpcan import it directly and resolve the existing ImportError. -
Update the module docstring to remove “example implementation” language and describe it as the core
HostedMCPServer. -
Remove the unused
import jsonon line 14. -
Chain the
ImportErrorin your dependency‐check block for better tracebacks:--- old/examples/python/custom_tools/hosted_server.py +++ new/src/praisonai-agents/praisonaiagents/mcp/hosted_server.py try: from praisonaiagents.mcp.protocol import MCPProtocol from starlette.applications import Starlette -except ImportError: - raise RuntimeError("Missing MCP or Starlette dependencies") +except ImportError as e: + raise RuntimeError("Missing MCP or Starlette dependencies") from e
-
Adjust any import paths or references in your test/examples to point to the new location.
These changes will ensure the core package exports the server implementation correctly and improve code quality.
📝 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.
| """ | |
| Hosted MCP Server implementation for PraisonAI Agents. | |
| This module provides a base class for creating hosted MCP servers | |
| that can handle requests and integrate with the MCP protocol. | |
| Note: This is an example implementation. To use it, ensure you have installed: | |
| pip install praisonaiagents[mcp] starlette>=0.27.0 | |
| """ | |
| try: | |
| from praisonaiagents.mcp.protocol import MCPProtocol | |
| from starlette.applications import Starlette | |
| except ImportError as e: | |
| raise RuntimeError("Missing MCP or Starlette dependencies") from e |
User description
This PR fixes the ImportError when trying to import HostedMCPServer from praisonaiagents.mcp.
Changes
Resolves #813
Generated with Claude Code
PR Type
Bug fix
Description
Add missing
HostedMCPServerclass to fix ImportErrorImplement base class for hosted MCP servers
Add starlette dependency for SSE transport
Export new class in module
__init__.pyChanges diagram
Changes walkthrough 📝
__init__.py
Export HostedMCPServer class in modulesrc/praisonai-agents/praisonaiagents/mcp/init.py
HostedMCPServerfromhosted_servermoduleHostedMCPServerto__all__exports listhosted_server.py
Implement HostedMCPServer base classsrc/praisonai-agents/praisonaiagents/mcp/hosted_server.py
HostedMCPServerabstract base classpyproject.toml
Add starlette dependency for MCPsrc/praisonai-agents/pyproject.toml
starlette>=0.27.0to MCP optional dependenciesSummary by CodeRabbit
New Features
Chores