Sub topic 10
Writing a custom Apex action
This chapter shows how to write an Apex invocable method and expose it to an agent as a custom action. It also covers deployment with the Salesforce CLI and the mistakes that most often stop an action from working.
Prerequisites
This chapter assumes you have the following:
- A Developer Edition org with Agentforce enabled and an agent already created in Agentforce Builder.
- A topic on that agent with instructions, as covered in earlier chapters.
- Basic reading knowledge of Apex: classes, collections, SOQL, and the
public with sharingmodifier. - The Salesforce CLI installed, if you want to deploy from your machine. You can also paste the class into the Developer Console.
Why a custom action
Standard actions cover common jobs such as looking up a record or drafting an email. They cannot know your own business rules. A custom action lets the agent call code you wrote. In this chapter the code counts the open cases for an account.
Agentforce can call several kinds of targets as actions: Apex invocable methods, Flows, and prompt templates. Apex is the right choice when you need logic that is awkward in Flow, such as aggregate queries or careful bulk handling. If a Flow can do the job, a Flow is usually easier for an admin to maintain.
How an action reaches your code
The agent never runs your Apex directly. The builder reads the invocable method's signature and uses its labels and descriptions to tell the language model what the action does and what inputs it needs. The model decides whether to call it, fills in the inputs, and the platform runs the method.
Because the model reads your labels and descriptions, they act as documentation for the agent. Vague text leads to wrong or missed calls.
The Apex class
Create GetOpenCaseCountAction.cls in your project. This class takes a list of account IDs and returns the open case count for each.
public with sharing class GetOpenCaseCountAction {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
}
public class Response {
@InvocableVariable(label='Open Case Count')
public Integer openCaseCount;
}
@InvocableMethod(label='Get Open Case Count' description='Returns the number of open cases for an account')
public static List<Response> getOpenCaseCount(List<Request> requests) {
Set<Id> accountIds = new Set<Id>();
for (Request r : requests) {
accountIds.add(r.accountId);
}
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acct, COUNT(Id) total
FROM Case
WHERE IsClosed = false AND AccountId IN :accountIds
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acct'), (Integer) ar.get('total'));
}
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response res = new Response();
res.openCaseCount = counts.containsKey(r.accountId) ? counts.get(r.accountId) : 0;
responses.add(res);
}
return responses;
}
}Walking through the design
The class follows the rules Salesforce places on invocable methods, and a few good habits on top of them.
- One invocable method per class. Salesforce allows only one
@InvocableMethodin a class. Put each action in its own class. - Static and public. The method must be
static, and the class must bepublicorglobal. - List in, list out. The method takes a
Listand returns aList. The platform may batch several calls into one invocation, so the code must handle many requests at once. - Wrapper classes for inputs and outputs. The
RequestandResponseinner classes carry the data. Each field you want exposed needs@InvocableVariable. - Order matters. The returned list must match the order of the input list. The loop at the end builds one response per request, in request order, so the first response answers the first request.
with sharing. The class respects the running user's record access. See the callout below on which user that is.- Zero, not null. If an account has no open cases, the aggregate query returns no row for it. The ternary expression turns that gap into
0, which is a real answer. Anullwould force the agent to guess.
The query runs once for the whole batch, not once per request. This keeps you under the SOQL query limit of 100 per transaction when many requests arrive together.
What the annotations control
The labels and descriptions are what the builder shows and what the model reads.
| Annotation property | Where it appears | Notes |
|---|---|---|
| `label` on `@InvocableMethod` | Action name in the builder | Use a short verb phrase. |
| `description` on `@InvocableMethod` | Guidance for the model | Say what the action returns and when to use it. |
| `label` on `@InvocableVariable` | Input and output names | Plain words, because the model reads them. |
| `required=true` | Marks an input as mandatory | The agent must collect it before calling. |
Leave required=true on accountId. Without it the agent might call the action with an empty value, and the query would silently return nothing.
Deploy the class with the Salesforce CLI
Log in to your org under an alias, then deploy the source directory. Run these from the root of a Salesforce DX project.
sf org login web --alias agentforce-dev
sf project deploy start --source-dir force-app --target-org agentforce-devThe first command opens a browser window for you to log in. The second sends everything under force-app to the org. If the deploy fails, the error output names the file and line. A common cause is a missing metadata file: each class needs both a .cls file and a .cls-meta.xml file, and sf apex generate class creates both.
Deploying a class to a Developer Edition org does not require tests. Production deployments require 75 percent code coverage, so write a test class now if you plan to move this code later.
Add the action to a topic
After the class is in the org, attach it to your agent.
- Open your agent in Agentforce Builder.
- Open the topic that should use the action, for example Case Status Questions.
- Choose to add an action, then pick the option for Apex.
- Select Get Open Case Count from the list.
- Review the action's name, description, and inputs. Edit the text if it is not clear.
- Save the action to the topic.
If the class does not appear in the list, see the troubleshooting table below.
Tell the topic when to use the action
An action that exists is not an action that gets used. Your topic instructions must say when to call it. This sample topic does that.
Topic: Case Status Questions
Description: Answer questions about the status of a customer's support cases.
Instructions:
1. Ask for the account if the user has not named one.
2. Use the Get Open Case Count action to look up the number of open cases.
3. Report the number in one sentence. Do not guess when the action returns no result.
4. If the user asks about anything other than case status, say you cannot help with that.Each instruction has a job. Step 1 makes sure the required input exists. Step 2 names the action by its label, so the model links the instruction to the right tool. Step 3 sets the output format and forbids invented numbers. Step 4 sets the scope boundary.
One gap remains. The action wants an account ID, but the user will say an account name. The agent needs a way to turn the name into an ID. A standard action that queries records can do this, so add one to the same topic and have step 1 use it. Otherwise the agent will ask the user for an ID they do not know.
Test the action
Open the conversation preview in the builder and ask, "How many open cases does Acme have?" Use an account in your org that has several open cases. Then check the following:
- The agent chooses the right topic.
- The agent calls the action and shows the input it used.
- The count matches what a list view of open cases for that account shows.
- An account with no open cases gives
0, not a guess. - An off-topic question gets the refusal from step 4.
The builder's preview lets you inspect the steps the agent took, including which action ran and with what values. Use that trace first when the answer is wrong.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Class is missing from the action list | Not deployed, or no `@InvocableMethod` | Confirm deployment, then check the annotation and that the method is `public static`. |
| Deploy fails with a missing metadata error | No `.cls-meta.xml` file | Generate the class with `sf apex generate class`. |
| Agent never calls the action | Topic instructions do not mention it | Name the action in an instruction. Tighten its description. |
| Agent asks for an ID the user cannot give | No step to resolve a name to an ID | Add a lookup action and an instruction that uses it first. |
| Count is lower than expected | Sharing rules hide records from the running user | Check that user's Case access and the permission sets. |
| Responses are mixed up between accounts | Response order differs from request order | Build the response list by looping over the requests. |
| Limits exceeded errors | Query or DML inside a loop | Query once outside the loop, as the sample does. |
Edge cases to keep in mind
- Duplicate IDs in one batch. The sample handles them. The
Setremoves duplicates for the query, and the final loop still returns one response per request. - Null input.
required=trueis enforced by the agent, not by Apex. If you call the method from other code, a nullaccountIdis possible. The query treats it as no match and returns0, but you may prefer to throw an error in your own code. - Large result sets. An aggregate query returns one row per account, so it stays small. If you ever return record lists, cap them and tell the agent how many were cut off.
- Changes after deployment. If you change labels or add fields, check the action in the builder. It may need to be refreshed or re-added before the new inputs appear.
Exercise
The getOpenCaseCount method loops over the aggregate query results to build its response list. A colleague proposes replacing the final loop with one that iterates over counts.keySet(), because it looks shorter. Why would that break the action?
Show answer
The key set only has accounts that have at least one open case, and its order is not tied to the request order. Accounts with zero open cases would get no response, so the response list would be shorter than the request list. Responses could also be paired with the wrong requests. The loop over requests guarantees one response per request, in the same order, and lets the ternary expression supply 0 for missing accounts.
Exercise
Your agent answers "I can't help with that" when a user asks about open cases for "Acme", even though the action is deployed and added to the topic. Name two things to check.
Show answer
First, check the topic instructions: they must tell the agent when to use the action, and they must include a way to get an account ID from the name, such as a lookup action. Second, use the conversation preview trace to see whether the topic was chosen at all. If the topic's description is too narrow, the question may not match it, and the refusal rule in step 4 fires instead.