MCPInstall
twilio/ai avatar

twilio-debugging-observability

Debug Twilio integrations and set up production observability. Covers the Console Debugger, Monitor Alerts API, Event Streams for error log streaming, status callback tracking, common error codes, and a systematic debugging workflow. Use this skill whenever a Twilio integration produces errors, messages fail to deliver, calls drop unexpectedly, or you need to set up monitoring for a production deployment.

Installs
192
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/twilio/ai --skill twilio-debugging-observability
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads twilio-debugging-observability automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Overview

Twilio provides several layers of debugging and observability: the Console Debugger for interactive troubleshooting, the Monitor REST API for programmatic alert queries, Event Streams for real-time error streaming, and status callbacks for per-resource delivery tracking. This skill covers the systematic approach to diagnosing issues and setting up production monitoring.


Prerequisites

  • Twilio account with TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN -- see twilio-iam-auth-setup
  • SDK: pip install twilio requests / npm install twilio
  • For Event Streams: a publicly accessible HTTPS endpoint or AWS Kinesis stream

Quickstart

Check for recent errors on your account using the Monitor Alerts API.

Python

import os
from twilio.rest import Client

client = Client(os.environ["TWILIO_ACCOUNT_SID"], os.environ["TWILIO_AUTH_TOKEN"])

alerts = client.monitor.alerts.list(log_level="error", limit=10)
for alert in alerts:
    print(f"{alert.date_created}: [{alert.error_code}] {alert.alert_text}")

Node.js

const twilio = require("twilio");
const client = twilio(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);

const alerts = await client.monitor.alerts.list({ logLevel: "error", limit: 10 });
alerts.forEach(a => {
    console.log(`${a.dateCreated}: [${a.errorCode}] ${a.alertText}`);
});

Key Patterns

1. Systematic Debugging Workflow

When something fails, work through these layers in order:

1. Check status callbacks FIRST
   (Did your endpoint receive delivery/call status? What error code?)
   |
2. Check the resource directly via REST API
   (GET /Messages/{sid} or /Calls/{sid} — current state + error_code)
   |
3. Check number reputation / sender registration
   (Is the number spam-flagged? Is A2P 10DLC registered? Toll-free verified?)
   |
4. Check the Console Debugger for webhook/TwiML errors
   (Console > Monitor > Errors — shows HTTP request/response details)
   |
5. Check your webhook endpoint
   (Is it reachable? Responding within 15s? Returning valid TwiML/200?)
   |
6. Query Monitor Alerts API or Event Streams
   (For patterns across many messages/calls, or historical analysis)

Why status callbacks first: Status callbacks tell you the exact error code for the specific message or call that failed. The Console Debugger aggregates errors across your account and may not surface the one you're looking for. Start specific, then broaden.

Number reputation checklist:

  • SMS 30007 (carrier filtering) → Check A2P 10DLC registration status, content for spam triggers
  • SMS 30034 → Sender not registered for A2P 10DLC — register brand + campaign
  • Calls going to voicemail / "Spam Likely" → Check STIR/SHAKEN attestation, Voice Integrity status (see twilio-numbers-senders)
  • Toll-free SMS blocked → Check toll-free verification status

Rule of thumb: If status callbacks show delivered but the user says they didn't receive it, the issue is on the carrier/device side (not Twilio). If the Console Debugger shows no errors at all, the problem is in your application (webhook, TwiML, business logic).

2. Console Debugger

The Console Debugger shows errors and warnings for your account in real time.

Each entry includes:

  • The exact error or warning that occurred
  • Potential causes and suggested solutions
  • The full HTTP request and response for the associated webhook

Configure a Debugger webhook for real-time alerting:

Console > Monitor > Logs > Debugger > (gear icon) > set Callback URL

Debugger webhook POST parameters:

ParameterDescription
SidDebugger event identifier
AccountSidAccount that generated the event
LevelError or Warning
TimestampISO 8601 time
PayloadJSON: resource_sid, error_code, more_info, webhook (full request/response)

Python (Flask) -- debugger webhook handler

import json, os
from flask import Flask, request
from twilio.request_validator import RequestValidator

app = Flask(__name__)
validator = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"])

@app.route("/debugger", methods=["POST"])
def debugger_event():
    sig = request.headers.get("X-Twilio-Signature", "")
    if not validator.validate(request.url, request.form, sig):
        return "Forbidden", 403
    level = request.form.get("Level")
    payload = json.loads(request.form.get("Payload", "{}"))
    error_code = payload.get("error_code")
    resource_sid = payload.get("resource_sid")
    msg = payload.get("more_info", {}).get("msg", "")
    print(f"[{level}] Error {error_code} on {resource_sid}: {msg}")
    return "", 204

