MCP + Simulink 自动建模完整搭建指南

利用 VS Code Copilot Chat 的 MCP (Model Context Protocol) 能力,通过自然语言对话驱动 MATLAB/Simulink 自动创建电力电子仿真模型。


目录

  1. 整体架构
  2. 环境准备
  3. Python 虚拟环境配置
  4. MATLAB Engine API 安装
  5. MCP Server 开发
  6. VS Code MCP 配置
  7. Simulink 建模脚本
  8. 在 Copilot Chat 中使用
  9. 常见问题与解决
  10. 完整项目文件清单

1. 整体架构

┌──────────────────────────────────────────────────────────────────┐
│                        VS Code                                    │
│  ┌─────────────┐     ┌──────────────────┐     ┌──────────────┐  │
│  │ Copilot Chat │ ──▶ │   MCP Client     │ ──▶ │  .mcp.json   │  │
│  │  (对话界面)   │     │ (内置,stdio协议)  │     │  (服务配置)   │  │
│  └─────────────┘     └──────────────────┘     └──────┬───────┘  │
│                                                      │          │
└──────────────────────────────────────────────────────┼──────────┘
                                                       │ stdio
┌──────────────────────────────────────────────────────┼──────────┐
│                    Python 进程                        ▼          │
│  ┌──────────────────────────────────────────────────────────┐   │
│  │             MCP Server (server.py)                        │   │
│  │  • simulink_create_model         • simulink_add_block     │   │
│  │  • simulink_connect_blocks       • simulink_set_params    │   │
│  │  • simulink_run_simulation       • simulink_get_info      │   │
│  │  • simulink_feedback_loop        • simulink_close_model   │   │
│  └──────────────────────────┬───────────────────────────────┘   │
│                              │ MATLAB Engine API                 │
│  ┌──────────────────────────▼───────────────────────────────┐   │
│  │              matlab_engine.py (封装层)                     │   │
│  │  new_system / open_system / add_block / add_line / ...   │   │
│  └──────────────────────────┬───────────────────────────────┘   │
└──────────────────────────────┼───────────────────────────────────┘
                               │
┌──────────────────────────────▼───────────────────────────────────┐
│                     MATLAB / Simulink                             │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │   Simscape Electrical (ee_lib) + Foundation Library       │    │
│  │   • Three-Phase Source   • N-Channel MOSFET              │    │
│  │   • Induction Machine    • Phase Splitter                │    │
│  │   • Gate Driver          • Solver Configuration          │    │
│  └─────────────────────────────────────────────────────────┘    │
└──────────────────────────────────────────────────────────────────┘

工作流程

Simulink MATLAB Engine server.py MCP Client Copilot Chat 用户 Simulink MATLAB Engine server.py MCP Client Copilot Chat 用户 "创建一个PID控制系统" 获取可用工具列表 list_tools() via stdio [simulink_create_model, simulink_add_block, ...] call_tool("simulink_create_feedback_loop") JSON-RPC 调用 eng.new_system() / add_block() 创建 .slx 文件 完成 结果 JSON 响应 "PID控制系统模型已创建 ✅"

2. 环境准备

必需软件

软件 版本要求 说明
MATLAB R2022b+ 需包含 Simulink、Simscape、Simscape Electrical
Python 3.10+ 用于运行 MCP Server
VS Code 最新版 内置 Copilot Chat 和 MCP 支持

检查 MATLAB 工具箱

在 MATLAB 命令窗口中运行:

% 检查必需工具箱
license('test', 'Simulink')              % 应返回 1
license('test', 'Simscape')              % 应返回 1
license('test', 'Power_System_Blocks')   % Simscape Electrical

3. Python 虚拟环境配置

3.1 创建虚拟环境

# 在项目根目录下
cd c:\jason\imcc_starter
python -m venv .venv

# 激活虚拟环境 (Windows PowerShell)
.venv\Scripts\Activate.ps1

3.2 安装 Python 依赖

创建 mcp-server/requirements.txt

mcp>=1.0.0
matlabengine>=9.14.0

安装:

pip install -r mcp-server/requirements.txt

3.3 验证安装

python -c "import mcp; print('MCP OK')"
python -c "import matlab.engine; print('MATLAB Engine OK')"

