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

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)

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