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)}`);
        }
    }
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 mentions 'search and retrieve' but doesn't specify whether this is read-only, requires permissions, has rate limits, or describes the return format. This is a significant gap for a tool with no annotation coverage.

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's appropriately sized and front-loaded, directly stating the tool's purpose without unnecessary elaboration.

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 lack of annotations and output schema, the description is incomplete. It doesn't address behavioral aspects like safety, permissions, or return values, which are crucial for a search/retrieve tool. The high schema coverage helps, but overall context is insufficient.

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?

The schema description coverage is 100%, so the schema already documents the single parameter ('name') with its optional nature and partial matching capability. The description adds no additional parameter semantics beyond what the schema provides, meeting the baseline of 3 when the schema does the heavy lifting.

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 specific verbs ('search and retrieve') and resource ('contacts from Apple Contacts app'), making it immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'calendar' or 'mail', which would require a 5.

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 prerequisites, appropriate contexts, or exclusions, leaving the agent to infer usage solely from the tool name and purpose.

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

Related 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/wearesage/mcp-apple'

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