> For a complete index of all SignalWire documentation pages, fetch https://signalwire.com/docs/llms.txt

# AgentBase

> The central class for building AI-powered voice agents with SignalWire.

[ai]: /docs/swml/reference/ai

[swml-reference]: /docs/swml/reference/ai

[agentserver]: /docs/server-sdks/reference/typescript/agents/agent-server

[swmlservice]: /docs/server-sdks/reference/typescript/agents/swml-service

[setnativefunctions]: /docs/server-sdks/reference/typescript/agents/agent-base/native-functions

[ref-datamap]: /docs/server-sdks/reference/typescript/agents/data-map

`AgentBase` is the central class in the SignalWire Server SDK. It provides a
complete framework for building AI-powered voice agents, combining prompt management,
tool definitions, skill loading, speech configuration, and web serving into a single
composable interface.

`AgentBase` extends [`SWMLService`][swmlservice], inheriting its SWML document
serving and SWAIG tool registry (the `/swaig` endpoint and tool registration/
dispatch live on `SWMLService`). On top of that, `AgentBase` uses
**composition** internally, assembling functionality from `PromptManager`,
`SwmlBuilder`, `SessionManager`, `ContextBuilder`, and `SkillManager`. All setter
methods return `this` for fluent method chaining.

AgentBase generates a SWML document with the [`ai`][ai] verb.
See the [SWML reference][swml-reference] for the full specification of all
supported parameters and behaviors.

## **Constructor**

```typescript {3}
import { AgentBase } from '@signalwire/sdk';

const agent = new AgentBase({
  name: 'support',
  route: '/support',
});
```

### Constructor Parameters

**`name`** `string` — required

Display name of the agent. Used in logging, SIP username mapping, and the default
prompt fallback.

---

**`route`** `string` — default: /

HTTP route path where this agent is served. Used by
[`AgentServer`][agentserver] when hosting multiple agents on one process.

---

**`host`** `string` — default: 0.0.0.0

Network interface the HTTP server binds to.

---

**`port`** `number`

Port the HTTP server listens on. Defaults to the `PORT` environment variable,
falling back to `3000`.

---

**`basicAuth`** `[string, string]`

Explicit `[username, password]` tuple for HTTP Basic Auth on all endpoints. If not
set, credentials are read from `SWML_BASIC_AUTH_USER` / `SWML_BASIC_AUTH_PASSWORD`
env vars, or auto-generated on startup.

---

**`usePom`** `boolean` — default: true

Enable Prompt Object Model for structured prompt building. Set to `false` to use
plain text prompts only.

---

**`tokenExpirySecs`** `number` — default: 3600

Expiration time in seconds for SWAIG function authentication tokens.

---

**`autoAnswer`** `boolean` — default: true

Automatically add an `answer` verb before the AI verb in the SWML document.

---

**`recordCall`** `boolean` — default: false

Enable call recording. When `true`, a `record_call` verb is added to the SWML document.

---

**`recordFormat`** `string` — default: mp4

Recording file format. Common values: `"mp4"`, `"wav"`.

---

**`recordStereo`** `boolean` — default: true

Record in stereo (separate channels for each party) when `true`.

---

**`defaultWebhookUrl`** `string`

Base URL for SWAIG function webhooks. If not set, the SDK auto-detects from the
incoming request or uses `SWML_PROXY_URL_BASE`.

---

**`nativeFunctions`** `string[]`

List of native SWAIG function names to enable at construction time (e.g.,
`["check_time", "wait_for_user"]`). Can also be set later via
[`setNativeFunctions()`][setnativefunctions].

---

**`agentId`** `string`

Unique identifier for this agent instance. Auto-generated as a random hex string
if not provided.

---

**`suppressLogs`** `boolean`

Suppress SDK log output. Useful in testing or when integrating with external logging.

---

**`enablePostPromptOverride`** `boolean` — default: false

When `true`, register the `/post_prompt_override` route allowing external callers to
replace the post-prompt text at runtime.

---

**`checkForInputOverride`** `boolean` — default: false

When `true`, register the `/check_for_input` route allowing external callers to inject
input checks at runtime.

---

**`configFile`** `string`

Path to a JSON configuration file. When provided, its `service` section supplies
defaults for `name`, `route`, `host`, and `port`. Constructor arguments still take
precedence over file values.

