Skip to content

Architecture

icloud-mcp is one stdio MCP server for Apple/iCloud Calendar, Contacts, Mail, and, on macOS only, Reminders. Any MCP-compatible host can run it as a child process. It uses JSON-RPC on stdin and stdout. It reads configuration only from the process environment. The build produces one release artifact.

The server does not embed or prefer a model vendor or agent product. Every domain capability is composable: Calendar, Contacts, Mail read, Mail mutation, Mail send, and Reminders. A domain is registered only when the effective configuration grants at least one of its capabilities.

The protocol boundary is narrow:

  • Calendar uses CalDAV over HTTPS.
  • Contacts uses CardDAV over HTTPS.
  • Mail reads and mutations use IMAP over implicit TLS.
  • Mail send uses authenticated SMTP submission with mandatory STARTTLS.
  • Reminders, on macOS only, use one local Unix socket to a separate signed helper app. The helper owns EventKit and the macOS privacy grant.

The server does not use a private Apple API or browser automation. The Go process does not link a local Apple framework or read a synced database. Its only external executables are darwin-only: /usr/bin/open starts the Reminders helper, /usr/bin/codesign checks the helper signature, and /usr/bin/getconf returns the private per-user temporary directory. It does not use a plugin or runtime-downloaded code.

  1. config.Load reads and validates the 17 environment variables. It resolves boot-only file:// identity and password values.

  2. Each secret file must be a regular file of 4 KiB or less. Its mode must be 0600 or stricter.

  3. Configuration failure occurs before network access. When configuration requests send, the literal SMTP recipient policy * is valid.

  4. This policy writes a boot warning to stderr.

  5. The server builds a shared security.Redactor from the enabled credential pairs. The variants include Basic-auth and SASL PLAIN encodings.

  6. RedactingWriter receives all stderr and standard library logs.

  7. One immutable CapabilityPlan applies global read-only, the optional domain gates, and ICLOUD_MCP_PERMISSIONS. It is the source of tool registration, icloud_capabilities output, and the initialize instructions. ICLOUD_MCP_RESOURCE_SCOPES is a separate immutable allowlist checked in each domain operation path.

    • ICLOUD_MCP_PERMISSIONS alone selects the domains. When it is set, only the domains whose tokens appear in it are built and registered. Calendar is not special: a Mail-only or Contacts-only list omits every Calendar tool.
    • The initialize instructions come from the same plan. They name only the domain tool groups that this process registered, route the host to tools/list and icloud_capabilities for the exact surface, state global read-only when it applies, and keep the untrusted-content rule. They carry no identity, mailbox, recipient, host, or resource path. No domain is described as always available.
  8. The server builds separate Calendar, Contacts, IMAP, and SMTP transports or dialers only for enabled capabilities. Calendar and Contacts receive separate credential objects and authenticated HTTP clients.

  9. Calendar makes no boot network access. Its first call runs bounded two-step CalDAV discovery. A failure affects only that domain and is retried on a later call. Successful discovery state is immutable.

  10. Contacts makes no boot network access. Its first call starts discovery through a concurrency-safe gate with a 10 second attempt deadline.

  11. Contacts caches only a complete, validated discovery. It does not cache a failure.

  12. Mail makes no boot network access. Each attempt creates and closes a new authenticated protocol session.

  13. A transient Mail read can use one replacement session. Mutations and SMTP never retry.

  14. Reminders make no boot helper start. The first Reminders tool call or icloud_capabilities starts the helper. A non-darwin build reports the domain unavailable with reason not_darwin.

  15. The finalized plan registers the MCP handlers. The optional loopback-only -health endpoint starts next.

  16. Then, ServeStdio controls stdin and stdout.

EOF cancels active handlers before the server waits for its workers. EOF and SIGTERM are normal shutdown conditions. Terminal input failures, including an oversized frame, remain errors even when cancellation interrupts the reader.

After boot, a Calendar, Contacts, IMAP, or SMTP failure affects only that tool call. It does not unregister tools or change another domain client. It also does not change a successful discovery cache.

