MAGI MCP 服务器
MAGI 代码审查系统的 MCP 服务器实现。该服务器提供了一个标准化接口,用于提交代码审查并使用模型上下文协议 (MCP) 监控其进度。
特征
- 代码提交和审查编排
- 与 MAGI Gateway 集成以进行分布式代码审查
- 包含 Melchior、Balthasar 和 Casper 代理的多代理审查系统
- 基于多数原则的代码质量评估决策
入门
先决条件
- Python 3.11+
- 访问 MAGI 网关(默认:ws://127.0.0.1:8000/ws)
- Docker(可选,用于容器化部署)
安装
- 克隆存储库
- 安装依赖项:
pip install -r requirements.txt
用法
该项目由两个主要部分组成:
- MCP 服务器 (
src/server.py
) - 实现 MCP 协议进行代码审查 - 测试客户端(
src/client.py
)- 用于测试服务器功能的简单客户端
运行服务器
默认情况下,服务器连接到 MAGI 网关的ws://127.0.0.1:8000/ws
。您可以通过设置MAGI_URL
环境变量来覆盖此设置:
MAGI_URL=ws://your-magi-gateway.com/ws python -m src.server
注:您可以使用 MAGI 系统官方网关: ws://magisystem.ai/ws
Docker 部署
您还可以使用 Docker 部署 MAGI MCP SSE 服务器:
- 构建 Docker 镜像:
docker build -t magi-mcp-server .
- 运行容器:
docker run -p 8080:8080 magi-mcp-server
- 要连接到特定的 MAGI 网关:
docker run -p 8080:8080 -e MAGI_URL=ws://your-magi-gateway.com/ws magi-mcp-server
- 要在调试模式下运行:
docker run -p 8080:8080 -e DEBUG=1 magi-mcp-server
与客户端一起测试
client.py
脚本仅供测试使用,用于验证 MCP 服务器的功能。本脚本不适用于生产环境。
python -m src.client --file path/to/your/code.py
客户端选项
--file
, -f
:要审查的 Python 文件的路径--magi-url
:MAGI 网关 WebSocket URL(默认值:ws://127.0.0.1:8000/ws)--server-script
:服务器脚本的路径(默认值:src/server.py)--timeout
:审核超时时间(秒)(默认值:300)--output
, -o
:将结果保存到 JSON 文件--debug
:启用调试模式
如果没有提供文件,客户端将使用示例代码片段进行测试。
例子
# Review a specific Python file
python -m src.client --file my_code.py
# Save review results to a file
python -m src.client --file my_code.py --output review_results.json
# Use a custom MAGI Gateway
python -m src.client --file my_code.py --magi-url ws://custom-gateway:8000/ws
例子
(base) ➜ mcp-magi git:(main) ✗ python src/client.py
2025-03-03 03:24:45,320 - magi-client - INFO - Creating MAGIClient...
2025-03-03 03:24:45,321 - magi-client - INFO - Using server script: /workspace/mcp-magi/src/server.py
2025-03-03 03:24:45,321 - magi-client - INFO - MAGI URL: ws://127.0.0.1:8000/ws
🚀 Starting MAGI Code Review...
2025-03-03 03:24:45,321 - magi-client - INFO - Starting code review...
2025-03-03 03:24:45,321 - magi-client - INFO - Starting stdio client...
2025-03-03 03:24:45,327 - magi-client - INFO - Initializing client session...
2025-03-03 03:24:45,564 - magi-client - INFO - Session initialized successfully
2025-03-03 03:24:45,565 - magi-client - INFO - Calling code_review tool...
INFO:mcp.server.lowlevel.server:Processing request of type CallToolRequest
WARNING:__main__:Received response for different request ID: None
WARNING:__main__:Received response for different request ID: None
2025-03-03 03:24:55,501 - magi-client - INFO - Code review completed successfully
2025-03-03 03:24:55,555 - magi-client - INFO - Review completed, printing results...
==================================================
MAGI CODE REVIEW RESULTS
==================================================
🎯 Final Decision: NEGATIVE
✅ Passed: False
📝 Detailed Reviews:
--------------------------------------------------
Reviewer melchior: I'll analyze this code from an architectural perspective.
Architectural Review:
1. Code Organization:
- The code follows a basic modular structure with separate function definitions
- There's a clear entry point with the `if __name__ == "__main__"` idiom
- Functions have single responsibilities, which aligns with SOLID principles
2. Design Patterns:
- The code implements a simple procedural pattern
- While basic, it demonstrates separation of concerns between calculation and program execution
3. Component Interactions:
- Clear data flow between functions
- Simple and predictable function interfaces
- Low coupling between components
4. Scalability & Maintainability:
- The code is easily maintainable due to its simplicity
- The `calculate_sum` function is reusable and independent
- Could benefit from type hints for better maintainability
- No error handling mechanisms in place
Recommendations:
1. Add type hints:
\```python
def calculate_sum(numbers: list[int]) -> int:
\```
2. Consider adding input validation
3. Could be enhanced with a proper exception handling strategy
4. Consider implementing an interface or class structure for more complex scenarios
<decision>POSITIVE</decision>
While the code is very basic, it follows good architectural principles:
- Clear separation of concerns
- Single responsibility principle
- Good modularization
- Clean interface between components
The code provides a solid foundation that could be easily extended while maintaining its architectural integrity. The simplicity here is actually a strength, as it doesn't over-engineer a straightforward solution.
Reviewer balthasar: I'll analyze this Python code from a security and stability perspective:
Security Analysis:
1. Input Validation:
- No input validation is performed on the 'numbers' parameter
- Could potentially accept non-numeric values leading to TypeErrors
- No bounds checking for potential integer overflow
2. Error Handling:
- No exception handling mechanisms
- Could crash if invalid input is provided
- No logging of errors or unexpected behavior
3. Data Protection:
- No sensitive data handling concerns in this simple example
- Variables are appropriately scoped
4. Stability Issues:
- No type hints to ensure correct input types
- No protection against large input arrays that could cause memory issues
Recommended Improvements:
\```python
from typing import List, Union
import logging
def calculate_sum(numbers: List[Union[int, float]]) -> Union[int, float]:
try:
if not numbers:
return 0
if not all(isinstance(x, (int, float)) for x in numbers):
raise TypeError("All elements must be numbers")
return sum(numbers)
except Exception as e:
logging.error(f"Error in calculate_sum: {str(e)}")
raise
def main() -> None:
try:
numbers = [1, 2, 3, 4, 5]
result = calculate_sum(numbers)
print(f"The sum is: {result}")
except Exception as e:
print(f"An error occurred: {str(e)}")
\```
While the original code is functional for basic use cases, it lacks important security and stability features that would make it production-ready.
<decision>NEGATIVE</decision>
Reasons for negative decision:
1. Missing input validation
2. No error handling
3. No type checking
4. No logging mechanism
5. Potential for uncaught exceptions
The code needs significant improvements to meet security and stability standards for production use. While it may work for simple cases, it's not robust enough for handling edge cases or potential misuse.
Reviewer casper: I'll review this Python code focusing on functionality, implementation, and user experience aspects.
Code Review:
1. Functionality and Completeness:
- The code successfully implements a basic sum calculation function
- The main structure is properly organized with separate functions
- Includes proper `if __name__ == "__main__":` entry point
- Basic functionality is complete for the intended purpose
2. User Experience:
- Output message is clear and descriptive ("The sum is: ")
- However, lacks input validation for non-numeric values
- No error handling for empty lists or invalid inputs
- Could benefit from user interaction rather than hardcoded values
3. Performance and Efficiency:
- The implementation is simple and straightforward
- For small lists, the performance is acceptable
- Could use built-in `sum()` function for better performance
- Memory usage is minimal and efficient
4. Implementation Best Practices:
- Good function naming conventions
- Clear code structure
- Missing docstrings for function documentation
- No type hints which could improve code clarity
Suggestions for Improvement:
\```python
def calculate_sum(numbers: list[float]) -> float:
"""Calculate the sum of numbers in a list.
Args:
numbers: List of numbers to sum
Returns:
float: Sum of all numbers
Raises:
ValueError: If list is empty or contains non-numeric values
"""
if not numbers:
raise ValueError("List cannot be empty")
return sum(numbers)
def main():
try:
numbers = [float(x) for x in input("Enter numbers separated by space: ").split()]
result = calculate_sum(numbers)
print(f"The sum is: {result}")
except ValueError as e:
print(f"Error: {e}")
if __name__ == "__main__":
main()
\```
<decision>POSITIVE</decision>
The code is fundamentally sound and achieves its basic purpose. While there's room for improvement in terms of error handling, user interaction, and documentation, the current implementation is functional and follows basic programming principles. The positive decision is based on the code's correct functionality and clear structure, though implementing the suggested improvements would make it more robust and user-friendly.
🤖 MAGI Agents State:
--------------------------------------------------
🔹 MELCHIOR:
Decision: NEGATIVE
Content: I'll analyze this code from an architectural perspective.
Architectural Review:
1. Code Organization:
- The code follows a basic modular structure with separate function definitions
- There's a clea...
🔹 BALTHASAR:
Decision: NEGATIVE
Content: I'll analyze this Python code from a security and stability perspective:
Security Analysis:
1. Input Validation:
- No input validation is performed on the 'numbers' parameter
- Could potentially acce...
🔹 CASPER:
Decision: NEGATIVE
Content: I'll review this Python code focusing on functionality, implementation, and user experience aspects.
Code Review:
1. Functionality and Completeness:
- The code successfully implements a basic sum ca...
✨ Review completed successfully!
建筑学
服务器充当 MCP 客户端和 MAGI 网关之间的桥梁:
Test Client <-> MCP Server <-> MAGI Gateway <-> Review Agents (Melchior, Balthasar, Casper)
审核流程:
- 客户端向 MCP 服务器提交代码
- 服务器将代码转发到 MAGI 网关
- MAGI Gateway 将代码分发给三个审核代理
- 每个代理审查代码并提供积极或消极的决定
- 最终决定基于多数票(至少 2 条正面评价才能通过)
- 结果返回给客户端
发展
出于开发目的,您可以启用调试日志记录:
DEBUG=1 python -m src.server
或者使用客户端时:
python -m src.client --file my_code.py --debug
执照
MIT 许可证