Skip to main content
Version: 4.6.0

AiAgent

Configure an AI Agent using the Fluent API. This API provides a structured interface for creating AI Agents in ServiceNow's AI Agent Studio, automatically handling all underlying complexity and relationships between multiple tables.


Overview

The AiAgent API enables you to define intelligent agents that can:

  • Execute Tools: Use built-in or custom tools (CRUD, Script, RAG, Web Search, etc.)
  • Process Context: Apply custom scripts to transform context before execution
  • Control Access: Define role-based security and data access controls
  • Trigger Automatically: Configure triggers for automatic agent invocation
  • Manage Versions: Support multiple versions with different configurations

The plugin automatically generates all required ServiceNow records (~9 tables) with proper relationships and defaults.


Supported Record Types

Based on the metadata files generated by this plugin:

Record TypeTableDescription
AI Agentsn_aia_agentPrimary agent definition
AI Agent Configsn_aia_agent_configAgent configuration and settings
AI Agent Versionsn_aia_versionVersion information for the agent
AI Agent Toolsn_aia_toolTool definitions (script, CRUD, RAG, etc.)
AI Agent Tool M2Msn_aia_agent_tool_m2mMany-to-many relationship between agents and tools
Agent Access Role Configurationsys_agent_access_role_configurationRole-based data access controls
Trigger Configurationsn_aia_trigger_configurationAutomated trigger definitions
Trigger Agent Usecase M2Msn_aia_trigger_agent_usecase_m2mMapping between triggers, agents, and use cases

API Parameters

Main Configuration

Field NameTypeMandatoryDescription
$idNow.ID[string]YesUnique identifier for the agent
namestringYesDisplay name of the AI Agent
descriptionstringYesBrief description of what the agent does
agentRolestringYesRole or purpose of the agent (e.g., "News research specialist")
securityAclSecurityAclUserAccessConfigYesMANDATORY - Automatically generates sys_security_acl and sys_security_acl_role records. Defines user access controls and role-based permissions for this agent
activebooleanNoWhether the agent is active (default: true)
advancedModebooleanNoEnables advanced configuration options for power users (default: false)
agentConfigSysOverridesstring | Record<'sn_aia_agent_config'>NoReference to override another agent config
agentLearningbooleanNoEnable agent learning from interactions (default: false)
agentTypeAiAgentAgentTypeNoType: 'internal', 'external', 'voice', or 'aia_internal' (default: 'internal')
channelAiAgentChannelTypeNoChannel: 'nap' (Now Assist Panel) or 'nap_and_va' (Panel + Virtual Agent) (default: 'nap_and_va')
compiledHandbookstringNoCompiled handbook content for the agent
conditionstringNoCondition table reference
contextProcessingScript((context: any, ...dependencies: any[]) => any) | stringNoServer-side script that transforms or enriches context before agent execution
dataAccessDataAccessConfigTypeNoData access controls (required if runAsUser not set)
docUrlstringNoDocumentation URL for the agent
externalbooleanNoWhether the agent is external
externalAgentConfigurationstring | Record<'sn_aia_external_agent_configuration'>NoReference to external agent configuration
iconUrlstringNoIcon URL for the agent in the UI
memoryCategoriesAiAgentMemoryCategory[]NoCategories of long-term memory the agent may access: 'device_and_software', 'meetings_and_events', 'projects', 'workplace'
parentstring | Record<'sn_aia_agent'>NoReference to the parent AI Agent
postProcessingMessagestringNoMessage displayed after agent completes
processingMessagestringNoMessage displayed while agent is processing
publicbooleanNoWhether the agent is publicly accessible (default: false)
recordTypeAiAgentRecordTypeNoLifecycle stage: 'template', 'aia_internal', 'custom', or 'promoted' (default: 'template')
runAsUserstring | Record<'sys_user'>NoUser to run the agent as (sys_user sys_id or Record reference). When set, dataAccess is optional
sourceIdstring | Record<'sn_aia_agent'>NoReference to source agent (for cloned agents)
sysDomainstringNoDomain ID
toolsAiAgentToolDetailsType[]NoArray of tools the agent can use
triggerConfigAiAgentTriggerConfigType[]NoArray of trigger configurations for automatic invocation
versionDetailsAiAgentVersionDetailsType[]NoArray of version details with instructions

