Files
Atomizer/mcp_server/tools
Claude 16cddd5243 feat: Comprehensive expression extraction and OP2 result extractor example
Enhanced expression extraction to find ALL named expressions in .prt files,
not just specific format. Added pyNastran-based result extraction example.

Expression Extraction Improvements:
- Updated regex to handle all NX expression format variations:
  * #(Type [units]) name: value;
  * (Type [units]) name: value;
  * *(Type [units]) name: value;
  * ((Type [units]) name: value;
- Added Root:expression_name: pattern detection
- Finds expressions even when value is not immediately available
- Deduplication to avoid duplicates
- Filters out NX internal names

Test Results with Bracket.prt:
- Previously: 1 expression (tip_thickness only)
- Now: 5 expressions found:
  * support_angle = 30.0 degrees
  * tip_thickness = 20.0 mm
  * p3 = 10.0 mm
  * support_blend_radius = 10.0 mm
  * p11 (reference found, value unknown)

OP2 Result Extraction (pyNastran):
- Created example extractor: op2_extractor_example.py
- Functions for common optimization metrics:
  * extract_max_displacement() - max displacement magnitude on any node
  * extract_max_stress() - von Mises or max principal stress
  * extract_mass() - total mass and center of gravity
- Handles multiple element types (CQUAD4, CTRIA3, CTETRA, etc.)
- Returns structured JSON for optimization engine integration
- Command-line tool for testing with real OP2 files

Usage:
  python optimization_engine/result_extractors/op2_extractor_example.py <file.op2>

Integration Ready:
- pyNastran already in requirements.txt
- Result extractor pattern established
- Can be used as template for custom metrics

Next Steps:
- Integrate result extractors into MCP tool framework
- Add safety factor calculations
- Support for thermal, modal results
2025-11-15 13:49:16 +00:00
..

MCP Tools Documentation

This directory contains the MCP (Model Context Protocol) tools that enable LLM-driven optimization configuration for Atomizer.

Available Tools

1. Model Discovery (model_discovery.py) IMPLEMENTED

Purpose: Parse Siemens NX .sim files to extract FEA model information.

Function: discover_fea_model(sim_file_path: str) -> Dict[str, Any]

What it extracts:

  • Solutions: Analysis types (static, thermal, modal, etc.)
  • Expressions: Parametric variables that can be optimized
  • FEM Info: Mesh, materials, loads, constraints
  • Linked Files: Associated .prt files and result files

Usage Example:

from mcp_server.tools import discover_fea_model, format_discovery_result_for_llm

# Discover model
result = discover_fea_model("C:/Projects/Bracket/analysis.sim")

# Format for LLM
if result['status'] == 'success':
    markdown_output = format_discovery_result_for_llm(result)
    print(markdown_output)

# Access structured data
for expr in result['expressions']:
    print(f"{expr['name']}: {expr['value']} {expr['units']}")

Command Line Usage:

python mcp_server/tools/model_discovery.py examples/test_bracket.sim

Output Format:

  • JSON: Complete structured data for programmatic use
  • Markdown: Human-readable format for LLM consumption

Supported .sim File Versions:

  • NX 2412 (tested)
  • Should work with NX 12.0+ (XML-based .sim files)

Limitations:

  • Expression values are best-effort extracted from .sim XML
  • For accurate values, the associated .prt file is parsed (binary parsing)
  • Binary .prt parsing is heuristic-based and may miss some expressions

2. Build Optimization Config (PLANNED)

Purpose: Generate optimization_config.json from natural language requirements.

Function: build_optimization_config(requirements: str, model_info: Dict) -> Dict[str, Any]

Planned Features:

  • Parse LLM instructions ("minimize stress while reducing mass")
  • Select appropriate result extractors
  • Suggest reasonable parameter bounds
  • Generate complete config for optimization engine

3. Start Optimization (PLANNED)

Purpose: Launch optimization run with given configuration.

Function: start_optimization(config_path: str, resume: bool = False) -> Dict[str, Any]


4. Query Optimization Status (PLANNED)

Purpose: Get current status of running optimization.

Function: query_optimization_status(session_id: str) -> Dict[str, Any]


5. Extract Results (PLANNED)

Purpose: Parse FEA result files (OP2, F06, XDB) for optimization metrics.

Function: extract_results(result_files: List[str], extractors: List[str]) -> Dict[str, Any]


6. Run NX Journal (PLANNED)

Purpose: Execute NXOpen scripts via file-based communication.

Function: run_nx_journal(journal_script: str, parameters: Dict) -> Dict[str, Any]


Testing

Unit Tests

# Install pytest (if not already installed)
pip install pytest

# Run all MCP tool tests
pytest tests/mcp_server/tools/ -v

# Run specific test
pytest tests/mcp_server/tools/test_model_discovery.py -v

Example Files

Example .sim files for testing are located in examples/:

  • test_bracket.sim: Simple structural analysis with 4 expressions

Development Guidelines

Adding a New Tool

  1. Create module: mcp_server/tools/your_tool.py

  2. Implement function:

def your_tool_name(param: str) -> Dict[str, Any]:
    """
    Brief description.

    Args:
        param: Description

    Returns:
        Structured result dictionary
    """
    try:
        # Implementation
        return {
            'status': 'success',
            'data': result
        }
    except Exception as e:
        return {
            'status': 'error',
            'error_type': 'error_category',
            'message': str(e),
            'suggestion': 'How to fix'
        }
  1. Add to __init__.py:
from .your_tool import your_tool_name

__all__ = [
    # ... existing tools
    "your_tool_name",
]
  1. Create tests: tests/mcp_server/tools/test_your_tool.py

  2. Update documentation: Add section to this README


Error Handling

All MCP tools follow a consistent error handling pattern:

Success Response:

{
  "status": "success",
  "data": { ... }
}

Error Response:

{
  "status": "error",
  "error_type": "file_not_found | invalid_file | unexpected_error",
  "message": "Detailed error message",
  "suggestion": "Actionable suggestion for user"
}

Integration with MCP Server

These tools are designed to be called by the MCP server and consumed by LLMs. The workflow is:

  1. LLM Request: "Analyze my FEA model at C:/Projects/model.sim"
  2. MCP Server: Calls discover_fea_model()
  3. Tool Returns: Structured JSON result
  4. MCP Server: Formats with format_discovery_result_for_llm()
  5. LLM Response: Uses formatted data to answer user

Future Enhancements

  • Support for binary .sim file formats (older NX versions)
  • Direct NXOpen integration for accurate expression extraction
  • Support for additional analysis types (thermal, modal, etc.)
  • Caching of parsed results for performance
  • Validation of .sim file integrity
  • Extraction of solver convergence settings

Last Updated: 2025-11-15 Status: Phase 1 (Model Discovery) COMPLETE