Skip to content

Configuration

github-actions[bot] edited this page Apr 3, 2026 · 20 revisions

Configuration

This page documents all configuration options for the MATLAB MCP Server, organized by category. Every option is explained with its key name, expected type, default value, and description.


Overview

The server loads configuration from config.yaml in the current working directory by default. All settings can be overridden via environment variables using the MATLAB_MCP_ prefix.

Configuration Priority (highest to lowest):

  1. Command-line flags (--transport, --port, etc.)
  2. Environment variables (MATLAB_MCP_*)
  3. Values in config.yaml
  4. Built-in defaults

Environment Variable Naming Convention

Environment variables follow the pattern MATLAB_MCP_<SECTION>_<KEY>, where:

  • <SECTION> is the top-level YAML key (lowercase)
  • <KEY> is the nested key (lowercase, with underscores for nesting depth)

Examples:

# Server section
export MATLAB_MCP_SERVER_TRANSPORT=streamablehttp
export MATLAB_MCP_SERVER_HOST=127.0.0.1
export MATLAB_MCP_SERVER_PORT=8765

# Pool section
export MATLAB_MCP_POOL_MIN_ENGINES=2
export MATLAB_MCP_POOL_MAX_ENGINES=10

# Execution section
export MATLAB_MCP_EXECUTION_SYNC_TIMEOUT=60

# Security section (bearer token auth)
export MATLAB_MCP_AUTH_TOKEN=abc123def456...

# Sessions section
export MATLAB_MCP_SESSIONS_MAX_SESSIONS=50
export MATLAB_MCP_SESSIONS_SESSION_TIMEOUT=3600

Type Coercion:

  • Boolean values: "true", "True", "1"True; "false", "False", "0"False
  • Integer values: "123"123
  • Lists (YAML): Use semicolon-separated strings: export MATLAB_MCP_WORKSPACE_DEFAULT_PATHS="/path1;/path2;/path3"

Configuration Sections

Server Settings

Controls transport, binding, logging, and basic server behavior.

Key Type Default Description
server.name string "matlab-mcp-server" Server identifier reported to MCP clients in the ServerInfo field
server.transport enum "stdio" Transport protocol: "stdio" (single-user), "sse" (deprecated), "streamablehttp" (primary remote transport)
server.host string "127.0.0.1" Bind address for HTTP/SSE transports (e.g., "0.0.0.0" for remote access; note: requires firewall rule on Windows)
server.port integer 8765 TCP port for HTTP/SSE transports
server.log_level enum "info" Logging verbosity: "debug", "info", "warning", "error"
server.log_file string null Log file path (if null, logs to stderr only; use "./logs/server.log" to also write files)
server.result_dir string "./results" Directory where large result files are saved when inline output exceeds thresholds
server.drain_timeout_seconds integer 300 Maximum seconds to wait for in-flight jobs during shutdown before forcing termination
server.stateless_http boolean false Stateless HTTP mode — each request gets its own ephemeral workspace, no session persistence (streamablehttp only)

Transport Notes:

  • "stdio": Single-user, local only, no auth needed. Ideal for local development and single-machine deployments.
  • "sse": Multi-user via Server-Sent Events. Deprecated as of v2.0; kept for backward compatibility. Requires bearer token auth middleware.
  • "streamablehttp": Multi-user via HTTP. Recommended for remote access and CI/CD agents. Requires bearer token auth.

Host Binding Notes:

  • "127.0.0.1" (default): Only local connections; no firewall prompts on Windows 10.
  • "0.0.0.0": Accepts remote connections; triggers Windows Firewall UAC on first run without admin rights. Corporate firewalls may block inbound traffic.

Engine Pool Settings

Manages MATLAB engine lifecycle, scaling, and health.

Key Type Default Description
pool.min_engines integer 2 Minimum warm engines kept ready at all times
pool.max_engines integer 10 Hard ceiling on engines (macOS limited to 4; server logs a warning if you request more)
pool.scale_down_idle_timeout integer 900 Seconds an engine can sit idle before being shut down to reclaim resources (15 min)
pool.engine_start_timeout integer 120 Seconds to wait for MATLAB startup before giving up with an error
pool.health_check_interval integer 60 Seconds between engine health pings (trivial MATLAB evaluations to detect stuck processes)
pool.proactive_warmup_threshold float 0.8 Engine utilization ratio (0.0–1.0) — when crossed, proactively start new engines before queue builds up
pool.queue_max_size integer 50 Maximum pending jobs in the execution queue before rejecting new submissions
pool.matlab_root string null Explicit MATLAB installation path (e.g., /Applications/MATLAB_R2024a.app); null = auto-detect

macOS Limitation: MATLAB on macOS has a hard limit of 4 concurrent engine instances due to OS licensing. The server respects this internally but will not error if max_engines is higher; operations may degrade or hang if the limit is exceeded.


