bio_img_matlab

The MATLAB Blog

Practical Advice for People on the Leading Edge

Exploring the MATLAB Model Context Protocol (MCP) Core Server with Claude Desktop

Over at the Artificial Intelligence blog my colleagues, Yann Debray and Akshay Paul, have announced the release of the MATLAB MCP Core Server, MathWorks' first MCP Server.
Introduced last November by Anthropic, MCP is an open standard for AI applications to connect to external tools and data. Some people refer to it as the 'USB-C for AI' because it is a standard way of connecting AI models to other things. There has been a lot of hype around it, some of which may be justified; and even more articles and tutorials that go into great depth about how everything works. For us, however, the core principle is very simple...

MATLAB MCP Core Server allows AI models to use MATLAB

In one sense, MCP doesn't provide us with anything fundamentally new. Early last month, for example, I showed how to configure Ollama to call tools defined in MATLAB. I could have done similar articles for ChatGPT and a range of other AI systems but I would have needed to tweak the code a little in each case. With MCP, I would only need to show you how to define a tool once.
Last Friday, we released one MCP server for MATLAB but, as you saw from Yann's blogpost, it already works with many MCP Clients such as VSCode, Claude Desktop or Gemini CLI. Indeed, it should work with any MCP client with a little configuration.
The practical upshot of this is that now, you can plug MATLAB into any AI system using MATLAB MCP Core Server. So...I started by plugging it into Claude Desktop.

Baby steps with Claude Desktop and the first hallucination of the day

Installation details are in the project's README.md. If everything has gone well, when you launch Claude Desktop it will also launch a copy of MATLAB. You will also be able to see the available tools via the Search and Tools button on Claude Desktop
As you can see, the server provides 5 tools to the AI. These are
  • Detect MATLAB Toolboxes: Reports which MATLAB toolboxes you have installed
  • Check MATLAB Code: Uses the checkcode function in MATLAB to check MATLAB code for possible issues
  • Evaluate MATLAB Code: Runs MATLAB code sent via a string
  • Run MATLAB File: Runs an .m file
  • Run MATLAB Test file: Runs a MATLAB Test file
I've been using the Detect MATLAB Toolboxes tool as a simple test to see if everything is working OK. Since it's the simplest connection between AI and MATLAB, if this tool doesn't work, none of the others are likely to either!
I ask Claude: "What MATLAB toolboxes do I have installed?"
The AI calls the detect_matlab_toolboxes tool. This calls the ver command on my local copy of MATLAB and returns the result to the AI.
In turn, the AI responds a nicely formatted result, grouping the toolboxes into categories it came up with itself. I don't fully agree with the categorization but that's another story.
Looks reasonable apart from the fact that I know that I have 99 toolboxes installed and not 102! I ask the AI to print every toolbox, one line each and numbering each line. It correctly does so, without missing anything. I'll spare you from the boredom of actually seeing that though.
Then I ask:
Claude's statement, that I had 102 toolboxes installed, was a classic example of an hallucination and hallucinations are a fundamental limitation of LLM based technologies. We can engineer around them but they'll always be there. I go into more depth about this topic in my article on Giving LLMs new capabilities: Ollama tool calling in MATLAB where I use hallucinations as the motivation for developing tools to assist the AI in areas where we know it is weak.
The detect_matlab_toolboxes tool worked perfectly. It was Claude itself that hallucinated a little on the result and you should expect this sometimes. After all, at the end of every chat on Claude Desktop right now there is a disclaimer
Some people like to point out mistakes like this as justification for not using LLM-based AI technologies. I, however, prefer to simply be mindful and do what Claude suggests - double check responses.
Knowing that LLMs can't always count well, if I really cared about the number of toolboxes I have installed, I could use MATLAB to count them. Thanks to the LLM, however, I don't need to write the code myself.
I ask Claude: Find out what MATLAB toolboxes I have installed and use MATLAB to count them.
Here, it has used two tools from MATLAB MCP Core Server: detect_matlab_toolboxes and evaluate_matlab_code. I can expand either one to see what the result of that tool call was. Here are the first parts of both
Scrolling down to the bottom of the evaluate_matlab_code call, I can also see the response from MATLAB which is sent back to the AI.
All of the code that the AI wrote was there too. For reference, here is what Claude came up with
v = ver;
 
% Count the number of installed products (MATLAB + toolboxes)
total_count = length(v);
 
% Display the count
fprintf('Total number of MATLAB products installed: %d', total_count);
 
% Also show MATLAB and Simulink separately if present
matlab_idx = find(strcmp({v.Name}, 'MATLAB'));
simulink_idx = find(strcmp({v.Name}, 'Simulink'));
 
if ~isempty(matlab_idx)
fprintf('MATLAB Version: %s', v(matlab_idx).Version);
end
 
if ~isempty(simulink_idx)
fprintf('Simulink Version: %s', v(simulink_idx).Version);
end
 
% Count toolboxes (excluding MATLAB and Simulink base products)
toolbox_count = total_count - length(matlab_idx) - length(simulink_idx);
fprintf('Number of additional toolboxes/blocksets: %d', toolbox_count);
Even this simple example demonstrates several important concepts. The MCP server allows Claude to run whatever MATLAB code it writes on my local machine. My local MATLAB sends the results of any code execution back to Claude which can then use it for further reasoning.

File system woes and workarounds

