Give an OpenAI Agents SDK agent an email tool
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.