4. MATLAB Engine API 安装

方法一:在 MATLAB 中安装(推荐)

MATLAB 命令窗口中执行:

% 切换到 MATLAB Engine 安装目录
cd(fullfile(matlabroot, 'extern', 'engines', 'python'))

% 安装到当前 Python 环境
system('python -m pip install .')

方法二:手动指定 Python 路径

% 如果使用虚拟环境
cd(fullfile(matlabroot, 'extern', 'engines', 'python'))
system('c:\jason\imcc_starter\.venv\Scripts\python.exe -m pip install .')

验证

import matlab.engine
eng = matlab.engine.start_matlab()   # 启动需要 10-30 秒
print(eng.eval("version"))           # 显示 MATLAB 版本
eng.quit()

5. MCP Server 开发

5.1 项目目录结构

imcc_starter/
├── .mcp.json                          # VS Code MCP 服务配置
├── mcp-server/
│   ├── requirements.txt               # Python 依赖
│   ├── server.py                      # MCP 主服务入口
│   ├── matlab_engine.py               # MATLAB Engine 封装
│   └── tools/
│       └── simulink_tools.py          # Simulink 建模工具
├── matlab-scripts/
│   ├── init_simulink.m                # Simulink 环境初始化
│   ├── block_templates.m              # 模块模板库
│   ├── build_complete_model.m         # 完整建模脚本
│   ├── fix_solver.m                   # Solver 修复脚本
│   └── fix_neutral.m                  # 中性点修复脚本
└── 02_model/HW/                       # 模型输出目录

5.2 MCP Server 主入口 (server.py)

"""
MCP Simulink Server - 主入口
通过 MCP 协议暴露 Simulink 自动建模工具
"""
import asyncio
import json
import logging

from mcp.server import Server, NotificationOptions
from mcp.server.models import InitializationCapabilities
from mcp.server.stdio import stdio_server

from matlab_engine import MatlabEngine
from tools.simulink_tools import SimulinkTools

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("mcp-simulink")

# 初始化 MATLAB 引擎(延迟加载)
matlab = MatlabEngine()
simulink = SimulinkTools(matlab)

# 创建 MCP Server
server = Server("simulink-mcp")

# ============================================================
# 工具定义 - 注册 8 个 Simulink 建模工具
# ============================================================

@server.list_tools()
async def list_tools() -> list[dict]:
    """列出所有可用的 Simulink 建模工具"""
    return [
        {
            "name": "simulink_create_model",
            "description": "创建一个新的 Simulink 模型文件 (.slx)",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string", "description": "模型名称"},
                    "savePath": {"type": "string", "description": "保存路径"}
                },
                "required": ["modelName"]
            }
        },
        {
            "name": "simulink_add_block",
            "description": "向模型中添加一个 Simulink 模块",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"},
                    "blockType": {
                        "type": "string",
                        "description": "模块类型: Sum, Gain, Integrator, TransferFcn, Inport, Outport, Scope, Constant, Step 等"
                    },
                    "blockName": {"type": "string"},
                    "position": {"type": "array", "items": {"type": "number"}}
                },
                "required": ["modelName", "blockType"]
            }
        },
        {
            "name": "simulink_connect_blocks",
            "description": "连接两个 Simulink 模块",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"},
                    "srcBlock": {"type": "string"},
                    "srcPort": {"type": "number", "description": "源端口号,默认 1"},
                    "dstBlock": {"type": "string"},
                    "dstPort": {"type": "number", "description": "目标端口号,默认 1"}
                },
                "required": ["modelName", "srcBlock", "dstBlock"]
            }
        },
        {
            "name": "simulink_set_block_params",
            "description": "设置 Simulink 模块参数",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"},
                    "blockName": {"type": "string"},
                    "params": {"type": "object", "description": "参数字典"}
                },
                "required": ["modelName", "blockName", "params"]
            }
        },
        {
            "name": "simulink_run_simulation",
            "description": "运行 Simulink 仿真",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"},
                    "stopTime": {"type": "string", "description": "仿真停止时间,默认 10"}
                },
                "required": ["modelName"]
            }
        },
        {
            "name": "simulink_get_model_info",
            "description": "获取模型结构信息",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"}
                },
                "required": ["modelName"]
            }
        },
        {
            "name": "simulink_create_feedback_loop",
            "description": "快速创建 PID 反馈控制系统",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"},
                    "plantTF": {"type": "string", "description": "传递函数"},
                    "kp": {"type": "number"},
                    "ki": {"type": "number"},
                    "kd": {"type": "number"}
                },
                "required": ["modelName", "plantTF"]
            }
        },
        {
            "name": "simulink_close_model",
            "description": "关闭并保存模型",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "modelName": {"type": "string"},
                    "save": {"type": "boolean"}
                },
                "required": ["modelName"]
            }
        }
    ]


