Skip to main content
Glama

comsol-mcp

An MCP server that lets AI assistants drive COMSOL Multiphysics on Windows: build geometry, set parameters, generate meshes, solve studies, evaluate fields, and export plots — while your COMSOL Desktop stays connected to the same live session.

Built on MPh (the Python bridge to the COMSOL Java API) and the official MCP Python SDK.

MCP client (opencode / Claude Desktop / Cline / ...)
        │  stdio
        ▼
  comsol_mcp/server.py  ──MPh + JPype──▶  COMSOL Multiphysics server (:2036)
                                                    ▲
                                            COMSOL Desktop (client mode)

Features

  • Live session sharing — start the server, connect COMSOL Desktop in client mode, and watch changes appear in the GUI as the model is edited.

  • Full workflow — parameters, geometry, physics, materials, mesh, study, solve, evaluate, plot.

  • Escape hatch — comsol_python runs arbitrary Python against the raw com.comsol.model.Model Java object, so nothing is out of reach.

  • Long solves — background solving with status polling instead of blocked tool calls.

  • Safe saves — timestamped .bak-* backups before overwriting a model.

Related MCP server: comsol-mcp-server

Requirements

OS

Windows 10/11 (tested). Core logic is cross-platform; screenshot and some helpers are Windows-only.

COMSOL

Multiphysics 6.x with a valid license (tested on 6.4.0.429).

Python

3.11+

Java

Bundled with COMSOL; no separate JDK needed.

COMSOL_ROOT is optional — MPh discovers installed COMSOL versions from the Windows registry.

Installation

git clone https://github.com/Aknpa-Kacyraho/comsol-mcp
cd comsol-mcp

python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -e .

Verify:

python -c "import comsol_mcp; print(comsol_mcp.__version__)"
python tests\smoke_test.py
python tests\modeling_test.py
python tests\full_test.py
python tests\edge_test.py
python tests\mesh_test.py
python tests\boolean_test.py
python tests\stability_test.py

Each test starts its own COMSOL server on a random port and cleans up after itself.

Configure your MCP client

opencode

{
  "mcp": {
    "comsol": {
      "type": "local",
      "command": [
        "C:\\path\\to\\comsol-mcp\\.venv\\Scripts\\python.exe",
        "C:\\path\\to\\comsol-mcp\\server.py"
      ],
      "cwd": "C:\\path\\to\\comsol-mcp",
      "environment": {
        "PYTHONUTF8": "1",
        "PYTHONIOENCODING": "utf-8"
      },
      "enabled": true,
      "timeout": 3600000
    }
  }
}

timeout is in milliseconds. Keep it large so long solves are not cut off.

Claude Desktop

{
  "mcpServers": {
    "comsol": {
      "command": "C:\\path\\to\\comsol-mcp\\.venv\\Scripts\\python.exe",
      "args": ["C:\\path\\to\\comsol-mcp\\server.py"],
      "env": {
        "PYTHONUTF8": "1",
        "PYTHONIOENCODING": "utf-8"
      }
    }
  }
}

DeepSeek Harness (DSH)

Add an entry to home/cordis.patch.yml (under insert):

    - id: mcp-comsol
      name: '@deepseek-ai/dsh-mcp-client'
      config:
        serverName: comsol
        transport: stdio
        command: 'C:/path/to/comsol-mcp/.venv/Scripts/python.exe'
        args:
          - 'C:/path/to/comsol-mcp/server.py'
        cwd: 'C:/path/to/comsol-mcp'
        env:
          PYTHONUTF8: '1'
          PYTHONIOENCODING: 'utf-8'
        toolCallTimeoutMs: 3600000

Tools then appear as mcp__comsol__*. Restart DSH to pick up the change.

Cline / other stdio clients

Use the same command and args as Claude Desktop. Any client that speaks stdio MCP works; the server only writes logs to logs/ and nothing to stdout except protocol messages.

Tools

Tool

What it does

comsol_status

Connection state, port, loaded models, current model, background job status

comsol_start

Connect to an existing server or start one (default port 2036)

comsol_stop

Disconnect and optionally shut the server down

comsol_open

Open a .mph file or create a new model

comsol_use

