Sub topic 9
Implementing an action with Apex
What this chapter assumes
You should know what an Agentforce agent, topic, and action are, and you should be comfortable writing Apex classes and tests. The earlier chapters covered how the agent reads names, labels, and descriptions. This chapter applies that to one concrete target: an Apex class with an invocable method.
Why Apex is a good fit for an action
Choose Apex when the action needs logic that is awkward in Flow. Examples are querying with a computed filter, shaping a response from several objects, or calling a service with custom error handling. The agent never sees your Apex code. It sees only the metadata attached to the class: the method's label and description, and the label and description of every input and output field. The code decides what happens. The metadata decides whether the agent calls the action and how it uses the result.
The rules for an invocable method
An action based on Apex must expose an invocable method. The platform enforces these rules.
- The method is
staticand annotated with@InvocableMethod. - A class can have only one invocable method.
- The method takes one parameter, which is a
List. It returns aListorvoid. - Return a list for actions, because the agent needs outputs to explain.
- Fields you want the agent to see are annotated with
@InvocableVariablein a wrapper class. - The class and method must be
publicorglobal.
Wrapper classes are the usual way to pass several inputs and outputs. Each field becomes one input or output of the action. Keep the wrappers flat: simple types such as String, Id, Boolean, Decimal, Date, and Integer work best. The data types chapter explains why flat structures are easier for the agent to fill.
Where the agent's view comes from
Each annotation attribute maps to something the agent reads.
| Annotation attribute | What the agent uses it for |
|---|---|
| `@InvocableMethod(label)` | The action's name, used when choosing between actions |
| `@InvocableMethod(description)` | When to call the action, and what it does |
| `@InvocableVariable(label)` on an input | The name of the value the agent must supply |
| `@InvocableVariable(description)` on an input | How to get the value, its format, and what to do if it is missing |
| `required=true` | Marks the input as one the action cannot run without |
| `@InvocableVariable(label, description)` on an output | How the agent interprets and reports the value |
The field name in Apex, such as orderNumber, is for developers. Treat the label and description as the text the agent actually reads.
Walking through the order status example
Here is the class from this tutorial's running example.
public with sharing class GetOrderStatus {
public class Request {
@InvocableVariable(
label='Order Number'
description='The order number the customer provided, for example 00000101. Ask the customer if it was not given. Do not guess.'
required=true
)
public String orderNumber;
}
public class Response {
@InvocableVariable(
label='Order Status'
description='Current status of the order, such as Draft or Activated. Empty if no order was found.'
)
public String status;
@InvocableVariable(
label='Result Message'
description='A short plain-language message describing the outcome, including when no order matches the number.'
)
public String message;
}
@InvocableMethod(
label='Get Order Status'
description='Looks up the status of one order by its order number. Use when the customer asks where their order stands.'
)
public static List<Response> getStatus(List<Request> requests) {
Set<String> numbers = new Set<String>();
for (Request r : requests) {
numbers.add(r.orderNumber);
}
Map<String, Order> byNumber = new Map<String, Order>();
for (Order o : [SELECT OrderNumber, Status FROM Order WHERE OrderNumber IN :numbers WITH USER_MODE]) {
byNumber.put(o.OrderNumber, o);
}
List<Response> results = new List<Response>();
for (Request r : requests) {
Response res = new Response();
Order o = byNumber.get(r.orderNumber);
if (o == null) {
res.message = 'No order was found with number ' + r.orderNumber + '.';
} else {
res.status = o.Status;
res.message = 'Order ' + r.orderNumber + ' has status ' + o.Status + '.';
}
results.add(res);
}
return results;
}
}Three design choices in this class matter for the agent.
- The input description says what to do when the value is missing ("Ask the customer") and forbids guessing. The agent reads this when it decides whether to call the action or ask a question first.
- The output description for
statussays it is empty when no order was found. The agent knows an empty value is a normal outcome, not a failure. - The
messageoutput gives the agent a sentence it can repeat. The not-found case has its own wording, so the agent does not have to invent an explanation.
How a call flows through the class
The diagram shows the path of one request, including the branch for an order that does not exist.
Bulk safety and result order
The method receives a list even when the agent asks about one order. Write it as if the list could hold many entries. The example does this well. It collects all order numbers, runs one query, and then builds one response per request.
Keep two habits.
- Never run a query or DML statement inside the loop over
requests. Query once, then look up values in a map. - Return one response for each request, in the same order. The platform matches outputs to inputs by position. A shorter or reordered list gives the wrong result to the wrong caller.
Security: sharing and user mode
An agent can run as a service agent user or as the logged-in user, depending on how it is set up. Either way, your Apex should not return data the running user is not allowed to see. The example uses two protections together.
with sharingon the class applies record-level sharing rules.WITH USER_MODEon the query enforces object and field permissions.
If the running user cannot read orders, the query fails or returns nothing, so the agent cannot become a way around your security model. Grant the agent's user the access the action needs and no more.
Returning empty results and failures
There are three outcomes to plan for, and each should look different to the agent.
| Outcome | What to return | Why |
|---|---|---|
| Success | Populated outputs and a confirming message | The agent can state the result |
| Valid but empty | Empty data field and a message saying nothing matched | The agent reports "not found" instead of retrying |
| Unexpected failure | A message that says what failed and what the user can do | The agent can explain without exposing internals |
An unhandled exception stops the action, and the agent gets little useful to explain. For problems you can foresee, catch them and return a message. The version below adds handling for a blank order number and for a query that fails, and it stays bulk safe.
public with sharing class GetOrderStatusSafe {
public class Request {
@InvocableVariable(
label='Order Number'
description='The order number the customer provided, for example 00000101. Ask the customer if it was not given. Do not guess.'
required=true
)
public String orderNumber;
}
public class Response {
@InvocableVariable(
label='Order Status'
description='Current status of the order, such as Draft or Activated. Empty if no order was found.'
)
public String status;
@InvocableVariable(
label='Result Message'
description='A short plain-language message describing the outcome, including when no order matches the number or the lookup fails.'
)
public String message;
}
@InvocableMethod(
label='Get Order Status'
description='Looks up the status of one order by its order number. Use when the customer asks where their order stands.'
)
public static List<Response> getStatus(List<Request> requests) {
Set<String> numbers = new Set<String>();
for (Request r : requests) {
if (String.isNotBlank(r.orderNumber)) {
numbers.add(r.orderNumber.trim());
}
}
Map<String, Order> byNumber = new Map<String, Order>();
String failure;
try {
for (Order o : [SELECT OrderNumber, Status FROM Order WHERE OrderNumber IN :numbers WITH USER_MODE]) {
byNumber.put(o.OrderNumber, o);
}
} catch (QueryException e) {
failure = 'The order lookup failed because the data could not be read. Ask the user to contact support.';
}
List<Response> results = new List<Response>();
for (Request r : requests) {
Response res = new Response();
if (String.isBlank(r.orderNumber)) {
res.message = 'No order number was provided. Ask the customer for it.';
} else if (failure != null) {
res.message = failure;
} else {
Order o = byNumber.get(r.orderNumber.trim());
if (o == null) {
res.message = 'No order was found with number ' + r.orderNumber + '.';
} else {
res.status = o.Status;
res.message = 'Order ' + r.orderNumber + ' has status ' + o.Status + '.';
}
}
results.add(res);
}
return results;
}
}The failure message tells the agent what to do next. That keeps the agent from guessing at a cause or showing a raw system error.
Testing the class
Test the Apex like any other code, then test the metadata by talking to the agent in a later chapter. This test covers the found, not-found, and blank cases.
@IsTest
private class GetOrderStatusSafeTest {
private static GetOrderStatusSafe.Request makeRequest(String orderNumber) {
GetOrderStatusSafe.Request r = new GetOrderStatusSafe.Request();
r.orderNumber = orderNumber;
return r;
}
@IsTest
static void returnsStatusForExistingOrder() {
Account a = new Account(Name = 'Test Account');
insert a;
Order o = new Order(AccountId = a.Id, EffectiveDate = Date.today(), Status = 'Draft');
insert o;
String number1 = [SELECT OrderNumber FROM Order WHERE Id = :o.Id].OrderNumber;
List<GetOrderStatusSafe.Response> results =
GetOrderStatusSafe.getStatus(new List<GetOrderStatusSafe.Request>{ makeRequest(number1) });
System.assertEquals(1, results.size());
System.assertEquals('Draft', results[0].status);
}
@IsTest
static void returnsMessageWhenNothingMatches() {
List<GetOrderStatusSafe.Response> results =
GetOrderStatusSafe.getStatus(new List<GetOrderStatusSafe.Request>{ makeRequest('99999999') });
System.assertEquals(null, results[0].status);
System.assert(results[0].message.contains('No order was found'));
}
@IsTest
static void keepsOrderAndSizeForMixedInput() {
List<GetOrderStatusSafe.Response> results =
GetOrderStatusSafe.getStatus(new List<GetOrderStatusSafe.Request>{
makeRequest(''), makeRequest('99999999')
});
System.assertEquals(2, results.size());
System.assert(results[0].message.contains('No order number'));
System.assert(results[1].message.contains('No order was found'));
}
}Common mistakes
- Using a vague description such as "The id". The agent cannot tell which id to supply.
- Marking an input required but giving no hint about where the value comes from. Say whether to ask the user or take it from earlier context.
- Returning a list shorter than the input list. Results then pair with the wrong requests.
- Returning internal text, such as a stack trace or a raw exception message. Return a short plain message.
- Adding outputs the agent does not need. Each extra field is more text the agent may repeat or misread.
Exercise
A teammate's invocable method has one input described as "The account" and one output called "Result" with the description "Output of the action". The agent often calls the action with the wrong value and then gives confusing answers. List two changes to the annotations that would help, and state one rule about the returned list.
Show answer
Rewrite the input label and description to say exactly what is needed, for example label "Account Name" with a description such as "The exact name of the customer's account. Ask the customer if it was not given. Do not guess." Rewrite the output to say what the value means and when it is empty, for example label "Account Status" with "Current status of the account. Empty if no account was found." Also add a message output for the not-found case. The rule for the returned list is that it must contain one response per request, in the same order as the requests.
Exercise
In the GetOrderStatusSafe class, a request has a blank order number and the query throws a QueryException. What does the agent receive for that request, and why is that better than letting the exception escape?
Show answer
The agent receives a response with an empty status and the message "No order number was provided. Ask the customer for it." The blank check runs before the failure check, so the blank input is reported first. A request with a valid number would instead get the lookup-failure message. Handling it this way gives the agent a plain message it can act on, such as asking the customer for the number. An escaped exception stops the whole action and leaves the agent with little to explain.