Sub topic 3
Modeling inputs and outputs with @InvocableVariable
This chapter assumes you can write basic Apex classes, use collections, and read a SOQL query. It also assumes you know that an Agentforce agent selects actions within a topic. The previous chapter covered the @InvocableMethod annotation. This chapter covers the objects that go into and come out of that method.
Why the wrapper classes matter
An invocable method takes one parameter, a List of some type, and returns a List or nothing. To pass several named values, you wrap them in an Apex class. Each field you expose is marked with @InvocableVariable. The platform reads these classes and builds the action's input and output schema from them. Agent Builder then shows that schema, and the agent's reasoning engine uses it to decide what to ask the user for and how to read the result.
So the wrapper classes serve two readers. The Apex compiler checks the types. The agent reads the field names, labels, and descriptions.
The shape of a wrapper class
The example from the topic plan shows the standard pattern. Two inner classes, Request and Response, sit inside the action class:
public with sharing class GetOpenCasesAction {
public class Request {
@InvocableVariable(
label='Account Id'
description='The Salesforce Id of the account whose open cases should be listed'
required=true
)
public Id accountId;
@InvocableVariable(
label='Maximum Cases'
description='How many cases to include in the summary. Defaults to 5 if not provided'
)
public Integer maxCases;
}
// Response class and @InvocableMethod follow
}The same class can carry both input and output fields, but separate Request and Response classes keep the contract clear. The agent sees a field as an input or an output depending on where the class is used.
Rules for @InvocableVariable fields
The compiler and the platform enforce these rules:
- The field must be an instance member. A
staticfield is rejected. - The field must be
publicorglobal. - The class that contains it must be
publicorglobal, and an inner class must be a static-style inner class like the ones above, not an instance of another class. - The method's parameter must be a
Listof the wrapper type, and so must its return type if it returns anything. - An action class can contain only one
@InvocableMethod.
The annotation takes these attributes:
| Attribute | Purpose | Notes |
|---|---|---|
| `label` | Display name of the field | Defaults to the field name if omitted |
| `description` | Explains the field in plain language | The agent reads it. Chapter 4 covers writing it well |
| `required` | Marks an input as mandatory | Defaults to `false`. It matters only for inputs |
Supported types
You cannot use every Apex type in a wrapper field. These are the ones that work reliably for agent actions:
| Category | Types |
|---|---|
| Primitives | `Boolean`, `Date`, `Datetime`, `Decimal`, `Double`, `Id`, `Integer`, `Long`, `String`, `Time` |
| Records | A specific `SObject` type such as `Account` |
| Custom types | An Apex class that itself uses `@InvocableVariable` fields |
| Collections | A `List` of any type above |
Map and Set fields are not supported. Apex enums are not supported either, so represent a fixed set of choices as a String and say the allowed values in the description.
Prefer flat classes with primitive fields. Nested custom types and SObject fields are legal, but the agent has to fill them in, and language models do this less reliably than they fill a handful of scalar values. When an action needs a record, take its Id as input and query the record inside the method.
A complete example with several types
The next class uses a date, an integer, a boolean, and a string. It has no SOQL, so you can run it in anonymous Apex or a scratch org without data.
public with sharing class CalculateDueDateAction {
public class Request {
@InvocableVariable(
label='Start Date'
description='The date counting begins, in the user\'s local date'
required=true
)
public Date startDate;
@InvocableVariable(
label='Days To Add'
description='Number of days to add to the start date. Must be 1 or more'
required=true
)
public Integer daysToAdd;
@InvocableVariable(
label='Skip Weekends'
description='True to count only Monday to Friday. Defaults to false'
)
public Boolean skipWeekends;
}
public class Response {
@InvocableVariable(
label='Due Date'
description='The calculated due date, or empty if the input was not valid'
)
public Date dueDate;
@InvocableVariable(
label='Message'
description='A short sentence describing the result or the reason it failed'
)
public String message;
}
@InvocableMethod(
label='Calculate Due Date'
description='Adds a number of days to a start date, optionally skipping weekends'
category='Utilities'
)
public static List<Response> calculate(List<Request> requests) {
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response res = new Response();
if (r.startDate == null || r.daysToAdd == null || r.daysToAdd < 1) {
res.message = 'A start date and a positive number of days are required.';
} else {
Date current = r.startDate;
Integer remaining = r.daysToAdd;
while (remaining > 0) {
current = current.addDays(1);
if (r.skipWeekends == true && isWeekend(current)) {
continue;
}
remaining--;
}
res.dueDate = current;
res.message = 'Due date is ' + current.format() + '.';
}
responses.add(res);
}
return responses;
}
private static Boolean isWeekend(Date d) {
// 1900-01-07 was a Sunday, so the remainder is 0 for Sunday and 6 for Saturday
Integer day = Math.mod(Date.newInstance(1900, 1, 7).daysBetween(d), 7);
return day == 0 || day == 6;
}
}Three habits in this class carry over to every action:
- Test optional inputs against
null.skipWeekends == trueis safe when the agent leaves the field out. Writingif (r.skipWeekends)would throw a null-pointer error. - Add a response for every request. The loop adds one
ResponseperRequest, including invalid ones. The platform matches results to inputs by position, so a skipped entry shifts every later result. - Put the failure reason in an output field. The
messagefield gives the agent something it can tell the user.
Required versus optional inputs
Setting required=true tells Agent Builder that the agent must have a value before it calls the action. If the user has not provided one, the agent asks for it. This is the right choice for values the method cannot work without, such as the account Id in GetOpenCasesAction.
For other inputs, leave required off and apply a default in code. maxCases is optional, and the method uses 5 when it is null or less than 1. State that default in the description so the agent knows it can omit the field.
Designing the output
Output fields are what the agent reads when it composes its reply, so design them for a reader, not for another program.
- Return a count and a summary.
GetOpenCasesActionreturnscaseCountas anIntegerandsummaryas aString. The count lets the agent reason about quantity. The summary gives it text to quote. - Format values in Apex when the format matters. A
Dateis fine, but a currency amount with a currency code is clearer as a formattedString. - Keep the output small. Every field and every character of text goes into the agent's context. Return a limited number of lines and say so, as
maxCasesdoes, instead of returning every record. - Never leave a result silently empty. When nothing matches, set the text field to a sentence such as
No open cases were found for this account.An empty value forces the agent to guess what happened.
Outputs that you do not assign stay null, and the agent sees no value. The Response above sets dueDate only on success, and message in both cases, so one field is always populated.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Save fails with a message about the variable | Field is `static`, private, or has an unsupported type | Make it a public instance field with a supported type |
| Action is missing in Agent Builder | Wrapper class is not `public` or `global`, or there are two invocable methods in the class | Fix visibility and keep one `@InvocableMethod` per class |
| `System.NullPointerException` on an optional input | Method assumed the field was populated | Check for `null` before use |
| Agent shows the wrong result for a user | Response list is shorter than or out of order with the request list | Add exactly one response per request, in order |
| Agent asks for a value it should infer | Description is vague or the field is marked required | Improve the description, and make the field optional if a default exists |
Summary of the approach
- Create a
Requestclass for the values the agent must supply. Mark the essential onesrequired=true. - Create a
Responseclass with a small number of fields: a result, a count if useful, and a message. - Use supported types, and prefer primitives and
Idover nested objects. - Write a
labelanddescriptionon every field. The next chapter develops this. - In the method, treat every input as possibly
nulland return one response per request.
Exercise
An invocable method takes a List<Request> with 3 entries. Entry 2 has a null accountId, and your loop skips it with continue before building a response. What goes wrong, and how do you fix it?
Show answer
The method returns 2 responses for 3 requests. The platform matches responses to requests by position, so the response for entry 3 is paired with entry 2, and the third request has no result. The fix is to create a Response for every request, including invalid ones. For the null accountId, return a response with a message such as "An account Id is required." and leave the other fields at their defaults.
Exercise
You want an action to accept one of three statuses: "New", "Working", or "Closed". Apex enums are not supported in @InvocableVariable fields. What type do you use, and where do you tell the agent the allowed values?
Show answer
Use a String field. List the allowed values in the field's description, for example "One of New, Working, or Closed". Also validate the value in the method and return a clear message in the response if it is not one of the three.