{
  "openapi": "3.0.3",
  "info": {
    "title": "Mail Service Now \u2014 Email Services & API for Private Clients",
    "version": "0.8.0",
    "description": "Email Services & API for Private Clients. Recommended owner-approved scoped OAuth at https://mailservicenow.com/api/mcp supports durable domain/mailbox onboarding, exact DNS previews and customer-domain inbox read/search/send/reply. Credentials travel only through OAuth transport. Legacy customer keys and REST remain available. Documented 2026-10-07. Account approval, ownership, DNS, mailbox creation, exact-config mail-server acknowledgement and actual delivery are separate. Full guide: https://mailservicenow.com/docs/agent-onboarding.md"
  },
  "servers": [
    {
      "url": "https://us-central1-mailservicenow.cloudfunctions.net"
    },
    {
      "url": "https://mailservicenow.com/api"
    },
    {
      "url": "https://mailservicenow.web.app/api"
    }
  ],
  "paths": {
    "/sendMail": {
      "post": {
        "summary": "Send email",
        "description": "Plain-text or sanitized HTML body. HTML sends use multipart/alternative with a generated plain-text fallback when text is omitted or blank. Safe semantic tags, tables, links, and images are retained; supplied styles, classes, scripts, forms, and unsafe URLs are removed. No HTML resources are fetched by the server. Always set from to an address on a verified domain you own, for example support@example-domain.com. If it's omitted and the account has exactly one sendable hosted mailbox, that mailbox is used as a fallback; with more than one, omitting from is an error (400 Choose the address to send from). The shared agent key sends as noreply@mailservicenow.com. Optional attachments (max 3, 2MB each, 4MB total; common image, PDF, text, CSV, and Office Open XML types). Agent sends cost 1 credit, consumed after validation and before SMTP (not refunded if SMTP fails). Order: auth, global kill switch, agent-key disable, rate limit, validation, credit, SMTP. Agent key disabled is 503 and does not spend a credit. Max 5 recipients. Combined text and html input and processed bodies max 100KiB UTF-8; encoded MIME max 6MiB before credit charging. MCP send_mail accepts the same from rule and does not accept attachments.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SendRequest"
              },
              "example": {
                "to": "recipient@example.com",
                "from": "support@example-domain.com",
                "subject": "Hello from an agent",
                "text": "Sent via MailServiceNow."
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Sent. creditsRemaining is present for agent auth only.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SendSuccess"
                },
                "example": {
                  "ok": true,
                  "messageId": "<id@mail.mailservicenow.com>",
                  "creditsRemaining": 99
                }
              }
            }
          },
          "400": {
            "description": "Missing fields, more than 5 recipients, combined body over 100KiB, invalid field types, encoded MIME over 6MiB, or Choose the address to send from when several hosted mailboxes exist and from is omitted",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid agent key or Firebase ID token",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "405": {
            "description": "Method not allowed (POST only; OPTIONS is 204)"
          },
          "429": {
            "description": "Rate limit exceeded, or insufficient agent credits. Distinguish by the error string.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "examples": {
                  "rate": {
                    "value": {
                      "ok": false,
                      "error": "Rate limit exceeded"
                    }
                  },
                  "credits": {
                    "value": {
                      "ok": false,
                      "error": "Insufficient credits"
                    }
                  }
                }
              }
            }
          },
          "500": {
            "description": "Send failed or MTA is not configured"
          },
          "503": {
            "description": "Sending temporarily disabled (global kill switch) or Agent key disabled (agent key frozen). Neither spends a credit.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "ok": false,
                  "error": "Sending temporarily disabled"
                }
              }
            }
          }
        }
      }
    },
    "/inbox": {
      "get": {
        "summary": "List inbound mail, or read one message",
        "description": "Omit id, messageId, thread, view, and q to list messages. unreadInPage counts unread rows in this page only. Read responses sanitize stored HTML and provide a plain-text fallback for HTML-only messages. Generated inbound fallback is bounded to 256KiB UTF-8; markup that expands beyond 256KiB is omitted in favor of text. Reading by id or messageId marks that row read and updates the thread unreadCount. view=threads lists conversation threads in folder=inbox unless folder is archive or trash. A missing folder field counts as inbox. thread=<64-hex> returns that thread oldest-first and marks its inbound rows read. q= is a case-insensitive substring search of subject, from, and body over the newest 200 inbound and 200 outbound rows in the mailbox. Search does not mark mail read. Optional folder on q= or the flat list limits that result to inbox, archive, or trash. If id or messageId is set, that single-message read wins, then thread, then q, then view. Does not spend credits and is not rate limited. Empty until the VPS ingest poller runs.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "parameters": [
          {
            "name": "limit",
            "in": "query",
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 50,
              "default": 25
            }
          },
          {
            "name": "mailbox",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "Optional @mailservicenow.com mailbox. Needs the composite Firestore index."
          },
          {
            "name": "id",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "Firestore document id. Pattern ^[A-Za-z0-9_-]{1,128}$"
          },
          {
            "name": "messageId",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "RFC Message-ID"
          },
          {
            "name": "view",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "threads"
              ]
            },
            "description": "threads lists mail_threads instead of the flat message page"
          },
          {
            "name": "thread",
            "in": "query",
            "schema": {
              "type": "string",
              "pattern": "^[a-f0-9]{64}$"
            },
            "description": "Thread id. Returns ordered messages."
          },
          {
            "name": "q",
            "in": "query",
            "schema": {
              "type": "string",
              "minLength": 2,
              "maxLength": 200
            },
            "description": "Substring search. Wins over view and the flat list. Does not win over id, messageId, or thread."
          },
          {
            "name": "folder",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "inbox",
                "archive",
                "trash"
              ]
            },
            "description": "On view=threads, omitted means inbox. On the flat list and on q=, omitted means every folder. Threads and messages with no folder field are inbox."
          }
        ],
        "responses": {
          "200": {
            "description": "List or one message",
            "content": {
              "application/json": {
                "schema": {
                  "oneOf": [
                    {
                      "$ref": "#/components/schemas/InboxList"
                    },
                    {
                      "$ref": "#/components/schemas/InboxOne"
                    },
                    {
                      "$ref": "#/components/schemas/ThreadList"
                    },
                    {
                      "$ref": "#/components/schemas/ThreadDetail"
                    },
                    {
                      "$ref": "#/components/schemas/SearchResult"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "Invalid id, messageId, mailbox, thread, view, or search query"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Message or thread not found"
          },
          "405": {
            "description": "Method not allowed (GET or POST)"
          }
        }
      },
      "post": {
        "summary": "Mark a thread read or unread, or move it to a folder",
        "description": "Same auth as GET /inbox. No credits and no rate limit. Body is JSON. Pass thread (64 hex), or id, or messageId. Pass unread true or false, folder (inbox, archive, or trash), or both. id wins over messageId and over thread when more than one target is set. unread on a thread sets every inbound row in that thread. unread on an id sets that one inbound row and refreshes the thread unreadCount. Outbound rows stay read. folder moves the whole thread and the messages loaded for it (up to 100 inbound and 100 outbound). A new inbound message files the thread back into inbox. Does not spend credits.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MailboxStateRequest"
              },
              "examples": {
                "unread": {
                  "value": {
                    "thread": "ff9b088e3dc69e06daa1346a1e020ffae7bac32de41df5a2c236f406557f4c82",
                    "unread": true
                  }
                },
                "archive": {
                  "value": {
                    "thread": "ff9b088e3dc69e06daa1346a1e020ffae7bac32de41df5a2c236f406557f4c82",
                    "folder": "archive"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated thread, or one message when that row has no thread id",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MailboxStateResult"
                }
              }
            }
          },
          "400": {
            "description": "Missing target, invalid thread or id, unread not boolean, or folder not inbox, archive, or trash"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Thread or message not found"
          },
          "405": {
            "description": "Method not allowed (GET or POST)"
          }
        }
      }
    },
    "/attachment": {
      "get": {
        "summary": "Download one stored attachment",
        "description": "Same auth as inbox. No credits and no rate limit. box=inbound (default) or outbound. index is the attachment index on that message. disposition=inline is honored for image, pdf, and text. Bytes come from Firebase Storage. Firestore stores metadata only.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "Firestore document id"
          },
          {
            "name": "messageId",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "RFC Message-ID. id wins when both are set."
          },
          {
            "name": "index",
            "in": "query",
            "required": true,
            "schema": {
              "type": "integer",
              "minimum": 0,
              "maximum": 2
            }
          },
          {
            "name": "box",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "inbound",
                "outbound"
              ],
              "default": "inbound"
            }
          },
          {
            "name": "disposition",
            "in": "query",
            "schema": {
              "type": "string",
              "enum": [
                "inline"
              ]
            }
          }
        ],
        "responses": {
          "200": {
            "description": "File bytes. Content-Type is the stored type. Content-Disposition is attachment, or inline when requested and the type can be previewed."
          },
          "400": {
            "description": "Invalid box, index, id, or messageId"
          },
          "401": {
            "description": "Unauthorized"
          },
          "404": {
            "description": "Message or attachment not found"
          },
          "405": {
            "description": "Method not allowed (GET only)"
          }
        }
      }
    },
    "/drafts": {
      "get": {
        "summary": "List or read the signed-in user's drafts",
        "description": "Firebase ID token only. Agent keys are 403. Drafts are stored in Firestore collection drafts and are readable only for that uid. No credits.",
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "One draft. Omit to list the newest 25."
          }
        ],
        "responses": {
          "200": {
            "description": "draft or drafts"
          },
          "400": {
            "description": "Invalid id"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Drafts require a signed-in user"
          },
          "404": {
            "description": "Draft not found"
          }
        }
      },
      "post": {
        "summary": "Create or update a draft",
        "description": "Body fields to, subject, text, html, optional inReplyTo, references, and id. Sanitized HTML and any user-written plain-text fallback are preserved. Blank text remains blank in a draft; a fresh fallback is generated from the final HTML when sent. At least one of to, subject, text, readable html, or inReplyTo is required. Combined text and html max 100KiB UTF-8. Passing id updates that user's draft. Omit id to create. Maximum 50 drafts per user.",
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ ok, draft } with draft.id"
          },
          "400": {
            "description": "Empty draft, invalid id, or field too long"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Drafts require a signed-in user"
          },
          "404": {
            "description": "Draft not found"
          }
        }
      },
      "delete": {
        "summary": "Delete one draft",
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "parameters": [
          {
            "name": "id",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "{ ok, id }"
          },
          "400": {
            "description": "id is required or invalid"
          },
          "401": {
            "description": "Unauthorized"
          },
          "403": {
            "description": "Drafts require a signed-in user"
          },
          "404": {
            "description": "Draft not found"
          },
          "405": {
            "description": "Method not allowed"
          }
        }
      }
    },
    "/credits": {
      "get": {
        "summary": "Read agent credits and key status",
        "description": "Firebase ID token or agent API key. Returns remaining credits (default key starts at 100), agent key last4 and status, send limits, and whether this caller can change the kill switch. Does not spend a credit. Does not return the full key. Humans are not charged on send.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Credits and key status",
            "content": {
              "application/json": {
                "example": {
                  "ok": true,
                  "credits": {
                    "remaining": 100,
                    "initial": 100,
                    "humansCharged": false,
                    "authFailureBurnsCredit": false
                  },
                  "agentKey": {
                    "id": "default",
                    "last4": "ab12",
                    "status": "active",
                    "disabled": false,
                    "frozenUntil": null
                  },
                  "sending": {
                    "enabled": true
                  },
                  "canControl": true,
                  "canPauseAll": false,
                  "docs": "https://mailservicenow.com/developers/#credits"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid agent key or Firebase ID token. No credit spent."
          }
        }
      },
      "post": {
        "summary": "Freeze or unfreeze sending",
        "description": "Agent key may set disabled (boolean) and frozenUntil (ISO time or null) on agent_keys/default. An operator Firebase account may also set sendingEnabled, which writes config/send.enabled. Other signed-in users are 403. Checked on the next sendMail and MCP send_mail before any credit spend. Does not itself spend a credit.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "disabled": {
                    "type": "boolean"
                  },
                  "frozenUntil": {
                    "type": "string",
                    "nullable": true
                  },
                  "sendingEnabled": {
                    "type": "boolean"
                  }
                }
              },
              "example": {
                "disabled": true
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated status. Same body as GET /credits."
          },
          "400": {
            "description": "Invalid JSON or control fields"
          },
          "401": {
            "description": "Missing or invalid credential. No credit spent."
          },
          "403": {
            "description": "Caller cannot change this flag"
          },
          "405": {
            "description": "Method not allowed (GET or POST)"
          }
        }
      }
    },
    "/webhooks": {
      "get": {
        "summary": "Read the default agent webhook",
        "description": "Agent API key only. Returns the HTTPS URL and HMAC secret, or webhook null when none is registered. Does not spend a credit.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "Current registration",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookRegistration"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid agent key, or invalid Firebase token"
          },
          "403": {
            "description": "Webhooks require an agent API key"
          }
        }
      },
      "post": {
        "summary": "Register or replace the default agent webhook",
        "description": "Agent API key only. One HTTPS URL. rotateSecret true issues a new whsec_ secret. enabled false keeps the row and skips delivery. Does not spend a credit. Private, loopback, and metadata URLs are rejected.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookWrite"
              },
              "example": {
                "url": "https://example.com/hooks/msn"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Stored registration, including secret",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookRegistration"
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON or URL"
          },
          "401": {
            "description": "Missing or invalid agent key, or invalid Firebase token"
          },
          "403": {
            "description": "Webhooks require an agent API key"
          },
          "405": {
            "description": "Method not allowed"
          }
        }
      },
      "delete": {
        "summary": "Remove the default agent webhook",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "responses": {
          "200": {
            "description": "{ ok: true, webhook: null }"
          },
          "401": {
            "description": "Missing or invalid agent key"
          },
          "403": {
            "description": "Webhooks require an agent API key"
          },
          "405": {
            "description": "Method not allowed"
          }
        }
      }
    },
    "/addMailbox": {
      "post": {
        "summary": "Create a mailbox with a delivery mode",
        "description": "Standard customer key (msn_ from a ready verifyAccessRequest) or Firebase ID token. Account setup must be complete. The shared agent key is 401 Invalid API key when sent as X-Api-Key, or 401 Firebase sign-in required when sent as Bearer. Accounts not yet approved are 403 Account setup is not complete yet. A ready key does not create this mailbox by itself. mode is hosted, forward, or both. forwardTo is an array of email addresses (a single string is accepted). Required and non-empty for forward and both. Must be empty for hosted. Lowercased and de-duplicated. At most 5 targets. Rejects an invalid address, a target equal to the mailbox, a target on the same domain that is not a mailbox, a forwarding loop, and mailservicenow.com. This request does not write mail-server maps. The mail server syncs from mtaMailboxExport about every 60 seconds. Response mailbox.delivery is the plan that sync reads: hosted is vmailbox only, forward is a virtual alias only, both is vmailbox plus alias address -> address, forwardTo. For hosted/both, omit password to generate a secure password or supply a nonempty custom value of at most 1024 UTF-8 bytes without controls, line breaks, or invalid Unicode. Weak custom passwords are accepted. Creation atomically stores only the hash and returns password once with clientSettings. Existing mailbox conflicts never rotate credentials. Forward-only rejects a supplied password. Use clientSettings.mailboxes[].provisioningStatus for exact current-configuration acknowledgment; legacy mtaApplied alone is not current credential readiness. Configuration applied does not verify login. A new claim without verified ownership is 403 domain_ownership_required. Prove its account-bound TXT using verifyDomain/verify_domain first.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MailboxWrite"
              },
              "example": {
                "domainId": "acme.example",
                "localPart": "sales",
                "mode": "both",
                "forwardTo": [
                  "ada@gmail.com"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Mailbox stored atomically with a password for hosted/both. Save the response password now; it cannot be retrieved later. clientSettings reports pending until the exact configuration is acknowledged. No login probe is performed.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MailboxResult"
                }
              }
            }
          },
          "400": {
            "description": "Invalid mode, address, cap of 5, self-forward, missing mailbox on the same domain, or forwarding loop"
          },
          "401": {
            "description": "Missing Firebase token, or agent key (Firebase sign-in required)"
          },
          "403": {
            "description": "Account setup is not complete yet"
          },
          "409": {
            "description": "That mailbox already exists on this domain. domain_removed when the domain was removed: That domain was removed. Add it again if you still own it. The removed row is not changed. Body includes code and error."
          }
        }
      }
    },
    "/setMailboxMode": {
      "post": {
        "summary": "Change a mailbox delivery mode",
        "description": "Same auth as addMailbox: standard customer key or Firebase ID token. The shared agent key is refused. Does not delete stored Maildir. Switching to forward does not issue IMAP/SMTP credentials and removes webmail login. Switching back to hosted or both restores access. The mail server syncs the new mode from mtaMailboxExport about every 60 seconds. mtaApplied and mtaAppliedAt confirm it is live.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MailboxModeWrite"
              },
              "example": {
                "domainId": "acme.example",
                "localPart": "sales",
                "mode": "forward",
                "forwardTo": [
                  "ada@gmail.com",
                  "bills@example.com"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Updated mailbox, including mode, forwardTo, and delivery",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MailboxResult"
                }
              }
            }
          },
          "400": {
            "description": "Invalid mode, address, cap of 5, self-forward, or forwarding loop"
          },
          "401": {
            "description": "Firebase sign-in required"
          },
          "403": {
            "description": "Account setup is not complete yet"
          },
          "404": {
            "description": "Mailbox not found"
          },
          "409": {
            "description": "domain_removed when the domain was removed: That domain was removed. Add it again if you still own it. The removed row is not changed. Body includes code and error."
          }
        }
      }
    },
    "/deleteMailbox": {
      "post": {
        "summary": "Delete a mailbox record",
        "description": "Standard customer key or Firebase ID token. Account setup must be complete. The shared agent key is 401 Firebase sign-in required on Bearer, or 401 Invalid API key on X-Api-Key. Accounts not yet approved are 403 Account setup is not complete yet. A caller who does not own the mailbox gets 404. Body is { address } or { domain, localPart }. domainId and mailboxId are accepted. Deletes the Firestore mailbox record. A missing mailbox is 404. a protected address is 409 and is not deleted. The last active mailbox on a verified domain is 409: This is the last mailbox on <domain>. Add another mailbox first, or contact support to remove the domain. Only active mailboxes count. Unverified domains are not affected. Does not delete the Maildir. Response mailbox.delivery is the removal plan (vmailbox false, virtualAlias null) and mtaApplied is false. Routing drops on the next mail server sync, about every 60 seconds. The Maildir is kept. maildir is leave.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/MailboxDelete"
              },
              "examples": {
                "address": {
                  "value": {
                    "address": "sales@acme.example"
                  }
                },
                "parts": {
                  "value": {
                    "domain": "acme.example",
                    "localPart": "sales"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Mailbox record removed. The Maildir is kept. Routing drops on the next mail server sync, about every 60 seconds.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MailboxDeleteResult"
                }
              }
            }
          },
          "400": {
            "description": "Missing or invalid address, or address does not match domain and localPart"
          },
          "401": {
            "description": "Missing Firebase token, or agent key (Firebase sign-in required)"
          },
          "403": {
            "description": "Account setup is not complete yet"
          },
          "404": {
            "description": "Mailbox not found, including a mailbox on another account"
          },
          "409": {
            "description": "A protected address is not deleted. Or the last active mailbox on a verified domain: This is the last mailbox on <domain>. Add another mailbox first, or contact support to remove the domain. There is no force flag. Operators use POST /operatorRemoveDomain. domain_removed when the domain was removed: That domain was removed. Add it again if you still own it. The removed row is not changed."
          }
        }
      }
    },
    "/operatorRemoveDomain": {
      "post": {
        "summary": "Operator: mark a domain and its mailboxes removed",
        "description": "Operator Firebase ID token, the same check as the domain allowlist. Standard and request_access keys are 403 even when the email is an operator address. Agent keys are 403. Body is { uid or ownerEmail, domainId, confirm }. When the domain has any mailbox, confirm must be the domain name. Marks the domain removed and every mailbox on it removed. Mail stored for this domain is permanently deleted and cannot be recovered. A protected domain is 409. A domain that contains a protected address is 409. mailservicenow.com is 409. This is the supported path for removing a domain's last mailbox. deleteMailbox stays 409 for that case and has no force flag. A domain whose account record is gone can still be removed. The claim is released in that write when it still names that account.",
        "security": [
          {
            "BearerAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "uid": {
                    "type": "string"
                  },
                  "ownerEmail": {
                    "type": "string"
                  },
                  "domainId": {
                    "type": "string"
                  }
                },
                "required": [
                  "domainId"
                ]
              },
              "example": {
                "ownerEmail": "ada@example.com",
                "domainId": "acme.example"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Domain and mailboxes marked removed. maildir is leave."
          },
          "400": {
            "description": "Missing uid and ownerEmail, or they name different accounts, or domainId is invalid"
          },
          "401": {
            "description": "Missing Authorization Bearer token"
          },
          "403": {
            "description": "This action is limited to operator accounts."
          },
          "404": {
            "description": "Account or domain not found"
          },
          "409": {
            "description": "A protected domain is not removed. A domain that contains a protected address is not removed."
          }
        }
      }
    },
    "/addDomain": {
      "post": {
        "summary": "Add a customer domain",
        "description": "Standard customer key (msn_ from a ready verifyAccessRequest) or Firebase ID token. Account setup must be complete. The shared agent key is 401 Invalid API key on X-Api-Key, or 401 Firebase sign-in required on Bearer. Accounts not yet approved are 403 Account setup is not complete yet. Body field domain is the hostname, such as example-domain.com. Email signup does not call this for you; DNS signup/approval may already add its proved hostname, and intendedUse does not create mailboxes. The live function checks DNS immediately. Before MX, SPF, and DKIM match, the response can be 200 with created true, verified false, and domain.status failed. Read domain.dnsInstructions.records and domain.failureReason, publish those records, then POST /verifyDomain. Calling addDomain again for the same normalized name (lowercase, trim, strip a trailing dot) returns 200 created false and does not change mailboxes or DNS. An account may add additional domains. A subdomain or parent of a domain already on the account is 409 code domain_variant. That hostname is a subdomain or parent of a domain already on this account. Use the existing domain and add mailboxes on it, or contact support@mailservicenow.com to remove it. A hostname on another account is 409 code domain_claimed. That domain belongs to another account. If you own it, contact support@mailservicenow.com to have it moved to your account. mailservicenow.com is 400. MCP add_domain uses the same rule. The shared agent key is refused. The saved account key is accepted. Every new claim has an unpredictable account/domain-bound TXT at _msn-domain.<domain>, value msn-domain-verification=<64hex>, returned as dnsInstructions.records id ownership. dnsInstructions.ownership includes required, expiresAt and verifiedAt. Initial proof expires after 24 hours. Repeating addDomain preserves an active proof and renews an expired one. Mailboxes and DNS-provider records are unchanged. New ownership must be verified before mailbox creation/sending; shared public mail DNS alone is insufficient. Previously verified domains are grandfathered; unverified legacy domains gain a challenge lazily. Reserved foreign claims require operator review, not automatic transfer. Ownership TXT CNAME and wildcard answers are refused.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "domain"
                ],
                "properties": {
                  "domain": {
                    "type": "string",
                    "description": "Hostname you control, such as example-domain.com."
                  }
                }
              },
              "example": {
                "domain": "example-domain.com"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Domain stored. dnsInstructions.records includes MX mail.mailservicenow.com priority 10, SPF, and DKIM. verified may already be false when DNS is not published yet.",
            "content": {
              "application/json": {
                "example": {
                  "ok": true,
                  "created": true,
                  "verified": false,
                  "domain": {
                    "id": "example-domain.com",
                    "name": "example-domain.com",
                    "status": "failed"
                  }
                }
              }
            }
          },
          "400": {
            "description": "Enter a domain you own, such as example.com. or That domain name is not valid. Product domain mailservicenow.com cannot be added."
          },
          "401": {
            "description": "Invalid API key, or Firebase sign-in required for a shared agent key"
          },
          "403": {
            "description": "Account setup is not complete yet"
          },
          "409": {
            "description": "domain_variant. That hostname is a subdomain or parent of a domain already on this account. Use the existing domain and add mailboxes on it, or contact support@mailservicenow.com to remove it. domain_claimed when another account holds the name. That domain belongs to another account. If you own it, contact support@mailservicenow.com to have it moved to your account. Body includes code and error."
          }
        }
      }
    },
    "/getDnsInstructions": {
      "get": {
        "summary": "Read DNS records for a domain",
        "description": "Same auth as POST /addDomain. Query domainId is the hostname. Returns instructions (MX, SPF, DKIM, optional DMARC) for the signed-in account's domain. A removed domain is 409 domain_removed and is not returned. Also returns instructions.records id ownership and instructions.ownership {required,expiresAt,verifiedAt} for new claims; this is an account-bound DNS proof, not an API key. Same-account MCP equivalent is get_dns_instructions with domainId.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "parameters": [
          {
            "name": "domainId",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string"
            },
            "description": "Domain id, such as example-domain.com."
          }
        ],
        "responses": {
          "200": {
            "description": "domain, status, and instructions"
          },
          "400": {
            "description": "domainId is required"
          },
          "401": {
            "description": "Invalid API key, or Firebase sign-in required"
          },
          "403": {
            "description": "Account setup is not complete yet"
          },
          "404": {
            "description": "Domain not found"
          },
          "409": {
            "description": "domain_removed. That domain was removed. Add it again if you still own it. The removed row is not changed. Body includes code and error."
          }
        }
      }
    },
    "/verifyDomain": {
      "post": {
        "summary": "Check DNS and mark the domain verified or failed",
        "description": "Same auth as POST /addDomain. Body domainId (or domain) is the hostname. Call this after publishing dnsInstructions. verified true sets domain.status to verified. verified false sets failed and failureReason. checks.mx, checks.spf, and checks.dkim say which row missed. The preferred MX (lowest priority number) must be mail.mailservicenow.com. MX still on Cloudflare Email Routing fails with MX points at that host. Two SPF TXT records fail with Publish one SPF TXT. transient true means the lookup did not finish; status is left unchanged. A removed domain is 409 domain_removed and its status is not changed. Add the name again with addDomain if you still own it. The web app button is Check DNS. Moving MX off a previous host, including Cloudflare Email Routing, stops mail that host delivers today. New claims must prove the exact account-bound _msn-domain TXT in addition to mail DNS. Initial proof lasts 24 hours; expired proof is 409 domain_ownership_expired, renewed through addDomain. A concurrent removal/transfer/renewal is 409 domain_claim_changed. Successful proof stays with that claim; removal/re-add requires fresh proof. Same-account MCP equivalent is verify_domain with domainId.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "domainId": {
                    "type": "string"
                  },
                  "domain": {
                    "type": "string",
                    "description": "Accepted when domainId is omitted."
                  }
                }
              },
              "example": {
                "domainId": "example-domain.com"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "verified true or false, plus checks. transient true when DNS lookup did not finish.",
            "content": {
              "application/json": {
                "example": {
                  "ok": true,
                  "created": false,
                  "verified": true,
                  "transient": false,
                  "domain": {
                    "id": "example-domain.com",
                    "status": "verified"
                  }
                }
              }
            }
          },
          "400": {
            "description": "domainId is required, or the domain name is not valid"
          },
          "401": {
            "description": "Invalid API key, or Firebase sign-in required"
          },
          "403": {
            "description": "Account setup is not complete yet"
          },
          "404": {
            "description": "Domain not found"
          },
          "409": {
            "description": "domain_removed. That domain was removed. Add it again if you still own it. Status is not changed. Body includes code and error."
          }
        }
      }
    },
    "/listDomains": {
      "get": {
        "summary": "List domains and mailboxes",
        "description": "Standard customer key or Firebase ID token. Account setup must be complete. Each mailbox includes mode, forwardTo (array; empty for hosted), and delivery (vmailbox and virtualAlias). Existing hosted mailboxes, including a protected address, read back as hosted. A legacy forwardTo string is returned as a one-element array. Removed domains are omitted. The shared agent key is 401 Firebase sign-in required. A ready key does not add domains by itself; call POST /addDomain first.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "parameters": [
          {
            "name": "uid",
            "in": "query",
            "schema": {
              "type": "string"
            },
            "description": "Operator read of another account. Writes ignore this."
          }
        ],
        "responses": {
          "200": {
            "description": "domains[].mailboxes[] include mode, forwardTo, and delivery",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/DomainList"
                }
              }
            }
          },
          "401": {
            "description": "Firebase sign-in required"
          },
          "403": {
            "description": "Account setup is not complete yet"
          }
        }
      }
    },
    "/requestAccess": {
      "post": {
        "summary": "Ask for an account (no API key)",
        "description": "Public. Agents can sign up themselves with a username. contactEmail is optional. A username is 3 to 64 characters (letters, digits, and . _ - + @) and is stored case-insensitively. Reserved names such as admin, root, postmaster, and abuse are refused. A username that looks like an email is not a verified email and is never mailed. When contactEmail is set, the 8-digit code is emailed to that address and is not in the response. The code expires in 24 hours. When contactEmail is omitted, domain is required and the response includes a TXT record at exactly _msn-verify.<domain> with a single-use token that expires in 24 hours. Publish that TXT, then POST /verifyAccessRequest with method dns. Poll /getRequestStatus with requestId and username. The key is returned once on verify when the account is ready. The response does not say whether a username or domain is already on file. mailservicenow.com and its subdomains are refused on the DNS check. Rate limit: 5/hour per IP and 3/hour per email or username. 429 includes retryAfter seconds and a Retry-After header. Same behavior as MCP request_access. Request creation is not idempotent; persist requestId and avoid blind retries. Verification is the approval submission, not self-approval. An unmatched verified request awaits service owner/admin review. Email/DNS access and credential handling require the owner's authorization.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AccessRequest"
              },
              "example": {
                "contactEmail": "ops@example-domain.com",
                "domain": "example-domain.com",
                "agentName": "ExampleAgent",
                "intendedUse": "Send a notification from an agent"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Code emailed. expiresIn is seconds until the code expires (86400, 24 hours).",
            "content": {
              "application/json": {
                "example": {
                  "ok": true,
                  "requestId": "ar_0123456789abcdef01234567",
                  "expiresIn": 86400,
                  "message": "If the verification code email doesn't arrive within a few minutes, check the spam folder or contact support."
                }
              }
            }
          },
          "400": {
            "description": "contactEmail, domain, agentName, or intendedUse is invalid"
          },
          "429": {
            "description": "Rate limit exceeded. Body includes retryAfter seconds.",
            "content": {
              "application/json": {
                "example": {
                  "ok": false,
                  "error": "Rate limit exceeded",
                  "retryAfter": 3600
                }
              }
            }
          },
          "500": {
            "description": "Could not send the access code"
          }
        }
      }
    },
    "/verifyAccessRequest": {
      "post": {
        "summary": "Verify an email code or DNS TXT proof (no API key)",
        "description": "Public. Email route submits requestId and its emailed 8-digit code; no-email route submits requestId and method dns after publishing the exact _msn-verify.<domain> TXT. Proof expires after 24 hours; five mismatches lock it; CNAME/wildcard proofs are refused. A policy-approved new account returns ready with apiKey once; unmatched accounts return setting_up and await service owner/admin approval. Existing approved accounts can get a key before mail DNS/mailboxes are ready. Email recovery adds a key; DNS-bound recovery on the same verified domain rotates all previous customer keys. Save the returned key; status polling never returns it. The separate submitApplication flow returns pending_review after email verification. No verification can self-approve a pending account. Same behavior as MCP verify_access_request.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/AccessVerify"
              },
              "example": {
                "requestId": "ar_0123456789abcdef01234567",
                "code": "12345678"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "ready with apiKey, setting_up with no apiKey, or unavailable with a neutral message and no apiKey",
            "content": {
              "application/json": {
                "examples": {
                  "ready": {
                    "value": {
                      "ok": true,
                      "status": "ready",
                      "requestId": "ar_0123456789abcdef01234567",
                      "access": "standard",
                      "apiKey": "msn_<your-key>",
                      "tokenType": "Bearer",
                      "message": "Save this key now. It is shown once.",
                      "quotas": {
                        "credits": 100,
                        "burstPerMinute": 5,
                        "perUtcDay": 50
                      }
                    }
                  },
                  "setting_up": {
                    "value": {
                      "ok": true,
                      "status": "setting_up",
                      "requestId": "ar_0123456789abcdef01234567",
                      "message": "We're setting up your account. We'll email you when it's ready."
                    }
                  },
                  "unavailable": {
                    "value": {
                      "ok": true,
                      "status": "unavailable",
                      "requestId": "ar_0123456789abcdef01234567",
                      "message": "This request could not be completed."
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "requestId or code is invalid"
          },
          "401": {
            "description": "That code is not valid, or that code is no longer valid"
          },
          "404": {
            "description": "Request not found"
          },
          "409": {
            "description": "Completed proof (usually code already_complete), rejected request, or verification conflict. Inspect the error; not every 409 is already_complete. A completed proof cannot return the key again. Poll the saved request; only after ready and if no usable key is saved, obtain a fresh challenge with request_access and verify_access_request. If no usable saved key exists: Once the account is ready, get the key with a fresh request_access plus verify_access_request. The key is shown once. \"Do NOT resend the same requestId\" applies only while the result is pending."
          },
          "410": {
            "description": "That code has expired"
          }
        }
      }
    },
    "/getRequestStatus": {
      "post": {
        "summary": "Check whether an account request is ready (no API key)",
        "description": "Public. Body is requestId and either email or username (contactEmail is accepted as email). Unknown email, unknown username, a real identity with the wrong requestId, an unknown requestId, an empty requestId, and a requestId that contains a slash all return HTTP 200 with the same body: ok true, status pending, ready false. A match also includes requestId. status is ready, setting_up, pending, or unavailable. ready is true only when the account is ready. Poll about every 20 minutes. get_request_status allows 10 per hour per IP and 6 per hour per email, counted separately from request_access, so that poll has room for an extra check. The same per-username limit applies when no email was set. The 429 body is the same whether or not the email or username is on file. This call does not return the key. Once the account is ready, get the key with a fresh request_access plus verify_access_request. The key is shown once. \"Do NOT resend the same requestId\" applies only while the result is pending. Same behavior as MCP get_request_status. ready describes account approval only, not key possession or mail delivery. unavailable is neutral and includes locked/rejected outcomes. No expired state is exposed; expired unverified requests can remain pending here while verification returns 410. No approval webhook is provided.",
        "security": [],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "requestId"
                ],
                "properties": {
                  "requestId": {
                    "type": "string"
                  },
                  "email": {
                    "type": "string",
                    "description": "contactEmail from request_access, when an email was set"
                  },
                  "username": {
                    "type": "string",
                    "description": "username from request_access, when no email was set"
                  }
                }
              },
              "example": {
                "requestId": "ar_0123456789abcdef01234567",
                "email": "ops@example-domain.com"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "A match includes requestId. The three negative cases share the pending example and do not echo requestId.",
            "content": {
              "application/json": {
                "examples": {
                  "unknown": {
                    "value": {
                      "ok": true,
                      "status": "pending",
                      "ready": false
                    }
                  },
                  "setting_up": {
                    "value": {
                      "ok": true,
                      "status": "setting_up",
                      "ready": false,
                      "requestId": "ar_0123456789abcdef01234567"
                    }
                  },
                  "ready": {
                    "value": {
                      "ok": true,
                      "status": "ready",
                      "ready": true,
                      "requestId": "ar_0123456789abcdef01234567"
                    }
                  }
                }
              }
            }
          },
          "429": {
            "description": "Rate limit exceeded. The body is the same whether or not the email is on file.",
            "content": {
              "application/json": {
                "example": {
                  "ok": false,
                  "error": "Rate limit exceeded",
                  "retryAfter": 3600
                }
              }
            }
          }
        }
      }
    },
    "/getAccountStatus": {
      "post": {
        "summary": "Read this key's own account",
        "description": "Account key only. The shared agent key is 403. The mail-server sync token is 401. A body that names another uid or email is 403. Returns status (ready, setting_up, or unavailable), accessLevel (standard or null), ready, domains with verification mx, spf, dkim, and dmarc (verified, missing, or unchecked), mailboxes (address, mode, ready), and canSend. When canSend is false, reason is a fixed next step and never includes a key or a DNS value. A hosted address needs a domain you own. Same behavior as MCP get_account_status. canSend checks account/domain/mailbox eligibility and does not wait for MTA sync, test delivery, credits or global sending switches. ready/status describe account approval. Mailbox ready describes send eligibility. Separate configurationProvisioning, serviceHealth, storageUsage and deliveryVerification fields report current evidence. get_mailbox_diagnostics(address) reads one existing owned mailbox without an onboarding ID. Legacy mtaApplied/mtaAppliedAt are receipt metadata, never current configuration or delivery proof. Inbound delivery remains not_tested.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": false,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {}
              },
              "example": {}
            }
          }
        },
        "responses": {
          "200": {
            "description": "This key's account. reason is omitted when canSend is true.",
            "content": {
              "application/json": {
                "examples": {
                  "needs_mailbox": {
                    "value": {
                      "ok": true,
                      "status": "ready",
                      "accessLevel": "standard",
                      "ready": true,
                      "domains": [
                        {
                          "name": "example-domain.com",
                          "status": "verified",
                          "verification": {
                            "mx": "verified",
                            "spf": "verified",
                            "dkim": "verified",
                            "dmarc": "unchecked"
                          }
                        }
                      ],
                      "mailboxes": [],
                      "canSend": false,
                      "reason": "Add a fully hosted mailbox on a verified domain before sending."
                    }
                  },
                  "can_send": {
                    "value": {
                      "ok": true,
                      "status": "ready",
                      "accessLevel": "standard",
                      "ready": true,
                      "domains": [
                        {
                          "name": "example-domain.com",
                          "status": "verified",
                          "verification": {
                            "mx": "verified",
                            "spf": "verified",
                            "dkim": "verified",
                            "dmarc": "verified"
                          }
                        }
                      ],
                      "mailboxes": [
                        {
                          "address": "support@example-domain.com",
                          "mode": "hosted",
                          "ready": true
                        }
                      ],
                      "canSend": true
                    }
                  }
                }
              }
            }
          },
          "401": {
            "description": "MTA sync token is not accepted here"
          },
          "403": {
            "description": "This action is limited to the account key, or this key can only read its own account."
          },
          "404": {
            "description": "Account not found"
          }
        }
      }
    },
    "/mcp": {
      "get": {
        "summary": "MCP discovery / health (no auth)",
        "responses": {
          "200": {
            "description": "Server info",
            "content": {
              "application/json": {
                "example": {
                  "ok": true,
                  "name": "mailservicenow",
                  "version": "0.8.0",
                  "transport": "json-rpc-2.0",
                  "protocolVersion": "2024-11-05",
                  "tools": [
                    "request_access",
                    "verify_access_request",
                    "get_request_status",
                    "get_account_status",
                    "get_mailbox_diagnostics",
                    "send_mail",
                    "get_credits",
                    "list_inbox",
                    "get_message",
                    "mark_read",
                    "list_domain_allowlist",
                    "add_domain_allowlist",
                    "remove_domain_allowlist",
                    "check_domain_allowlist",
                    "add_domain",
                    "list_domains",
                    "get_dns_instructions",
                    "verify_domain",
                    "operator_remove_domain",
                    "operator_delete_request",
                    "add_mailbox",
                    "issue_mailbox_credential",
                    "set_mailbox_mode",
                    "delete_mailbox",
                    "start_onboarding",
                    "get_onboarding_status",
                    "resume_onboarding",
                    "renew_onboarding_proof",
                    "search_mailbox",
                    "reply_to_message",
                    "reconcile_mailbox",
                    "get_mailbox_recovery"
                  ],
                  "auth": "Owner-approved OAuth at https://mailservicenow.com/api/mcp with exact domain/mailbox scopes; legacy customer/service keys remain supported for existing tools."
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "MCP JSON-RPC 2.0 (initialize, tools/list, tools/call)",
        "description": "Recommended scoped OAuth flow: /docs/agent-onboarding.md. start_onboarding(idempotencyKey,domain,localPart) returns a durable onboardingId for get_onboarding_status, resume_onboarding and renew_onboarding_proof. Customer-domain inbox list_inbox/get_message/search_mailbox/send_mail/reply_to_message require mailbox scopes and exact target binding. OAuth returns 401/403 transport challenges; credentials never appear in MCP results. DNS changes need independent owner authorization. Legacy behavior follows. Stateless HTTPS JSON-RPC. Not SSE. request_access, verify_access_request, and get_request_status need no API key. See /requestAccess, /verifyAccessRequest, and /getRequestStatus. get_account_status needs the account key and returns only that account. See /getAccountStatus. The shared agent key is refused on get_account_status. get_mailbox_diagnostics requires the same own-account standard key and an address; it is read-only and idempotent, requires no onboarding ID, and returns sanitized configuration revision/acknowledgement, recent service health, storage and next-action details. It does not send probes, resync, create onboarding or change mailbox settings. Scoped OAuth cannot call this diagnostic. Unknown and other-owner addresses both return 404. A standard-access customer key may call send, inbox, credits, domain and mailbox tools; webhooks use REST, and receives 403 on operator allowlist tools. Agent API key (Bearer or X-Api-Key) for send and inbox tools. add_mailbox, issue_mailbox_credential, set_mailbox_mode, and delete_mailbox accept a Firebase ID token once account setup is complete and refuse the shared agent key with Firebase sign-in required. Tools: send_mail (to, subject, text or html; sanitized HTML includes a plain-text alternative; combined input/output body limit 100KiB and encoded MIME limit 6MiB before credits; always set from to an address on a verified domain you own, for example support@example-domain.com; if from is omitted and the account has exactly one sendable hosted mailbox, that mailbox is used as a fallback; with more than one, omitting from is an error (400 Choose the address to send from); the shared agent key sends as noreply@mailservicenow.com; 1 credit; rate limits), get_credits (credits remaining), list_inbox (limit, mailbox), get_message (id or messageId), mark_read (id or messageId, optional unread boolean; no credit), add_mailbox (domainId, localPart, mode hosted|forward|both, forwardTo array max 5, optional password; hosted/both returns password once and clientSettings), issue_mailbox_credential (address, optional password; explicitly replaces the IMAP/SMTP password and returns it once, storing only a SHA512-CRYPT hash), set_mailbox_mode (same mode and forwardTo), delete_mailbox (address, or domain and localPart). delete_mailbox removes the mailbox record, does not delete Maildir, and returns a delivery removal with mtaApplied false. A protected address is not deleted (409). The last active mailbox on a verified domain is 409: This is the last mailbox on <domain>. Add another mailbox first, or contact support to remove the domain. Unverified domains are not affected. A missing mailbox is 404. A removed domain is 409 domain_removed: That domain was removed. Add it again if you still own it. The removed row is left unchanged. Mailbox tool output includes mode, forwardTo, and delivery. Forward-only has no IMAP login. More than 5 targets, a self-forward, or a forwarding loop is 400. The mail server syncs mailbox changes from mtaMailboxExport about every 60 seconds. mtaApplied and mtaAppliedAt are legacy receipt metadata only. Current configuration requires an exact revision-bound acknowledgement and a valid timestamp; service readiness additionally requires fresh successful sync/service health. SMTP acceptance, hosted storage delivery and forwarding remain not_tested until independently verified. Forward-only hosted storage is not_applicable. delete_mailbox drops routing on the next sync and keeps the Maildir. There is no force flag on delete_mailbox. Admins remove a domain, including its last mailbox, with operator_remove_domain (uid or ownerEmail, plus domainId; confirm is the domain name when any mailbox exists). The claim is released when it still names that account. mailservicenow.com is 409 system_domain. A missing account can still be removed and the audit row sets ownerMissing true. Mail stored for this domain is permanently deleted and cannot be recovered. A protected domain and any domain that contains a protected address are 409. Standard and request_access keys, the shared agent key, and the MTA token are refused on that tool. delete_mailbox does not release the claim. operator_delete_request is admin only. Pass id or ids (at most 200). It deletes those access requests, leaves the account and its key unchanged, writes one request.delete audit row per id, and clears that email's request rate counter. A customer key, the shared agent key, and the MTA token are refused. The call deletes the exact ids given and does not search for duplicates. REST is POST /api/admin/requestDelete. Preview is GET /api/admin/requestDuplicates with email and or domain. HTTP 401 on auth failure before any tool runs, including mark_read and send_mail, so a bad key does not spend a credit. Tool results for 402/404/409/410/429/503 use HTTP 200 with result.isError and structuredContent.status. Other failures use JSON-RPC error -32000. Methods: initialize, notifications/initialized, initialized, ping, tools/list, tools/call. initialize, tools/list, ping and public-only batches need no key. A protected tool in a batch requires auth for the entire batch. Discovery is not authorization. list_domains takes no arguments; get_dns_instructions and verify_domain require domainId and reject account overrides. These three require an active approved standard customer key and refuse Firebase, shared, MTA, revoked and unapproved credentials. get_dns_instructions returns instructions.records; verify_domain returns verified, transient, and checks. No DNS-provider changes occur. There is no public approval-decision tool. The full autonomous onboarding guide is /docs/mailservicenow-for-ai.md#agent-onboarding-sequence.",
        "security": [
          {},
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          },
          {
            "ScopedOAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/JsonRpcRequest"
              },
              "example": {
                "jsonrpc": "2.0",
                "id": 2,
                "method": "tools/call",
                "params": {
                  "name": "send_mail",
                  "arguments": {
                    "to": "recipient@example.com",
                    "from": "support@example-domain.com",
                    "subject": "Hello from MCP",
                    "text": "Sent via MailServiceNow MCP."
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "JSON-RPC response, or a tool error envelope. Check result.isError / structuredContent.ok. Auth failures are 401, not 200."
          },
          "204": {
            "description": "JSON-RPC notification acknowledged"
          },
          "401": {
            "description": "Missing or invalid credential for protected calls, revoked/inactive customer key, or unsupported caller for the selected tool. Bootstrap public methods need no key. Tool-level auth failures may be JSON-RPC error.data.status instead."
          },
          "405": {
            "description": "Method not allowed"
          }
        }
      }
    },
    "/api/account/team": {
      "servers": [
        {
          "url": "https://mailservicenow.com",
          "description": "Firebase Hosting route (not the Functions base URL)"
        }
      ],
      "get": {
        "tags": [
          "Account teams"
        ],
        "security": [
          {
            "FirebaseIdentity": []
          }
        ],
        "responses": {
          "200": {
            "description": "Success; private no-store response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "invitations": {
                      "type": "array",
                      "items": {
                        "type": "object",
                        "properties": {
                          "emailNotification": {
                            "type": "object",
                            "required": [
                              "status",
                              "attemptCount",
                              "retryAvailable",
                              "retryAfter",
                              "deliveryConfirmed"
                            ],
                            "properties": {
                              "status": {
                                "type": "string",
                                "enum": [
                                  "not_requested",
                                  "pending",
                                  "submitting",
                                  "submitted",
                                  "failed",
                                  "unknown"
                                ]
                              },
                              "attemptCount": {
                                "type": "integer",
                                "minimum": 0,
                                "maximum": 3
                              },
                              "retryAvailable": {
                                "type": "boolean"
                              },
                              "retryAfter": {
                                "type": "string",
                                "format": "date-time",
                                "nullable": true
                              },
                              "deliveryConfirmed": {
                                "type": "boolean",
                                "enum": [
                                  false
                                ]
                              },
                              "completedAt": {
                                "type": "string",
                                "format": "date-time"
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid fields or recipient unavailable"
          },
          "401": {
            "description": "Firebase sign-in required"
          },
          "403": {
            "description": "Account access or owner permission denied"
          },
          "409": {
            "description": "Stale invitation or unavailable ownership transfer"
          },
          "410": {
            "description": "Invitation expired"
          },
          "429": {
            "description": "Invitation rate or count limit"
          }
        },
        "summary": "List accessible customer accounts, invitations or a selected account team",
        "description": "Actor-level endpoint. Omit X-Account-Id. Recipient must already have a verified sign-in and completed account setup. GET without accountId returns accounts and incoming invitations; with accountId returns team details. Members see no pending invitations. Reads never send email. Member invitations include emailNotification status and explicit retry availability; SMTP acceptance never confirms inbox delivery. Ownership transfer is disabled.",
        "parameters": [
          {
            "name": "accountId",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "pattern": "^[A-Za-z0-9_-]{1,128}$"
            }
          }
        ]
      },
      "post": {
        "tags": [
          "Account teams"
        ],
        "security": [
          {
            "FirebaseIdentity": []
          }
        ],
        "responses": {
          "200": {
            "description": "Success; private no-store response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "invitation": {
                      "type": "object",
                      "properties": {
                        "emailNotification": {
                          "type": "object",
                          "required": [
                            "status",
                            "attemptCount",
                            "retryAvailable",
                            "retryAfter",
                            "deliveryConfirmed"
                          ],
                          "properties": {
                            "status": {
                              "type": "string",
                              "enum": [
                                "not_requested",
                                "pending",
                                "submitting",
                                "submitted",
                                "failed",
                                "unknown"
                              ]
                            },
                            "attemptCount": {
                              "type": "integer",
                              "minimum": 0,
                              "maximum": 3
                            },
                            "retryAvailable": {
                              "type": "boolean"
                            },
                            "retryAfter": {
                              "type": "string",
                              "format": "date-time",
                              "nullable": true
                            },
                            "deliveryConfirmed": {
                              "type": "boolean",
                              "enum": [
                                false
                              ]
                            },
                            "completedAt": {
                              "type": "string",
                              "format": "date-time"
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid fields or recipient unavailable"
          },
          "401": {
            "description": "Firebase sign-in required"
          },
          "403": {
            "description": "Account access or owner permission denied"
          },
          "409": {
            "description": "Stale invitation or unavailable ownership transfer"
          },
          "410": {
            "description": "Invitation expired"
          },
          "429": {
            "description": "Invitation rate/count limit, email cooldown or three-attempt email limit"
          },
          "503": {
            "description": "Invitation email sender is unavailable; existing invitation remains available"
          }
        },
        "summary": "Manage account-wide team membership",
        "description": "Owner-only invitations, revocation and removal; only the exact verified recipient may accept or decline. Members may read and send all account mail but cannot manage domains, credentials or team access. Invitations expire after seven days; removed members cannot replay them. No team-governance MCP tool exists. Transfer and new owner-key creation actions are disabled. Creation commits the invitation and email intent together, then attempts SMTP. Duplicate invite requests retain the same invitation and never retry a failed email. Owner-only retryInvitationEmail compares the current expectedAttemptCount before claiming a send, with a one-minute cooldown and three-attempt cap. Only pending, legacy not_requested, or proven-unsent failed notifications can be sent. Submitted, submitting, and unknown outcomes never replay; submitting older than two minutes displays unknown. No email failure removes the invitation.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "oneOf": [
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "action",
                      "accountId",
                      "email"
                    ],
                    "properties": {
                      "action": {
                        "type": "string",
                        "enum": [
                          "invite"
                        ]
                      },
                      "accountId": {
                        "type": "string"
                      },
                      "email": {
                        "type": "string",
                        "format": "email"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "action",
                      "invitationId"
                    ],
                    "properties": {
                      "action": {
                        "type": "string",
                        "enum": [
                          "acceptInvitation"
                        ]
                      },
                      "invitationId": {
                        "type": "string"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "action",
                      "invitationId"
                    ],
                    "properties": {
                      "action": {
                        "type": "string",
                        "enum": [
                          "declineInvitation"
                        ]
                      },
                      "invitationId": {
                        "type": "string"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "action",
                      "accountId",
                      "invitationId"
                    ],
                    "properties": {
                      "action": {
                        "type": "string",
                        "enum": [
                          "revokeInvitation"
                        ]
                      },
                      "accountId": {
                        "type": "string"
                      },
                      "invitationId": {
                        "type": "string"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "action",
                      "accountId",
                      "memberUid"
                    ],
                    "properties": {
                      "action": {
                        "type": "string",
                        "enum": [
                          "removeMember"
                        ]
                      },
                      "accountId": {
                        "type": "string"
                      },
                      "memberUid": {
                        "type": "string"
                      }
                    }
                  },
                  {
                    "type": "object",
                    "additionalProperties": false,
                    "required": [
                      "action",
                      "accountId",
                      "invitationId",
                      "expectedAttemptCount"
                    ],
                    "properties": {
                      "action": {
                        "type": "string",
                        "enum": [
                          "retryInvitationEmail"
                        ]
                      },
                      "accountId": {
                        "type": "string"
                      },
                      "invitationId": {
                        "type": "string"
                      },
                      "expectedAttemptCount": {
                        "type": "integer",
                        "minimum": 0,
                        "maximum": 3,
                        "description": "Use the current emailNotification.attemptCount from the invitation; replaying an old count cannot create another send."
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }
    },
    "/mailboxClientSettings": {
      "get": {
        "summary": "Read mailbox mail-app connection settings",
        "description": "Read-only, authorized hosted/both mailboxes. Optional exact address filter. No password is returned; current configuration acknowledgment is distinct from login verification. Standard customer credentials retain own-account scope; operators retain existing named product-domain permission gates.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "parameters": [
          {
            "in": "query",
            "name": "address",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Configured endpoints and per-mailbox credential metadata/readiness.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/MailboxClientSettings"
                }
              }
            }
          }
        }
      }
    },
    "/mailboxClientCredential": {
      "post": {
        "summary": "Explicitly set or reset a mailbox password",
        "description": "Authorized hosted/both mailbox only. Existing clients need the new password after the mail server applies it. Omit password for secure generation or supply a nonempty custom password up to 1024 UTF-8 bytes, without controls/line breaks or invalid Unicode. Weak values are accepted. Existing passwords cannot be recovered. Does not promise termination of existing authenticated sessions.",
        "security": [
          {
            "BearerAuth": []
          },
          {
            "ApiKeyAuth": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "address"
                ],
                "properties": {
                  "address": {
                    "type": "string"
                  },
                  "password": {
                    "type": "string",
                    "minLength": 1,
                    "writeOnly": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "New password returned once, with exact address/username and MailboxClientSettings fields. Only SHA512-CRYPT is persisted; custom hints are omitted. Latest configuration awaits acknowledgment."
          },
          "400": {
            "description": "Invalid password or address"
          },
          "403": {
            "description": "Mailbox is not authorized or not eligible for hosted access"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "BearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Standard customer API key msn_\u2026 for own-account operations, legacy shared service key for shared-mail tools, or a Firebase ID token on supported account/mailbox/operator routes. A three-part Bearer value is verified as a JWT. Public bootstrap requires no credential; MCP new domain tools and get_account_status require the customer key. Staff privileges require a verified Firebase token with the relevant role."
      },
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Api-Key",
        "description": "Agent API key msn_\u2026. When this header is present it is the only credential checked."
      },
      "ScopedOAuth": {
        "type": "oauth2",
        "flows": {
          "authorizationCode": {
            "authorizationUrl": "https://mailservicenow.com/oauth/authorize",
            "tokenUrl": "https://mailservicenow.com/oauth/token",
            "refreshUrl": "https://mailservicenow.com/oauth/token",
            "scopes": {
              "onboarding:manage": "Start, read and resume selected mailbox setup",
              "domain:read": "Read selected domain DNS instructions",
              "domain:verify": "Verify selected domain ownership and mail DNS",
              "mailbox:read": "Read selected inbox",
              "mailbox:search": "Search selected inbox",
              "mailbox:send": "Send from selected mailbox",
              "mailbox:reply": "Reply from selected mailbox"
            }
          }
        }
      },
      "FirebaseIdentity": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "Firebase ID token",
        "description": "Verified, active Firebase sign-in identity. Customer API keys and shared service keys are not accepted for team governance."
      }
    },
    "schemas": {
      "AccessRequest": {
        "type": "object",
        "required": [
          "domain",
          "agentName",
          "intendedUse"
        ],
        "properties": {
          "username": {
            "type": "string",
            "description": "Required when contactEmail is omitted. 3 to 64 characters: letters, digits, and . _ - + @."
          },
          "contactEmail": {
            "type": "string",
            "description": "Optional. When set, the 8-digit code is emailed here."
          },
          "domain": {
            "type": "string",
            "description": "Domain you control, such as example.com"
          },
          "agentName": {
            "type": "string"
          },
          "intendedUse": {
            "type": "string"
          }
        }
      },
      "AccessVerify": {
        "type": "object",
        "required": [
          "requestId"
        ],
        "properties": {
          "requestId": {
            "type": "string"
          },
          "code": {
            "type": "string",
            "description": "8 digit code from the email, when contactEmail was set"
          },
          "method": {
            "type": "string",
            "description": "dns after publishing the TXT record. Omit for the email code."
          }
        }
      },
      "Error": {
        "type": "object",
        "required": [
          "ok",
          "error"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              false
            ]
          },
          "error": {
            "type": "string"
          }
        }
      },
      "SendRequest": {
        "type": "object",
        "required": [
          "to",
          "subject"
        ],
        "anyOf": [
          {
            "required": [
              "text"
            ]
          },
          {
            "required": [
              "html"
            ]
          }
        ],
        "properties": {
          "to": {
            "description": "One address, a comma- or semicolon-separated string, or an array of addresses. Max 5.",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "array",
                "items": {
                  "type": "string"
                },
                "maxItems": 5
              }
            ]
          },
          "subject": {
            "type": "string"
          },
          "text": {
            "type": "string",
            "description": "Plain text; generated from html when omitted or blank. Combined text and html input/output bodies max 100KiB UTF-8."
          },
          "html": {
            "type": "string",
            "description": "Optional HTML. Sanitized semantic tags, tables, links and images; scripts, styles, forms, foreign content and unsafe URLs are removed. Only explicit HTTP/HTTPS/mailto links and HTTPS public-host images are retained; CID/data images are unsupported."
          },
          "from": {
            "type": "string",
            "description": "Always set from to an address on a verified domain you own, for example support@example-domain.com. If it's omitted and the account has exactly one sendable hosted mailbox, that mailbox is used as a fallback; with more than one, omitting from is an error (400 Choose the address to send from). The shared agent key sends as noreply@mailservicenow.com."
          },
          "inReplyTo": {
            "type": "string",
            "description": "Optional Message-ID to thread this send."
          },
          "references": {
            "description": "Optional References chain.",
            "oneOf": [
              {
                "type": "string"
              },
              {
                "type": "array",
                "items": {
                  "type": "string"
                }
              }
            ]
          },
          "attachments": {
            "type": "array",
            "maxItems": 3,
            "description": "Optional. Max 3 files, 2MB each, 4MB total decoded. MCP send_mail does not accept this field.",
            "items": {
              "$ref": "#/components/schemas/AttachmentUpload"
            }
          }
        }
      },
      "SendSuccess": {
        "type": "object",
        "required": [
          "ok",
          "messageId"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "messageId": {
            "type": "string"
          },
          "threadId": {
            "type": "string",
            "description": "Present when the send was filed onto a thread."
          },
          "attachmentCount": {
            "type": "integer",
            "description": "Files included on the SMTP message."
          },
          "attachmentsStored": {
            "type": "integer",
            "description": "Blobs stored for a threaded send. 0 when the send was not filed on a thread."
          },
          "creditsRemaining": {
            "type": "integer",
            "description": "Agent auth only."
          }
        }
      },
      "InboundSummary": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "messageId": {
            "type": "string"
          },
          "mailbox": {
            "type": "string"
          },
          "from": {
            "type": "string"
          },
          "to": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "subject": {
            "type": "string"
          },
          "preview": {
            "type": "string"
          },
          "date": {
            "type": "string",
            "nullable": true
          },
          "ingestedAt": {
            "type": "string",
            "nullable": true
          },
          "unread": {
            "type": "boolean"
          },
          "folder": {
            "type": "string",
            "enum": [
              "inbox",
              "archive",
              "trash"
            ],
            "description": "Missing stored folder is returned as inbox."
          },
          "source": {
            "type": "string"
          },
          "attachments": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/AttachmentMeta"
            }
          }
        }
      },
      "AttachmentUpload": {
        "type": "object",
        "required": [
          "filename",
          "contentBase64"
        ],
        "properties": {
          "filename": {
            "type": "string"
          },
          "contentType": {
            "type": "string"
          },
          "contentBase64": {
            "type": "string",
            "description": "Standard base64. Data URLs are accepted."
          }
        }
      },
      "AttachmentMeta": {
        "type": "object",
        "properties": {
          "index": {
            "type": "integer"
          },
          "filename": {
            "type": "string"
          },
          "contentType": {
            "type": "string"
          },
          "size": {
            "type": "integer"
          },
          "sha256": {
            "type": "string"
          },
          "preview": {
            "type": "string",
            "enum": [
              "image",
              "pdf",
              "text",
              "download"
            ]
          }
        }
      },
      "InboxList": {
        "type": "object",
        "required": [
          "ok",
          "messages",
          "unreadInPage"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "messages": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/InboundSummary"
            }
          },
          "unreadInPage": {
            "type": "integer"
          }
        }
      },
      "ThreadSummary": {
        "type": "object",
        "properties": {
          "threadId": {
            "type": "string"
          },
          "mailbox": {
            "type": "string"
          },
          "subject": {
            "type": "string"
          },
          "count": {
            "type": "integer"
          },
          "preview": {
            "type": "string"
          },
          "from": {
            "type": "string"
          },
          "latestAt": {
            "type": "string",
            "nullable": true
          },
          "unread": {
            "type": "boolean"
          },
          "unreadCount": {
            "type": "integer"
          },
          "folder": {
            "type": "string",
            "enum": [
              "inbox",
              "archive",
              "trash"
            ]
          }
        }
      },
      "ThreadList": {
        "type": "object",
        "required": [
          "ok",
          "threads",
          "unreadThreads"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "threads": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ThreadSummary"
            }
          },
          "unreadThreads": {
            "type": "integer",
            "description": "Unread threads in this page only."
          },
          "folder": {
            "type": "string",
            "enum": [
              "inbox",
              "archive",
              "trash"
            ]
          },
          "inboxUnread": {
            "type": "integer",
            "description": "Unread inbox threads among the newest 200 thread rows. Not limited to this page."
          }
        }
      },
      "MailboxStateRequest": {
        "type": "object",
        "properties": {
          "thread": {
            "type": "string",
            "pattern": "^[a-f0-9]{64}$"
          },
          "id": {
            "type": "string"
          },
          "messageId": {
            "type": "string"
          },
          "unread": {
            "type": "boolean"
          },
          "folder": {
            "type": "string",
            "enum": [
              "inbox",
              "archive",
              "trash"
            ]
          }
        }
      },
      "MailboxStateResult": {
        "type": "object",
        "required": [
          "ok"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "thread": {
            "$ref": "#/components/schemas/ThreadSummary"
          },
          "message": {
            "$ref": "#/components/schemas/InboundSummary"
          },
          "inboxUnread": {
            "type": "integer"
          }
        }
      },
      "ThreadDetail": {
        "type": "object",
        "required": [
          "ok",
          "thread",
          "messages"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "thread": {
            "$ref": "#/components/schemas/ThreadSummary"
          },
          "messages": {
            "type": "array",
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/InboundSummary"
                },
                {
                  "type": "object",
                  "properties": {
                    "text": {
                      "type": "string"
                    },
                    "direction": {
                      "type": "string",
                      "enum": [
                        "inbound",
                        "outbound"
                      ]
                    },
                    "inReplyTo": {
                      "type": "string"
                    },
                    "references": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                }
              ]
            }
          }
        }
      },
      "InboxOne": {
        "type": "object",
        "required": [
          "ok",
          "message"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "message": {
            "allOf": [
              {
                "$ref": "#/components/schemas/InboundSummary"
              },
              {
                "type": "object",
                "properties": {
                  "text": {
                    "type": "string"
                  },
                  "html": {
                    "type": "string",
                    "description": "Sanitized HTML when present. HTML-only mail receives a readable text fallback. Oversized expanded HTML is omitted in favor of bounded text."
                  }
                }
              }
            ]
          }
        }
      },
      "SearchHit": {
        "type": "object",
        "required": [
          "id",
          "direction",
          "matched",
          "snippet"
        ],
        "properties": {
          "id": {
            "type": "string",
            "description": "Firestore document id"
          },
          "direction": {
            "type": "string",
            "enum": [
              "inbound",
              "outbound"
            ]
          },
          "threadId": {
            "type": "string"
          },
          "messageId": {
            "type": "string"
          },
          "mailbox": {
            "type": "string"
          },
          "from": {
            "type": "string"
          },
          "subject": {
            "type": "string"
          },
          "snippet": {
            "type": "string"
          },
          "matched": {
            "type": "array",
            "items": {
              "type": "string",
              "enum": [
                "subject",
                "from",
                "body"
              ]
            }
          },
          "date": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "SearchResult": {
        "type": "object",
        "required": [
          "ok",
          "query",
          "hits"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "query": {
            "type": "string"
          },
          "scanned": {
            "type": "integer"
          },
          "hits": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/SearchHit"
            }
          }
        }
      },
      "Draft": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string"
          },
          "to": {
            "type": "string"
          },
          "subject": {
            "type": "string"
          },
          "text": {
            "type": "string",
            "description": "Optional user-written plain-text fallback; stays blank until send if omitted."
          },
          "html": {
            "type": "string",
            "description": "Sanitized HTML, or empty for a plaintext draft."
          },
          "inReplyTo": {
            "type": "string"
          },
          "references": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "nullable": true
          },
          "updatedAt": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "WebhookWrite": {
        "type": "object",
        "required": [
          "url"
        ],
        "properties": {
          "url": {
            "type": "string",
            "format": "uri",
            "description": "HTTPS endpoint. No credentials, fragment, or private host."
          },
          "enabled": {
            "type": "boolean"
          },
          "rotateSecret": {
            "type": "boolean"
          }
        }
      },
      "WebhookRegistration": {
        "type": "object",
        "required": [
          "ok"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "webhook": {
            "nullable": true,
            "type": "object",
            "properties": {
              "url": {
                "type": "string"
              },
              "enabled": {
                "type": "boolean"
              },
              "secret": {
                "type": "string",
                "description": "whsec_ HMAC key. Treat it like the agent API key."
              },
              "createdAt": {
                "type": "string",
                "nullable": true
              },
              "updatedAt": {
                "type": "string",
                "nullable": true
              }
            }
          }
        }
      },
      "MailboxDelivery": {
        "type": "object",
        "required": [
          "vmailbox",
          "virtualAlias"
        ],
        "description": "Postfix plan the mail server sync reads. The sync runs about every 60 seconds. hosted: vmailbox true and virtualAlias null. forward: vmailbox false and virtualAlias the forward targets. both: vmailbox true and virtualAlias the mailbox address followed by forwardTo.",
        "properties": {
          "vmailbox": {
            "type": "boolean"
          },
          "virtualAlias": {
            "type": "string",
            "nullable": true
          }
        }
      },
      "Mailbox": {
        "type": "object",
        "required": [
          "address",
          "mode",
          "forwardTo",
          "delivery"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "localPart": {
            "type": "string"
          },
          "address": {
            "type": "string"
          },
          "mode": {
            "type": "string",
            "enum": [
              "hosted",
              "forward",
              "both"
            ]
          },
          "forwardTo": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "string",
              "format": "email"
            },
            "description": "Empty for hosted. One to five addresses for forward and both."
          },
          "delivery": {
            "$ref": "#/components/schemas/MailboxDelivery"
          },
          "status": {
            "type": "string"
          },
          "mtaApplied": {
            "type": "boolean",
            "description": "True after the mail server sync confirms this mode. The sync runs about every 60 seconds."
          },
          "mtaAppliedAt": {
            "type": "string",
            "nullable": true,
            "format": "date-time",
            "description": "Timestamp of that confirmation. Null until mtaApplied is true."
          }
        }
      },
      "MailboxWrite": {
        "type": "object",
        "required": [
          "domainId",
          "localPart",
          "mode"
        ],
        "properties": {
          "domainId": {
            "type": "string"
          },
          "localPart": {
            "type": "string"
          },
          "password": {
            "type": "string",
            "minLength": 1,
            "writeOnly": true,
            "description": "Optional for hosted/both; omission generates a secure password. At most 1024 UTF-8 bytes, no controls/line breaks or invalid Unicode. Weak values are allowed. Forward-only rejects this field."
          },
          "mode": {
            "type": "string",
            "enum": [
              "hosted",
              "forward",
              "both"
            ]
          },
          "forwardTo": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "string"
            },
            "description": "Required for forward and both. Must be empty or omitted for hosted. A single string is accepted from older clients."
          }
        }
      },
      "MailboxModeWrite": {
        "type": "object",
        "required": [
          "domainId",
          "mode"
        ],
        "properties": {
          "domainId": {
            "type": "string"
          },
          "localPart": {
            "type": "string"
          },
          "mailboxId": {
            "type": "string",
            "description": "Used when localPart is omitted."
          },
          "mode": {
            "type": "string",
            "enum": [
              "hosted",
              "forward",
              "both"
            ]
          },
          "forwardTo": {
            "type": "array",
            "maxItems": 5,
            "items": {
              "type": "string"
            }
          }
        }
      },
      "MailboxResult": {
        "type": "object",
        "required": [
          "ok",
          "mailbox"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "mailbox": {
            "$ref": "#/components/schemas/Mailbox"
          },
          "password": {
            "type": "string",
            "readOnly": true,
            "description": "Hosted/both creation only. Returned once; never store in logs or browser storage."
          },
          "clientSettings": {
            "$ref": "#/components/schemas/MailboxClientSettings"
          }
        }
      },
      "MailboxClientSettings": {
        "type": "object",
        "properties": {
          "passwordSetupVersion": {
            "type": "integer",
            "enum": [
              1
            ],
            "description": "Clients require this capability before sending custom-password mutations."
          },
          "host": {
            "type": "string"
          },
          "ready": {
            "type": "boolean",
            "description": "Nonempty mailbox list, each with a credential and matching current configuration acknowledgement. Not proof of login."
          },
          "loginVerified": {
            "type": "boolean",
            "enum": [
              false
            ]
          },
          "imap": {
            "type": "object",
            "description": "Configured host, port 993, securityLabel SSL/TLS."
          },
          "smtp": {
            "type": "object",
            "description": "Configured host, port 587, securityLabel STARTTLS."
          },
          "mailboxes": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "address": {
                  "type": "string"
                },
                "username": {
                  "type": "string"
                },
                "credentialSet": {
                  "type": "boolean"
                },
                "ready": {
                  "type": "boolean"
                },
                "provisioningStatus": {
                  "type": "string",
                  "enum": [
                    "pending",
                    "applied"
                  ]
                },
                "provisioningAppliedAt": {
                  "type": "string",
                  "nullable": true
                },
                "loginVerified": {
                  "type": "boolean",
                  "enum": [
                    false
                  ]
                }
              }
            }
          }
        }
      },
      "MailboxDelete": {
        "type": "object",
        "description": "Provide address, or domain (or domainId) plus localPart (or mailboxId).",
        "properties": {
          "address": {
            "type": "string",
            "description": "Full mailbox address."
          },
          "domain": {
            "type": "string"
          },
          "domainId": {
            "type": "string"
          },
          "localPart": {
            "type": "string"
          },
          "mailboxId": {
            "type": "string"
          }
        }
      },
      "MailboxDeleteResult": {
        "type": "object",
        "required": [
          "ok",
          "deleted",
          "mailbox"
        ],
        "properties": {
          "ok": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "deleted": {
            "type": "boolean",
            "enum": [
              true
            ]
          },
          "mailbox": {
            "type": "object",
            "required": [
              "address",
              "removed",
              "delivery",
              "mtaApplied",
              "maildir"
            ],
            "properties": {
              "id": {
                "type": "string"
              },
              "localPart": {
                "type": "string"
              },
              "address": {
                "type": "string"
              },
              "domain": {
                "type": "string"
              },
              "removed": {
                "type": "boolean",
                "enum": [
                  true
                ]
              },
              "previousMode": {
                "type": "string",
                "enum": [
                  "hosted",
                  "forward",
                  "both"
                ]
              },
              "delivery": {
                "type": "object",
                "description": "Removal plan for the next mail server sync. vmailbox false and virtualAlias null drop the address from both maps. Routing drops about every 60 seconds. The Maildir is kept.",
                "required": [
                  "vmailbox",
                  "virtualAlias"
                ],
                "properties": {
                  "vmailbox": {
                    "type": "boolean",
                    "enum": [
                      false
                    ]
                  },
                  "virtualAlias": {
                    "type": "string",
                    "nullable": true
                  }
                }
              },
              "mtaApplied": {
                "type": "boolean",
                "enum": [
                  false
                ]
              },
              "maildir": {
                "type": "string",
                "enum": [
                  "leave"
                ],
                "description": "Mail already stored on the server is not deleted."
              },
              "updatedAt": {
                "type": "string",
                "format": "date-time"
              }
            }
          }
        }
      },
      "DomainList": {
        "type": "object",
        "required": [
          "ok",
          "domains"
        ],
        "properties": {
          "ok": {
            "type": "boolean"
          },
          "domains": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "status": {
                  "type": "string"
                },
                "mailboxes": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/Mailbox"
                  }
                }
              }
            }
          }
        }
      },
      "JsonRpcRequest": {
        "type": "object",
        "required": [
          "jsonrpc",
          "method"
        ],
        "properties": {
          "jsonrpc": {
            "type": "string",
            "enum": [
              "2.0"
            ]
          },
          "id": {},
          "method": {
            "type": "string"
          },
          "params": {
            "type": "object"
          }
        }
      }
    }
  }
}
