Agents

Skills teach your agent the API. Unit works inside the dashboard. MCP lets an agent call the API. All of it is on this page.

Skills

The skill is documentation an agent loads on demand: endpoints, ID prefixes, scopes, pagination, and send-safety rules. It is not a live connection and it contains no secrets. Install it, then give the agent a key at runtime.

Install
npx skills add unitpostcom/skills --skill unitpost
npx skills add unitpostcom/skills --skill unitpost -g

Unit

Unit is the assistant in the dashboard. Describe the outcome and it does the work — templates, campaigns, segments, automations — and asks before anything sends.

Meet Unit

MCP

The MCP server is the live tool surface. One tool per API operation. Connect in the browser with OAuth, or paste a key for headless clients.

Server URLhttps://mcp.unitpost.com/mcp
TransportStreamable HTTP
Auth (recommended)OAuth 2.1 — add the URL, approve in the browser(scopes match API capabilities; tokens refresh automatically)
Auth (legacy)Authorization: Bearer pk_live_YOUR_KEY(workspace API key from Settings → API keys; for clients that can only paste a key)
Toolsone per API operation (email_send, email_campaigns_send, …)(the default set)
Toolsets (optional)https://mcp.unitpost.com/mcp?toolsets=default,campaigns(or the X-MCP-Toolsets header; add ?readonly=1 for read-only tools)

Cursor

Add the server URL and approve in the browser (Cursor handles OAuth itself, including reconnect). Static key config still works as a fallback.

  1. Connect with OAuth (recommended)

    Add a remote server with the URL below — Cursor opens Unitpost in the browser to approve. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically. If Cursor ever signs you out, the Authenticate button re-runs the same approval (a 401 from us triggers its reconnect).

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "url": "https://mcp.unitpost.com/mcp"
        }
      }
    }

    Prefer this over pasting secrets. To pin credentials instead, add an auth object with CLIENT_ID: cursor-oauth (public client, PKCE — no secret needed).

  2. Reload and verify

    Reload MCP servers in Cursor. unitpost should show connected with tools like email_send, email_campaigns_send, email_domains_verify.

  3. Send a test

    Ask the agent to send a test email from a verified domain, then confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Claude Code

Add the server URL, then authenticate from the in-session MCP panel. The browser opens at the Authenticate step, not at add time. API keys still work as a fallback.

  1. Add the server

    Run once. This only saves the URL — no browser opens yet.

    Shell
    claude mcp add --transport http unitpost https://mcp.unitpost.com/mcp

    Use -s user to install for every project. claude mcp list now shows unitpost as ! Needs authentication — that is expected.

  2. Authenticate with OAuth (recommended)

    Start a Claude Code session, run /mcp, select unitpost, and choose Authenticate. Your browser opens to Unitpost — pick a workspace, approve the scopes, and you're connected. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    If the browser doesn't open automatically, copy the URL shown in the terminal and open it manually. Tokens refresh automatically; if auth ever lapses, repeat this step.

  3. Verify

    Run claude mcp list (or /mcp in a session). unitpost should show connected with its tools listed — no ! Needs authentication flag.

    Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.

  4. Send a test

    Ask Claude to send an email from a verified domain and confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Claude Desktop

Claude Desktop connects with OAuth: add the server URL, approve in the browser, done. No browser or older plan? The headless guide has the mcp-remote bridge config.

  1. Add a custom connector (recommended)

    In Claude Desktop: Settings → Connectors → Add custom connector. Paste the server URL below as the Remote MCP server URL and complete the browser approval. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    Remote MCP server URLhttps://mcp.unitpost.com/mcp
  2. Verify

    The unitpost connector should show as connected with its tools available in chat.

    Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.

  3. Send a test

    Ask Claude to send an email from a verified domain and confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Claude

Add the server URL as a custom connector once on claude.ai and approve in the browser; the connector is then available in Claude on the web, Desktop, and mobile.

  1. Add a custom connector

    On claude.ai: Settings → Connectors → Add custom connector. Paste the server URL below and complete the browser approval. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    Remote MCP server URLhttps://mcp.unitpost.com/mcp

    On a Team or Enterprise plan, an Owner may need to add the connector for the organization first.

  2. Verify

    Open a chat, check the unitpost connector is enabled in the tools menu, and ask Claude to list your sending domains.

  3. Send a test

    Ask Claude to send a test email from a verified domain. Send tools are marked destructive, so Claude asks before anything goes out. Confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Codex

The Codex CLI, IDE extension and app share one config file, so connecting once covers all three. Add the server URL and sign in with OAuth in the browser.

  1. Add the server

    Run the command below; Codex detects OAuth and starts sign-in right away. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically. In the Codex app or IDE extension instead: Settings → MCP servers → Add server, name it unitpost, choose Streamable HTTP, paste the server URL and save, then click Authenticate.

    Shell
    codex mcp add unitpost --url https://mcp.unitpost.com/mcp

    Leave the bearer token and header fields empty: OAuth needs neither.

  2. Sign in again when needed

    If sign-in was skipped or has lapsed, run codex mcp login unitpost, or click Authenticate next to unitpost in the app's MCP servers list.

  3. Verify

    Run codex mcp list. unitpost shows OAuth in the Auth column (Not logged in means sign-in is still pending). In a session, /mcp lists its tools, like email_send and email_domains_list.

    Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.

  4. Send a test

    Ask Codex to send an email from a verified domain and confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

ChatGPT

Add the server URL as a custom MCP connector in ChatGPT and approve in the browser. Codex keeps its own MCP config: see the Codex guide.

  1. Connect with OAuth

    In ChatGPT, open the MCPs tab and connect a custom MCP. Select Streamable HTTP, paste the server URL below, and complete the browser approval. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    MCP server URLhttps://mcp.unitpost.com/mcp

    Custom MCP connectors may need developer mode, or a workspace admin on Business and Enterprise plans.

  2. Verify

    Start a chat with the unitpost connector enabled and ask ChatGPT to list your sending domains.

  3. Send a test

    Ask ChatGPT to send a test email from a verified domain. It asks you to confirm before sending; check the message in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

