Skip to main content
Glama
jons-mcp-imessage
by jonmmease

jons-mcp-imessage

A local MCP server for querying and sending iMessages on macOS.

This FastMCP server exposes tools through the Model Context Protocol (MCP), enabling AI assistants to read your iMessage history and send messages.

Requirements

  • macOS (tested on Tahoe 26.x, should work on recent versions)

  • Python 3.10+

  • Messages.app (for sending messages)

Related MCP server: iMessage RAG MCP

Permissions Required

This server requires specific macOS permissions to function. Permission issues are the most common cause of problems.

Full Disk Access (Required for Reading Messages)

The application running this server needs Full Disk Access to read ~/Library/Messages/chat.db.

To grant Full Disk Access:

  1. Open System Settings (or System Preferences on older macOS)

  2. Navigate to Privacy & Security → Full Disk Access

  3. Click the lock icon and authenticate if needed

  4. Click the + button

  5. Add the appropriate application:

    • If using Claude Desktop: Add Claude.app (usually in /Applications)

    • If running from terminal: Add your terminal app (e.g., Terminal.app, iTerm.app, Zed.app)

    • If running via another app: Add that specific application

  6. Restart the application after granting access

How to verify: Run check_permissions tool - it will report whether database access is working.

Automation Permission (Required for Sending Messages)

To send messages via AppleScript, the application needs permission to control Messages.app.

This permission is prompted automatically the first time you try to send a message. Click "OK" to allow.

To manually grant or verify:

  1. Open System Settings → Privacy & Security → Automation

  2. Find your application (Terminal, Claude Desktop, etc.)

  3. Ensure Messages is checked

Contacts Permission (Optional - For Contact Name Enrichment)

The server can enrich message responses with contact names from your Contacts app. This is optional - all features work without it, but you'll see phone numbers/emails instead of names.

To enable contact name enrichment:

  1. Open System Settings (or System Preferences on older macOS)

  2. Navigate to Privacy & Security → Contacts

  3. Click the lock icon and authenticate if needed

  4. Click the + button

  5. Add the appropriate application:

    • If using Claude Desktop: Add Claude.app (usually in /Applications)

    • If running from terminal: Add your terminal app (e.g., Terminal.app, iTerm.app)

  6. Restart the application after granting access

What you get with Contacts permission:

  • Message responses include contact_name field (e.g., "John Smith" instead of just "+15551234567")

  • Conversation responses include participant_names field

  • lookup_contact tool becomes available for explicit contact lookups

Without Contacts permission:

  • Contact name fields will be null

  • lookup_contact returns an error message

  • All other functionality works normally (graceful degradation)

Installation

# Clone the repository
git clone <your-repo-url>
cd jons-mcp-imessage

# Install with uv
uv pip install -e .

Running the Server

uv run jons-mcp-imessage

Adding to Claude Code

# Register the MCP server with Claude Code
claude mcp add jons-mcp-imessage -- uv run --directory /path/to/jons-mcp-imessage jons-mcp-imessage

Adding to Claude Desktop

Add the following to your Claude Desktop configuration file:

Location: ~/Library/Application Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "jons-mcp-imessage": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/path/to/jons-mcp-imessage",
        "jons-mcp-imessage"
      ],
      "env": {
        "OPENAI_API_KEY": "sk-your-openai-api-key"
      }
    }
  }
}

Notes:

  • Replace /path/to/jons-mcp-imessage with the actual path to this repository

  • Replace sk-your-openai-api-key with your OpenAI API key (required for semantic search)

  • If you don't have an OpenAI key, omit the env section entirely - keyword search will still work

  • Restart Claude Desktop after modifying the config

Search Features

The search system combines two powerful search methods:

Keyword Search (FTS5)

Full-text search using SQLite FTS5 with BM25 ranking. Supports:

  • Phrase search: "exact phrase"

  • Prefix matching: word*

  • Proximity: word1 NEAR word2

  • Boolean: word1 AND word2, word1 OR word2, NOT word

AI-powered search using OpenAI embeddings to find conceptually similar messages, even when exact keywords don't match.

Setup

  1. Basic Setup (keyword search only): Works out of the box

  2. Full Setup (hybrid search): Set your OpenAI API key:

    export OPENAI_API_KEY=your-api-key

Search Modes

  • hybrid (default): Combines keyword + semantic results using RRF

  • keyword: FTS5 only (no API key needed)

  • semantic: Embedding similarity only (requires API key)

Index Management

The search index is stored separately from iMessage's chat.db at: ~/.local/share/jons-mcp-imessage/search_index.db

