Technical guide

How to integrate Claude with Salesforce

Everything an engineer needs to connect Claude to Salesforce: architecture, the exact build steps with real code, field mapping, the data model, security, monitoring, and the pitfalls we design out.

Platform: Anthropic ClaudeType: AIDirection: Outbound API, two-way via MCPObjects: Any record

Claude connected to Salesforce turns the CRM your team already lives in into an AI workbench: cases summarized on arrival, reply drafts written from full record context, unstructured text classified onto the right fields, and an org you can query in plain English. This page covers the four ways to wire the two together and when each fits.

The four patterns: the Anthropic Messages API called from Apex or Flow for automation inside the org; Claude inside Agentforce through Amazon Bedrock for teams that want frontier AI within the Salesforce trust boundary; the Model Context Protocol (MCP), which lets Claude Desktop and Claude Code read and act on your org from a conversation; and Claude Code with our 141 free Salesforce skills for development work.

For the API pattern we build it the Salesforce-native way: an External plus Named Credential so the API key never lives in code, prompts assembled from record context and stored in Custom Metadata so admins can tune them without a deploy, async callouts that respect governor limits, and every result written back to the record with a full audit trail.

We do not just recommend this stack, we run it: Marc the site chatbot, the CRM Advisor, and the Salesforce Formula Generator on cloudsheer.com are all Claude-powered and in production. Every Claude build is delivered by a senior architect at a fixed price, sandbox-tested, and backed by 30 days of hypercare.

The connection at a glance

Salesforce flow / ApexSource
Named CredentialSalesforce
Claude APIIntegration
RecordsOutcome
Integration facts

How Claude connects to Salesforce

The real connection surface: how it authenticates, what it is built on, the endpoints and events in play, and where the reference docs live.

Connects via
Apex HTTP callouts using a Named Credential + External Credential carrying the x-api-key headerFlow HTTP Callout / External Services against the Anthropic Messages APIClaude models inside Agentforce via Amazon Bedrock (Salesforce-Anthropic partnership)An MCP server exposing SOQL and scoped CRUD tools to Claude Desktop and Claude Code
Package
Custom build (no managed package)
Authentication
Anthropic API key sent in the x-api-key header alongside a required anthropic-version header, stored in a Salesforce External Credential and referenced by a Named Credential (the secret is write-only in Setup)
API type
REST
https://api.anthropic.com/v1

Key endpoints

/v1/messages/v1/models
Free download

Build this with AI agents

Copy the full playbook as a prompt for any coding agent, or install it as a Claude Code skill. Either way your agent builds with our exact approach: the architecture, the Apex code, the field mapping, the rate limits, and the pitfalls to design out. Free, no signup.

Loading the Claude playbook...
Paste into Claude Code, Cursor, or any coding agent
From our builds

What we build for a Claude integration

Anthropic Claude connected to Salesforce for summarization, drafting, and conversational org access - the same models running three production tools on cloudsheer.com.

3client projects
15delivery tasks shipped

Marc, the site chatbot

A Claude-powered pre-sales assistant running in production on cloudsheer.com.

CRM Advisor

A Claude-backed recommendation tool weighing Salesforce, HubSpot, Zoho, and Dynamics.

Salesforce Formula Generator

A four-mode Claude workbench that generates, explains, fixes, and optimizes formulas.

Real components we ship

Anthropic Messages APIApex callouts via Named CredentialMCP server for Claude Desktop / Claude CodeClaude in Agentforce via Amazon Bedrock
Step 0

What you will need

What we confirm on both sides before writing a line of code.

A Salesforce edition with API access (Enterprise, Unlimited, or Developer)
A dedicated sandbox to build and test in
An Anthropic Console account with an API key, or AWS Bedrock access for the Agentforce pattern
System Administrator access on both systems
A dedicated integration user with a minimum-access permission set
Agreement on the objects, prompts, and guardrails the Claude workflows will use
How it works

From trigger to record, end to end

The production runtime flow, with what happens in each system.

  1. 1

    Trigger in Salesforce

    In Salesforce

    A record change or a button starts the Claude action.

    $A record-triggered flow or a Quick Action fires the process.
  2. 2

    Prompt is built

    In Salesforce

    Apex or Flow assembles record context into a prompt.

    $System prompt from Custom Metadata plus record fields, queued async.
  3. 3

    Call Claude

    In transit

    The request posts to the Anthropic Messages API.

    $HTTPS via callout:NamedCredential with x-api-key and anthropic-version headers, no secrets in code.
  4. 4

    Result written back

    In Salesforce

    Claude's response is parsed and lands on the record.

    $Content blocks parsed; summary, draft, and token usage stored for audit.
Architecture

How the data actually flows