@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[dict]:
    """路由工具调用到对应的处理函数"""
    try:
        matlab.ensure_connected()

        if name == "simulink_create_model":
            result = simulink.create_model(
                arguments["modelName"],
                arguments.get("savePath")
            )
        elif name == "simulink_add_block":
            result = simulink.add_block(
                arguments["modelName"],
                arguments["blockType"],
                arguments.get("blockName"),
                arguments.get("position")
            )
        elif name == "simulink_connect_blocks":
            result = simulink.connect_blocks(
                arguments["modelName"],
                arguments["srcBlock"],
                arguments["dstBlock"],
                arguments.get("srcPort", 1),
                arguments.get("dstPort", 1)
            )
        elif name == "simulink_set_block_params":
            result = simulink.set_block_params(
                arguments["modelName"],
                arguments["blockName"],
                arguments["params"]
            )
        elif name == "simulink_run_simulation":
            result = simulink.run_simulation(
                arguments["modelName"],
                arguments.get("stopTime", "10")
            )
        elif name == "simulink_get_model_info":
            result = simulink.get_model_info(arguments["modelName"])
        elif name == "simulink_create_feedback_loop":
            result = simulink.create_feedback_loop(
                arguments["modelName"],
                arguments["plantTF"],
                arguments.get("kp", 1.0),
                arguments.get("ki", 0.1),
                arguments.get("kd", 0.01)
            )
        elif name == "simulink_close_model":
            result = simulink.close_model(
                arguments["modelName"],
                arguments.get("save", True)
            )
        else:
            raise ValueError(f"Unknown tool: {name}")

        return [{"type": "text", "text": json.dumps(result, ensure_ascii=False, indent=2)}]

    except Exception as e:
        logger.error(f"Tool {name} failed: {e}")
        return [{"type": "text", "text": json.dumps({"error": str(e)}, ensure_ascii=False)}]


# ============================================================
# 启动服务
# ============================================================

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            InitializationCapabilities(
                sampling=NotificationOptions(),
                roots=NotificationOptions(),
            ),
        )


if __name__ == "__main__":
    asyncio.run(main())

5.3 MATLAB Engine 封装 (matlab_engine.py)

关键要点:所有无返回值的 MATLAB 函数调用必须使用 nargout=0,否则会报 “Too many output arguments” 错误。

"""
MATLAB Engine 封装层
管理与 MATLAB 的连接,提供 MATLAB 函数调用的 Python 接口
"""
import logging
from typing import Any

logger = logging.getLogger("matlab-engine")


