Sub topic 12
Building an invocable Apex method for an action
This chapter shows how to write an Apex class that an agent can call as an action. It assumes you have read the earlier chapters on topics, instructions, and action inputs and outputs. You should also be able to write basic Apex (classes, SOQL, lists) and open Setup and Agentforce Builder.
Why Apex for an action
A Flow action suits simple lookups and record updates. Apex suits logic that is awkward in a Flow: grouping results, calling external code, or applying branching rules. Either way, the agent never sees your code. It sees a name, a description, and a list of inputs and outputs. Your job is to expose those clearly and to make the code safe to run on the agent's behalf.
The anatomy of an invocable method
An invocable method is a static Apex method marked with @InvocableMethod. Its inputs and outputs are usually small inner classes whose fields are marked with @InvocableVariable. The platform reads these annotations to build the action definition that you add to a topic.
public with sharing class GetOrderStatus {
public class Request {
@InvocableVariable(label='Order Number' description='The order number the customer provided' required=true)
public String orderNumber;
}
public class Response {
@InvocableVariable(label='Status' description='Current status of the order, or Not found')
public String status;
}
@InvocableMethod(label='Get Order Status' description='Looks up the status of an order by its order number')
public static List<Response> getStatus(List<Request> requests) {
List<Response> results = new List<Response>();
for (Request r : requests) {
Response res = new Response();
List<Order> orders = [
SELECT Status FROM Order
WHERE OrderNumber = :r.orderNumber
WITH USER_MODE
LIMIT 1
];
res.status = orders.isEmpty() ? 'Not found' : orders[0].Status;
results.add(res);
}
return results;
}
}This version works, but it has a flaw that the next sections fix. First, here is what each piece does.
Annotation attributes that matter to the agent
| Annotation | Attribute | What the agent or builder uses it for |
|---|---|---|
| `@InvocableMethod` | `label` | The action's display name in Builder. |
| `@InvocableMethod` | `description` | Tells the agent what the action does and when it applies. |
| `@InvocableVariable` | `label` | The display name of an input or output. |
| `@InvocableVariable` | `description` | Tells the agent what value to put in or what the value means. |
| `@InvocableVariable` | `required` | Marks an input the agent must supply before it can run the action. |
Treat the descriptions as prompt text. A description such as "The order number the customer provided" tells the agent to take the value from the conversation and not to invent one. A blank or vague description gives the agent nothing to reason with, and the result is wrong inputs or an action that is never chosen.
Structural rules
- A class can contain only one
@InvocableMethod. - The method must be
staticandpublicorglobal. - The method takes a single parameter, which is a list. It returns
voidor a list. - Classes used as input or output types must be
publicorglobal, and the annotated fields must be accessible the same way. - Keep the label of the method and the labels of its variables unique and readable, because they appear in Builder.
Why the method takes and returns lists
The platform can call an invocable method with several requests in one transaction. That is why the parameter is List<Request> and the return value is List<Response>. Two rules follow from this:
- Return exactly one response for each request, in the same order.
- Do not run SOQL or DML inside the loop.
The first version above breaks the second rule. It runs one query per request, so a large batch can hit the governor limit of 100 SOQL queries per transaction. An agent usually sends one request at a time, but the same class might also be called from a Flow, and the limit is the same there. Collect the keys, query once, and then build the responses.
public with sharing class GetOrderStatus {
public class Request {
@InvocableVariable(label='Order Number' description='The order number the customer provided' required=true)
public String orderNumber;
}
public class Response {
@InvocableVariable(label='Status' description='Current status of the order, or Not found')
public String status;
}
@InvocableMethod(label='Get Order Status' description='Looks up the status of an order by its order number')
public static List<Response> getStatus(List<Request> requests) {
Set<String> orderNumbers = new Set<String>();
for (Request r : requests) {
if (r.orderNumber != null) {
orderNumbers.add(r.orderNumber);
}
}
Map<String, String> statusByNumber = new Map<String, String>();
for (Order o : [
SELECT OrderNumber, Status FROM Order
WHERE OrderNumber IN :orderNumbers
WITH USER_MODE
]) {
statusByNumber.put(o.OrderNumber, o.Status);
}
List<Response> results = new List<Response>();
for (Request r : requests) {
Response res = new Response();
res.status = statusByNumber.containsKey(r.orderNumber)
? statusByNumber.get(r.orderNumber)
: 'Not found';
results.add(res);
}
return results;
}
}The final loop always adds one response per request, so the output stays aligned with the input even when an order is missing or the number is null.
Running safely on behalf of a user
An agent action runs with the permissions of the running user, but Apex does not enforce object and field permissions on its own. Two choices make the difference:
with sharingmakes the class respect record sharing rules.WITH USER_MODEmakes the query respect object and field permissions of the running user. It fails with an exception if the user cannot readStatus.
Together they mean the action cannot return data the user could not see in the org. This supports the instruction from the topic example, "Never share details about orders that belong to other customers." An instruction is only a request to the model. The permission check is what actually enforces it. Use both.
Return a result the agent can reason about
The method returns the text Not found for a missing order. That matches the topic instruction, "If the action returns 'Not found', tell the customer you could not find the order." The agent can only follow that step if the action returns exactly that value. When you change an output value, update the instruction at the same time.
Avoid throwing exceptions for expected cases such as a missing record. An unhandled exception gives the agent a generic failure, and it cannot tell the customer anything useful. Reserve exceptions for real faults, such as a permission error.
How the pieces fit together at runtime
The diagram shows one request passing through the topic, the agent's reasoning, and your method.
The agent chose the topic from its classification description, followed the instructions to ask for the number, and filled the Order Number input from the customer's reply. It then used the Status output to write its answer.
Adding the method to a topic
After you deploy the class:
- Open the agent in Agentforce Builder and select the topic, for example Order Status.
- Add a new action and choose the Apex action type.
- Pick
Get Order Statusfrom the list of invocable methods. - Check the generated inputs and outputs. Edit the descriptions if the agent needs more guidance.
- Reference the action by name in the topic instructions, as in step 2 of the example: "Use the Get Order Status action with that order number."
If the method does not appear in the list, check that the class is deployed, that it has exactly one @InvocableMethod, and that the method signature follows the structural rules above.
Testing the Apex class
Test the class like any other Apex, then test the agent's use of it in Builder. A unit test covers the found and not-found paths.
@IsTest
private class GetOrderStatusTest {
@IsTest
static void returnsStatusForKnownOrder() {
Account a = new Account(Name = 'Test Co');
insert a;
Order o = new Order(AccountId = a.Id, EffectiveDate = Date.today(), Status = 'Draft');
insert o;
String orderNumber = [SELECT OrderNumber FROM Order WHERE Id = :o.Id].OrderNumber;
GetOrderStatus.Request req = new GetOrderStatus.Request();
req.orderNumber = orderNumber;
Test.startTest();
List<GetOrderStatus.Response> out =
GetOrderStatus.getStatus(new List<GetOrderStatus.Request>{ req });
Test.stopTest();
Assert.areEqual(1, out.size());
Assert.areEqual('Draft', out[0].status);
}
@IsTest
static void returnsNotFoundForUnknownOrder() {
GetOrderStatus.Request req = new GetOrderStatus.Request();
req.orderNumber = 'does-not-exist';
List<GetOrderStatus.Response> out =
GetOrderStatus.getStatus(new List<GetOrderStatus.Request>{ req });
Assert.areEqual('Not found', out[0].status);
}
}The unit test proves the code is correct. It does not prove the agent calls the action at the right time with the right input. For that, use the Builder preview and try phrasings such as a missing order number, a wrong order number, and a question about someone else's order.
Common errors
- Vague descriptions. The agent skips the action or sends a wrong value. Rewrite the descriptions as short, concrete statements.
- SOQL inside the loop. It passes with one request and fails on a larger batch. Query once outside the loop.
- Mismatched output. The method returns
NOT_FOUNDbut the instruction saysNot found. Keep them identical. - Response count differs from request count. The platform expects one result per request. Always add a response in the final loop.
- Missing permission enforcement. A class without
with sharingorUSER_MODEmay expose data the user should not see. - Editing the signature after adding the action. Changing input or output fields can leave the action definition out of date. Re-check the action in Builder after each change.
Exercise
A teammate's invocable method runs a SOQL query inside a for loop over requests, and it passes every unit test that sends one request. Why is it still a problem, and how do you fix it?
Show answer
Each request in the loop runs its own query, so a call with more than 100 requests exceeds the governor limit of 100 SOQL queries per transaction. Collect the lookup keys into a set, run one query with IN :keys, store the results in a map, and then loop over the requests to build one response each from the map.
Exercise
The topic instruction says to tell the customer "I could not find the order" when the action returns 'Not found', but the agent keeps reporting an empty status. The Apex method returns null for missing orders. What do you change, and where?
Show answer
Change the Apex method so it sets status to the exact text Not found when no order matches, as the instruction expects. Alternatively, rewrite the instruction to handle a blank status, but returning the agreed value keeps the code and the instruction consistent.
Exercise
Why use both with sharing and WITH USER_MODE in the class when the topic instructions already say not to share other customers' orders?
Show answer
Instructions only guide the model, so they cannot guarantee that data stays private. with sharing applies record sharing rules and WITH USER_MODE applies object and field permissions of the running user, so the query itself cannot return data the user may not see.