Skip to main content
Glama
4tal

MCP Google Contacts Server

by 4tal

search_contacts

Search Google Contacts by name, email, phone, organization, or other fields using server-side or client-side search to find specific contact information.

Instructions

Enhanced search contacts by name, email, phone, organization, or other fields.

    This uses server-side search when available and falls back to comprehensive client-side search.

    Args:
        query: Search term to find in contacts
        max_results: Maximum number of results to return (default: 50)
        search_fields: Specific fields to search in (e.g., ['emails', 'phones', 'organization'])
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_resultsNo
search_fieldsNo

Implementation Reference

  • MCP tool handler for 'search_contacts'. Initializes service, calls service.search_contacts(), formats results using format_contacts_list.
    @mcp.tool()
    async def search_contacts(
        query: str, max_results: int = 50, search_fields: Optional[List[str]] = None
    ) -> str:
        """Enhanced search contacts by name, email, phone, organization, or other fields.
    
        This uses server-side search when available and falls back to comprehensive client-side search.
    
        Args:
            query: Search term to find in contacts
            max_results: Maximum number of results to return (default: 50)
            search_fields: Specific fields to search in (e.g., ['emails', 'phones', 'organization'])
        """
        service = init_service()
        if not service:
            return "Error: Google Contacts service is not available. Please check your credentials."
    
        try:
            contacts = service.search_contacts(query, max_results, search_fields)
    
            if not contacts:
                return f"No contacts found matching '{query}'."
    
            return f"Search results for '{query}':\n\n{format_contacts_list(contacts)}"
        except Exception as e:
            return f"Error: Failed to search contacts - {str(e)}"
  • Core search_contacts method in GoogleContactsService class. Uses people.searchContacts API or falls back to manual search.
    def search_contacts(
        self, query: str, max_results: int = 50, search_fields: Optional[List[str]] = None
    ) -> List[Dict[str, Any]]:
        """Enhanced search functionality with server-side filtering and multiple field support.
    
        Args:
            query: Search term
            max_results: Maximum number of results
            search_fields: Specific fields to search in
    
        Returns:
            List of matching contact dictionaries
        """
        try:
            # Use the searchContacts API endpoint for better search
            # Note: This is a newer API that might not be available in all regions
            search_request = {
                "query": query,
                "readMask": ",".join(self.PERSON_FIELDS),
                "pageSize": min(max_results, 50),  # API limit for search
            }
    
            try:
                # Try the new search API first
                response = self.service.people().searchContacts(**search_request).execute()
                results = response.get("results", [])
    
                contacts = []
                for result in results:
                    person = result.get("person", {})
                    if person:
                        contact = self._format_contact_enhanced(person)
                        contacts.append(contact)
    
                return contacts[:max_results]
    
            except HttpError as search_error:
                # Fallback to manual search if the search API isn't available
                print(f"Search API not available, falling back to manual search: {search_error}")
                return self._manual_search_contacts(query, max_results, search_fields)
    
        except Exception as error:
            raise GoogleContactsError(f"Error searching contacts: {error}")
  • Fallback _manual_search_contacts method that performs client-side search across multiple fields in listed contacts.
    def _manual_search_contacts(
        self, query: str, max_results: int = 50, search_fields: Optional[List[str]] = None
    ) -> List[Dict[str, Any]]:
        """Fallback manual search with enhanced field matching."""
        # Get a larger set of contacts to search through
        all_contacts = self.list_contacts(max_results=max_results * 3, include_all_fields=True)
    
        query_lower = query.lower()
        matches = []
    
        # Default search fields
        if not search_fields:
            search_fields = [
                "displayName",
                "givenName",
                "familyName",
                "nickname",
                "emails",
                "phones",
                "organization",
                "jobTitle",
            ]
    
        for contact in all_contacts:
            match_found = False
    
            for field in search_fields:
                field_value = contact.get(field, "")
    
                # Handle list fields (emails, phones, etc.)
                if isinstance(field_value, list):
                    for item in field_value:
                        if query_lower in str(item).lower():
                            match_found = True
                            break
                # Handle string fields
                elif field_value and query_lower in str(field_value).lower():
                    match_found = True
                    break
    
            if match_found:
                matches.append(contact)
                if len(matches) >= max_results:
                    break
    
        return matches
  • src/tools.py:64-73 (registration)
    Top-level registration function that calls register_contact_tools (which contains the search_contacts tool definition).
    def register_tools(mcp: FastMCP) -> None:
        """Register all Google Contacts tools with the MCP server.
    
        Args:
            mcp: FastMCP server instance
        """
        register_contact_tools(mcp)
        register_directory_tools(mcp)
        register_contact_group_tools(mcp)

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/4tal/mcp-google-contacts'

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