GitHub Copilot

Add the server URL and approve in the browser. If your setup needs a static key, VS Code prompts for it at runtime (never stored in the file).

  1. Connect with OAuth (recommended)

    Create or edit `.vscode/mcp.json` in your workspace (or MCP: Add Server from the Command Palette for a user-level entry) with the server URL below, then start it. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    JSON
    {
      "servers": {
        "unitpost": {
          "type": "http",
          "url": "https://mcp.unitpost.com/mcp"
        }
      }
    }

    VS Code tries HTTP streamable first, then OAuth on 401 (DCR). Official redirects we allow: https://vscode.dev/redirect and http://127.0.0.1:33418.

  2. Start the server

    Open the MCP view and start unitpost. Complete the browser approval, then confirm tools are listed. If it disconnects later, restart it here.

  3. Send a test

    In Copilot agent mode, ask it to send a test email from a verified domain and confirm in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Gemini CLI

Prefer the OAuth browser approval. If your setup needs static config, paste the key block instead.

  1. Connect with OAuth (recommended)

    Add this block to `~/.gemini/settings.json` (no headers — Gemini discovers OAuth from the 401). No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "httpUrl": "https://mcp.unitpost.com/mcp"
        }
      }
    }
  2. Verify

    Restart the Gemini CLI and run /mcp. unitpost should list its tools. If it shows as needing authentication, run /mcp auth unitpost — the browser opens for approval, and tokens refresh automatically after that.

  3. Send a test

    Ask Gemini to send an email from a verified domain and confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Grok

Add the server URL as a remote HTTP MCP server and approve in the browser. The Unitpost plugin for Grok bundles this same server with the Unitpost skill.

  1. Add the server

    Add a remote HTTP MCP server with the URL below; Grok opens Unitpost in the browser to approve. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "type": "http",
          "url": "https://mcp.unitpost.com/mcp"
        }
      }
    }

    The plugin source is public at github.com/unitpostcom/unitpost-grok-plugin.

  2. Verify

    unitpost should show connected with tools like email_send and email_domains_list.

    Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.

  3. Send a test

    Ask Grok to send a test email from a verified domain, then confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Windsurf

Prefer the OAuth browser approval. If your setup needs static config, paste the key block instead.

  1. Connect with OAuth (recommended)

    In Windsurf: Settings → Cascade → MCP Servers → Add Server, or paste this into `~/.codeium/windsurf/mcp_config.json`. Windsurf uses serverUrl (not url) for remote HTTP. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "serverUrl": "https://mcp.unitpost.com/mcp"
        }
      }
    }
  2. Refresh and verify

    Refresh the MCP server list. Unitpost's tools should appear under unitpost.

  3. Send a test

    Ask Cascade to send a test email from a verified domain, then confirm in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

OpenCode

OpenCode auto-detects OAuth on 401 (DCR). Add a remote server and run `opencode mcp auth unitpost`.

  1. Add the remote server

    Put this in ~/.config/opencode/opencode.jsonc (or project opencode.json). No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    JSON
    {
      "$schema": "https://opencode.ai/config.json",
      "mcp": {
        "unitpost": {
          "type": "remote",
          "url": "https://mcp.unitpost.com/mcp",
          "oauth": {}
        }
      }
    }
  2. Authenticate

    Restart OpenCode, then run opencode mcp auth unitpost (or wait for the first tool call). Complete the browser approval.

  3. Verify

    Run opencode mcp list. unitpost should show connected.

  4. Send a test

    Ask the agent to send a test email from a verified domain and confirm it in Unitpost Emails.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

v0

v0 uses the server while it builds: it can check your sending domain, draft templates and send a test. The app it generates sends through the Unitpost SDK with an API key, because v0's MCP tools aren't available to generated code.

  1. Add the server

    In a v0 chat, open the + menu in the prompt form → MCPs → add a custom server with the URL below, and choose OAuth for authentication. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    Text
    https://mcp.unitpost.com/mcp
  2. Verify

    Ask v0 to list your Unitpost sending domains. It should call email_domains_list; v0 asks before running a tool unless your chat's permission mode allows it.

  3. Send from the app v0 builds

    Create an API key in Unitpost (Settings → API keys, scoped to emails:send), add it to the v0 project as the environment variable UNITPOST_API_KEY, and ask v0 to send email with the unitpost npm package.

    TypeScript
    import { Unitpost } from "unitpost";
    
    const unitpost = new Unitpost(); // reads process.env.UNITPOST_API_KEY
    
    await unitpost.email.send({
      from: "hello@yourdomain.com",
      to: "you@example.com",
      subject: "Hello from v0",
      html: "<p>It works.</p>",
    });

    The from address needs a verified domain. Keep the key in environment variables, never in the code v0 writes.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Generic / custom client

