Example: Inline 2FA-code signup

Operations

Sign up for a third-party service on behalf of a user, wait for the verification code email, extract the code, and complete the signup — all in one agent turn without any public webhook receiver.

This is the flagship WebSocket use case. Full implementation:

import WebSocket from "ws";
import { randomUUID } from "node:crypto";

const API = "https://myagentmail.com/v1";
const KEY = process.env.MYAGENTMAIL_KEY!;

async function mam(method: string, path: string, body?: unknown) {
  const r = await fetch(`${API}${path}`, {
    method,
    headers: { "X-API-Key": KEY, "Content-Type": "application/json" },
    body: body ? JSON.stringify(body) : undefined,
  });
  if (!r.ok) throw new Error(`${method} ${path} → ${r.status}`);
  return r.json();
}

async function getVerificationCode(timeoutMs = 120_000): Promise<{ inbox: any, code: string }> {
  // 1. Spin up a fresh inbox just for this signup
  const inbox = await mam("POST", "/inboxes", {
    username: `signup-${randomUUID().slice(0, 8)}`,
  });

  // 2. Open a WebSocket subscribed to that inbox
  const ws = new WebSocket("wss://myagentmail.com/v1/ws", {
    headers: { "X-API-Key": KEY },
  });

  const code = await new Promise<string>((resolve, reject) => {
    const timer = setTimeout(() => {
      ws.close();
      reject(new Error("Timed out waiting for 2FA code"));
    }, timeoutMs);

    ws.on("open", () => {
      ws.send(JSON.stringify({
        type: "subscribe",
        event_types: ["message.received"],
        inbox_ids: [inbox.id],
      }));
    });

    ws.on("message", (raw) => {
      const frame = JSON.parse(raw.toString());
      if (frame.type !== "event" || frame.event_type !== "message.received") return;

      const haystack = (frame.message.subject || "") + " " + (frame.message.plain_body || "");
      const m = haystack.match(/\b\d{4,8}\b/);
      if (m) {
        clearTimeout(timer);
        ws.close();
        resolve(m[0]);
      }
    });
    ws.on("error", reject);
  });

  return { inbox, code };
}

// Use it
const { inbox, code } = await getVerificationCode();
console.log("Inbox:", inbox.email);
console.log("Code:",  code);
// → Submit the code to whatever signup page you're automating

The key insight: the WebSocket is outbound-only. You don't need a public URL or a deployed webhook receiver. This works from a Lambda, a container, a CI runner, or your laptop.