Tools available:

  • search_index_status - Check index health and sync status

  • rebuild_search_index - Full reindex (use if issues occur)

Troubleshooting

Issue

Solution

"No results found"

Check if index is synced with search_index_status

Semantic search not working

Verify OPENAI_API_KEY is set

Slow first search

Index is building in background, try again shortly

Stale results

chat.db may be locked by Messages app

Available Tools

Reading Messages

Tool

Description

check_permissions

Verify database access and diagnose permission issues

list_conversations

List all conversations with metadata (participants, last message, etc.)

get_conversation_messages

Get messages from a specific conversation by contact or chat_id

get_recent_messages

Get recent messages across all conversations

get_message_context

Get messages before/after a specific message in the same thread

search_messages

Search messages by text content with optional filters

search_contacts

Search for contacts/handles by phone number or email in iMessage database

lookup_contact

Look up contact name from Contacts app by phone/email (requires Contacts permission)

Sending Messages

Tool

Description

send_message

Send a message to an existing conversation

send_message Limitations

Important: The send_message tool has significant limitations:

  1. Existing conversations only: Can only send to contacts you have previously messaged. New contacts require starting a conversation manually in Messages.app first.

  2. No delivery confirmation: The tool reports success when the message is handed to Messages.app, but cannot confirm actual delivery. Messages may silently fail if:

    • The recipient has blocked you

    • The phone number/email is invalid

    • Network issues occur

  3. Messages.app must be running: If Messages.app is not running, the tool will fail with a "Messages not running" error.

  4. Service detection: By default, attempts iMessage first. Use service="SMS" to force SMS for non-iMessage contacts.

Example Usage

# Check if permissions are configured correctly
check_permissions()

# List your 10 most recent conversations
list_conversations(limit=10)

# Get messages from a specific contact
get_conversation_messages(contact="+15551234567", limit=20)

# Search for messages containing specific text
search_messages(query="dinner plans", sender="+15551234567")

# Get context around a specific message (5 messages before and after)
get_message_context(rowid=12345, before=5, after=5)

# Send a message (to existing conversation only)
send_message(recipient="+15551234567", message="Hello!")

Troubleshooting

"Permission denied" or "Unable to read database"

Cause: Full Disk Access not granted.

Fix: Follow the Full Disk Access instructions above. Make sure to:

  • Grant access to the correct application (the one actually running the server)

  • Restart the application after granting access

"Messages not running (-600)"

Cause: Messages.app is not running.

Fix: Open Messages.app before sending messages.

"Not allowed to send Apple events (-1743)"

Cause: Automation permission not granted.

Fix:

  1. Go to System Settings → Privacy & Security → Automation

  2. Find your application and enable Messages access

  3. If not listed, try sending a message again to trigger the permission prompt

"Can't get buddy id" or "existing conversations only"

Cause: Trying to message a contact you haven't messaged before.

Fix: Start a conversation with this contact manually in Messages.app first, then try again.

Messages appear empty or "(non-text message)"

Cause: The message contains only attachments (images, videos) or is a system message (like "renamed the group").

Note: This is expected behavior. The server extracts text content only.

Privacy Considerations

This server accesses your local iMessage database and optionally your Contacts database. Be aware that:

  • All message history is accessible: The server can read all messages stored locally

  • Contact information is exposed: Phone numbers and email addresses are visible

  • Attachments are referenced: File paths to attachments (photos, videos) are included

  • No cloud access: Only locally-stored messages are accessible (not messages only on iCloud)

Contact Name Privacy

If you grant Contacts permission:

  • Contact names come from YOUR Contacts app: The server reads your personal contact list to enrich message responses

  • Names are NOT stored: Contact names are resolved at query time and are NOT stored in any database or search index

  • Names are cached in-memory only: The server loads all contacts into memory on first use, cache is cleared on restart

  • All Contacts databases are read: Includes main Contacts DB plus any per-source databases (iCloud, CardDAV, etc.)

Use appropriate caution when granting AI assistants access to this server.

Development

Setup

# Install with dev dependencies
uv pip install -e ".[dev]"

Running Tests

# Run all tests
uv run pytest

# Run with coverage
uv run pytest --cov=src

# Run a specific test file
uv run pytest tests/test_parser.py

Code Quality

# Type check
uv run mypy src/jons_mcp_imessage

# Format code
uv run black src tests

# Lint code
uv run ruff check src tests

Project Structure

