# 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**:
```python
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**:
```bash
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 (`optimization_config.py`) ✅ IMPLEMENTED

**Purpose**: Generate `optimization_config.json` from user selections of objectives, constraints, and design variables.

**Functions**:
- `build_optimization_config(...)` - Create complete optimization configuration
- `list_optimization_options(sim_file_path)` - List all available options for a model
- `format_optimization_options_for_llm(options)` - Format options as Markdown

**What it does**:
- Discovers available design variables from the FEA model
- Lists available objectives (minimize mass, stress, displacement, volume)
- Lists available constraints (max stress, max displacement, mass limits)
- Builds a complete `optimization_config.json` based on user selections
- Validates that all selections are valid for the model

**Usage Example**:
```python
from mcp_server.tools import build_optimization_config, list_optimization_options

# Step 1: List available options
options = list_optimization_options("examples/bracket/Bracket_sim1.sim")
print(f"Available design variables: {len(options['available_design_variables'])}")

# Step 2: Build configuration
result = build_optimization_config(
    sim_file_path="examples/bracket/Bracket_sim1.sim",
    design_variables=[
        {'name': 'tip_thickness', 'lower_bound': 15.0, 'upper_bound': 25.0},
        {'name': 'support_angle', 'lower_bound': 20.0, 'upper_bound': 40.0}
    ],
    objectives=[
        {'objective_key': 'minimize_mass', 'weight': 5.0},
        {'objective_key': 'minimize_max_stress', 'weight': 10.0}
    ],
    constraints=[
        {'constraint_key': 'max_displacement_limit', 'limit_value': 1.0},
        {'constraint_key': 'max_stress_limit', 'limit_value': 200.0}
    ],
    optimization_settings={
        'n_trials': 150,
        'sampler': 'TPE'
    }
)

if result['status'] == 'success':
    print(f"Config saved to: {result['config_file']}")
```

**Command Line Usage**:
```bash
python mcp_server/tools/optimization_config.py examples/bracket/Bracket_sim1.sim
```

**Available Objectives**:
- `minimize_mass`: Minimize total mass (weight reduction)
- `minimize_max_stress`: Minimize maximum von Mises stress
- `minimize_max_displacement`: Minimize maximum displacement (increase stiffness)
- `minimize_volume`: Minimize total volume (material usage)

**Available Constraints**:
- `max_stress_limit`: Maximum allowable von Mises stress
- `max_displacement_limit`: Maximum allowable displacement
- `min_mass_limit`: Minimum required mass (structural integrity)
- `max_mass_limit`: Maximum allowable mass (weight budget)

**Output**: Creates `optimization_config.json` with:
- Design variable definitions with bounds
- Multi-objective configuration with weights
- Constraint definitions with limits
- Optimization algorithm settings (trials, sampler)

---

### 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

```bash
# 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**:
```python
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'
        }
```

3. **Add to `__init__.py`**:
```python
from .your_tool import your_tool_name

__all__ = [
    # ... existing tools
    "your_tool_name",
]
```

4. **Create tests**: `tests/mcp_server/tools/test_your_tool.py`

5. **Update documentation**: Add section to this README

---

## Error Handling

All MCP tools follow a consistent error handling pattern:

**Success Response**:
```json
{
  "status": "success",
  "data": { ... }
}
```

**Error Response**:
```json
{
  "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 | Phase 2 (Optimization Config Builder) ✅ COMPLETE