---

**`schemaPath`** `string`

Path to a custom SWML JSON Schema file used for validation. Falls back to the built-in
schema when omitted.

---

**`schemaValidation`** `boolean` — default: true

Enable SWML schema validation on rendered documents. Can also be disabled via
`SWML_SKIP_SCHEMA_VALIDATION` env var.

---

**`signingKey`** `string`

SignalWire Signing Key used to verify inbound webhook signatures. When set,
the agent auto-mounts webhook signature validation middleware on `POST /`,
`/swaig`, and `/post_prompt` — unsigned or mis-signed requests receive a `403`.
Falls back to the `SIGNALWIRE_SIGNING_KEY` environment variable. When both are
unset, validation is disabled and a one-time startup warning is emitted. Treat
this value as a secret.

---

**`webhookTrustProxy`** `boolean` — default: false

When `true`, the webhook validation middleware honors `X-Forwarded-Proto` and
`X-Forwarded-Host` when reconstructing the public URL for signature
verification. Defaults to `false` because those proxy headers are spoofable.
`SWML_PROXY_URL_BASE` always takes precedence.

---

## **Properties**

**`name`** `string`

The agent's display name. Set at construction time.

---

**`route`** `string`

HTTP route path where this agent is served.

---

**`host`** `string`

Network interface the HTTP server binds to.

---

**`port`** `number`

Port the HTTP server listens on.

---

**`agentId`** `string`

Unique identifier for this agent instance.

---

## **Static Members**

**`PROMPT_SECTIONS`** `Array<{ title: string; body?: string; bullets?: string[]; numbered?: boolean }>`

Class-level attribute. Subclasses can set this to declaratively define prompt sections
instead of calling `promptAddSection()` in the constructor.

---

## **Examples**

### Basic agent with a tool

```typescript {3}
import { AgentBase, FunctionResult } from '@signalwire/sdk';

const agent = new AgentBase({ name: 'support-agent', route: '/support' });

agent.addLanguage({ name: 'English', code: 'en-US', voice: 'rime.spore' });
agent.setPromptText('You are a friendly customer support agent.');
agent.addHints(['SignalWire', 'SWML', 'SWAIG']);
agent.setParams({ temperature: 0.7, end_of_speech_timeout: 1000 });

agent.defineTool({
  name: 'check_order',
  description: 'Look up the status of a customer order',
  parameters: {
    type: 'object',
    properties: {
      order_id: { type: 'string', description: 'The order ID to look up' },
    },
  },
  required: ['order_id'],
  handler: async (args) => {
    const orderId = args.order_id;
    return new FunctionResult(`Order ${orderId} shipped on March 28.`);
  },
});

await agent.run();
```

### Subclass with declarative prompt sections

```typescript {3}
import { AgentBase, FunctionResult } from '@signalwire/sdk';

class SupportAgent extends AgentBase {
  static override PROMPT_SECTIONS = [
    {
      title: 'Role',
      body: 'You are a customer support agent for Acme Corp.',
    },
    {
      title: 'Guidelines',
      bullets: ['Be polite and professional', 'Escalate billing disputes'],
    },
  ];

  protected override defineTools(): void {
    this.defineTool({
      name: 'transfer_call',
      description: 'Transfer the caller to a live agent',
      handler: async () => {
        return new FunctionResult('Transferring now.').connect('+15551234567');
      },
    });
  }
}

const agent = new SupportAgent({ name: 'support', route: '/support' });
await agent.run();
```

## **Methods**

#### [addAnswerVerb](/docs/server-sdks/reference/typescript/agents/agent-base/add-answer-verb)

Configure the answer verb that connects the call.

#### [addFunctionInclude](/docs/server-sdks/reference/typescript/agents/agent-base/add-function-include)

Add a remote function include to the SWAIG configuration.

#### [addHint](/docs/server-sdks/reference/typescript/agents/agent-base/add-hint)

Add a single speech recognition hint to improve transcription accuracy.

#### [addHints](/docs/server-sdks/reference/typescript/agents/agent-base/add-hints)

Add multiple speech recognition hints at once.

#### [addInternalFiller](/docs/server-sdks/reference/typescript/agents/agent-base/add-internal-filler)

Add filler phrases for a specific function and language.

#### [addLanguage](/docs/server-sdks/reference/typescript/agents/agent-base/add-language)

