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)
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses important behavioral traits: the server-side/client-side fallback mechanism and the default max_results value. However, it doesn't mention rate limits, authentication requirements, pagination behavior, or what happens when no results are found.

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

Conciseness4/5

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

The description is well-structured with a clear purpose statement followed by behavioral context and parameter explanations. It's appropriately sized at 4 sentences, though the Args section formatting could be cleaner. Every sentence adds value.

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?

For a search tool with 3 parameters, 0% schema coverage, no annotations, and no output schema, the description does reasonably well but has gaps. It covers parameters well and mentions search behavior, but doesn't describe the return format, error conditions, or how results are ordered/filtered.

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

Parameters4/5

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

Schema description coverage is 0%, so the description must compensate. It provides meaningful context for all three parameters: explaining what 'query' searches for, clarifying 'max_results' default and purpose, and giving examples for 'search_fields'. This adds substantial value beyond the bare schema.

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: 'Enhanced search contacts by name, email, phone, organization, or other fields.' It specifies the verb ('search') and resource ('contacts') with examples of searchable fields. However, it doesn't explicitly differentiate from siblings like 'search_contacts_by_group' or 'search_directory'.

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 'search_contacts_by_group', 'search_directory', or 'list_contacts'. It mentions server-side vs client-side search behavior but doesn't explain when one approach is preferred or what distinguishes this from other search tools.

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

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