jons-mcp-imessage/
├── src/
│   └── jons_mcp_imessage/
│       ├── __init__.py          # Package exports
│       ├── constants.py         # Configuration constants
│       ├── exceptions.py        # Custom exceptions
│       ├── utils.py             # Utility functions
│       ├── server.py            # FastMCP server setup
│       ├── db/
│       │   ├── __init__.py      # Database module exports
│       │   ├── connection.py    # SQLite connection management
│       │   ├── models.py        # Pydantic data models
│       │   ├── parser.py        # attributedBody binary parser
│       │   └── queries.py       # Query helpers and utilities
│       └── tools/
│           ├── __init__.py      # Tool exports
│           ├── health.py        # Permission checking
│           ├── contacts.py      # Contact search
│           ├── conversations.py # Conversation tools
│           ├── messages.py      # Message tools
│           └── send.py          # Message sending
├── tests/
│   ├── test_parser.py           # attributedBody parser tests
│   ├── test_db.py               # Database utility tests
│   └── test_send.py             # Send tool tests
├── docs/
│   └── IMESSAGE_DATABASE_FORMAT.md  # Database format documentation
├── pyproject.toml               # Project configuration
├── CLAUDE.md                    # AI assistant guidance
└── README.md                    # This file

License

MIT

Available Tools

13 tools
check_permissionsA

Check if the server has the required permissions to access iMessage data.

This tool helps debug permission issues by checking:

  • Full Disk Access for ~/Library/Messages/chat.db

  • Access to ~/Library/Messages/Attachments

Returns: Dictionary with access status, paths checked, and any error messages. Includes macOS version for debugging.

Inputs: no named parameters. Returns: object

get_conversation_messagesA

Get messages from a specific conversation.

You can specify the conversation by either chat_id or contact identifier. If contact is provided, it will be normalized and used to find the chat. Messages are enriched with contact names for senders.

Args: chat_id: Database row ID of the chat (from list_conversations) contact: Phone number or email to find the conversation limit: Maximum number of messages to return (default: 50) offset: Number of messages to skip (default: 0)

Returns: Dictionary with messages list, conversation info, and pagination.

Inputs: chat_id, contact, limit, offset. Returns: object

get_message_contextA

Get messages surrounding a specific message in the same conversation.

Use this to get context around a message found via search. Returns messages from the same chat/thread, ordered chronologically, with the target message marked.

Args: rowid: The rowid of the message to get context for before: Number of messages to fetch before the target (default: 5) after: Number of messages to fetch after the target (default: 5)

Returns: Dictionary with: - messages: List of messages in chronological order - target_index: Index of the target message in the list - chat_id: The chat ID for the conversation - chat_identifier: The chat identifier (phone/email/group)

Inputs: rowid (required), before, after. Returns: object

get_rebuild_progressA

Get the current progress of a background index rebuild.

Returns: Dictionary with rebuild progress information, or status indicating no rebuild is in progress.

Inputs: no named parameters. Returns: object

get_recent_messagesA

Get the most recent messages across all conversations.

Args: limit: Maximum number of messages to return (default: 50) offset: Number of messages to skip (default: 0) after_date: Only return messages after this date (ISO8601 format)

Returns: Dictionary with messages list and pagination metadata.

Inputs: limit, offset, after_date. Returns: object

hello_worldA

Return a friendly greeting.

This is an example tool that demonstrates the basic pattern for creating MCP tools with FastMCP. The docstring here becomes the tool's description in the MCP protocol.

Args: name: The name to greet. Defaults to "World".

Returns: A greeting message.

Inputs: name. Returns: result

list_conversationsA

List all conversations with metadata.

Returns conversations sorted by most recent message, including:

  • Participant information

  • Contact names for participants

  • Message count

  • Last message preview

  • Whether it's a group chat

Args: limit: Maximum number of conversations to return (default: 20) offset: Number of conversations to skip (default: 0)

Returns: Dictionary with conversations list and pagination metadata.

Inputs: limit, offset. Returns: object

lookup_contactA

Look up a contact by phone number or email address.

Returns contact information if found in your Contacts, or None if not found. This tool explicitly resolves contacts from the macOS Contacts app.

Args: phone_or_email: The phone number or email address to look up.

Returns: Dictionary containing: - name: Contact's display name if found - matched_handle: The input phone/email that was matched - error: Error message if Contacts access is not available Or None if the contact is not found.

Inputs: phone_or_email (required). Returns: result

rebuild_search_indexA

Rebuild the entire search index from scratch.

This will:

  1. Clear the existing search index

  2. Re-index all messages from chat.db

  3. Update sync metadata

Note: This does NOT generate embeddings. Use a separate tool for that.