Node.js (Express) -- debugger webhook handler

const express = require("express");
const twilio = require("twilio");
const app = express();
app.use(express.urlencoded({ extended: false }));

app.post("/debugger", (req, res) => {
    const valid = twilio.validateRequest(
        process.env.TWILIO_AUTH_TOKEN,
        req.headers["x-twilio-signature"],
        `https://${req.headers.host}${req.originalUrl}`,
        req.body
    );
    if (!valid) return res.status(403).send("Forbidden");
    const payload = JSON.parse(req.body.Payload || "{}");
    const { error_code, resource_sid } = payload;
    const msg = payload.more_info?.msg || "";
    console.log(`[${req.body.Level}] Error ${error_code} on ${resource_sid}: ${msg}`);
    res.sendStatus(204);
});

3. Monitor Alerts API

The Monitor REST API (monitor.twilio.com/v1/Alerts) provides programmatic access to error and warning logs. Individual alert instances include the full HTTP request and response data.

Python -- query alerts with date filtering

from datetime import datetime, timedelta

# Alerts from the last 24 hours
start = datetime.utcnow() - timedelta(days=1)
alerts = client.monitor.alerts.list(
    start_date=start,
    log_level="error",
    limit=50
)

for alert in alerts:
    print(f"{alert.date_created} [{alert.error_code}]")
    # Fetch full details including HTTP request/response
    detail = client.monitor.alerts(alert.sid).fetch()
    print(f"  Request URL: {detail.request_url}")
    print(f"  Response body: {detail.response_body}")

Node.js -- query alerts with date filtering

const startDate = new Date(Date.now() - 24 * 60 * 60 * 1000);
const alerts = await client.monitor.alerts.list({
    startDate,
    logLevel: "error",
    limit: 50,
});

for (const alert of alerts) {
    console.log(`${alert.dateCreated} [${alert.errorCode}]`);
    const detail = await client.monitor.alerts(alert.sid).fetch();
    console.log(`  Request URL: ${detail.requestUrl}`);
    console.log(`  Response body: ${detail.responseBody}`);
}

Retention: Enterprise accounts: 13 months. Free accounts: 30 days.

4. Monitor Events API

The Events resource (monitor.twilio.com/v1/Events) tracks all changes to Twilio resources -- phone number provisioning, account settings, recording access, API key creation, and more.

Python -- audit recent account changes

events = client.monitor.events.list(limit=20)
for event in events:
    print(f"{event.event_date}: {event.event_type}")
    print(f"  Resource: {event.resource_type} ({event.resource_sid})")
    print(f"  Actor: {event.actor_type} ({event.actor_sid}) from {event.source_ip_address}")

Each event captures: event type, resource, actor (who triggered it), source (API / Console / Twilio admin), and IP address.

Use cases:

  • Audit who changed a phone number's webhook URL
  • Track API key creation and deletion
  • Detect unexpected configuration changes
  • Feed events into a SIEM for security monitoring

5. Event Streams for Error Log Streaming

For production monitoring, stream errors to your infrastructure in real time using Event Streams. The Twilio SDK does not wrap Event Streams -- use requests / fetch directly.

Python -- set up error log streaming to a webhook

import os, requests

account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]

# Step 1: Create a webhook sink
sink = requests.post(
    "https://events.twilio.com/v1/Sinks",
    auth=(account_sid, auth_token),
    data={
        "Description": "Error monitoring sink",
        "SinkType": "webhook",
        "SinkConfiguration": '{"destination": "https://yourapp.com/twilio-errors", "method": "POST"}'
    }
).json()

# Step 2: Subscribe to error log events
subscription = requests.post(
    "https://events.twilio.com/v1/Subscriptions",
    auth=(account_sid, auth_token),
    data={
        "Description": "Error log subscription",
        "SinkSid": sink["sid"],
        "Types": '[{"type": "com.twilio.error-logs.error.logged"}]'
    }
).json()

print(f"Sink: {sink['sid']}, Subscription: {subscription['sid']}")

Sink types: webhook, kinesis, segment

Useful event types for observability:

Event typeDescription
com.twilio.error-logs.error.loggedAll errors and warnings on account
com.twilio.messaging.message.deliveredMessage delivered successfully
com.twilio.messaging.message.undeliveredMessage delivery failed
com.twilio.voice.insights.call-summaryPost-call quality and status summary

6. Status Callback Monitoring

Status callbacks are the most granular observability mechanism -- they fire for individual resource state changes.

Message delivery tracking:

# Attach when sending
message = client.messages.create(
    to="+15558675310", from_="+15017122661", body="Hello!",
    status_callback="https://yourapp.com/msg-status"
)

Call lifecycle tracking:

call = client.calls.create(
    to="+15558675310", from_="+15017122661",
    url="https://yourapp.com/voice",
    status_callback="https://yourapp.com/call-status",
    status_callback_event=["initiated", "ringing", "answered", "completed"]
)

Recording completion tracking:

# In TwiML
response = VoiceResponse()
response.record(
    recording_status_callback="https://yourapp.com/recording-status",
    recording_status_callback_event="completed absent failed"
)

Recording status values: in-progress, completed, absent, failed. The RecordingUrl is available when status is completed.

7. Debugging Webhooks

When Twilio can't reach your webhook or receives an error, the problem is often in your infrastructure.

Common causes and fixes:

SymptomLikely causeFix
Error 11200 in DebuggerWebhook URL returned non-200 / unreachableVerify endpoint is live: curl -I https://yourapp.com/sms
Error 11205HTTP connection failure (port closed, refused, firewall)Verify server is running and port is open: curl -I https://yourapp.com/sms
Error 12100TwiML document could not be parsedCheck for debug output, BOM characters, or malformed XML
Parameters missing after redirectHTTP 301/302 strips POST bodyFix URL to avoid redirect (add/remove www., use HTTPS directly)
Webhook works locally but not deployedTunnel expired or firewallUse curl from an external host to test
Intermittent failuresngrok session expired / recycledDeploy to a stable host for anything beyond quick tests

Test webhooks manually:

# Simulate an inbound SMS webhook
curl -X POST https://yourapp.com/sms \
  -d "From=+15551234567" \
  -d "To=+15559876543" \
  -d "Body=Test message" \
  -d "MessageSid=SM00000000000000000000000000000000"

Browser testing: Visit your webhook URL in Firefox -- it highlights XML errors in the response.

8. Common Error Codes

CodeNameCauseFix
11200HTTP retrieval failureTwilio cannot reach your webhook URLCheck URL, DNS, firewall, SSL cert
11205HTTP connection failureWebhook endpoint refused connectionVerify server is running and port is open
11751Media download failureMMS media URL unreachableCheck media URL accessibility
12100Document parse failureTwiML is not valid XMLValidate XML; remove debug output
12200Schema compliance failureTwiML verbs/attributes are invalidCheck TwiML reference for correct syntax
20003Authentication errorInvalid Account SID or Auth TokenVerify credentials in environment
21211Invalid To numberNumber not in E.164 formatUse + country code + number
21608Unverified number (trial)Trial accounts can only send to verified numbersVerify number or upgrade account
30003Unreachable destinationCarrier cannot deliver messageCheck number validity; retry later
30006Landline or unreachableDestination is a landlineUse voice channel instead
30007Carrier filteringMessage filtered by carrierReview content; register for A2P 10DLC
30008Unknown errorCarrier returned generic errorRetry; contact support if persistent

Full error reference: https://www.twilio.com/docs/api/errors

9. Querying Resource State Directly

When you need the current state of a message or call (not waiting for a callback):

Python

# Check message delivery status
message = client.messages("SMxxxxxxxxxx").fetch()
print(f"Status: {message.status}, Error: {message.error_code}")

# Check call status
call = client.calls("CAxxxxxxxxxx").fetch()
print(f"Status: {call.status}, Duration: {call.duration}")

Node.js

const message = await client.messages("SMxxxxxxxxxx").fetch();
console.log(`Status: ${message.status}, Error: ${message.errorCode}`);

const call = await client.calls("CAxxxxxxxxxx").fetch();
console.log(`Status: ${call.status}, Duration: ${call.duration}`);

10. CLI Debugging

The Twilio CLI supports debug logging:

# Verbose output for any CLI command
twilio api:core:messages:list --limit 5 -l debug

# Log levels: debug, info, warn, error

Debug output goes to stderr, so you can pipe normal output while still seeing diagnostics.


Monitoring Checklist

Set up before going to production:

What to monitorHowAlert threshold
Webhook errorsDebugger webhook or Event Streams (com.twilio.error-logs.error.logged)Any error
Message delivery failuresStatus callback failed/undelivered> 2% failure rate
Call completion rateStatus callback completed vs total< 95% completion
Webhook response timeYour APM (DataDog, New Relic)p95 > 5 seconds
429 rate limit hitsCount in your backoff handler> 5% of requests
Account configuration changesMonitor Events APIAny unexpected change
Recording failuresRecording status callback failed/absentAny failure

