Skip to main content
Glama
ai-caller-mcp

ai-caller-mcp

README.md
# ai-caller

Let ChatGPT or Claude phone people **in your own cloned voice, from your own mobile number**.

You tell your assistant "call Alex and ask when he's free for a climb on Saturday". It calls a
tool on this server, and an ElevenLabs voice agent speaking in your cloned voice rings Alex. Alex's
phone shows your mobile number. When the call ends, the assistant reads the transcript and tells
you what was agreed.

```
ChatGPT / Claude ──MCP──▶ mcp_server.py (Cloud Run) ──API──▶ ElevenLabs agent (your voice)
                                                               │  native Twilio integration
                                                               ▼
                                              Twilio, From = your verified mobile ──▶ the person's phone
```

No server of ours sits in the audio path: ElevenLabs places the call through your Twilio account.
The MCP server only starts calls, reads transcripts and keeps a small phone book.

It was built and tested in New Zealand, so phone numbers are checked as NZ numbers
(`callerid_test.normalise_nz`). To call elsewhere, change that function and the `+64` check in
`phonebook.py`.

> **Use it responsibly.** The agent is told never to claim to be human when sincerely asked.
> Check the rules on automated calls, AI disclosure and recording where you live. Only call
> people who would be fine getting a call from you.

## What's in the repo

| File | What it does |
| --- | --- |
| `callerid_test.py` | Phase 0: proves Twilio calls show **your** number (verify the caller ID, place a test call, log what the phone showed). |
| `voice_agent.py` | Phase 1: CLI for ElevenLabs (list voices and numbers, import your Twilio number, create or update the agent, place a call). |
| `mcp_server.py` | Phase 2: the remote MCP server (FastMCP), with Google sign-in for ChatGPT and Claude. Tools: `place_call`, `get_call`, `list_recent_calls`, `list_contacts`, `save_contact`, `delete_contact`. |
| `phonebook.py` | Named contacts, so you can say "call Alex". |
| `credentials.py` | Reads credentials from environment variables or the OS keyring. Nothing secret lives in the repo. |
| `prompts/mcp_base.txt` | The agent's system prompt. Each call's brief is passed in as `{{call_brief}}`. |
| `terraform/` | Cloud Run service, Firestore, Secret Manager and Artifact Registry on Google Cloud. |
| `scripts/push_secrets.sh` | Puts your ElevenLabs key and Google OAuth secret into Secret Manager at a hidden prompt. |
| `tests/` | Offline tests (fake Twilio and ElevenLabs): `pytest tests`. |

## What you need

- A **paid Twilio account**. Trial accounts call only verified numbers and show a Twilio number,
  which defeats the point. Verified caller IDs live in the **US1** region, so the call is routed
  through the US.
- An **ElevenLabs account** on a plan with Agents and Instant Voice Cloning.
- For ChatGPT or Claude: a **Google Cloud project** with billing (Cloud Run scales to zero; at one
  person's use the bill is about cents), plus `gcloud` and `terraform`.
- Python 3.12 or newer.

```bash
git clone https://github.com/<you>/ai-caller && cd ai-caller
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements-dev.txt
pytest tests          # offline, no credentials needed
```

Credentials are read by `credentials.py`: an environment variable (`TWILIO_ACCOUNT_SID`,
`TWILIO_AUTH_TOKEN`, `ELEVENLABS_API_KEY`), or the OS keyring:

```bash
python credentials.py set twilio/account_sid      # hidden prompt
python credentials.py set twilio/auth_token
python credentials.py set elevenlabs/api_key
```

Set your name once. The agent uses it ("Hi, it's Alex's AI assistant"):

```bash
export AI_CALLER_OWNER_NAME=Alex
```

## Phase 0: does a call show your number?

Mobile numbers usually can't be ported to a programmable carrier. Twilio's *verified outgoing
caller ID* is the route: you prove you own the number, then Twilio may send it as `From`. Whether
the other side's phone shows it depends on the carriers, so test before building anything on top.

1. Twilio Console → Voice → Settings → Geo permissions: allow your country.
2. Run:

```bash
python callerid_test.py account                         # Trial or Full?
python callerid_test.py verify 021XXXXXXX               # Twilio calls you; type the code it prints
python callerid_test.py call --to 027YYYYYYY --network spark
python callerid_test.py result CA... shown               # or hidden / other-number / blocked / not-answered
python callerid_test.py log
```

`--dry-run` (before the command) prints requests without sending them. Results go to
`data/callerid_tests.jsonl` (gitignored). In NZ, a call to a 020 mobile showed the owner's number.

## Phase 1: a voice agent in your voice

1. ElevenLabs → Voices → **Instant Voice Clone**: record or upload 1–2 minutes of clean speech.
2. Import your verified number into ElevenLabs and create the agent:

```bash
python voice_agent.py voices                              # your clone's voice_id
python voice_agent.py import-number +6421XXXXXXX          # uses the Twilio SID + token
python voice_agent.py numbers                             # note the phnum_... id
python voice_agent.py create-agent --voice-id <voice_id> \
    --name "MCP caller (my voice)" \
    --prompt-file prompts/mcp_base.txt \
    --first-message "{{opening_line}}" \
    --tts-model eleven_v4_turbo
python voice_agent.py agents                              # note the agent_... id
```

`create-agent` sets up what was learned the hard way:

- **Model:** Claude Haiku 5.5 with no reasoning. In a text-only test it started replying in
  0.3–0.5 s, against 0.4–1.5 s for Sonnet 5.5. DeepSeek was fastest but once went silent on a
  real call.
- **Backup models:** GPT-5.4 mini, then Gemini 3.5 Flash, from other providers. They take over if
  the main model hasn't started answering after 2 s (ElevenLabs' default is 4 s).
