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

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