Skip to main content
Glama
RayanZaki

MCP Google Contacts Server

by RayanZaki

search_directory

Find specific people in your Google Workspace directory using targeted search queries to locate organization members.

Instructions

Search for people specifically in the Google Workspace directory.

    This performs a more targeted search of your organization's directory.
    
    Args:
        query: Search term to find specific directory members
        max_results: Maximum number of results to return (default: 20)
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
max_resultsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary MCP tool handler for 'search_directory'. Decorated with @mcp.tool(), it handles tool invocation by initializing the service, performing the directory search via the service method, formatting the results, and returning a user-friendly string response.
    @mcp.tool()
    async def search_directory(query: str, max_results: int = 20) -> str:
        """Search for people specifically in the Google Workspace directory.
        
        This performs a more targeted search of your organization's directory.
        
        Args:
            query: Search term to find specific directory members
            max_results: Maximum number of results to return (default: 20)
        """
        service = init_service()
        if not service:
            return "Error: Google Contacts service is not available. Please check your credentials."
        
        try:
            results = service.search_directory(query, max_results)
            return format_directory_people(results, query)
        except Exception as e:
            return f"Error: Failed to search directory - {str(e)}"
  • Core helper method in GoogleContactsService class that executes the Google People API searchDirectoryPeople request, processes the response, formats each person using _format_directory_person, and returns a list of formatted directory contacts.
    def search_directory(self, query: str, max_results: int = 20) -> List[Dict]:
        """Search for people in the Google Workspace directory.
        
        This is a more focused search function that uses the searchDirectoryPeople endpoint.
        
        Args:
            query: Search query to find specific users
            max_results: Maximum number of results to return
            
        Returns:
            List of matching directory contact dictionaries
        """
        try:
            response = self.service.people().searchDirectoryPeople(
                query=query,
                readMask='names,emailAddresses,organizations,phoneNumbers',
                sources=['DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT', 'DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE'],
                pageSize=max_results
            ).execute()
            
            people = response.get('people', [])
            
            
            if not people:
                return []
            
            # Format the results
            directory_results = []
            for person in people:
                contact = self._format_directory_person(person)
                directory_results.append(contact)
            
            return directory_results
            
        except HttpError as error:
            if error.resp.status == 403:
                print("Directory search access forbidden. This may not be a Google Workspace account.")
                return []
            raise Exception(f"Error searching directory: {error}")
  • Supporting formatter utility that converts the list of directory search results into a human-readable string format, including summaries and structured details for each person. Used by the search_directory handler.
    def format_directory_people(people: List[Dict[str, Any]], query: Optional[str] = None) -> str:
        """Format a list of directory people into a readable string.
        
        Args:
            people: List of directory people dictionaries
            query: Optional search query used to find these people
            
        Returns:
            Formatted string representation of the directory people
        """
        if not people:
            if query:
                return f"No directory members found matching '{query}'."
            return "No directory members found."
        
        # Count how many users have emails
        users_with_email = sum(1 for user in people if user.get('email'))
        
        # Format the results
        formatted_users = []
        for i, user in enumerate(people, 1):
            user_parts = []
            user_parts.append(f"Directory Member {i}:")
            
            if user.get('displayName'):
                user_parts.append(f"Name: {user['displayName']}")
            
            if user.get('email'):
                user_parts.append(f"Email: {user['email']}")
            
            if user.get('department'):
                user_parts.append(f"Department: {user['department']}")
            
            if user.get('jobTitle'):
                user_parts.append(f"Title: {user['jobTitle']}")
            
            if user.get('phone'):
                user_parts.append(f"Phone: {user['phone']}")
            
            if user.get('resourceName'):
                user_parts.append(f"ID: {user['resourceName']}")
            
            formatted_users.append("\n".join(user_parts))
        
        query_part = f" matching '{query}'" if query else ""
        summary = f"Found {len(people)} directory member(s){query_part}. {users_with_email} have email addresses."
        formatted_users.append(summary)
        
        return "\n\n".join(formatted_users)
  • Server initialization code where the FastMCP instance is created and register_tools is invoked to define and register all MCP tools, including 'search_directory', via decorators inside register_tools.
    mcp = FastMCP("google-contacts")
    
    # Register all tools
    register_tools(mcp)
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'more targeted search' which hints at specificity, but doesn't describe important behaviors like authentication requirements, rate limits, pagination, error handling, or what constitutes a 'targeted' search. For a search tool with zero annotation coverage, this leaves significant gaps in understanding how it operates.

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 and appropriately sized. It starts with the core purpose, adds context about the search type, and then provides parameter details in a clear format. Every sentence adds value, though the 'more targeted search' phrase could be more specific to earn a perfect score.

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 that there's an output schema (which handles return values) and only 2 parameters with good description coverage, the description is reasonably complete for a search tool. However, the lack of annotations means important behavioral aspects like authentication, rate limits, and error handling aren't addressed, and the relationship to sibling tools isn't clarified, leaving some contextual gaps.

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?

The description adds meaningful context for both parameters beyond what the schema provides. It explains that 'query' is a 'Search term to find specific directory members' and 'max_results' has a 'default: 20', which clarifies their purpose and usage. Since schema description coverage is 0%, the description effectively compensates by providing this essential parameter information.

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: 'Search for people specifically in the Google Workspace directory.' It specifies the verb ('search'), resource ('people'), and scope ('Google Workspace directory'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'search_contacts' or 'list_workspace_users', 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 Guidelines3/5

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

The description provides some implied usage context by mentioning 'more targeted search' and specifying the directory scope, which suggests it's for organizational directory searches rather than general contacts. However, it lacks explicit guidance on when to use this tool versus alternatives like 'search_contacts' or 'list_workspace_users', and doesn't mention any prerequisites or exclusions.

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/RayanZaki/mcp-google-contacts-server'

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