mokafari/hil-mcp-server
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.
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
- Install MCP dependencies:
pip install -r requirements_mcp.txt
- 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 statusget_connection_status- Get connection stateget_contactor_statuses- Get all contactor statesread_errors- Read active error codesread_errors_with_names- Read errors with human-readable namesget_sensed_cell_voltages- Read all cell voltagesget_cell_temperatures- Read all temperature sensorsget_pack_current- Read current sensor valueget_system_info- Get system role, IP, versionsread_rtdb- Read RTDB value by IDget_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 voltageset_cell_temperature- Set temperature on specific NTC (-40 to 85°C)set_all_temperatures- Set all temperaturesset_pack_current- Set pack current simulationset_system_role- Switch master/slave rolewrite_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 operationsrequest_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 statepower_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 testsfilter_tests- Filter tests by markers, expressions, or nodeidsget_test_info- Get detailed test informationrun_single_test- Execute a single testrun_targeted_tests- Execute filtered testscollect_tests- Collect test list without execution
State Management
store_value- Store value in session stateget_stored_value- Retrieve stored valuelist_stored_values- List all stored valuesclear_stored_values- Clear stored values
Test Sequences
create_test_sequence- Create a named test sequenceadd_sequence_step- Add step to sequenceexecute_test_sequence- Execute stored sequencelist_test_sequences- List all sequencesdelete_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:
- Call
request_confirmation(operation="operation_name")to get a token - Token expires after 30 seconds
- Token is single-use
- 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 policyRTDB_MAP_PATH: Path to RTDB mapping file
Troubleshooting
Server Won't Start
- Check MCP SDK installation:
pip install mcp - Verify Python path includes project root
- Check VeriStand connection (if hardware operations needed)
Tool Execution Fails
- Check error message in response
- Verify hardware is connected and initialized
- For Tier 3 operations, ensure confirmation token is valid
- Check input validation (ranges, formats)
Test Execution Issues
- Verify pytest is installed and accessible
- Check test path is correct
- Ensure test fixtures are available
- Review pytest output in tool response
Development
Adding New Tools
- Add tool function to appropriate
tools/*.pyfile - Add schema definition to
schemas/tool_schemas.py - Add routing logic to
server.py_route_tool_call() - 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.