Package Role
cmd/icloud-mcp Configuration wiring, independent domain construction, capability plan, timeouts, stdio
internal/config Strict booleans, environment validation, file:// secrets (0600+, 4 KiB), Mail recipient policy
internal/security DAV and socket allowlists, TLS policy, redaction, process-local audit tokens
internal/icloud Calendar CalDAV, iCalendar, recurrence, free slots, and validation.
Calendar retry/rate policy; per-calendar materialization 2,500; multi-calendar materialization 10,000; imported-UID REPORT +/-50y.
internal/contacts Lazy CardDAV discovery, bounded DAV/XML, vCard model, search, conditional writes
internal/mail Mail service, MIME handling, IMAP mutation policy, SMTP submission
internal/mail/imapadapter Narrow beta go-imap boundary and decode-time protocol guard
internal/mcptools Compositional schemas, handlers, capability reporting, redacted results, mutation audit
internal/reminders Helper protocol v1 client, strict response decoder, darwin launcher and peer checks (launcher_darwin.go, peer_darwin.go), and a non-darwin stub
helper/reminders Swift package of the IcloudMcpReminders.app helper: socket server, EventKit store, serialized writes; built by scripts/build-reminders-helper.sh
internal/health Optional loopback-only /healthz and /status with version, domain enablement, and multi-domain rate limits

internal/icloud keeps its historical name but contains only Calendar code. Shared code can provide redaction, audit formatting, result sizing, and limiter primitives. It does not own an authenticated client for multiple domains.

The following table groups the complete surface:

Capability group Read/local tools Mutation tools
Global icloud_capabilities none
Calendar list_calendars, search_events, get_event, find_free_slots, validate_event, calendar_capabilities create_event, update_event, delete_event
Contacts list_address_books, search_contacts, get_contact create_contact, update_contact, delete_contact
Mail read list_mailboxes, search_messages, get_message none
Mail mutation none set_message_flags, move_message, trash_message
Mail send none send_message, reply_message
Mail attachments get_attachment attachment references on send_message and reply_message
Mail drafts none stage_attachment, create_draft
Reminders list_reminder_lists, search_reminders, get_reminder create_reminder, update_reminder, delete_reminder

Default registration has seven tools: six Calendar read tools and the global capability tool. An explicit operator profile enables all 33 tools. The legacy switches reach at most 24 tools, because no switch grants the attachment and draft tokens. Disabled tools have no handler. Disabled optional domains have no client.

The same immutable registration plan generates the local icloud_capabilities result. It reports the version, global read-only state, healthcheck state, configured domains, and effective capability groups. It also reports sorted tool names and the count.

The result contains no identity, secret, host, shard, path, mailbox, recipient, or runtime error. calendar_capabilities contains only Calendar data.

The server exposes at most 33 tools. Disabled tools are absent from tools/list. A disabled optional domain has no client.

Group Tools
Global icloud_capabilities
Calendar read list_calendars, search_events, get_event, find_free_slots, validate_event, calendar_capabilities
Calendar write create_event, update_event, delete_event
Contacts read list_address_books, search_contacts, get_contact
Contacts write create_contact, update_contact, delete_contact
Mail read list_mailboxes, search_messages, get_message
Mail mutation set_message_flags, move_message, trash_message
Mail send send_message, reply_message
Mail attachments get_attachment
Mail drafts stage_attachment, create_draft
Reminders read list_reminder_lists, search_reminders, get_reminder
Reminders write create_reminder, update_reminder
Reminders delete delete_reminder

The default surface has seven read-only tools. The complete surface has exactly 33 tools with explicit permissions and domain gates.

tool -> 25s context -> Calendar read/write limiter -> 4/2 semaphore -> retry policy
-> Calendar Basic-auth client -> Calendar allowlist -> verified HTTPS

Calendar discovery is lazy. A successful discovery state is immutable. Reads have bounded service retries. The HTTP classifier retries 429, 502, 503, and 504. It uses bounded Retry-After or backoff and rewinds read request bodies. It does not retry transport errors.

The client never repeats PUT, DELETE, or full-series delete. A transport failure after mutation dispatch maps to outcome_unknown. Gateway 502, 503, and 504 have the same result. Update and delete read the full object again and use conditional requests.

