GuidesIntermediate · 8 steps

Build AI Agents That Handle 2FA: SMS Verification Guide

How to build AI agents that handle SMS 2FA on real carrier numbers: polling the 15-minute window, automatic refunds, and setup via MCP, skill or REST API.

VoidMob Team
12 min read
Updated Oct 1, 2026

Every developer building autonomous AI agents hits the same wall: two-factor authentication. The agent can browse, fill forms and run a whole workflow, until it reaches SMS verification. Then everything stops.

Most guides skip this part entirely or suggest manual workarounds that defeat the purpose of automation. But SMS-based 2FA isn't going anywhere. Platforms rely on it as their primary authentication layer, and AI agents need to handle it programmatically if they're going to operate without constant human intervention.

This guide walks through building AI agent 2FA handling that holds up in production: the number, the polling loop, the timeouts and the failure modes of SMS verification.

Key takeaways

  • VoIP numbers fail because platforms check carrier databases that identify line types at the infrastructure level: you need real mobile numbers connected to carrier networks
  • Successful SMS automation requires three components: real non-VoIP carrier numbers, programmatic API access with fast polling, and session persistence for account-number pairing
  • Services behave differently: some delay the SMS, some limit attempts per hour, some fall back to a voice call, so size timeouts per service and log what you see
  • Pair the number with a connection in the same country: a mobile proxy there gives the session a carrier IP where the number is registered
  • On VoidMob a one-time US number stays open 15 minutes and can receive several codes; if no SMS arrives the price is refunded automatically, except on services marked non-refundable

Why Most AI Agents Fail at 2FA

The typical failure pattern looks like this: developer builds a solid agent using Selenium or Playwright, automates login flows perfectly, then hits SMS verification and bolts on a VoIP number from some free service.

Works once. Fails the second time because platforms blacklist VoIP ranges aggressively.

Google Voice, Twilio, and similar services show up in carrier databases as non-mobile lines. Instagram blocks them outright. Twitter flags accounts. LinkedIn requires additional verification. Even smaller platforms now check against HLR (Home Location Register) databases that expose VoIP numbers instantly.

And that's before parallel runs. A test suite that runs several sessions at once needs a number for each, which with physical SIM cards means buying, activating and looking after a drawer of phones.

VoIP Detection is Universal

Platforms don't just block known VoIP providers. They query carrier databases that identify line types at the infrastructure level. A number either originates from a mobile network or it doesn't: there's no middle ground.

The Real Infrastructure Requirements

Building reliable AI agent 2FA systems requires actual mobile numbers connected to carrier infrastructure. Not shortcuts. Not workarounds.

Three components make this work:

Real carrier numbers - Each verification needs a number that platforms recognize as legitimate mobile service: a non-VoIP number issued by a mobile carrier, not a virtual phone system.

Programmatic API access - Manual checking defeats automation entirely. The agent needs to request a number, receive it instantly, then poll for incoming SMS codes through API calls. Response times matter here because most 2FA codes expire in 5-10 minutes.

Session persistence - Some platforms remember which number verified which account. Rotating numbers randomly triggers security flags. Better systems let developers reserve specific numbers for specific accounts across sessions.

The tricky part is that AI SMS verification at scale looks more like infrastructure management than a simple API integration.

Step-by-Step Implementation

Let's look at how to structure the authentication flow architecture. The AI agent needs to detect when a platform requests SMS verification, pause the automation sequence, obtain a phone number, submit it, retrieve the code, and resume, with nobody copying the code by hand.

Most developers structure this as a state machine with explicit checkpoints:

text
LOGIN_INITIATED -> PHONE_REQUESTED -> NUMBER_SUBMITTED -> CODE_PENDING -> CODE_RECEIVED -> VERIFICATION_COMPLETE
sms_verification.py
1import requests2import time3 4class SMSVerificationHandler:5  def __init__(self, api_key):6      self.api_key = api_key7      self.base_url = "https://api.provider.com/v1"8 9  def get_number(self, service):10      """Request a phone number for specific service"""11      response = requests.post(12          f"{self.base_url}/numbers/request",13          headers={"Authorization": f"Bearer {self.api_key}"},14          json={"service": service, "country": "US"}15      )16      return response.json()["number"], response.json()["session_id"]17 18  def poll_for_code(self, session_id, timeout=300):19      """Poll for SMS code with exponential backoff"""20      start_time = time.time()21      wait_time = 222 23      while time.time() - start_time < timeout:24          response = requests.get(25              f"{self.base_url}/messages/{session_id}",26              headers={"Authorization": f"Bearer {self.api_key}"}27          )28 29          if response.json().get("code"):30              return response.json()["code"]31 32          time.sleep(wait_time)33          wait_time = min(wait_time * 1.5, 15)34 35      raise TimeoutError("SMS code not received within timeout period")36 37## Usage in AI agent flow38handler = SMSVerificationHandler(api_key="your_key")39phone_number, session_id = handler.get_number("instagram")40# Agent submits phone_number to platform41verification_code = handler.poll_for_code(session_id)42# Agent enters verification_code

