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;
      }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. Addedv1.0.0

TDQS

C2.9/5.0
Behavior2/5

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

With no annotations, the description carries the full behavioral disclosure burden. It states the basic action and result but does not disclose execution side effects, persistence between calls, result format, or how saveScript and scriptPath affect behavior. This is thin for an arbitrary code-execution tool.

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

Conciseness4/5

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

The description is one compact sentence with no filler and the primary action is front-loaded. It is concise, though arguably too terse given the missing behavioral context.

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

Completeness3/5

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

For a tool with one required parameter and fully documented optional parameters, the schema plus description are mostly usable. However, with no output schema and no annotations, the vague phrase 'return the results' leaves the return format undefined, and no execution-environment context is given.

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?

Schema description coverage is 100%, so each parameter is already documented in the schema. The description adds no additional meaning for 'code', 'saveScript', or 'scriptPath', so the baseline 3 applies.

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 uses a specific verb ('Execute'), identifies the target ('MATLAB code'), and notes the outcome ('return the results'). It is clear on its face but does not explicitly distinguish this tool from its sibling generate_matlab_code, so it stops short of a 5.

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?

No guidance is given about when to choose execute_matlab_code over generate_matlab_code, and there are no exclusions or prerequisites. The intended use must be inferred from the tool name and basic semantics rather than from explicit direction.

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

Deploy Server

Other Tools