Version Details (versionDetails)

Version information for the agent. This is an array that can contain multiple versions.

Key Fields:

  • name — Version name (e.g., "V1", "V2", "Production")
  • number — Version number (e.g., 1, 2, 3)
  • state — Version state: 'draft', 'committed', 'published', or 'withdrawn'
  • instructionsMost important field — Detailed instructions that guide the agent's behavior, capabilities, and decision-making process
  • condition — Optional condition for when this version should be used

Data Access Controls (dataAccess)

MANDATORY when runAsUser is not set - Defines which roles the agent can inherit from the invoking user during execution.

When to Use:

  • Use dataAccess when you want the agent to run with dynamic user identity (inheriting roles from the invoking user)
  • Omit dataAccess when runAsUser is set to a specific user sys_id

Security ACL Configuration (securityAcl)

MANDATORY - Automatically generates sys_security_acl and sys_security_acl_role records for this agent. Controls who can invoke the agent.

Access Types

'Any authenticated user' — Any logged-in user can invoke this agent. No roles required.

'Specific role' — Only users who hold at least one of the listed roles can access. roles is required.

'Public' — No authentication required. Anyone can access.

Important Notes:

  • securityAcl controls who can invoke the agent (access control)
  • runAsUser / dataAccess controls which user identity the agent runs under (execution context) — these are separate concerns
  • The plugin automatically creates sys_security_acl and sys_security_acl_role records
  • The ACL name is derived from the agent's internal name: {domain}.{scope}.{agentName}

Tools (tools)

Tools allow agents to perform actions during execution. The type field acts as a discriminator — required fields differ per tool type.

Tool Types

Each tool type uses a discriminated union on the type field:

typeRequired extra fieldDescription
'crud'inputs: ToolInputTypeDatabase CRUD operations (script is auto-generated)
'script'scriptCustom server-side script
'capability'capabilityIdNow Assist skill
'subflow'subflowIdFlow Designer flow
'action'flowActionIdFlow Designer action
'catalog'catalogItemIdService Catalog item
'topic'virtualAgentIdVirtual Agent topic
'topic_block'virtualAgentIdVirtual Agent topic block
'web_automation'(none)OOB Web Search tool
'knowledge_graph'(none)OOB Knowledge Graph tool
'file_upload'(none)OOB File Uploader tool
'rag'(none)OOB RAG Search Retrieval tool
'deep_research'(none)Deep Research tool
'desktop_automation'(none)Desktop Automation tool
'mcp'(none)MCP tool

Note: For script tools, inputs is a simple array of ToolInputField. For CRUD tools, inputs is a ToolInputType object. The SDK auto-generates the input_schema from inputs.


Trigger Configuration (triggerConfig)

Configure automatic agent invocation based on record changes or schedules.

Trigger Types

Trigger TypeDescription
record_createTriggers when a new record is created
record_create_or_updateTriggers when a record is created or updated
record_updateTriggers when an existing record is updated
emailTriggers based on email events
scheduledTriggers at scheduled intervals
dailyTriggers daily at a specified time
weeklyTriggers weekly on a specified day
monthlyTriggers monthly on a specified day

Complete Example

Below example shows all the different configurations for an AI agent. It has different types of triggers supported and different types of tools supported.

import { AiAgent } from '@servicenow/sdk/core';

