MAGI MCP 서버
MAGI 코드 검토 시스템을 위한 MCP 서버 구현. 이 서버는 모델 컨텍스트 프로토콜(MCP)을 사용하여 코드 검토를 제출하고 진행 상황을 모니터링하기 위한 표준화된 인터페이스를 제공합니다.
특징
- 코드 제출 및 검토 오케스트레이션
- 분산 코드 검토를 위한 MAGI Gateway와의 통합
- Melchior, Balthasar 및 Casper 에이전트를 포함하는 다중 에이전트 검토 시스템
- 코드 품질 평가를 위한 다수결 기반 의사 결정
시작하기
필수 조건
- 파이썬 3.11+
- MAGI Gateway에 접속(기본값: ws://127.0.0.1:8000/ws)
- Docker(컨테이너화된 배포를 위한 선택 사항)
설치
- 저장소를 복제합니다
- 종속성 설치:지엑스피1
용법
이 프로젝트는 두 가지 주요 구성 요소로 구성됩니다.
- MCP 서버(
src/server.py
) - 코드 검토를 위한 MCP 프로토콜을 구현합니다. - 테스트 클라이언트(
src/client.py
) - 서버 기능을 테스트하기 위한 간단한 클라이언트
서버 실행
기본적으로 서버는 ws://127.0.0.1:8000/ws
의 MAGI Gateway에 연결합니다. MAGI_URL
환경 변수를 설정하여 이 설정을 재정의할 수 있습니다.
MAGI_URL=ws://your-magi-gateway.com/ws python -m src.server
참고: MAGI 시스템 공식 게이트웨이를 사용할 수 있습니다: ws://magisystem.ai/ws
도커 배포
Docker를 사용하여 MAGI MCP SSE 서버를 배포할 수도 있습니다.
- Docker 이미지를 빌드합니다.
docker build -t magi-mcp-server .
- 컨테이너를 실행합니다.
docker run -p 8080:8080 magi-mcp-server
- 특정 MAGI Gateway에 연결하려면:
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 Gateway 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 Gateway 간의 브리지 역할을 합니다.
Test Client <-> MCP Server <-> MAGI Gateway <-> Review Agents (Melchior, Balthasar, Casper)
검토 과정:
- 클라이언트가 MCP 서버에 코드를 제출합니다.
- 서버는 코드를 MAGI Gateway로 전달합니다.
- MAGI Gateway는 3명의 리뷰 에이전트에게 코드를 배포합니다.
- 각 에이전트는 코드를 검토하고 긍정적 또는 부정적 결정을 내립니다.
- 최종 결정은 다수결 투표에 따라 결정됩니다(최소 2개의 긍정적인 리뷰가 통과해야 함)
- 결과는 클라이언트에게 반환됩니다.
개발
개발 목적으로 디버그 로깅을 활성화할 수 있습니다.
DEBUG=1 python -m src.server
또는 클라이언트를 사용하는 경우:
python -m src.client --file my_code.py --debug
특허
MIT 라이센스