-
Notifications
You must be signed in to change notification settings - Fork 0
Examples
Ready-to-run code examples for the MATLAB MCP server. These aren't executed directly — ask your AI agent to run them!
graph LR
Agent["🤖 AI Agent<br/>(Claude, Cursor)"]
MCP["MCP Server"]
Pool["Engine Pool<br/>(2-10 MATLAB)"]
Workspace["Session Workspace"]
Agent -->|execute_code<br/>MATLAB code| MCP
MCP -->|acquire engine| Pool
Pool -->|execute in| Workspace
Workspace -->|stdout/variables<br/>figures| MCP
MCP -->|job_id or result| Agent
style Agent fill:#6366f1
style MCP fill:#8b5cf6
style Pool fill:#ec4899
style Workspace fill:#f59e0b
Before running any examples:
-
Server running locally:
matlab-mcp --transport sse # or stdio for single user -
Agent connected:
- Claude Desktop, Claude Code, Cursor, or Codex CLI via
/mcpendpoint - Bearer token authentication (if configured):
MATLAB_MCP_AUTH_TOKENenv var
- Claude Desktop, Claude Code, Cursor, or Codex CLI via
-
MATLAB available:
- MATLAB R2022b+ running or accessible via Engine API
- Common toolboxes pre-installed (Signal, Image Processing optional)
Ask your agent: "Calculate the sum of integers from 1 to 100"
result = sum(1:100);
fprintf('Sum: %d\n', result);Expected output:
Sum: 5050
Ask your agent: "Create a 3×3 magic square and show its properties"
A = magic(3);
disp('Magic Square:');
disp(A);
fprintf('Sum of rows: %d\n', sum(A(1,:)));
fprintf('Determinant: %.2f\n', det(A));
fprintf('Rank: %d\n', rank(A));Expected output:
Magic Square:
8 1 6
3 5 7
4 9 2
Sum of rows: 15
Determinant: -360.00
Rank: 3
Ask your agent: "Solve the system: 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('x = %.4f, y = %.4f, z = %.4f\n', x(1), x(2), x(3));Ask your agent: "Generate 1000 random samples from a normal distribution and compute stats"
data = randn(1000, 1);
fprintf('Mean: %.4f\n', mean(data));
fprintf('Std Dev: %.4f\n', std(data));
fprintf('Min: %.4f\n', min(data));
fprintf('Max: %.4f\n', max(data));
fprintf('Median: %.4f\n', median(data));Ask your agent: "Create a table of 5 students with names, test scores, and calculate averages"
students = table(...
{'Alice'; 'Bob'; 'Charlie'; 'Diana'; 'Eve'}, ...
[92; 85; 78; 95; 88], ...
[88; 90; 82; 93; 86], ...
'VariableNames', {'Name', 'Test1', 'Test2'});
students.Average = (students.Test1 + students.Test2) / 2;
disp(students);
fprintf('Class Average: %.2f\n', mean(students.Average));All MATLAB plots are automatically converted to interactive Plotly JSON and static PNG.
Ask your agent: "Plot sine and cosine functions from 0 to 2π"
x = linspace(0, 2*pi, 200);
y1 = sin(x);
y2 = cos(x);
plot(x, y1, 'r-', 'LineWidth', 2, 'DisplayName', 'sin(x)'); hold on;
plot(x, y2, 'b--', 'LineWidth', 2, 'DisplayName', 'cos(x)');
xlabel('x'); ylabel('y');
title('Trigonometric Functions');
legend;
grid on;Plot features preserved:
- Line colors (red, blue)
- Line styles (solid
—, dashed--) - Line width
- Legend and labels
- Grid
Ask your agent: "Visualize the peaks function as a 3D surface"
[X, Y] = meshgrid(-3:0.1:3, -3:0.1:3);
Z = peaks(X, Y);
surf(X, Y, Z);
colorbar;
shading interp;
xlabel('X'); ylabel('Y'); zlabel('Z');
title('Peaks Function');Ask your agent: "Show frequency response plots for 4 different signal frequencies"
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
sgtitle('Frequency Sweep');Ask your agent: "Create a histogram of test scores and a bar chart of class averages"
scores = randn(100, 1) * 15 + 75; % mean 75, std 15
subplot(1, 2, 1);
histogram(scores, 20, 'EdgeColor', 'black');
xlabel('Score'); ylabel('Frequency');
title('Score Distribution');
subplot(1, 2, 2);
classes = {'A', 'B', 'C', 'D'};
avgs = [92, 85, 78, 65];
bar(avgs);
set(gca, 'XTickLabel', classes);
ylabel('Average Score');
title('Class Performance');Requires Signal Processing Toolbox (optional). Examples work with basic MATLAB too.
Ask your agent: "Generate a 1 kHz tone with noise, compute its FFT, and show frequency spectrum"
fs = 8000; % Sample rate
t = 0:1/fs:1; % 1 second
signal = sin(2*pi*1000*t) + 0.3*randn(size(t));
N = length(signal);
Y = fft(signal);
f = (0:N-1) * fs / N;
subplot(2, 1, 1);
plot(t(1:500), signal(1:500));
xlabel('Time (s)'); ylabel('Amplitude');
title('Time Domain (1 kHz Tone + Noise)');
grid on;
subplot(2, 1, 2);
plot(f(1:N/2), abs(Y(1:N/2)) / N, 'LineWidth', 1);
xlabel('Frequency (Hz)'); ylabel('Magnitude');
title('Frequency Domain');
xlim([0, 2000]);
grid on;Ask your agent: "Design a 5th-order Butterworth filter at 500 Hz (Fs=8kHz) and show impulse response"
fs = 8000;
fc = 500;
wc = 2 * fc / fs; % Normalized cutoff
[b, a] = butter(5, wc); % Requires Signal Processing Toolbox
subplot(2, 1, 1);
impz(b, a);
title('Filter Impulse Response');
grid on;
subplot(2, 1, 2);
freqz(b, a, 1024, fs);
grid on;Ask your agent: "Create a spectrogram of a chirp signal from 100 Hz to 1 kHz"
fs = 8000;
t = 0:1/fs:2; % 2 seconds
% Linear chirp from 100 Hz to 1 kHz
f0 = 100; f1 = 1000;
signal = chirp(t, f0, t(end), f1);
spectrogram(signal, 512, 256, 512, fs, 'yaxis');
title('Spectrogram: 100 Hz → 1 kHz Chirp');Jobs exceeding sync_timeout (default 30s) auto-promote to async. Use mcp_progress() to report progress.
Ask your agent: "Estimate π using Monte Carlo with 1 million samples, reporting progress every 100k samples"
n = 1e6;
inside = 0;
for i = 1:n
x = rand();
y = rand();
if x^2 + y^2 <= 1
inside = inside + 1;
end
% Report progress every 100k samples
if mod(i, 1e5) == 0
pct = (i / n) * 100;
msg = sprintf('Sample %d/%d (%.1f%%)', i, n, pct);
mcp_progress(__mcp_job_id__, pct, msg);
end
end
pi_estimate = 4 * inside / n;
fprintf('Estimated π: %.6f\n', pi_estimate);
fprintf('Error: %.6f\n', abs(pi_estimate - pi));Agent sees:
- Initial job ID returned immediately
- Progress updates: "Sample 100000/1000000 (10.0%)" → "50%" → "100%"
- Final result when complete
Ask your agent: "Solve a 1000×1000 linear system iteratively with progress tracking"
n = 1000;
A = gallery('poisson', n);
b = ones(n, 1);
x = zeros(n, 1);
r = b - A*x;
rr = r' * r;
max_iter = 100;
for k = 1:max_iter
Ap = A * r;
alpha = rr / (r' * Ap);
x = x + alpha * r;
r_new = r - alpha * Ap;
rr_new = r_new' * r_new;
% Report progress every 10 iterations
if mod(k, 10) == 0
residual = sqrt(rr_new);
pct = (k / max_iter) * 100;
mcp_progress(__mcp_job_id__, pct, ...
sprintf('Iteration %d: residual=%.6f', k, residual));
end
if sqrt(rr_new) < 1e-6
break;
end
r = r_new;
rr = rr_new;
end
fprintf('Converged in %d iterations\n', k);
fprintf('Final residual: %.6e\n', sqrt(rr));Use file tools to work with data on the server.
Ask your agent: "Generate random data, save to a .mat file, then read it back"
% Generate and save
data = randn(1000, 5);
labels = {'X', 'Y', 'Z', 'W', 'V'};
save('mydata.mat', 'data', 'labels');
fprintf('Saved mydata.mat\n');Then: "Show me what's in mydata.mat"
load('mydata.mat');
whos % Lists variable names, sizes, typesThe agent can then call read_data(filename="mydata.mat", format="summary") to see the variables.
Ask your agent: "Create a table and export to CSV"
names = {'Alice'; 'Bob'; 'Charlie'};
scores = [92; 85; 78];
T = table(names, scores, 'VariableNames', {'Name', 'Score'});
writetable(T, 'results.csv');
fprintf('Exported to results.csv\n');Then: "Show me the CSV contents"
The agent calls read_data(filename="results.csv", format="summary").
Ask your agent: "Create a heatmap and save it as an image"
data = peaks(100);
imagesc(data);
colorbar;
title('Peaks Heatmap');
saveas(gcf, 'heatmap.png');
fprintf('Saved heatmap.png\n');Then: "Show me the heatmap image"
The agent calls read_image(filename="heatmap.png") — the image renders inline in the chat.
server:
transport: "stdio"
log_level: "info"
pool:
min_engines: 1
max_engines: 2
execution:
sync_timeout: 30
max_execution_time: 86400server:
transport: "streamablehttp"
host: "127.0.0.1"
port: 8765
log_level: "info"
pool:
min_engines: 4
max_engines: 16
matlab_root: "/Applications/MATLAB_R2024a.app"
execution:
sync_timeout: 30
max_execution_time: 86400
security:
blocked_functions:
- system
- unix
- dos
- eval
- assignin
sessions:
max_sessions: 50
session_timeout: 3600
monitoring:
enabled: true
database: "/var/log/matlab_mcp/metrics.db"server:
transport: "streamablehttp"
host: "0.0.0.0"
port: 8765
pool:
min_engines: 2
max_engines: 8
matlab_root: "/opt/matlab"
security:
blocked_functions_enabled: true
max_upload_size_mb: 500
monitoring:
enabled: true
database: "/data/metrics.db"You: "Can you solve this optimization problem? Minimize f(x,y) = (x-2)² + (y-3)² starting from (0,0)"
Agent executes:
options = optimoptions('fminunc', 'Display', 'iter');
[x_opt, f_opt] = fminunc(@(p) (p(1)-2)^2 + (p(2)-3)^2, [0; 0], options);
fprintf('Optimal point: x=%.4f, y=%.4f\n', x_opt(1), x_opt(2));
fprintf('Minimum value: %.6f\n', f_opt);Agent returns result and can immediately follow up: "Can you plot the contours around that optimum?"
You: "Load the data I uploaded (test_data.csv) and show me summary statistics"
Agent executes:
T = readtable('test_data.csv');
disp(T);
summary(T);You: "Now plot distributions for the numeric columns"
Agent extracts numeric columns and creates subplots automatically.
You: "I have 1000 images. Process each one (takes ~3s each) and report progress"
Agent executes a loop with mcp_progress() calls, and the server streams back:
- "Processing image 1/1000 (0%)"
- "Processing image 250/1000 (25%)"
- ... until complete
| Task | Pattern |
|---|---|
| Multi-step analysis | Execute one cell at a time; agent persists workspace across calls |
| Large outputs | Results >50KB saved to file; agent reads via read_data or read_image
|
| Error recovery | If code errors, workspace state is preserved; agent can fix and retry |
| Plot rendering | All figures auto-converted to Plotly; rendered in agent's native UI |
| Bulk imports | Upload ZIP, extract in MATLAB, process — use file tools for convenience |
| External functions | Add custom .m functions to session temp dir; they're on the path |
-
Configuration Reference — Full
config.yamlschema - MCP Tools Reference — Complete tool parameter specs
- Architecture — How the server scales and isolates sessions
- Custom Tools — Expose your own MATLAB functions