export const newsCollectorAgent = AiAgent({
$id: Now.ID['news_collector_agent'],
name: 'News Collector Agent',
description: 'AI agent that searches for and saves news articles',
agentRole: 'News research specialist',

// Core properties
recordType: 'custom',
channel: 'nap_and_va',
processingMessage: 'Searching for news...',
postProcessingMessage: 'News collection completed',
active: true,
public: false,

// Version details with instructions
versionDetails: [
{
name: 'V1',
number: 1,
state: 'published',
instructions: `You are a news collection specialist. Your job is to:

1. Search the web for the latest news articles using the Web Search tool
2. Analyze and extract relevant information from search results
3. Save articles to the database using the Save Article tool
4. Provide a comprehensive summary of findings

Guidelines:
- Focus on recent and credible news sources
- Extract key information: title, content, source, and publication date
- Verify information accuracy before saving
- Organize results by topic and relevance`,
}
],

// Security ACL — controls who can invoke this agent
securityAcl: {
$id: Now.ID['news_collector_agent_acl'],
type: 'Specific role',
roles: [
'282bf1fac6112285017366cb5f867469', // itil role sys_id
'b05926fa0a0a0aa7000130023e0bde98', // user role sys_id
],
},

// Data access — controls which roles the agent can inherit from the invoking user
dataAccess: {
roleList: [
'282bf1fac6112285017366cb5f867469',
'b05926fa0a0a0aa7000130023e0bde98',
],
description: 'Role-based access for news collection',
},

// Tools
tools: [
// OOB Web Search tool
{
name: 'Web Search',
description: 'Searches the web for latest news articles',
type: 'web_automation',
executionMode: 'autopilot',
maxAutoExecutions: 5,
displayOutput: true,
outputTransformationStrategy: 'paraphrase',
preMessage: 'Searching the web for news...',
postMessage: 'Search completed',
},
// Custom CRUD tool to save articles
{
name: 'Save Article',
description: 'Saves a news article to the database',
type: 'crud',
recordType: 'custom',
executionMode: 'autopilot',
maxAutoExecutions: 10,
displayOutput: true,
outputTransformationStrategy: 'summary',
preMessage: 'Saving article...',
postMessage: 'Article saved successfully',
inputs: {
operationName: 'create',
table: 'x_my_app_news_articles',
inputFields: [
{
name: 'title',
description: 'Article title',
mandatory: true,
mappedToColumn: 'title',
type: 'string',
},
{
name: 'content',
description: 'Article content',
mandatory: false,
mappedToColumn: 'content',
type: 'string',
},
{
name: 'source_url',
description: 'Source URL',
mandatory: false,
mappedToColumn: 'source_url',
type: 'url',
},
],
returnFields: [
{ name: 'sys_id' },
{ name: 'title' },
{ name: 'number' },
],
},
},
// Custom script tool
{
name: 'Validate Tweet Data',
description: 'Validates tweet content and enriches it with metadata',
type: 'script',
executionMode: 'autopilot',
displayOutput: true,
outputTransformationStrategy: 'summary',
preMessage: 'Validating tweet data...',
postMessage: 'Validation completed',
// Script content — use module import (preferred) or Now.include() for legacy scripts
script: validateTweetData,
// Input fields for script tools (simple array)
inputs: [
{
name: 'content',
description: 'The tweet content to validate',
mandatory: true,
value: '',
invalidMessage: null,
},
],
}
],

// Triggers
triggerConfig: [
// Record-based trigger
{
name: 'News Collection Trigger',
channel: 'Now Assist Panel',
objectiveTemplate: 'Collect latest news for topic: ${topic_name}',
description: 'Triggers when high-priority topics are created or updated',
active: true,
targetTable: 'x_my_app_news_topics',
triggerFlowDefinitionType: 'record_create_or_update',
triggerCondition: 'active=true^priority=high',
showNotifications: true,
enableDiscovery: false,
domain: 'global',
},
// Scheduled trigger
{
name: 'Daily News Summary Trigger',
channel: 'Now Assist Panel',
objectiveTemplate: 'Generate daily news summary report',
description: 'Runs daily at 8:00 AM to collect and summarize news',
active: true,
triggerFlowDefinitionType: 'daily',
schedule: {
time: '1970-01-01 08:00:00', // Run at 8:00 AM
triggerStrategy: 'every',
},
showNotifications: false,
domain: 'global',
},
],
});

Best Practices

1. Security Configuration

  • Always set securityAcl — it is mandatory and auto-generates the sys_security_acl record
  • securityAcl.type controls who can invoke the agent: 'Any authenticated user', 'Specific role', or 'Public'
  • securityAcl.$id is required — it identifies the generated ACL record
  • runAsUser is separate: it controls which user identity the agent runs under (not who can invoke it)
  • Use dataAccess.roleList when runAsUser is not set, to restrict which roles the agent can inherit from the invoking user
  • Set runAsUser to a specific user sys_id to always run as that user regardless of who invokes the agent

2. Tool Configuration

  • Always set type for all tools to specify the tool type
  • Use type-specific ID fields (e.g., capabilityId for capabilities, subflowId for subflows)
  • For script tools: Use a simple array of ToolInputField for inputs
  • For CRUD tools: Use a ToolInputType object for inputs with operation details
  • Use recordType: 'custom' for custom tools
  • Separate overrides: Use sysOverrides for the tool record, m2mSysOverrides for the M2M record
  • Input schema is auto-generated: Don't manually specify inputSchema — it's generated from inputs

