Skip to content

matlab-deep-learning/mcpHTTPClient

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MATLAB MCP HTTP Client

Create MCP client in MATLAB® to call external tools in LLM workflows

Model Context Protocol (MCP) is a framework for communication between AI agents and external tools. Typically, a large language model (LLM) application sets up one or more MCP clients that each connect to an MCP server. The MCP server provides context and tools the LLM application can use.

This add-on allows you to:

Setup

Examples

Functions

Setup

Using this add-on requires MATLAB R2025a or newer.

To generate and execute tool calls from MATLAB, you also need version 4.6.0 or newer of the Large Language Models (LLMs) with MATLAB add-on.

Use MATLAB Online

You can use the add-on in MATLAB Online by clicking this link: Open in MATLAB Online

Install Using Add-On Explorer

The recommended way of using the add-on in an installed version of MATLAB is to use the Add-On Explorer.

  1. In MATLAB, go to the Home tab, and in the Environment section, click the Add-Ons icon.
  2. In the Add-On Explorer, search for "MATLAB MCP HTTP Client".
  3. Select Install.

Examples

Create MCP Client

Create an MCP client using the mcpHTTPClient function. Specify the URL of the MCP server to which you want to connect. For example, use the IO Aerospace MCP server to access aerospace and astrodynamics tools.

endpoint = "https://mcp.io-aerospace.org/";
client = mcpHTTPClient(endpoint);

The MCP client stores information about the available tools from the server in the ServerTools property.

serverTools = client.ServerTools;

The IO Aerospace MCP server provides a tool called get_celestial_body_properties that returns the geophysical properties of a celestial body.

toolGetCelestialBodyProperties = serverTools{23}
toolGetCelestialBodyProperties = struct with fields:
            name: 'get_celestial_body_properties'
           title: 'Get celestial body properties'
     description: 'Gets geophysical properties of a celestial body'
     inputSchema: [1x1 struct]
    outputSchema: [1x1 struct]
     annotations: [1x1 struct]

The input schema specifies the arguments required for the tool.

toolGetCelestialBodyProperties.inputSchema.properties
ans = struct with fields:
    celestialBodyName: [1x1 struct]

toolGetCelestialBodyProperties.inputSchema.properties.celestialBodyName
ans = struct with fields:
    description: 'Celestial body name'
           type: 'string'
           enum: {162x1 cell}

To call this tool, use the callTool function and specify the name of the tool as a positional input argument. Then, specify the tool arguments as additional name-value arguments Argument1=Value1,...,ArgumentN=ValueN. The tool get_celestial_body_properties provided by the IO Aerospace MCP server has one input argument, celestialBodyName.

toolName = toolGetCelestialBodyProperties.name;
toolOutput = callTool(client,toolName,celestialBodyName="Mars");
prettyPrintJSON(toolOutput)
{
  "naifId": 499,
  "centerOfMotionId": 10,
  "barycenterOfMotionId": 4,
  "name": "MARS",
  "radii": {
    "x": 3.39619E+6,
    "y": 3.39619E+6,
    "z": 3.3762E+6
  },
  "gm": 4.2828373620699086E+13,
  "frameName": "IAU_MARS",
  "frameId": 10014,
  "j2": "NaN",
  "j3": "NaN",
  "j4": "NaN"
}

Automatically Call External Tool Using LLM

This example shows how to use an LLM together with an MCP client to automatically call and execute external tools. The example requires the Large Language Models (LLMs) with MATLAB add-on.

First, configure the connection to the OpenAI® Chat Completion API following the Large Language Models (LLMs) with MATLAB documentation: OpenAI.

Create an MCP client using the mcpHTTPClient function. Specify the URL of the MCP server to which you want to connect. For example, use the IO Aerospace MCP server to access aerospace and astrodynamics tools.

endpoint = "https://mcp.io-aerospace.org/";
client = mcpHTTPClient(endpoint);

The MCP client stores information about the available tools from the server in the ServerTools property.

serverTools = client.ServerTools;

One of the tools available from this MCP server is get_celestial_body_properties.

toolGetCelestialBodyProperties = client.ServerTools{23}
toolGetCelestialBodyProperties = struct with fields:
            name: 'get_celestial_body_properties'
           title: 'Get celestial body properties'
     description: 'Gets geophysical properties of a celestial body'
     inputSchema: [1x1 struct]
    outputSchema: [1x1 struct]
     annotations: [1x1 struct]

To use the tools provided by the MCP client with the LLM, first convert the tools to fArray, an array of openAIFunction objects. Connect to the OpenAI Chat Completion API. Use the model GPT-4.1 mini. Give the model access to the server tools using the Tools argument.

fArray = openAIFunction(serverTools);
model = openAIChat(ModelName="gpt-4.1-mini",Tools=fArray);

