MCP Pytest Server

local-only server

The server can only run on the client’s local machine because it depends on local resources.

Integrations

  • Allows integration with pytest for test automation, including recording test session starts, test outcomes, and session finishes. The integration enables pytest to use the MCP service tools through a conftest.py configuration.

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

ログの表示

サーバーの出力とログを表示するには:

  1. サーバーが稼働しているライブターミナル出力を表示する
  2. ~/workspace/mcp-pytest-server/output.log のログファイルを確認します。
  3. ログをリアルタイムで追跡するには、tail を使用します。
    tail -f ~/workspace/mcp-pytest-server/output.log
  4. 履歴ログの場合は、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 を使用することをお勧めします):
    1. uvxをインストールします: npm install -g uvx
    2. 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' } } } }
    3. サービスを開始: uvx start memory

mcp-pytest-server 開発のみのインストール

プロジェクトディレクトリに移動する

cd ~/workspace/mcp-pytest-server

JavaScript依存関係をインストールする

npm install @modelcontextprotocol/sdk npm install

MCP Pytestサーバーを起動する

node index.js

MCP統合でPytestを実行する

pytest --mcp

検査サービス

メモリサービスの検査

メモリ サービスを検査するには:

  1. デバッグモードでサービスを開始します。
    npx --node-options='--inspect' @modelcontextprotocol/server-memory
  2. chrome://inspect で Chrome DevTools を開きます。
  3. 「Node専用のDevToolsを開く」をクリックします
  4. ブレークポイントを設定してサービスの実行を検査する

あるいは、VSCode に組み込まれている Node.js デバッグを使用します。

  1. launch.json 構成を作成します。
{ "type": "node", "request": "launch", "name": "Debug Memory Service", "runtimeExecutable": "npx", "runtimeArgs": ["@modelcontextprotocol/server-memory"], "args": [], "console": "integratedTerminal" }

開発中のMCP-Pytestサービスの検査

mcp-pytest サービスを検査するには:

  1. デバッグモードでサービスを開始します。
    node --inspect ~/workspace/mcp-pytest-server/index.js
  2. chrome://inspect で Chrome DevTools を開きます。
  3. 「Node専用のDevToolsを開く」をクリックします
  4. ブレークポイントを設定してサービスの実行を検査する

あるいは、VSCode に組み込まれている Node.js デバッグを使用します。

  1. launch.json 構成を作成します。
{ "type": "node", "request": "launch", "name": "Debug MCP-Pytest Service", "program": "${workspaceFolder}/index.js", "console": "integratedTerminal" }

アーキテクチャと実装

概要

MCP pytest 統合は複数のコンポーネントで構成されています。

  1. mcp-pytest-server : MCP サービスツールを実装した Node.js サーバー
  2. conftest.py : pytest を MCP サービスと統合するテスト構成
  3. SDK : MCP 統合用の JavaScript と Python の両方の SDK

コンポーネントの詳細

mcp-pytest-server (JavaScript)

  • 場所: ~/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 (Python)

  • 場所: ~/workspace/textgrad/tests/conftest.py
  • 目的: pytest を MCP サービスと統合するように設定する
  • 現在の状態: ~/workspace/mcp-pytest-server/python-sdk から Python SDK を正常に使用しています

SDK

JavaScript SDK

  • 場所: https://github.com/modelcontextprotocol/typescript-sdk
  • パッケージステータス: npm で '@modelcontextprotocol/sdk' として公開されています
  • 使用方法: npm install @modelcontextprotocol/sdk でインストールできます
  • 実装: MCP 統合用の TypeScript/JavaScript クライアントを提供します

Python SDK

  • 場所: ~/workspace/mcp-pytest-server/python-sdk
  • パッケージのステータス: どのパッケージ マネージャー (PyPI、Conda など) でも公開されていません
  • 使用法: pytest統合によって内部的に使用される
  • 実装: MCP 統合用の Python クライアントを提供する
  • 複数のプロジェクトへのインストール:
    1. パッケージディレクトリに移動します: cd ~/workspace/mcp-pytest-server/python-sdk
    2. 開発モードでインストールします: pip install -e 。
    3. パッケージはシステム上のすべてのPythonプロジェクトで利用できるようになります。
    4. 更新するには、リポジトリから最新の変更をプルするだけです

実施状況

3つのツール(record_session_start、record_test_outcome、record_session_finish)のコア機能はindex.jsに実装されています。実装内容は次のとおりです。

実装状況: 3つのツール(record_session_start、record_test_outcome、record_session_finish)のコア機能がindex.jsに実装されました。実装内容は以下のとおりです。

  • すべてのツールの入力検証
  • 適切なエラー処理とログ記録
  • ツールの登録とリクエストの処理
  • 基本的な応答生成

1. record_session_start [実装済み]

**説明:**このツールは、pytestセッションの開始時に呼び出されます。 memory MCPサーバーに「TestRun_Latest」および「Env_Current」エンティティを作成または更新することで、現在のテスト実行のコンテキストを初期化します。重要な点として、このツールは「TestRun_Latest」に関連付けられた以前のテスト実行のデータをすべてクリアし、最後の実行に関する唯一の信頼できる情報源を維持することも保証します。

実装の詳細:

  • 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": "passed", "duration": 0.123}' use_mcp_tool pytest-mcp record_test_outcome '{"nodeid": "test_module.py_failure", "outcome": "failed", "duration": 0.05, "error": "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}}'

## Debugging the service

ノード ~/ワークスペース/mcp-pytest-server/index.js

ps aux | grep index.js sudo tcpdump -i any -s 0 -w mcp_traffic.pcap port <ポート番号>

cline

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