Multi-calendar search_events queries each selected calendar. It then sorts the events and applies the fair 400-event result limit. Every search row includes the validated calendar path, so callers can pass it to get_event or update_event without resolving the UID again. More than 10,000 filtered materialized events cause payload_too_large. The per-calendar REPORT materialization limit is 2,500. When <uid>.ics is missing, imported-UID REPORT fallback uses a 50-year window on each side of now.

search_events can opt into bounded continuation with cursor="start". The initial marker is not a token. Later pages use a signed, stateless token that binds the query, explicit calendars, filters, and read scope. The token expires after 300 seconds and is valid only for the handler registration that signed it. Cursor mode uses strict keyset ordering and collapses exact duplicate rows only in that opt-in path. A call without cursor keeps the legacy ordering, duplicates, offset window, and no nextCursor.

The first cursor page performs one normal bounded fetch in waves of at most four calendars. It keeps one wave of backend results alive, applies the 2,500 per-calendar limit and the 10,000 filtered materialized budget during the merge, and stops scheduling waves after a definitive overflow. It also keeps the 256 KiB serialized result and all recurrence and deadline limits. The completed scan is retained in process memory for at most 300 seconds, in at most four generation-scoped snapshots and at most 32 MiB of row text. Later pages of the same generation read that snapshot without another backend fetch. There is no background worker, disk store, or cross-process cache. A snapshot is never written to logs.

Every completed scan gets an unpredictable process-local generation ID. The signed token binds that generation, the semantic query, and the last-row identity. A repeated cursor=start for the same query stores a new generation without rebinding existing tokens. An expired or evicted generation returns stale_cursor; it never continues inside a newer scan. The serializer reserves room for the token and metadata before it selects the last emitted row. Incomplete results suppress the continuation. total is the snapshot count for that generation.

find_free_slots filters calendar scopes before reads or event accounting. It accepts at most 10,000 returned events, including duplicates, transparent events, and all-day events excluded from busy time. Explicit and implicit selections share this budget. Overflow returns payload_too_large without slots and advises narrowing the range or calendars.

An availability-specific collector reads ordered waves of at most four calendars. It joins each wave, checks batches in selection order, and stops before another wave on failure. This preserves deterministic errors without changing search_events fairness. The domain-wide read limiter and four-read semaphore remain in effect.

The accumulator has a fixed capacity of 10,000 event records, allocated only for nonempty results. The collector retains at most four additional returned batches and four read workers. Each production search returns at most 2,500 records. Returned slice capacities can exceed their lengths. Batch references are cleared before the next wave. Cancellation joins the active reads before return. Cleanup depends on the service context and existing transport deadlines; no detached workers remain.

These event counts are not an exact byte or RSS bound. REPORT bodies, parser state, recurrence temporaries, and batch backing arrays retain their separate client limits. Discovery and permitted path metadata still scale with calendar count. Concurrent MCP calls each own a collector, while the domain semaphore bounds active client reads.

Busy interval conversion starts only after complete collection and processes at most 10,000 records. Time buffers extend the query and pad intervals; they do not expand the event budget. Existing buffered-range and recurrence limits remain unchanged. Any incomplete search fails without availability.

tool -> 25s context -> lazy discovery -> Contacts read/write limiter
-> 4-request semaphore -> Contacts Basic-auth client
-> Contacts allowlist -> verified HTTPS

Discovery resolves current-user-principal and one or more address-book home sets. It also resolves at most 100 books. Opaque book identifiers refer to fixed, validated collection URLs. Reads can retry bounded HTTP status failures. The client never repeats PUT or DELETE. Transport ambiguity maps to outcome_unknown.

Contact search uses CardDAV text predicates as a bounded prefilter when their meaning matches. A general query uses any-of FN/N/EMAIL/TEL/ORG. Without a general query, email uses EMAIL. The client then combines each query, email, phone, and group condition locally.

Phone matching normalizes digits. Thus, a phone-only search uses a bounded all-card VERSION-presence query instead of a server TEL predicate.

tool -> 25s context -> resource scope -> Reminders client
-> launcher (once per helper) -> socket file, peer uid, and signature checks
-> one request per connection over a Unix socket -> helper -> EventKit

