How to Build an Invoice Reminder Email Agent With the Claude Agent SDK (Python, Step-by-Step)

How to build an invoice reminder email agent with the Claude Agent SDK

Chasing late invoices is the job every freelancer and small studio puts off. You open the spreadsheet, see three clients past due, and decide you'll write those awkward emails tomorrow. In this tutorial you'll build a small Python agent with the Claude Agent SDK that does it for you: it reads your invoice list, works out who's overdue, writes a reminder in the right tone for how late they are, and either saves it as a draft or sends it. When I build this kind of thing for a client, the part that matters most isn't the AI. It's the guardrails, so we'll spend real time on those.

Quick answer: Install claude-agent-sdk (Python 3.10+), set ANTHROPIC_API_KEY, and write two custom tools with the @tool decorator: one that lists overdue invoices from a CSV and one that sends a reminder. Wrap them with create_sdk_mcp_server, pass that to query() through mcp_servers, and lock the agent down with tools=[], allowed_tools=["mcp__billing__*"] and permission_mode="dontAsk". Run it daily with cron.

What You'll Build

  • ✓ An invoices.csv file that acts as your simple billing database
  • ✓ A list_overdue_invoices tool that only reads data
  • ✓ A send_reminder tool that drafts or sends one email and refuses to remind the same client twice in 7 days
  • ✓ An agent that picks the tone (light nudge, clear request, firm follow-up) based on how many days late each invoice is
  • ✓ A cron entry that runs it every weekday morning

The agent can't touch anything else on your machine. It gets no file, shell or web tools, only the two functions you write.

Prerequisites

  • Python 3.10 or newer (the SDK's minimum)
  • An API key from the Claude Console
  • Your invoice data as a CSV export (from a spreadsheet, your accounting tool, anywhere)
  • Optional: SMTP details for the mailbox you send invoices from

You don't need to install Claude Code separately. The Python SDK ships with a bundled Claude Code binary on normal platform installs.

Step 1: Set Up the Project

Create a folder, a virtual environment and install the SDK. On macOS or Linux:

mkdir invoice-agent
cd invoice-agent
python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk
export ANTHROPIC_API_KEY=your-api-key

On Windows PowerShell:

py -m venv .venv
.venv\Scripts\Activate.ps1
pip install claude-agent-sdk
$env:ANTHROPIC_API_KEY = "your-api-key"

One thing that trips people up: the SDK reads the key from your environment and doesn't load .env files on its own. If you keep secrets in a .env, load it yourself (for example with python-dotenv) before the agent starts.

Step 2: Create the Invoice File

Save this as invoices.csv in the project folder. The last_reminder column is what stops the agent from nagging the same client every morning.

invoice_id,client,email,amount,currency,due_date,status,last_reminder
INV-1041,Northwind Cafe,accounts@northwind.example.com,1200.00,USD,2026-11-10,unpaid,
INV-1042,Bluebird Yoga,hello@bluebird.example.com,450.00,USD,2026-10-20,unpaid,2026-11-05
INV-1043,Kite Legal,billing@kite.example.com,2800.00,USD,2026-11-25,unpaid,
INV-1044,Maple Bakery,owner@maple.example.com,300.00,USD,2026-11-01,paid,

Use your own clients' details once you've tested. I always start clients on fake example.com addresses so a mistake can't reach a real inbox.

Step 3: Write the Read-Only Tool

Create agent.py. Start with the imports and two small helpers that read and write the CSV:

import asyncio
import csv
import json
import os
import smtplib
from datetime import date
from email.message import EmailMessage
from pathlib import Path
from typing import Any

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ResultMessage,
    ToolAnnotations,
    create_sdk_mcp_server,
    query,
    tool,
)

INVOICES = Path("invoices.csv")
OUTBOX = Path("outbox")
SEND_FOR_REAL = os.environ.get("SEND_EMAILS") == "1"
MIN_DAYS_BETWEEN_REMINDERS = 7


def load_invoices() -> list[dict[str, str]]:
    with INVOICES.open(newline="") as f:
        return list(csv.DictReader(f))