Add a language configuration with voice settings for multilingual conversations.

#### [addMcpServer](/docs/server-sdks/reference/typescript/agents/agent-base/add-mcp-server)

Add an external MCP server for tool discovery and invocation.

#### [addPatternHint](/docs/server-sdks/reference/typescript/agents/agent-base/add-pattern-hint)

Add a speech recognition hint with pattern matching and replacement.

#### [addPostAiVerb](/docs/server-sdks/reference/typescript/agents/agent-base/add-post-ai-verb)

Add a SWML verb to run after the AI conversation ends.

#### [addPostAnswerVerb](/docs/server-sdks/reference/typescript/agents/agent-base/add-post-answer-verb)

Add a SWML verb to run after the call is answered but before the AI starts.

#### [addPreAnswerVerb](/docs/server-sdks/reference/typescript/agents/agent-base/add-pre-answer-verb)

Add a SWML verb to run before the call is answered.

#### [addPronunciation](/docs/server-sdks/reference/typescript/agents/agent-base/add-pronunciation)

Add a pronunciation rule to correct how the AI speaks a specific word or phrase.

#### [addSkill](/docs/server-sdks/reference/typescript/agents/agent-base/add-skill)

Load and activate a skill on the agent.

#### [addSkillByName](/docs/server-sdks/reference/typescript/agents/agent-base/add-skill-by-name)

Look up a skill class in the global registry and add it by name.

#### [removeSkillByName](/docs/server-sdks/reference/typescript/agents/agent-base/remove-skill-by-name)

Remove every skill instance matching a given name.

#### [resetContexts](/docs/server-sdks/reference/typescript/agents/agent-base/reset-contexts)

Clear every context from the agent's ContextBuilder.

#### [getPromptPom](/docs/server-sdks/reference/typescript/agents/agent-base/get-prompt-pom)

Return the current POM-structured prompt.

#### [setPromptPom](/docs/server-sdks/reference/typescript/agents/agent-base/set-prompt-pom)

Replace the prompt with the supplied POM array.

#### [setPronunciations](/docs/server-sdks/reference/typescript/agents/agent-base/set-pronunciations)

Replace every pronunciation rule in a single call.

#### [setInternalFillers](/docs/server-sdks/reference/typescript/agents/agent-base/set-internal-fillers)

Set every internal-filler entry in one call.

#### [setFunctionIncludes](/docs/server-sdks/reference/typescript/agents/agent-base/set-function-includes)

Replace the SWAIG function-includes list.

#### [autoMapSipUsernames](/docs/server-sdks/reference/typescript/agents/agent-base/auto-map-sip-usernames)

Auto-register the agent's route as the SIP username target.

#### [validateToolToken](/docs/server-sdks/reference/typescript/agents/agent-base/validate-tool-token)

Validate a per-tool HMAC token.

#### [clearSwaigQueryParams](/docs/server-sdks/reference/typescript/agents/agent-base/clear-swaig-query-params)

Remove every SWAIG query-param override.

#### [enableDebugRoutes](/docs/server-sdks/reference/typescript/agents/agent-base/enable-debug-routes)

Expose the agent's debug HTTP endpoints.

#### [addSwaigQueryParams](/docs/server-sdks/reference/typescript/agents/agent-base/add-swaig-query-params)

Append query parameters to all SWAIG webhook URLs.

#### [asRouter](/docs/server-sdks/reference/typescript/agents/agent-base/as-router)

Get the agent's Hono app for mounting as a sub-router.

#### [clearPostAiVerbs](/docs/server-sdks/reference/typescript/agents/agent-base/clear-post-ai-verbs)

Remove all post-AI verbs from the call flow.

#### [clearPostAnswerVerbs](/docs/server-sdks/reference/typescript/agents/agent-base/clear-post-answer-verbs)

Remove all post-answer verbs from the call flow.

#### [clearPreAnswerVerbs](/docs/server-sdks/reference/typescript/agents/agent-base/clear-pre-answer-verbs)

Remove all pre-answer verbs from the call flow.

#### [defineContexts](/docs/server-sdks/reference/typescript/agents/agent-base/define-contexts)

Define multi-step conversation contexts and workflows.

#### [defineTool](/docs/server-sdks/reference/typescript/agents/agent-base/define-tool)

Define a SWAIG tool that the AI can invoke during conversations.