The helper app IcloudMcpReminders.app holds the macOS Reminders grant. The Go process never links EventKit. It starts the helper with /usr/bin/open, so macOS charges the privacy grant to the helper bundle. The socket and token live in <user temp dir>/icloud-mcp-reminders-<uid>/, mode 0700, with new random names for each launch, so each server process has its own helper. Before it sends the token, the client checks the socket owner and mode, the peer uid, and the peer code signature against the designated requirement. The helper checks the peer uid, the client code signature from the peer audit token, and then the token. Requests are at most 64 KiB, replies at most 1 MiB. A refused connection or a bad_token reply means that the helper did not run the request, so the client starts a new helper and sends the request once more. A create, update, or delete that loses its reply after dispatch returns outcome_unknown and is never repeated.

Update and delete need if_last_modified. The helper runs every create, update, and delete on one serial queue, and refuses a second write while one runs (busy). It reads the item from a new EventKit store, compares last_modified, and saves. After an update it compares the saved title, notes, and url with the request. A difference means that EventKit merged another write into the save: the result is conflict and the item stays as EventKit stored it. Two helper processes or another app can still race. See Reminders.

With a restricted write or delete scope, update and delete read the reminder first. A reminder in a list outside the scope never reaches the mutation.

tool -> 25s context -> Mail limiter/semaphore -> fixed IMAP dial
-> verified implicit TLS -> login -> LIST or SELECT -> bounded commands
-> logout/close

Read operations use EXAMINE and PEEK. Search scans bounded descending UID windows. Each read asks for one FETCH projection: summary for search, reply headers for reply, and the full message with BODYSTRUCTURE for message retrieval. Only the full projection processes the MIME tree. A guarded connection applies the 4 MiB inbound session limit. It also limits protocol nesting and lists before go-imap creates a recursive BODYSTRUCTURE.

A guarded STORE also needs the tagged status line of its own command, because go-imap discards a tagged OK response code. The same guard scan reports the completed protocol lines of that one command to a bounded observer. The observer binds the tag of the outbound STORE line and reads only the tagged status, so no other command response is evidence and no wire limit changes.

Mutation sessions select the source mailbox for read and write. They compare UIDVALIDITY before mutation. Only one mutation runs at a time. The client never retries a mutation command automatically.

tool -> local input/recipient/message validation -> 25s context
-> send limiter/semaphore -> smtp.mail.me.com:587 -> EHLO
-> mandatory STARTTLS -> verified TLS -> EHLO -> AUTH
-> MAIL FROM -> every RCPT TO -> DATA only if all recipients succeeded

The client builds the encoded message in bounded memory before connection. From is the configured Mail address. to, cc, and bcc are individually optional. Together, they must contain at least one recipient. Bcc exists only in the envelope. The client keeps no SMTP session and retries no stage.

MCP handlers can run concurrently. The server limits and protects this shared mutable state:

  • Calendar successful discovery state, independent rate buckets, and 4/2 read/write semaphores.
  • Contacts successful lazy-discovery state, independent rate buckets, and a four-request semaphore.
  • Mail independent read/mutation/send buckets and 2/1/1 semaphores.
  • Process-local keyed audit token material.
  • Tool-namespaced idempotency entries shared by Calendar and Contacts updates.
  • The Reminders client endpoint and token, and one verified helper process. The helper serializes its writes and serves at most 16 connections at the same time.

The server has no selected-mailbox state, Mail connection pool, or SMTP session. Read operations have no result cache across calls. Keyed updates keep bounded result text in memory under the contract below.

  • Calendar and Contacts expose ETags. Update and delete send a full GET and require a usable, strong server ETag.
  • They always send a specific If-Match. A caller ETag can make the precondition stronger. Create uses If-None-Match: *.
  • A Mail message reference is (mailbox, UIDVALIDITY, UID). Get and mutation compare UIDVALIDITY after selecting the mailbox. Search cursors pair before_uid with the preceding page’s UIDVALIDITY.
  • Reads expose MODSEQ when CONDSTORE is available. The adapter observes the tagged status of the guarded STORE it sent, so it detects MODIFIED.
  • Thus, a conditional flag mutation keeps its atomic precondition. A tagged MODIFIED for this UID returns concurrent_modification. A dispatched but unverifiable STORE returns outcome_unknown, never a success.
  • The capability flag reports true only for a guarded session on a CONDSTORE server. No path falls back to an unconditional STORE.
  • Reminders expose last_modified, an RFC 3339 UTC timestamp with exactly millisecond precision. Update and delete send it as if_last_modified, and the helper compares the exact string.

