Skip to main content
Glama
HBPEKING-TKS

COMSOL MCP Server

by HBPEKING-TKS
README.md
# COMSOL MCP Server

MCP Server for COMSOL Multiphysics simulation automation via AI agents.

[![CI](https://github.com/HBPEKING-TKS/mcp_server/actions/workflows/ci.yml/badge.svg)](https://github.com/HBPEKING-TKS/mcp_server/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)

## Project Goal

Build a complete COMSOL MCP Server enabling AI agents (like Claude, opencode) to perform multiphysics simulations through the MCP protocol:

1. **Model Management** - Create, load, save, version control
2. **Geometry Building** - Blocks, cylinders, spheres, boolean operations
3. **Physics Configuration** - Heat transfer, fluid flow, electrostatics, solid mechanics
4. **Meshing & Solving** - Auto mesh, stationary/time-dependent studies
5. **Results Visualization** - Evaluate expressions, export plots
6. **Knowledge Integration** - Embedded guides + PDF semantic search

## Requirements

- **COMSOL Multiphysics** (version 5.x or 6.x)
- **Python 3.10+** (NOT Windows Store version)
- **Java runtime** (required by MPh/COMSOL)

## Installation

```bash
# Clone repository
git clone https://github.com/HBPEKING-TKS/mcp_server.git
cd comsol-multiphysics-mcp

# Install dependencies
python -m pip install -e .

# Test server
python -m src.server
```

## Building PDF Knowledge Base

```bash
# Install additional dependencies
pip install pymupdf chromadb sentence-transformers

# Build knowledge base (requires COMSOL PDF documentation)
python scripts/build_knowledge_base.py

# Check status
python scripts/build_knowledge_base.py --status
```

## Usage

### Option 1: With opencode

Create `opencode.json` in project root:

```json
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "comsol": {
      "type": "local",
      "command": ["python", "-m", "src.server"],
      "enabled": true,
      "environment": {
        "HF_ENDPOINT": "https://hf-mirror.com"
      },
      "timeout": 30000
    }
  }
}
```

### Option 2: With Claude Desktop

```json
{
  "mcpServers": {
    "comsol": {
      "command": "python",
      "args": ["-m", "src.server"],
      "cwd": "/path/to/comsol-multiphysics-mcp"
    }
  }
}
```

## Code Structure

```
comsol-multiphysics-mcp/
├── opencode.json                    # MCP server config for opencode
├── pyproject.toml                   # Python project config
├── README.md                        # This file
├── LICENSE                          # MIT License
│
├── src/
│   ├── server.py                    # MCP Server entry point
│   ├── tools/
│   │   ├── session.py               # COMSOL session management (start/stop/status)
│   │   ├── model.py                 # Model CRUD + versioning
│   │   ├── parameters.py            # Parameter management + sweeps
│   │   ├── geometry.py              # Geometry creation (block/cylinder/sphere)
│   │   ├── physics.py               # Physics interfaces + boundary conditions
│   │   ├── mesh.py                  # Mesh generation
│   │   ├── study.py                 # Study creation + solving (sync/async)
│   │   └── results.py               # Results evaluation + export
│   ├── resources/
│   │   └── model_resources.py       # MCP resources (model tree, parameters)
│   ├── knowledge/
│   │   ├── embedded.py              # Embedded physics guides + troubleshooting
│   │   ├── retriever.py             # PDF vector search retriever
│   │   ├── pdf_processor.py         # PDF chunking + embedding
│   │   └── prompts/                 # Reference docs (API, physics, workflow)
│   ├── async_handler/
│   │   └── solver.py                # Async solving with progress tracking
│   └── utils/
│       └── versioning.py            # Model version path management
│
├── scripts/
│   └── build_knowledge_base.py      # Build PDF vector database
│
├── comsol_models/                   # Saved models (structured)
│   └── {model_name}/
│       ├── {model_name}_{timestamp}.mph
│       └── {model_name}_latest.mph
│
└── tests/
    └── test_basic.py                # Unit tests
```

## Available Tools (80+ total)

### Session (4)
| Tool | Description |
|------|-------------|
| `comsol_start` | Start local COMSOL client |
| `comsol_connect` | Connect to remote server |
| `comsol_disconnect` | Clear session |
| `comsol_status` | Get session info |

### Model (9)
| Tool | Description |
|------|-------------|
| `model_load` | Load .mph file |
| `model_create` | Create empty model |
| `model_save` | Save to file |
| `model_save_version` | Save with timestamp |
| `model_list` | List loaded models |
| `model_set_current` | Set active model |
| `model_clone` | Clone model |
| `model_remove` | Remove from memory |
| `model_inspect` | Get model structure |

### Parameters (5)
| Tool | Description |
|------|-------------|
| `param_get` | Get parameter value |
| `param_set` | Set parameter |
| `param_list` | List all parameters |
| `param_sweep_setup` | Setup parametric sweep |
| `param_description` | Get/set description |

### Geometry (14)
| Tool | Description |
|------|-------------|
| `geometry_list` | List geometry sequences |
| `geometry_create` | Create geometry sequence |
| `geometry_add_block` | Add rectangular block |
| `geometry_add_cylinder` | Add cylinder |
| `geometry_add_sphere` | Add sphere |
| `geometry_boolean_union` | Union objects |
| `geometry_boolean_difference` | Subtract objects |
| `geometry_import` | Import CAD file |
| `geometry_build` | Build geometry |
| ... | ... |

### Physics (16)
| Tool | Description |
|------|-------------|
| `physics_add_electrostatics` | Add Electrostatics |
| `physics_add_solid_mechanics` | Add Solid Mechanics |
| `physics_add_heat_transfer` | Add Heat Transfer |
| `physics_add_laminar_flow` | Add Laminar Flow |
| `physics_configure_boundary` | Configure boundary condition |
| `multiphysics_add` | Add coupling |
| `physics_setup_heat_boundaries` | Configure heat boundaries |
| `physics_setup_flow_boundaries` | Configure flow boundaries |
| ... | ... |

### Study & Solving (8)
| Tool | Description |
|------|-------------|
| `study_list` | List studies |
| `study_solve` | Solve synchronously |
| `study_solve_async` | Solve in background |
| `study_get_progress` | Get progress |
| `study_cancel` | Cancel solving |
| `study_wait` | Wait for completion |

### Results (9)
| Tool | Description |
|------|-------------|
| `results_evaluate` | Evaluate expression |
| `results_global_evaluate` | Evaluate scalar |
| `results_inner_values` | Get time steps |
| `results_outer_values` | Get sweep values |
| `results_export_data` | Export data |
| `results_export_image` | Export plot image |

### Knowledge (8)
| Tool | Description |
|------|-------------|
| `docs_get` | Get documentation |
| `docs_list` | List available docs |
| `physics_get_guide` | Physics quick guide |
| `troubleshoot` | Troubleshooting help |
| `modeling_best_practices` | Best practices |
| `pdf_search` | Search PDF docs |
| `pdf_search_status` | PDF search status |
| `pdf_list_modules` | List PDF modules |

## Key Technical Discoveries

### MPh Library API Patterns

```python
# Access Java model via property (not callable)
jm = model.java  # NOT model.java()

# Create component with True flag
comp = jm.component().create('comp1', True)

# Create 3D geometry
geom = comp.geom().create('geom1', 3)

# Boundary condition with selection
bc = physics.create('inl1', 'InletBoundary')
bc.selection().set([1, 2, 3])
bc.set('U0', '1[mm/s]')
```

### Boundary Condition Property Names

| Physics | Condition | Property |
|---------|-----------|----------|
| Heat Transfer | HeatFluxBoundary | `q0` |
| Heat Transfer | TemperatureBoundary | `T0` |
| Heat Transfer | ConvectiveHeatFlux | `h`, `Text` |
| Laminar Flow | InletBoundary | `U0` |
| Laminar Flow | OutletBoundary | `p0` |

## Model Versioning

Models are saved with structured paths:

```
./comsol_models/{model_name}/{model_name}_{timestamp}.mph
./comsol_models/{model_name}/{model_name}_latest.mph
```

## MCP Resources

| URI | Description |
|-----|-------------|
| `comsol://session/info` | Session information |
| `comsol://model/{name}/tree` | Model tree structure |
| `comsol://model/{name}/parameters` | Model parameters |
| `comsol://model/{name}/physics` | Physics interfaces |

## License

MIT

TDQS

B3.4/5.0

Scored across 78 tools

Disambiguation4/5

Tools are organized by domain with descriptive names, but some overlap exists between generic and specific geometry tools (e.g., geometry_add_feature vs geometry_add_block) and between boundary condition configuration tools (physics_boundary_selection, physics_configure_boundary, interactive setup flows). However, descriptions mostly clarify differences.

Naming Consistency4/5

Names follow a consistent prefix_pattern (comsol_, model_, geometry_, physics_, param_, results_, study_) with verb_noun structure. Minor inconsistencies: modeling_best_practices uses 'modeling_' vs 'model_', pdf_list_modules vs docs_ prefix, and geometry_add_feature uses 'feature' instead of specific type.

Tool Count2/5

With 78 tools, the surface is overly broad. Many tools are redundant (e.g., separate geometry_add_block/cylinder/sphere vs generic geometry_add_feature; multiple interactive setup flows duplicate manual setup). Consolidation could reduce count significantly without loss of functionality.

Completeness4/5

The tool set covers the full COMSOL workflow from connection to results evaluation. Minor gaps include explicit material library management tools, integration operators, and probe creation. However, core modeling tasks are well-supported.

Maintenance

ActivityMaintained
ResponsivenessSyncing