def save_invoices(rows: list[dict[str, str]]) -> None:
    with INVOICES.open("w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        writer.writeheader()
        writer.writerows(rows)

Now the first tool. The @tool decorator takes a name, a description Claude reads to decide when to call it, and an input schema. In Python the schema can be a plain dict of names to types, and the SDK converts it to JSON Schema for you.

@tool(
    "list_overdue_invoices",
    "List unpaid invoices that are at least min_days_overdue days past due. "
    "Each row includes days_overdue and last_reminder (blank if never reminded).",
    {"min_days_overdue": int},
    annotations=ToolAnnotations(readOnlyHint=True),
)
async def list_overdue_invoices(args: dict[str, Any]) -> dict[str, Any]:
    today = date.today()
    overdue = []
    for row in load_invoices():
        if row["status"] != "unpaid":
            continue
        days = (today - date.fromisoformat(row["due_date"])).days
        if days >= args["min_days_overdue"]:
            overdue.append({**row, "days_overdue": days})
    return {"content": [{"type": "text", "text": json.dumps(overdue, indent=2)}]}

The readOnlyHint annotation tells the SDK this tool has no side effects. It's metadata, not enforcement, so keep it honest: only put it on tools that really don't change anything.

Step 4: Write the Send Tool (With a Hard Guardrail)

This is the tool that matters. Notice that the "don't remind twice in a week" rule lives in Python, not in the prompt. A prompt is a request; code is a rule. If the guard trips, the tool returns is_error with a clear message, and Claude reads that message and moves on to the next invoice instead of crashing the run.

@tool(
    "send_reminder",
    "Send one payment reminder email for an invoice. Refuses if that invoice "
    "was reminded in the last 7 days.",
    {"invoice_id": str, "subject": str, "body": str},
)
async def send_reminder(args: dict[str, Any]) -> dict[str, Any]:
    rows = load_invoices()
    row = next((r for r in rows if r["invoice_id"] == args["invoice_id"]), None)
    if row is None:
        return {
            "content": [{"type": "text", "text": f"No invoice {args['invoice_id']}."}],
            "is_error": True,
        }
    if row["last_reminder"]:
        gap = (date.today() - date.fromisoformat(row["last_reminder"])).days
        if gap < MIN_DAYS_BETWEEN_REMINDERS:
            return {
                "content": [{"type": "text", "text": f"Skipped: reminded {gap} days ago."}],
                "is_error": True,
            }

    msg = EmailMessage()
    msg["From"] = os.environ.get("FROM_EMAIL", "billing@example.com")
    msg["To"] = row["email"]
    msg["Subject"] = args["subject"]
    msg.set_content(args["body"])

    if SEND_FOR_REAL:
        with smtplib.SMTP(os.environ["SMTP_HOST"], 587) as smtp:
            smtp.starttls()
            smtp.login(os.environ["SMTP_USER"], os.environ["SMTP_PASSWORD"])
            smtp.send_message(msg)
        where = f"sent to {row['email']}"
    else:
        OUTBOX.mkdir(exist_ok=True)
        path = OUTBOX / f"{row['invoice_id']}.eml"
        path.write_bytes(bytes(msg))
        where = f"saved as draft {path}"

    row["last_reminder"] = date.today().isoformat()
    save_invoices(rows)
    return {"content": [{"type": "text", "text": f"Reminder for {row['invoice_id']} {where}."}]}

By default nothing is sent. Every reminder lands in an outbox/ folder as an .eml file you can open in any mail client. Emails only go out when you set SEND_EMAILS=1.

Step 5: Register the Tools and Lock Down the Agent

Wrap both tools in an in-process MCP server. It runs inside your Python process, not as a separate server you have to host.

billing = create_sdk_mcp_server(
    name="billing",
    version="1.0.0",
    tools=[list_overdue_invoices, send_reminder],
)

Next, the system prompt. This is where you set tone and business rules that don't need hard enforcement:

SYSTEM_PROMPT = """You are the accounts-receivable assistant for a small design studio.
Your job: find overdue invoices and send one short, friendly reminder for each.

Rules:
- Call list_overdue_invoices with min_days_overdue=3 first.
- Tone depends on days_overdue: under 15 = light nudge, 15 to 30 = clear
  request with the amount and due date, over 30 = firm but polite, and ask
  the client to reply with a payment date.
- Always mention the invoice number, amount and currency.
- Never threaten, never add late fees, never invent payment links.
- Sign off as "Accounts, Pixel and Pine Studio".
- If send_reminder returns an error, skip that invoice and move on.
- Finish with a one-line summary per invoice: sent, drafted or skipped."""

Finally, the main loop. The options here are the security model, so read the comments:

async def main() -> None:
    options = ClaudeAgentOptions(
        system_prompt=SYSTEM_PROMPT,
        mcp_servers={"billing": billing},
        tools=[],                              # no built-in tools at all
        allowed_tools=["mcp__billing__*"],     # pre-approve only our two tools
        permission_mode="dontAsk",             # anything else is denied, never prompts
        max_turns=20,
        max_budget_usd=0.50,
        setting_sources=[],                    # ignore local Claude Code settings
    )
    async for message in query(
        prompt="Check for overdue invoices and handle today's reminders.",
        options=options,
    ):
        if isinstance(message, ResultMessage):
            print(f"Finished: {message.subtype}")
            if message.result:
                print(message.result)
            if message.total_cost_usd is not None:
                print(f"Cost this run: ${message.total_cost_usd:.4f}")


if __name__ == "__main__":
    asyncio.run(main())

Here's what each setting does:

  • tools=[] removes every built-in tool (Bash, Read, Edit, web search) from Claude's context. Your MCP tools aren't affected.
  • allowed_tools=["mcp__billing__*"] pre-approves your two tools. Custom tool names follow the pattern mcp__{server_key}__{tool_name}, and the key is the one you used in mcp_servers.
  • permission_mode="dontAsk" turns any call that would need approval into a denial. Nobody's watching a cron job, so there's no one to click "allow" anyway.
  • max_turns and max_budget_usd put a ceiling on a run that goes sideways. The budget is a client-side estimate and can overshoot a little, so leave headroom.
  • setting_sources=[] stops the agent from picking up Claude Code settings, hooks or permissions from your user or project folders.

Step 6: Test in Draft Mode, Then Go Live

Run it:

python agent.py

You'll see a summary line per invoice and the cost of the run, pulled from ResultMessage.total_cost_usd. Open the files in outbox/ and read every draft. Check the tone, the amounts and the sign-off. Then reset the last_reminder column in your CSV and run it again to see how the wording changes. When you're happy, add your SMTP details and switch sending on:

export SMTP_HOST=smtp.yourprovider.com
export SMTP_USER=billing@yourdomain.com
export SMTP_PASSWORD=your-app-password
export FROM_EMAIL=billing@yourdomain.com
SEND_EMAILS=1 python agent.py

Many providers won't accept your normal login over SMTP and want an app password instead, so check your provider's settings page first.

Step 7: Run It Every Weekday

On macOS or Linux, add a line to your crontab (crontab -e). Cron doesn't load your shell profile, so pass the key and use the full path to the venv's Python:

0 9 * * 1-5 cd /home/you/invoice-agent && ANTHROPIC_API_KEY=your-api-key SEND_EMAILS=1 /home/you/invoice-agent/.venv/bin/python agent.py >> agent.log 2>&1

On Windows, create a daily task in Task Scheduler that runs .venv\Scripts\python.exe agent.py with the project folder as the start location. If you'd rather not keep a machine on, the same job works as a Claude scheduled task; I walked through that setup in my Cowork scheduled task tutorial.

Troubleshooting

"Not logged in" or "Invalid API key"

ANTHROPIC_API_KEY isn't set in the shell (or cron line) that runs the script. Remember the SDK won't read a .env file for you.

CLINotFoundError

The bundled Claude Code binary is missing. This happens when pip installs the source distribution instead of a platform wheel, for example on ARM64 Windows. Try pip install --force-reinstall claude-agent-sdk, or install Claude Code natively so the SDK finds it on your PATH.

Claude says it can't use the tools

Check that the key in mcp_servers (here billing) matches the prefix in allowed_tools. In dontAsk mode, a tool that isn't pre-approved is silently denied.

The run ends with error_max_turns or error_max_budget_usd

Your limits are too tight for the size of your invoice list. Raise max_turns a little at a time. If you have hundreds of invoices, filter the CSV down before the agent sees it.

Nothing was emailed

Sending is off unless SEND_EMAILS=1 is set. Look in outbox/: your drafts are there.

setting_sources=[] seems to be ignored

Python SDK 0.1.59 and earlier treated an empty list like "not set". Upgrade the package.

Frequently Asked Questions

Can I use my Claude Pro or Max subscription instead of an API key?

Not for an agent you build or ship to others. Anthropic's docs say third-party developers can't offer claude.ai login or rate limits in their products without prior approval, and point you to API key authentication. Amazon Bedrock, Google Cloud and Microsoft Foundry credentials also work.

How much does each run cost?

You pay normal API token rates, and it depends on how many invoices you have and how long the emails are. Don't guess: the script prints total_cost_usd after every run, and max_budget_usd stops a run that gets expensive.

Can it read invoices from Google Sheets instead of a CSV?

Yes. Replace load_invoices and save_invoices with calls to the Sheets API, and the agent doesn't change. If you want Claude itself to talk to Sheets, see my Claude and Google Sheets tutorial.

Is the Agent SDK only for Python?

No. There's a TypeScript SDK too (Node.js 18.14+). The same idea works there with tool(), createSdkMcpServer and Zod schemas.

Can other apps use these tools?

The tools in this tutorial live inside your script. If you want the same invoice tools available in Claude Desktop, build them as a standalone MCP server instead. My FastMCP tutorial shows how with a very similar invoice example.

Wrapping Up

An invoice reminder agent is about 150 lines of Python: two tools, a system prompt for tone, and a tight set of options so it can't do anything you didn't plan for. Run it in draft mode for a week, read what it writes, and only then let it send. Once it's earning its keep, the same pattern works for quote follow-ups, contract renewals and "your subscription ends soon" emails.

Want this built for your business?

I'm Basant, an AI automation consultant. Book a call: https://topmate.io/basant_narayan_singh

See more of my work at singhbasant.com.

NextGen Digital... Welcome to WhatsApp chat
Howdy! How can we help you today?
Type here...