Only update_event and update_contact use this result cache when the caller supplies idempotency_key. Create tools use resource UIDs for conflict detection. They do not use this cache.

Each entry identifies a tool, a key, and a SHA-256 hash of parsed update parameters. Parameters include the resource identity, changed fields, and etag. Calendar scope and recurrence_id also participate. Tool namespaces prevent a Calendar key from matching a Contacts key.

The first valid request owns a pending claim. Concurrent calls with the same key and parameters wait for that owner. Different parameters return conflict, even while the owner is pending. Cancellation or timeout ends only the waiting call. It does not release the owner’s claim or permit another write.

Entry state Lifetime
Pending claim No expiry while the process runs
Success or definitive domain error 15 minutes after the request completes
outcome_unknown, unclassified error, or internal_error Until process exit
Response serialization or result-size error after a successful write Until process exit
Interrupted handler or result that cannot be recorded Bounded outcome_unknown result until process exit

The server saves result text and the MCP IsError flag. Cache hits return the saved result through the domain writer, which applies redaction and result limits again. A cache hit does not extend the expiry interval. Local validation failures before a claim do not create an entry.

The cache has a shared limit of 1,024 entries and a 256 KiB payload limit per entry. Expired known results free capacity. Pending and uncertain entries are not removed to make space. A full cache returns conflict for a new claim before it calls the service. Existing entries can still return their saved results.

All entries exist only in process memory. Another process cannot use them. Process exit removes every entry. After expiry or restart, the same key can start a new write. Neither condition proves that the previous write failed. Before choosing a new key after an ambiguous result, use get_event or get_contact to reconcile the resource.

See error recovery for caller procedures, including full-cache conflicts.

Calendar text, contact data, and Mail content are untrusted. The stdio reader accepts at most 1 MiB in each JSON-RPC frame. Protocol errors can reflect caller input. The server passes them through only up to 64 KiB. It replaces larger records with bounded local errors. Each serialized MCP result, including Calendar, has a 256 KiB limit.

mcp-go checks the input schema before any middleware or handler. Its refusal text can repeat caller values. mcptools.ConfigureSchemaRefusals adds an OnAfterCallTool hook that rewrites this refusal into the validation payload before the response is written. It caches each compiled schema by tool name and schema digest. For raw arguments above 64 KiB, it skips the second validation and names only missing and unknown arguments.

The function puts its hook first among the OnAfterCallTool hooks. mcp-go runs OnSuccess hooks before them, so do not add an OnSuccess hook that reads tool results. A test fails if the production server registers one.

Search tools return summary models. Contact results exclude PHOTO and raw vCard. Mail results exclude raw MIME, raw headers, HTML, and attachment bodies.

Calendar REPORT XML has depth 32 and 262,144-token limits. It also has response and property item limits. iCalendar limits components, properties, parameters, overrides, alarms, and EXDATE values.

Contact DAV XML has depth 32 and 100,000-token limits. It also limits propstats and properties. Each vCard has a 10,000-property limit.

Calendar recurrence expansion returns at most 2,000 occurrences. Its iterator advances at most 100,000 times for each series.

IMAP limits protocol nesting and list counts before recursive decode. It limits modeled MIME parts and depth after decode. SMTP accepts at most 1 MiB of inbound responses in each session.

