Skip to main content
Glama
tsmztech

Salesforce MCP Server

salesforce_execute_anonymous

Execute anonymous Apex code in Salesforce to test scripts, debug issues, or perform data operations when specific tools are unavailable.

Instructions

Execute anonymous Apex code in Salesforce.

Examples:

  1. Execute simple Apex code: { "apexCode": "System.debug('Hello World');" }

  2. Execute Apex code with variables: { "apexCode": "List accounts = [SELECT Id, Name FROM Account LIMIT 5]; for(Account a : accounts) { System.debug(a.Name); }" }

  3. Execute Apex with debug logs: { "apexCode": "System.debug(LoggingLevel.INFO, 'Processing accounts...'); List accounts = [SELECT Id FROM Account LIMIT 10]; System.debug(LoggingLevel.INFO, 'Found ' + accounts.size() + ' accounts');", "logLevel": "DEBUG" }

Notes:

  • The apexCode parameter is required and must contain valid Apex code

  • The code is executed in an anonymous context and does not persist

  • The logLevel parameter is optional (defaults to 'DEBUG')

  • Execution results include compilation success/failure, execution success/failure, and debug logs

  • For security reasons, some operations may be restricted based on user permissions

  • This tool can be used for data operations or updates when there are no other specific tools available

  • When users request data queries or updates that aren't directly supported by other tools, this tool can be used if the operation is achievable using Apex code

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
apexCodeYesApex code to execute anonymously
logLevelNoLog level for debug logs (optional, defaults to DEBUG)

Implementation Reference

  • The handleExecuteAnonymous function that executes the core tool logic: validates inputs, runs conn.tooling.executeAnonymous, processes results (compilation, execution, exceptions), retrieves recent ApexLog debug logs, and formats a comprehensive text response.
    export async function handleExecuteAnonymous(conn: any, args: ExecuteAnonymousArgs) {
      try {
        // Validate inputs
        if (!args.apexCode || args.apexCode.trim() === '') {
          throw new Error('apexCode is required and cannot be empty');
        }
        
        console.error(`Executing anonymous Apex code`);
        
        // Set default log level if not provided
        const logLevel = args.logLevel || 'DEBUG';
        
        // Execute the anonymous Apex code
        const result = await conn.tooling.executeAnonymous(args.apexCode);
        
        // Format the response
        let responseText = '';
        
        // Add compilation and execution status
        if (result.compiled) {
          responseText += `**Compilation:** Success\n`;
        } else {
          responseText += `**Compilation:** Failed\n`;
          responseText += `**Line:** ${result.line}\n`;
          responseText += `**Column:** ${result.column}\n`;
          responseText += `**Error:** ${result.compileProblem}\n\n`;
        }
        
        if (result.compiled && result.success) {
          responseText += `**Execution:** Success\n`;
        } else if (result.compiled) {
          responseText += `**Execution:** Failed\n`;
          responseText += `**Error:** ${result.exceptionMessage}\n`;
          if (result.exceptionStackTrace) {
            responseText += `**Stack Trace:**\n\`\`\`\n${result.exceptionStackTrace}\n\`\`\`\n\n`;
          }
        }
        
        // Get debug logs if available
        if (result.compiled) {
          try {
            // Query for the most recent debug log
            const logs = await conn.query(`
              SELECT Id, LogUserId, Operation, Application, Status, LogLength, LastModifiedDate, Request
              FROM ApexLog 
              ORDER BY LastModifiedDate DESC 
              LIMIT 1
            `);
            
            if (logs.records.length > 0) {
              const logId = logs.records[0].Id;
              
              // Retrieve the log body
              const logBody = await conn.tooling.request({
                method: 'GET',
                url: `${conn.instanceUrl}/services/data/v58.0/tooling/sobjects/ApexLog/${logId}/Body`
              });
              
              responseText += `\n**Debug Log:**\n\`\`\`\n${logBody}\n\`\`\``;
            } else {
              responseText += `\n**Debug Log:** No logs available. Ensure debug logs are enabled for your user.`;
            }
          } catch (logError) {
            responseText += `\n**Debug Log:** Unable to retrieve debug logs: ${logError instanceof Error ? logError.message : String(logError)}`;
          }
        }
        
        return {
          content: [{ 
            type: "text", 
            text: responseText
          }]
        };
      } catch (error) {
        console.error('Error executing anonymous Apex:', error);
        return {
          content: [{ 
            type: "text", 
            text: `Error executing anonymous Apex: ${error instanceof Error ? error.message : String(error)}` 
          }],
          isError: true,
        };
      }
    }
  • Tool definition including name, detailed description with examples, and inputSchema specifying required 'apexCode' string and optional 'logLevel' enum.
    export const EXECUTE_ANONYMOUS: Tool = {
      name: "salesforce_execute_anonymous",
      description: `Execute anonymous Apex code in Salesforce.
      
    Examples:
    1. Execute simple Apex code:
       {
         "apexCode": "System.debug('Hello World');"
       }
    
    2. Execute Apex code with variables:
       {
         "apexCode": "List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5]; for(Account a : accounts) { System.debug(a.Name); }"
       }
    
    3. Execute Apex with debug logs:
       {
         "apexCode": "System.debug(LoggingLevel.INFO, 'Processing accounts...'); List<Account> accounts = [SELECT Id FROM Account LIMIT 10]; System.debug(LoggingLevel.INFO, 'Found ' + accounts.size() + ' accounts');",
         "logLevel": "DEBUG"
       }
    
    Notes:
    - The apexCode parameter is required and must contain valid Apex code
    - The code is executed in an anonymous context and does not persist
    - The logLevel parameter is optional (defaults to 'DEBUG')
    - Execution results include compilation success/failure, execution success/failure, and debug logs
    - For security reasons, some operations may be restricted based on user permissions
    - This tool can be used for data operations or updates when there are no other specific tools available
    - When users request data queries or updates that aren't directly supported by other tools, this tool can be used if the operation is achievable using Apex code
    `,
      inputSchema: {
        type: "object",
        properties: {
          apexCode: {
            type: "string",
            description: "Apex code to execute anonymously"
          },
          logLevel: {
            type: "string",
            enum: ["NONE", "ERROR", "WARN", "INFO", "DEBUG", "FINE", "FINER", "FINEST"],
            description: "Log level for debug logs (optional, defaults to DEBUG)"
          }
        },
        required: ["apexCode"]
      }
    };
  • src/index.ts:45-63 (registration)
    Registration of the tool in the ListToolsRequestSchema handler by including EXECUTE_ANONYMOUS in the exported tools list.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        SEARCH_OBJECTS, 
        DESCRIBE_OBJECT, 
        QUERY_RECORDS, 
        AGGREGATE_QUERY,
        DML_RECORDS,
        MANAGE_OBJECT,
        MANAGE_FIELD,
        MANAGE_FIELD_PERMISSIONS,
        SEARCH_ALL,
        READ_APEX,
        WRITE_APEX,
        READ_APEX_TRIGGER,
        WRITE_APEX_TRIGGER,
        EXECUTE_ANONYMOUS,
        MANAGE_DEBUG_LOGS
      ],
    }));
  • src/index.ts:288-301 (registration)
    Registration in the CallToolRequestSchema switch statement: handles 'salesforce_execute_anonymous' case by validating args and invoking the handler.
    case "salesforce_execute_anonymous": {
      const executeArgs = args as Record<string, unknown>;
      if (!executeArgs.apexCode) {
        throw new Error('apexCode is required for executing anonymous Apex');
      }
      
      // Type check and conversion
      const validatedArgs: ExecuteAnonymousArgs = {
        apexCode: executeArgs.apexCode as string,
        logLevel: executeArgs.logLevel as 'NONE' | 'ERROR' | 'WARN' | 'INFO' | 'DEBUG' | 'FINE' | 'FINER' | 'FINEST' | undefined
      };
    
      return await handleExecuteAnonymous(conn, validatedArgs);
    }
  • src/index.ts:25-25 (registration)
    Import of the tool definition, handler function, and types from the executeAnonymous module.
    import { EXECUTE_ANONYMOUS, handleExecuteAnonymous, ExecuteAnonymousArgs } from "./tools/executeAnonymous.js";