class MatlabEngine:
    """MATLAB Engine 封装,支持延迟连接和自动重连"""

    def __init__(self):
        self._eng = None
        self._connected = False

    def ensure_connected(self):
        """确保与 MATLAB 的连接处于活跃状态"""
        if not self._connected:
            self.connect()

    def connect(self):
        """建立与 MATLAB 的连接"""
        try:
            import matlab.engine
            logger.info("正在启动 MATLAB Engine...")
            self._eng = matlab.engine.start_matlab()
            # 添加当前项目路径
            self._eng.addpath(self._eng.genpath(
                r'c:\jason\imcc_starter\matlab-scripts'
            ))
            self._connected = True
            logger.info("MATLAB Engine 连接成功")
        except ImportError:
            raise RuntimeError(
                "未安装 MATLAB Engine API for Python。\n"
                "请运行: pip install matlabengine\n"
                "或参考: https://www.mathworks.com/help/matlab/matlab_external/"
                "install-the-matlab-engine-for-python.html"
            )
        except Exception as e:
            raise RuntimeError(f"无法连接到 MATLAB: {e}\n"
                             "请确保 MATLAB 已安装且 license 可用。")

    def disconnect(self):
        """断开 MATLAB 连接"""
        if self._eng:
            try:
                self._eng.quit()
            except Exception:
                pass
            self._eng = None
            self._connected = False

    # ---- 基础 MATLAB 操作 ----

    def eval(self, expr: str, nargout: int = 0) -> Any:
        """执行 MATLAB 表达式"""
        self.ensure_connected()
        return self._eng.eval(expr, nargout=nargout)

    def feval(self, func_name: str, *args, nargout: int = 0) -> Any:
        """调用 MATLAB 函数"""
        self.ensure_connected()
        func = getattr(self._eng, func_name)
        return func(*args, nargout=nargout)

    # ---- Simulink 专用操作 ----
    # 注意:以下所有操作都使用 nargout=0(无返回值)

    def new_system(self, model_name: str) -> str:
        """创建新 Simulink 模型"""
        return self.feval("new_system", model_name, nargout=0)

    def open_system(self, model_name: str):
        """打开已有模型"""
        return self.feval("open_system", model_name, nargout=0)

    def close_system(self, model_name: str, save: bool = True):
        """关闭模型"""
        if save:
            self.feval("close_system", model_name, 1, nargout=0)
        else:
            self.feval("close_system", model_name, 0, nargout=0)

    def add_block(self, source_type: str, dest: str):
        """添加 Simulink 模块"""
        return self.feval("add_block", source_type, dest, nargout=0)

    def add_line(self, model: str, src: str, dst: str):
        """添加连线"""
        return self.feval("add_line", model, src, dst, nargout=0)

    def set_param(self, obj: str, param: str, value: str):
        """设置对象参数"""
        return self.feval("set_param", obj, param, value, nargout=0)

    def get_param(self, obj: str, param: str) -> str:
        """获取对象参数 (需要 nargout=1 才能返回值)"""
        return self.feval("get_param", obj, param, nargout=1)

    def save_system(self, model_name: str, path: str = None):
        """保存模型"""
        if path:
            return self.feval("save_system", model_name, path, nargout=0)
        else:
            return self.feval("save_system", model_name, nargout=0)

    def sim(self, model_name: str) -> Any:
        """运行仿真"""
        return self.feval("sim", model_name, nargout=0)

    def find_system(self, model_name: str) -> list:
        """查找系统中的模块"""
        result = self.feval("find_system", model_name, nargout=1)
        if result:
            return list(result)
        return []

5.4 Simulink 工具集 (tools/simulink_tools.py)

"""
Simulink 建模工具集
封装所有 Simulink 自动建模操作
"""
import logging
from typing import Optional
from matlab_engine import MatlabEngine

logger = logging.getLogger("simulink-tools")

# 常用 Simulink 库模块映射
BUILTIN_BLOCKS = {
    "Inport": "simulink/Sources/In1",
    "Outport": "simulink/Sinks/Out1",
    "Constant": "simulink/Sources/Constant",
    "Step": "simulink/Sources/Step",
    "Sum": "simulink/Math Operations/Sum",
    "Gain": "simulink/Math Operations/Gain",
    "Integrator": "simulink/Continuous/Integrator",
    "TransferFcn": "simulink/Continuous/Transfer Fcn",
    "PID": "simulink/Continuous/PID Controller",
    "Scope": "simulink/Sinks/Scope",
    "Mux": "simulink/Signal Routing/Mux",
    "Demux": "simulink/Signal Routing/Demux",
}