Any streamable-HTTP MCP client that speaks MCP OAuth connects with just the URL. Anything else uses a Bearer API key.

  1. Connect with OAuth (recommended)

    Point the client at the server URL below. A spec-compliant client discovers OAuth itself: it reads the WWW-Authenticate: Bearer resource_metadata="…" challenge on the first 401, fetches /.well-known/oauth-protected-resource, runs the PKCE code flow against the advertised authorization server, and retries with the token. No key to copy. Your client opens Unitpost in the browser — pick a workspace, approve the scopes, and you're connected. Tokens refresh automatically.

    Server URLhttps://mcp.unitpost.com/mcp
    TransportStreamable HTTP
    Auth (recommended)OAuth 2.1 — add the URL, approve in the browser
    Auth (legacy)Authorization: Bearer pk_live_YOUR_KEY
    Toolsone per API operation (email_send, email_campaigns_send, …)
    Toolsets (optional)https://mcp.unitpost.com/mcp?toolsets=default,campaigns
  2. Discover tools

    The server advertises one tool per API operation (email_send, email_campaigns_send, email_domains_verify, …). A write's body maps to the API request body. Every tool declares securitySchemes: [{ type: "oauth2", scopes: […] }] so linking-aware clients (ChatGPT) show the Connect UI.

  3. Choose toolsets (optional)

    With no parameters the server lists its default set of tools, the same list it always has. Newer tools come in groups: add ?toolsets= to the URL, or send an X-MCP-Toolsets header, with any of audience, templates, campaigns, sending, inbox, domains and workspace (the server instructions list every group), plus default for the standard set and all for everything. ?readonly=1 (X-MCP-Readonly: 1) lists only read tools and refuses writes; ?scoped=1 (X-MCP-Scoped: 1) hides tools your key can't call. Fewer tools means less of the model's context spent on tool definitions.

    Text
    https://mcp.unitpost.com/mcp?toolsets=default,campaigns,templates
  4. Verify

    Call a read tool (e.g. list domains). An unauthenticated call answers 401 with a WWW-Authenticate: Bearer resource_metadata="…" challenge (start OAuth there). With a key, a 401 Invalid API key usually means a missing Bearer prefix or a mistyped key — recreate the key and retry.

    Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.

No browser on this machine? For headless setups, CI, SSH, or clients that can only paste a key, use the API-key setup instead.

Headless / API key

OAuth needs a browser. Where there isn't one — CI jobs, SSH sessions, containers, or any client that can only paste a static header — send a workspace API key as the Bearer token instead. Same scopes, same gates, same tools.

  1. Create an API key

    Open https://www.unitpost.com → Settings → API keys → create a scoped key. Copy the full pk_live_… value (shown once). In every snippet below, replace pk_live_YOUR_KEY with that value.

    Shown once. Keep the Bearer prefix in every snippet. Grant only the scopes the agent needs (e.g. emails:send for email_send). Prefer a revocable key dedicated to the agent.

  2. Cursor (static key)

    Edit `~/.cursor/mcp.json` (all projects) or `.cursor/mcp.json` (this project only) — or Cursor Settings → MCP → Add new MCP server. Put the unitpost entry under top-level mcpServers.

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "url": "https://mcp.unitpost.com/mcp",
          "headers": {
            "Authorization": "Bearer pk_live_YOUR_KEY"
          }
        }
      }
    }
  3. Claude Code (static header)

    Flags stay before the name/URL.

    Shell
    claude mcp add --transport http --header "Authorization: Bearer pk_live_YOUR_KEY" unitpost https://mcp.unitpost.com/mcp
  4. Claude Desktop (mcp-remote bridge)

    For plans without custom connectors. In Claude Desktop: Settings → Desktop app → Developer → Edit Config, then merge the block below — mcpServers must be a top-level key (sibling of preferences), not nested inside it.

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "command": "npx",
          "args": [
            "-y",
            "mcp-remote",
            "https://mcp.unitpost.com/mcp",
            "--header",
            "Authorization:${AUTH_HEADER}"
          ],
          "env": {
            "AUTH_HEADER": "Bearer pk_live_YOUR_KEY"
          }
        }
      }
    }

    Deliberately no space after Authorization: in args — Claude Desktop mangles spaces there; the value lives in env instead. Requires Node.js 18+. If npx is not found, set "command" to your absolute npx path (e.g. /opt/homebrew/opt/node@22/bin/npx). Save, then ⌘Q (Quit) Claude Desktop — closing the window is not enough.

  5. Codex (TOML)

    For a machine where codex mcp login can't open a browser. Edit ~/.codex/config.toml (shared by the CLI, IDE extension and app) and set UNITPOST_API_KEY to your key in the environment Codex runs in. Codex sends it as Authorization: Bearer …, so the key never sits in the file.

    TOML
    [mcp_servers.unitpost]
    url = "https://mcp.unitpost.com/mcp"
    bearer_token_env_var = "UNITPOST_API_KEY"
  6. VS Code (runtime-prompted key)

    Create or edit `.vscode/mcp.json`. When VS Code prompts later, paste only the pk_live_… value — not Bearer (the config already adds it).

    JSON
    {
      "inputs": [
        {
          "id": "unitpost-key",
          "type": "promptString",
          "description": "Unitpost API key (pk_live_…)",
          "password": true
        }
      ],
      "servers": {
        "unitpost": {
          "type": "http",
          "url": "https://mcp.unitpost.com/mcp",
          "headers": {
            "Authorization": "Bearer ${input:unitpost-key}"
          }
        }
      }
    }
  7. Gemini CLI (static header)

    Edit `~/.gemini/settings.json` (user-level) or `.gemini/settings.json` (project).

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "httpUrl": "https://mcp.unitpost.com/mcp",
          "headers": {
            "Authorization": "Bearer pk_live_YOUR_KEY"
          }
        }
      }
    }
  8. Windsurf (static header)

    Edit `~/.codeium/windsurf/mcp_config.json`. Windsurf uses serverUrl (not url) for remote HTTP.

    JSON
    {
      "mcpServers": {
        "unitpost": {
          "serverUrl": "https://mcp.unitpost.com/mcp",
          "headers": {
            "Authorization": "Bearer pk_live_YOUR_KEY"
          }
        }
      }
    }
  9. OpenCode (static header)

    Set oauth: false and pass the Bearer key.

    JSON
    {
      "mcp": {
        "unitpost": {
          "type": "remote",
          "url": "https://mcp.unitpost.com/mcp",
          "oauth": false,
          "headers": {
            "Authorization": "Bearer pk_live_YOUR_KEY"
          }
        }
      }
    }
  10. Any other client (generic)

    Configure a streamable-HTTP MCP server with the URL below, and send the header on every MCP request.

    JSON
    {
      "url": "https://mcp.unitpost.com/mcp",
      "headers": {
        "Authorization": "Bearer pk_live_YOUR_KEY"
      }
    }
  11. Verify with the key

    Call a read tool (e.g. list domains). A 401 Invalid API key usually means a missing Bearer prefix or a mistyped key — recreate the key and retry. Then send a test email from a verified domain and confirm it in Unitpost Emails.

    Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.

