Asterisk Between a SIP Trunk and an AI Voice Agent: Diagram, Config and CLI Reference

15 min read

Asterisk Between a SIP Trunk and an AI Voice Agent: Diagram, Config and CLI Reference

The problem

Many teams put Asterisk, the open-source PBX, between their phone provider and their AI agent. It is a sensible choice. Asterisk speaks SIP to the carrier, handles authentication, NAT, codecs, call recording and transfers, and gives the agent a much simpler audio stream than raw SIP and RTP. The catch is that it has a lot of configuration surface. One wrong line, such as a missing identify section, a private IP in the SDP or a closed RTP port range, gives you a call that is rejected, silent, or audible in one direction only.

This page is the Asterisk reference for the rest of this series. It shows where each piece sits, which config option controls what, minimal pjsip.conf and extensions.conf examples based on the official documentation, and the CLI commands to look inside a live call. Other parts link here instead of repeating it. For what the SIP codes in your logs mean, see the companion SIP response code chart.

Version. Everything here is written against Asterisk 22 LTS using the PJSIP channel driver (res_pjsip and chan_pjsip), checked against docs.asterisk.org on 26 Nov 2026. The Asterisk versions page lists 22 as an LTS series released 2024-10-16, with full support until 2028-10-16, and 24 as the newest LTS, released 2026-11-05. The same options exist in 24. A few features are newer than 22.0, and I note the minimum version next to them. None of the snippets below were run for this article; they are assembled from the official examples and option references, with documentation IP addresses (RFC 5737 ranges) in place of real ones.

This is part 3 of the Voice AI over SIP series. If a term is new to you, the glossary defines it in plain language and links to the part that covers it.

The diagram

Diagram of an Asterisk server between a SIP trunk provider and an AI voice agent, showing firewall ports, PJSIP sections, RTP, dialplan, recording and the three ways to stream audio to the agent

Reading it from left to right:

  1. The SIP trunk provider. A carrier's session border controller (SBC) sends and receives calls. It can be Tata Communications, Tata Tele Business Services (TTBS) or any other provider; the Asterisk side looks the same. Providers authenticate you either by fixed IP address (they only accept traffic from your server's IP, and you only accept theirs) or with a username and password using SIP digest authentication. The trunk options in India are compared in the provider comparison and the Tata part.
  2. The firewall and NAT. Two kinds of traffic cross it. SIP signalling uses port 5060 (UDP or TCP; 5061 is the usual TLS port). The audio travels as RTP over UDP on a port range; the official rtp.conf sample sets 10000 to 20000, and the Asterisk NAT guide forwards the same range. Only the carrier's IPs should reach 5060. The ARI HTTP port (8088 by default) should never be exposed to the internet.
  3. PJSIP sections in pjsip.conf. A transport says where Asterisk listens and which public address to write into SIP and SDP. An identify section matches incoming requests from the carrier's IPs to an endpoint. The endpoint holds the call settings: dialplan context, codecs, media handling. An AoR (address of record) holds the carrier's contact URI for outbound calls. An auth section is only needed for digest authentication.
  4. RTP and codecs. Phone networks deliver G.711 (μ-law, ulaw, or A-law, alaw) at 8 kHz. The agent leg can use the same codec or signed linear audio (slin, raw 16-bit PCM). Asterisk converts between them.
  5. The dialplan in extensions.conf. It answers the call, can start recording with MixMonitor, and hands the audio to the agent using one of three methods.
  6. The agent link. Option A is ARI (the Asterisk REST Interface): your app gets the call through Stasis() and asks Asterisk to create an External Media channel that streams audio to it. Option B is AudioSocket, a simple TCP protocol. Option C is the WebSocket channel driver.

Config reference: what each setting does