The polling logic matters more than it looks. Checking every second hammers the API and wastes resources. Exponential backoff starting at 2 seconds, capping at 15, gives you 12-15 checks over 5 minutes, which is enough to catch codes quickly without excessive requests.

Running the Flow on VoidMob

The handler above is generic. On VoidMob, a person does one setup step: create an API key in the dashboard under Developers > API Keys and top up the prepaid balance with crypto. There is no sign-up or deposit endpoint for agents. After that, the agent requests numbers and reads codes inside its own task through one of three paths:

  • REST API: point base_url at https://dashboard.voidmob.com/api/v1 and send the key as a bearer token. Endpoints, idempotency and rate limits are in the VoidMob developer docs.
  • MCP server: npx -y @voidmob/mcp, with the key in the client's env as VOIDMOB_API_KEY. VOIDMOB_SANDBOX=1 runs every tool on mock data with play money and no key. It is a local stdio server with no hosted MCP URL; per-client install commands are on the VoidMob MCP server page.
  • Agent skill: tell any agent with a shell Read https://voidmob.com/skill.md and follow it, or install it with npx skills add voidmobcom/voidmob-mcp --skill voidmob.

Runtime guides cover OpenClaw setup, Hermes Agent setup, Pi coding agent setup and Grok Bot setup, and VoidMob for AI agents covers the jobs agents use it for.

Size the timeout to the window, not to the 5 minutes above. A one-time US non-VoIP number stays open up to 15 minutes and can receive several codes. If no SMS arrives, the price is refunded automatically, except on services marked non-refundable, so poll until the code arrives or the window closes instead of cancelling early: frequent cancellations can pause SMS purchasing. One-time numbers cover the services in VoidMob's catalog. To test your own app's SMS 2FA flow, use a dedicated monthly number, which receives SMS from any sender.

The MCP server tells the agent to quote the price and get the user's go-ahead, and every buy carries that approved price (max_price_cents): if the live price has risen, nothing is charged and the new price comes back for approval. For hard limits, start the server with VOIDMOB_MAX_ORDER_CENTS (per purchase), VOIDMOB_BUDGET_CENTS (per server session) or VOIDMOB_READ_ONLY=1; a purchase over a limit is refused and charges nothing. The key itself has no spend cap, so the prepaid balance is the account-wide limit: fund only what agents should spend.

15 min
Verification window
A one-time number stays open this long
Several
Codes per number
Within the same window
Refunded
No SMS
Automatically, except services marked non-refundable

Handling Service-Specific Behavior

Services do not send codes the same way. Some hold the SMS back for a while after the request, some limit how many codes a number can request per hour, and some switch to a voice call after a failed attempt. None of that is documented reliably, so treat it as data: log the time from request to code for each service your agent touches and set that service's timeout from your own numbers, never shorter than a minute and never longer than the 15-minute window.

Match the number's country to the account's country. A US account gets a US number; for an account registered elsewhere, a dedicated number in that country receives the code.

Managing Numbers Across Several Agents

Running several agents at once means managing several active phone numbers, tracking which number belongs to which account, and handling renewal/rotation schedules. On VoidMob, up to 5 one-time verification numbers can wait for a code at the same time by default (higher limits on request); long-term rentals and dedicated numbers don't count toward that limit.

The database schema should track:

  • Number assignment (which agent/account uses which number)
  • Verification history (success/failure rates per number)
  • Cooldown periods (platform-specific reuse restrictions)
  • Cost tracking (per-verification pricing adds up fast)

Dedicated numbers work better for long-term accounts. Shared pool numbers cost less for one-time verifications. Some platforms let developers switch between modes depending on use case.

