Skip to content

Custom Tools

github-actions[bot] edited this page Mar 18, 2026 · 11 revisions

Custom Tools

Expose your own MATLAB functions as first-class MCP tools. AI agents can discover and call them directly, with full parameter validation and help text.

How It Works

  1. Write your MATLAB function (.m file)
  2. Describe it in custom_tools.yaml
  3. The server registers it as an MCP tool at startup
  4. Agents see it alongside built-in tools

Configuration

Point your config.yaml to the custom tools file:

custom_tools:
  config_file: "./custom_tools.yaml"

YAML Schema

tools:
  - name: tool_name                    # MCP tool name (what agents call)
    matlab_function: pkg.func          # MATLAB function to call
    description: "What it does"        # Shown to agents
    parameters:
      - name: param_name
        type: string                   # string | int | float | double | bool | logical | list | dict | any
        required: true                 # or false
        description: "Parameter help"  # Shown to agents (optional)
      - name: optional_param
        type: float
        default: 1.0                   # Default value if not provided
    returns: "Description of return value"

Parameter Types

YAML Type Aliases Python Type
string str str
float number float
double float
int integer int
bool boolean bool
logical bool
list list
dict dict
any Any

Complete Example

1. MATLAB Function (mylib/analyze_signal.m)

function result = analyze_signal(signal_path, sample_rate, window_size)
    % ANALYZE_SIGNAL  Frequency analysis of a signal file
    %
    %   result = analyze_signal(signal_path, sample_rate, window_size)
    %
    %   Returns struct with: frequencies, magnitudes, snr, peaks

    data = load(signal_path);
    signal = data.signal;

    N = length(signal);
    Y = fft(signal, window_size);
    f = (0:window_size/2-1) * sample_rate / window_size;
    mag = abs(Y(1:window_size/2)) / N;

    [peaks, locs] = findpeaks(mag, 'MinPeakHeight', max(mag)*0.1);

    result.frequencies = f;
    result.magnitudes = mag;
    result.snr = snr(signal);
    result.peaks = struct('frequencies', f(locs), 'amplitudes', peaks);
end

2. Custom Tool Definition (custom_tools.yaml)

tools:
  - name: analyze_signal
    matlab_function: mylib.analyze_signal
    description: >
      Analyze a signal file and return frequency components, SNR,
      and peak detection results.
    parameters:
      - name: signal_path
        type: string
        required: true
        description: "Path to the signal data file (.mat)"
      - name: sample_rate
        type: double
        required: true
        description: "Sample rate in Hz"
      - name: window_size
        type: int
        default: 1024
        description: "FFT window size"
    returns: "Struct with fields: frequencies, magnitudes, snr, peaks"

3. Make Sure MATLAB Can Find It

Add the directory containing your .m files to the workspace paths in config.yaml:

workspace:
  default_paths:
    - "/path/to/mylib"

4. Agent Usage

The agent now sees analyze_signal as a tool and can call it:

"Analyze the signal in data/recording.mat at 44100 Hz sample rate"

The server:

  1. Validates parameters against the YAML schema
  2. Calls mylib.analyze_signal('data/recording.mat', 44100, 1024) in MATLAB
  3. Returns the result to the agent

Multiple Tools

tools:
  - name: analyze_signal
    matlab_function: mylib.analyze_signal
    description: "Frequency analysis of signal files"
    parameters:
      - name: signal_path
        type: string
        required: true
        description: "Path to the signal data file (.mat)"
    returns: "Frequency analysis struct"

  - name: train_model
    matlab_function: ml.train_classifier
    description: "Train a classification model"
    parameters:
      - name: dataset_path
        type: string
        required: true
        description: "Path to training data"
      - name: model_type
        type: string
        default: "svm"
        description: "Model type: svm, tree, knn, ensemble"
      - name: validation_split
        type: double
        default: 0.2
        description: "Validation data fraction (0-1)"
    returns: "Trained model and accuracy metrics"

  - name: process_image
    matlab_function: imgtools.enhance_image
    description: "Image enhancement pipeline"
    parameters:
      - name: image_path
        type: string
        required: true
        description: "Path to the input image"
      - name: denoise_strength
        type: double
        default: 0.5
        description: "Denoising strength (0=none, 1=maximum)"
      - name: sharpen
        type: logical
        default: false
        description: "Apply sharpening filter"
    returns: "Enhanced image saved to temp directory"

  - name: compute_statistics
    matlab_function: stats.compute_summary
    description: "Compute summary statistics for a data file"
    parameters:
      - name: data_path
        type: string
        required: true
        description: "Path to the .mat file containing the data variable"
    returns: "Struct with mean, std, median, min, max, histogram data"

Loading and Registration

Custom tools are loaded at server startup:

  1. Read YAML file – The server reads custom_tools.yaml (path from config.yaml)
  2. Parse definitions – Each tool definition is validated as a CustomToolDef
  3. Create handlers – For each tool, the server generates an async handler function with proper type signatures
  4. Register with FastMCP – Each handler is registered as an MCP tool, making it discoverable by agents
  5. Parameter validation – FastMCP automatically validates parameters against the declared types before calling the handler

If a tool definition is invalid (missing required fields, unknown type), it is logged as a warning and skipped.

Parameter Descriptions

Include a description field for each parameter to provide help text to agents:

tools:
  - name: my_tool
    matlab_function: pkg.func
    parameters:
      - name: input_file
        type: string
        required: true
        description: "Input data file in .mat or .csv format"
      - name: threshold
        type: float
        default: 0.5
        description: "Detection threshold (0-1)"

Tips

  • Function names with packages: Use pkg.func notation to call functions in MATLAB packages (e.g., +mylib/analyze_signal.mmylib.analyze_signal)
  • MEX files: Custom tools work with .mex files too — just reference the function name without the extension
  • MATLAB numeric types: Use double for MATLAB's default floating-point type, int for integers, and logical for booleans
  • Error handling: If the MATLAB function throws an error, the MCP server returns a structured error response to the agent
  • Testing: Test your functions in MATLAB first before exposing them as tools
  • Return values: The return value from the MATLAB function is automatically converted to JSON and sent to the agent. Structs become objects, arrays become lists.

Clone this wiki locally