Skip to main content
Glama
tsmztech

Salesforce MCP Server

salesforce_write_apex

Create or update Apex classes in Salesforce to implement custom business logic and automate processes within the platform.

Instructions

Create or update Apex classes in Salesforce.

Examples:

  1. Create a new Apex class: { "operation": "create", "className": "AccountService", "apiVersion": "58.0", "body": "public class AccountService { public static void updateAccounts() { /* implementation */ } }" }

  2. Update an existing Apex class: { "operation": "update", "className": "AccountService", "body": "public class AccountService { public static void updateAccounts() { /* updated implementation */ } }" }

Notes:

  • The operation must be either 'create' or 'update'

  • For 'create' operations, className and body are required

  • For 'update' operations, className and body are required

  • apiVersion is optional for 'create' (defaults to the latest version)

  • The body must be valid Apex code

  • The className in the body must match the className parameter

  • Status information is returned after successful operations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
operationYesWhether to create a new class or update an existing one
classNameYesName of the Apex class to create or update
apiVersionNoAPI version for the Apex class (e.g., '58.0')
bodyYesFull body of the Apex class

Implementation Reference

  • The `handleWriteApex` function implements the core logic for creating or updating Apex classes in Salesforce using the Tooling API. It validates inputs, checks for existing classes, performs CRUD operations, and returns formatted success or error responses.
    export async function handleWriteApex(conn: any, args: WriteApexArgs) {
      try {
        // Validate inputs
        if (!args.className) {
          throw new Error('className is required');
        }
        
        if (!args.body) {
          throw new Error('body is required');
        }
        
        // Check if the class name in the body matches the provided className
        const classNameRegex = new RegExp(`\\b(class|interface|enum)\\s+${args.className}\\b`);
        if (!classNameRegex.test(args.body)) {
          throw new Error(`The class name in the body must match the provided className: ${args.className}`);
        }
        
        // Handle create operation
        if (args.operation === 'create') {
          console.error(`Creating new Apex class: ${args.className}`);
          
          // Check if class already exists
          const existingClass = await conn.query(`
            SELECT Id FROM ApexClass WHERE Name = '${args.className}'
          `);
          
          if (existingClass.records.length > 0) {
            throw new Error(`Apex class with name '${args.className}' already exists. Use 'update' operation instead.`);
          }
          
          // Create the new class using the Tooling API
          const createResult = await conn.tooling.sobject('ApexClass').create({
            Name: args.className,
            Body: args.body,
            ApiVersion: args.apiVersion || '58.0', // Default to latest if not specified
            Status: 'Active'
          });
          
          if (!createResult.success) {
            throw new Error(`Failed to create Apex class: ${createResult.errors.join(', ')}`);
          }
          
          return {
            content: [{ 
              type: "text", 
              text: `Successfully created Apex class: ${args.className}\n\n` +
                    `**ID:** ${createResult.id}\n` +
                    `**API Version:** ${args.apiVersion || '58.0'}\n` +
                    `**Status:** Active`
            }]
          };
        } 
        // Handle update operation
        else if (args.operation === 'update') {
          console.error(`Updating Apex class: ${args.className}`);
          
          // Find the existing class
          const existingClass = await conn.query(`
            SELECT Id FROM ApexClass WHERE Name = '${args.className}'
          `);
          
          if (existingClass.records.length === 0) {
            throw new Error(`No Apex class found with name: ${args.className}. Use 'create' operation instead.`);
          }
          
          const classId = existingClass.records[0].Id;
          
          // Update the class using the Tooling API
          const updateResult = await conn.tooling.sobject('ApexClass').update({
            Id: classId,
            Body: args.body
          });
          
          if (!updateResult.success) {
            throw new Error(`Failed to update Apex class: ${updateResult.errors.join(', ')}`);
          }
          
          // Get the updated class details
          const updatedClass = await conn.query(`
            SELECT Id, Name, ApiVersion, Status, LastModifiedDate
            FROM ApexClass
            WHERE Id = '${classId}'
          `);
          
          const classDetails = updatedClass.records[0];
          
          return {
            content: [{ 
              type: "text", 
              text: `Successfully updated Apex class: ${args.className}\n\n` +
                    `**ID:** ${classId}\n` +
                    `**API Version:** ${classDetails.ApiVersion}\n` +
                    `**Status:** ${classDetails.Status}\n` +
                    `**Last Modified:** ${new Date(classDetails.LastModifiedDate).toLocaleString()}`
            }]
          };
        } else {
          throw new Error(`Invalid operation: ${args.operation}. Must be 'create' or 'update'.`);
        }
      } catch (error) {
        console.error('Error writing Apex class:', error);
        return {
          content: [{ 
            type: "text", 
            text: `Error writing Apex class: ${error instanceof Error ? error.message : String(error)}` 
          }],
          isError: true,
        };
      }
    }
  • The `WRITE_APEX` Tool object defines the name, description, and input schema (including properties like operation, className, apiVersion, body) for the salesforce_write_apex tool.
    export const WRITE_APEX: Tool = {
      name: "salesforce_write_apex",
      description: `Create or update Apex classes in Salesforce.
      
    Examples:
    1. Create a new Apex class:
       {
         "operation": "create",
         "className": "AccountService",
         "apiVersion": "58.0",
         "body": "public class AccountService { public static void updateAccounts() { /* implementation */ } }"
       }
    
    2. Update an existing Apex class:
       {
         "operation": "update",
         "className": "AccountService",
         "body": "public class AccountService { public static void updateAccounts() { /* updated implementation */ } }"
       }
    
    Notes:
    - The operation must be either 'create' or 'update'
    - For 'create' operations, className and body are required
    - For 'update' operations, className and body are required
    - apiVersion is optional for 'create' (defaults to the latest version)
    - The body must be valid Apex code
    - The className in the body must match the className parameter
    - Status information is returned after successful operations`,
      inputSchema: {
        type: "object",
        properties: {
          operation: {
            type: "string",
            enum: ["create", "update"],
            description: "Whether to create a new class or update an existing one"
          },
          className: {
            type: "string",
            description: "Name of the Apex class to create or update"
          },
          apiVersion: {
            type: "string",
            description: "API version for the Apex class (e.g., '58.0')"
          },
          body: {
            type: "string",
            description: "Full body of the Apex class"
          }
        },
        required: ["operation", "className", "body"]
      }
    };
  • src/index.ts:240-255 (registration)
    In the main tool dispatch switch statement, this case handles calls to 'salesforce_write_apex' by validating arguments and delegating to the `handleWriteApex` function.
    case "salesforce_write_apex": {
      const apexArgs = args as Record<string, unknown>;
      if (!apexArgs.operation || !apexArgs.className || !apexArgs.body) {
        throw new Error('operation, className, and body are required for writing Apex');
      }
      
      // Type check and conversion
      const validatedArgs: WriteApexArgs = {
        operation: apexArgs.operation as 'create' | 'update',
        className: apexArgs.className as string,
        apiVersion: apexArgs.apiVersion as string | undefined,
        body: apexArgs.body as string
      };
    
      return await handleWriteApex(conn, validatedArgs);
    }
  • src/index.ts:22-22 (registration)
    Import statement bringing in the WRITE_APEX tool definition, handler function, and type from writeApex.ts.
    import { WRITE_APEX, handleWriteApex, WriteApexArgs } from "./tools/writeApex.js";
  • src/index.ts:57-57 (registration)
    The WRITE_APEX tool is included in the list of available tools returned by ListToolsRequest.
    WRITE_APEX,