Left to right: sources, the integration layer, Salesforce, and the outcomes it drives.

System architecture
SourcesWhere the data starts
Salesforce record
Flow / Apex trigger
Claude Desktop via MCP
Integration layerTransforms and routes
Prompt assembly
Claude Messages API
MCP server (optional)
SalesforceSystem of record
Case, Lead, any record
AI fields
Reports
OutcomesWhat the business gets
Summaries and drafts on the record
Plain-English org queries
No app-switching

Sources feed the integration layer, Salesforce stores the result, and the outcomes ship to the business.

Data model

The objects behind the integration

The Salesforce objects we read and write, what each one is for, and the fields that carry the load.

ObjectPurposeKey fields
Any record (Case, Lead, Opportunity)The record whose context is sent to Claude and where the result lands.Description, AI_Summary__c, AI_Draft__c, Status
AI_Interaction__c (custom)Logs each prompt, response, model, and token count for audit and cost tracking.Prompt__c, Response__c, Model__c, Tokens__c
Error_Log__c (custom)Captures every failed request so anything can be replayed.Payload__c, Status__c, Related_Id__c

Salesforce objects typically in play for Claude

Not object-specific; AI output is written to any sObject (Case, Lead, Opportunity, or custom) plus AI_Interaction__c for audit
Step by step

Build the Claude integration

Every step we follow to ship a production-grade build, with the code that matters.

1

Pick the connection pattern

Claude and Salesforce connect four ways; the right one depends on who consumes the AI.

  • Anthropic Messages API from Apex or Flow: AI inside record automation (summaries, drafts, classification)
  • Claude in Agentforce via Amazon Bedrock: agentic AI within the Salesforce trust boundary, suited to regulated industries
  • MCP server: Claude Desktop and Claude Code query and update the org conversationally
  • Claude Code for development: build Salesforce faster with our 141 free skills
  • A Salesforce edition with API access (Enterprise, Unlimited, or Developer) and a dedicated sandbox track
2

Create the Anthropic API key

The API pattern starts in the Anthropic Console.

  • Create a workspace and API key in the Anthropic Console, and set a monthly spend limit
  • Choose models up front: claude-haiku-4-5 for volume work, claude-sonnet-5 for reasoning-heavy jobs
  • Note the required headers: x-api-key and anthropic-version on every request
3

Store secrets with External and Named Credentials

The modern Salesforce auth stack, so the key never lives in code or metadata.

  • Create an External Credential with a custom header principal carrying x-api-key
  • Create a Named Credential pointing at https://api.anthropic.com and attach the anthropic-version header
  • Grant the External Credential through a permission set, so only the integration user can call out
  • This replaces legacy Remote Site Settings and hard-coded tokens entirely

Pro tip: Named Credentials, not code

Named Credentials keep the secret and endpoint out of your Apex and metadata, so nothing sensitive ships in a deployment or lands in version control.

4

Design prompts as configuration

Prompts change more often than code, so they should not require a deploy.

  • Store system prompts in Custom Metadata records an admin can edit in Setup
  • Define the record fields that feed each prompt and the JSON shape Claude must return
  • Set temperature and max_tokens per use case, and version prompts so changes are auditable
5

Build the Apex service

One well-built service class carries every Claude use case.

  • A Queueable service that assembles the prompt, calls POST /v1/messages via callout:NamedCredential, and parses the content blocks
  • JSON.serialize for the request; deserialize the response and validate against the expected shape before any DML
  • Return structured errors so the caller can decide to retry, queue, or surface
InboundRecordApi.clsapex
@RestResource(urlMapping='/inbound/records/*')
global with sharing class InboundRecordApi {
  @HttpPost
  global static void upsertRecords() {
    List<Row> items = (List<Row>) JSON.deserialize(
      RestContext.request.requestBody.toString(), List<Row>.class);

    List<MyObject__c> rows = new List<MyObject__c>();
    for (Row r : items) {
      rows.add(new MyObject__c(External_Id__c = r.id, Name = r.name, Amount__c = r.amount));
    }
    upsert rows External_Id__c;         // bulk + idempotent on the external id
    RestContext.response.statusCode = 200;
  }
  global class Row { global String id; global String name; global Decimal amount; }
}
6

Trigger from Flow or Quick Action

Users and automation both need a way in.

  • A record-triggered flow calls invocable Apex for automatic summaries on create
  • A Quick Action button gives agents on-demand drafts from the record page
  • Triggers cannot call out synchronously, so every path hands off to the async service
SyncToServiceQueueable.clsapex
public class SyncToServiceQueueable implements Queueable, Database.AllowsCallouts {
  private List<Id> ids;
  public SyncToServiceQueueable(List<Id> ids) { this.ids = ids; }

