hil-mcp-server

mokafari/hil-mcp-server

3.2

If you are the rightful owner of hil-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

This MCP server is designed for BMS HIL testing, providing a structured API for intelligent test automation and system interaction.

Tools
5
Resources
0
Prompts
0

MCP Server for BMS HIL Testing

This MCP (Model Context Protocol) server exposes the BMS HIL test infrastructure to LLMs, enabling intelligent test automation, debugging, and system interaction through a safe, structured API.

Overview

The MCP server provides a comprehensive interface to:

  • Hardware Status Queries: Read operational status, contactor states, voltages, temperatures, errors
  • Controlled Hardware Control: Set voltages, temperatures, currents with validation
  • Safety-Critical Operations: Power cycling, contactor control, E-stop (with confirmation)
  • Test Discovery & Execution: Discover, filter, and run pytest tests
  • Ad-Hoc Test Sequences: Construct and execute custom test sequences for debugging

Installation

  1. Install MCP dependencies:
pip install -r requirements_mcp.txt
  1. Ensure all project dependencies are installed:
pip install -r requirements.txt

Running the Server

The server uses stdio transport for IDE integration:

python -m mcp_server.server

For IDE integration (e.g., Cursor), configure the MCP server in your IDE settings:

{
  "mcpServers": {
    "bms-hil": {
      "command": "C:/SW/BMS_QA_HIL/mcp_server/venv/Scripts/python.exe",
      "args": ["-m", "mcp_server.server"],
      "cwd": "C:/SW/BMS_QA_HIL"
    }
  }
}

Note: See CURSOR_SETUP.md for detailed setup instructions and troubleshooting.

Tool Categories

Tier 1: Status Tools (Read-Only)

Safe read-only operations that do not modify hardware state:

  • get_operational_status - Get current operational status
  • get_connection_status - Get connection state
  • get_contactor_statuses - Get all contactor states
  • read_errors - Read active error codes
  • read_errors_with_names - Read errors with human-readable names
  • get_sensed_cell_voltages - Read all cell voltages
  • get_cell_temperatures - Read all temperature sensors
  • get_pack_current - Read current sensor value
  • get_system_info - Get system role, IP, versions
  • read_rtdb - Read RTDB value by ID
  • get_software_versions - Get ACO/SCO/SBMS versions

Tier 2: Control Tools (Controlled Writes)

Operations with validation and range checking:

  • set_cell_voltage - Set voltage on specific cell (0-5V)
  • set_all_cell_voltages - Set all cells to same voltage
  • set_cell_temperature - Set temperature on specific NTC (-40 to 85°C)
  • set_all_temperatures - Set all temperatures
  • set_pack_current - Set pack current simulation
  • set_system_role - Switch master/slave role
  • write_rtdb - Write RTDB value (with validation)
  • parametrize_rtdb - Parametrize RTDB value (persistent)
  • clear_errorcodes - Clear specified error codes

Tier 3: Safety Tools (Safety-Critical)

Operations requiring confirmation tokens:

  • request_confirmation - Generate confirmation token for Tier 3 operations
  • request_connect_with_precharge - Request pack connection (requires confirmation)
  • request_disconnect - Request pack disconnection (requires confirmation)
  • trigger_estop - Activate E-stop (requires confirmation)
  • restore_estop - Restore E-stop state
  • power_cycle_bcu - Power cycle BCU (requires confirmation)
  • hard_reboot_bcu - Hard reboot BCU (requires confirmation)
  • shutdown_bcu - Shutdown BCU (requires confirmation)

Test Discovery & Execution

  • list_tests - List all available pytest tests
  • filter_tests - Filter tests by markers, expressions, or nodeids
  • get_test_info - Get detailed test information
  • run_single_test - Execute a single test
  • run_targeted_tests - Execute filtered tests
  • collect_tests - Collect test list without execution

State Management

  • store_value - Store value in session state
  • get_stored_value - Retrieve stored value
  • list_stored_values - List all stored values
  • clear_stored_values - Clear stored values

Test Sequences

  • create_test_sequence - Create a named test sequence
  • add_sequence_step - Add step to sequence
  • execute_test_sequence - Execute stored sequence
  • list_test_sequences - List all sequences
  • delete_test_sequence - Delete a sequence

Usage Examples

Example 1: Read System Status

# Get operational status
result = get_operational_status()
# Returns: {"success": true, "data": {"status_code": 2, "status_name": "OPERATIONAL"}}

# Get contactor states
result = get_contactor_statuses()
# Returns: {"success": true, "data": {"positive": {"closed": false, "open": true}, ...}}

Example 2: Set Cell Voltage (with validation)

