MATLAB MCP Server
Интеграция MATLAB MCP
Это реализация сервера Model Context Protocol (MCP) для MATLAB. Он позволяет клиентам MCP (таким как агенты LLM или Claude Desktop) взаимодействовать с общей сессией MATLAB с помощью API MATLAB Engine для Python.
Функции
Выполнение кода MATLAB: запуск произвольных фрагментов кода MATLAB с помощью инструмента
runMatlabCode.Извлечение переменных: получение значений переменных из рабочего пространства MATLAB с помощью инструмента
getVariable.Структурированная коммуникация: инструменты возвращают результаты и ошибки в виде структурированного JSON для более удобного программного использования клиентами.
Неблокируемое выполнение: вызовы движка MATLAB выполняются асинхронно с использованием
asyncio.to_threadдля предотвращения блокировки сервера.Стандартное ведение журнала: использует стандартный модуль
loggingPython, выводя данные вstderrдля видимости в клиентских журналах.Общий сеанс: подключается к существующему общему сеансу MATLAB.
ТО, ЧТО ДЕЛАТЬ:
Добавьте инструмент
setVariableдля записи данных в рабочее пространство MATLAB.Добавьте инструмент
runScriptдля непосредственного выполнения файлов.m.Добавьте инструменты для управления рабочим пространством (например,
clearWorkspace,getWorkspaceVariables).Расширьте вспомогательный модуль
matlab_to_pythonдля обработки более сложных типов данных (структуры, массивы ячеек, объекты).Добавить поддержку взаимодействия с моделями Simulink.
Related MCP server: MATLAB MCP Server
Требования
Python 3.12 или выше
MATLAB ( рекомендуется R2023a или выше — проверьте совместимость MATLAB Engine API с Python) с установленным MATLAB Engine API для Python.
Пакет
numpyPython.
Установка
Клонируйте этот репозиторий:
git clone https://github.com/jigarbhoye04/MatlabMCP.git cd MatlabMCPНастройте виртуальную среду Python (рекомендуется):
# Install uv if you haven't already: https://github.com/astral-sh/uv uv init uv venv source .venv/bin/activate # On Windows use: .venv\Scripts\activateУстановить зависимости:
uv pip syncУбедитесь, что MATLAB установлен и MATLAB Engine API для Python настроен для вашей среды Python. См. документацию MATLAB .
Запустите MATLAB и поделитесь его движком: выполните следующую команду в командном окне MATLAB:
matlab.engine.shareEngineВы можете проверить, что он общий, запустив
matlab.engine.isEngineSharedв MATLAB (он должен вернутьtrueили1). Серверу MCP нужен этот общий движок для подключения.
Конфигурация (для Claude Desktop)
Чтобы использовать этот сервер с Claude Desktop:
Перейдите в Claude Desktop -> Настройки -> Разработчик -> Изменить конфигурацию.
Это откроет
claude_desktop_config.json. Добавьте или измените разделmcpServers, чтобы включить конфигурациюMatlabMCP:{ "mcpServers": { "MatlabMCP": { "command": "C:\\Users\\username\\.local\\bin\\uv.exe", // Path to your uv executable "args": [ "--directory", "C:\\Users\\username\\Desktop\\MatlabMCP\\", // ABSOLUTE path to the cloned repository directory "run", "main.py" ] // Optional: Add environment variables if needed // "env": { // "MY_VAR": "value" // } } // Add other MCP servers here if you have them } }ВАЖНО: Замените пути
C:\\Users\\username\\...на правильные абсолютные пути для вашей системы.Сохраните файл и перезапустите Claude Desktop .
Ведение журнала: журналы сервера (из модуля
loggingPython) будут отображаться в файлах журнала MCP Claude Desktop (доступных черезtail -f ~/Library/Logs/Claude/mcp-server-MatlabMCP.logна macOS или проверку%APPDATA%\Claude\logs\на Windows).
Разработка
Структура проекта:
MatlabMCP/
├── .venv/ # Virtual environment created by uv
├── Docs/
│ └── Images/
│ └── Updates.md # Documentation for updates and changes
├── main.py # The MCP server script
├── pyproject.toml # Project metadata and dependencies
├── README.md # This file
└── uv.lock # Lock file for dependenciesДокументация
Подробную документацию по функциям сервера, его использованию и заметкам по разработке см. в разделе « Обновления ».
Внося вклад
Вклады приветствуются! Если у вас есть предложения или улучшения, смело открывайте issue или отправляйте pull request.
Давайте сделаем это еще лучше вместе!
This server cannot be deployed
Maintenance
Related MCP Connectors
Use your Mac, Windows or Linux computer from ChatGPT, Claude or Codex: files, commands, documents.
Build Apps and run code in 30 languages — sandboxed, with persistent sessions for agent loops.
Work on your own computers from Claude or ChatGPT: run commands, edit and search files.
Hosted Slack MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceAllows interaction with MATLAB by creating and executing scripts and functions through Claude or other MCP clients, supporting script management and execution result retrieval with environment configuration capabilities.40-
- AlicenseBqualityFmaintenanceIntegrates MATLAB with AI to execute code, generate scripts from natural language, and access MATLAB documentation seamlessly.254Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables interactive MATLAB development by allowing users to execute scripts and specific code sections, manage workspace variables, and capture generated plots. It integrates with the MATLAB Python Engine to provide persistent execution context for MCP-compatible clients.19BSD 3-Clause
- AlicenseAqualityDmaintenanceMCP server that connects any AI agent to MATLAB — execute code, async jobs, interactive Plotly plots, custom tools, and monitoring dashboard2034 PyPI4MIT