When I first started using the MATLAB MCP Core Server with Claude Desktop, I had a lot of file system troubles. In short, Claude kept trying to do things like writing an .m file to its internal file system at /home/claude/ and try to get MATLAB to run it. Of course, MATLAB was on my local machine and so couldn't see Claude's file system. When this failed, it would try over and over again in different locations, or trying to launch MATLAB in different ways but never actually getting anywhere.
Speaking to other Claude desktop users at MathWorks, some people had similar problems to me while others had no problems at all. As such, your mileage may vary.
I eventually resolved this by following the instructions on Connect to local MCP servers (MCP) to install Node.js and the Filesystem MCP Server. My Claude Desktop configuration file, claude_desktop_config.json, now contains the configuration for both the MATLAB MCP Core Server as well as the Claude Filesystem Server and looks like this
{
"mcpServers": {
"matlab-mcp": {
"command": "C:\\Users\\walki\\Downloads\\matlab-mcp-core-server.exe",
"args": [
"--matlab-root=C:\\Program Files\\MATLAB\\R2025b",
"--initial-working-folder=C:\\Users\\walki\\Downloads\\work"
],
"env": {}
},
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"C:\\Users\\walki\\Downloads\\work"
]
}
}
}
I created the folder C:\Users\walki\Downloads\work on my local machine for the purposes of working with Claude desktop. In any prompts I made, I explicitly mentioned this folder and things worked a lot better.
Enough of the plumbing. Let's do something more interesting with this set up

Find the best polynomial for this dataset

I created a dataset from a 5th order polynomial with some random noise thrown in. For the record, this is how I generated it
x = linspace(-4, 4, 60);
y_true = 0.05*x.^5 - 0.8*x.^3 + 2*x;
noise = 0.5 * randn(size(x));
y_noisy = y_true + noise;
Claude isn't going to know that though. All Claude is going to get it is a .csv file containing two columns: x and y_noisy along with the following prompt
On my local machine, there is a file called polynomial_data.csv inside the folder C:\Users\walki\Downloads\work
In that folder, create and run a MATLAB script that satisfies the following
- Load this data into MATLAB and plot it. Do not join the points.
- The data is from a polynomial with added noise. Create a process that discovers which order of polynomial fits the data best.
Use several different techniques to try to determine the best one.
- When making multiple plots, use tiled plots instead of subplot.
- Finish with a plot that combines the original data along with the best fit polynomial
Notice that some aspects of this prompt are rather specific. The note about preferring tiled plots over subplots, for example and explicitly asking not to join the data points. That's because this isn't my first rodeo! My first prompt was much simpler than this and didn't give great results. I've iterated several times since then to show you a better result. Let's see how it does in the following video
I've sped up the parts of the video where Claude was writing code because there isn't much to look at. These are clearly marked. Everything else in the video is in real-time. The actual clock time for the entire process was around 3 minutes. In that time, without any additional input from me,
  • Claude took a look at the data file on my local machine, wrote MATLAB code to my specifications and saved it on my machine.
  • It ran the code using my local MATLAB. The code failed and Claude analyzed the error message.
  • Claude had used the function crossvalind which is in Bioinformatics toolbox. I didn't have this installed, hence the error.
  • Claude rewrote the MATLAB script so that it didn't use crossvalind.
  • It successfully ran the new script and generated a Markdown report along with the result and a bunch of plots.
The script correctly determined that a 5th order polynomial was the best fit and it reported the following when I ran it manually
=== BEST POLYNOMIAL ORDER BY DIFFERENT CRITERIA ===
RMSE: Order 10
Adjusted R²: Order 5
AIC: Order 5
BIC: Order 5
Cross-Validation: Order 7
 
*** CONSENSUS BEST ORDER: 5 ***
 
Analysis complete! Best polynomial order: 5
Polynomial coefficients (highest to lowest degree):
0.0524 0.0010 -0.8361 -0.0194 2.0813 0.0502
I checked those parameters using MATLAB's curve fitting toolbox and they are correct.
I didn't ask Claude to use cross-validation or measures such as Bayesian Information Criterion (BIC) -- It came up with those itself. I've vaguely heard of BIC but not sure if its relevant here -- that's one for my research list. I also don't know if it's implemented cross-validation correctly since I haven't taken a closer look yet.

Next steps for me

At this stage, I have a choice. I could put the code onto GitHub and start hand-editing it. At some point, it will be in a state I'm willing to share with others for code review, Alternatively, I could work on the prompt a little more after further research. For example, do I want to install Bioinformatics toolbox and insist that it uses crossvalind or do I want to insist that it doesn't? Other things I might add to the prompt include
  • I like that it produced a Markdown report file -- something I hadn't thought to ask for. However, it didn't include any of the plots. Perhaps I should add something about that to the prompt?
  • I'll have a chat with an expert (or ask blog readers!) if any of the methods it used are a bad idea. If so, I'll make sure to exclude them.
  • I might point Claude to the MATLAB Coding Guidelines and ask it to adhere to them.
  • If you watch the video, you'll see that the legend on one of the plots looks terrible. Can I improve this via prompting?
  • The color choice for 'Original Data' could be a little better given that I'm using Dark Mode! I should be more specific about how I want the plots to look
Interestingly for me, I find myself leaning towards throwing this code away and spending more time on the prompt and researching the problem further before I start hand editing the code. What would you suggest I add to this prompt?
Whatever I decide, I've already learned a lot getting this far...and I've only used 2 out of the 5 tools provided by the MATLAB MCP Core Server.

Next steps for you

Download the MATLAB MCP Core Server and integrate it with the MCP-compatible AI tool of your choice. If you have any problems or suggestions, please open an issue on the project's GitHub repository.
I'm looking forward to seeing what you all do with this new technology.
|
  • print

댓글

댓글을 남기려면 링크 를 클릭하여 MathWorks 계정에 로그인하거나 계정을 새로 만드십시오.