Switch the active model when several are loaded

comsol_save

Save or save-as; copies a timestamped backup before writing and reports SAVE_LOCKED / SAVE_PERMISSION_DENIED instead of losing the original

comsol_inspect

Structured model tree: parameters, geometry, physics, selections, materials, mesh, studies, results

comsol_geometry

Create/update/delete/build geometry features: Block, Cylinder, Sphere, Rectangle, Circle, Import, booleans

comsol_physics

Create physics interfaces and features, bind selections, set properties

comsol_selection

Named Box / Ball / Explicit selections, then reuse them in boundary conditions

comsol_diagnose

Model health check: COMSOL-reported problems plus missing geometry/physics/material/mesh/study

comsol_help

Offline cheat sheets for geometry, heat, solid, flow, electrostatics, selection, mesh

comsol_material

Materials from built-in presets (copper/aluminum/steel/silicon/water/air) or custom properties

comsol_params

Read or set global parameters (200[A], 1.5[mm], ...)

comsol_sweep

Add a parametric sweep (parameter names + value lists, units inferred)

comsol_mesh

Mesh sequences: feature tree, global size levels, local Size refinement, FreeTri/FreeQuad/Map/Sweep, boundary layers, quality stats

comsol_study

List/create studies and steps (Stationary/Transient/Eigenfrequency/Frequency), set step properties

comsol_solve

Run a study, foreground or background; returns job_id and tracks running/completed/failed

comsol_eval

Evaluate an expression, return min/max/mean

comsol_plot

Render a surface plot of any expression and export PNG

comsol_export

Export field values (with x/y/z coordinates) to CSV

comsol_model

List, remove from memory, or rename loaded models

comsol_python

Execute Python against the COMSOL Java API

comsol_desktop

Launch COMSOL Desktop and connect it to the running server

comsol_screenshot

Capture the COMSOL window so the assistant can see the current UI

HPC cluster tools (Slurm, e.g. KIT SCC bwUniCluster 3.0)

Optional extension in comsol_mcp/cluster.py; the local tools above are unchanged. See docs/CLUSTER.md.

Tool

What it does

comsol_cluster_config

Show or change cluster settings (cluster.json)

comsol_cluster_check

Test SSH, list partitions and COMSOL modules

comsol_cluster_submit

Upload a .mph and run comsol batch via sbatch

comsol_cluster_status

Slurm state and tail of batch.log

comsol_cluster_fetch

Download output.mph and logs for local evaluation

comsol_cluster_cancel

Cancel a job

Stability and failure semantics

  • All COMSOL Java calls go through one worker thread. Parallel tool calls queue; they never touch the JVM from another thread.

  • Long calls return a task_id; a client-side wait timeout means still running, not failed. comsol_status exposes worker.current, worker.pending and the last five tasks.

  • While a solve is running, only comsol_status is available. Other tools fail fast with MODEL_BUSY instead of hanging in the queue.

  • comsol_save copies a timestamped backup before writing. On failure it returns save_succeeded, backup_created and original_integrity_verified; a true file-exists check does not prove the old content is intact, so keep the backup.

  • comsol_stop releases the client, but the JVM cannot be re-created in the same process. Restart the MCP server to reconnect.

  • The idle watchdog exits only when busy=false and the worker queue is empty, so a long foreground solve is never killed.

  • comsol_status also reports worker liveness, the current task, and recent task results.

Details and troubleshooting: docs/STABILITY.md.

Live desktop sharing

COMSOL supports a client–server mode where the server owns the model and Desktop is just a viewer.

  1. Ask the assistant to run comsol_start. A server starts on port 2036.

  2. Launch the client:

    .\start_client.ps1

    or

    & "<COMSOL_ROOT>\bin\win64\comsolmphclient.exe" -server localhost -port 2036
  3. Click Connect in the dialog.

  4. Open the same model from the server's file list.

Edits made through MCP now appear in the Desktop tree as they happen.

If you prefer not to share a session, skip the Desktop part: MCP opens the .mph file independently and saves results you can reopen.

Examples

examples/heat_transfer_2d.py builds a 2D steady-state heat transfer model from scratch, solves it, evaluates the temperature field, and exports a PNG — a minimal end-to-end script using the same API the tools call.

python examples\heat_transfer_2d.py

examples/plate_with_holes.py goes through the MCP tool layer: geometry with two holes, named selections, comsol_study, a background solve with job_id polling, PNG export, and a checked save. Verified on COMSOL 6.4.

python examples\plate_with_holes.py

Escape hatch

Anything the 25 tools do not cover can be done through comsol_python, which exposes model, java, client, mph, np:

ht = java.modelNode('comp1').physics('ht')
flux = ht.create('hf1', 'HeatFluxBoundary', 1)
flux.selection().set([2])
flux.set('q0', '1e4[W/m^2]')

Useful Java API entry points:

  • Geometry: java.modelNode('comp1').geom('geom1')

  • Physics: java.modelNode('comp1').physics('ht')

  • Materials: java.modelNode('comp1').material('mat1').propertyGroup('def')

  • Mesh: java.modelNode('comp1').mesh('mesh1')

  • Study: java.study('std1')

  • Results: java.result()

Environment variables

Variable

Default

Purpose

COMSOL_ROOT

auto-detected

COMSOL installation root

COMSOL_PORT

2036

Default server port

COMSOL_MCP_HOME

current directory

Where logs/ and out/ are written

COMSOL_MCP_IDLE_TIMEOUT

1800

Exit after this many idle seconds; 0 disables. Prevents stale processes piling up when a client disconnects.

COMSOL_MCP_MAX_PENDING

32

Maximum queued worker tasks; further calls fail fast with WORKER_OVERLOADED.

COMSOL_MCP_LOG_MAX_BYTES

5242880

Rotate logs/comsol-mcp.log at this size.

COMSOL_MCP_LOG_BACKUPS

3

Number of rotated log files to keep.

COMSOL_MCP_CLUSTER

1

0 disables the HPC cluster tools.

Limitations

  • One COMSOL client per process: after comsol_stop, the MCP process must be restarted before connecting again (JVM limitation).

  • Cancelling a running solve is not exposed by the COMSOL Java API; a long solve must finish, or the COMSOL process must be restarted.

  • Progress reporting during solve is coarse — the job is either running or finished, no percentage.

  • comsol_screenshot brings the COMSOL window to the foreground before capturing; it will briefly steal focus.

  • Windows-specific helpers: screenshot, and launching Desktop. Everything else works wherever MPh works.

Acknowledgements

Self-check

The 0.3.0 release went through a three-perspective review (user / designer / engineer). See docs/SELF-CHECK.md for the checklist and what was fixed.

Official docs

Docs

  • docs/MODELING-CHEATSHEET.md — end-to-end modeling checklist: parameters, geometry, booleans, selections, materials, physics, studies

  • docs/MESH-GUIDE.md — meshing handbook: size levels, element types, mapped meshes and edge groups, local refinement, boundary layers, quality, mesh independence

  • docs/CLUSTER.md — run models as Slurm batch jobs on an HPC cluster (KIT SCC)

  • docs/SELF-CHECK.md — user / designer / engineer review

  • examples/ — runnable scripts: server startup, open model in Desktop, graded 2D mesh

Disclaimer

This project is not affiliated with, endorsed by, or supported by COMSOL AB. "COMSOL" and "COMSOL Multiphysics" are trademarks of COMSOL AB. You need your own valid COMSOL license to use this software.

License

MIT. See LICENSE.

Available Tools

31 tools
comsol_cluster_cancelC

Cluster: Slurm-Job abbrechen (scancel).

Inputs: job_id (required). Returns: result

comsol_cluster_checkA

Cluster: Verbindung prüfen (SSH ohne Rückfrage), Slurm-Partitionen und verfügbare COMSOL-Module auflisten. Vor dem ersten Submit aufrufen. Rechnet nichts auf dem Login-Knoten.

Inputs: no named parameters. Returns: result

comsol_cluster_configB

Cluster (Slurm/SCC): Einstellungen anzeigen oder ändern. Ohne values: anzeigen. values z. B. {'user': 'ka_ab1234', 'host': 'uc3.scc.kit.edu', 'partition': 'cpu', 'cores': 32, 'time': '04:00:00', 'comsol_module': 'cae/comsol/6.3', 'remote_dir': '/hkfs/work/workspace/scratch/'}. Gespeichert in cluster.json.