To provide the conversation as context to the model, create a messageHistory object.

history = messageHistory;

Specify a prompt that could result in a tool call. For example, ask the model about the properties of Mars.

userPrompt = "Tell me about the properties of Mars.";

Add userPrompt to the history with the addUserMessage function. Generate output using the generate function.

history = addUserMessage(history,userPrompt);
[~,completeOutput] = generate(model,history);

If the model detects one or more tool calls, then the generate function returns information about the names and any input arguments in the tool_calls field of the completeOutput output structure.

LLMs can hallucinate tool names and arguments. Therefore, validate the first function call against the tool specifications in fArray.

toolRequest = completeOutput.tool_calls(1).function;
validateToolCall(toolRequest,fArray);

Execute the first function call using the callTool function. To add the tool call result to the history, use the addToolCallToHistory function, defined at the bottom of this example.

toolOutput = callTool(client,toolRequest);
history = addToolCallToHistory(history,completeOutput,toolOutput);
prettyPrintJSON(toolOutput)
{
  "naifId": 499,
  "centerOfMotionId": 10,
  "barycenterOfMotionId": 4,
  "name": "MARS",
  "radii": {
    "x": 3.39619E+6,
    "y": 3.39619E+6,
    "z": 3.3762E+6
  },
  "gm": 4.2828373620699086E+13,
  "frameName": "IAU_MARS",
  "frameId": 10014,
  "j2": "NaN",
  "j3": "NaN",
  "j4": "NaN"
}

To generate a natural language response with the tool call result, use the generate function with the updated history.

generatedText = generate(model,history)
Mars is a celestial body with the following properties:
- NAIF ID: 499
- Center of Motion ID: 10
- Barycenter of Motion ID: 4
- Radii: Approximately 3,396.19 km along the x and y axes, and 3,376.2 km along the z axis
- Standard gravitational parameter (GM): 4.2828373620699e+13 m^3/s^2
- Reference Frame Name: IAU_MARS
- Reference Frame ID: 10014

If you want more specific information or additional properties, please let me know!

You can ask follow up questions to the model about the tool call result. For example, ask the model about the gravitational parameter of Mars.

userFollowUpPrompt = "How would these properties affect someone standing on Mars?";
history = addUserMessage(history,userFollowUpPrompt);
generatedText = generate(model,history)
generatedText = 
    Standing on Mars would feel very different from Earth. Mars' weaker gravity 
    (about 38% of Earth's) means you'd weigh much less, making movement easier but 
    less stable.

Helper Functions

LLMs can hallucinate tool calls or make errors about the arguments that the tools need. Therefore, validate the tool name and arguments against fArray, the list of openAIFunction objects containing the tool specifications.

function validateToolCall(toolRequest,fArray)
% Validate tool name
toolName = toolRequest.name;
toolIndex = find(strcmp(toolName,[fArray.FunctionName]),1);
assert(~isempty(toolIndex),"Invalid tool name '%s'.",toolName)

% Validate arguments
try
    args = jsondecode(toolRequest.arguments);
catch
    error("Model returned invalid JSON syntax for arguments of tool '%s'.",toolName);
end
f = fArray(toolIndex);
argsRequired = string(fieldnames(f.Parameters));
assert(all(isfield(args,argsRequired)),"Invalid tool parameters '%s'.",strjoin(fieldnames(args),","));
end
function history = addToolCallToHistory(history,completeOutput,toolOutput)
history = addResponseMessage(history,completeOutput);
history = addToolMessage(history,completeOutput.tool_calls.id,completeOutput.tool_calls.function.name,toolOutput);
end
function prettyPrintJSON(output)
disp(jsonencode( ...
    jsondecode(output), ...
    PrettyPrint=true))
end

Functions

mcpHTTPClient

client = mcpHTTPClient(endpoint) returns an MCP client based on the MCP server URL endpoint.

The mcpHTTPClient object stores the tools associated with the MCP server in the ServerTools property, specified as a cell array of structs. Each struct contains information about one tool, including the tool name and arguments.

callTool

result = callTool(client,toolName,argumentName1=x1,argumentName2=x2,...) calls a tool with name toolName with input argument argumentName1 specified as x1, etc.

result = callTool(client,toolRequest) calls a tool request toolRequest returned by an LLM. For example, you can specify toolRequest as the completeOutput.tool_calls.function output of the generate (Large Language Models (LLMs) with MATLAB) function.

When using the MATLAB HTTP MCP Client, you should thoroughly review and validate all tool calls before you run them. Always keep a human in the loop for important actions and only proceed once you’re confident the call will do exactly what you expect. For more information, see information on trust, safety and security with MCP and MCP security considerations.

Copyright 2025 The MathWorks, Inc.

About

An MCP client in pure MATLAB code

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages