Sub topic 9
Adding a custom action backed by Apex
Built-in actions cover common tasks. When the agent must read your own data or apply your own rules, you write a custom action. This chapter builds one from an invocable Apex method, deploys it from the CLI, and attaches it to a topic.
This chapter assumes you have already created an agent with sf agent create and that you can deploy to your org with sf project deploy start. You should know basic Apex, including SOQL and with sharing. You should also understand what a topic is in Agentforce.
How an Apex action reaches the agent
An agent never calls Apex directly. It chooses among the actions listed in the current topic, and each action is a metadata record that points at a target. For Apex, the target is a class with an @InvocableMethod.
The pieces are:
- The Apex class, which holds the logic and describes its inputs and outputs.
- An action definition, stored as
GenAiFunctionmetadata, which names the class as its invocation target. - A topic definition, stored as
GenAiPluginmetadata, which lists the actions the agent may use for that topic.
The agent's planner reads the action's name and description, plus the labels and descriptions of its inputs, and decides whether and when to call it. These text fields are how the agent "sees" your code, so they matter as much as the logic.
Writing the invocable method
An invocable method must be public static or global static. It takes one List parameter and may return a List. Each element of the input list is one call, so the method must handle several requests in a single invocation.
public with sharing class CaseStatusAction {
public class Request {
@InvocableVariable(
label='Case Number'
description='The case number, for example 00001026'
required=true
)
public String caseNumber;
}
public class Result {
@InvocableVariable(
label='Case Status'
description='Current status of the case, or Not found'
)
public String status;
}
@InvocableMethod(
label='Get Case Status'
description='Returns the status of a case from its case number'
)
public static List<Result> getStatus(List<Request> requests) {
Set<String> numbers = new Set<String>();
for (Request req : requests) {
numbers.add(req.caseNumber);
}
Map<String, String> statusByNumber = new Map<String, String>();
for (Case c : [
SELECT CaseNumber, Status
FROM Case
WHERE CaseNumber IN :numbers
WITH USER_MODE
]) {
statusByNumber.put(c.CaseNumber, c.Status);
}
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
res.status = statusByNumber.containsKey(req.caseNumber)
? statusByNumber.get(req.caseNumber)
: 'Not found';
results.add(res);
}
return results;
}
}This version differs from a one-query-per-request loop in three ways:
- It runs one SOQL query for the whole batch, so it stays under governor limits if the list grows.
- It adds
descriptiontext to each variable. Thelabelalone is often too thin for the planner. - It uses
WITH USER_MODE, so field-level security and object permissions of the running user apply.
The results list must have the same length and order as the requests. The platform matches outputs to inputs by position.
Writing the Apex test
Apex deployed to production needs test coverage. Write the test now so the class deploys cleanly later.
@IsTest
private class CaseStatusActionTest {
@IsTest
static void returnsStatusForExistingCase() {
Case c = new Case(Subject = 'Printer offline', Status = 'New', Origin = 'Web');
insert c;
c = [SELECT CaseNumber FROM Case WHERE Id = :c.Id];
CaseStatusAction.Request req = new CaseStatusAction.Request();
req.caseNumber = c.CaseNumber;
List<CaseStatusAction.Result> out = CaseStatusAction.getStatus(
new List<CaseStatusAction.Request>{ req }
);
System.assertEquals(1, out.size());
System.assertEquals('New', out[0].status);
}
@IsTest
static void returnsNotFoundForUnknownCase() {
CaseStatusAction.Request req = new CaseStatusAction.Request();
req.caseNumber = '99999999';
List<CaseStatusAction.Result> out = CaseStatusAction.getStatus(
new List<CaseStatusAction.Request>{ req }
);
System.assertEquals('Not found', out[0].status);
}
}Deploying the class from the CLI
Deploy only the class and its test, and run only that test. This keeps feedback fast.
sf project deploy start \
--source-dir force-app/main/default/classes \
--test-level RunSpecifiedTests \
--tests CaseStatusActionTest \
--target-org my-dev-orgTo run the test on its own against the org:
sf apex run test \
--class-names CaseStatusActionTest \
--result-format human \
--wait 10 \
--target-org my-dev-orgFix failures here, before involving the agent. A failing Apex method looks like a confusing agent failure later.
Defining the action as metadata
The action is a GenAiFunction file. In a source-format project it lives under force-app/main/default/genAiFunctions/. A minimal definition for the class above looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<GenAiFunction xmlns="http://soap.sforce.com/2006/04/metadata">
<description>Look up the current status of a support case by its case number.</description>
<invocationTarget>CaseStatusAction</invocationTarget>
<invocationTargetType>apex</invocationTargetType>
<isConfirmationRequired>false</isConfirmationRequired>
<masterLabel>Get Case Status</masterLabel>
</GenAiFunction>Save it as GetCaseStatus.genAiFunction-meta.xml. The file name, without the suffix, is the action's API name. That is the name you use in test specs as GetCaseStatus.
Treat this file as a starting point. Field names and extra fields, such as input and output schema entries, can vary by API version. If you are unsure, create the action once in Setup, retrieve it, and copy its structure:
sf project retrieve start \
--metadata GenAiFunction \
--target-org my-dev-orgThe retrieved file is the authority for your org's API version.
Attaching the action to a topic
An action the topic does not list is never offered to the agent. Topics are GenAiPlugin metadata. Add the function to the plugin's function list. The retrieved topic file shows the exact structure for your version. The relevant part is a reference to the action by API name:
<genAiFunctions>
<functionName>GetCaseStatus</functionName>
</genAiFunctions>Deploy the action and the topic together so the reference resolves:
sf project deploy start \
--metadata GenAiFunction:GetCaseStatus \
--metadata GenAiPlugin \
--target-org my-dev-orgDepending on how the topic was created, the agent definition may also need to be re-synced for it to see the change. Retrieve the agent metadata after deploying, check that the diff in Git matches what you expect, and commit.
Permissions
The agent runs as an agent user, and that user needs access to everything the action touches. Check three things:
- The agent user has a permission set that grants Apex class access to
CaseStatusAction. - That user has read access to
Caseand theStatusandCaseNumberfields. - Sharing rules let that user see the case records. A case the user cannot see returns
Not found, which looks like a logic bug but is a sharing result.
Verifying the action
Preview first, then test.
sf agent preview --api-name Case_Helper --target-org my-dev-orgAsk "What is the status of case 00001026?" using a case number that exists in your org. If the preview shows the action running, the wiring is correct. If the agent answers without calling it, work through the common causes:
| Symptom | Likely cause |
|---|---|
| The agent never calls the action | The action is not listed in the topic, or the topic is not selected |
| The agent asks for the wrong input | The variable description is vague or missing |
| The action runs and returns `Not found` | Wrong case number, or the agent user cannot see the record |
| Deploy fails on the function file | The class is not deployed yet, or the target name is misspelled |
| Deploy fails on coverage | The test class is missing or covers too little |
When preview behaves, lock it in with a test case that names the action:
testCases:
- utterance: What is the status of case 00001026?
expectedTopic: case_status
expectedActions:
- GetCaseStatus
expectedOutcome: The agent tells the user the current status of the case.Design guidelines
- Give each action one job. "Get Case Status" is easier for the planner to choose than a general "Case Tools" action.
- Write descriptions for the planner, not for developers. Say what the action returns and when to use it.
- Return a clear value for failure, such as
Not found, instead of throwing. The agent can then tell the user something sensible. - Set
isConfirmationRequiredtotruefor actions that change data. Read-only lookups usually do not need it. - Do not put secrets in descriptions or return values. Both can end up in the conversation.
Exercise
Your Apex action deploys and passes its tests, but the preview agent never calls it when you ask about a case. Name two metadata or permission checks you would make, and say what command helps you inspect the metadata.
Show answer
First, confirm the GenAiFunction is listed in the GenAiPlugin (topic) the agent selects, since an unlisted action is never offered. Second, confirm the agent user has access to the Apex class through a permission set, and read access to Case and its fields. Use sf project retrieve start --metadata GenAiFunction --target-org my-dev-org (and the same for GenAiPlugin) to see what the org actually holds, then compare it with your local files in Git. Also review the action and input descriptions, since vague text makes the planner skip the action.