Execution Settings

Controls code execution timeouts, workspace isolation, and job behavior.

Key Type Default Description
execution.sync_timeout integer 30 Seconds before auto-promoting synchronous code execution to async (background job). Useful for long-running code that should not block the agent.
execution.max_execution_time integer 86400 Hard time limit per job in seconds (24 hours = 86400); jobs exceeding this are forcibly terminated
execution.workspace_isolation boolean true Clear all variables between sessions to prevent state leakage
execution.engine_affinity boolean false Pin a session to the same engine across requests (slightly faster warm start but reduces engine utilization flexibility)
execution.temp_dir string "./temp" Base directory for per-session temporary files
execution.temp_cleanup_on_disconnect boolean true Delete session temp files when the client disconnects

sync_timeout Guidance:

  • 30 (default): Good for most code. Inline results for quick operations (matrix math, plotting); async jobs for heavy computation.
  • 60: If most agent code runs 30–60 seconds, increase this to avoid unnecessary async overhead.
  • 5: If you want all non-trivial code auto-promoted to async immediately.

Workspace Configuration

Paths added to MATLAB's search path and startup commands.

Key Type Default Description
workspace.default_paths list[string] [] Directories added to MATLAB's path on each engine startup (e.g., shared libraries, custom toolboxes)
workspace.startup_commands list[string] [] MATLAB commands executed on each engine startup (e.g., "format long", "set(0,'DefaultFigureVisible','off')")

Example:

workspace:
  default_paths:
    - "/shared/custom_libs"
    - "/shared/data"
  startup_commands:
    - "format long"
    - "set(groot, 'DefaultFigureVisible', 'off')"

Toolbox Filtering

Controls which MATLAB toolboxes are reported to agents.

Key Type Default Description
toolboxes.mode enum "all" Filter mode: "all" (report all installed), "whitelist" (only listed), "blacklist" (exclude listed)
toolboxes.list list[string] [] Toolbox names to include (whitelist mode) or exclude (blacklist mode)

Modes:

Mode Use Case
"all" Default; report all available toolboxes. Useful for exploratory agents.
"whitelist" Production; report only approved toolboxes. Prevents agents from using unlicensed or unsafe tools.
"blacklist" Exclude specific toolboxes (e.g., symbolic computation on shared servers).

Example (Whitelist):

toolboxes:
  mode: "whitelist"
  list:
    - "Signal Processing Toolbox"
    - "Image Processing Toolbox"
    - "Optimization Toolbox"

Custom Tools Configuration

Exposes user-written MATLAB functions as MCP tools.

Key Type Default Description
custom_tools.config_file string null Path to custom_tools.yaml that defines custom function bindings (see Custom-Tools)

Example:

custom_tools:
  config_file: "./custom_tools.yaml"

See Custom-Tools for the full schema and examples.


Security Settings

Code validation, upload limits, and authentication.

Key Type Default Description
security.blocked_functions_enabled boolean true Enable the function blocklist (prevents dangerous operations like system(), eval())
security.blocked_functions list[string] See below MATLAB functions that raise a BlockedFunctionError if executed
security.max_upload_size_mb integer 100 Maximum file upload size in megabytes

Default Blocked Functions:

system, unix, dos, !, eval, feval, evalc, evalin, assignin, perl, python

These functions are blocked because they can:

  • Execute shell commands (system, unix, dos, !, perl, python)
  • Execute arbitrary code (eval, feval, evalc, evalin, assignin)

The validator strips string literals and comments before scanning code, so disp('system') will NOT trigger a false positive.

Custom Blocklist Example:

security:
  blocked_functions_enabled: true
  blocked_functions:
    - "system"
    - "eval"
    - "my_dangerous_function"

To disable blocking entirely (not recommended for production):

security:
  blocked_functions_enabled: false

Bearer Token Authentication

Protects HTTP/SSE transports with bearer token authentication.

Key Type Default Description
auth.enabled boolean false Enable bearer token authentication on HTTP/SSE transports
auth.token_env_var string "MATLAB_MCP_AUTH_TOKEN" Environment variable name where the server reads the bearer token

Authentication Flow:

  1. Server reads token from env: On startup, the server reads $MATLAB_MCP_AUTH_TOKEN (or the value of auth.token_env_var).
  2. Clients send token in header: HTTP/SSE clients include Authorization: Bearer <token> in every request.
  3. Invalid/missing token returns 401: Server responds with HTTP 401 and WWW-Authenticate: Bearer header per RFC 6750.
  4. stdio transport bypasses auth: Single-user stdio deployments ignore this setting (no HTTP layer).

Generating a Token:

Use the CLI helper to generate a random 64-character hex token:

matlab-mcp --generate-token

