Skip to main content
Glama

contacts

Search and retrieve contact details from the Apple Contacts app using partial or complete names. Simplify access to stored contact information through direct queries.

Instructions

Search and retrieve contacts from Apple Contacts app

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nameNoName to search for (optional - if not provided, returns all contacts). Can be partial name to search.

Implementation Reference

  • Main handler function for the 'contacts' MCP tool. Loads the contacts module and calls findNumber or getAllNumbers based on whether a name is provided, formats the response.
    export async function handleContacts(
      args: ContactsArgs,
      loadModule: LoadModuleFunction
    ) {
      try {
        const contactsModule = await loadModule('contacts');
    
        if (args.name) {
          const numbers = await contactsModule.findNumber(args.name);
          return {
            content: [{
              type: "text",
              text: numbers.length ?
                `${args.name}: ${numbers.join(", ")}` :
                `No contact found for "${args.name}". Try a different name or use no name parameter to list all contacts.`
            }],
            isError: false
          };
        } else {
          const allNumbers = await contactsModule.getAllNumbers();
          const contactCount = Object.keys(allNumbers).length;
    
          if (contactCount === 0) {
            return {
              content: [{
                type: "text",
                text: "No contacts found in the address book. Please make sure you have granted access to Contacts."
              }],
              isError: false
            };
          }
    
          // Explicitly type 'phones' as string[]
          const formattedContacts = Object.entries(allNumbers)
            .filter(([_, phones]) => (phones as string[]).length > 0) 
            .map(([name, phones]) => `${name}: ${(phones as string[]).join(", ")}`);
    
          return {
            content: [{
              type: "text",
              text: formattedContacts.length > 0 ?
                `Found ${contactCount} contacts:\n\n${formattedContacts.join("\n")}` :
                "Found contacts but none have phone numbers. Try searching by name to see more details."
            }],
            isError: false
          };
        }
      } catch (error) {
        return {
          content: [{
            type: "text",
            text: `Error accessing contacts: ${error instanceof Error ? error.message : String(error)}`
          }],
          isError: true
        };
      }
    }
  • tools.ts:3-15 (schema)
    MCP Tool schema definition for the 'contacts' tool, specifying name, description, and inputSchema with optional 'name' parameter.
    const CONTACTS_TOOL: Tool = {
        name: "contacts",
        description: "Search and retrieve contacts from Apple Contacts app",
        inputSchema: {
          type: "object",
          properties: {
            name: {
              type: "string",
              description: "Name to search for (optional - if not provided, returns all contacts). Can be partial name to search."
            }
          }
        }
      };
  • index.ts:116-119 (registration)
    Registration of the 'contacts' tool call handler in the main MCP server request handler switch statement.
    case "contacts": {
      const validatedArgs = ContactsArgsSchema.parse(args);
      return await handleContacts(validatedArgs, loadModule);
    }
  • index.ts:102-104 (registration)
    Registration for listing tools, which includes the 'contacts' tool from the imported tools array.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools
    }));
  • Default export of the contacts module providing helper functions getAllNumbers, findNumber, and findContactByPhone used by the handler.
    export default { getAllNumbers, findNumber, findContactByPhone };
  • Helper function to retrieve all contacts and their phone numbers using JXA to interact with the Contacts app.
    async function getAllNumbers() {
        try {
            if (!await checkContactsAccess()) {
                return {};
            }
    
            const nums: { [key: string]: string[] } = await run(() => {
                const Contacts = Application('Contacts');
                const people = Contacts.people();
                const phoneNumbers: { [key: string]: string[] } = {};
    
                for (const person of people) {
                    try {
                        const name = person.name();
                        const phones = person.phones().map((phone: unknown) => (phone as { value: string }).value);
    
                        if (!phoneNumbers[name]) {
                            phoneNumbers[name] = [];
                        }
                        phoneNumbers[name] = [...phoneNumbers[name], ...phones];
                    } catch (error) {
                        // Skip contacts that can't be processed
                    }
                }
    
                return phoneNumbers;
            });
    
            return nums;
        } catch (error) {
            throw new Error(`Error accessing contacts: ${error instanceof Error ? error.message : String(error)}`);
        }
    }
  • Helper function to find phone numbers for a given contact name, with fallback to full list search.
    async function findNumber(name: string) {
        try {
            if (!await checkContactsAccess()) {
                return [];
            }
    
            const nums: string[] = await run((name: string) => {
                const Contacts = Application('Contacts');
                const people = Contacts.people.whose({name: {_contains: name}})(); // Ensure it's executed
                let phoneValues: string[] = [];
    
                if (people.length > 0) {
                    const person = people[0];
                    // Check if phones property exists and is callable
                    if (typeof person.phones === 'function') { 
                        const phones = person.phones();
                        if (Array.isArray(phones)) {
                            phoneValues = phones.map((phone: any) => {
                                // Check if phone object and value property exist
                                if (phone && typeof phone.value === 'function') {
                                    const val = phone.value();
                                    return typeof val === 'string' ? val : null; // Return null if not a string
                                }
                                return null; // Return null if phone or value is invalid
                            }).filter((value): value is string => value !== null && value !== ''); // Filter out nulls and empty strings
                        }
                    }
                }
                return phoneValues;
            }, name);
    
            // If no numbers found, run getAllNumbers() to find the closest match (changed from getNumbers)
            if (nums.length === 0) {
                const allNumbers = await getAllNumbers();
                const closestMatch = Object.keys(allNumbers).find(personName => 
                    personName.toLowerCase().includes(name.toLowerCase())
                );
                return closestMatch ? allNumbers[closestMatch] : [];
            }
    
            return nums;
        } catch (error) {
            throw new Error(`Error finding contact: ${error instanceof Error ? error.message : String(error)}`);
        }
    }

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

B3.1/5.0
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool searches and retrieves contacts, implying a read-only operation, but doesn't specify permissions needed, whether it accesses local or synced data, rate limits, or what the return format looks like (e.g., list of contacts with fields). This leaves significant gaps for a tool interacting with personal data.

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 with zero waste. It front-loads the core purpose ('Search and retrieve contacts') and specifies the source ('from Apple Contacts app'), making it easy to parse quickly.

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

Completeness3/5

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

Given the tool's moderate complexity (searching personal contacts), lack of annotations, and no output schema, the description is minimally adequate. It states what the tool does but omits critical context like return format, error handling, or data sensitivity considerations. It relies heavily on the schema for parameter details, leaving behavioral aspects underspecified.

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 input schema fully documents the single optional parameter. The description adds no additional parameter semantics beyond what's in the schema (e.g., no examples of search syntax or format). 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 tool's purpose with a specific verb ('Search and retrieve') and resource ('contacts from Apple Contacts app'). It distinguishes itself from siblings like calendar or mail by focusing on contacts, but doesn't explicitly differentiate from potential contact-related tools that might exist in other contexts.

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. It doesn't mention any prerequisites, limitations, or scenarios where other tools might be more appropriate. The agent must infer usage from the purpose alone.

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

Deploy Server

Other Tools

Related Tools