Behavior3/5

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

With no annotations provided, the description carries full burden. It discloses that 'Status information is returned after successful operations' and includes important behavioral constraints like 'The body must be valid Apex code' and 'The className in the body must match the className parameter.' However, it doesn't mention authentication requirements, error handling, or whether operations are reversible/destructive.

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 well-structured with clear sections (purpose, examples, notes). Every sentence adds value, though the examples could be more concise. The purpose statement is front-loaded, and the notes section efficiently covers important constraints without redundancy.

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 write operation with no annotations and no output schema, the description provides adequate but incomplete context. It covers the main operations and constraints but lacks information about authentication, error responses, rate limits, or what 'Status information' specifically includes. Given the complexity of writing Apex code in Salesforce, more behavioral context would be helpful.

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 baseline is 3. The description adds some value through examples showing how parameters combine in different operations and clarifying that apiVersion is optional for create operations with a default. However, it doesn't significantly enhance understanding beyond what the schema already provides.

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 'Create or update Apex classes in Salesforce' - a specific verb (create/update) with a specific resource (Apex classes) and platform (Salesforce). It distinguishes from siblings like salesforce_read_apex (read vs write) and salesforce_write_apex_trigger (classes vs triggers).

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

Usage Guidelines4/5

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

The description provides clear context through examples showing when to use create vs update operations. It doesn't explicitly state when NOT to use this tool or mention alternatives like salesforce_execute_anonymous for one-off code execution, but the examples provide practical guidance for the two main use cases.

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