Pytest MCP 서비스
패키지 상태
로컬 컴파일된 소스가 아닌, 게시된 npm 패키지(@modelcontextprotocol/mcp-pytest-server)를 실행하고 있습니다. 이는 다음 방법을 통해 확인되었습니다.
- 실행 파일 경로: ~/.npm/_npx/15b07286cbcc3329/node_modules/.bin/mcp-server-memory
- 바이너리를 지정하는 package.json 구성은 dist/index.js로 빌드되어야 합니다.
- npm 글로벌 캐시에 존재
참고로 Python SDK 릴리스는 https://github.com/modelcontextprotocol/python-sdk/tags 에서 확인할 수 있습니다.
로그 보기
서버 출력과 로그를 보려면:
- 서버가 실행 중인 라이브 터미널 출력을 확인하세요.
- ~/workspace/mcp-pytest-server/output.log에서 로그 파일을 확인하세요.
- tail을 사용하면 실시간으로 통나무를 따라갈 수 있습니다.지엑스피1
- 과거 기록의 경우 less 또는 cat을 사용하세요.
less ~/workspace/mcp-pytest-server/output.log
cat ~/workspace/mcp-pytest-server/output.log
시작하기
필수 조건
- Node.js v16 이상
- Python 3.8 이상
- npm 설치됨
- 메모리 서비스(@modelcontextprotocol/server-memory)가 실행 중입니다(백그라운드 실행에는 uvx를 사용하는 것이 좋습니다):
- uvx 설치:
npm install -g uvx
- uvx 구성(uvx.config.js)을 생성합니다.
module.exports = {
services: {
memory: {
command: 'node ~/.npm/_npx/15b07286cbcc3329/node_modules/.bin/mcp-server-memory',
autorestart: true,
log: 'memory.log',
env: {
NODE_ENV: 'production'
}
}
}
}
- 서비스 시작:
uvx start memory
mcp-pytest-server 개발 전용 설치
프로젝트 디렉토리로 이동
cd ~/workspace/mcp-pytest-server
JavaScript 종속성 설치
npm install @modelcontextprotocol/sdk
npm install
MCP Pytest 서버 시작
MCP 통합으로 Pytest 실행
검사 서비스
메모리 서비스 검사
메모리 서비스를 검사하려면:
- 디버그 모드에서 서비스를 시작합니다.
npx --node-options='--inspect' @modelcontextprotocol/server-memory
- chrome://inspect에서 Chrome DevTools를 엽니다.
- "Node용 전용 DevTools 열기"를 클릭하세요.
- 중단점을 설정하고 서비스 실행을 검사합니다.
또는 VSCode의 기본 제공 Node.js 디버깅을 사용하세요.
- launch.json 구성을 만듭니다.
{
"type": "node",
"request": "launch",
"name": "Debug Memory Service",
"runtimeExecutable": "npx",
"runtimeArgs": ["@modelcontextprotocol/server-memory"],
"args": [],
"console": "integratedTerminal"
}
개발 중 MCP-Pytest 서비스 검사
mcp-pytest 서비스를 검사하려면:
- 디버그 모드에서 서비스를 시작합니다.
node --inspect ~/workspace/mcp-pytest-server/index.js
- chrome://inspect에서 Chrome DevTools를 엽니다.
- "Node용 전용 DevTools 열기"를 클릭하세요.
- 중단점을 설정하고 서비스 실행을 검사합니다.
또는 VSCode의 기본 제공 Node.js 디버깅을 사용하세요.
- launch.json 구성을 만듭니다.
{
"type": "node",
"request": "launch",
"name": "Debug MCP-Pytest Service",
"program": "${workspaceFolder}/index.js",
"console": "integratedTerminal"
}
아키텍처 및 구현
개요
MCP pytest 통합은 여러 구성 요소로 구성됩니다.
- mcp-pytest-server : MCP 서비스 도구를 구현하는 Node.js 서버
- conftest.py : pytest를 MCP 서비스와 통합하는 테스트 구성
- SDK : MCP 통합을 위한 JavaScript 및 Python SDK
구성 요소 세부 정보
mcp-pytest-server(자바스크립트)
- 위치: ~/workspace/mcp-pytest-server
- 구현: Node.js(index.js)
- 상태: 게시된 npm 패키지 실행 중(로컬로 컴파일되지 않음)
- 패키지 상태: npm에 '@modelcontextprotocol/mcp-pytest-server'로 게시됨
- 실행 경로: ~/.npm/_npx/15b07286cbcc3329/node_modules/.bin/mcp-server-memory(게시된 패키지 사용 확인)
- 기능: PyTest 통합을 위한 MCP 서비스 도구 제공
conftest.py(파이썬)
- 위치: ~/workspace/textgrad/tests/conftest.py
- 목적: MCP 서비스와 통합하기 위해 pytest를 구성합니다.
- 현재 상태: ~/workspace/mcp-pytest-server/python-sdk에서 Python SDK를 성공적으로 사용 중
SDKs
자바스크립트 SDK
파이썬 SDK
- 위치: ~/workspace/mcp-pytest-server/python-sdk
- 패키지 상태: 어떤 패키지 관리자(PyPI, Conda 등)에도 게시되지 않음
- 사용법: pytest 통합을 통해 내부적으로 사용됨
- 구현: MCP 통합을 위한 Python 클라이언트 제공
- 여러 프로젝트 설치:
- 패키지 디렉토리로 이동합니다: cd ~/workspace/mcp-pytest-server/python-sdk
- 개발 모드로 설치: pip install -e .
- 이제 이 패키지는 시스템의 모든 Python 프로젝트에서 사용할 수 있습니다.
- 업데이트하려면 저장소에서 최신 변경 사항을 가져오기만 하면 됩니다.
구현 상태
세 가지 도구(record_session_start, record_test_outcome, record_session_finish)의 핵심 기능은 index.js에 구현되어 있습니다. 구현 내용은 다음과 같습니다.
구현 상태: 세 가지 도구(record_session_start, record_test_outcome, record_session_finish)의 핵심 기능이 index.js에 구현되었습니다. 구현 내용은 다음과 같습니다.
- 모든 도구에 대한 입력 검증
- 적절한 오류 처리 및 로깅
- 도구 등록 및 요청 처리
- 기본 응답 생성
1. record_session_start
[구현됨]
설명: 이 도구는 pytest 세션 시작 시 호출됩니다. memory
MCP 서버에 "TestRun_Latest" 및 "Env_Current" 엔티티를 생성하거나 업데이트하여 현재 테스트 실행의 컨텍스트를 초기화합니다. 중요한 점은 이 도구가 "TestRun_Latest"와 관련된 이전 테스트 실행의 모든 데이터를 삭제하여 마지막 실행에 대한 단일 진실 소스(SSO)를 유지한다는 것입니다.
구현 세부 정보:
- environment.os 및 environment.python_version에 대한 입력 검증
- 환경 세부 정보를 포함한 기본 응답 생성
- 잘못된 매개변수에 대한 오류 처리
입력 스키마:
{
"environment": {
"os": "string",
"python_version": "string"
}
}
**Example Usage:**
mcp 호출 pytest-mcp record_session_start '{"environment": {"os": "Macos", "python_version": "3.13.1"}}'
Expected Behavior:
Clear Previous Data: Deletes the "TestRun_Latest" entity and any relations where "TestRun_Latest" is the from or to entity from the memory MCP server. This ensures no accumulation of historical data.
Create "Env_Current" Entity: Creates an entity named "Env_Current" with the entity type "TestEnvironment" and observations for the operating system and Python version.
Create "TestRun_Latest" Entity: Creates an entity named "TestRun_Latest" with the entity type "TestRun" and an initial observation like "status: running".
Create Relation: Creates a relation of type "ran_on" from "TestRun_Latest" to "Env_Current".
Example Interaction (run in cline window):
use_mcp_tool pytest-mcp record_session_start '{"환경": {"os": "Macos", "python_version": "3.13.1"}}'
## 2. record_test_outcome [IMPLEMENTED]
Description:
This tool is called after each individual test case has finished executing. It records the outcome of the test (passed, failed, skipped), its duration, and any error information if the test failed.
**Implementation Details:**
- Input validation for nodeid, outcome, duration, and optional error
- Basic response generation with test outcome details
- Error handling for invalid parameters
Input Schema:
{ "nodeid": "문자열", "outcome": "문자열(통과|실패|건너뜀)", "duration": "숫자", "error": "문자열(선택 사항)" }
Expected Behavior:
Create/Update TestCase Entity: Creates or updates an entity with the name matching the nodeid (e.g., "test_module.py::test_function"), setting its entity type to "TestCase".
Add Outcome Observation: Adds an observation with the format "outcome: <outcome>" to the TestCase entity.
Add Duration Observation: Adds an observation with the format "duration: <duration>" to the TestCase entity.
Add Error Observation (if applicable): If the outcome is "failed" and the error field is provided, add an observation with the format "error: <error>" to the TestCase entity.
Create Relation: Creates a relation of type "contains_test" from "TestRun_Latest" to the TestCase entity.
Example Interaction (run in cline window):
use_mcp_tool pytest-mcp record_test_outcome '{"nodeid": "test_module.py_example", "outcome": "통과", "기간": 0.123}' use_mcp_tool pytest-mcp record_test_outcome '{"nodeid": "test_module.py_failure", "outcome": "실패", "기간": 0.05, "오류": "AssertionError: ... "}'
## 3. record_session_finish [IMPLEMENTED]
Description:
This tool is called at the end of a pytest session. It records summary information about the entire test run, such as the total number of tests, the counts of passed, failed, and skipped tests, and the exit status of the pytest process. It also updates the status of the "TestRun_Latest" entity to "finished".
**Implementation Details:**
- Input validation for summary object
- Basic response generation with session summary
- Error handling for invalid parameters
Input Schema:
{ "summary": { "total_tests": "integer", "passed": "integer", "failed": "integer", "skipped": "integer", "exitstatus": "integer" } }
Expected Behavior:
Update TestRun_Latest Status: Updates the "TestRun_Latest" entity's observation "status: running" to "status: finished".
Add Summary Observations: Adds observations to the "TestRun_Latest" entity for total_tests, passed, failed, skipped, and exitstatus based on the input summary.
Add End Time Observation: Adds an observation with the format "end_time: <timestamp>" to the "TestRun_Latest" entity.
Example Interaction (run in cline window):
use_mcp_tool pytest-mcp record_session_finish '{"summary": {"total_tests": 10, "passed": 7, "failed": 2, "skipped": 1, "exitstatus": 0}}'
노드 ~/workspace/mcp-pytest-server/index.js
ps aux | grep index.js sudo tcpdump -i any -s 0 -w mcp_traffic.pcap port <포트 번호>
use_pytest-mcp
#Development
Suggested Optimizations:
## Faster JSON
Use a Faster JSON Library: Replace the built-in json module with orjson for faster parsing and serialization.
import orjson as json
## Dispatch mechanism
Implement a Dispatch Mechanism: Use dictionaries to map request types and tool names to handler functions.
def handle_list_tools(request):
# ...
def handle_record_session_start(args):
# ...
# ... other tool handlers ...
request_handlers = {
"list_tools": handle_list_tools,
"call_tool": {
"record_session_start": handle_record_session_start,
# ... other tools ...
}
}
def handle_request(request):
request_type = request["type"]
handler = request_handlers.get(request_type)
if handler:
if request_type == "call_tool":
tool_name = request["name"]
tool_handler = handler.get(tool_name)
if tool_handler:
tool_handler(request["arguments"])
else:
send_response({"type": "error", "code": -32601, "message": f"Unknown tool: {tool_name}"})
else:
handler(request)
else:
send_response({"type": "error", "code": -32601, "message": f"Unknown request type: {request_type}"})
## Concurrency
Concurrency: Explore using asynchronous programming (e.g., asyncio) or threading to handle multiple requests concurrently. This would require more significant changes to the server's structure.
## Python SDK Implementation Summary
### Current Status
- Python SDK package structure created at ~/workspace/mcp-pytest-server/python-sdk
- Basic package files implemented:
- setup.py with package configuration
- src/mcp/__init__.py with version information
- Package successfully installed in development mode using pip install -e .
- PYTHONPATH configuration verified to allow package import
- Currently running as a development installation with full source access
- Service level: Development/Testing (not production-ready)
### Service Level Details
- **Development Mode**: Running with pip install -e . allows for immediate code changes without reinstallation
- **Source Access**: Full access to source code for debugging and development
- **Dependencies**: Managed through setup.py with direct access to local development environment
- **Stability**: Suitable for testing and development, not recommended for production use
- **Performance**: May include debug logging and unoptimized code paths
### Remaining Tasks
- Implement core MCP client functionality in Python SDK
- Add pytest integration hooks
- Create proper test suite for Python SDK
- Publish package to PyPI for easier distribution
- Optimize for production deployment