This prints:

Generated bearer token: abc123def456...xyz789

# On POSIX (Linux/macOS):
export MATLAB_MCP_AUTH_TOKEN='abc123def456...xyz789'

# On Windows (PowerShell):
$env:MATLAB_MCP_AUTH_TOKEN='abc123def456...xyz789'

# On Windows (Command Prompt):
set MATLAB_MCP_AUTH_TOKEN=abc123def456...xyz789

Then start the server:

export MATLAB_MCP_AUTH_TOKEN='abc123def456...xyz789'
matlab-mcp --transport streamablehttp

Security Warning: Do not commit tokens to version control. Always use environment variables or secrets management systems.


Code Quality Checking

Static analysis of MATLAB code before execution.

Key Type Default Description
code_checker.enabled boolean true Enable the MATLAB code linter (checkcode)
code_checker.auto_check_before_execute boolean false Automatically lint code before every execute_code call (may slow execution)
code_checker.severity_levels list[string] ["error", "warning"] Report only issues at these severity levels: "error", "warning", "info"

Example:

code_checker:
  enabled: true
  auto_check_before_execute: false
  severity_levels: ["error", "warning"]

Agents can also call the check_code tool directly to lint code without executing it.


Output Formatting

Controls how results are formatted and saved (text truncation, figure conversion, thumbnails).

Key Type Default Description
output.plotly_conversion boolean true Convert MATLAB figures to interactive Plotly JSON for agent UIs
output.static_image_format enum "png" Static image format when figures are not converted: "png", "jpg", "svg"
output.static_image_dpi integer 150 DPI for static image rendering
output.thumbnail_enabled boolean true Generate base64-encoded PNG thumbnails for inline display
output.thumbnail_max_width integer 400 Maximum width of thumbnails in pixels
output.large_result_threshold integer 10000 Result size (elements) above which data is saved to a .mat file instead of inlined
output.max_inline_text_length integer 50000 Text length (characters) above which output is saved to a .txt file instead of inlined

Output Thresholds:

  • Results with >10,000 elements (matrices, arrays) are automatically saved to a file.
  • Text output >50,000 characters is saved to a .txt file.
  • Files are saved to result_dir and referenced in the response.

Example:

output:
  plotly_conversion: true
  static_image_dpi: 200
  thumbnail_enabled: true
  thumbnail_max_width: 600
  large_result_threshold: 50000
  max_inline_text_length: 100000

Session Management

Controls session lifecycle, cleanup, and job retention.

Key Type Default Description
sessions.max_sessions integer 10 Maximum concurrent user sessions (limits workspace isolation overhead)
sessions.session_timeout integer 3600 Idle timeout in seconds (1 hour = 3600); inactive sessions are cleaned up
sessions.job_retention_seconds integer 86400 How long to retain completed job metadata (1 day = 86400 seconds) for history queries

Session Cleanup: Sessions are considered idle if no requests arrive within session_timeout seconds. Cleanup happens periodically (roughly every pool.health_check_interval seconds). Sessions with active/pending jobs are NOT cleaned up even if idle.

Example:

sessions:
  max_sessions: 50
  session_timeout: 7200  # 2 hours
  job_retention_seconds: 604800  # 7 days

Monitoring & Metrics

Collects server metrics and provides a web dashboard.

Key Type Default Description
monitoring.enabled boolean true Enable metrics collection (zero overhead when disabled)
monitoring.sample_interval integer 10 Seconds between metric samples (pool utilization, error rate, etc.)
monitoring.retention_days integer 7 Days of historical metrics to retain in the database
monitoring.db_path string "./monitoring/metrics.db" SQLite database file path for persisting metrics
monitoring.dashboard_enabled boolean true Enable the web dashboard at http://localhost:8766 (stdio) or /dashboard (HTTP)

Dashboard Features:

  • Real-time engine pool utilization, job counts, error rates
  • Time-series charts of execution times and error trends
  • Event log of recent MATLAB execution and warnings
  • Health status indicator (green/orange/red for healthy/degraded/unhealthy)

Optional Dependency: The monitoring dashboard requires psutil for system metrics. Install with:

pip install -e ".[monitoring]"

Example:

monitoring:
  enabled: true
  sample_interval: 5
  retention_days: 30
  db_path: "./metrics.db"
  dashboard_enabled: true

Human-in-the-Loop (HITL) Approval Gates

Pauses execution and requests human approval for sensitive operations.

Key Type Default Description
hitl.enabled boolean false Enable approval gates (off by default, zero cost when disabled)
hitl.approve_all_execute boolean false Require approval before every execute_code call
hitl.approve_all_file_operations boolean false Require approval before file uploads/deletes
hitl.approve_protected_functions boolean true Require approval only for code calling protected MATLAB functions (e.g., system, eval)