Inputs: values. Returns: result

comsol_cluster_fetchA

Cluster: Ergebnisse eines Jobs herunterladen (output.mph, batch.log, slurm-*.out) nach /cluster/runs//. Danach mit comsol_open(path=...) lokal öffnen und mit comsol_eval/comsol_plot auswerten. include_mph=false holt nur Logs.

Inputs: job_id, include_mph. Returns: result

comsol_cluster_statusA

Cluster: Status eines Jobs (Slurm-Zustand, Laufzeit, Ende von batch.log). job_id leer = alle bekannten Jobs mit Slurm-Zustand auflisten.

Inputs: job_id, log_lines. Returns: result

comsol_cluster_submitA

Cluster: COMSOL-Modell als Slurm-Batchjob rechnen. mph_file leer = aktuell lokal geöffnetes Modell in seiner gespeicherten Fassung (vorher comsol_save!). study: Studien-Tag (z. B. std1), leer = alle. params: {'name': 'wert'} überschreibt Parameter (comsol batch -pname/-plist). partition/time/nodes/cores/mem überschreiben cluster.json für diesen Job. Gibt job_id zurück; danach comsol_cluster_status und comsol_cluster_fetch.

Inputs: mem, time, cores, nodes, +7 more. Returns: result

comsol_desktopA

启动 COMSOL Desktop 并连接当前后端 server(client-server 模式),让用户能在图形界面里实时看到同一模型。open_file 可选,启动后打开该 .mph。注意:会弹出 Connect to Server 窗口,需要用户点一下 Connect。

Inputs: open_file. Returns: result

comsol_diagnoseA

模型体检:列出 COMSOL 报告的问题(未定义变量、空选择、几何/网格问题),并检查是否缺几何、物理场、材料、网格、研究或解。求解失败后先跑这个。

Inputs: no named parameters. Returns: result

comsol_evalA

对表达式求值并给出统计量(min/max/mean/size)。expression 例如 'T'、'es.normE'、'solid.mises';unit 可选,如 'degC'。dataset 为空时用默认数据集。

Inputs: expression (required), unit, dataset. Returns: result

comsol_exportB

把表达式在网格上的取值导出为 CSV(含索引与数值)。expression 如 'T',file 为输出路径(相对 comsol-bridge 目录)。适合后续用 Python/Excel 分析。

Inputs: file (required), expression (required), unit. Returns: result

comsol_geometryA

通用几何工具。action=list 列出现有几何和特征;create 新建特征(feature_type 如 Block/Cylinder/Sphere/Rectangle/Circle/Import/Union/Difference);update 改属性;delete 删除特征;run 重建几何。properties 是属性字典,如 {"size": ["0.1","0.1","0.1"], "pos": ["0","0","0"]}。模型没有组件/几何时会自动创建(dimension 指定 2 或 3)。

Inputs: tag, action, geometry, component, +3 more. Returns: result

comsol_helpA

COMSOL 建模速查,不访问 COMSOL。topic 可选 geometry/heat/solid/flow/electrostatics/selection/mesh/study/sweep。写模型前先查,能少踩属性名和单位的坑。

Inputs: topic. Returns: result

comsol_inspectA

查看当前模型的完整结构:参数、组件与维度、几何特征、物理场及其边界条件、材料、网格、研究、求解结果与数据集。做任何修改前先用它确认标签。

Inputs: no named parameters. Returns: result

comsol_materialA

材料工具。action=list 列出材料和当前物性;create 新建材料,preset 可选 copper/aluminum/steel/silicon/water/air,或用 properties 传自定义物性;update 改属性;remove 删除。属性名如 thermalconductivity、density、heatcapacity、youngsmodulus、poissonsratio、electricconductivity、relpermittivity、dynamicviscosity,值可带单位。

Inputs: tag, action, preset, component, +1 more. Returns: result

comsol_meshA