  public void execute(QueueableContext ctx) {
    for (MyObject__c rec : [SELECT Id, Name, External_Id__c FROM MyObject__c WHERE Id IN :ids]) {
      HttpRequest req = new HttpRequest();
      req.setEndpoint('callout:Service_NC/v1/records'); // secret lives in the Named Credential
      req.setMethod('POST');
      req.setHeader('Content-Type', 'application/json');
      req.setBody(JSON.serialize(new Map<String,Object>{
        'externalId' => rec.External_Id__c, 'name' => rec.Name }));
      HttpResponse res = new Http().send(req);
      if (res.getStatusCode() != 200) ErrorLog.capture(rec.Id, res);
    }
  }
}
7

Engineer for scale and governor limits

Built to survive real volume, not just a demo.

  • Bulkify everything: batch summaries run through Queueable chains, never callouts in loops
  • Route routine work to Haiku and reserve Sonnet for complex reasoning, cutting cost per call
  • Add retry with backoff and a dead-letter Error_Log__c record for anything that fails
NightlySyncBatch.clsapex
global class NightlySyncBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
  global Database.QueryLocator start(Database.BatchableContext bc) {
    return Database.getQueryLocator([SELECT Id, External_Id__c FROM MyObject__c WHERE Needs_Sync__c = true]);
  }
  global void execute(Database.BatchableContext bc, List<MyObject__c> scope) {
    ServiceClient.sync(scope);       // one callout per 200-record chunk stays under limits
  }
  global void finish(Database.BatchableContext bc) { /* chain the next job or log the run */ }
}

Watch out: governor limits

Salesforce caps SOQL, DML, and callouts per transaction. Bulkify everything and move volume to Queueable or Batch Apex, or the integration will fail at scale.

8

Lock down security and data handling

Exactly the access it needs and nothing more.

  • A least-privilege permission set, field-level security, and sharing for the integration user
  • Anthropic's commercial API does not train on your inputs and outputs by default
  • Add a PII-redaction step before sending sensitive fields, and Shield Platform Encryption where required
9

Optional: stand up MCP and Agentforce patterns

The conversational and agentic layers on top of the same foundation.

  • An MCP server exposing SOQL query and scoped CRUD tools lets Claude Desktop and Claude Code work the org in plain English
  • Permissions are enforced by the integration user profile, so Claude sees only what it is granted
  • On Agentforce, Claude models are available through Amazon Bedrock within the Salesforce trust boundary - licensing runs through Salesforce
SyncToServiceTest.clsapex
@IsTest
private class SyncToServiceTest {
  private class Mock implements HttpCalloutMock {
    public HttpResponse respond(HttpRequest req) {
      HttpResponse res = new HttpResponse();
      res.setStatusCode(200); res.setBody('{"ok":true}');
      return res;
    }
  }
  @IsTest static void syncsInBulk() {
    Test.setMock(HttpCalloutMock.class, new Mock());
    List<MyObject__c> recs = new List<MyObject__c>();
    for (Integer i = 0; i < 200; i++)
      recs.add(new MyObject__c(Name = 'Row ' + i, External_Id__c = 'EXT-' + i));
    insert recs;

    Test.startTest();     // proves the callout is bulk-safe under governor limits
    System.enqueueJob(new SyncToServiceQueueable(new List<Id>(new Map<Id,MyObject__c>(recs).keySet())));
    Test.stopTest();
  }
}
10

Test, deploy, monitor, and hand over

We prove it works before it ships, then keep it healthy.

  • Apex tests with Test.setMock(HttpCalloutMock) covering success, failure, and a 200-record bulk case
  • Golden-example prompt validation in a sandbox, then a parallel run against human output
  • Deploy via change sets or an SFDX and CI pipeline, monitor tokens and failures, and hand over with 30 days of hypercare
Field mapping

Example field mapping

How Claude data lands on your Salesforce records. We tailor the full mapping to your org.

ClaudeSalesforceNotes
Record context fieldsClaude prompt (user message)Assembled by Flow or Apex
System prompt + guardrailsClaude system parameterStored in Custom Metadata
Claude response textAI_Summary__c / AI_Draft__cParsed from the messages response
Model + token usageAI_Interaction__cCost tracking and audit
ErrorsError_Log__cRetry with backoff
MCP tool callsSOQL / DML via integration userPermissions enforced by profile
API & limits

Rate limits and governor limits

The platform constraints we design around, so the integration stays fast and never falls over at scale.

Specific to Claude

Apex: max 100 callouts per transaction; per-callout timeout max 120s; cumulative 120s per transaction
Apex heap limits cap response handling: ~6 MB sync / 12 MB async
Anthropic side: per-model requests-per-minute and tokens-per-minute limits by usage tier

Salesforce platform limits