Area Limits
Tool deadline 25 s (DAV HTTP 30 s)
Stdio / MCP result 1 MiB frame. 256 KiB result. Reflected protocol errors have a 64 KiB limit.
Calendar Search range: 366 days. Results: 400 total, 2,500 per calendar, and 10,000 materialized across calendars. Recurrence: 2,000 expansions, 100k steps per series, and 250k steps per search. Rate: 60 reads and 20 writes per minute. Concurrency: 4 reads and 2 writes.
Contacts 100 books. 100 summaries. 2000 cards scanned. Rate: 60 reads and 20 writes per minute. Concurrency: 4.
Mail Rate: 60 reads, 20 mutations, and 20 sends per minute. Semaphores: 2 reads, 1 mutation, and 1 send. No mutation or send retry.
Reminders 500 lists. Search: 200 results (default 50), 50 list ids, 256-byte text, 366-day due range. Title 1,024 bytes, notes 32 KiB, url 2,048 bytes. Helper request 64 KiB, reply 1 MiB, exchange 15 s, EventKit work 10 s, idle exit 60 s. No rate limiter: no network request leaves the Mac.
Writes No automatic replay of Calendar PUT/DELETE, Contacts writes, IMAP mutations, SMTP, or Reminders writes after dispatch. Ambiguous outcomes use outcome_unknown.

The server discovers Calendar and Contacts when first used in each domain. Each Mail call uses a fresh IMAP or SMTP session.

Use Go 1.26.0 or newer. The project has one module and exactly 13 direct requirements, and all are runtime dependencies. If you add a direct dependency, add its justification here.

Dependency Exact version Justification
github.com/emersion/go-webdav v0.8.0 CalDAV primitives. Discovery and conditional operations remain hand-written.
github.com/emersion/go-ical v0.0.0-20261112170022-46c5b53a1723 iCalendar parse/encode
github.com/mark3labs/mcp-go v1.7.0 MCP stdio, schemas, JSON-RPC
github.com/teambition/rrule-go v1.8.2 Bounded recurrence with timezone preservation
golang.org/x/time v0.16.0 Per-domain rate limiters
github.com/emersion/go-vcard v0.1.0 vCard 3.0/4.0 read, 3.0 write
github.com/emersion/go-imap/v2 v2.0.0-beta.9 IMAP behind internal/mail/imapadapter
github.com/emersion/go-message v0.18.2 MIME / plain-text bounds
github.com/emersion/go-smtp v0.26.0 SMTP + STARTTLS
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 SASL PLAIN after STARTTLS
golang.org/x/text v0.44.0 RFC 5051-compatible Unicode collation for local Contacts matching
golang.org/x/sys v0.50.0 Darwin socket peer credentials (LOCAL_PEERCRED, LOCAL_PEERPID) and process start time for the Reminders helper check. New in the build, linked into the macOS binary only.
github.com/santhosh-tekuri/jsonschema/v6 v6.0.3 Names the failed arguments of an input schema refusal. Tests check published schemas and actual outputs. The MCP SDK already links it.

Calendar uses custom discovery, iCloud-compatible REPORT, and conditional PUT or DELETE code. go-webdav FindCalendarHomeSet loses shard authority during discovery. v0.7.0 also lacked the required conditional write API. v0.8.0 adds If-Match options, but the tested hand-written requests remain. Calendar update always gets the full object before PUT. Thus, VERSION, PRODID, and VTIMEZONE remain.

Contacts uses custom bounded PROPFIND, REPORT, GET, PUT, and DELETE code. It also uses custom href resolution, redirects, and XML decoding. Resource hrefs are arbitrary. The client never derives them from a contact UID.

Each production Calendar, Contacts, IMAP, SMTP, and Reminders mutation writes the same safe fields. They are tool, domain, resourceType, process-local opaque HMAC resourceToken, and status.

Calendar hashes its path/UID tuple before logging. Production audit records contain no raw Calendar path or UID. They also contain no raw contact UID, mailbox/UIDVALIDITY/UID tuple, or recipient.

Production startup and the fixture-only executable use shared MCP registration and bounded stdio startup code. The fixture executable is compiled from cmd/icloud-mcp tests with synthetic services. It checks initialization, capability registration, denied writes, frame limits, cancellation, domain failure isolation, and shutdown. These fixtures do not change production destination policies.

The external scripts/protocol_evidence.py runner also selects ^TestProtocol scenarios in internal/mcptools. Idempotency scenarios use stateful service fixtures. Recurrence scenarios use a local TLS DAV fixture and the Calendar client. These checks do not establish live iCloud compatibility.

The runner saves transcripts, commands, environment metadata, source revision, working diff, fixture SHA-256 values, and results outside the repository. See Testing for commands and artifact details.

See CalDAV compatibility, CardDAV compatibility, Mail compatibility, and security.