# Set cell 0 to 3.7V
result = set_cell_voltage(cell_idx=0, voltage=3.7)
# Validates: cell_idx in [0, 29], voltage in [0, 5]V

Example 3: Safety Operation with Confirmation

# Step 1: Request confirmation
conf_result = request_confirmation(operation="power_cycle_bcu")
# Returns: {"success": true, "data": {"confirmation_token": "...", "expires_in_seconds": 30}}

# Step 2: Use token for operation
token = conf_result["data"]["confirmation_token"]
result = power_cycle_bcu(confirmation_token=token)

Example 4: Test Discovery and Execution

# List all tests
tests = list_tests(test_path="NextGen/tests")

# Filter by marker
safety_tests = filter_tests(marker="safety")

# Run single test
result = run_single_test(nodeid="NextGen/tests/test_voltage.py::test_voltage_limits")

Example 5: Create and Execute Test Sequence

# Create sequence
create_test_sequence(name="voltage_check", description="Check voltage limits")

# Add steps
add_sequence_step(
    sequence_name="voltage_check",
    tool_name="get_sensed_cell_voltages",
    parameters={},
    store_result_as="voltages"
)

add_sequence_step(
    sequence_name="voltage_check",
    tool_name="set_cell_voltage",
    parameters={"cell_idx": 0, "voltage": 3.7}
)

# Execute sequence
result = execute_test_sequence(sequence_name="voltage_check", stop_on_error=True)

Example 6: Store and Use Values

# Store a value
store_value(key="target_voltage", value=3.7)

# Use stored value in parameters (via $ prefix in sequences)
# In sequence step: {"voltage": "$target_voltage"}

# Retrieve stored value
voltage = get_stored_value(key="target_voltage")

Safety Features

Range Validation

All control operations validate inputs:

  • Cell voltages: 0-5V
  • Temperatures: -40 to 85°C
  • Currents: Configurable limits
  • Cell/NTC indices: Validated against system limits

Confirmation System

Tier 3 operations require confirmation tokens:

  1. Call request_confirmation(operation="operation_name") to get a token
  2. Token expires after 30 seconds
  3. Token is single-use
  4. Use token in the safety operation call

State Checks

The server validates system state before dangerous operations:

  • Verifies contactor states before power operations
  • Checks operational status before critical commands
  • Validates hardware communication health

Error Handling

All tools return structured responses:

{
  "success": true/false,
  "data": {...},
  "error": "error message if failed",
  "metadata": {...}
}

Common error types:

  • ValidationError: Input validation failed (range, format, etc.)
  • HardwareCommunicationError: Communication with hardware failed
  • ConfirmationError: Invalid or expired confirmation token
  • ToolNotFoundError: Unknown tool name

Architecture

mcp_server/
├── server.py              # Main MCP server with stdio transport
├── tools/
│   ├── status_tools.py    # Tier 1: Read-only operations
│   ├── control_tools.py   # Tier 2: Controlled writes
│   ├── safety_tools.py    # Tier 3: Safety-critical
│   ├── test_tools.py      # Test discovery and execution
│   └── sequence_tools.py  # Test sequence construction
├── schemas/
│   └── tool_schemas.py    # JSON schema definitions
├── safety/
│   └── validators.py      # Safety validation logic
└── state/
    ├── session_state.py   # Session state management
    └── test_sequences.py  # Test sequence storage

Configuration

The server reads from existing project configuration:

  • IP addresses: Defaults to 192.168.1.101 (master), 192.168.1.102 (follower)
  • Safety limits: Defined in mcp_server/safety/validators.py
  • Test paths: Defaults to NextGen/tests

Environment variables can override defaults:

  • NP_FAILURE_POLICY: NP client failure policy
  • RTDB_MAP_PATH: Path to RTDB mapping file

Troubleshooting

Server Won't Start

  1. Check MCP SDK installation: pip install mcp
  2. Verify Python path includes project root
  3. Check VeriStand connection (if hardware operations needed)

Tool Execution Fails

  1. Check error message in response
  2. Verify hardware is connected and initialized
  3. For Tier 3 operations, ensure confirmation token is valid
  4. Check input validation (ranges, formats)

Test Execution Issues

  1. Verify pytest is installed and accessible
  2. Check test path is correct
  3. Ensure test fixtures are available
  4. Review pytest output in tool response

Development

Adding New Tools

  1. Add tool function to appropriate tools/*.py file
  2. Add schema definition to schemas/tool_schemas.py
  3. Add routing logic to server.py _route_tool_call()
  4. Update this README with tool documentation

Testing

Unit tests should be added for:

  • Schema validation
  • Safety validators
  • Tool execution logic
  • State management

License

Part of the BMS_QA_HIL project.