Vercel AI SDK

Give an AI SDK agent the Unitpost send tool through the AI SDK MCP client, or one typed tool that calls the REST API. Either way your server code holds a send-only key and decides which sends go out.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Connect the AI SDK MCP client

    Install ai and @ai-sdk/mcp. createMCPClient connects over streamable HTTP with your key as a Bearer header. ?toolsets=sending keeps the server's list to sending tools, and the agent gets one of them: email_send.

    TypeScript
    import { createMCPClient } from "@ai-sdk/mcp";
    import { generateText, isStepCount } from "ai";
    
    const mcp = await createMCPClient({
      transport: {
        type: "http",
        url: "https://mcp.unitpost.com/mcp?toolsets=sending",
        headers: { Authorization: `Bearer ${process.env.UNITPOST_API_KEY}` },
      },
    });
    
    try {
      const { email_send } = await mcp.tools();
      const result = await generateText({
        model: "anthropic/claude-sonnet-5.5", // any model the AI SDK supports
        tools: { email_send },
        stopWhen: isStepCount(5),
        prompt: "Email ada@example.com from hi@yourdomain.com: the report is ready.",
      });
      console.log(result.text);
    } finally {
      await mcp.close();
    }

    email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one REST send tool

    No MCP client needed: one typed tool() that posts to /api/v1/email. Your code holds the key, checks the recipient, and sends the result or the error envelope back to the model.

    TypeScript
    import { tool } from "ai";
    import { z } from "zod";
    
    const ALLOWED = new Set(["ada@example.com"]); // who this agent may email
    
    export const sendEmail = tool({
      description: "Send one email through Unitpost.",
      inputSchema: z.object({
        from: z.string().describe("Sender on a verified domain, e.g. Acme <hi@acme.com>"),
        to: z.string().describe("One recipient address"),
        subject: z.string(),
        text: z.string().describe("Plain-text body"),
        idempotency_key: z.string().describe("A new value for each message; the same value when retrying this one"),
      }),
      execute: async (email) => {
        if (!ALLOWED.has(email.to)) return { refused: `${email.to} is not on the allowlist` };
        const { idempotency_key, ...message } = email;
        const body = JSON.stringify(message);
        const res = await fetch("https://www.unitpost.com/api/v1/email", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.UNITPOST_API_KEY}`,
            "Content-Type": "application/json",
            "User-Agent": "my-agent/1.0",
            "Idempotency-Key": idempotency_key, // the model's: a retry of this message reuses it
          },
          body,
        });
        return res.json(); // { id, status, scheduled_at } or { error: { code, message, details } }
      },
    });

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In the AI SDK, toolApproval decides per call: deny any recipient off the allowlist and ask a person about the rest. The result then holds a tool-approval-request; answer it with a tool-approval-response and call generateText again.

    TypeScript
    const ALLOWED = new Set(["ada@example.com"]);
    
    const result = await generateText({
      model: "anthropic/claude-sonnet-5.5",
      tools: { email_send },
      prompt,
      toolApproval: ({ toolCall }) => {
        const body = (toolCall.input as { body?: Record<string, string | string[]> }).body ?? {};
        const recipients = [body.to, body.cc, body.bcc].flat().filter(Boolean) as string[];
        return recipients.length > 0 && recipients.every((a) => ALLOWED.has(a))
          ? "user-approval"
          : { type: "denied", reason: "A recipient is not on the allowlist." };
      },
    });
    
    for (const part of result.content) {
      if (part.type === "tool-approval-request" && !part.isAutomatic) {
        console.log("Approve this send?", part.toolCall.input); // show a person, then reply
      }
    }

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

OpenAI Agents SDK

Connect an Agents SDK agent (Python) to the Unitpost MCP server and filter it down to the send tool, or give it one function tool that calls the REST API. Approvals pause the run until a person says yes.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Connect MCPServerStreamableHttp

    Install openai-agents. MCPServerStreamableHttp sends your key as a Bearer header, and create_static_tool_filter leaves the agent one tool: email_send.

    Python
    import asyncio
    import os
    
    from agents import Agent, Runner
    from agents.mcp import MCPServerStreamableHttp, create_static_tool_filter
    
    
    async def main() -> None:
        async with MCPServerStreamableHttp(
            name="unitpost",
            params={
                "url": "https://mcp.unitpost.com/mcp?toolsets=sending",
                "headers": {"Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}"},
            },
            tool_filter=create_static_tool_filter(allowed_tool_names=["email_send"]),
        ) as server:
            agent = Agent(
                name="Mailer",
                instructions="Send email only when asked. Pass a new idempotency_key per message.",
                mcp_servers=[server],
            )
            result = await Runner.run(agent, "Email ada@example.com from hi@yourdomain.com: the report is ready.")
            print(result.final_output)
    
    
    asyncio.run(main())

    email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one function tool

    No MCP server needed: one @tool function that posts to /api/v1/email. The SDK builds the schema from the signature and docstring.

    Python
    import json
    import os
    
    import httpx
    from agents import Agent
    from agents.decorators import tool
    
    ALLOWED = {"ada@example.com"}  # who this agent may email
    
    
    @tool
    async def send_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        """Send one email through Unitpost.
    
        Args:
            sender: From address on a verified domain, e.g. "Acme <hi@acme.com>".
            to: One recipient address.
            subject: Subject line.
            text: Plain-text body.
            idempotency_key: A new value for each message; the same value when
                retrying this one, so a retry never sends twice.
        """
        if to not in ALLOWED:
            return f"Refused: {to} is not on this agent's allowlist."
        body = json.dumps({"from": sender, "to": to, "subject": subject, "text": text})
        async with httpx.AsyncClient() as http:
            res = await http.post(
                "https://www.unitpost.com/api/v1/email",
                content=body,
                headers={
                    "Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}",
                    "Content-Type": "application/json",
                    "User-Agent": "my-agent/1.0",
                    "Idempotency-Key": idempotency_key,  # the model's: a retry reuses it
                },
            )
        return res.text  # {"id": ...} or {"error": {"code": ..., "message": ...}}
    
    
    agent = Agent(name="Mailer", instructions="Send email only when asked.", tools=[send_email])

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In the Agents SDK, @tool(needs_approval=True) on the function, or require_approval={"email_send": "always"} on the MCP server, pauses the run at each send. Approve or reject the pending calls, then resume.

    Python
    from agents import Runner
    
    
    async def run_with_approval(agent, prompt: str) -> str:
        result = await Runner.run(agent, prompt)
        while result.interruptions:
            state = result.to_state()
            for item in result.interruptions:
                answer = input(f"Send {item.name} with {item.arguments}? [y/N] ")
                if answer.strip().lower() == "y":
                    state.approve(item, always_approve=False)
                else:
                    state.reject(item)
            result = await Runner.run(agent, state)
        return result.final_output

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

LangChain

Load the Unitpost send tool into a LangChain agent (Python) with the built-in MCP adapter, or write one tool that calls the REST API. Human-in-the-loop middleware pauses the agent before each send.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Load the tools with MCPAdapter

    Install langchain[mcp] (1.4 or later; langchain.mcp is in beta). A FastMCP Client with auth set to the key sends it as a Bearer token. Keep only email_send from the list.

    Python
    import asyncio
    import os
    
    from fastmcp.client import Client
    from langchain.agents import create_agent
    from langchain.mcp import MCPAdapter
    
    
    async def main():
        client = Client("https://mcp.unitpost.com/mcp?toolsets=sending", auth=os.environ["UNITPOST_API_KEY"])
        async with MCPAdapter(client) as adapter:
            tools = [t for t in await adapter.list_tools() if t.name == "email_send"]
            agent = create_agent("claude-sonnet-5", tools)
            result = await agent.ainvoke(
                {"messages": [{"role": "user", "content": "Email ada@example.com from hi@yourdomain.com: the report is ready."}]}
            )
            print(result["messages"][-1].content)
    
    
    asyncio.run(main())

    Still on langchain-mcp-adapters? LangChain's migration guide replaces MultiServerMCPClient with MCPAdapter. email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one REST send tool

    No MCP needed: one @tool function that posts to /api/v1/email. The docstring becomes the tool description the model reads.

    Python
    import json
    import os
    
    import httpx
    from langchain.tools import tool
    
    ALLOWED = {"ada@example.com"}  # who this agent may email
    
    
    @tool
    def send_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        """Send one email through Unitpost. sender must be on a verified domain.
    
        idempotency_key: a new value for each message, and the same value when
        retrying that message, so a retry never sends twice.
        """
        if to not in ALLOWED:
            return f"Refused: {to} is not on this agent's allowlist."
        body = json.dumps({"from": sender, "to": to, "subject": subject, "text": text})
        res = httpx.post(
            "https://www.unitpost.com/api/v1/email",
            content=body,
            headers={
                "Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}",
                "Content-Type": "application/json",
                "User-Agent": "my-agent/1.0",
                "Idempotency-Key": idempotency_key,  # the model's: a retry reuses it
            },
        )
        return res.text  # {"id": ...} or {"error": {"code": ..., "message": ...}}

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In LangChain, HumanInTheLoopMiddleware pauses the agent before the send tool runs (send_email here, email_send over MCP). It needs a checkpointer and a thread ID; resume with a decision.

    Python
    from langchain.agents import create_agent
    from langchain.agents.middleware import HumanInTheLoopMiddleware
    from langgraph.checkpoint.memory import InMemorySaver
    from langgraph.types import Command
    
    agent = create_agent(
        "claude-sonnet-5",
        [send_email],
        middleware=[
            HumanInTheLoopMiddleware(
                interrupt_on={"send_email": {"allowed_decisions": ["approve", "reject"]}},
            )
        ],
        checkpointer=InMemorySaver(),
    )
    
    config = {"configurable": {"thread_id": "mail-1"}}
    paused = agent.invoke({"messages": [{"role": "user", "content": "Email ada@example.com: the report is ready."}]}, config)
    print(paused["__interrupt__"])  # the pending send: show it to a person
    agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config)

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

Mastra

Connect a Mastra agent to the Unitpost MCP server with MCPClient, or give it one tool that calls the REST API. Tool approval pauses each send until you approve or decline it.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Connect MCPClient

    Install @mastra/mcp and @mastra/core. MCPClient sends the key in requestInit.headers. listTools() names each tool serverName_toolName, so the send tool is unitpost_email_send.

    TypeScript
    import { Agent } from "@mastra/core/agent";
    import { MCPClient } from "@mastra/mcp";
    
    export const mcp = new MCPClient({
      id: "unitpost",
      servers: {
        unitpost: {
          url: new URL("https://mcp.unitpost.com/mcp?toolsets=sending"),
          requestInit: {
            headers: { Authorization: `Bearer ${process.env.UNITPOST_API_KEY}` },
          },
        },
      },
    });
    
    const tools = await mcp.listTools();
    
    export const mailer = new Agent({
      id: "mailer",
      name: "Mailer",
      instructions: "Send email only when asked. Pass a new idempotency_key per message.",
      model: "openai/gpt-6.1-sol", // any model Mastra supports
      tools: { unitpost_email_send: tools.unitpost_email_send },
    });

    email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one REST send tool

    No MCP needed: one createTool that posts to /api/v1/email. requireApproval: true pauses every call to it before execute runs.

    TypeScript
    import { createTool } from "@mastra/core/tools";
    import { z } from "zod";
    
    const ALLOWED = new Set(["ada@example.com"]); // who this agent may email
    
    export const sendEmail = createTool({
      id: "send-email",
      description: "Send one email through Unitpost.",
      inputSchema: z.object({
        from: z.string().describe("Sender on a verified domain, e.g. Acme <hi@acme.com>"),
        to: z.string().describe("One recipient address"),
        subject: z.string(),
        text: z.string().describe("Plain-text body"),
        idempotency_key: z.string().describe("A new value for each message; the same value when retrying this one"),
      }),
      requireApproval: true,
      execute: async (email) => {
        if (!ALLOWED.has(email.to)) return { refused: `${email.to} is not on the allowlist` };
        const { idempotency_key, ...message } = email;
        const body = JSON.stringify(message);
        const res = await fetch("https://www.unitpost.com/api/v1/email", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.UNITPOST_API_KEY}`,
            "Content-Type": "application/json",
            "User-Agent": "my-agent/1.0",
            "Idempotency-Key": idempotency_key, // the model's: a retry of this message reuses it
          },
          body,
        });
        return res.json(); // { id, status, scheduled_at } or { error: { code, message, details } }
      },
    });

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In Mastra, requireApproval on the tool, or requireToolApproval on the MCP server, pauses each send. The stream emits a tool-call-approval chunk; approve or decline it with the stream's runId.

    TypeScript
    // On the MCP server instead: requireToolApproval: ({ toolName }) => toolName === "email_send"
    const stream = await mailer.stream("Email ada@example.com: the report is ready.");
    
    for await (const chunk of stream.fullStream) {
      if (chunk.type === "tool-call-approval") {
        const ok = await askPerson(chunk.payload.toolName, chunk.payload.args); // your own UI
        const next = ok
          ? await mailer.approveToolCall({ runId: stream.runId })
          : await mailer.declineToolCall({ runId: stream.runId });
        for await (const text of next.textStream) process.stdout.write(text);
      }
    }

    Approval keeps a snapshot of the paused run, so configure a storage provider on your Mastra instance. Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

