Skip to main content
Glama

execute_matlab_code

Execute MATLAB code to run calculations, analyze data, or perform simulations directly from the MCP server interface.

Instructions

Execute MATLAB code and return the results

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesMATLAB code to execute
saveScriptNoWhether to save the MATLAB script for future reference
scriptPathNoCustom path to save the MATLAB script (optional)

Implementation Reference

  • Core implementation of the MATLAB code execution logic. Sanitizes input code for ASCII compatibility, writes to temporary .m file, executes via MATLAB batch mode using child_process.exec, handles optional script saving, cleans up temp files, and returns stdout/stderr.
    async executeCode(code: string, saveScript: boolean = false, scriptPath?: string): Promise<{ output: string; error?: string; scriptPath?: string }> { try { // Create a temporary .m file with ASCII-only code const tempFile = path.join(this.config.tempDir, `script_${Date.now()}.m`); // Convert any non-ASCII characters to their ASCII equivalents const asciiCode = code .replace(/[']/g, "'") // Replace smart quotes .replace(/["]/g, '"') // Replace smart quotes .replace(/[—]/g, '--') // Replace em dash .replace(/[–]/g, '-') // Replace en dash .replace(/[…]/g, '...'); // Replace ellipsis fs.writeFileSync(tempFile, asciiCode); // If saveScript is true, save the script to the specified path or to the current directory let savedScriptPath: string | undefined; if (saveScript) { const targetPath = scriptPath || path.join(process.cwd(), `matlab_script_${Date.now()}.m`); fs.copyFileSync(tempFile, targetPath); savedScriptPath = targetPath; } // Execute the MATLAB script using a simple command const command = `"${this.config.executablePath}" -batch "run('${tempFile.replace(/\\/g, '/')}'); pause(1);"`; const { stdout, stderr } = await execAsync(command); // Clean up the temporary file if not saving if (!saveScript) { fs.unlinkSync(tempFile); } return { output: stdout, error: stderr || undefined, scriptPath: savedScriptPath }; } catch (error) { console.error("Error executing MATLAB code:", error); return { output: "", error: error instanceof Error ? error.message : String(error) }; } }
  • MCP tool call handler for 'execute_matlab_code'. Validates input parameters, invokes the executeCode method on MatlabHandler, formats the response with output/error and saved script path if applicable, marks as error if failed.
    case 'execute_matlab_code': { const code = String(request.params.arguments?.code || ''); const saveScript = Boolean(request.params.arguments?.saveScript || false); const scriptPath = request.params.arguments?.scriptPath as string | undefined; if (!code) { throw new McpError( ErrorCode.InvalidParams, 'MATLAB code is required' ); } try { const result = await this.matlabHandler.executeCode(code, saveScript, scriptPath); let responseText = result.error ? `Error executing MATLAB code:\n${result.error}` : `MATLAB execution result:\n${result.output}`; if (result.scriptPath) { responseText += `\n\nMATLAB script saved to: ${result.scriptPath}`; } return { content: [ { type: 'text', text: responseText, }, ], isError: !!result.error, }; } catch (error) { return { content: [ { type: 'text', text: `Error executing MATLAB code: ${error instanceof Error ? error.message : String(error)}`, }, ], isError: true, }; } }
  • Input schema definition for the execute_matlab_code tool, registered in the ListToolsRequestSchema handler. Specifies required 'code' parameter and optional saveScript/scriptPath.
    name: 'execute_matlab_code', description: 'Execute MATLAB code and return the results', inputSchema: { type: 'object', properties: { code: { type: 'string', description: 'MATLAB code to execute', }, saveScript: { type: 'boolean', description: 'Whether to save the MATLAB script for future reference', }, scriptPath: { type: 'string', description: 'Custom path to save the MATLAB script (optional)', }, }, required: ['code'], }, },
  • src/index.ts:289-336 (registration)
    Registration of available tools including execute_matlab_code in the MCP server's ListToolsRequestSchema handler.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: 'execute_matlab_code', description: 'Execute MATLAB code and return the results', inputSchema: { type: 'object', properties: { code: { type: 'string', description: 'MATLAB code to execute', }, saveScript: { type: 'boolean', description: 'Whether to save the MATLAB script for future reference', }, scriptPath: { type: 'string', description: 'Custom path to save the MATLAB script (optional)', }, }, required: ['code'], }, }, { name: 'generate_matlab_code', description: 'Generate MATLAB code from a natural language description', inputSchema: { type: 'object', properties: { description: { type: 'string', description: 'Natural language description of what the code should do', }, saveScript: { type: 'boolean', description: 'Whether to save the generated MATLAB script', }, scriptPath: { type: 'string', description: 'Custom path to save the MATLAB script (optional)', }, }, required: ['description'], }, }, ], }));
  • Helper method to check if MATLAB executable is available on the system, used before executing code.
    async checkMatlabAvailability(): Promise<boolean> { try { await execAsync(`"${this.config.executablePath}" -nosplash -nodesktop -r "disp('MATLAB is available'); exit;"`); return true; } catch (error) { console.error("MATLAB is not available:", error); return false; } }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/WilliamCloudQi/matlab-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server