# Examples
This page contains practical, real-world usage examples for the MATLAB MCP Server across JavaScript, MATLAB, and Python, progressing from simple to advanced scenarios.
---
## Basic MATLAB Execution
### Example 1: Simple Calculation
**What it demonstrates:** Basic code execution and output capture.
**Prerequisites:**
- MATLAB R2022b+ installed
- Server running: `matlab-mcp --inspect` (inspect mode skips pool startup)
```matlab
% Calculate eigenvalues of a 3×3 magic square
A = magic(3);
eigenvalues = eig(A);
disp(eigenvalues)
```
**Expected output:**
```
15.0000
4.1231
-4.1231
```
---
### Example 2: Matrix Operations
**What it demonstrates:** Larger computations and result formatting.
```matlab
% Create two 100×100 random matrices, multiply, show trace
A = rand(100);
B = rand(100);
C = A * B;
fprintf('Trace of A*B: %.6f\n', trace(C));
fprintf('Matrix dimensions: %d×%d\n', size(C, 1), size(C, 2));
```
**Expected output:**
```
Trace of A*B: 4982.731405
Matrix dimensions: 100×100
```
---
### Example 3: Solve Linear System
**What it demonstrates:** Structured computation and array output.
```matlab
% Solve: 3x + 2y - z = 1
% 2x - 2y + 4z = -2
% -x + 0.5y - z = 0
A = [3 2 -1; 2 -2 4; -1 0.5 -1];
b = [1; -2; 0];
x = A \ b;
fprintf('Solution: x=%.4f, y=%.4f, z=%.4f\n', x(1), x(2), x(3));
```
---
## Plotting and Visualization
All figures are automatically converted to interactive Plotly JSON and static PNG thumbnails.
### Example 4: Simple Line Plot
**What it demonstrates:** Figure creation and automatic Plotly conversion.
```matlab
% Plot sin(x) from 0 to 2π
x = linspace(0, 2*pi, 200);
y = sin(x);
plot(x, y, 'LineWidth', 2, 'DisplayName', 'sin(x)');
xlabel('x');
ylabel('y');
title('Sine Wave');
grid on;
legend;
```
**Agent sees:**
- Interactive Plotly chart (zoom, pan, hover)
- Static PNG thumbnail
- Axis labels and title preserved
```mermaid
graph LR
A["MATLAB figure
plot(x,y)"] -->|mcp_extract_props.m| B["Figure JSON
properties"]
B -->|Plotly mapper| C["Interactive
Plotly JSON"]
C -->|Browser| D["Agent sees
interactive chart"]
```
---
### Example 5: 3D Surface Plot
**What it demonstrates:** Complex 3D visualization.
```matlab
% Peaks function as 3D surface
[X, Y] = meshgrid(-3:0.1:3);
Z = peaks(X, Y);
surf(X, Y, Z);
colorbar;
shading interp;
title('Peaks Function');
xlabel('X');
ylabel('Y');
zlabel('Z');
```
---
### Example 6: Subplot Layout
**What it demonstrates:** Multi-panel figures with subplot domain computation.
```matlab
% Four frequency sine waves in 2×2 grid
t = linspace(0, 1, 1000);
freqs = [5 10 20 50];
for i = 1:4
subplot(2, 2, i);
plot(t, sin(2*pi*freqs(i)*t), 'LineWidth', 1.5);
title(sprintf('%d Hz', freqs(i)));
xlabel('Time (s)');
ylabel('Amplitude');
grid on;
end
```
**Agent receives:**
- Four traces in proper subplot domains
- Each subplot as a separate Plotly subplot with correct axis positioning
---
## Signal Processing
### Example 7: FFT Analysis
**What it demonstrates:** Signal processing with Plotly dual-subplot visualization.
```matlab
% Generate 440 Hz signal with noise, compute FFT
fs = 8000; % Sample rate
t = 0:1/fs:0.5; % 0.5 second duration
signal = sin(2*pi*440*t) + 0.3*randn(size(t));
% FFT analysis
N = length(signal);
Y = fft(signal);
f = (0:N-1) * fs / N;
% Plot results
figure;
subplot(2, 1, 1);
plot(t*1000, signal);
title('Time Domain: 440 Hz + Noise');
xlabel('Time (ms)');
ylabel('Amplitude');
grid on;
subplot(2, 1, 2);
plot(f(1:N/2), abs(Y(1:N/2))/N);
title('Frequency Domain (FFT)');
xlabel('Frequency (Hz)');
ylabel('Magnitude');
xlim([0 2000]);
grid on;
```
---
### Example 8: Filter Design and Response
**What it demonstrates:** Signal Processing Toolbox integration.
```matlab
% Design low-pass Butterworth filter
fc = 1000; % Cutoff frequency (Hz)
fs = 8000; % Sample rate (Hz)
[b, a] = butter(4, fc/(fs/2)); % 4th order
% Plot frequency response
freqz(b, a, 1024, fs);
title('Low-Pass Butterworth Filter (1 kHz cutoff)');
grid on;
```
---
## Asynchronous Jobs (Long-Running)
Code exceeding `sync_timeout` (default 30s) automatically promotes to async. Report progress with `mcp_progress()`.
### Example 9: Monte Carlo Simulation
**What it demonstrates:** Automatic async promotion and progress tracking.
```matlab
% Estimate π via Monte Carlo (1 million trials)
n_trials = 1e6;
inside_circle = 0;
for i = 1:n_trials
x = rand();
y = rand();
if x^2 + y^2 <= 1
inside_circle = inside_circle + 1;
end
% Report progress every 100k trials
if mod(i, 1e5) == 0
pct = (i / n_trials) * 100;
msg = sprintf('Trial %d / %d (%.1f%%)', i, n_trials, pct);
mcp_progress(__mcp_job_id__, pct, msg);
end
end
pi_estimate = 4 * inside_circle / n_trials;
fprintf('\nEstimated π = %.6f (error: %.6f)\n', ...
pi_estimate, abs(pi_estimate - pi));
```
**Agent experience:**
1. Receives job ID immediately
2. Polls progress: "Trial 100000 / 1000000 (10%)" → "Trial 500000 / 1000000 (50%)" → etc.
3. Gets final result: "Estimated π = 3.141592"
---
### Example 10: Large SVD Computation
**What it demonstrates:** Async promotion for matrix operations.
```matlab
% Singular value decomposition of large matrix
% This ~45 second computation triggers automatic async
A = randn(5000, 5000);
fprintf('Computing SVD of 5000×5000 matrix...\n');
[U, S, V] = svd(A, 'econ');
fprintf('Singular values (top 10):\n');
disp(diag(S)(1:10));
fprintf('Computation complete.\n');
```
---
## File Operations
### Example 11: Save and Read Data
**What it demonstrates:** Persisting results and agent file retrieval.
```matlab
% Generate and save data
x = linspace(0, 10, 100);
y = sin(x) .* exp(-x/5);
% Save as MAT file (binary)
save('signal_data.mat', 'x', 'y');
% Also save as CSV (human-readable)
T = table(x', y', 'VariableNames', {'x', 'y'});
writetable(T, 'signal_data.csv');
fprintf('Saved signal_data.mat and signal_data.csv\n');
```
**Agent can then:**
```
read_data(filename="signal_data.mat", format="summary")
```
Returns:
```
Name Size Bytes Class
x 1x100 800 double array
y 1x100 800 double array
```
Or:
```
read_data(filename="signal_data.csv", format="summary")
```
Returns CSV text inline.
---
### Example 12: Generate and Read Plot
**What it demonstrates:** Saving figures and agent image retrieval.
```matlab
% Create and save a plot
figure('Visible', 'off');
x = linspace(-pi, pi, 200);
plot(x, sin(x), 'b-', 'LineWidth', 2);
plot(x, cos(x), 'r--', 'LineWidth', 2);
legend('sin(x)', 'cos(x)');
xlabel('x');
ylabel('y');
title('Trigonometric Functions');
grid on;
% Save as PNG
saveas(gcf, 'trig_functions.png');
close;
fprintf('Saved trig_functions.png\n');
```
**Agent retrieves:**
```
read_image(filename="trig_functions.png")
```
Image displays inline in Claude Desktop, Cursor, etc.
---
## Code Quality & Validation
### Example 13: Check Code Quality
**What it demonstrates:** Static MATLAB linting via MCP tool.
```matlab
% Code with potential issues (unused variables, implicit expansion)
function result = analyze_data(data)
mean_val = mean(data);
unused_var = sum(data); % Unused
% Implicit expansion (potential issue)
result = data * [1 2 3]; % Broadcasting
end
```
**Agent calls:**
```
check_code(code=<<< function result = analyze_data(data) ... end >>>)
```
Returns warnings:
```
Line 4: Implicit expansion occurs for operator *.
Line 3: Variable "unused_var" is not used.
```
---
### Example 14: Custom Tool Example
**What it demonstrates:** Using agent-defined custom MATLAB tools.
Assuming `custom_tools.yaml` contains:
```yaml
tools:
- name: signal_analysis
function: signal_analysis
parameters:
- name: signal
type: array
description: Input signal vector
- name: fs
type: number
description: Sample rate in Hz
```
And corresponding MATLAB function:
```matlab
function [freq_peaks, power] = signal_analysis(signal, fs)
Y = fft(signal);
power = abs(Y).^2 / length(signal);
[~, peak_idx] = max(power);
freq_peaks = (peak_idx - 1) * fs / length(signal);
end
```
**Agent uses it like any built-in tool:**
```
signal_analysis(signal=[values...], fs=8000)
```
---
## Monitoring & Diagnostics
### Example 15: Check Server Health
**What it demonstrates:** Real-time metrics access.
```javascript
// JavaScript / Node.js example
async function getServerHealth() {
const response = await fetch('http://127.0.0.1:8765/health', {
headers: {
'Authorization': 'Bearer YOUR_TOKEN_HERE'
}
});
const health = await response.json();
console.log('Server Status:', health.status);
console.log('Uptime:', health.uptime_seconds);
console.log('Engines:', health.engine_count);
console.log('Active Jobs:', health.active_jobs);
return health;
}
getServerHealth();
```
---
### Example 16: Monitor Pool Utilization
**What it demonstrates:** Pool metrics via MCP tool.
Agent calls:
```
get_pool_status()
```
Returns:
```json
{
"total_engines": 8,
"busy_engines": 6,
"available_engines": 2,
"max_engines": 10,
"utilization_percent": 75.0
}
```
---
## Configuration & Deployment
### Configuration 1: Single-User Local Setup
```yaml
# config.yaml for local development
server:
transport: "stdio"
log_level: "debug"
pool:
min_engines: 1
max_engines: 2
execution:
sync_timeout: 30
security:
blocked_functions_enabled: true
```
**Run:**
```bash
matlab-mcp --config config.yaml
```
---
### Configuration 2: Multi-User Server with Auth
```yaml
# config.yaml for production multi-user
server:
transport: "streamablehttp"
host: "127.0.0.1"
port: 8765
log_level: "info"
pool:
min_engines: 4
max_engines: 16
warmup_percent: 50
execution:
sync_timeout: 60
max_concurrent_jobs: 100
sessions:
max_sessions: 50
session_timeout: 3600
security:
blocked_functions_enabled: true
require_proxy_auth: false
monitoring:
enabled: true
metrics_db: "./monitoring/metrics.db"
dashboard_port: 8765
```
**Run with auth:**
```bash
export MATLAB_MCP_AUTH_TOKEN=your-secure-token-here
matlab-mcp --config config.yaml
```
---
## Architecture Diagram
```mermaid
graph TB
Agent["AI Agent
(Claude, Cursor, etc.)"]
Transport["Transport Layer
(stdio, HTTP, SSE)"]
Auth["Auth Middleware
(Bearer Token)"]
MCP["MCP Tool Handler
(execute_code, etc.)"]
Sec["Security Validator
(blocked functions)"]
Job["Job Executor
(async promotion)"]
Pool["Engine Pool
(elastic scaling)"]
MATLAB["MATLAB Engine
(R2022b+)"]
Fmt["Result Formatter
(Plotly, PNG)"]
Agent -->|Request| Transport
Transport -->|MCP JSON-RPC| Auth
Auth -->|Validated| MCP
MCP -->|Check code| Sec
Sec -->|Valid| Job
Job -->|Acquire engine| Pool
Pool -->|Execute| MATLAB
MATLAB -->|Output| Job
Job -->|Format| Fmt
Fmt -->|Response| Agent
```
---
## Tips & Best Practices
1. **Use progress reporting** for jobs over 10 seconds — agents appreciate visibility:
```matlab
mcp_progress(__mcp_job_id__, percent, message);
```
2. **Vectorize when possible** — MATLAB is fastest with array operations, slowest with loops:
```matlab
% ✓ Fast
result = sin(x) .* cos(y);
% ✗ Slow
for i = 1:length(x)
result(i) = sin(x(i)) * cos(y(i));
end
```
3. **Close figures explicitly** to avoid memory leaks:
```matlab
figure; plot(...); saveas(gcf, 'output.png'); close;
```
4. **Validate inputs** in custom tools — agents may send unexpected types:
```matlab
function result = my_tool(data)
if ~isvector(data), error('Input must be a vector'); end
result = sum(data);
end
```
5. **Use inspect mode** for testing without MATLAB:
```bash
matlab-mcp --inspect # Pool disabled, tools return mocks
```