One Number per Account

Give each long-lived account you own its own number and keep it. Login and recovery codes go to the number on file, so an account tied to a one-time number that has expired can lock you out. A dedicated monthly number stays yours and keeps receiving codes.

Proxies: Keep the Connection in the Number's Country

Verification flows go more smoothly when the connection comes from the same country as the number. Many services compare the two, so a US number submitted from a datacenter IP in Frankfurt is a common reason for an extra check or a refusal.

A mobile proxy in the number's country gives the session a carrier IP there instead of a cloud address. For an agent running on a server, the session then comes from a mobile network in the number's country rather than from a data center abroad.

For the network side (why agents fail on cloud IPs, sessions, rotation and coordinating many agents), see AI agents on mobile infrastructure.

Common Failure Modes and Fixes

Code never arrives - The service may have refused the number or delayed the SMS. Check whether that service limits how often one number can request a code, and try a new number if the window closes empty. On a VoidMob one-time number, an attempt that gets no SMS is refunded automatically when the 15-minute window closes (except on services marked non-refundable), so let the window run out rather than cancelling and rebuying.

Code arrives but expired - The polling interval is too slow or timeout too short. Increase check frequency during the first 60 seconds when most codes arrive.

Platform rejects number as invalid - VoIP detection or the number's already associated with another account. Verify the provider supplies actual mobile numbers, not virtual ones. Check platform-specific limits on number reuse.

Verification succeeds but account gets flagged later - Session fingerprinting mismatch. The agent's browser fingerprint, IP location, and phone number geography need to align.

Sometimes a service's SMS delivery is simply slow or down. Build retry logic with a new number and accept that some attempts fail for reasons outside your control.

Production Deployment Checklist

Before running AI agents with automated 2FA in production:

  • Test each target platform individually with manual verification first
  • Implement comprehensive logging (every number request, code received, verification attempt)
  • Set up monitoring for success rates below expected thresholds
  • Configure alerts for repeated failures on specific platforms
  • Build cost tracking - verification fees scale faster than expected
  • Create fallback flows for manual intervention when automation fails
  • Document platform-specific quirks and timeout requirements

Monitor number pool health regularly. Numbers that consistently fail verifications should be rotated out. Track which platforms accept which numbers most reliably. Over time patterns emerge that improve success rates.

FAQ

Can AI agents handle 2FA for any platform?

Most SMS-based 2FA works, but some platforms use app-based authentication (Google Authenticator, Authy) that's harder to automate. Email-based 2FA is actually easier than SMS. Hardware token systems (YubiKey) generally can't be automated.

How much does SMS verification infrastructure cost at scale?

Per-verification prices vary by platform. VoidMob shows each service's one-time price before purchase and refunds it automatically if no SMS arrives, except on services marked non-refundable. Dedicated monthly numbers are priced per country. Multiply the per-verification price by daily volume, add the monthly numbers, and budget accordingly based on agent count.

Is this legal?

Using AI authentication systems is legal when verifying owned accounts or accounts with permission to access. Violating platform terms of service is a separate issue: many platforms restrict automation regardless of how 2FA is handled. Know the rules before deploying.

What's the difference between SMS verification and mobile proxies?

They answer different checks. A non-VoIP number receives the code a service sends to a phone. A mobile proxy gives the session a carrier IP in a chosen country instead of a datacenter address. A flow that only needs a code needs only the number; an agent running on a server in another country usually needs both.

Why not just use virtual phone number services?

They're detected and blocked. Platforms check carrier databases that identify VoIP vs real mobile lines. Virtual numbers work for low-security scenarios but fail on any platform with serious fraud prevention (social media, financial services, e-commerce).

Wrapping Up

Building AI agents that handle two-factor authentication reliably comes down to infrastructure choices. VoIP shortcuts fail fast. Real mobile numbers connected to carrier networks pass verification consistently. Proper API integration lets agents handle the entire flow programmatically.

The implementation isn't complex: request a number, submit it, poll for the code, verify. But the underlying infrastructure determines whether that simple flow succeeds occasionally or consistently.

For developers looking to understand the broader context of non-VoIP SMS verification, our comprehensive SMS verification guide covers the fundamentals in detail.

Automate SMS Verification for Your AI Agents

VoidMob provides real mobile numbers, proxies, and eSIMs through one API. Build reliable AI agent 2FA systems without managing physical SIM cards.