File and sectionOptionWhat it doesWhy it matters for a voice agent
pjsip.conf transportbindAddress and port Asterisk listens on, for example 0.0.0.0 (port 5060 if none given)Must match what the firewall forwards
pjsip.conf transportlocal_netNetworks treated as local, so no address rewriting for themMissing or wrong, and Asterisk writes the wrong address in SDP
pjsip.conf transportexternal_media_addressPublic IP written into the SDP for destinations outside local_netThe fix for one-way audio behind NAT
pjsip.conf transportexternal_signaling_addressPublic IP written into SIP headers (Contact, Via) for outside destinationsWithout it, the carrier sends BYE and re-INVITE to a private IP
pjsip.conf identifyendpoint, matchMaps requests from given source IPs or networks to an endpointWithout a match, inbound calls from an IP-auth trunk are rejected
pjsip.conf endpointcontextDialplan context for inbound calls from this endpoint (default default)Keep trunk calls in their own context, never in one that can dial out freely
pjsip.conf endpointdisallow, allowCodec list, in order of preferenceNo shared codec with the trunk gives 488
pjsip.conf endpointdirect_mediaWhether media may flow directly between the two far ends (default yes)Set no so audio passes through Asterisk, which a media bridge to an agent needs
pjsip.conf endpointrtp_symmetricSend RTP back to the address it arrives from (default no)Helps when the far end is behind NAT
pjsip.conf endpointforce_rportSend responses back to the source port, RFC 3581 (default yes)NAT on the remote side
pjsip.conf endpointrewrite_contactReplace the Contact URI with the source address of the request (default no)NAT on the remote side
pjsip.conf endpointdtmf_modeHow key presses are carried (default rfc4733)Must match the trunk, or IVR menus and PIN entry break
pjsip.conf endpointoutbound_authAuth section used when the far end challenges with 401 or 407Only for digest-auth trunks
pjsip.conf endpointaorsAoR(s) this endpoint uses for outbound callsDial(PJSIP/number@endpoint) needs a contact here
pjsip.conf endpointrtp_timeoutHang up after this many seconds without RTP (default 0, off)Stops dead calls from holding channels and agent sessions
pjsip.conf aorcontactSIP URI of the carrier for outbound calls; can be repeatedSeveral contacts give simple redundancy
pjsip.conf aorqualify_frequencySeconds between SIP OPTIONS checks (default 0, off)Shows whether the carrier is reachable in pjsip show contacts
pjsip.conf authauth_type, username, passwordCredentials for digest authenticationOnly for digest-auth trunks
pjsip.conf registrationserver_uri, client_uri, outbound_authRegisters with the provider so it knows where to send inbound callsOnly if the provider requires REGISTER
rtp.confrtpstart, rtpendUDP port range for RTP (sample file: 10000 to 20000)Must match the firewall exactly
http.confenabled, bindaddr, bindportThe built-in HTTP server ARI runs on (disabled by default, port 8088)ARI does not work unless this is on
ari.conf[user] type=user, read_only, passwordARI user accountsYour agent app logs in with these
websocket_client.confuri, protocols, connection_typeOutbound WebSocket connections for the WebSocket channel driver (since 22.5.0)Used by option C
extensions.confAnswer, MixMonitor, Stasis, AudioSocket, DialThe call flowSee the dialplan example below

You can print the built-in help for any PJSIP option from the CLI, for example config show help res_pjsip endpoint rtp_symmetric, as the PJSIP configuration sections page describes.

Minimal pjsip.conf for an IP-authenticated trunk

This follows the structure of the NAT example in the official "Configuring res_pjsip to work through NAT" page, cut down to an IP-authenticated trunk. Replace the RFC 5737 addresses: 198.51.100.5 stands for your public IP, 192.0.2.0/24 for your private network, and 203.0.113.1 and 203.0.113.2 for the carrier's signalling IPs.

ini
; pjsip.conf (Asterisk 22 LTS). Example based on the official NAT guide.

[transport-udp]
type=transport
protocol=udp
bind=0.0.0.0
local_net=192.0.2.0/24
local_net=127.0.0.1/32
external_media_address=198.51.100.5
external_signaling_address=198.51.100.5

[carrier]
type=endpoint
transport=transport-udp
context=from-trunk
disallow=all
allow=ulaw
allow=alaw
aors=carrier-aor
direct_media=no
rtp_symmetric=yes
rewrite_contact=yes
rtp_timeout=30

[carrier-aor]
type=aor
contact=sip:203.0.113.1
qualify_frequency=60

[carrier-identify]
type=identify
endpoint=carrier
match=203.0.113.1
match=203.0.113.2

If the provider uses digest authentication instead, add an auth section and point the endpoint at it. Add a registration only if the provider says inbound calls require one:

ini
[carrier-auth]
type=auth
auth_type=userpass
username=YOUR_TRUNK_USERNAME
password=YOUR_TRUNK_PASSWORD

; on the [carrier] endpoint, add:
; outbound_auth=carrier-auth

[carrier-reg]
type=registration
transport=transport-udp
outbound_auth=carrier-auth
server_uri=sip:sip.provider.example
client_uri=sip:YOUR_TRUNK_USERNAME@sip.provider.example
retry_interval=60

Two notes. The PJSIP troubleshooting guide says every inbound request must match an endpoint through an identifier (the user part of the From header, the source IP, or anonymous), and unmatched requests are rejected. The default identify_by is username,ip, so the identify section is what lets an IP-auth trunk in. Also, transport sections are not reloaded at runtime unless allow_reload is set, so a transport change usually needs a restart.

Minimal extensions.conf: three ways to reach the agent

ini
; extensions.conf (Asterisk 22 LTS)

[from-trunk]
; Inbound calls from the carrier. Pick ONE of the three options below.
; DIDs that arrive with a leading + need a pattern such as _+X.
exten => _X.,1,NoOp(Inbound call to ${EXTEN})
 same => n,Answer()
 same => n,MixMonitor(${UNIQUEID}.wav)

; Option A: hand the channel to an ARI application named voice-agent.
 same => n,Stasis(voice-agent,${EXTEN})

; Option B: stream audio to an AudioSocket server over TCP.
; The first argument must be a UUID string, unique per call.
; same => n,AudioSocket(40325ec2-5efd-4bd3-805f-53576e581d13,agent.example:9092)

; Option C: bridge to the agent through the WebSocket channel driver
; (22.6.0 or later), using the [media_connection1] section in websocket_client.conf.
; same => n,Dial(WebSocket/media_connection1/c(ulaw))

 same => n,Hangup()

[to-trunk]
; Outbound calls through the carrier: PJSIP/<number>@<endpoint>
exten => _X.,1,Dial(PJSIP/${EXTEN}@carrier,30)
 same => n,Hangup()

What the official docs say about each piece:

  • Stasis and ARI. The "Getting Started with ARI" page enables the HTTP server in http.conf (enabled = yes), creates an ARI user in ari.conf (type = user), and sends the call to Stasis(hello-world). The app connects to the events WebSocket at /ari/events and gets a StasisStart event when the channel enters. To get audio out, the app calls POST /channels/externalMedia. Its transport and encapsulation pair picks the driver: UDP with RTP (chan_rtp, the default), TCP with AudioSocket, or WebSocket. app and format are required; external_host is the host:port the audio is sent to. The app then puts the caller's channel and the External Media channel in a mixing bridge. The endpoint exists since 16.6.0 and 17.1.0.
  • AudioSocket. The dialplan application page (generated from branch 22) says AudioSocket(uuid,service) sends the channel audio as 16-bit, 8 kHz mono PCM and does not answer the call by itself, so Answer() comes first. Other sample rates are available through the channel driver interface, Dial(AudioSocket/...). The wire protocol is a 3-byte header (1 byte message type, 2 bytes payload length, big-endian) followed by the payload. Type 0x01 carries the 16-byte call UUID, 0x10 carries 8 kHz signed linear audio, 0x03 a DTMF digit, 0x00 hangup and 0xff an error. Types 0x11 to 0x18 carry 12 kHz up to 192 kHz audio.
  • WebSocket channel driver. Available from 23.0.0, 22.6.0, 21.11.0 and 20.16.0. Binary frames carry audio and text frames carry control commands, such as FLUSH_MEDIA to drop queued audio when a caller interrupts the agent. Messages are capped at 65500 bytes. JSON control messages are preferred from 22.8.0 and 23.2.0. The matching websocket_client.conf example in the docs is:
ini
; websocket_client.conf (22.5.0 or later), from the res_websocket_client docs
[media_connection1]
type=websocket_client
uri=ws://localhost:8787
protocols=media
connection_type=per_call_config
connection_timeout=500
reconnect_interval=500
reconnect_attempts=5
tls_enabled=no
  • MixMonitor. The syntax is MixMonitor(filename.extension,[options,[command]]). It records as an audiohook, does not answer the call, and the file is complete once the call ends or StopMixMonitor runs. The docs warn against putting untrusted values such as caller ID into the arguments, because the optional command runs in a shell. Using ${UNIQUEID} for the file name avoids that. Without a full path, the file goes into Asterisk's monitor spool directory. Check the recording and consent rules for your country before you turn it on; for India they are covered in India's rules for AI phone calls.