Protected Functions: By default, code that calls potentially dangerous MATLAB functions (even those not in the blocklist) triggers an approval request. The blocklist (security.blocked_functions) prevents execution entirely; HITL gates request approval for sensitive operations.

Approval Workflow:

  1. Agent calls execute_code with code that triggers a gate
  2. Server calls ctx.elicit(HumanApproval) via the MCP elicitation API
  3. Human reviews and approves/denies via their MCP client
  4. If approved: code executes; if denied: returns an error to the agent

Example (Require approval for file operations):

hitl:
  enabled: true
  approve_all_execute: false
  approve_all_file_operations: true
  approve_protected_functions: true

Note: Elicitation requires client support. Claude Code, Cursor, and Codex CLI support elicitation; verify your agent before enabling HITL in production.


Complete Example Configuration

server:
  name: "matlab-mcp-server"
  transport: "streamablehttp"
  host: "127.0.0.1"
  port: 8765
  log_level: "info"
  log_file: "./logs/server.log"
  result_dir: "./results"
  stateless_http: false

pool:
  min_engines: 2
  max_engines: 8
  scale_down_idle_timeout: 900
  engine_start_timeout: 120
  health_check_interval: 60
  proactive_warmup_threshold: 0.8
  queue_max_size: 50
  matlab_root: null

execution:
  sync_timeout: 30
  max_execution_time: 86400
  workspace_isolation: true
  engine_affinity: false
  temp_dir: "./temp"
  temp_cleanup_on_disconnect: true

workspace:
  default_paths:
    - "/shared/libs"
  startup_commands:
    - "format long"

toolboxes:
  mode: "whitelist"
  list:
    - "Signal Processing Toolbox"
    - "Image Processing Toolbox"

custom_tools:
  config_file: "./custom_tools.yaml"

security:
  blocked_functions_enabled: true
  blocked_functions:
    - "system"
    - "eval"
    - "!"
  max_upload_size_mb: 100

code_checker:
  enabled: true
  auto_check_before_execute: false
  severity_levels: ["error", "warning"]

output:
  plotly_conversion: true
  static_image_dpi: 150
  thumbnail_enabled: true
  thumbnail_max_width: 400
  large_result_threshold: 10000
  max_inline_text_length: 50000

sessions:
  max_sessions: 10
  session_timeout: 3600
  job_retention_seconds: 86400

monitoring:
  enabled: true
  sample_interval: 10
  retention_days: 7
  db_path: "./monitoring/metrics.db"
  dashboard_enabled: true

hitl:
  enabled: false
  approve_all_execute: false
  approve_all_file_operations: false
  approve_protected_functions: true

Architecture Diagram

graph TB
    A["config.yaml"] -->|parsed by| B["AppConfig<br/>Pydantic model"]
    C["MATLAB_MCP_*<br/>Environment variables"] -->|overrides| B
    D["CLI flags<br/>--port, --transport, etc"] -->|overrides| C
    B -->|provides| E["ServerConfig"]
    B -->|provides| F["PoolConfig"]
    B -->|provides| G["ExecutionConfig"]
    B -->|provides| H["SecurityConfig"]
    B -->|provides| I["OutputConfig"]
    B -->|provides| J["SessionConfig"]
    B -->|provides| K["MonitoringConfig"]
    B -->|provides| L["HITLConfig"]
    E -->|controls| M["server.py<br/>Transport & binding"]
    F -->|controls| N["EnginePoolManager"]
    G -->|controls| O["JobExecutor"]
    H -->|controls| P["SecurityValidator<br/>BearerAuthMiddleware"]
    I -->|controls| Q["ResultFormatter"]
    J -->|controls| R["SessionManager"]
    K -->|controls| S["MetricsCollector"]
    L -->|controls| T["HITL Gates"]
Loading

CLI Flags

Command-line flags override config file and environment variables:

matlab-mcp --help
Flag Type Description
--config PATH string Path to config.yaml (default: ./config.yaml)
--transport {stdio,sse,streamablehttp} enum Override server transport
--host HOST string Override bind host
--port PORT integer Override bind port
--log-level {debug,info,warning,error} enum Override log level
--inspect flag Start in inspect mode (no MATLAB engine pool, 0 engines) — useful for testing transport and auth without MATLAB
--generate-token flag Generate a random 64-character bearer token and print env var setup snippets, then exit
--pool-min-engines N integer Override minimum pool size
--pool-max-engines N integer Override maximum pool size

Example:

# Start with custom config and override port
matlab-mcp --config /etc/matlab-mcp/production.yaml --port 9000

# Generate a new token
matlab-mcp --generate-token

# Start in inspect mode for testing (no MATLAB)
matlab-mcp --inspect --transport streamablehttp

Clone this wiki locally