CrewAI

Add the Unitpost MCP server to a CrewAI agent's mcps and filter it to the send tool, or give the agent one tool that calls the REST API. A pre-tool-call hook checks recipients and asks a person before anything goes out.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Add MCPServerHTTP to the agent

    Install crewai. MCPServerHTTP connects over streamable HTTP with your key in headers, and create_static_tool_filter keeps one tool: email_send.

    Python
    import os
    
    from crewai import Agent, Crew, Task
    from crewai.mcp import MCPServerHTTP
    from crewai.mcp.filters import create_static_tool_filter
    
    mailer = Agent(
        role="Mailer",
        goal="Send the emails the task asks for, and nothing else",
        backstory="Sends transactional email through Unitpost.",
        mcps=[
            MCPServerHTTP(
                url="https://mcp.unitpost.com/mcp?toolsets=sending",
                headers={"Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}"},
                streamable=True,
                tool_filter=create_static_tool_filter(allowed_tool_names=["email_send"]),
            ),
        ],
    )
    
    task = Task(
        description="Email ada@example.com from hi@yourdomain.com: the report is ready. Pass an idempotency_key.",
        expected_output="The id of the sent email",
        agent=mailer,
    )
    
    print(Crew(agents=[mailer], tasks=[task]).kickoff())

    email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one REST send tool

    No MCP needed: one @tool function that posts to /api/v1/email. Pass it in the agent's tools.

    Python
    import json
    import os
    
    import httpx
    from crewai.tools import tool
    
    ALLOWED = {"ada@example.com"}  # who this agent may email
    
    
    @tool("send_email")
    def send_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        """Send one email through Unitpost. sender must be on a verified domain.
    
        idempotency_key: a new value for each message, and the same value when
        retrying that message, so a retry never sends twice.
        """
        if to not in ALLOWED:
            return f"Refused: {to} is not on this agent's allowlist."
        body = json.dumps({"from": sender, "to": to, "subject": subject, "text": text})
        res = httpx.post(
            "https://www.unitpost.com/api/v1/email",
            content=body,
            headers={
                "Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}",
                "Content-Type": "application/json",
                "User-Agent": "my-agent/1.0",
                "Idempotency-Key": idempotency_key,  # the model's: a retry reuses it
            },
        )
        return res.text  # {"id": ...} or {"error": {"code": ..., "message": ...}}

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In CrewAI, a PRE_TOOL_CALL hook runs before the tool: raise HookAborted to block the call, and the agent reads why. CrewAI prefixes MCP tool names with the server's name, so scope the hook to the name your crew lists for email_send.

    Python
    from crewai.hooks import HookAborted, InterceptionPoint, ToolCallHookContext, on
    
    ALLOWED = {"ada@example.com"}
    
    
    @on(InterceptionPoint.PRE_TOOL_CALL, tools=["send_email"])
    def approve_send(ctx: ToolCallHookContext) -> None:
        if ctx.tool_input.get("to") not in ALLOWED:
            raise HookAborted(reason="recipient is not on the allowlist", source="email-policy")
        answer = ctx.request_human_input(
            prompt=f"Send this email? {ctx.tool_input}",
            default_message="Type 'yes' to send:",
        )
        if answer.lower() != "yes":
            raise HookAborted(reason="declined by a person", source="email-policy")

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

