Skip to main content
Glama
4tal

MCP Google Contacts Server

by 4tal

search_directory

Search your Google Workspace directory to find specific organization members using targeted queries.

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 MCP tool handler for 'search_directory', decorated with @mcp.tool() which handles registration. It initializes the GoogleContactsService and delegates to the service's search_directory method, then formats the output.
    @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 implementing the directory search logic using the Google People API's searchDirectoryPeople endpoint, formatting results with _format_directory_person.
    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}")
  • Helper function to format the results of directory searches into a user-friendly string output, including summaries and statistics.
    def format_directory_people(people: List[Dict[str, Any]], query: Optional[str] = None) -> str:
        """Format a list of directory people into a readable string with enhanced display.
    
        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 "No directory members found matching '" + query + "'."
            return "No directory members found."
    
        # Count how many users have emails
        users_with_email = _count_users_with_email(people)
    
        # Format the results
        formatted_users = []
        for i, user in enumerate(people, 1):
            user_parts = _format_single_directory_user(user, i)
            formatted_users.append("\n".join(user_parts))
    
        # Add summary
        query_part = " matching '" + query + "'" if query else ""
        summary = (
            "📊 Found "
            + str(len(people))
            + " directory member(s)"
            + query_part
            + ". "
            + str(users_with_email)
            + " have email addresses."
        )
        formatted_users.append("=" * 50)
        formatted_users.append(summary)
    
        return "\n\n".join(formatted_users)
  • src/tools.py:64-73 (registration)
    Registration entry point that calls register_directory_tools(mcp), which defines and registers the search_directory tool via @mcp.tool() decorator.
    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