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.
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
Data flows left to right
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- Reference
- Official developer docs
Key endpoints
/v1/messages/v1/modelsBuild 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...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.
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
What you will need
What we confirm on both sides before writing a line of code.
From trigger to record, end to end
The production runtime flow, with what happens in each system.
- 1
Trigger in Salesforce
In SalesforceA record change or a button starts the Claude action.
$A record-triggered flow or a Quick Action fires the process. - 2
Prompt is built
In SalesforceApex or Flow assembles record context into a prompt.
$System prompt from Custom Metadata plus record fields, queued async. - 3
Call Claude
In transitThe request posts to the Anthropic Messages API.
$HTTPS via callout:NamedCredential with x-api-key and anthropic-version headers, no secrets in code. - 4
Result written back
In SalesforceClaude's response is parsed and lands on the record.
$Content blocks parsed; summary, draft, and token usage stored for audit.
How the data actually flows
Left to right: sources, the integration layer, Salesforce, and the outcomes it drives.
Sources feed the integration layer, Salesforce stores the result, and the outcomes ship to the business.
The objects behind the integration
The Salesforce objects we read and write, what each one is for, and the fields that carry the load.
| Object | Purpose | Key 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
Build the Claude integration
Every step we follow to ship a production-grade build, with the code that matters.
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
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
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.
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
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
@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; }
}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
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);
}
}
}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
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.
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
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
@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();
}
}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
Example field mapping
How Claude data lands on your Salesforce records. We tailor the full mapping to your org.
| Claude | Salesforce | Notes |
|---|---|---|
| Record context fields | Claude prompt (user message) | Assembled by Flow or Apex |
| System prompt + guardrails | Claude system parameter | Stored in Custom Metadata |
| Claude response text | AI_Summary__c / AI_Draft__c | Parsed from the messages response |
| Model + token usage | AI_Interaction__c | Cost tracking and audit |
| Errors | Error_Log__c | Retry with backoff |
| MCP tool calls | SOQL / DML via integration user | Permissions enforced by profile |
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
Salesforce platform limits
Secure by design
How we keep the integration safe, least-privilege, and compliant.
Monitoring, retries, and reliability
What keeps the integration trustworthy in production, and how you know the moment something needs attention.
How we test, deploy, and hand it over
The quality gates every build clears before it touches your production org.
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
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.
Other ai, identity and cloud integrations we have built
Same architecture, different system. Each guide has the full build with real code.
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.