class SimulinkTools:
    """Simulink 自动建模工具类"""

    def __init__(self, engine: MatlabEngine):
        self.eng = engine

    def create_model(self, model_name: str, save_path: Optional[str] = None) -> dict:
        """创建新的 Simulink 模型"""
        try:
            self.eng.eval(f"bdclose('{model_name}')")
        except Exception:
            pass

        self.eng.new_system(model_name)
        self.eng.open_system(model_name)

        if save_path:
            full_path = f"{save_path}/{model_name}.slx"
            self.eng.save_system(model_name, full_path)
        else:
            self.eng.save_system(model_name)

        return {
            "status": "success",
            "modelName": model_name,
            "message": f"Simulink 模型 '{model_name}' 已创建并打开"
        }

    def add_block(self, model_name: str, block_type: str,
                  block_name: Optional[str] = None,
                  position: Optional[list] = None) -> dict:
        """添加模块到模型"""
        source = BUILTIN_BLOCKS.get(block_type, block_type)
        if not block_name:
            block_name = block_type
        dest = f"{model_name}/{block_name}"

        try:
            self.eng.add_block(source, dest)
        except Exception as e:
            return {"status": "error", "message": str(e)}

        if position and len(position) == 4:
            pos_str = f"[{position[0]} {position[1]} {position[2]} {position[3]}]"
            self.eng.set_param(dest, "Position", pos_str)

        return {
            "status": "success",
            "blockName": block_name,
            "blockType": block_type,
            "fullPath": dest
        }

    def connect_blocks(self, model_name: str, src_block: str, dst_block: str,
                       src_port: int = 1, dst_port: int = 1) -> dict:
        """连接两个模块"""
        src = f"{model_name}/{src_block}/{src_port}"
        dst = f"{model_name}/{dst_block}/{dst_port}"
        try:
            self.eng.add_line(model_name, src, dst)
            return {"status": "success", "src": f"{src_block}:{src_port}", "dst": f"{dst_block}:{dst_port}"}
        except Exception as e:
            return {"status": "error", "message": str(e)}

    def set_block_params(self, model_name: str, block_name: str, params: dict) -> dict:
        """设置模块参数"""
        full_path = f"{model_name}/{block_name}"
        results = {}
        for param, value in params.items():
            try:
                self.eng.set_param(full_path, param, str(value))
                results[param] = "success"
            except Exception as e:
                results[param] = str(e)
        return {"status": "success", "blockPath": full_path, "params": results}

    def run_simulation(self, model_name: str, stop_time: str = "10") -> dict:
        """运行仿真"""
        try:
            self.eng.set_param(model_name, "StopTime", stop_time)
            self.eng.sim(model_name)
            return {"status": "success", "stopTime": stop_time}
        except Exception as e:
            return {"status": "error", "error": str(e)}

    def get_model_info(self, model_name: str) -> dict:
        """获取模型结构信息"""
        try:
            blocks = self.eng.find_system(model_name)
            return {
                "modelName": model_name,
                "blockCount": len(blocks) if blocks else 0,
                "blocks": [str(b) for b in blocks] if blocks else []
            }
        except Exception as e:
            return {"error": str(e)}

    def close_model(self, model_name: str, save: bool = True) -> dict:
        """关闭模型"""
        if save:
            self.eng.save_system(model_name)
        self.eng.close_system(model_name, save)
        return {"status": "success", "modelName": model_name, "saved": save}

    def create_feedback_loop(self, model_name: str, plant_tf: str,
                             kp: float = 1.0, ki: float = 0.1,
                             kd: float = 0.01) -> dict:
        """快速创建 PID 反馈控制系统"""
        steps = []
        self.create_model(model_name)
        steps.append("模型已创建")

        # 添加模块
        self.add_block(model_name, "Step", "Step Input", [50, 100, 90, 130])
        self.add_block(model_name, "Sum", "Sum", [200, 100, 230, 130])
        self.eng.set_param(f"{model_name}/Sum", "Inputs", "|+-")
        self.add_block(model_name, "PID", "PID Controller", [350, 90, 390, 140])
        self.add_block(model_name, "TransferFcn", "Plant", [500, 90, 550, 140])
        self.add_block(model_name, "Outport", "Output", [650, 100, 670, 130])
        self.add_block(model_name, "Scope", "Scope", [650, 180, 680, 210])

        # 设置参数
        self.set_block_params(model_name, "PID Controller", {"P": str(kp), "I": str(ki), "D": str(kd)})
        self.set_block_params(model_name, "Plant", {"Numerator": "[1]", "Denominator": "[1 2 1]"})

        # 连线
        self.connect_blocks(model_name, "Step Input", "Sum", 1, 1)
        self.connect_blocks(model_name, "Sum", "PID Controller", 1, 1)
        self.connect_blocks(model_name, "PID Controller", "Plant", 1, 1)
        self.connect_blocks(model_name, "Plant", "Output", 1, 1)
        self.connect_blocks(model_name, "Plant", "Scope", 1, 1)

        # 反馈
        self.eng.add_line(model_name, f"{model_name}/Plant/1", f"{model_name}/Sum/2")

        return {"status": "success", "modelName": model_name, "steps": steps}