Salesforce caps API calls per 24 hours by edition and license count. We budget the daily allocation up front so the integration never starves other tools.
Per transaction, Apex allows 100 callouts and a 120-second cumulative callout timeout. Long Claude generations run in Queueable Apex, never inline.
Anthropic enforces requests-per-minute and tokens-per-minute limits by usage tier. We honour them and back off with jitter on HTTP 429 responses.
Apex cannot consume streaming (SSE) responses, so we request complete messages and size max_tokens to the job - Haiku for volume work, Sonnet for reasoning.
Security

Secure by design

How we keep the integration safe, least-privilege, and compliant.

Secrets stored in Named Credentials and permission sets, never in code or metadata
Anthropic's commercial API does not use your inputs and outputs for training by default
A least-privilege integration user, with field-level security and sharing scoped tight
Optional PII-redaction step before any sensitive field leaves Salesforce
The Bedrock pattern keeps processing inside the Salesforce trust boundary entirely
Every automation runs as a dedicated integration user, so actions are attributable and revocable
Sandbox-first delivery and change-set deployment keep production changes reviewed and controlled
Monitoring

Monitoring, retries, and reliability

What keeps the integration trustworthy in production, and how you know the moment something needs attention.

Every request and response is logged to AI_Interaction__c with model and token counts, tagged with the related record id.
Failed calls retry with exponential backoff; anything still failing lands in a dead-letter Error Log for review.
Token usage per call is tracked so spend is visible on a dashboard, with alerts before costs creep.
A dashboard surfaces failures, latency, and volume so problems are caught before users notice.
Optional email or Slack alerts fire on repeated failures or unusual spend.
Testing & deployment

How we test, deploy, and hand it over

The quality gates every build clears before it touches your production org.

Apex unit tests with HttpCalloutMock cover the success path, failure handling, and a 200-record bulk case, at 75 percent or higher coverage.
Prompt outputs are validated against golden examples in a sandbox before anything reaches production users.
A parallel run puts AI drafts side by side with human work until quality is signed off.
Everything deploys through change sets or an SFDX and CI pipeline, under version control.
Permission sets, sharing, and Named Credentials are configured in production, then we run 30 days of monitored hypercare.
Pitfalls

Common pitfalls we design out

The mistakes that quietly break integrations, and how we avoid each one.

Long generations exceed the 120-second Apex callout window

Run calls in Queueable Apex with max_tokens sized to the job; route volume work to Haiku.

Streaming responses cannot be consumed in Apex

Request complete (non-streaming) messages; stream only in off-platform UIs.

Prompt changes require a code deployment

Store system prompts in Custom Metadata so admins tune them in Setup, with versioning.

AI output overwrites human edits

Write to dedicated AI fields with a review status, never over agent-authored content.

Costs creep as usage grows

Log tokens per call to AI_Interaction__c, alert on spend, and route routine work to Haiku.

Gotchas specific to Claude

Long generations can exceed the 120s Apex callout timeout, so heavy calls run in Queueable Apex with max_tokens sized to the job
Apex cannot consume streaming (SSE) responses; request complete messages and stream only in off-platform UIs
You cannot make a callout after uncommitted DML in the same transaction; call Claude before DML or in async
The anthropic-version header is required on every request; missing it fails the call even with a valid key
FAQ

Claude integration: technical FAQs

How do you authenticate Claude with Salesforce?

An External Credential carries the x-api-key header and a Named Credential points at api.anthropic.com with the anthropic-version header attached, guarded by a permission set. No secrets in code or metadata.

Does the Claude integration handle bulk volume?

Yes. All Apex is bulkified, batch summaries run through chained Queueables, and routine work routes to claude-haiku-4-5 to keep cost and latency down at volume.

How do you handle Apex's callout limits with long generations?

Calls run in Queueable Apex with max_tokens sized to the job, staying inside the 120-second callout window. Apex cannot consume streaming responses, so we request complete messages.

How is the integration tested and deployed?

Apex tests with HttpCalloutMock cover success, failure, and a 200-record bulk case at 75 percent plus coverage, and prompt outputs are validated against golden examples. Deployment runs via change sets or an SFDX and CI pipeline.

What happens if the Anthropic API is briefly down or rate-limits us?

Failed calls retry with exponential backoff and jitter on HTTP 429, and anything still failing lands in an Error Log with alerting so no request is lost.

How do you keep AI costs under control?

Every call logs its model and token count to AI_Interaction__c, a dashboard tracks spend, alerts fire on anomalies, and routine work runs on Haiku while Sonnet is reserved for reasoning-heavy jobs.

Want us to build your Claude integration?

Skip the build. In a free 30-minute call we will map your Claude flow and hand you a clear, fixed-price plan.

Ask me anything