CANNOT

  • Cannot fetch more than 10,000 alerts per request — Use date range filters for large accounts
  • Cannot get full HTTP request/response from alert list — Only available when fetching a single alert by SID
  • Cannot combine multiple filters on Events API — One additional field (ResourceSid, ActorSid, SourceIpAddress) plus date range per request
  • Cannot delete an Event Streams sink before its subscription — Must delete the subscription first
  • Cannot guarantee status callback delivery or order — Best-effort. Use composite keys for idempotency.
  • Cannot rely on a static error code list — New error codes are added without notice. Always link to the full reference rather than hardcoding.

Next Steps

  • Webhook architecture: twilio-webhook-architecture
  • Scale webhook handling: twilio-reliability-patterns
  • Compliance monitoring: twilio-compliance-traffic
  • Credential security: twilio-iam-auth-setup

FAQ

What does the twilio-debugging-observability skill do?

Debug Twilio integrations and set up production observability. Covers the Console Debugger, Monitor Alerts API, Event Streams for error log streaming, status callback tracking, common error codes, and a systematic debugging workflow. Use this skill whenever a Twilio integration produces errors, messages fail to deliver, calls drop unexpectedly, or you need to set up monitoring for a production deployment.

How do I install twilio-debugging-observability?

Run npx skills add https://github.com/twilio/ai --skill twilio-debugging-observability in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/twilio-debugging-observability/ (personal) or .claude/skills/twilio-debugging-observability/ (project).

Which AI agents can use twilio-debugging-observability?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is twilio-debugging-observability safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains twilio-debugging-observability?

It is published by twilio/ai in twilio/ai. It has 192 recorded installs.

More from twilio/ai

View all →

SMS and MMS deep-dive reference. Covers SMS-specific error codes, message filtering troubleshooting ("Messages Being Filtered or Blocked?" diagnostic checklist), MMS media support (US/CA/AU only), and SMS pumping indicators. For sending SMS, use twilio-send-message instead. Use this skill only when debugging SMS delivery issues or needing SMS-specific details not in the consolidated send skill.

Send messages via Twilio's Programmable Messaging API across all channels — SMS, MMS, RCS, and WhatsApp. Covers text messages, media, rich content (cards, carousels, buttons), template-based sends, Messaging Services, status callbacks, and WhatsApp's 24-hour service window. Use when the user wants to send a message — whether they say "send SMS", "text message", "branded message", "rich message", "WhatsApp message", "RCS message", "notification", or "alert". For picking the right channel for a use case, first consult twilio-messaging-channel-advisor.

Backend & APIs800 installs

Send transactional and bulk email via the SendGrid v3 Mail Send API. Covers single sends, personalized batch sends with dynamic templates, scheduled sends with cancellation, attachments, and sandbox mode for testing. Use this skill when the caller has a SendGrid API key (SG.-prefix). Do NOT use this skill if the caller is using the Twilio Email API (comms.twilio.com) — that is a separate product with different credentials.

Design, secure, and operate Twilio webhook endpoints. Covers inbound event handling, status callbacks, signature validation, connection overrides for retry and timeout tuning, local development tunneling, and production hardening. Use this skill whenever an agent needs to receive HTTP callbacks from Twilio for any product -- messaging, voice, verify, or event streams.

Backend & APIs296 installs

Secure Twilio applications against common attacks. Covers credential management (API keys vs auth tokens), request validation (webhook signature verification), PCI DSS compliance, HIPAA account requirements, SMS pumping prevention, geo-permissions, and account isolation patterns. Use this skill when developers are building or deploying Twilio apps.

Security245 installs

Twilio Messaging channel overview and onboarding guide. Covers all channels (SMS, WhatsApp, RCS, Facebook Messenger), the unified Messages API, channel selection guidance, and the recommended setup sequence from first message to production monitoring. Start here before choosing a specific messaging channel.

Backend & APIs227 installs

Popular devops & cloud skills

View category →
microsoft avatar

microsoft-foundry

microsoft/azure-skills

Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure

OfficialDevOps & Cloud780.1K installs
microsoft avatar

azure-diagnostics

microsoft/azure-skills

Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.

OfficialDevOps & Cloud770.8K installs
microsoft avatar

azure-prepare

microsoft/azure-skills

Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.

OfficialDevOps & Cloud769.8K installs
microsoft avatar

azure-ai

microsoft/azure-skills

Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.

OfficialDevOps & Cloud769.2K installs
microsoft avatar

azure-deploy

microsoft/azure-skills

Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.

OfficialDevOps & Cloud768.8K installs
microsoft avatar

azure-validate

microsoft/azure-skills

Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.

OfficialDevOps & Cloud768.5K installs