Sub topic 2
Writing an @InvocableMethod
This chapter covers the @InvocableMethod annotation: what it does, the rules the compiler enforces, and the parts of the contract that affect an Agentforce agent. It assumes you can write basic Apex (classes, collections, SOQL) and know what sharing and field-level security mean. It also assumes you know what an agent topic is. The next chapters cover the fields of the request and response types and the writing of descriptions in detail. Here you build the method itself.
What the annotation does
@InvocableMethod marks one Apex method as callable by declarative tools. Flow, Process Builder, the REST API, and Agentforce can all discover and run such a method without anyone writing Apex that calls it. The annotation is the entry point of an agent action. It tells the platform three things:
- This method can be called from outside Apex.
- Here is the name and description to show to the person or agent choosing it.
- Here is its category, for grouping in pickers.
The platform reads the method's single parameter and its return type to build the action's inputs and outputs. The method signature is therefore part of the contract with the agent, so changing it later changes what the agent sees.
The smallest useful action
The class below counts open cases for each account it is given. It uses wrapper types for the input and output, which the platform requires once you need named fields. The @InvocableVariable details are covered in the next chapter.
public with sharing class CountOpenCasesAction {
public class Request {
@InvocableVariable(
label='Account Id'
description='The Salesforce Id of the account to count open cases for'
required=true
)
public Id accountId;
}
public class Response {
@InvocableVariable(
label='Open Case Count'
description='Number of open cases for the account'
)
public Integer openCaseCount;
}
@InvocableMethod(
label='Count Open Cases'
description='Returns how many support cases are open for an account'
category='Service'
)
public static List<Response> countOpenCases(List<Request> requests) {
Set<Id> accountIds = new Set<Id>();
for (Request r : requests) {
if (r.accountId != null) {
accountIds.add(r.accountId);
}
}
Map<Id, Integer> countsByAccount = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acct, COUNT(Id) total
FROM Case
WHERE AccountId IN :accountIds AND IsClosed = false
WITH USER_MODE
GROUP BY AccountId
]) {
countsByAccount.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 = countsByAccount.containsKey(r.accountId)
? countsByAccount.get(r.accountId)
: 0;
responses.add(res);
}
return responses;
}
}Three habits in this code are worth copying everywhere:
- The method takes a list and returns a list, and the returned list has one entry per request, in the same order.
- The query runs once, outside any loop over requests.
- The class is declared
with sharingand the query usesWITH USER_MODE, so the action sees only what the running user can see.
The rules the platform enforces
The compiler or the platform rejects methods that break these rules. Most errors in a first invocable method come from this list.
| Rule | What it means in practice |
|---|---|
| Static | The method must be declared `static`. |
| Visibility | The method must be `public` or `global`. A `private` method is not callable. |
| One per class | A class can contain only one `@InvocableMethod`. Each action needs its own outer class. |
| One parameter | The method takes at most one parameter, and it must be a `List`. |
| Allowed element types | The list holds primitives, `Id`, an sObject type, the generic `SObject`, or an Apex class with at least one `@InvocableVariable`. |
| Return type | `void`, or a list of one of the same element types. |
| No other annotations | Other method annotations, such as `@AuraEnabled` or `@future`, cannot go on the same method. |
| Visible wrapper types | A request or response class must be `public` or `global`. If it is an inner class, its outer class must be too. |
Because only one invocable method fits in a class, a common layout is one outer class per action, with Request and Response as inner classes. The example above follows that layout. It keeps each action's contract in one file and avoids name clashes between actions.
Two shapes are not allowed as the parameter. A Map or Set cannot be the parameter or the return type, and you cannot take several parameters. If an action needs several inputs, put them as fields on the request class. This is also what lets the agent fill each input by name.
The annotation's parameters
The annotation accepts these named parameters.
| Parameter | Purpose | Notes for agent actions |
|---|---|---|
| `label` | Display name of the action | Appears in Agent Builder. Use a verb phrase such as `Get Open Cases`. |
| `description` | What the action does | The agent's reasoning engine reads this when deciding whether to call the action. |
| `category` | Group name in pickers | Optional. It helps admins find the action, and the agent does not rely on it. |
| `callout` | Set to `true` if the method calls an external system | Declare it on any method that makes callouts. |
| `iconName`, `configurationEditor` | Flow Builder display options | Not used by agents. You can leave them out. |
If you omit label, the platform falls back to the method name. If you omit description, the action shows no description, and the agent then has only the label and names to work with. That is rarely enough. Treat description as required, and write it so a person who has never seen your code knows when to use the action.
How the call reaches your method
The agent never calls your Apex directly. The reasoning engine selects an action based on the user's request and the topic's instructions. It then fills in the inputs from the conversation and asks the platform to run the method.
The platform packages the agent's inputs into a list with one Request, so an agent call usually runs your method with a list of one. Flow can send many requests in one call, for example when a record-triggered flow runs for 200 records. The same method serves both callers, so write it for the list case. A method that only works for a list of one will fail in Flow.
Behavior to know before you build
The method runs in the caller's transaction. All the usual governor limits apply, shared with everything else running in that transaction. Chapter work on limits comes later, but the rule for now is simple: no SOQL or DML inside a loop over requests.
The returned list must line up with the input list. If request 3 has no matching data, return a response for it anyway, with an empty or zero value. Skipping it shifts every later result to the wrong request. The example above does this with a 0 for accounts that have no open cases.
Null inputs are possible. An input marked required=true is a signal to the agent, which will ask the user for the value. Still guard against null in the Apex, as the example does with r.accountId != null. Flow and other callers can pass null for fields that the agent would always fill.
Do not return null for the list. Return an empty list at minimum, and in normal cases return one response per request.
An uncaught exception ends the action. The platform reports the failure to the agent, which then tells the user something unhelpful. Catching expected failures and returning a readable message is covered in the error handling chapter.
Trying the method before the agent
You can run the method from Anonymous Apex in the Developer Console or VS Code. This checks the Apex alone, before the agent is involved. It needs at least one account in the org.
Account acct = [SELECT Id FROM Account LIMIT 1];
CountOpenCasesAction.Request req = new CountOpenCasesAction.Request();
req.accountId = acct.Id;
List<CountOpenCasesAction.Response> results =
CountOpenCasesAction.countOpenCases(
new List<CountOpenCasesAction.Request>{ req }
);
System.debug('Open cases: ' + results[0].openCaseCount);If this works, any failure you see later in Agent Builder comes from registration, descriptions, or the agent's choices, and the Apex logic is not the cause. Separating the two saves time. A full unit test replaces this check once the action is stable, and it gets its own chapter.
Common mistakes
- Two invocable methods in one class. The save fails. Move one to a new outer class.
- A non-static method. The save fails. Add
static. - A
Requestclass with no@InvocableVariablefields. The class is not accepted as a parameter type, and the platform reports an error on save. - Returning fewer responses than requests. There is no compile error, so this is a quiet bug. Results attach to the wrong inputs in Flow. Assert
results.size() == requests.size()in your tests. - Querying inside the request loop. It passes with one request and hits the SOQL limit with a bulk call from Flow.
- Leaving out
with sharing. An Apex class without a sharing keyword runs with the sharing mode of its caller. For an action the agent runs on behalf of a user, state your intent explicitly.
Where this fits
The annotation turns an ordinary static method into something the platform can offer as an action. The rules above are mechanical. The next chapter looks at the request and response types, where you decide what the agent sends and receives.
Exercise
A teammate's class has two methods, getOpenCases and getClosedCases, and both carry @InvocableMethod. The class will not save. Name the rule that was broken and describe two ways to fix it. Then say what the returned list must look like if the incoming list holds three requests and only the second one matches any data.
Show answer
A class can contain only one @InvocableMethod. Fix it by moving one method into a second outer class, which gives each action its own class and contract. Alternatively, merge the logic into one method and add an input field, such as a status filter, to the request class. The returned list must still hold three responses in the same order as the three requests. The first and third carry empty or zero values (for example openCaseCount = 0 or a "no cases found" message), and the second carries the real data. Dropping the empty ones would shift the results onto the wrong requests.