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;
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool executes code and returns results, but lacks critical details such as execution environment (e.g., sandboxed, local MATLAB instance), safety considerations (e.g., code injection risks), performance traits (e.g., timeout limits), or error handling. This leaves significant gaps for an agent to understand how the tool behaves beyond its basic function.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise and front-loaded, consisting of a single sentence that directly states the tool's core function. There is no wasted language or redundancy, making it efficient for an agent to parse. Every word earns its place by conveying essential information without unnecessary elaboration.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of executing code (a potentially risky operation) and the lack of annotations and output schema, the description is insufficiently complete. It doesn't address critical context like execution safety, result format, error conditions, or dependencies. For a tool with no structured safety or output information, the description should provide more guidance to help an agent use it effectively and safely.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, clearly documenting all three parameters. The description adds no additional parameter semantics beyond what the schema provides, such as code syntax requirements or path formatting. However, with high schema coverage, the baseline score of 3 is appropriate, as the schema adequately handles parameter documentation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Execute') and resource ('MATLAB code'), making it immediately understandable. It distinguishes from the sibling tool 'generate_matlab_code' by focusing on execution rather than generation. However, it doesn't specify what kind of results are returned or the execution environment, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention the sibling tool 'generate_matlab_code' or any other potential tools, nor does it specify prerequisites, execution context, or limitations. The agent must infer usage based solely on the tool name and description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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