3. Version Management

  • Start with state: 'draft' for testing
  • Use state: 'published' for production
  • Increment number for new versions
  • Use meaningful name (e.g., "V1", "V2")

4. Trigger Configuration

  • channel and objectiveTemplate are required fields on every trigger
  • Use specific triggerCondition to avoid unnecessary invocations
  • Set triggerStrategy: 'every' for all matching records
  • Set triggerStrategy: 'once' for one-time execution
  • For scheduled triggers use schedule (nested object) to configure time/interval/strategy
  • Use sysOverrides to override the trigger configuration record; use m2mSysOverrides to override the trigger-agent-usecase M2M mapping

5. Script Fields

  • Use module imports for server-side script files (or Now.include for legacy scripts)
  • Keep scripts concise and focused
  • Handle errors gracefully in scripts
  • Return proper status from tool scripts

Common Patterns

Pattern 1: Agent with Dynamic User Identity

AiAgent({
$id: Now.ID['dynamic_agent'],
name: 'Dynamic Agent',
description: 'Agent with dynamic user identity',
agentRole: 'Dynamic assistant',
securityAcl: { $id: Now.ID['dynamic_agent_acl'], type: 'Any authenticated user' },
versionDetails: [
{
name: 'V1',
number: 1,
state: 'published',
instructions: 'Assist users with their tasks...',
}
],
// No runAsUser set = dynamic user identity
dataAccess: {
roleList: ['itil_role_sys_id'], // MANDATORY when runAsUser not set
},
})

Pattern 2: Agent with Fixed User Identity

AiAgent({
$id: Now.ID['fixed_agent'],
name: 'Fixed Agent',
description: 'Agent with fixed user identity',
agentRole: 'System assistant',
securityAcl: { $id: Now.ID['fixed_agent_acl'], type: 'Any authenticated user' },
runAsUser: '82ef6be43bc7a2103542c11f23e45a61', // Specific user sys_id
versionDetails: [
{
name: 'V1',
number: 1,
state: 'published',
instructions: 'Perform system tasks...',
}
],
// dataAccess is omitted — not needed when runAsUser is set
})

Troubleshooting

Tools Not Appearing in Agent

Problem: Tools are generated as separate files but not linked to the agent.

Solution:

  • Ensure type is set for all tools
  • For script tools, use array of ToolInputField for inputs
  • For CRUD tools, use ToolInputType object for inputs
  • Check that type-specific ID fields are set correctly (e.g., capabilityId, subflowId)

Data Access Validation Error

Problem: Error: "dataAccess.roleList is mandatory when runAsUser is not set"

Solution:

  • Either set runAsUser to a user sys_id
  • Or provide dataAccess.roleList with at least one role

Trigger Not Firing

Problem: Trigger configured but agent not invoked automatically.

Solution:

  • Verify triggerConfig.active is true
  • Ensure channel and objectiveTemplate are set (both required)
  • Check triggerCondition matches your records
  • Ensure targetTable is correct
  • For scheduled triggers, verify the schedule object is correctly configured

Script Fields Not Working

Problem: Scripts showing as [object Object] or not executing.

Solution:

  • Use string format for scripts: `(function() { ... })()`
  • Or use function format: (inputs) => { ... }
  • Ensure CDATA tags are NOT manually added (handled automatically)

Table Schema

sn_aia_agent

Column NameTypeMandatoryDefault ValueDescription
advanced_modeTrue/FalseFALSEfalseWhether advanced mode is enabled
agent_typeChoiceFALSEinternalType of agent (internal/external/voice/aia_internal)
channelChoiceFALSEnap_and_vaChannel where agent operates
compiled_handbookStringFALSECompiled handbook content
conditionConditionsFALSECondition table reference
context_processing_scriptScriptFALSEjavascript:sn_aia.AiAgentContexts.AGENT_CONTEXT_PROCESSING_SCRIPT_TEMPLATE;Script for processing context
descriptionTranslated TextTRUEDescription of the agent
external_agent_configurationReferenceFALSEReference to external agent config
nameTranslated TextTRUEDisplay name of the agent
parentReferenceFALSEReference to parent agent
post_processing_messageTranslated TextFALSEMessage shown after processing
processing_messageTranslated TextFALSEMessage shown during processing
record_typeChoiceFALSEcustomRecord type (template/custom etc.)
roleTranslated TextFALSERole/purpose of the agent
source_idReferenceFALSEReference to source agent
sys_domainDomain IDFALSEDomain identifier