Pydantic AI

Attach the Unitpost MCP server to a Pydantic AI agent as a toolset filtered to the send tool, or register one tool that calls the REST API. Deferred approvals end the run until a person decides.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Attach an MCPToolset

    Install pydantic-ai-slim[mcp]. MCPToolset takes the key as auth and sends it as a Bearer token; .filtered() keeps one tool: email_send.

    Python
    import asyncio
    import os
    
    from pydantic_ai import Agent
    from pydantic_ai.mcp import MCPToolset
    
    unitpost = MCPToolset("https://mcp.unitpost.com/mcp?toolsets=sending", auth=os.environ["UNITPOST_API_KEY"]).filtered(
        lambda ctx, tool_def: tool_def.name == "email_send"
    )
    agent = Agent("openai:gpt-6.1-sol", toolsets=[unitpost])
    
    
    async def main():
        result = await agent.run("Email ada@example.com from hi@yourdomain.com: the report is ready.")
        print(result.output)
    
    
    asyncio.run(main())

    email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one REST send tool

    No MCP needed: one @agent.tool_plain function that posts to /api/v1/email. requires_approval=True defers every call to it until it's approved.

    Python
    import json
    import os
    
    import httpx
    from pydantic_ai import Agent, DeferredToolRequests
    
    ALLOWED = {"ada@example.com"}  # who this agent may email
    agent = Agent("openai:gpt-6.1-sol", output_type=[str, DeferredToolRequests])
    
    
    @agent.tool_plain(requires_approval=True)
    async def send_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        """Send one email through Unitpost. sender must be on a verified domain.
    
        idempotency_key: a new value for each message, and the same value when
        retrying that message, so a retry never sends twice.
        """
        if to not in ALLOWED:
            return f"Refused: {to} is not on this agent's allowlist."
        body = json.dumps({"from": sender, "to": to, "subject": subject, "text": text})
        async with httpx.AsyncClient() as http:
            res = await http.post(
                "https://www.unitpost.com/api/v1/email",
                content=body,
                headers={
                    "Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}",
                    "Content-Type": "application/json",
                    "User-Agent": "my-agent/1.0",
                    "Idempotency-Key": idempotency_key,  # the model's: a retry reuses it
                },
            )
        return res.text  # {"id": ...} or {"error": {"code": ..., "message": ...}}

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In Pydantic AI, requires_approval=True on the tool, or .approval_required() on the MCP toolset, ends the run with a DeferredToolRequests output. Answer each pending call, then run again with the message history.

    Python
    from pydantic_ai import DeferredToolRequests, DeferredToolResults
    
    # For MCP: Agent(..., toolsets=[unitpost.approval_required()], output_type=[str, DeferredToolRequests])
    
    
    async def run_with_approval(prompt: str) -> str:
        result = await agent.run(prompt)
        while isinstance(result.output, DeferredToolRequests):
            approvals = {}
            for call in result.output.approvals:
                answer = input(f"Send {call.tool_name} with {call.args}? [y/N] ")
                approvals[call.tool_call_id] = answer.strip().lower() == "y"
            result = await agent.run(
                message_history=result.all_messages(),
                deferred_tool_results=DeferredToolResults(approvals=approvals),
            )
        return result.output

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