- **Turn-taking:** `eager`, so the agent replies as soon as the caller seems done. It may
  occasionally jump into a mid-sentence pause.
- **Built-in tools:** `end_call` and `play_keypad_touch_tone` (DTMF). New ElevenLabs agents have
  every tool off, and an agent that can't press keys gets stuck on a voicemail's "press 1 to send".
- **TTS model:** English agents accept only `eleven_turbo_v2`, `eleven_flash_v2` and
  `eleven_v4_turbo`. v4 turbo sounded most like the owner.

An existing agent can be brought up to date with `python voice_agent.py update-agent --agent-id
agent_... --prompt-file prompts/mcp_base.txt`.

A first call to yourself, with no server involved (the built-in test prompt):

```bash
python voice_agent.py create-agent --voice-id <voice_id>   # test agent, remembered in data/agent.json
python voice_agent.py call --to 021XXXXXXX
```

## Phase 2: the MCP server for ChatGPT and Claude

### Run it locally (no sign-in)

```bash
export AI_CALLER_NO_AUTH=1 AI_CALLER_AGENT_ID=agent_... AI_CALLER_PHONE_NUMBER_ID=phnum_...
python mcp_server.py               # http://127.0.0.1:8765/mcp
```

Try it with the MCP Inspector (`npx @modelcontextprotocol/inspector`) or any local MCP client. In
this mode the phone book lives in memory.

### Deploy to Google Cloud

1. **Infrastructure.** Copy `terraform/terraform.tfvars.example` to `terraform/terraform.tfvars`
   (gitignored), fill it in, then:

   ```bash
   cd terraform && terraform init && terraform apply
   ```

   This creates the Cloud Run service `ai-caller-mcp` (running a placeholder image), its service
   account, the Firestore database `ai-caller`, Secret Manager secrets (two generated keys plus
   placeholders for the two you supply), an Artifact Registry repository and public invoker
   access. The app's own OAuth rejects everyone else. Note the outputs `ai_caller_mcp_url`,
   `ai_caller_google_redirect_uri` and `image`.

2. **Google sign-in.** In Google Cloud Console → Google Auth Platform:
   - Branding and Audience: External; add your Gmail address as a test user, or publish the app.
     The `openid` + `email` scopes need no verification, and apps left in "Testing" may have
     their refresh tokens expired.
   - Clients → Create → **Web application**. Authorized JavaScript origin: the service URL.
     Authorized redirect URI: `ai_caller_google_redirect_uri`, exactly.

3. Put the client ID into `ai_caller_google_oauth_client_id` in `terraform.tfvars` and run
   `terraform apply` again.

4. **Secrets.** Paste the ElevenLabs key and the Google client secret at hidden prompts:

   ```bash
   PROJECT=my-gcp-project REGION=australia-southeast1 scripts/push_secrets.sh
   ```

5. **Build and deploy the image:**

   ```bash
   IMAGE=$(terraform -chdir=terraform output -raw image)
   gcloud builds submit --tag "$IMAGE" .
   gcloud run deploy ai-caller-mcp --image "$IMAGE" --region australia-southeast1
   curl "$(terraform -chdir=terraform output -raw ai_caller_mcp_url | sed 's#/mcp$##')/api/healthz"
   ```

   Use `/api/healthz`, not `/healthz`: Google's front end answers the bare `/healthz` path on
   `*.run.app` itself, with a 404.

6. **Connect.**
   - ChatGPT: Plugins → **+** → Add custom MCP server. URL: `ai_caller_mcp_url` (ends in `/mcp`).
     Auth: OAuth. Sign in with Google.
   - Claude: Settings → Connectors → Add custom connector, same URL.

   ChatGPT asks you to confirm every `place_call`, because the tool is marked destructive.

### How the server behaves

- **Sign-in:** OAuth 2.1 served by the app itself (FastMCP `GoogleProvider`). It has to be an
  OAuth proxy, because Google offers no dynamic client registration. Tokens work only for verified
  Google accounts listed in `AI_CALLER_ALLOWED_EMAILS`; everyone else gets 401. Only ChatGPT, Claude
  and localhost callback URLs are accepted.
- **State:** OAuth registrations and the phone book are Fernet-encrypted in Firestore. Without
  this, every cold start would force ChatGPT to reconnect.
- **Stateless HTTP:** Cloud Run scales to zero, and a new instance knows no MCP session ids. With
  sessions on, ChatGPT's reconnect got 404 "session not found" and the connector showed as
  disconnected, so the server runs with `stateless_http=True`.
- **Firestore keys:** ChatGPT identifies itself with a URL as `client_id`. Firestore treats `/` in
  a document id as a path separator, so the store's key sanitizer is switched on.
- **One instance:** `max_instance_count = 1`, because the OAuth proxy's refresh-token replay
  protection is per process.

## Writing a good brief

The assistant writes the brief, and the brief is the whole job description for the call. Good
briefs:

- say who is being called and why, in the second person ("You are calling Alex to…");
- give the facts the caller may use (dates, places, a booking reference) and say what it must not
  promise;
- include any numbers to key in on a phone menu. The agent presses keys itself, but only enters
  codes given in the brief;
- keep the call in one language, unless the person on the other end prefers another.

## Costs

You pay Twilio per minute (an outbound call to a mobile, from the US1 region), ElevenLabs credits
per minute of agent conversation, and the LLM usage ElevenLabs bills through. Cloud Run, Firestore
and Secret Manager cost cents at personal use.

## License

MIT, see `LICENSE`.