Args: background: If True, runs the rebuild in a background thread and returns immediately with progress tracking info. If False, blocks until complete.

Returns: Dictionary with rebuild status and progress information.

Inputs: background. Returns: object

search_contactsA

Search for contacts/handles in the iMessage database.

Searches by phone number or email address. Returns matching handles with their service type and conversation count.

Args: query: Search query (phone number or email, partial matches supported) limit: Maximum number of results to return (default: 20)

Returns: Dictionary containing: - results: List of matching handles with id, service, conversation_count - total: Total number of matches - query: The normalized search query

Inputs: query (required), limit. Returns: object

search_index_statusA

Get the current status of the search index.

Returns information about the search index including:

  • Total number of indexed messages

  • Total number of messages with embeddings

  • Last indexed message rowid

  • Last embedded message rowid

  • Schema version

  • Database path and size

  • Backfill status (if applicable)

Returns: Dictionary with search index status and metadata.

Inputs: no named parameters. Returns: object

search_messagesA

Search messages using hybrid keyword + semantic search.

Combines FTS5 full-text search with OpenAI embedding-based semantic search, merged using Reciprocal Rank Fusion (RRF) for optimal relevance.

This function is designed to handle partial failures gracefully:

  • If sync fails, search uses existing index

  • If semantic search fails, falls back to keyword search

  • If keyword search fails, returns empty results rather than crashing

  • Returns error information in response for visibility

Args: query: Search query text sender: Filter by sender phone/email (exact match after normalization) chat_id: Filter by specific conversation ID participants: Filter by chat participants (for group chats) after_date: Only messages after this date (ISO8601 format) before_date: Only messages before this date (ISO8601 format) service: Filter by "iMessage" or "SMS" search_mode: "hybrid" (default), "keyword" (FTS5 only), or "semantic" (vector only) limit: Results per page (default 100) offset: Pagination offset (default 0)

Returns: Dictionary with messages, pagination, and index_status including: - messages: List of matching messages with relevance scores - search_mode: The search mode that was used - fts5_matches: Number of keyword matches found - semantic_matches: Number of semantic matches found - pagination: Pagination metadata (total, limit, offset, has_more, next_offset) - index_status: Current state of the search index - errors: List of error messages encountered (if any) - warning: Warning message if partial results (optional)

Inputs: query (required), sender, chat_id, participants, +6 more. Returns: object

send_messageA

Send a message to an existing conversation via AppleScript.

IMPORTANT LIMITATIONS:

  • Can only send to contacts with EXISTING conversations in Messages

  • No delivery confirmation - the message may silently fail to send

  • Messages.app must be running

  • Requires Automation permission for Messages.app

Args: recipient: Phone number or email address of the recipient message: The message text to send service: Service type - "iMessage" or "SMS" (default: iMessage)

Returns: Dictionary with success status and any warnings/errors.

Inputs: recipient (required), message (required), service. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 13 tools

    Disambiguation4/5

    Most tools have distinct purposes, but there is some overlap between get_conversation_messages and get_recent_messages, as both retrieve messages with similar parameters. The hello_world tool also stands out as a trivial example that doesn't align with the iMessage domain, potentially causing confusion. However, the majority of tools are well-differentiated by their specific functions.

    Naming Consistency4/5

    Tool names follow a consistent verb_noun pattern (e.g., get_conversation_messages, search_contacts, rebuild_search_index), with only one minor deviation: check_permissions uses a verb_noun format but is slightly less descriptive. Overall, the naming is predictable and enhances usability, though not perfect.

    Tool Count5/5

    With 13 tools, the server is well-scoped for managing iMessage data, covering permissions, conversations, messages, contacts, search, and sending. Each tool serves a clear purpose, and the count is neither too sparse nor overwhelming, fitting typical use cases effectively.

    Completeness4/5

    The toolset provides comprehensive coverage for reading, searching, and sending iMessages, with robust features like permissions checks and index management. However, there are minor gaps, such as no tools for deleting messages or managing conversations (e.g., creating new chats), which could limit full lifecycle operations but are not critical for core functionality.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      B
      maintenance
      Enables AI assistants to search and retrieve from your local macOS iMessage history using hybrid retrieval with context expansion, all processed locally without sending data off-device.
      -
    • A
      license
      A
      quality
      B
      maintenance
      Enables AI agents on macOS to securely read and search the local Messages database, catch up on missed messages via a persistent inbox, and send texts or files to allowlisted chats, with optional voice note transcription and text-to-speech.
      10
      12 npm
      MIT