#### [defineTypedTool](/docs/server-sdks/reference/typescript/agents/agent-base/define-typed-tool)

Define a tool with a typed handler and automatic schema inference.

#### [defineTools](/docs/server-sdks/reference/typescript/agents/agent-base/define-tools)

Override hook that registers tools during construction.

#### [enableDebugEvents](/docs/server-sdks/reference/typescript/agents/agent-base/enable-debug-events)

Enable real-time debug event webhooks from the AI module during calls.

#### [enableMcpServer](/docs/server-sdks/reference/typescript/agents/agent-base/enable-mcp-server)

Expose the agent's tools as an MCP server endpoint.

#### [enableSipRouting](/docs/server-sdks/reference/typescript/agents/agent-base/enable-sip-routing)

Enable SIP-based call routing for this agent.

#### [extractSipUsername](/docs/server-sdks/reference/typescript/agents/agent-base/extract-sip-username)

Extract a SIP username from a request body (static method).

#### [getApp](/docs/server-sdks/reference/typescript/agents/agent-base/get-app)

Get the Hono application instance.

#### [getBasicAuthCredentials](/docs/server-sdks/reference/typescript/agents/agent-base/get-basic-auth-credentials)

Retrieve the agent's Basic Auth credentials and their origin.

#### [getFullUrl](/docs/server-sdks/reference/typescript/agents/agent-base/get-full-url)

Get the full URL for this agent's endpoint.

#### [getMcpServers](/docs/server-sdks/reference/typescript/agents/agent-base/get-mcp-servers)

Get the list of configured MCP servers.

#### [getName](/docs/server-sdks/reference/typescript/agents/agent-base/get-name)

Get the agent's display name.

#### [getPostPrompt](/docs/server-sdks/reference/typescript/agents/agent-base/get-post-prompt)

Retrieve the current post-prompt text.

#### [getPrompt](/docs/server-sdks/reference/typescript/agents/agent-base/get-prompt)

Retrieve the current rendered prompt text.

#### [getRegisteredTools](/docs/server-sdks/reference/typescript/agents/agent-base/get-registered-tools)

Get summaries of all registered tools.

#### [getTool](/docs/server-sdks/reference/typescript/agents/agent-base/get-tool)

Look up a registered tool by name.

#### [handleMcpRequest](/docs/server-sdks/reference/typescript/agents/agent-base/handle-mcp-request)

Handle an MCP JSON-RPC 2.0 request.

#### [hasSkill](/docs/server-sdks/reference/typescript/agents/agent-base/has-skill)

Check whether a specific skill is currently loaded.

#### [isMcpServerEnabled](/docs/server-sdks/reference/typescript/agents/agent-base/is-mcp-server-enabled)

Check if the MCP server endpoint is enabled.

#### [listSkills](/docs/server-sdks/reference/typescript/agents/agent-base/list-skills)

List all currently loaded skills.

#### [manualSetProxyUrl](/docs/server-sdks/reference/typescript/agents/agent-base/manual-set-proxy-url)

Manually set the proxy URL base for webhook callbacks.

#### [setNativeFunctions](/docs/server-sdks/reference/typescript/agents/agent-base/native-functions)

Set the list of native platform functions.

#### [onDebugEvent](/docs/server-sdks/reference/typescript/agents/agent-base/on-debug-event)

Lifecycle hook for debug events received at /debug\_events.

#### [onFunctionCall](/docs/server-sdks/reference/typescript/agents/agent-base/on-function-call)

Pre-execution hook called before each SWAIG function invocation.

#### [onSummary](/docs/server-sdks/reference/typescript/agents/agent-base/on-summary)

Handle post-prompt summaries generated after a conversation ends.

#### [onSwmlRequest](/docs/server-sdks/reference/typescript/agents/agent-base/on-swml-request)

Lifecycle hook called on every SWML request before rendering.

#### [promptAddSection](/docs/server-sdks/reference/typescript/agents/agent-base/prompt-add-section)

Add a new section to the agent's structured prompt.

#### [promptAddSubsection](/docs/server-sdks/reference/typescript/agents/agent-base/prompt-add-subsection)

Add a subsection to an existing prompt section.

#### [promptAddToSection](/docs/server-sdks/reference/typescript/agents/agent-base/prompt-add-to-section)

