Skip to main content
Glama

messages_search_messages

Search iMessage conversations for specific text, sender, or chat history using AppleScript automation on macOS.

Instructions

[iMessage operations] Search for messages containing specific text or from a specific sender

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
searchTextYesText to search for in messages
senderNoSearch for messages from a specific sender (phone number or email)
chatIdNoLimit search to a specific chat ID
limitNoMaximum number of messages to retrieve
daysBackNoLimit search to messages from the last N days

Implementation Reference

  • Handler function that dynamically generates AppleScript to query the Messages database (chat.db) using SQLite, building WHERE clauses based on searchText, sender, chatId, daysBack parameters, and returns formatted message results.
          script: (args) => `
    on run
    	-- Path to the Messages database
    	set dbPath to (do shell script "echo ~/Library/Messages/chat.db")
    	
    	-- Create a temporary SQL file for our query
    	set tempFile to (do shell script "mktemp /tmp/imessage_search.XXXXXX")
    	
    	-- Build WHERE clause based on provided parameters
    	set whereClause to ""
    	
    	${args.searchText ? `
    	-- Add search text condition if provided
    	set whereClause to whereClause & "message.text LIKE '%${args.searchText.replace(/'/g, "''")}%' "
    	` : ''}
    	
    	${args.sender ? `
    	-- Add sender condition if provided
    	if length of whereClause > 0 then
    		set whereClause to whereClause & "AND "
    	end if
    	set whereClause to whereClause & "handle.id LIKE '%${args.sender.replace(/'/g, "''")}%' "
    	` : ''}
    	
    	${args.chatId ? `
    	-- Add chat ID condition if provided
    	if length of whereClause > 0 then
    		set whereClause to whereClause & "AND "
    	end if
    	set whereClause to whereClause & "chat.chat_identifier = '${args.chatId.replace(/'/g, "''")}' "
    	` : ''}
    	
    	${args.daysBack ? `
    	-- Add date range condition
    	if length of whereClause > 0 then
    		set whereClause to whereClause & "AND "
    	end if
    	set whereClause to whereClause & "message.date > (strftime('%s', 'now', '-${args.daysBack} days') - strftime('%s', '2001-01-01')) * 1000000000 "
    	` : ''}
    	
    	-- If no search parameters were provided, add a default condition to avoid returning all messages
    	if length of whereClause = 0 then
    		set whereClause to "1=1 "
    	end if
    	
    	-- Write SQL query to temp file
    	do shell script "cat > " & quoted form of tempFile & " << 'EOF'
    SELECT
        datetime(message.date/1000000000 + strftime('%s', '2001-01-01'), 'unixepoch', 'localtime') as message_date,
        handle.id as sender,
        message.text as message_text,
        chat.display_name as chat_name,
        chat.chat_identifier as chat_id
    FROM
        message
        LEFT JOIN handle ON message.handle_id = handle.ROWID
        LEFT JOIN chat_message_join ON message.ROWID = chat_message_join.message_id
        LEFT JOIN chat ON chat_message_join.chat_id = chat.ROWID
    WHERE
        " & whereClause & "
    ORDER BY
        message.date DESC
    LIMIT ${args.limit};
    EOF"
    	
    	-- Execute the query
    	set queryResult to do shell script "sqlite3 " & quoted form of dbPath & " < " & quoted form of tempFile
    	
    	-- Clean up temp file
    	do shell script "rm " & quoted form of tempFile
    	
    	-- Process and display results
    	set resultList to paragraphs of queryResult
    	set messageData to {}
    	
    	repeat with messageLine in resultList
    		set messageData to messageData & messageLine
    	end repeat
    	
    	return messageData
    end run
          `
  • JSON Schema defining the input parameters for the messages_search_messages tool, with searchText required.
    schema: {
      type: "object",
      properties: {
        searchText: {
          type: "string",
          description: "Text to search for in messages",
          default: ""
        },
        sender: {
          type: "string",
          description: "Search for messages from a specific sender (phone number or email)",
          default: ""
        },
        chatId: {
          type: "string",
          description: "Limit search to a specific chat ID",
          default: ""
        },
        limit: {
          type: "number",
          description: "Maximum number of messages to retrieve",
          default: 50
        },
        daysBack: {
          type: "number",
          description: "Limit search to messages from the last N days",
          default: 30
        }
      },
      required: ["searchText"]
  • Tool list registration: dynamically generates tool list including 'messages_search_messages' by combining category.name + '_' + script.name, with description and inputSchema from the script definition.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: this.categories.flatMap((category) =>
        category.scripts.map((script) => ({
          name: `${category.name}_${script.name}`, // Changed from dot to underscore
          description: `[${category.description}] ${script.description}`,
          inputSchema: script.schema || {
            type: "object",
            properties: {},
          },
        })),
      ),
    }));
  • Core tool execution handler: for 'messages_search_messages', invokes the script generator function with arguments, executes the generated AppleScript via osascript, and returns the result as text content.
    const scriptContent =
      typeof script.script === "function"
        ? script.script(request.params.arguments)
        : script.script;
    
    const result = await this.executeScript(scriptContent);
    
    this.log("info", "Tool execution completed successfully", { 
      tool: toolName,
      resultLength: result.length
    });
    
    return {
      content: [
        {
          type: "text",
          text: result,
        },
      ],
    };
  • src/index.ts:34-34 (registration)
    Registers the messages category (containing search_messages script) with the AppleScriptFramework, enabling the 'messages_search_messages' tool.
    server.addCategory(messagesCategory);
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the search functionality but fails to describe key behaviors such as whether the search is case-sensitive, how results are ordered, if there are rate limits, or what the output format looks like. This leaves significant gaps for an agent to understand how to use it effectively.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core functionality with no wasted words. It uses brackets for context ('[iMessage operations]') and clearly states the action and criteria, making it easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a search tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It lacks details on behavioral traits, result formatting, and usage context, leaving the agent with insufficient information to operate the tool confidently beyond basic parameter input.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal value by implying text and sender filtering, but doesn't provide additional semantics beyond what's in the schema. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Search') and resource ('messages') with specific criteria ('containing specific text or from a specific sender'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'messages_get_messages' or 'messages_list_chats', which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'messages_get_messages' or 'messages_list_chats', nor does it mention prerequisites or exclusions. It merely states what the tool does without contextual usage advice.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/joshrutkowski/applescript-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server