6. VS Code MCP 配置

6.1 创建 .mcp.json

在项目根目录创建 .mcp.json

{
  "mcpServers": {
    "simulink": {
      "command": "c:/jason/imcc_starter/.venv/Scripts/python.exe",
      "args": [
        "c:/jason/imcc_starter/mcp-server/server.py"
      ],
      "env": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

6.2 配置说明

字段 说明
command Python 解释器路径(使用虚拟环境中的)
args MCP Server 脚本路径
env.PYTHONUNBUFFERED 设置为 1 确保实时输出

6.3 加载配置

  1. 保存 .mcp.json 后,按 Ctrl+Shift+P → 输入 Reload Window 重新加载窗口
  2. Copilot Chat 会自动检测 .mcp.json 并启动 MCP Server
  3. 首次启动时 MATLAB Engine 需要 10-30 秒初始化

7. Simulink 建模脚本

7.1 Simscape Electrical 库结构

R2026a 中 Simscape Electrical 的主要库路径:

路径 包含
Simscape Electrical ee_lib 电源、电机、半导体、开关
Foundation Library fl_lib 基础电气/机械/液压元件
Simscape Utilities nesl_utility Solver Configuration, PS-Simulink Converter
Simulink simulink Step, Scope, Mux, Demux 等

7.2 关键 Simscape 模块路径

% 电源
'ee_lib/Sources/Voltage Source (Three-Phase)'

% 电机
'ee_lib/Electromechanical/Asynchronous/Induction Machine Squirrel Cage'

% 半导体
'ee_lib/Semiconductors & Converters/N-Channel MOSFET'
'ee_lib/Semiconductors & Converters/Gate Driver'

% 连接器
'ee_lib/Connectors & References/Phase Splitter'
'ee_lib/Connectors & References/Floating Neutral (Three-Phase)'
'ee_lib/Connectors & References/Grounded Neutral (Three-Phase)'

% 基础元件
'fl_lib/Electrical/Electrical Elements/Electrical Reference'
'fl_lib/Mechanical/Rotational Elements/Inertia'
'fl_lib/Mechanical/Rotational Elements/Mechanical Rotational Reference'

% 工具
'nesl_utility/Solver Configuration'
'nesl_utility/PS-Simulink Converter'
'nesl_utility/Simulink-PS Converter'

7.3 Simscape 连接规则

规则 说明
物理连接 Simscape 模块间使用绿色物理连线(conserving ports)
信号连接 PS-Simulink Converter 将物理信号转为 Simulink 信号
Solver Configuration 每个物理网络必须连接恰好一个 Solver Configuration
Electrical Reference 电路中必须有接地点
nargout=0 通过 MATLAB Engine 调用无返回值函数时必须显式指定

8. 在 Copilot Chat 中使用

8.1 基础建模对话

启动 VS Code 并加载工作区后,在 Copilot Chat 中说:

你说 Copilot 做的
“创建一个名为 motor_test 的 Simulink 模型” 调用 simulink_create_model
“添加一个 Step 模块” 调用 simulink_add_block
“把 Step 连接到 Scope” 调用 simulink_connect_blocks
“设置 Gain 模块增益为 5.0” 调用 simulink_set_block_params
“运行 20 秒仿真” 调用 simulink_run_simulation
“查看模型结构” 调用 simulink_get_model_info
“创建一个 PID 控制系统” 调用 simulink_create_feedback_loop

8.2 电力电子建模对话

用户: 在HW文件夹中创建一个三相异步电机驱动模型
      包含三相电压源、背靠背MOSFET、鼠笼式异步电机

Copilot: [调用 MCP 工具逐步创建]
  1. simulink_create_model("three_phase_motor_drive", "02_model/HW")
  2. simulink_add_block(..., "Three-Phase Source")
  3. simulink_add_block(..., "N-Channel MOSFET") × 6
  4. simulink_add_block(..., "Induction Machine Squirrel Cage")
  5. simulink_connect_blocks(...) × N
  ...

9. 常见问题与解决

9.1 启动问题

问题 原因 解决
ModuleNotFoundError: mcp 未安装 mcp 包 pip install mcp
ModuleNotFoundError: matlab 未安装 MATLAB Engine API 按第4节步骤安装
.mcp.json 不生效 VS Code 未重载 Ctrl+Shift+PReload Window
MATLAB 连接超时 MATLAB 启动需要时间 首次等待 30 秒,后续复用会话

9.2 建模问题

问题 原因 解决
“Too many output arguments” 函数调用缺少 nargout=0 对所有 Simulink 操作函数添加 nargout=0
“每个物理网络必须连接 Solver Configuration” Solver Config 未连入电路 将 Solver Configuration 连到 Electrical Reference
“初始条件求解失败” 电机中性点悬空/机械端口未连接 添加 Floating Neutral + Inertia + Mechanical Reference
“只能从非连接端口向连接端口连线” 端口类型不匹配(信号 vs 物理) 确保 Simscape 模块间用物理端口连接

9.3 Simscape 电机建模注意事项

✅ 必须连接的端口:
   • 三相电源 → Phase Splitter → MOSFETs → Phase Combiner → 电机(复合端口)
   • 电机机械端口 → Inertia → Mechanical Reference
   • Solver Configuration → Electrical Reference
   • Electrical Reference 必须存在于电路中

⚠️ 常见陷阱:
   • 电机"扩展三相端口"模式可能导致中性点浮空
   • 推荐使用"复合三相端口" + Phase Splitter/Combiner
   • MOSFET 初始关断导致零电流,需加 snubber 电阻或设置初始条件

9.4 调试技巧

% 在 MATLAB 中诊断模型
open_system('three_phase_motor_drive');

% 更新图(检查连线错误)
set_param('three_phase_motor_drive', 'SimulationCommand', 'update');

% 查看所有模块
blocks = find_system('three_phase_motor_drive');
disp(blocks);

% 查看模块端口
ph = get_param('three_phase_motor_drive/Induction Motor', 'PortHandles');
fprintf('LConn=%d, RConn=%d\n', length(ph.LConn), length(ph.RConn));

10. 完整项目文件清单

imcc_starter/
│
├── .mcp.json                               # VS Code MCP 配置
├── imcc_starter.prj                        # MATLAB 项目文件
├── imcc_starter.code-workspace             # VS Code 工作区
│
├── mcp-server/                             # MCP Server (Python)
│   ├── requirements.txt                    #   Python 依赖
│   ├── server.py                           #   MCP 主入口 (8个工具)
│   ├── matlab_engine.py                    #   MATLAB Engine 封装
│   └── tools/
│       └── simulink_tools.py               #   Simulink 工具实现
│
├── matlab-scripts/                         # MATLAB 辅助脚本
│   ├── init_simulink.m                     #   环境初始化
│   ├── block_templates.m                   #   模块模板
│   ├── build_complete_model.m              #   完整三相电机建模
│   ├── fix_solver.m                        #   Solver 配置修复
│   ├── fix_neutral.m                       #   中性点修复
│   ├── fix_mech.m                          #   机械端口修复
│   ├── fix_motor_port.m                    #   电机端口模式切换
│   ├── fix_init.m                          #   初始条件修复
│   ├── wire_hw_model.m                     #   接线脚本
│   └── final_wiring.m                      #   最终接线
│
├── 02_model/HW/                            # 模型输出
│   └── three_phase_motor_drive.slx         #   三相电机驱动模型
│
└── resources/project/                      # 项目资源
    └── Project.xml

附录:快速启动检查清单

  • MATLAB 已安装且 Simscape Electrical 可用
  • Python 3.10+ 虚拟环境已创建
  • pip install mcp matlabengine 已完成
  • MATLAB 中已安装 Engine API for Python
  • .mcp.json 中 Python 路径指向 venv
  • VS Code 已 Reload Window
  • 在 Copilot Chat 中测试: “创建一个 Simulink 模型”

文档版本: v1.0
创建日期: 2026-06-22
适用 MATLAB: R2026a (Simscape Electrical)
适用 Python: 3.10+

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