Append content to an existing prompt section.

#### [promptHasSection](/docs/server-sdks/reference/typescript/agents/agent-base/prompt-has-section)

Check whether a named section exists in the agent's prompt.

#### [registerSipUsername](/docs/server-sdks/reference/typescript/agents/agent-base/register-sip-username)

Register a SIP username to route calls to this agent.

#### [registerSwaigFunction](/docs/server-sdks/reference/typescript/agents/agent-base/register-swaig-function)

Register a raw SWAIG function descriptor, typically from a DataMap.

#### [removeSkill](/docs/server-sdks/reference/typescript/agents/agent-base/remove-skill)

Unload a skill from the agent.

#### [renderSwml](/docs/server-sdks/reference/typescript/agents/agent-base/render-swml)

Render the complete SWML document.

#### [run](/docs/server-sdks/reference/typescript/agents/agent-base/run)

Start the HTTP server (alias for serve).

#### [serve](/docs/server-sdks/reference/typescript/agents/agent-base/serve)

Start the Hono HTTP server to serve SWML and SWAIG endpoints.

#### [setDynamicConfigCallback](/docs/server-sdks/reference/typescript/agents/agent-base/set-dynamic-config-callback)

Set a callback for per-request dynamic agent configuration.

#### [setGlobalData](/docs/server-sdks/reference/typescript/agents/agent-base/set-global-data)

Replace the global data object available to the AI.

#### [setLanguages](/docs/server-sdks/reference/typescript/agents/agent-base/set-languages)

Replace all language configurations at once.

#### [setParam](/docs/server-sdks/reference/typescript/agents/agent-base/set-param)

Set a single AI parameter by key.

#### [setParams](/docs/server-sdks/reference/typescript/agents/agent-base/set-params)

Configure AI model parameters such as temperature and timeouts.

#### [setPostPrompt](/docs/server-sdks/reference/typescript/agents/agent-base/set-post-prompt)

Set the post-prompt for generating call summaries.

#### [setPostPromptLlmParams](/docs/server-sdks/reference/typescript/agents/agent-base/set-post-prompt-llm-params)

Set LLM parameters for the post-prompt.

#### [setPostPromptUrl](/docs/server-sdks/reference/typescript/agents/agent-base/set-post-prompt-url)

Override the URL where post-prompt summaries are delivered.

#### [setPromptLlmParams](/docs/server-sdks/reference/typescript/agents/agent-base/set-prompt-llm-params)

Set LLM parameters for the main prompt.

#### [setPromptText](/docs/server-sdks/reference/typescript/agents/agent-base/set-prompt-text)

Set the agent's system prompt as raw text.

#### [setupGracefulShutdown](/docs/server-sdks/reference/typescript/agents/agent-base/setup-graceful-shutdown)

Register signal handlers for graceful shutdown (static method).

#### [setWebHookUrl](/docs/server-sdks/reference/typescript/agents/agent-base/set-web-hook-url)

Override the default webhook URL for SWAIG function calls.

#### [updateGlobalData](/docs/server-sdks/reference/typescript/agents/agent-base/update-global-data)

Merge data into the global data object.

#### [validateBasicAuth](/docs/server-sdks/reference/typescript/agents/agent-base/validate-basic-auth)

Custom basic-auth validation hook.

#### [onRequest](/docs/server-sdks/reference/typescript/agents/agent-base/on-request)

Public hook called on every inbound request before rendering.

#### [pom](/docs/server-sdks/reference/typescript/agents/agent-base/pom)

Get the agent's prompt as a PromptObjectModel snapshot.

#### [getRawPrompt](/docs/server-sdks/reference/typescript/agents/agent-base/get-raw-prompt)

Retrieve the raw stored prompt text, unrendered.

#### [getContexts](/docs/server-sdks/reference/typescript/agents/agent-base/get-contexts)

Retrieve the agent's contexts as a serialized dictionary.

#### [createToolToken](/docs/server-sdks/reference/typescript/agents/agent-base/create-tool-token)

Create a per-call SWAIG token for a tool.

#### [setLanguageParams](/docs/server-sdks/reference/typescript/agents/agent-base/set-language-params)

Set engine-specific params on an added language.

#### [getLanguageParams](/docs/server-sdks/reference/typescript/agents/agent-base/get-language-params)

Read engine-specific params on an added language.