sn_aia_agent_config

Column NameTypeMandatoryDefault ValueDescription
activeTrue/FalseFALSEtrueWhether the configuration is active
agentReferenceFALSEReference to the AI Agent
agent_learningTrue/FalseFALSEfalseWhether agent learning is enabled
doc_urlURLFALSEDocumentation URL
icon_urlURLFALSEIcon URL
publicTrue/FalseFALSEfalseWhether the configuration is public
run_as_userReferenceFALSEUser to run the agent as
sys_domainDomain IDFALSEDomain identifier
sys_overridesReferenceFALSEReference to override configuration

sn_aia_version

Column NameTypeMandatoryDefault ValueDescription
conditionCondition StringFALSECondition for version activation
instructionsTranslated TextFALSEVersion-specific instructions
stateChoiceFALSEdraftState of the version (draft/published etc.)
sys_domainDomain IDFALSEglobalDomain identifier
sys_overridesReferenceFALSEReference to override version
target_idDocument IDFALSEReference to target record
target_tableTable NameFALSEName of the target table
version_nameTranslated TextFALSEDisplay name of the version
version_numberIntegerFALSEVersion number

sn_aia_tool

Column NameTypeMandatoryDefault ValueDescription
activeTrue/FalseFALSEtrueWhether the tool is active
descriptionStringTRUEDescription of the tool
input_schemaJSONFALSEJSON schema defining tool inputs (auto-generated)
nameStringTRUEName of the tool
record_typeChoiceFALSEcustomRecord type (custom/template etc.)
scriptScriptFALSETool implementation script
sys_domainDomain IDFALSEDomain identifier
sys_overridesReferenceFALSEReference to override tool
target_documentDocument IDFALSETarget document reference
target_document_tableTable NameFALSETarget document table name
typeChoiceFALSEType of tool (crud/script etc.)

sn_aia_agent_tool_m2m

Column NameTypeMandatoryDefault ValueDescription
activeTrue/FalseFALSEtrueWhether the tool mapping is active
agentReferenceTRUEReference to the AI Agent
descriptionStringFALSEDescription of the tool usage
display_outputTrue/FalseFALSEtrueWhether to display tool output
document_statusChoiceFALSEStatus of document processing
execution_modeChoiceFALSEcopilotMode of execution (copilot/autopilot)
inputsJSONFALSEInput parameters for the tool
max_auto_executionsIntegerFALSE10Maximum automatic executions
nameStringTRUEName of the tool mapping
output_transformation_strategyChoiceFALSEnoneStrategy for transforming output
post_messageTranslated TextFALSEMessage shown after execution
post_processing_scriptScriptFALSEjavascript:AiAgentConstants.SCRIPT_TEMPLATEPost-processing script
pre_messageTranslated TextFALSEMessage shown before execution
pre_runTrue/FalseFALSEfalseWhether to run before other tools
sys_domainDomain IDFALSEDomain identifier
sys_overridesReferenceFALSEReference to override mapping
timeoutIntegerFALSETimeout duration in seconds
toolReferenceTRUEReference to the tool
tool_attributesJSONFALSE{}Additional tool attributes
transformation_instructionStringFALSEInstructions for transformation
widgetsListFALSEAssociated widgets

sys_agent_access_role_configuration

Column NameTypeMandatoryDefault ValueDescription
actionChoiceTRUElimit_to_rolesAction to perform for access control
agentDocument IDTRUEReference to the AI Agent
agent_tableTable NameTRUETable name of the agent (sn_aia_agent)
allow_all_session_rolesTrue/FalseFALSEfalseWhether to allow all session roles
descriptionStringFALSEDescription of the access configuration
nameStringFALSEName of the configuration (auto-set to agent sys_id)
role_listListFALSEList of roles for access control

For guidance on building and configuring AI agents end-to-end, see the building-ai-agents-guide topic.