Skip to main content
Glama
simonl77

Salesforce MCP Server

by simonl77

salesforce_execute_anonymous

Execute anonymous Apex code in Salesforce to run data operations, queries, or updates when specific tools are unavailable. Supports debug logging and temporary execution without persistence.

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 handler function that executes anonymous Apex code, handles compilation/execution results, retrieves debug logs, and formats the response for the tool.
    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,
        };
      }
    }
  • The Tool object definition including the name 'salesforce_execute_anonymous', description, and inputSchema for parameter validation.
    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:288-301 (registration)
    Registration in the main tool dispatcher switch statement: validates arguments and invokes the handleExecuteAnonymous 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:45-63 (registration)
    Registration of the tool in the ListToolsRequest handler by including EXECUTE_ANONYMOUS in the tools array.
    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
      ],
    }));
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing: 'The code is executed in an anonymous context and does not persist' (transient nature), 'Execution results include compilation success/failure, execution success/failure, and debug logs' (return format), and 'For security reasons, some operations may be restricted based on user permissions' (security constraints). It doesn't mention rate limits or specific destructive behaviors, but covers key operational aspects.

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 appropriately structured with purpose statement, examples, and notes sections. While comprehensive, some sentences could be more concise (e.g., the two usage guideline sentences are somewhat repetitive). Overall, it's well-organized and most content earns its place.

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?

For a powerful code execution tool with no annotations and no output schema, the description does well by explaining the anonymous context, persistence behavior, security restrictions, and when to use versus alternatives. It could benefit from more detail about return structure since there's no output schema, but it mentions key result components. Given the complexity and lack of structured metadata, it's quite complete.

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 provides examples showing parameter usage but doesn't add significant semantic meaning beyond what's in the schema descriptions. The baseline of 3 is appropriate when the schema does the heavy lifting.

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 explicitly states 'Execute anonymous Apex code in Salesforce' - a specific verb ('Execute') and resource ('anonymous Apex code') with clear scope ('in Salesforce'). It distinguishes from siblings like salesforce_query_records (for queries) and salesforce_dml_records (for data operations) by focusing on arbitrary code execution rather than 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: 'This tool can be used for data operations or updates when there are no other specific tools available' and '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.' This clearly defines when to use this tool versus the many sibling tools available.

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

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