PLECS-MCP
PLECS-MCP exposes PLECS's JSON-RPC interface as MCP tools for automating model inspection, simulation, analysis, plotting, and file-level editing.
Connect to and auto-start local PLECS; discover methods, help, statistics, and endpoints.
Load/save/close models; read/set parameters and model trees; get one-call model briefings.
Run simulations and analyses, including parameter sweeps, summaries, saved large results, and timeouts.
Extract state-space matrices for switch combinations.
Control scopes and query the webserver for CSV data and bitmaps with slicing/decimation and safe image saving.
Generate code, export FMUs, run simulation scripts, compare models, and execute raw/batched RPC calls.
Validate models and check schematic layout/orientation; diagnose errors.
Capture/plot scope and analysis results as inline PNGs or files.
Submit and poll background tasks; run pass/fail acceptance checks.
Search the component library, scan/clone/edit
.plecsfiles structurally, inspect artifacts/FMU metadata, and post-process saved results with FFT/THD.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PLECS-MCP Load the buck converter model and run a simulation, then summarize the inductor current"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PLECS-MCP
An MCP server that exposes the complete Plexim PLECS Standalone JSON-RPC interface as MCP tools, built on fastmcp.
Highlights:
One MCP tool per RPC method (22/22 on PLECS 5.0.7), plus
plecs_rpcandplecs_batchescape hatchesplecs_run_scriptis verified:[model, {"ScriptName": name}]; script names are listed byplecs_overviewplecs_validatenow runs a static connection graph check: missing components, subsystem ports, C-Script terminal ranges, top-level Output indices and C-Script code indicesArgument preflight and
plecs://docs/gotchasreturn corrected shapes for common mistakes instead of leaving the agent to guessplecs_connectstarts PLECS automatically (macOS / Windows / Linux) when the RPC port is closedResults are structured JSON; big arrays are auto-written to disk instead of flooding the context
Read-only RPC calls run concurrently with a simulation; blocking/mutating calls are serialized
Write guardrails: install dirs are refused, stray paths need
PLECS_MCP_ALLOWED_ROOTS, overwrites needoverwrite=trueIrreversible operations (
protect,crash) requireconfirm=trueMCP resources ship the RPC/analysis/error references the agent needs
plecs_capture/plecs_plotreturn inline PNG images; rawplecs_webserverbitmaps are saved to diskAsync tasks (
submit/task/task_result), acceptance checks, component-library search, file-level model cloning and local FFT/THD post-processing
Requirements
PLECS Standalone running locally
RPC enabled in Preferences → RPC (default port
1080)Python 3.10+ (tested with 3.13)
Related MCP server: SimuBridge
Install
cd "/Users/guohuawei/Workspace/AI Usecase/PLECS-MCP"
uv venv --python 3.13 .venv
uv pip install -e . --python .venv/bin/pythonRun
.venv/bin/python -m plecs_mcp # stdio (local agents)
.venv/bin/python -m plecs_mcp --transport http --port 8765 # remote agents
.venv/bin/plecs-mcpCodex (~/.codex/config.toml):
[mcp_servers.plecs]
command = "/Users/guohuawei/Workspace/AI Usecase/PLECS-MCP/.venv/bin/python"
args = ["-m", "plecs_mcp"]Claude Desktop / Cursor (mcpServers JSON):
{
"mcpServers": {
"plecs": {
"command": "/Users/guohuawei/Workspace/AI Usecase/PLECS-MCP/.venv/bin/python",
"args": ["-m", "plecs_mcp"]
}
}
}Transports: stdio (default), http, sse, streamable-http.
Binding a non-loopback host is refused unless PLECS_MCP_ALLOW_REMOTE=1 is set (there is no auth).
Quickstart (3 minutes)
.venv/bin/python examples/quickstart.py --model /path/to/model.plecs
.venv/bin/python examples/quickstart.py --model /path/to/model.plecs \
--analysis "Loop Gain (AC Sweep)"Runs connect → load → simulate (summary) → close, prints per-signal min/max/mean/rms and,
for AC sweeps, gain crossover + phase margin. Without --model it uses PLECS_EXAMPLE_MODEL
or a bundled PLECS demo.
Configuration
Resolution order: environment variables → config.yml → defaults.
config.yml is looked up at $PLECS_MCP_CONFIG, then ./config.yml, then the repo root.
plecs:
host: "127.0.0.1"
port: 1080
timeout: 30Variable | Default | Description |
| – | Explicit path to |
|
| Localhost only (PLECS restriction) |
|
| Must match the PLECS preference |
|
| Read timeout for non-simulation calls |
|
|
|
|
| Above this, results are saved and summarised |
|
| Above this, scope CSV is saved and summarised |
|
| Destination for auto-saved results |
|
| Write roots ( |
|
| RPC timing/error logging on stderr |
| – | Allow non-loopback HTTP bind |
|
| Default for |
| auto-detect | PLECS binary/bundle used by auto-start (alias: |
| auto-detect | Explicit |
Auto-start
plecs_connect(auto_start=True) (default, configurable with PLECS_MCP_AUTO_START=never or
--auto-start never) probes host:port; if the port is closed it locates
the newest install for the host OS, launches it, and polls the port for startup_timeout
(default 30 s):
Host | Discovery | Command |
macOS |
|
|
Windows |
| spawn |
Linux |
| spawn |
Before launching it checks whether a PLECS process already exists (pgrep / tasklist); if so it
skips the launch and tells you to enable Preferences → RPC instead of waiting 30 s.
Overrides: the app_path argument, PLECS_EXECUTABLE, PLECS_APP_PATH.
PLECS RPC is localhost-only, so the MCP server and PLECS must run on the same machine.
Tools
Tool | RPC method | Notes |
|
| Handshake; auto-starts PLECS, returns version + |
|
| Capability discovery |
|
| PLECS help text |
|
| Licence hints, open models, run state |
|
| Returns |
|
| Refuses when this session changed the model ( |
|
|
|
|
| Base64 JSON → parsed; |
|
| Parameter value (string) or all parameters |
|
| Expression string; marks the model dirty |
|
| optStruct or list; |
|
| Name property; |
|
| Switch vector built from |
|
| HoldTrace / RemoveTrace / ClearTraces / SaveTraces / LoadTraces (simulate before SaveTraces) |
|
|
|
|
| Requires Coder; diagnostics are surfaced verbatim |
|
| Atomic subsystems only |
|
| Verified: |
|
| Raw lines + parsed |
|
| Runtime counters |
|
| Global FMU co-simulation switch |
|
| Appends the demo signature (modifies the file) |
|
| Irreversible once saved; |
|
| Terminates PLECS; |
| any | Several RPC calls in one tool call, per-call errors inline |
| tree + get + statistics | One-call model briefing (solver, analyses, scopes, outports, scripts) |
| tree + get + | Structural and connection pre-flight checks (errors/warnings/diagnostics) |
|
| Geometry: overlapping component boxes, diagonal wires, wires drawn across a device |
|
| Scope screenshot as an inline PNG |
| simulate / analyze | Waveform or Bode PNG — PLECS bitmap by default, matplotlib fallback |
| simulate/analyze/codegen | Background tasks with polling |
| simulate + analyze | Pass/fail assertions (signal/time/analysis metrics) |
|
| Search the installed component library |
| – | Regex-search a |
| – | Copy/rename/patch a model file, then load-validate |
| – | Structural edits: add/remove component, set parameter, rotate/move, wire, add outport |
| – | List codegen/FMU output files |
| – | Read |
| – | Metrics + FFT/THD on a saved JSON result |
| – | Explain a PLECS error string |
| – | Known endpoints, active one flagged |
| any | Raw passthrough |
Return shape
Most tools return a JSON object (structured content). plecs_capture and plecs_plot return MCP
image content when inline=true (the default) and JSON metadata when inline=false:
dict results as-is; scalars/arrays wrapped as
{"result": ...}plecs_list_methods→{"methods": [...]};plecs_compare→{"diff": [...], "entries": [...]}plecs_connect→{"ok": true, "capabilities": {...}, ...}or{"ok": false, "hints": [...]}plecs_batch→{"count": n, "results": [{"ok": ..., "result"|"error": ...}]}
Data policy (large results)
Situation | Behaviour |
Simulation above | Full JSON saved under |
| Raw arrays replaced by |
Scope CSV above | Full CSV saved, response has |
| Applied client-side (PLECS ignores its own range options) |
| Base64 MAT decoded and written to |
PNG payloads | Written to |
| Nested base64 bitmaps are saved as |
MCP-mediated writes are refused inside /Applications, /System, /Library, /usr, /bin,
/sbin, /etc, and outside PLECS_MCP_ALLOWED_ROOTS. Existing files are never overwritten
without overwrite=true. PLECS-side outputs (FMU export) follow the path configured in the model.
MCP resources
The server exposes reference documents as MCP resources (no tool call needed):
URI | Content |
| end-to-end workflow |
| RPC method table and quirks |
| SolverOpts/ModelVars/analysis result shapes |
| symptom → cause → next step |
| data policy and write guardrails |
| exact argument shapes and common traps |
Images and plots
plecs_capture(model[, scope|analysis_name])returns the PLECS scope/analysis bitmap as an MCP image.plecs_plot(..., renderer="auto")— default: PLECS-rendered bitmap (same styling as the GUI).renderer="plecs"forces it (error if no Scope/analysis plot exists);renderer="matplotlib"renders locally and is the only way to overlay several responses.Waveform: runs a short simulation (default TimeSpan 1e-3 s);
renderer="plecs"captures the model Scope,matplotlibplots the top-level outports (requires at least one).Bode: runs
plecs.analyzethen captures<model>/Analyses/<Name property>; matplotlib usesF/Gr/Gi.Both accept
save_to(write a PNG) andinline=false(metadata:renderer,bytes).
Async tasks
plecs_submit("plecs.simulate", [model, opts]) returns {id, status}; poll with
plecs_task(id) and fetch with plecs_task_result(id). Only blocking methods are accepted, PLECS
still runs one at a time, and large results are stored as summary + file path.
Task records are persisted to PLECS_MCP_TASK_DIR (default ~/.plecs-mcp/tasks). After a server
restart, finished tasks are still readable and anything that was running is reported as lost
instead of pretending to be in progress.
Acceptance checks
plecs_check(model, checks, options=..., analysis_name=...) runs the needed simulation/analysis
and evaluates assertions:
[{"type": "signal", "index": 0, "metric": "rms", "op": ">", "value": 10},
{"type": "time", "metric": "stop", "op": ">=", "value": 0.001},
{"type": "analysis", "metric": "phase_margin_deg", "op": ">", "value": 45}]The response contains passed, per-check actual/pass, and the summaries used.
Discovery and file-level editing
plecs_library_search("resistor")parses the installedComponents.plecsas text (≈9.7k components, 0.6 s cold / 5 ms cached) — works without PLECS and without the 43 MB RPC tree.Components.plecsis located next to a macOS.appbundle or a Windows/Linux install binary (PLECS_LIBRARY_PATHoverrides discovery). Cache lives next to the output dir;refresh=truerebuilds it.backend="auto"(default) keeps the RPC model tree as a fallback: if the file is missing, unreadable, corrupt, or yields 0 components, the call ensures a PLECS connection first — starting PLECS automatically when it is not running (same policy asplecs_connect) — then retries over RPC and reportsbackend="rpc",fallback_reasonandautostarted. If PLECS is not installed (or its RPC preference is off), the error says so. Usebackend="text"or"rpc"to force one path.plecs_scan(path, "TimeSpan")greps model text without loading it.plecs_model_edit(path, operations, confirm|output)performs structural edits on a copy of a.plecsfile: add/remove components, set parameters, wire terminals, add outports. Everything outside the edited span stays byte-identical (including CRLF line endings); the result is loaded in PLECS to verify. In-place edits obey the normal write policy and create a.bak-<ms>backup. This is the alternative to schematic editing, which the RPC does not expose.plecs_model_clone(...)remains for copy + regex-level rewrites.plecs_artifacts(dir)/plecs_fmu_info(path)inspect codegen output and FMU metadata.
Local post-processing
plecs_analyze_data(result_path, fundamental=50) works on a saved JSON result (the ones written
by the inline-point limit): per-signal metrics plus FFT-based THD and harmonic amplitudes. Parameter
sweeps are saved as a JSON list and are summarised per entry. This covers the "arbitrary code
execution" gap without touching PLECS' console.
Concurrency
Measured on PLECS 5.0.6: statistics returns in 0.01 s while a 0.55 s simulation is running,
and a second simulate still waits for the first. The client mirrors that:
read-only calls share a read lock and run concurrently with a simulation
simulate/analyze/codegen/exportfmu/runScripttake a single "blocking" slot (PLECS allows one)load/close/save/set/scope/protecttake the exclusive write lock, so state never changes mid-run
Verified behaviour (PLECS 5.0.6)
simulatereturnsValuesas signals × time over JSON-RPC; summaries normalise both orientations.Models without top-level outports return
{"Time": [], "Values": []}and a summarynote.Only nested
{"SolverOpts": {"TimeSpan": ...}}is honoured; flat{"StopTime": ...}is silently ignored.SolverOpts.Timeoutworks for bothsimulateandanalyze;AnalysisOpts.Timeoutis rejected.analyzeneeds the analysis Name property;plecs.scopesupports noExportCSV/GetCursorData.plecs.webserverignoresTimeRange/Size; slicing and decimation happen in this server.plecs.save(model, save_as)renames the open model; the session registry follows the rename.plecs.protect(path)takes one subsystem path, returns 0, is idempotent, and only becomes permanent on save.plecs.exportfmu(path)accepts one path and requires an atomic subsystem.plecs.codegen(model)runs and returns Coder diagnostics as an RPC error string.plecs.runScript(model, {"ScriptName": name})works; the second argument is an optStruct, not a bare string. A successful run returnsnulland the script's output goes to the PLECS console/Octave log. The script name is theNameof aScript { ... }block in the.plecsfile (see demos such asbuck_converter_with_parameter_sweep).Business errors still return HTTP 200; the JSON
errorfield becomes a tool error.trust_env=False: macOS system proxies can hijack127.0.0.1:1080(HTTP 502), so PLECS is never reached through a proxy.
Known limitations
The RPC model tree exposes outport names and positions but no port index, so channel
iis not auto-labelled;summary.outportsis provided instead of guessing..tracefiles (scope SaveTraces) use a private format and are not parsed.plecs.runScriptreturnsnull; the script's printed output goes to the PLECS console/Octave log and is not captured by the RPC response. Scripts that callplecs('scope', ...)internally can close other open models;plecs_run_scriptsnapshots and reports them asclosed_models.Script names are not exposed by
getModelTree; read theScript { Name "..." }block in the.plecsfile (or search it withplecs_scan) before callingplecs_run_script.All JSON-RPC error messages are forwarded verbatim (including multi-line text and any
error.data); MCP does not truncate them. C-Script compilation errors are special only because PLECS itself sends a summary (component + phase); full Clang details are only in the PLECS Diagnostics dialog. Useplecs_get(model/component)to inspect the code segments andplecs_diagnosefor next steps, or ask the user for the Diagnostics contents.plecs_validategraph checks are static: they cover component references, subsystem ports, C-Script port/code indices and top-level Output indices. Built-in component terminal counts are not available in.plecs, so PLECS Diagnostics remains authoritative for those cases.PLECS can segfault inside its own compiler for some models; that is not an MCP error. If the connection drops during
plecs.simulate/plecs.analyze/plecs.get(model, "Topology"), MCP reports[plecs-crash]with the Crashpad dump path, restarts PLECS once and quarantines that file version, so retrying the identical call is refused instead of crashing again. Edit the model (or load a copy that compiled) to release it.plecs_layout_check(..., include_orientation=True)addsLAYOUT-004(info): the placement convention is measured from the 239 bundled models, not invented. Horizontal power parts put terminal 1 on the right (inductor 78% of 359, breaker 100% of 18), vertical passives and sources put it at the bottom (capacitor 100% of 270, DC source 100% of 181), vertical diodes and thyristors put it on top (96% of 219, 77% of 30). Only (type, axis) pairs with >=10 samples and >=70% agreement are checked; each finding carries thedirection/flippedto apply, and the corpus replay drops from 65% of models to 9%. Off by default.plecs_layout_checkuses the bounding box per component thatgetCircuitBitmapreturns, plusPosition/Pointsfrom the text. It reportsLAYOUT-001(error: two component boxes intersect),LAYOUT-002(warning: diagonal wire segment) andLAYOUT-003(info: a wire drawn across a device). Crossings are cosmetic - PLECS connects only through explicit connections - and overlay blocks (HeatSink,Goto,From) are excluded because PLECS ships demos that draw them on top of devices. The implicit last hop from a corner to a terminal is not checked.plecs_webservercommand arguments differ:getScope*take a scope path,getCircuitBitmaptakes the model name, andgetCursorDatatakes[scope, {"Index": 0}](a bare integer is rejected).plecs_scope("SaveTraces", ...)requires simulation data in the scope; a scope that has never simulated writes a.tracefile thatLoadTracesrejects. Run a simulation first (HoldTracealone does not create data). Seeplecs://docs/gotchas.PLECS 5.0.6 closes other open models while serving
getScopeCsv/getScopeBitmap. Theplecs_webserver/plecs_captureresponses reportclosed_modelswith a warning (and the server logs it); models are not auto-reloaded because that could discard unsaved changes.plecs_model_edithandles structure (components/params/wires/outports) and orientation (direction/flippedwhen adding,set_orientation,set_position) but does not do automatic layout or route wires around obstacles; coordinates are caller-supplied. PLECS RPC cannot changeDirection/Flipped/Position(plecs.setreportsUnknown parameter), so layout is text-level and needs a reload. Rotating a placed component invalidates explicitPoints; there is no delete-connection/set-points operation, so delete thePointslines in the text (or rewrite the corners) and reload - re-connectappends a duplicate Connection and leaves the stalePoints(verified on 5.0.6: identical bitmap). In-place editing is subject toPLECS_MCP_ALLOWED_ROOTSand is refused inside install directories.Gain crossover/phase margin only make sense for loop-gain AC sweeps; other analysis kinds are labelled.
Auto-start picks the newest install for the host OS: macOS
/Applications/PLECS*.app, Windows%ProgramFiles%\Plexim\*\plecs.exe, LinuxplecsonPATHor/opt/plecs*/plecs. Other platforms returnunsupported-platformand require a manual start.One MCP server instance manages one PLECS instance (localhost).
Example workflows
# parameter sweep (PLECS-native parallel)
plecs_simulate(model, options=[{"ModelVars": {"R": 10}}, {"ModelVars": {"R": 47}}], summary=True)
# Bode / loop gain
plecs_analyze(model, "Loop Gain (AC Sweep)", summary=True)
# → responses[0].gain_crossover_hz / phase_margin_deg / stable
# Simulation Script by name (from the .plecs Script block)
plecs_run_script(model, "Parameter Sweep (Sequential)")
# scope export with client-side slicing
plecs_webserver("getScopeCsv", [f"{model}/Scope"], time_range=[0, 1e-3], decimate=10)
# state space at one switch combination
plecs_state_space(model, {"FET": 1, "D": 0})
# acceptance gate
plecs_check(model, [{"type": "signal", "index": 0, "metric": "rms", "op": ">", "value": 10},
{"type": "analysis", "metric": "phase_margin_deg", "op": ">", "value": 45}],
analysis_name="Loop Gain (AC Sweep)")
# background run + poll
plecs_submit("plecs.simulate", [model, {"SolverOpts": {"TimeSpan": 0.5}}])
plecs_task("<id>"); plecs_task_result("<id>")
# figure (PLECS-rendered by default)
plecs_plot(model, kind="bode", analysis_name="Loop Gain (AC Sweep)")
plecs_plot(model, kind="waveform", renderer="matplotlib") # only for overlays
# structural model edit
plecs_model_edit(path, confirm=True, operations=[
{"op": "add_component", "type": "Resistor", "name": "R2",
"position": [400, 200], "direction": "right", "flipped": "off",
"parameters": {"R": "10"}},
{"op": "set_orientation", "component": "R2", "direction": "up", "flipped": "on"},
{"op": "set_position", "component": "R2", "position": [400, 240]},
{"op": "connect", "source": "V_dc", "source_terminal": 1,
"target": "R2", "target_terminal": 1},
{"op": "add_outport", "name": "Vout", "position": [600, 200]}])
# cheap multi-read
plecs_batch([{"method": "plecs.get", "params": [f"{model}/L1", "L"]},
{"method": "plecs.get", "params": [f"{model}/C1", "C"]}])Error table
Symptom | Meaning | Next step |
| RPC port closed | Run |
| Method missing in this build |
|
| Invalid parameters | Check the tool schema; |
| Wrong analysis name | Use the Name property from |
| Unsupported scope command | Use |
| A proxy intercepted localhost | Client already uses |
| File exists | Pass |
| Write blocked | Choose a path under |
Tests
.venv/bin/python -m pytest -q # 170 testsCurrent release: 0.4.4 — see CHANGELOG.md.
Unit: base64/model tree, summary maths, config precedence, paths, locks, app discovery/launch, plotting, checks, tasks, THD, model scan/clone, artifacts/FMU, library flattening, resources, sweep-result post-processing, image externalisation, task age ordering, CRLF round-trip
Surface: all 45 tools registered/documented; destructive tools need confirmation; batch/limits/guards
Integration: when
127.0.0.1:1080is reachable, exercises connect/load/tree/get/simulate/analyze/ summary/CSV/capture/plot/tasks/check/compare/model_edit on/tmpcopies of the bundled demos (user models are never touched)
CI (.github/workflows/ci.yml) runs the unit/surface suite on Python 3.10 and 3.13 on Ubuntu and
macOS; integration tests skip automatically when PLECS is not installed.
Layout
src/plecs_mcp/client.py JSON-RPC client (RW lock, timeouts, logging, no proxy)
src/plecs_mcp/config.py config.yml + environment resolution
src/plecs_mcp/paths.py write guardrails and output directories
src/plecs_mcp/session.py model registry (path, dirty flag, rename tracking)
src/plecs_mcp/codec.py base64 decoding, tree/compare parsing, CSV slicing
src/plecs_mcp/summary.py time-series statistics, Bode margins, analysis kinds
src/plecs_mcp/launcher.py per-OS discovery/launch, port polling, process check
src/plecs_mcp/diagnose.py error → cause → next steps
src/plecs_mcp/resources.py MCP reference documents
src/plecs_mcp/plotting.py waveform/Bode PNG rendering
src/plecs_mcp/tasks.py background task registry
src/plecs_mcp/checks.py declarative acceptance checks
src/plecs_mcp/library.py component-library browsing (RPC tree fallback)
src/plecs_mcp/library_text.py Components.plecs text parser + disk cache
src/plecs_mcp/plecsfile.py .plecs parser and structural editor
src/plecs_mcp/modelops.py model scan/clone
src/plecs_mcp/artifacts.py codegen output + FMU metadata
src/plecs_mcp/data.py local metrics/FFT/THD
src/plecs_mcp/server.py 45 MCP tools + 6 resources
examples/quickstart.py end-to-end smoke test
tests/ unit + surface + integrationAvailable Tools
45 toolsplecs_analyzePlecs AnalyzeA
Run an analysis (blocking).
analysis_name is the analysis NAME property (e.g. "Loop Gain (AC Sweep)"), not the
tree node label ("AC Sweep"). AC/Impulse/Multitone return {F, Gr, Gi};
Steady-State returns {Time, Values}. summary=true replaces raw arrays with
magnitude/phase ranges plus gain crossover and phase margin.
SolverOpts.Timeout is injected (verified: AnalysisOpts.Timeout is rejected).
Inputs: model_name (required), analysis_name (required), options, save_to, +4 more. Returns: object
plecs_analyze_dataPlecs Analyze DataBRead-only
Post-process a saved JSON result: metrics, and optional FFT/THD at a fundamental.
Accepts a single result object or the list written for a parameter sweep; list
entries are summarised (and THD-processed when fundamental is given).
Inputs: result_path (required), signal, harmonics, fundamental. Returns: object
plecs_artifactsPlecs ArtifactsCRead-only
List generated files (code generation / FMU output) with sizes.
Inputs: directory (required), limit, pattern. Returns: object
plecs_batchPlecs BatchA
Run several RPC calls in one tool call (still serialized by the client lock).
Each item is {"method": "plecs.get", "params": ["mdl/L1", "L"], "timeout": 30}.
Per-call failures are reported inline as {"ok": false, "error": ...} instead of
aborting the batch, which makes parameter sweeps and multi-model inspection cheap.
Inputs: calls (required), stop_on_error. Returns: object
plecs_capturePlecs CaptureC
Render a scope or analysis plot as a PNG (inline image, or a file with save_to).
analysis_name maps to <model>/Analyses/<Name property>; run the analysis first.
Inputs: model_name (required), inline, save_to, overwrite, +2 more.
plecs_checkPlecs CheckC
Run simulations/analyses and evaluate pass/fail assertions.
Check examples::
{"type": "signal", "index": 0, "metric": "rms", "op": ">", "value": 10}
{"type": "time", "metric": "stop", "op": ">=", "value": 1e-3}
{"type": "analysis", "metric": "phase_margin_deg", "op": ">", "value": 45}Inputs: checks (required), model_name (required), options, analysis_name, +1 more. Returns: object
plecs_closePlecs CloseADestructive
Close a model WITHOUT saving. Refuses when this session changed it via plecs_set.
PLECS exposes no "dirty" flag, so the guard only knows about edits made through this
MCP session; pass force=true to discard them.
Inputs: model_name (required), force. Returns: object
plecs_codegenPlecs CodegenB
Generate code with PLECS Coder (requires a PLECS Coder licence).
Verified on 5.0.6: plecs.codegen runs and streams Coder diagnostics back as an RPC
error ("Code generation error: ..."), which is surfaced verbatim. A model with blocks that
are ignored during code generation (e.g. Small Signal Response) fails instead of producing
partial artifacts.
Inputs: path (required), options, output_dir. Returns: object
plecs_comparePlecs CompareBRead-only
Compare two model files with PLECS's diff engine.
Returns the raw MergedItem(...) lines plus parsed entries
(depth/left/right/change/type) for direct use.
Inputs: after_path (required), before_path (required). Returns: object
plecs_connectPlecs ConnectAIdempotent
Handshake/health check; starts PLECS automatically when the RPC port is closed.
If the endpoint is unreachable and auto_start is true (default, or
PLECS_MCP_AUTO_START=always), the newest PLECS installation for this host is
launched and the port is polled for up to startup_timeout seconds.
Set auto_start=false (or PLECS_MCP_AUTO_START=never) for a pure health check.
Returns {"ok": true, "started": ..., ...} or {"ok": false, "launch": {...}, "hints": [...]}.
Inputs: host, port, app_path, auto_start, +1 more. Returns: object
plecs_crashPlecs CrashADestructive
Crash the running PLECS process (debug helper). Requires confirm=true.
Inputs: confirm. Returns: object
plecs_diagnosePlecs DiagnoseARead-only
Explain a PLECS error string and suggest next steps.
Inputs: error_text (required). Returns: object
plecs_export_fmuPlecs Export FmuADestructive
Export a subsystem as an FMU (uses the subsystem's saved FMU Export settings).
Verified on 5.0.6: only an atomic subsystem can be exported; a normal subsystem returns "Cannot export FMU for non-atomic subsystem". The signature is a single subsystem path.
Inputs: subsystem_path (required). Returns: object
plecs_extract_execution_log_dataPlecs Extract Execution Log DataARead-only
Runtime execution-log counters (Jacobian/Newton/solver call counts) for the last run.
Inputs: no named parameters. Returns: object
plecs_fmu_infoPlecs Fmu InfoARead-only
Read FMI metadata from an .fmu/.zip or an unpacked folder.
Inputs: path (required). Returns: object
plecs_getPlecs GetARead-only
Read a component/model parameter (model params too, e.g. "TimeSpan").
Values come back as strings; without parameter a dict of all parameters is returned.
For a C-Script component this includes Declarations, StartFcn, OutputFcn, UpdateFcn,
DerivativeFcn and TerminateFcn, which is the first step after a compilation error.
Inputs: path (required), parameter. Returns: object
plecs_get_model_treePlecs Get Model TreeARead-only
Return the model tree (needs an absolute path; PLECS returns base64 JSON).
summary=True drops connections and returns counts plus analysis/subsystem/component names.
decode=False returns {"result": "<base64>"} unchanged.
Inputs: model_path (required), decode, summary. Returns: object
plecs_instancesPlecs InstancesBRead-only
Known PLECS endpoints for this server process (the active one is flagged).
Inputs: no named parameters. Returns: object
plecs_layout_checkPlecs Layout CheckARead-only
Check schematic geometry of a model that is open in PLECS.
Uses the bounding box per component from plecs.webserver getCircuitBitmap
plus Position/Points from the .plecs text, and reports only what is
certain: LAYOUT-001 (error) two component boxes intersect, LAYOUT-002
(warning) a wire polyline has a diagonal segment, LAYOUT-003 (info) a wire
is drawn across a component that is not one of its endpoints, LAYOUT-004
(info) a polar two-terminal part has terminal 1 on the wrong side for reading
order (horizontal: left, vertical: top) and carries the exact direction /
flipped to apply. Orientation is opt-in (include_orientation=True): it is a
house style, and roughly two thirds of the bundled demos do not follow it. A crossing is cosmetic - PLECS connects only through
explicit connections - but it makes the schematic hard to read.
Top-level schematic only; margin absorbs the ~2 unit rounding between
schematic coordinates and rendered pixels.
Inputs: model_name (required), margin, include_wires, include_orientation. Returns: object
plecs_library_searchPlecs Library SearchB
Search the installed PLECS component library (types, names, default parameters).
backend: auto (default) parses Components.plecs as text and falls back to the
RPC model tree if the file is missing, unreadable, corrupt, or yields no components;
text / rpc force one path. The response reports backend and, when a fallback
happened, fallback_reason.
Inputs: limit, query, backend, refresh. Returns: object
plecs_list_methodsPlecs List MethodsARead-only
List RPC methods supported by the running PLECS build (system.listMethods).
Inputs: no named parameters. Returns: object
plecs_loadPlecs LoadB
Open a model file. model_path must be absolute. Returns {"result": 0} on success.
Inputs: model_path (required). Returns: object
plecs_method_helpPlecs Method HelpBRead-only
Return PLECS's own help text for an RPC method (system.methodHelp).
Inputs: method (required). Returns: object
plecs_model_clonePlecs Model CloneADestructive
Copy a model file, optionally rename/rewrite lines, then load it to verify.
replacements is a list of {"pattern": <regex>, "value": <replacement>}.
This is the file-level alternative to schematic editing (PLECS RPC cannot edit a model).
Inputs: source (required), target (required), name, validate, +2 more. Returns: object
plecs_model_editPlecs Model EditADestructive
Edit a .plecs file structurally (PLECS RPC cannot modify a schematic).
Operations (applied in order)::
{"op": "add_component", "type": "Resistor", "name": "R2",
"position": [400, 200], "direction": "right", "flipped": "off",
"parameters": {"R": "10"}}
{"op": "remove_component", "name": "R2"}
{"op": "set_parameter", "component": "R2", "variable": "R", "value": "22"}
{"op": "set_orientation", "component": "R2", "direction": "up", "flipped": "on"}
{"op": "set_position", "component": "R2", "position": [400, 240]}
{"op": "connect", "source": "V_dc", "source_terminal": 1,
"target": "R2", "target_terminal": 1, "points": [[110, 200], [400, 200]]}
{"op": "add_outport", "name": "Vout", "position": [600, 200]}direction is right/left/up/down and flipped is on/off:
set them when the component is added (or use set_orientation later) so the
terminal sides match the intended signal flow. Rotating a placed component
invalidates explicit Points; drop them or re-run connect so PLECS re-routes.
In-place editing requires confirm=true, obeys the same write policy as other
tools (allowed roots, no install dirs), and creates a .bak-<ms> backup; pass
output to write elsewhere. validate loads the result in PLECS and rolls
back the in-place edit if loading fails.
Inputs: path (required), operations (required), output, confirm, +1 more. Returns: object
plecs_overviewPlecs OverviewARead-only
One-call model briefing: files, state, solver settings, analyses, scopes, outports.
Cheaper than stitching statistics + get + getModelTree together yourself.
Inputs: model_name (required). Returns: object
plecs_plotPlecs PlotB
Run a simulation/analysis and return a PNG.
renderer: auto (default) prefers the PLECS-rendered bitmap; plecs forces
it (error if unavailable); matplotlib always renders locally (needed for overlays).
kind="waveform" runs a short simulation (default TimeSpan 1e-3 s);
kind="bode" requires analysis_name (the analysis Name property).
Inputs: model_name (required), kind, inline, options, +5 more.
plecs_protectPlecs ProtectADestructive
Make a subsystem non-viewable/non-modifiable. IRREVERSIBLE once saved; requires confirm=true.
Verified on 5.0.6: the call takes a single subsystem path, returns 0, and is idempotent; it changes the open model only, so the protection becomes permanent when you save it.
Inputs: subsystem_path (required), confirm. Returns: object
plecs_rpcPlecs RpcC
Raw escape hatch: call any PLECS RPC method verbatim.
Dict results are returned as-is; scalars and arrays are wrapped as {"result": ...}.
Inputs: method (required), params, timeout. Returns: object
plecs_run_scriptPlecs Run ScriptA
Run a model Simulation Script by name.
Verified on PLECS 5.0.6: the second argument is an optStruct, not a bare
string — plecs.runScript(model, {"ScriptName": name}). A successful run
returns null; the script's printed output goes to the PLECS console/Octave
log and is not captured by RPC. Use params only for a raw override.
script_name must exactly match a Script { Name "..." } block in the
.plecs file. The RPC model tree does not expose script names; use
plecs_overview(model).scripts or read the file. A wrong name lists the
available scripts in the error.
Inputs: model_name (required), script_name (required), params. Returns: object
plecs_savePlecs SaveAIdempotent
Save a model. With save_as the open model is RENAMED to the new file (use the new name afterwards).
save_as is checked against the write policy: install dirs are refused and an existing
target requires overwrite=true.
Inputs: model_name (required), save_as, overwrite. Returns: object
plecs_scanPlecs ScanARead-only
Regex-search a .plecs file on disk without opening it in PLECS.
Inputs: pattern (required), model_path (required), max_hits, ignore_case. Returns: object
plecs_scopePlecs ScopeC
Send a command to a scope (HoldTrace / RemoveTrace / ClearTraces / SaveTraces / LoadTraces).
Inputs: command (required), scope_path (required), argument. Returns: object
plecs_setPlecs SetCIdempotent
Set a parameter. value is a PLECS expression string (numbers are passed through).
Inputs: path (required), value (required), parameter (required). Returns: object
plecs_set_cosim_server_enabledPlecs Set Cosim Server EnabledC
Enable/disable the PLECS FMU Co-Simulation endpoint (global PLECS state).
Inputs: enabled (required). Returns: object
plecs_signPlecs SignBDestructive
Append the PLECS demo signature to a model file (modifies the file).
Inputs: file_path (required). Returns: object
plecs_simulatePlecs SimulateA
Run a simulation (blocking).
options is the PLECS optStruct (ModelVars / SolverOpts / OutputFormat);
pass a LIST of optStructs to let PLECS parallelize parameter sweeps.
Only models with top-level Outports return data ({"Time": [...], "Values": [...]};
over JSON-RPC, Values is signals x time). save_to writes a MatFile result to disk.
summary=true replaces the raw arrays with per-signal min/max/mean/p2p/rms.
Results above max_points (default 20000) are written to the MCP output dir and
returned as a summary. SolverOpts.Timeout is injected (default 600 s) so PLECS
aborts on its own even if the client gives up.
Inputs: model_name (required), options, save_to, summary, +3 more. Returns: object
plecs_state_spacePlecs State SpaceAIdempotent
Extract A/B/C/D/I for one switch combination.
switches may be a list in StateSpaceOrder.Switches order, or a mapping keyed by
component name ("FET") or full path ("model/FET"). Missing keys default to 0.
Two RPC calls are made for you: set SwitchVector then get Topology.
Inputs: model_name (required), switches. Returns: object
plecs_statisticsPlecs StatisticsARead-only
PLECS usage statistics: licence hints plus every open model and its state.
Inputs: no named parameters. Returns: object
plecs_submitPlecs SubmitA
Start a long blocking call in the background and return a task id.
Allowed methods: simulate, analyze, codegen, exportfmu, runScript.
For runScript pass [model, {"ScriptName": name}]. PLECS has no cancel API;
use SolverOpts.Timeout to bound the run.
Inputs: method (required), params, timeout. Returns: object
plecs_taskPlecs TaskCRead-only
Status/elapsed time for a background task.
Inputs: task_id (required). Returns: object
plecs_task_resultPlecs Task ResultARead-only
Fetch a finished task's result (large payloads arrive as summary + saved path).
Inputs: task_id (required). Returns: object
plecs_tasksPlecs TasksBRead-only
List background tasks, newest first.
Inputs: no named parameters. Returns: object
plecs_validatePlecs ValidateARead-only
Structural sanity check before simulating.
Checks solver/time settings, outports, analyses, and (by default) the native
.plecs connection graph: component references, subsystem ports, C-Script
terminal ranges, top-level Output indices, and C-Script code indices.
Warning-level findings do not change ok.
Inputs: model_name (required), include_code, include_connections. Returns: object
plecs_webserverPlecs WebserverA
Undocumented PLECS webserver channel (verified on PLECS 5.0.6).
Commands: getScopeInfo, getTraceNames, getScopeSignals, getScopeCsv, getCursorData,
getScopeBitmap, getCircuitBitmap. Pass the command's own arguments in arguments.
getScope* take a scope path; getCircuitBitmap takes the model name;
getCursorData also accepts [scope, {"Index": 0}] (a bare integer is rejected).
getScopeCsv is base64 CSV; PLECS ignores its own range/size options, so
time_range=[t0,t1] and decimate=N are applied here. CSVs above max_rows
(default 50000) are written to the MCP output dir and only metadata is returned.
Base64 images (getScopeBitmap, getCircuitBitmap, getScopeSignals) are
written to save_to (or auto-saved under PLECS_MCP_OUTPUT_DIR) and replaced
by saved metadata; image bytes are never returned inline.
Inputs: command (required), save_to, decimate, max_rows, +4 more. Returns: object
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 45 tools
Most tools target a distinct action (load, save, simulate, codegen, export_fmu, etc.), but several clusters overlap: plecs_simulate/plecs_plot/plecs_capture/plecs_check/plecs_submit all run or wrap simulations, plecs_overview/plecs_statistics/plecs_get_model_tree all summarize model state, and plecs_rpc/plecs_batch/plecs_webserver are three different escape hatches. The detailed descriptions do clarify boundaries in most cases, but an agent must read carefully to pick correctly.
All 45 tools share the plecs_ prefix and snake_case, which is highly predictable. However, the verb_noun convention is not uniform: many tools are noun-only (plecs_artifacts, plecs_instances, plecs_statistics, plecs_overview, plecs_scope, plecs_task, plecs_tasks, plecs_fmu_info), so the pattern is mostly but not entirely consistent.
45 tools is far above the 15-tool sweet spot and well past the 25-tool threshold for 'heavy'. While PLECS is a genuinely complex domain (schematic editing, simulation, codegen, FMU export, RPC introspection), the surface includes several near-duplicates (submit vs simulate, capture vs plot, task/tasks/task_result) that inflate the count.
The surface is unusually thorough: model lifecycle (load/save/close/clone/edit), simulation and analysis, plotting/capture, codegen, FMU export, validation, batch execution, background tasks, and raw RPC/webserver escape hatches. Minor gaps remain, such as no explicit 'create new model from scratch' operation and artifact listing without artifact cleanup, but agents have workarounds.
Maintenance
Related MCP Connectors
Protocol-native energy infrastructure orchestration for AI data centers. Provides 46 MCP tools across 8 grid protocols (IEC-61850, DNP3, Modbus, OCPP, OpenADR, IEEE 2030.5, IEC 60870-5-104, ICCP) with 5 core API primitives: connect, dispatch, settle, comply, and intel. Enables AI agents to programmatically interact with substations, grid interfaces, and energy assets for real-time workload-grid coordination.
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Email inboxes, webhook URLs, mock APIs and 170+ tools for coding agents over one MCP connection.
214 tools for AI agents over one MCP endpoint: image, video, audio, 3D, data, storage, mail, GPUs.
Related MCP Servers
- AlicenseAqualityDmaintenanceMCP server that connects any AI agent to MATLAB — execute code, async jobs, interactive Plotly plots, custom tools, and monitoring dashboard2021 PyPI4MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to control MATLAB Simulink models through natural language, providing tools for model creation, block management, wiring, simulation, and more via a local MCP backend.4MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to automate COMSOL Multiphysics simulations, including model management, geometry building, physics configuration, meshing, solving, and results visualization via the MCP protocol.MIT
- AlicenseBqualityBmaintenanceEnables controlling a local Scilab/Xcos installation to discover installed block libraries, create native block templates, read, write, and validate diagrams, and run simulations of arbitrary positive duration that return named numerical signal series. It exposes these capabilities as MCP tools over stdio or streamable HTTP, with model file access restricted to configured filesystem roots.112GPL 3.0