网格工具。action=list 查看特征树和统计;build 生成网格;size 设置全局尺寸(level 1-9,1 最细 9 最粗;或用 properties 自定义 hmax/hmin/hgrad/hcurve);add 添加网格特征(FreeTri/FreeQuad/Map/Sweep/BndLayer/Size/Distribution/Refine/Import);update 改属性或选择;remove 删除;stats 只看统计和质量。局部细化:add feature_type=Size,selection 传实体编号,entity_dim 传维度;边界层:先 add BndLayer,再 add BndLayerProp 且 parent 指向 BndLayer 的 tag。Sweep 的源面要传 selection_name='sourceface' 和 entity_dim=2(3D),层数用 parent=swe 的 Distribution 特征设置 numelem。Size/Distribution 会自动排到网格操作之前。结果含单元数、顶点数、最小/平均质量。

Inputs: tag, mesh, size, level, +8 more. Returns: result

comsol_modelA

模型管理。action=list 列出当前后端所有模型;remove 把模型从内存卸载(不删文件);rename 改模型显示名。切换当前模型用 comsol_use。

Inputs: name, action, new_name. Returns: result

comsol_openA

打开一个 .mph 模型,或新建空模型(new=true)。path 支持中文和相对路径(相对 comsol-bridge 目录)。打开后该模型成为当前操作对象。对于大模型(>50MB)加载可能需要几十秒。

Inputs: new, name, path. Returns: result

comsol_paramsA

读取或设置全局参数。values 为 {名称: 值} 字典时设置参数(值可带单位,如 '200[A]'、'1.5[mm]'),并返回设置后的全部参数;values 为空时只读取。evaluate=true 时返回数值(带单位换算到 SI)。

Inputs: values, evaluate. Returns: result

comsol_physicsA

通用物理场工具。action=list 列出接口和特征;add_interface 新建接口(physics_type 如 HeatTransfer/SolidMechanics/LaminarFlow/Electrostatics);add_feature 给接口加特征(feature_type 如 TemperatureBoundary/HeatFluxBoundary/InletBoundary);update_feature 设置选择或属性;remove_feature/remove_interface 删除。selection 传实体编号列表,或 named_selection 传命名选择的 tag。dimension 为特征维度,0 表示按几何自动推断(3D 边界=2,2D 边界=1)。

Inputs: tag, action, physics, component, +6 more. Returns: result

comsol_plotB

画结果图并导出 PNG。expression 例如 'T';unit 如 'degC';title 为图标题。自动按模型维度创建 2D/3D 表面图,file 为空时输出到 out/ 目录。返回图片路径。

Inputs: expression (required), file, unit, title, +2 more. Returns: result

comsol_pythonB

在当前 COMSOL 会话里执行 Python 代码(COMSOL Java API 逃生舱)。可用变量:model(mph Model)、java(model.java,com.comsol.model.Model)、client、mph、np、json。最后一行若是表达式会作为返回值。示例:java.modelNode('comp1').physics().create('ht','HeatTransfer','geom1')

Inputs: code (required). Returns: result

comsol_saveA

保存当前模型。path 为空时存回原文件;提供 path 时另存为。backup=true 时先把旧文件复制为 .bak-时间戳(不移动原文件),保存失败不会破坏原文件。返回 ok/error_code;SAVE_LOCKED 表示文件可能被 Desktop 打开。

Inputs: path, backup. Returns: result

comsol_screenshotA

截取 COMSOL Desktop 窗口为 PNG,让 AI 看到用户当前的界面和模型。file 为空时输出到 out/ 目录。窗口未找到时返回错误。

Inputs: file. Returns: result

comsol_selectionA

命名选择工具(对应 COMSOL 的 Box/Ball/Explicit Selection)。action=list 列出选择及其实体;create 创建选择;remove 删除。selection_type=Box 时用 box=[xmin,xmax,ymin,ymax,zmin,zmax](2D 可只给 4 个数);Ball 时用 center=[x,y,z] + radius;Explicit 时用 entities=[...]。entity_dim 为选择的实体维度:3=域、2=面(3D 边界)、1=边、0=自动取几何维度。condition 默认 intersects(与选择区域相交即选中),需要完全包含时传 inside。创建后可在 comsol_physics 里用 named_selection 把选择绑到边界条件上。

Inputs: box, tag, action, center, +6 more. Returns: result

comsol_solveA