Claude Agent SDK

Add the Unitpost MCP server to a Claude Agent SDK agent (TypeScript), or give it one in-process tool that calls the REST API. The canUseTool callback decides each send before it runs.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Add the server to mcpServers

    Install @anthropic-ai/claude-agent-sdk. Use type: "http" for streamable HTTP and put the key in headers. Tools are named mcp__<server>__<tool>, so the send tool is mcp__unitpost__email_send.

    TypeScript
    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    for await (const message of query({
      prompt: "Email ada@example.com from hi@yourdomain.com: the report is ready.",
      options: {
        mcpServers: {
          unitpost: {
            type: "http",
            url: "https://mcp.unitpost.com/mcp?toolsets=sending",
            headers: { Authorization: `Bearer ${process.env.UNITPOST_API_KEY}` },
          },
        },
        // Approves every send without asking: fine for a first test to yourself.
        // The "Gate each send" step replaces it with canUseTool.
        allowedTools: ["mcp__unitpost__email_send"],
      },
    })) {
      if (message.type === "result" && message.subtype === "success") console.log(message.result);
    }

    email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one in-process send tool

    No remote MCP needed: define the tool with tool(), wrap it in createSdkMcpServer, and pass that server in mcpServers. It posts to /api/v1/email and returns the result or the error envelope.

    TypeScript
    import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
    import { z } from "zod";
    
    const ALLOWED = new Set(["ada@example.com"]); // who this agent may email
    
    const sendEmail = tool(
      "send_email",
      "Send one email through Unitpost.",
      {
        from: z.string().describe("Sender on a verified domain, e.g. Acme <hi@acme.com>"),
        to: z.string().describe("One recipient address"),
        subject: z.string(),
        text: z.string().describe("Plain-text body"),
        idempotency_key: z.string().describe("A new value for each message; the same value when retrying this one"),
      },
      async (email) => {
        if (!ALLOWED.has(email.to)) {
          return { content: [{ type: "text", text: `Refused: ${email.to} is not on the allowlist.` }], isError: true };
        }
        const { idempotency_key, ...message } = email;
        const body = JSON.stringify(message);
        const res = await fetch("https://www.unitpost.com/api/v1/email", {
          method: "POST",
          headers: {
            Authorization: `Bearer ${process.env.UNITPOST_API_KEY}`,
            "Content-Type": "application/json",
            "User-Agent": "my-agent/1.0",
            "Idempotency-Key": idempotency_key, // the model's: a retry of this message reuses it
          },
          body,
        });
        return { content: [{ type: "text", text: await res.text() }], isError: !res.ok };
      },
    );
    
    // query({ prompt, options: { mcpServers: { mailer } } }) names it mcp__mailer__send_email
    export const mailer = createSdkMcpServer({ name: "mailer", version: "1.0.0", tools: [sendEmail] });

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. In the Agent SDK, canUseTool runs for every tool call that no allow rule approved, so leave the send tool out of allowedTools and decide there: allow it, or deny it with a message the agent reads.

    TypeScript
    const ALLOWED = new Set(["ada@example.com"]);
    
    for await (const message of query({
      prompt,
      options: {
        mcpServers, // as above, with no allowedTools entry for the send tool
        canUseTool: async (toolName, input) => {
          if (toolName !== "mcp__unitpost__email_send") {
            return { behavior: "deny", message: "This agent may only send email." };
          }
          const body = (input as { body?: { to?: string | string[]; cc?: string | string[]; bcc?: string | string[] } }).body ?? {};
          const recipients = [body.to, body.cc, body.bcc].flat().filter((r): r is string => Boolean(r));
          const blocked = recipients.filter((r) => !ALLOWED.has(r.toLowerCase()));
          return recipients.length > 0 && blocked.length === 0 // or ask a person here
            ? { behavior: "allow", updatedInput: input }
            : { behavior: "deny", message: `Not on the allowlist: ${blocked.join(", ") || "no recipient"}.` };
        },
      },
    })) {
      if (message.type === "result" && message.subtype === "success") console.log(message.result);
    }

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

Claude API

The Messages API can call the Unitpost MCP server itself through the MCP connector, with no MCP client on your side. For a person to approve each send, give Claude a client tool that calls the REST API instead.

  1. Create a send-only key

    Open https://www.unitpost.com → Settings → API keys and create a key with Sending only permissions. On a paid plan, open Advanced and keep only emails:send, so the key can send email and do nothing else. Copy the pk_live_… value (shown once) into the environment your agent runs in.

    Shell
    export UNITPOST_API_KEY=pk_live_YOUR_KEY

    A Sending only key can also send campaigns and read contacts, segments, templates and domains. Keep the key in your server code: the model never needs to see it.

  2. Attach the MCP connector

    Install anthropic. Pass the server in mcp_servers with your key as authorization_token (sent as a Bearer token), and allowlist email_send in the matching mcp_toolset. The connector needs the mcp-client-2025-11-20 beta.

    Python
    import os
    
    import anthropic
    
    client = anthropic.Anthropic()
    
    response = client.beta.messages.create(
        model="claude-opus-5-5",
        max_tokens=16000,
        betas=["mcp-client-2025-11-20"],
        mcp_servers=[
            {
                "type": "url",
                "url": "https://mcp.unitpost.com/mcp",
                "name": "unitpost",
                "authorization_token": os.environ["UNITPOST_API_KEY"],
            }
        ],
        tools=[
            {
                "type": "mcp_toolset",
                "mcp_server_name": "unitpost",
                "default_config": {"enabled": False},
                "configs": {"email_send": {"enabled": True}},
            }
        ],
        messages=[{"role": "user", "content": "Email ada@example.com from hi@yourdomain.com: the report is ready."}],
    )
    
    for block in response.content:
        if block.type == "mcp_tool_result":
            print(block.content)  # the send result, or the error envelope

    The connector runs email_send inside the request, with no pause for approval. email_send takes an idempotency_key beside body. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.

  3. Or add one client tool

    Your code runs this tool, so it can check and ask before the POST. @beta_tool builds the schema from the signature and docstring, and the tool runner loops until Claude is done.

    Python
    import json
    import os
    
    import anthropic
    import httpx
    from anthropic import beta_tool
    
    ALLOWED = {"ada@example.com"}  # who this agent may email
    
    
    def post_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        body = json.dumps({"from": sender, "to": to, "subject": subject, "text": text})
        res = httpx.post(
            "https://www.unitpost.com/api/v1/email",
            content=body,
            headers={
                "Authorization": f"Bearer {os.environ['UNITPOST_API_KEY']}",
                "Content-Type": "application/json",
                "User-Agent": "my-agent/1.0",
                "Idempotency-Key": idempotency_key,  # the model's: a retry reuses it
            },
        )
        return res.text  # {"id": ...} or {"error": {"code": ..., "message": ...}}
    
    
    @beta_tool
    def send_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        """Send one email through Unitpost.
    
        Args:
            sender: From address on a verified domain, e.g. "Acme <hi@acme.com>".
            to: One recipient address.
            subject: Subject line.
            text: Plain-text body.
            idempotency_key: A new value for each message; the same value when
                retrying this one, so a retry never sends twice.
        """
        if to not in ALLOWED:
            return f"Refused: {to} is not on this agent's allowlist."
        return post_email(sender, to, subject, text, idempotency_key)
    
    
    client = anthropic.Anthropic()
    runner = client.beta.messages.tool_runner(
        model="claude-opus-5-5",
        max_tokens=16000,
        tools=[send_email],
        messages=[{"role": "user", "content": "Email ada@example.com from hi@yourdomain.com: the report is ready."}],
    )
    print(runner.until_done())

    The model passes idempotency_key: a new one per message, and the same one when it retries that message, so a lost response never becomes a second email. A key made inside the tool would change on every retry. Never derive it from the content, or two separate identical notifications become one. User-Agent is required: a request without one is refused with missing_user_agent (403).

  4. Gate each send

    Every send is real mail to a real person. Send only transactional mail or mail people opted in to: the Acceptable Use Policy rules out cold outreach. Check each recipient against an allowlist, or have a person approve the send, before the call goes out. Pass an idempotency key, and the same key on a retry: for 24 hours a retry returns the first result instead of sending twice. With the connector, the allowlist in mcp_toolset and a send-only key are the controls. With the client tool, ask inside the function before the POST: the tool runner waits for it to return.

    Python
    @beta_tool
    def send_email(sender: str, to: str, subject: str, text: str, idempotency_key: str) -> str:
        """Send one email through Unitpost. sender must be on a verified domain.
    
        idempotency_key: a new value for each message, and the same value when
        retrying that message, so a retry never sends twice.
        """
        if to not in ALLOWED:
            return f"Refused: {to} is not on this agent's allowlist."
        if input(f"Send '{subject}' to {to}? [y/N] ").strip().lower() != "y":
            return "Refused: a person declined this send."
        return post_email(sender, to, subject, text, idempotency_key)

    Errors come back as { "error": { "code", "message", "details" } }. Branch on error.code and fix the call instead of resending it: domain_not_verified means the from domain isn't verified, validation_error names the bad fields in details, and rate_limit_exceeded comes with a Retry-After wait. Over MCP the same error arrives under data, with a hint for the next move.

  5. Verify the send

    Make the first send to an address you own, from an address on a verified domain. A success returns the email's id and a status of queued (scheduled when you set scheduled_at); over MCP the same object comes back under data. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back with email_get (MCP) or GET /api/v1/email/{id}.

    JSON
    {
      "id": "email_…",
      "status": "queued",
      "scheduled_at": null
    }

    A retry with the same idempotency key returns this same body (REST adds Idempotent-Replayed: true) and sends nothing new.

Search docs and guides

Search the docs and product guides.