Which option to pick is a judgement call. I would start with ARI External Media when the agent code needs to control the call (transfers, hangups, playing prompts), AudioSocket when you want the simplest possible TCP stream and 8 kHz is fine, and the WebSocket driver when your agent framework already speaks WebSocket audio and you run 22.6 or newer.

The ports to open

PortProtocolDirectionPurposeRestrict to
5060UDP and TCPcarrier to Asterisk and backSIP signallingCarrier's signalling IPs only
5061TCPsameSIP over TLS, if the carrier supports itCarrier's signalling IPs only
10000 to 20000UDPbothRTP audio (range from rtp.conf)Carrier's media IPs if they publish them
8088TCPagent app to AsteriskARI HTTP and events WebSocketLocalhost or a private network
your AudioSocket portTCPAsterisk to agentAudioSocket streamPrivate network

CLI commands for a live call

Run these from the Asterisk console (asterisk -rvvv) or one at a time with asterisk -rx "<command>". The first group comes from the official PJSIP troubleshooting guide and the "Making a phone call" page; the rest are standard Asterisk CLI commands.

CommandWhat it showsUse it when
core show versionExact Asterisk versionChecking whether a feature (WebSocket driver, JSON control) is available
core set verbose 4More detail in the consoleStarting any debugging session
pjsip show endpointsAll endpoints and their state; endpoints that failed to load are missingRight after a config change
pjsip show endpoint carrierFull settings of one endpoint, including its AoR and contactsChecking codecs, context, NAT options
pjsip show contactsContacts and their qualify status (reachable or not)Outbound calls fail or the carrier seems down
pjsip show registrationsOutbound registration statusDigest trunks that need REGISTER
pjsip show transportsTransports and their bind and external addressesChecking NAT settings
pjsip show identifiesIP matches for identify sectionsInbound calls from the trunk are rejected
pjsip set logger onEvery SIP message, in and out, in the consoleAny call setup failure; find the final response code
pjsip set logger host 203.0.113.1SIP messages to and from one host onlyBusy systems
rtp set debug onEvery RTP packet sent and received, with addressesOne-way audio or silence after the call connects
rtp set debug ip 203.0.113.1RTP debug for one address onlyBusy systems
rtp set debug offStops RTP debugAlways turn it off afterwards; it is very noisy
core show channelsActive channels and what application each is runningChecking the call reached Stasis, AudioSocket or Dial
core show channels conciseSame, one line per channel, easy to parseScripts and monitoring
pjsip show channelstatsPer-call RTP statistics such as packet loss and jitterChoppy or robotic audio
core show translationWhich codec conversions are available and their costChoosing codecs for the agent leg
dialplan show from-trunkThe parsed dialplan contextThe call goes to the wrong place
module show like websocketWhether the WebSocket modules are loadedOption C does not work

A typical order when a call fails: pjsip set logger on, place the call, read the final SIP response, look it up in the SIP response code chart, and if the call connected but the audio is wrong, switch to rtp set debug on and compare the addresses in the SDP with the addresses the packets actually come from.

Common failures and the setting behind them

SymptomUsual causeSetting to check
Inbound calls from the trunk rejectedNo identify match for the carrier's IPidentify section match
You hear the caller, they cannot hear the agentPrivate IP in your SDPexternal_media_address, local_net
No audio either wayRTP ports closed or wrong rangeFirewall and rtpstart and rtpend
Call drops about 32 seconds after answerACK not reaching Asterisk, often NATexternal_signaling_address, rewrite_contact
488 Not Acceptable HereNo common codecdisallow and allow
Key presses not detectedDTMF method mismatchdtmf_mode
Dead calls hold agent sessions openNo media timeoutrtp_timeout
ARI app never sees callsHTTP server off, wrong app name, or wrong contexthttp.conf enabled, Stasis() app name, endpoint context

Sources