Behavior4/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 effectively describes key behaviors: the code 'does not persist,' execution results include 'compilation success/failure, execution success/failure, and debug logs,' and 'some operations may be restricted based on user permissions.' However, it lacks details on rate limits, timeouts, or specific security restrictions.

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

Conciseness3/5

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

The description is front-loaded with the core purpose, but includes lengthy examples and notes that could be streamlined. While informative, some sentences (e.g., repeating parameter details) don't earn their place given the comprehensive schema. The structure is clear but could be more concise.

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

Completeness4/5

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

Given the tool's complexity (executing arbitrary code) and lack of annotations and output schema, the description does a good job covering essential context: purpose, usage guidelines, behavioral traits, and parameter examples. However, it could better explain the output format (e.g., what 'execution results' include) since there's no output schema.

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 the schema already documents both parameters thoroughly. The description adds minimal value beyond the schema, mainly through examples that illustrate parameter usage. It confirms apexCode is 'required' and logLevel 'defaults to DEBUG,' but these details are already in the schema.

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

Purpose5/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: 'Execute anonymous Apex code in Salesforce.' It specifies the verb ('Execute'), resource ('anonymous Apex code'), and context ('in Salesforce'), distinguishing it from sibling tools like salesforce_query_records or salesforce_dml_records that handle specific operations.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use this tool: 'When users request data queries or updates that aren't directly supported by other tools, this tool can be used if the operation is achievable using Apex code.' It also notes this is for operations 'when there are no other specific tools available,' helping differentiate from more specialized siblings.

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/tsmztech/mcp-server-salesforce'

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