agentleFS
wittyreferencewittyreference/twilio-claude-plugin/skills/tool-boundaries/SKILL.md

tool-boundaries

Skill2 starsChanged 8 months agoMITView on GitHub

Twilio development skill: tool-boundaries

  • Reads credentials

The file

We split this skill into the rules it gives an agent

12 rules. About 0 are common, 12 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈12

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Read-only operations agents can perform freely via MCP tools.

    line 52
  2. Distinctive:

    Write operations agents can perform with rate limits or validation.

    line 142
  3. Distinctive:

    When the same operation can be done multiple ways, use this guide:

    line 258
  4. Distinctive:

    Rule: Use MCP when agent decides to send.

    line 268
  5. Distinctive:

    Rule: Use Function for user-initiated, MCP for agent/system-initiated.

    line 298
  6. Distinctive:

    Rule: Always MCP. No dedicated CLI equivalent.

    line 363
  7. Distinctive:

    Return JSON data: - Never TwiML (that's for Functions)

    line 391
  8. Distinctive:

    Be stateless: - No persistent connections or file storage

    line 392
  9. Distinctive:

    Redact sensitive data: - No auth tokens in responses

    line 395
  10. Distinctive:

    Perform file operations: - No reading/writing local files

    line 400
  11. Distinctive:

    Store state internally: - Use Sync documents instead

    line 404
  12. Distinctive:

    Context: Should MCP tools wrap CLI commands for operations like deployment?

    line 412

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Tool Boundaries Reference

This document defines the architectural boundaries between MCP Server, Twilio CLI, Serverless Toolkit, and Twilio Functions. Use this as a decision guide when implementing new capabilities.


Component Overview

ComponentPurposeRuntimeOutput Type
MCP ServerAgent-accessible Twilio API wrapperIn-process with Claude Agent SDKJSON data
Twilio CLIDevOps/admin interface for humansTerminal / CI pipelinesCommands + logs
Serverless ToolkitDeployment mechanism (CLI plugin)CLI pluginDeployed code
Twilio FunctionsWebhook handlers on Twilio infraTwilio's Node.js runtimeTwiML / JSON
Agent TeamsParallel multi-agent coordinationMultiple Claude Code sessionsStructured task results

Dual Tool Registration

In this project, Twilio tools appear twice in Claude Code sessions:

  1. mcp__twilio__<name> — Project MCP server (via .mcp.json). Uses project .env credentials.
  2. mcp__plugin_twilio-claude-plugin_twilio__<name> — Official Twilio plugin (via ~/.claude/settings.json).

Always prefer mcp__twilio__ (the shorter prefix). It uses the project's configured credentials and matches the deployed account. The plugin uses its own credential config which may differ.

To disable the plugin entirely: set "twilio-claude-plugin@twilio-claude-plugin": false in ~/.claude/settings.json under enabledPlugins.


The Golden Rules

  1. MCP = Data Operations: Query, send, create, and modify records. Includes destructive operations (delete, release) that require user confirmation. Never deploy infrastructure.
  2. CLI = Infrastructure Operations: Deploy, configure environments, purchase numbers.
  3. Functions = Real-Time Webhooks: Handle calls/messages, return TwiML.
  4. Never Cross Layers: MCP does not invoke CLI. Functions do not use MCP.
  5. Teams = Parallel Coordination: Multiple agents working simultaneously. Teammates must not edit the same file.
  6. SID-First Principle: When you have a specific resource SID (call, message, recording, transcript, task, room, trunk, Sync resource), always use the SID-targeted validate_* or get_* tool instead of listing and filtering. SID-targeted tools provide deep validation (status, notifications, insights, sub-resources) in a single call. Reserve list_* tools for discovery when you don't have a SID.

Operation Risk Tiers

Tier 1: Safe (Agent Autonomous)

Read-only operations agents can perform freely via MCP tools.

OperationMCP ToolNotes
Query message historyget_message_logsFiltered by date, phone, status
Query call historyget_call_logsFiltered by date, phone, status
Get debugger alertsget_debugger_logsError analysis, monitoring
Get usage recordslist_usage_recordsBilling, cost analysis
List phone numberslist_phone_numbersInventory check
Search available numberssearch_available_numbersResearch only, no purchase
Get Sync documentget_documentState retrieval
List Sync documentslist_documentsState enumeration
List TaskRouter workerslist_workersAvailability check
List TaskRouter workflowslist_workflowsRouting config review
List TaskRouter task queueslist_task_queuesQueue topology discovery
Get TaskRouter task queueget_task_queueQueue config inspection
Get TaskRouter queue statsget_queue_statisticsReal-time operational metrics
List TaskRouter activitieslist_activitiesWorker state discovery
List TaskRouter reservationslist_reservationsTask-to-worker match visibility
List Sync Listslist_sync_listsList enumeration
List Sync List itemslist_sync_list_itemsCollection read
List Sync Mapslist_sync_mapsMap enumeration
Get Sync Map itemget_sync_map_itemKey-value lookup
List call queueslist_queuesQueue inventory
Get call queueget_queueQueue details
Get payment statusget_paymentPayment status check
Get verification statusget_verification_statusStatus check
Validate call (deep)validate_callStatus + notifications + Voice Insights
Validate message (deep)validate_messageDelivery + debugger alerts
Validate recordingvalidate_recordingCompletion polling + duration
Validate transcriptvalidate_transcriptCompletion + sentences
Validate debuggervalidate_debuggerAlerts, optionally filtered by resourceSid
Validate voice AI flowvalidate_voice_ai_flowFull flow: call → recording → transcript
Validate two-wayvalidate_two_wayBidirectional conversation
Validate language operatorvalidate_language_operatorOperator results on transcript
Validate Sync documentvalidate_sync_documentData structure + content
Validate Sync listvalidate_sync_listItem count + structure
Validate Sync mapvalidate_sync_mapKey/value validation
Validate TaskRouter taskvalidate_taskTask deep validation
Validate SIPvalidate_sipInfrastructure validation
Validate video roomvalidate_video_roomRoom + participants + tracks
Validate environmentvalidate_environmentAccount identity + credentials + services
List serverless serviceslist_servicesDeployment state
List serverless functionslist_functionsFunction inventory
List serverless logslist_logsRuntime logs
List environmentslist_environmentsDeployment environments
List buildslist_buildsBuild history
Get build statusget_build_statusBuild completion
List assetslist_assetsAsset inventory
List variableslist_variablesEnvironment variables
List Studio flowslist_studio_flowsFlow inventory
Get Studio flowget_flowFlow definition
Get execution statusget_execution_statusFlow execution state
List execution stepslist_execution_stepsStep-by-step trace
List messaging serviceslist_messaging_servicesService inventory
Get messaging serviceget_messaging_serviceService config
Lookup phone numberlookup_phone_numberCarrier info, validation
Check fraud riskcheck_fraud_riskFraud assessment
List video roomslist_video_roomsRoom inventory
Get video roomget_roomRoom details
List room participantslist_room_participantsParticipant inventory
List room recordingslist_room_recordingsRecording inventory
List proxy serviceslist_proxy_servicesProxy inventory
Get proxy serviceget_proxy_serviceService config
List proxy sessionslist_proxy_sessionsSession inventory
List content templateslist_content_templatesTemplate inventory
Get content templateget_content_templateTemplate details
List intelligence serviceslist_intelligence_servicesService inventory
List transcriptslist_transcriptsTranscript inventory
Get transcriptget_transcriptTranscript details
List sentenceslist_sentencesSentence extraction
List operator resultslist_operator_resultsAI operator output
List SIP domainslist_sip_domainsDomain inventory
List SIP trunkslist_sip_trunksTrunk inventory
Get SIP trunkget_sip_trunkTrunk config
List regulatory bundleslist_regulatory_bundlesCompliance status
Get accountget_accountAccount info + status
List accountslist_accountsSub-account inventory
Get account balanceget_account_balanceBalance check
List API keyslist_api_keysKey inventory
List addresseslist_addressesAddress inventory
List voice pricinglist_voice_pricing_countriesPricing reference
List messaging pricinglist_messaging_pricing_countriesPricing reference
List notify serviceslist_notify_servicesNotification services
List customer profileslist_customer_profilesTrustHub profiles
List trust productslist_trust_productsTrust products
List end userslist_end_usersEnd user inventory

Tier 2: Controlled (Agent with Guardrails)

Write operations agents can perform with rate limits or validation.

OperationMCP ToolGuardrail
Send SMSsend_smsRate limit: 10/minute, validated E.164
Send MMSsend_mmsRate limit: 10/minute, media URL validation
Make outbound callmake_callRate limit: 5/minute, validated E.164
Start verificationstart_verificationRate limit: 5/minute per recipient
Create Sync documentcreate_documentNamespace isolation for agent state
Update Sync documentupdate_documentAgent-owned documents only
Create TaskRouter taskcreate_taskPriority caps, timeout limits
Update TaskRouter taskupdate_taskChanges task state
Update TaskRouter workerupdate_workerChanges worker availability
Update TaskRouter reservationupdate_reservationCompletes assignment flow
Create Sync Listcreate_sync_listResource creation
Add Sync List itemadd_sync_list_itemData write
Update Sync List itemupdate_sync_list_itemData mutation
Remove Sync List itemremove_sync_list_itemData deletion
Create Sync Mapcreate_sync_mapResource creation
Add Sync Map itemadd_sync_map_itemData write
Update Sync Map itemupdate_sync_map_itemData mutation
Remove Sync Map itemremove_sync_map_itemData deletion
Create paymentcreate_paymentPCI Mode required (irreversible)
Update paymentupdate_paymentCompletes/cancels payment
Dequeue memberdequeue_memberRedirects queued caller
Create video roomcreate_video_roomRoom creation
Update video roomupdate_roomRoom state changes
Trigger Studio flowtrigger_flowFlow execution
Create messaging servicecreate_messaging_serviceService setup
Update messaging serviceupdate_messaging_serviceConfig changes
Delete messaging servicedelete_messaging_serviceService removal
Create proxy sessioncreate_proxy_sessionAnonymous communication
Create content templatecreate_content_templateTemplate creation
Delete content templatedelete_content_templateTemplate removal
Create transcriptcreate_transcriptIntelligence transcription
Delete transcriptdelete_transcriptTranscript removal
Create notify servicecreate_notify_serviceNotification setup
Send notificationsend_notificationPush notification
Create SIP domaincreate_sip_domainSIP infrastructure
Update SIP domainupdate_sip_domainSIP config changes
Create SIP trunkcreate_sip_trunkTrunking infrastructure
Update SIP trunkupdate_sip_trunkTrunk config changes
Create variablecreate_variableServerless env var
Update variableupdate_variableEnv var changes

Tier 3: Supervised (Human Confirmation Required)

Operations requiring explicit human approval before execution.

OperationToolWhy Supervised
Configure webhook URLsMCP: configure_webhookChanges production routing
Deploy to productionCLI: serverless:deploy --environment productionProduction infrastructure change
Purchase phone numberMCP: purchase_phone_numberFinancial commitment — always confirm with user
Release phone numberMCP: release_phone_numberReleases number back to Twilio pool
Rollback deploymentCLI: serverless:activateProduction impact
Delete Sync documentsMCP: delete_documentData loss potential

Tier 4: Prohibited (Never Autonomous)

Operations agents should NEVER perform autonomously.

OperationWhy Prohibited
Close/delete Twilio accountPermanent account-level destruction
Close/suspend accountCatastrophic
Force push to gitData loss potential
Deploy without tests passingQuality gate bypass
Commit with --no-verifyHook bypass
Modify production env vars directlySecurity risk
Purchase toll-free/shortcode numbersExpensive, regulatory

When to Use Each Component

Use MCP Server When

  • Agent needs to query Twilio data (logs, status, lookups)
  • Agent is sending test messages or making test calls
  • Agent is managing Sync state for its own memory
  • Agent is creating TaskRouter tasks for orchestration
  • Agent needs structured JSON responses for reasoning
  • Operation is stateless and returns immediate results

Use Twilio CLI When

  • Deploying serverless functions (serverless:deploy)
  • Local development server (serverless:start --ngrok)
  • Purchasing phone numbers (requires human approval)
  • Managing CLI profiles and credentials
  • Rollback operations (serverless:activate)
  • Interactive debugging sessions
  • One-time setup and configuration

Use Serverless Toolkit When

  • Building local development environment
  • Deploying Functions and Assets to Twilio
  • Managing environment variables per deployment
  • Viewing deployment logs and history
  • Promoting between environments (dev → prod)

Use Twilio Functions When

  • Handling inbound webhooks (calls, messages)
  • Response must be TwiML
  • Operation is triggered by real Twilio events
  • Low-latency is required (deployed on Twilio infra)
  • Need Twilio request signature validation (.protected.js)
  • Business logic runs close to Twilio infrastructure

Overlapping Functionality Resolution

When the same operation can be done multiple ways, use this guide:

SMS Sending

ToolUse When
MCP send_smsAgent-initiated: testing, debugging, proactive notifications
Function send-sms.protected.jsEvent-triggered: after call, verification success, workflow step
CLI api:core:messages:createHuman debugging, one-off manual sends

Rule: Use MCP when agent decides to send. Use Function when event triggers sending.

Debugger Logs

ToolUse When
MCP validate_debugger(resourceSid)SID-targeted: alerts for a specific call/message/resource
MCP validate_call(callSid) / validate_message(messageSid)Deep validation including debugger alerts for that resource
MCP get_debugger_logsTime-window browsing when no specific SID available
MCP analyze_errorsPattern detection and error grouping
CLI debugger:logs:listInteractive human debugging session

Rule: SID-first — use validate_* tools when you have a resource SID. Use get_debugger_logs for discovery. CLI for human debugging only.

Phone Number Configuration

ToolUse When
MCP configure_webhookAutomated configuration during deployment pipelines
CLI phone-numbers:updateInteractive setup, one-time manual configuration

Rule: Both require Tier 3 approval for production. MCP for automation, CLI for manual.

Verification

ToolUse When
MCP start_verificationAgent testing, automated verification flows
Function start-verification.protected.jsUser-facing flows triggered by form submission

Rule: Use Function for user-initiated, MCP for agent/system-initiated.

Sync State

ToolUse When
MCP validate_sync_document(serviceSid, name)SID-targeted: deep validation of a specific document
MCP validate_sync_list(serviceSid, name) / validate_sync_map(serviceSid, name)SID-targeted: validate list/map structure and contents
MCP create_document, update_document, List/Map CRUD toolsAgent state management workflows
Function (via context.getTwilioClient())Event-triggered state updates from webhooks
CLI twilio api:sync:*One-off manual inspection

Rule: SID-first for validation. MCP for agent workflows. Functions for event-triggered updates.

TaskRouter

ToolUse When
MCP validate_task(taskSid)SID-targeted: deep validation of a specific task
MCP list_workers, get_queue_statistics, list_task_queues, list_activitiesAgent monitoring and management (30 tools)
MCP create_task, update_task, update_worker, update_reservationAgent-driven task orchestration
Function (via context.getTwilioClient())Worker updates from call events, assignment callbacks
CLI twilio api:taskrouter:*One-time workspace setup

Rule: SID-first for task validation. MCP for monitoring. Functions for event-triggered routing.

Serverless Inspection

ToolUse When
MCP list_services, list_functions, list_logsAgent querying deployment state
MCP list_environments, list_builds, get_build_statusDeployment status checks
CLI serverless:deploy, serverless:activateDeployment, promotion, rollback (Tier 3)

Rule: MCP for read-only inspection. CLI for all infrastructure changes.

Account & Usage

ToolUse When
MCP get_accountAuth validation, account status check
MCP list_usage_records, get_account_balanceAutomated monitoring, cost analysis
CLI twilio api:core:accounts:fetchManual account inspection

Rule: MCP for agent-automated monitoring. CLI for manual inspection.

Recordings & Transcripts

ToolUse When
MCP validate_recording(recordingSid)SID-targeted: completion polling + status
MCP validate_transcript(transcriptSid)SID-targeted: completion + sentence extraction
MCP validate_language_operator(transcriptSid)SID-targeted: operator results on a transcript
MCP list_recordings, list_transcripts, list_sentencesDiscovery when no specific SID
CLIManual one-off retrieval

Rule: SID-first for validation. List tools for discovery only.

Studio Flows

ToolUse When
MCP trigger_flow, get_execution_status, list_execution_stepsAlways MCP for agent interaction
MCP list_studio_flows, get_flowFlow discovery and inspection

Rule: Always MCP. No dedicated CLI equivalent.

Lookups

ToolUse When
MCP lookup_phone_numberPhone number validation and carrier info
MCP check_fraud_riskFraud risk assessment

Rule: Always MCP. No dedicated CLI equivalent.

Video

ToolUse When
MCP validate_video_room(roomSid)SID-targeted: room + participants + tracks + recordings
MCP create_video_room, list_video_roomsRoom management
MCP list_room_participants, get_participantParticipant management

Rule: SID-first for room validation. Always MCP — no dedicated CLI equivalent.


MCP Server Boundaries

MCP Server SHOULD

  1. Remain a pure Twilio SDK wrapper - Direct API calls only
  2. Return JSON data - Never TwiML (that's for Functions)
  3. Be stateless - No persistent connections or file storage
  4. Validate inputs with Zod schemas - Type-safe, documented
  5. Implement rate limiting - Protect Tier 2 operations
  6. Redact sensitive data - No auth tokens in responses

MCP Server SHOULD NOT

  1. Invoke CLI commands - No exec(), spawn(), or shell calls
  2. Perform file operations - No reading/writing local files
  3. Make deployment decisions - That requires human oversight
  4. Purchase or delete resources - Financial/irreversible
  5. Modify account-level settings - Security sensitive
  6. Store state internally - Use Sync documents instead

Architecture Decision Record

Decision: MCP Stays Pure API

Context: Should MCP tools wrap CLI commands for operations like deployment?

Decision: No. MCP will NEVER wrap CLI commands.

Rationale:

  1. CLI invocation adds latency and failure modes (process spawning, parsing)
  2. CLI requires shell access, complicating security sandboxing
  3. API calls are more testable and produce predictable results
  4. Deployment must always require human oversight
  5. Keeps MCP focused on data operations, not infrastructure

Consequences:

  • Deployment is not an MCP tool (stays CLI-only)
  • Phone number purchase/release ARE MCP tools (purchase_phone_number, release_phone_number) — confirm with user before executing (financial/irreversible)
  • Account management tools exist (13 tools in P3 tier) — subaccount operations available via MCP
  • This is intentional, not a limitation

Anti-Patterns to Avoid

1. MCP Invoking CLI Commands

// DON'T DO THIS
const deployTool = {
  name: 'deploy_functions',
  handler: async () => {
    exec('twilio serverless:deploy');  // WRONG
  }
};

Why: Violates pure API principle. Deployment requires human oversight.

2. Functions Calling MCP

// DON'T DO THIS in a Function
const mcpServer = require('../mcp-servers/twilio');
await mcpServer.tools.send_sms({ to, body });  // WRONG

Why: Functions have direct SDK access via context.getTwilioClient(). MCP is for agent orchestration.

3. Duplicating Business Logic

// DON'T DO THIS
MCP: send_sms with complex retry logic
Function: send-sms.protected.js with identical retry logic

Why: Maintain single source of truth. Put business logic in Functions, keep MCP as thin wrapper.

4. Agent Deploying Autonomously

Agent: "I'll deploy these changes now."
*runs twilio serverless:deploy*  // WRONG

Why: Deployment is Tier 3 (requires human approval). Pre-bash hooks block this anyway.

5. Storing Secrets in MCP Tools

// DON'T DO THIS
const client = Twilio('ACxxxx...hardcoded', 'authtoken...hardcoded');  // WRONG

Why: Pre-write hooks block hardcoded credentials. Always use environment variables.


Decision Flowchart

Is this a webhook response to an inbound call/message?
├─ Yes → Use Functions (.js or .protected.js)
└─ No → Continue

Does the operation deploy or modify infrastructure?
├─ Yes → Use CLI (human approval required)
└─ No → Continue

Is this triggered by a real-time Twilio event?
├─ Yes → Use Functions
└─ No → Continue

Does the agent need to perform this operation?
├─ Yes → Use MCP Server tool
└─ No → Use CLI for manual operation

Is the operation read-only?
├─ Yes → MCP Tier 1 (autonomous)
└─ No → Does it cost money or affect production?
    ├─ Yes → MCP Tier 2/3 (guardrails/approval)
    └─ No → MCP Tier 2 (with rate limits)

Related Documentation

  • /agents/mcp-servers/twilio/docs/API_REFERENCE.md - Twilio API documentation and tool mapping
  • /agents/mcp-servers/twilio/CLAUDE.md - MCP server overview and usage
  • twilio-cli.md - CLI command reference (same directory)
  • /.claude/hooks/pre-bash-validate.sh - Safety hooks
  • /DESIGN_DECISIONS.md - Project-wide architectural decisions

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.