Skip to content

semanticarchitectures/mcp-matlab-wrapper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MCP MATLAB Wrapper

A secure Model Context Protocol (MCP) server that enables AI agents to run MATLAB simulations and retrieve results.

Overview

This project implements a robust MCP server that provides AI agents with secure access to MATLAB functionality. It includes session management, security controls, file operations, and comprehensive data conversion between Python and MATLAB formats.

Features

🔒 Security First

  • Script validation to block dangerous operations
  • File access control with path restrictions
  • Rate limiting and authentication
  • Session isolation and timeout management

🚀 High Performance

  • Concurrent MATLAB session support
  • Efficient data conversion
  • Resource pooling and management
  • Automatic cleanup and optimization

🛠 Rich Functionality

  • Execute MATLAB scripts with variable passing
  • File upload/download operations
  • Workspace variable management
  • Real-time session monitoring

📊 Data Integration

  • Seamless Python ↔ MATLAB data conversion
  • Support for complex nested structures
  • NumPy array compatibility
  • Comprehensive type mapping

Quick Start

Prerequisites

  • Python 3.8+
  • MATLAB R2019b+ with Engine API
  • Required Python packages (see requirements.txt)

Installation

# Clone the repository
git clone <repository-url>
cd mcp-matlab-wrapper

# Install dependencies
pip install -r requirements.txt

# Install the package
pip install -e .

Basic Usage

import asyncio
from mcp_matlab_wrapper import MCPMatlabServer

async def main():
    server = MCPMatlabServer()
    
    async with server.lifespan():
        # Server is running and ready to handle requests
        print("MCP MATLAB Server is running!")
        
        # Handle MCP requests here
        request = {
            "method": "create_session",
            "params": {"user_id": "demo_user"}
        }
        
        response = await server.handle_request(request)
        print(f"Session created: {response}")

asyncio.run(main())

Configuration

Create a config.json file:

{
  "server": {
    "host": "localhost",
    "port": 8000,
    "max_sessions": 10
  },
  "matlab": {
    "engine_path": "matlab",
    "startup_timeout": 60,
    "workspace_dir": "./workspace"
  },
  "security": {
    "require_auth": true,
    "rate_limit_requests": 100,
    "session_timeout": 3600
  }
}

Run the Server

# Using the configuration file
python -m mcp_matlab_wrapper.server --config config.json

# Or with command line options
python -m mcp_matlab_wrapper.server --host 0.0.0.0 --port 8080

API Reference

Session Operations

Create Session

{
  "method": "create_session",
  "params": {
    "user_id": "user123",
    "session_name": "simulation_1"
  }
}

Execute Script

{
  "method": "execute_script",
  "params": {
    "session_id": "session-uuid",
    "script": "x = 1:10; y = x.^2; result = sum(y);",
    "variables": {"input": [1,2,3,4,5]}
  }
}

Get Variable

{
  "method": "get_variable",
  "params": {
    "session_id": "session-uuid",
    "variable_name": "result"
  }
}

File Operations

Load File

{
  "method": "load_file",
  "params": {
    "file_path": "/workspace/data.mat"
  }
}

Save File

{
  "method": "save_file", 
  "params": {
    "file_path": "/workspace/output.txt",
    "content": "Results: 42"
  }
}

Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   MCP Client    │────│   MCP Server     │────│ Session Manager │
│   (AI Agent)    │    │                  │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                              │                          │
                              │                          │
                       ┌──────────────┐         ┌──────────────────┐
                       │   Security   │         │ MATLAB Engine    │
                       │   Manager    │         │    Manager       │
                       └──────────────┘         └──────────────────┘
                              │                          │
                       ┌──────────────┐         ┌──────────────────┐
                       │     File     │         │  Data Converter  │
                       │   Manager    │         │                  │
                       └──────────────┘         └──────────────────┘

Core Components

  • MCP Server: Main request handler and coordinator
  • Session Manager: Manages concurrent MATLAB sessions
  • Security Manager: Authentication, authorization, and validation
  • MATLAB Engine Manager: Controls MATLAB engine instances
  • File Manager: Secure file operations
  • Data Converter: Python ↔ MATLAB data conversion
  • Configuration: Centralized configuration management

Security Features

Script Validation

Blocks dangerous MATLAB functions:

  • System commands (system, dos, unix)
  • Dynamic evaluation (eval, evalin)
  • File operations (delete, rmdir)
  • Path manipulation (addpath, rmpath)

Access Control

  • Restricts file access to safe directories
  • Blocks system and sensitive paths
  • Validates file types and operations

Authentication

  • API key validation
  • Session token management
  • Rate limiting per client

Testing

# Run all tests
pytest tests/ -v

# Run with MATLAB integration tests (requires MATLAB)
pytest tests/ -v --run-matlab

# Run specific test modules
pytest tests/test_security.py -v
pytest tests/test_data_converter.py -v

Examples

See the examples/ directory for comprehensive usage examples:

  • basic_usage.py - Basic MATLAB operations
  • data_analysis.py - Data analysis workflow
  • file_operations.py - File handling examples

Development

Setup Development Environment

# Install development dependencies
pip install -r requirements-dev.txt

# Install pre-commit hooks
pre-commit install

# Run code formatting
black src/ tests/
isort src/ tests/

# Type checking
mypy src/

Project Structure

mcp-matlab-wrapper/
├── src/mcp_matlab_wrapper/     # Main package
│   ├── __init__.py
│   ├── server.py               # MCP server
│   ├── session_manager.py      # Session management
│   ├── security.py             # Security controls
│   ├── file_manager.py         # File operations
│   ├── matlab_engine.py        # MATLAB engine management
│   ├── data_converter.py       # Data conversion
│   └── config.py               # Configuration
├── tests/                      # Test suite
├── examples/                   # Usage examples  
├── docs/                       # Documentation
├── config/                     # Configuration files
└── requirements.txt            # Dependencies

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Submit a pull request

Code Standards

  • Follow PEP 8 style guidelines
  • Use type hints for all functions
  • Add comprehensive docstrings
  • Include error handling
  • Write tests for new features

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

  • Documentation: See the docs/ directory
  • Issues: GitHub Issues
  • Examples: Check the examples/ directory
  • Tests: Run the test suite for validation

Changelog

Version 1.0.0

  • Initial release
  • Core MCP server functionality
  • Session management
  • Security controls
  • File operations
  • Data conversion
  • Comprehensive test suite
  • Documentation and examples

Built with ❤️ for the AI community

About

An MCP wrapper for a MATLAB server

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages