-
Notifications
You must be signed in to change notification settings - Fork 0
Examples
Ready-to-run examples are organized by complexity and use case. These examples demonstrate how to ask your AI agent to execute MATLAB code through the MCP server.
graph LR
A["AI Agent<br/>(Claude, etc.)"] -->|"execute_code(code)"| B["MCP Server"]
B -->|"Acquire Engine"| C["Engine Pool"]
C -->|"Run MATLAB Code"| D["MATLAB Engine"]
D -->|"Capture Output<br/>Variables<br/>Figures"| E["Result Formatter"]
E -->|"Convert Plots<br/>to Plotly"| F["Response"]
F -->|"JSON + Metadata"| A
What it demonstrates: Basic MATLAB computation and formatted output.
% Simple calculations
x = 42;
y = 3.14159;
result = x * y;
fprintf('Answer: %.2f\n', result);Prerequisites: None — runs in base MATLAB.
Expected output:
Answer: 131.87
What it demonstrates: Array manipulation and linear algebra.
% Create and manipulate matrices
A = [1 2 3; 4 5 6; 7 8 9];
B = A' * A; % Transpose and multiply
trace_val = trace(B);
det_val = det(A);
fprintf('Trace(A^T * A): %.1f\n', trace_val);
fprintf('Det(A): %.1f\n', det_val);Prerequisites: None.
What it demonstrates: Using the backslash operator for equation solving.
% Solve Ax = b
A = [3 2 -1; 2 -2 4; -1 0.5 -1];
b = [1; -2; 0];
x = A \ b;
disp('Solution:');
disp(x);Prerequisites: None.
What it demonstrates: Computing mean, median, standard deviation, and quantiles.
% Generate random data and compute statistics
data = randn(1000, 1); % 1000 normal samples
stats.mean = mean(data);
stats.median = median(data);
stats.std = std(data);
stats.q25 = quantile(data, 0.25);
stats.q75 = quantile(data, 0.75);
fprintf('Mean: %.4f\n', stats.mean);
fprintf('Std Dev: %.4f\n', stats.std);
fprintf('IQR (Q25-Q75): [%.4f, %.4f]\n', stats.q25, stats.q75);Prerequisites: None.
What it demonstrates: Fitting a polynomial to noisy data.
% Generate noisy sinusoidal data
x = linspace(0, 2*pi, 100)';
y = sin(x) + 0.2*randn(100, 1);
% Fit a 4th-degree polynomial
p = polyfit(x, y, 4);
y_fit = polyval(p, x);
% Calculate R-squared
ss_res = sum((y - y_fit).^2);
ss_tot = sum((y - mean(y)).^2);
r_squared = 1 - (ss_res / ss_tot);
fprintf('R² = %.4f\n', r_squared);Prerequisites: None.
All figures are automatically converted to interactive Plotly JSON plus a static PNG thumbnail.
What it demonstrates: Creating a styled line plot with labels, grid, and legend.
% Create a sine wave plot
x = linspace(0, 2*pi, 200);
y1 = sin(x);
y2 = cos(x);
plot(x, y1, 'b-', 'LineWidth', 2, 'DisplayName', 'sin(x)');
hold on;
plot(x, y2, 'r--', 'LineWidth', 2, 'DisplayName', 'cos(x)');
hold off;
xlabel('x');
ylabel('y');
title('Sine and Cosine');
legend('show');
grid on;
xlim([0 2*pi]);Prerequisites: None.
Output: Interactive Plotly trace with line styles, markers, and hover data.
What it demonstrates: Rendering a 3D surface with color mapping and rotation support.
% Create a 3D surface
[X, Y] = meshgrid(-3:0.1:3);
Z = peaks(X, Y);
surf(X, Y, Z, 'EdgeColor', 'none');
colorbar;
shading interp;
title('Peaks Function');
xlabel('X'); ylabel('Y'); zlabel('Z');Prerequisites: None.
Output: WebGL-accelerated 3D plot with interactive rotation and zoom.
What it demonstrates: Arranging multiple plots in a grid layout.
% Create a 2x2 grid of different plots
t = linspace(0, 2*pi, 200);
subplot(2, 2, 1);
plot(t, sin(t));
title('sin(t)');
subplot(2, 2, 2);
plot(t, cos(t));
title('cos(t)');
subplot(2, 2, 3);
plot(t, sin(2*t));
title('sin(2t)');
subplot(2, 2, 4);
plot(t, exp(-t/4).*sin(t));
title('Damped oscillation');Prerequisites: None.
Output: Layout with 4 domains, each containing a trace and axes.
What it demonstrates: Visualizing 2D matrix data with color intensity.
% Create correlation matrix heatmap
data = randn(10, 10);
correlation = corr(data);
imagesc(correlation);
colorbar;
caxis([-1 1]);
title('Correlation Matrix');
xticks(1:10);
yticks(1:10);Prerequisites: None.
Output: Heatmap trace with categorical axes.
What it demonstrates: Binning and visualizing distributions.
% Plot histogram of random data
data = randn(10000, 1);
histogram(data, 50, 'Normalization', 'probability');
hold on;
x = linspace(-4, 4, 100);
plot(x, normpdf(x), 'r-', 'LineWidth', 2);
hold off;
title('Normal Distribution');
xlabel('Value');
ylabel('Probability');Prerequisites: None.
Output: Bar chart with overlay trace.
Requires the Signal Processing Toolbox (ver must list it).
What it demonstrates: Computing the Fast Fourier Transform and identifying dominant frequencies.
% Generate a multi-frequency signal
fs = 1000; % Sampling frequency
t = (0:1/fs:2)';
signal = sin(2*pi*50*t) + 0.5*sin(2*pi*120*t) + 0.3*randn(size(t));
% Compute FFT
N = length(signal);
Y = fft(signal);
f = (0:N-1) * fs / N;
% Plot magnitude spectrum (first half only)
subplot(2, 1, 1);
plot(t*1000, signal);
title('Time Domain');
xlabel('Time (ms)');
ylabel('Amplitude');
subplot(2, 1, 2);
plot(f(1:N/2), abs(Y(1:N/2))*2/N);
title('Frequency Domain (FFT)');
xlabel('Frequency (Hz)');
ylabel('Magnitude');
xlim([0 250]);Prerequisites:
- Signal Processing Toolbox (for optimal results)
Expected output:
- Time-domain plot showing the 50 Hz and 120 Hz components
- Frequency plot with peaks at 50 Hz and 120 Hz
What it demonstrates: Designing and applying a Butterworth low-pass filter.
% Design a Butterworth filter
fs = 1000;
fc = 100; % Cutoff frequency
order = 4;
% Normalized cutoff frequency (0 < Wn < 1)
Wn = fc / (fs/2);
% Design IIR filter
[b, a] = butter(order, Wn);
% Generate noisy signal
t = (0:1/fs:2)';
clean = sin(2*pi*10*t);
noise = 0.3*randn(size(t));
signal = clean + noise;
% Apply filter
filtered = filtfilt(b, a, signal);
% Plot results
plot(t*1000, signal, 'r-', 'Alpha', 0.5, 'DisplayName', 'Noisy');
hold on;
plot(t*1000, filtered, 'b-', 'LineWidth', 2, 'DisplayName', 'Filtered');
hold off;
legend('show');
xlabel('Time (ms)');
ylabel('Amplitude');
title('Low-Pass Filter (100 Hz cutoff)');Prerequisites:
- Signal Processing Toolbox
Expected output:
- Overlaid plot showing noise reduction
- Interactive legend toggling
What it demonstrates: Time-frequency analysis of a chirp signal.
% Generate a chirp signal (frequency increases over time)
fs = 1000;
t = (0:1/fs:3)';
f_start = 10; % Start frequency
f_end = 100; % End frequency
% Linear chirp
chirp_signal = chirp(t, f_start, t(end), f_end);
% Compute spectrogram
spectrogram(chirp_signal, [], [], [], fs, 'yaxis');
title('Spectrogram of Chirp Signal');
ylabel('Frequency (Hz)');
xlabel('Time (s)');
colorbar;Prerequisites:
- Signal Processing Toolbox
Expected output:
- Interactive spectrogram with frequency increasing over time
Jobs exceeding sync_timeout (default 30 seconds) are automatically promoted to asynchronous background execution. Use mcp_progress() to report progress back to the agent.
What it demonstrates: Long-running async job with periodic progress updates.
% Estimate pi using Monte Carlo method
% This typically takes 60+ seconds, triggering async promotion
n_trials = 1e7; % 10 million trials
inside_circle = 0;
for i = 1:n_trials
% Generate random point in [0,1]^2
x = rand();
y = rand();
% Check if inside unit circle
if x^2 + y^2 <= 1
inside_circle = inside_circle + 1;
end
% Report progress every 500K trials
if mod(i, 500000) == 0
progress_pct = (i / n_trials) * 100;
msg = sprintf('Trial %d / %d', i, n_trials);
mcp_progress(__mcp_job_id__, progress_pct, msg);
end
end
% Estimate pi
pi_estimate = 4 * inside_circle / n_trials;
fprintf('Pi estimate: %.6f (error: %.6f)\n', pi_estimate, abs(pi_estimate - pi));Prerequisites:
- MATLAB base language
-
sync_timeoutmust be < expected execution time (e.g.,sync_timeout: 30)
Expected behavior:
- Agent receives
status: "running"withjob_idimmediately - Agent polls
get_job_status(job_id)every few seconds - Progress updates: 10%, 20%, ..., 100%
- Final result retrieved with
get_job_result(job_id)
What it demonstrates: Memory-intensive async job with progress tracking.
% Singular Value Decomposition of a large matrix
% 5000x5000 = 25M elements
n = 5000;
fprintf('Creating %dx%d matrix...\n', n, n);
A = randn(n, n);
fprintf('Computing SVD...\n');
tic;
[U, S, V] = svd(A, 'econ');
elapsed = toc;
% Report metrics
singular_values = diag(S);
condition_number = singular_values(1) / singular_values(end);
fprintf('SVD completed in %.1f seconds\n', elapsed);
fprintf('Condition number: %.2e\n', condition_number);
fprintf('Top 5 singular values: ');
fprintf('%.4e ', singular_values(1:5));
fprintf('\n');Prerequisites:
- MATLAB base language
- Sufficient RAM (~500MB)
What it demonstrates: Solver with per-iteration progress reporting.
% Solve Ax = b using Conjugate Gradient method
% Report convergence progress per iteration
n = 1000;
A = sprand(n, n, 0.01);
A = A' * A; % Make symmetric positive-definite
b = randn(n, 1);
tol = 1e-6;
max_iter = n;
% Simplified MATLAB CG iteration tracking
x = zeros(n, 1);
r = b - A*x;
p = r;
rsold = r' * r;
for iter = 1:max_iter
Ap = A * p;
alpha = rsold / (p' * Ap);
x = x + alpha * p;
r = r - alpha * Ap;
rsnew = r' * r;
% Report every 10 iterations
if mod(iter, 10) == 0
residual = sqrt(rsnew);
progress_pct = min(100, (iter / max_iter) * 100);
msg = sprintf('Iter %d: residual = %.2e', iter, residual);
mcp_progress(__mcp_job_id__, progress_pct, msg);
end
if sqrt(rsnew) < tol
fprintf('Converged in %d iterations\n', iter);
break;
end
beta = rsnew / rsold;
p = r + beta * p;
rsold = rsnew;
end
fprintf('Final residual: %.2e\n', sqrt(rsnew));Prerequisites:
- MATLAB base language
What it demonstrates: Loading a CSV file and computing statistics.
% Read CSV file (previously uploaded by agent)
% Files are in the session temp directory
% List available files
dir_listing = dir('*.csv');
if isempty(dir_listing)
error('No CSV files found');
end
filename = dir_listing(1).name;
fprintf('Reading: %s\n', filename);
% Load CSV
T = readtable(filename);
fprintf('Loaded table with %d rows, %d columns\n', height(T), width(T));
% Display summary statistics
summary_table = array2table([
min(T{:,:}),
max(T{:,:}),
mean(T{:,:}),
std(T{:,:})
], 'VariableNames', T.Properties.VariableNames, ...
'RowNames', {'Min', 'Max', 'Mean', 'StdDev'});
disp(summary_table);Prerequisites:
- CSV file uploaded via
upload_datatool
What it demonstrates: Saving variables to a MATLAB .mat file for later retrieval.
% Perform analysis and save results
% Generate synthetic data
t = linspace(0, 10, 1000);
y = sin(t) + 0.1*randn(size(t));
% Fit exponential decay model
X = [ones(size(t')), t'];
params = X \ y';
% Save all results to .mat
results.time = t;
results.data = y;
results.parameters = params;
results.timestamp = datetime('now');
save('analysis_results.mat', '-struct', 'results');
fprintf('Saved to analysis_results.mat\n');Prerequisites:
- None
Output: .mat file in session temp directory, readable via read_data tool.
What it demonstrates: Generating a .m file programmatically, then reading it back.
% Create a reusable function script
script_content = sprintf([
'%% Auto-generated analysis script\n' ...
'function y = my_analysis(x)\n' ...
' y = sin(x) + cos(x.^2);\n' ...
'end\n'
]);
% Write to file
fid = fopen('my_analysis.m', 'w');
fprintf(fid, script_content);
fclose(fid);
fprintf('Created my_analysis.m\n');Prerequisites:
- None
Use case: Development, personal use, stdio transport.
File: config_minimal.yaml
server:
name: "matlab-mcp-minimal"
transport: "stdio"
log_level: "debug"
pool:
min_engines: 1
max_engines: 2
matlab_root: null # Auto-detect
execution:
sync_timeout: 30
temp_dir: "./temp"
output:
plotly_conversion: true
large_result_threshold: 50000
security:
blocked_functions_enabled: trueLaunch:
matlab-mcp --config config_minimal.yamlUse case: Team deployment, SSE transport, reverse proxy auth.
File: config_multiuser.yaml
server:
name: "matlab-mcp-team"
transport: "sse"
host: "127.0.0.1" # Behind reverse proxy only
port: 8765
log_level: "info"
pool:
min_engines: 4
max_engines: 16
scale_down_idle_timeout: 600
health_check_interval: 30
execution:
sync_timeout: 60 # Allow longer sync execution
max_execution_time: 3600 # 1 hour max
temp_dir: "./sessions"
output:
plotly_conversion: true
thumbnail_enabled: true
large_result_threshold: 100000
security:
blocked_functions_enabled: true
require_proxy_auth: true
max_upload_size_mb: 500
sessions:
max_sessions: 100
session_timeout: 7200 # 2 hours
monitoring:
enabled: true
sample_interval: 10Deployment:
# Behind nginx with authentication
nginx -c /etc/nginx/matlab-mcp.conf
matlab-mcp --config config_multiuser.yamlUse case: Exposing domain-specific MATLAB functions as first-class MCP tools.
File: custom_tools.yaml
tools:
- name: "analyze_signal"
matlab_function: "signal_analysis.analyze"
description: "Analyze frequency content of a signal"
parameters:
signal:
type: "list"
description: "Time-series signal samples"
sampling_rate:
type: "float"
default: 1000.0
description: "Sampling rate in Hz"
fft_size:
type: "int"
default: 1024
description: "FFT window size"
returns:
description: "Struct with frequency bins and magnitudes"
- name: "train_model"
matlab_function: "ml_suite.train_classifier"
description: "Train a classification model"
parameters:
training_data:
type: "string"
description: "Path to .mat file with X and y"
model_type:
type: "string"
default: "svm"
description: "Model type: 'svm', 'rf', 'nb'"
regularization:
type: "float"
default: 1.0
description: "Regularization parameter"
returns:
description: "Trained model struct"
- name: "generate_report"
matlab_function: "reporting.generate_latex_report"
description: "Generate a LaTeX PDF report"
parameters:
title:
type: "string"
description: "Report title"
sections:
type: "dict"
description: "Section names and content"
output_filename:
type: "string"
default: "report.pdf"
description: "Output PDF filename"
returns:
description: "Path to generated PDF"Usage by agent:
analyze_signal(signal=[...], sampling_rate=8000)
train_model(training_data="data.mat", model_type="rf")
generate_report(title="Q4 Analysis", sections={...})
- Explore the Configuration guide for all tuning options
- Read Async Jobs for deeper progress-reporting patterns
- Check Security before deploying to shared servers
-
See Custom Tools for exposing your own
.mfunctions