# 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:
- Create MCP clients to connect to streamable HTTP servers from MATLAB.
- Call external tools.
- Use external tools with the [Large Language Models (LLMs) with MATLAB](https://www.mathworks.com/matlabcentral/fileexchange/163796-large-language-models-llms-with-matlab) add\-on.


[Setup](#setup)
- [Use MATLAB Online](#use-matlab-online)
- [Install Using Add-On Explorer](#install-using-add-on-explorer)

[Examples](#examples)
- [Create MCP Client](#create-mcp-client)
- [Automatically Call External Tool Using LLM](#automatically-call-external-tool-using-llm)

[Functions](#functions)
- [mcpHTTPClient](#mcphttpclient)
- [callTool](#calltool)

<a id="setup"></a>
# 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](https://www.mathworks.com/matlabcentral/fileexchange/163796-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](https://www.mathworks.com/images/responsive/global/open-in-matlab-online.svg)](https://matlab.mathworks.com/open/github/v1?repo=matlab-deep-learning/mcpHTTPClient)


## 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**.

<a id="examples"></a>
# Examples

<a id="create-mcp-client"></a>
## 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](https://github.com/IO-Aerospace-software-engineering/mcp-server) to access aerospace and astrodynamics tools.

```matlab
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.

```matlab
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.

```matlab
toolGetCelestialBodyProperties = serverTools{23}
```

```matlabTextOutput
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.

```matlab
toolGetCelestialBodyProperties.inputSchema.properties
```

```matlabTextOutput
ans = struct with fields:
    celestialBodyName: [1x1 struct]

```

```matlab
toolGetCelestialBodyProperties.inputSchema.properties.celestialBodyName
```

```matlabTextOutput
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`.

```matlab
toolName = toolGetCelestialBodyProperties.name;
toolOutput = callTool(client,toolName,celestialBodyName="Mars");
prettyPrintJSON(toolOutput)
```

```matlabTextOutput
{
  "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"
}
```

<a id="automatically-call-external-tool-using-llm"></a>
## 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](https://www.mathworks.com/matlabcentral/fileexchange/163796-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](https://github.com/matlab-deep-learning/llms-with-matlab/blob/main/doc/OpenAI.md).


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](https://github.com/IO-Aerospace-software-engineering/mcp-server) to access aerospace and astrodynamics tools.

```matlab
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.

```matlab
serverTools = client.ServerTools;
```

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

```matlab
toolGetCelestialBodyProperties = client.ServerTools{23}
```

```matlabTextOutput
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.

```matlab
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.

```matlab
history = messageHistory;
```

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

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

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

```matlab
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`.

```matlab
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.

```matlab
toolOutput = callTool(client,toolRequest);
history = addToolCallToHistory(history,completeOutput,toolOutput);
prettyPrintJSON(toolOutput)
```

```matlabTextOutput
{
  "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.
```matlab
generatedText = generate(model,history)
```

```matlabTextOutput
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.

```matlab
userFollowUpPrompt = "How would these properties affect someone standing on Mars?";
history = addUserMessage(history,userFollowUpPrompt);
generatedText = generate(model,history)
```

```matlabTextOutput
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.

```matlab
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
```

```matlab
function history = addToolCallToHistory(history,completeOutput,toolOutput)
history = addResponseMessage(history,completeOutput);
history = addToolMessage(history,completeOutput.tool_calls.id,completeOutput.tool_calls.function.name,toolOutput);
end
```

```matlab
function prettyPrintJSON(output)
disp(jsonencode( ...
    jsondecode(output), ...
    PrettyPrint=true))
end
```

<a id="functions"></a>
# Functions

<a id="mcphttpclient"></a>
## 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.

<a id="calltool"></a>
## 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`](https://github.com/matlab-deep-learning/llms-with-matlab/blob/main//doc/functions/generate.md) (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](https://modelcontextprotocol.io/specification/2025-06-18/server/tools) and [MCP security considerations](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#security-considerations).

*Copyright 2025 The MathWorks, Inc.*

