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.
npx skills add unitpostcom/skills --skill unitpost
npx skills add unitpostcom/skills --skill unitpost -gUnit
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 UnitMCP
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 URL | https://mcp.unitpost.com/mcp |
|---|---|
| Transport | Streamable 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) |
| Tools | one 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.
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
authobject withCLIENT_ID: cursor-oauth(public client, PKCE — no secret needed).Reload and verify
Reload MCP servers in Cursor. unitpost should show connected with tools like
email_send,email_campaigns_send,email_domains_verify.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.
Add the server
Run once. This only saves the URL — no browser opens yet.
Shellclaude mcp add --transport http unitpost https://mcp.unitpost.com/mcpUse
-s userto install for every project.claude mcp listnow shows unitpost as! Needs authentication— that is expected.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.
Verify
Run
claude mcp list(or/mcpin a session). unitpost should show connected with its tools listed — no! Needs authenticationflag.Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.
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.
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 URL https://mcp.unitpost.com/mcp 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.
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.
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 URL https://mcp.unitpost.com/mcp On a Team or Enterprise plan, an Owner may need to add the connector for the organization first.
Verify
Open a chat, check the unitpost connector is enabled in the tools menu, and ask Claude to list your sending domains.
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.
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.Shellcodex mcp add unitpost --url https://mcp.unitpost.com/mcpLeave the bearer token and header fields empty: OAuth needs neither.
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.Verify
Run
codex mcp list. unitpost showsOAuthin the Auth column (Not logged inmeans sign-in is still pending). In a session,/mcplists its tools, likeemail_sendandemail_domains_list.Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.
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.
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 URL https://mcp.unitpost.com/mcp Custom MCP connectors may need developer mode, or a workspace admin on Business and Enterprise plans.
Verify
Start a chat with the unitpost connector enabled and ask ChatGPT to list your sending domains.
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).
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/redirectandhttp://127.0.0.1:33418.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.
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.
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" } } }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.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.
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.
Verify
unitpost should show connected with tools like
email_sendandemail_domains_list.Don't see it? Fully quit and reopen the client — closing the window is often not enough — then check again.
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.
Connect with OAuth (recommended)
In Windsurf: Settings → Cascade → MCP Servers → Add Server, or paste this into `~/.codeium/windsurf/mcp_config.json`. Windsurf uses
serverUrl(noturl) 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" } } }Refresh and verify
Refresh the MCP server list. Unitpost's tools should appear under unitpost.
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`.
Add the remote server
Put this in
~/.config/opencode/opencode.jsonc(or projectopencode.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": {} } } }Authenticate
Restart OpenCode, then run
opencode mcp auth unitpost(or wait for the first tool call). Complete the browser approval.Verify
Run
opencode mcp list. unitpost should show connected.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.
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.
Texthttps://mcp.unitpost.com/mcpVerify
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.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 variableUNITPOST_API_KEY, and ask v0 to send email with theunitpostnpm package.TypeScriptimport { 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.
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 URL https://mcp.unitpost.com/mcp Transport Streamable HTTP Auth (recommended) OAuth 2.1 — add the URL, approve in the browser Auth (legacy) Authorization: Bearer pk_live_YOUR_KEY Tools one per API operation (email_send, email_campaigns_send, …) Toolsets (optional) https://mcp.unitpost.com/mcp?toolsets=default,campaigns Discover tools
The server advertises one tool per API operation (
email_send,email_campaigns_send,email_domains_verify, …). A write'sbodymaps to the API request body. Every tool declaressecuritySchemes: [{ type: "oauth2", scopes: […] }]so linking-aware clients (ChatGPT) show the Connect UI.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 anX-MCP-Toolsetsheader, with any ofaudience,templates,campaigns,sending,inbox,domainsandworkspace(the server instructions list every group), plusdefaultfor the standard set andallfor 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.Texthttps://mcp.unitpost.com/mcp?toolsets=default,campaigns,templatesVerify
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 missingBearerprefix 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.
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, replacepk_live_YOUR_KEYwith that value.Shown once. Keep the
Bearerprefix in every snippet. Grant only the scopes the agent needs (e.g.emails:sendforemail_send). Prefer a revocable key dedicated to the agent.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
unitpostentry under top-levelmcpServers.JSON{ "mcpServers": { "unitpost": { "url": "https://mcp.unitpost.com/mcp", "headers": { "Authorization": "Bearer pk_live_YOUR_KEY" } } } }Claude Code (static header)
Flags stay before the name/URL.
Shellclaude mcp add --transport http --header "Authorization: Bearer pk_live_YOUR_KEY" unitpost https://mcp.unitpost.com/mcpClaude Desktop (mcp-remote bridge)
For plans without custom connectors. In Claude Desktop: Settings → Desktop app → Developer → Edit Config, then merge the block below —
mcpServersmust be a top-level key (sibling ofpreferences), 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:inargs— Claude Desktop mangles spaces there; the value lives inenvinstead. Requires Node.js 18+. Ifnpxis 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.Codex (TOML)
For a machine where
codex mcp logincan't open a browser. Edit~/.codex/config.toml(shared by the CLI, IDE extension and app) and setUNITPOST_API_KEYto your key in the environment Codex runs in. Codex sends it asAuthorization: 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"VS Code (runtime-prompted key)
Create or edit `.vscode/mcp.json`. When VS Code prompts later, paste only the
pk_live_…value — notBearer(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}" } } } }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" } } } }Windsurf (static header)
Edit `~/.codeium/windsurf/mcp_config.json`. Windsurf uses
serverUrl(noturl) for remote HTTP.JSON{ "mcpServers": { "unitpost": { "serverUrl": "https://mcp.unitpost.com/mcp", "headers": { "Authorization": "Bearer pk_live_YOUR_KEY" } } } }OpenCode (static header)
Set
oauth: falseand pass the Bearer key.JSON{ "mcp": { "unitpost": { "type": "remote", "url": "https://mcp.unitpost.com/mcp", "oauth": false, "headers": { "Authorization": "Bearer pk_live_YOUR_KEY" } } } }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" } }Verify with the key
Call a read tool (e.g. list domains). A 401 Invalid API key usually means a missing
Bearerprefix 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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Connect the AI SDK MCP client
Install
aiand@ai-sdk/mcp.createMCPClientconnects over streamable HTTP with your key as a Bearer header.?toolsets=sendingkeeps the server's list to sending tools, and the agent gets one of them:email_send.TypeScriptimport { 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_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.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.TypeScriptimport { 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-Agentis required: a request without one is refused withmissing_user_agent(403).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,
toolApprovaldecides per call: deny any recipient off the allowlist and ask a person about the rest. The result then holds atool-approval-request; answer it with atool-approval-responseand callgenerateTextagain.TypeScriptconst 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 onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Connect MCPServerStreamableHttp
Install
openai-agents.MCPServerStreamableHttpsends your key as a Bearer header, andcreate_static_tool_filterleaves the agent one tool:email_send.Pythonimport 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_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one function tool
No MCP server needed: one
@toolfunction that posts to/api/v1/email. The SDK builds the schema from the signature and docstring.Pythonimport 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-Agentis required: a request without one is refused withmissing_user_agent(403).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, orrequire_approval={"email_send": "always"}on the MCP server, pauses the run at each send. Approve or reject the pending calls, then resume.Pythonfrom 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_outputErrors come back as
{ "error": { "code", "message", "details" } }. Branch onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Load the tools with MCPAdapter
Install
langchain[mcp](1.4 or later;langchain.mcpis in beta). A FastMCPClientwithauthset to the key sends it as a Bearer token. Keep onlyemail_sendfrom the list.Pythonimport 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 replacesMultiServerMCPClientwithMCPAdapter.email_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one REST send tool
No MCP needed: one
@toolfunction that posts to/api/v1/email. The docstring becomes the tool description the model reads.Pythonimport 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-Agentis required: a request without one is refused withmissing_user_agent(403).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,
HumanInTheLoopMiddlewarepauses the agent before the send tool runs (send_emailhere,email_sendover MCP). It needs a checkpointer and a thread ID; resume with a decision.Pythonfrom 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 onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Connect MCPClient
Install
@mastra/mcpand@mastra/core.MCPClientsends the key inrequestInit.headers.listTools()names each toolserverName_toolName, so the send tool isunitpost_email_send.TypeScriptimport { 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_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one REST send tool
No MCP needed: one
createToolthat posts to/api/v1/email.requireApproval: truepauses every call to it beforeexecuteruns.TypeScriptimport { 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-Agentis required: a request without one is refused withmissing_user_agent(403).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,
requireApprovalon the tool, orrequireToolApprovalon the MCP server, pauses each send. The stream emits atool-call-approvalchunk; approve or decline it with the stream'srunId.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 onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Add MCPServerHTTP to the agent
Install
crewai.MCPServerHTTPconnects over streamable HTTP with your key inheaders, andcreate_static_tool_filterkeeps one tool:email_send.Pythonimport 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_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one REST send tool
No MCP needed: one
@toolfunction that posts to/api/v1/email. Pass it in the agent'stools.Pythonimport 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-Agentis required: a request without one is refused withmissing_user_agent(403).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_CALLhook runs before the tool: raiseHookAbortedto 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 foremail_send.Pythonfrom 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 onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Attach an MCPToolset
Install
pydantic-ai-slim[mcp].MCPToolsettakes the key asauthand sends it as a Bearer token;.filtered()keeps one tool:email_send.Pythonimport 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_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one REST send tool
No MCP needed: one
@agent.tool_plainfunction that posts to/api/v1/email.requires_approval=Truedefers every call to it until it's approved.Pythonimport 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-Agentis required: a request without one is refused withmissing_user_agent(403).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=Trueon the tool, or.approval_required()on the MCP toolset, ends the run with aDeferredToolRequestsoutput. Answer each pending call, then run again with the message history.Pythonfrom 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.outputErrors come back as
{ "error": { "code", "message", "details" } }. Branch onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Add the server to mcpServers
Install
@anthropic-ai/claude-agent-sdk. Usetype: "http"for streamable HTTP and put the key inheaders. Tools are namedmcp__<server>__<tool>, so the send tool ismcp__unitpost__email_send.TypeScriptimport { 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_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one in-process send tool
No remote MCP needed: define the tool with
tool(), wrap it increateSdkMcpServer, and pass that server inmcpServers. It posts to/api/v1/emailand returns the result or the error envelope.TypeScriptimport { 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-Agentis required: a request without one is refused withmissing_user_agent(403).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,
canUseToolruns for every tool call that no allow rule approved, so leave the send tool out ofallowedToolsand decide there: allow it, or deny it with a message the agent reads.TypeScriptconst 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 onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.
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 thepk_live_…value (shown once) into the environment your agent runs in.Shellexport UNITPOST_API_KEY=pk_live_YOUR_KEYA 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.
Attach the MCP connector
Install
anthropic. Pass the server inmcp_serverswith your key asauthorization_token(sent as a Bearer token), and allowlistemail_sendin the matchingmcp_toolset. The connector needs themcp-client-2025-11-20beta.Pythonimport 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 envelopeThe connector runs
email_sendinside the request, with no pause for approval.email_sendtakes anidempotency_keybesidebody. Tell the agent to pass a new one per message and the same one on a retry: the server's instructions say so too.Or add one client tool
Your code runs this tool, so it can check and ask before the POST.
@beta_toolbuilds the schema from the signature and docstring, and the tool runner loops until Claude is done.Pythonimport 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-Agentis required: a request without one is refused withmissing_user_agent(403).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_toolsetand 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 onerror.codeand fix the call instead of resending it:domain_not_verifiedmeans thefromdomain isn't verified,validation_errornames the bad fields indetails, andrate_limit_exceededcomes with aRetry-Afterwait. Over MCP the same error arrives underdata, with ahintfor the next move.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
idand astatusofqueued(scheduledwhen you setscheduled_at); over MCP the same object comes back underdata. Open Emails in the dashboard to see the message, its recipient and its delivery status, or read it back withemail_get(MCP) orGET /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.