运行研究(求解)。study 为空时用第一个研究。background=true 时立即返回 job_id,求解在后台进行,之后用 comsol_status 查看 job_status/耗时/结果;只有 status 可以在求解期间调用,其他修改类工具会快速返回 MODEL_BUSY。

Inputs: study, background. Returns: result

comsol_startA

连接或启动 COMSOL 后端。默认端口 2036:如果该端口已有 server 就连接它(例如 Desktop 已连上的 server),否则启动一个新的 server。cores 为 0 表示使用全部核心。首次启动约 10-20 秒。

Inputs: port, cores, version. Returns: result

comsol_statusA

查看 COMSOL 连接状态:是否已连接、端口、COMSOL 版本、已加载模型、当前模型、是否正在后台求解、上次错误。不会启动任何东西。

Inputs: no named parameters. Returns: result

comsol_stopA

断开并停止 COMSOL 后端。默认只断开当前客户端;stop_server=true 时同时关闭由本工具启动的 server 进程。Desktop 若正连着该 server 会被断开。

Inputs: stop_server. Returns: result

comsol_studyA

研究(study)工具。action=list 列出研究和求解步骤;create 新建研究(study_type: Stationary/Transient/Eigenfrequency/Frequency,properties 写 step 属性,如 {'tlist':'range(0,1,10)'});add_step 给已有研究加步骤;set 修改 study 或 step 属性;remove 删除研究。创建后用 comsol_solve 运行。

Inputs: step, study, action, properties, +1 more. Returns: result

comsol_sweepA

参数扫描工具。action=list 查看现有研究及扫描配置;add 给研究加 Parametric 特征(parameters 是参数名列表,values 是每个参数的取值串,空格分隔,长度需与 parameters 一致);remove 删除扫描。加完后正常 comsol_solve 就会对所有组合求解。

Inputs: study, action, values, parameters. Returns: result

comsol_useA

切换当前操作的模型。model 传模型名或 tag(见 comsol_status 的 models 列表)。一个后端可以同时加载多个 .mph,用这个工具指定后续操作作用于哪一个。

Inputs: model (required). Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 31 tools

    Disambiguation4/5

    Most tools target a clearly distinct resource+action (geometry, mesh, physics, study, selection, material each own one domain; solve/eval/plot/export/save/open are distinct lifecycle steps). Minor overlap exists between comsol_status, comsol_model, and comsol_use (all touch loaded-model listing/switching) and between comsol_inspect and comsol_diagnose, but descriptions give clear routing cues.

    Naming Consistency4/5

    All tools share a comsol_ prefix plus snake_case, giving a predictable namespace. The only deviation is stylistic: several tools are noun-based action-multiplexers (comsol_material, comsol_mesh, comsol_physics) while others are verb-based singletons (comsol_solve, comsol_plot, comsol_open), which is readable but not one pure verb_noun pattern.

    Tool Count3/5

    31 tools is heavy for a single server and effectively merges two surfaces: local modeling (~25 tools) and Slurm cluster orchestration (6 tools). Each tool does earn its place in a complex COMSOL workflow, but the breadth suggests it could be split into local and cluster servers.

    Completeness4/5

    Lifecycle coverage is strong: geometry, physics, mesh, study, material, and selection all have list/create/update/remove plus build/run, and the cluster flow is end-to-end (config, check, submit, status, fetch, cancel). Missing pieces are minor: no dataset/solution management tool, no file delete, and no multi-expression batch export.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      C
      maintenance
      Enables AI agents to automate COMSOL Multiphysics simulations, including model management, geometry building, physics configuration, meshing, solving, and results visualization through the MCP protocol.
      78
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables AI agents to automate COMSOL Multiphysics simulations, including model management, geometry building, physics configuration, meshing, solving, and results visualization via the MCP protocol.
      MIT
    • A
      license
      C
      quality
      D
      maintenance
      Enables AI agents to read and write .mph model files, control the COMSOL desktop GUI in real time, and run complete modeling, meshing, solving, and post-processing workflows.
      23
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to automate COMSOL Multiphysics simulations, covering model management, geometry building, physics configuration, meshing, solving, and results visualization via the Model Context Protocol.
      MIT