Skip to main content
Glama
4tal

MCP Google Contacts Server

by 4tal

list_workspace_users

Search and list Google Workspace users in your organization's directory to find email addresses and contact information.

Instructions

List Google Workspace users in your organization's directory.

    This tool allows you to search and list users in your Google Workspace directory,
    including their email addresses and other information.

    Args:
        query: Optional search term to find specific users (name, email, etc.)
        max_results: Maximum number of results to return (default: 50)
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryNo
max_resultsNo

Implementation Reference

  • The handler function for the 'list_workspace_users' tool, decorated with @mcp.tool() for automatic registration. It initializes the GoogleContactsService, calls list_directory_people on it, and formats the result using format_directory_people. The docstring and type hints define the tool schema.
    @mcp.tool()
    async def list_workspace_users(query: Optional[str] = None, max_results: int = 50) -> str:
        """List Google Workspace users in your organization's directory.
    
        This tool allows you to search and list users in your Google Workspace directory,
        including their email addresses and other information.
    
        Args:
            query: Optional search term to find specific users (name, email, etc.)
            max_results: Maximum number of results to return (default: 50)
        """
        service = init_service()
        if not service:
            return "Error: Google Contacts service is not available. Please check your credentials."
    
        try:
            workspace_users = service.list_directory_people(query=query, max_results=max_results)
            return format_directory_people(workspace_users, query)
        except Exception as e:
            return f"Error: Failed to list Google Workspace users - {str(e)}"
  • Core helper method implementing the Google People API calls (searchDirectoryPeople or listDirectoryPeople) to retrieve Workspace directory users, formats them using _format_directory_person, and handles errors.
    def list_directory_people(
        self, query: Optional[str] = None, max_results: int = 50
    ) -> List[Dict]:
        """List people from the Google Workspace directory.
    
        Args:
            query: Optional search query to filter directory results
            max_results: Maximum number of results to return
    
        Returns:
            List of formatted directory contact dictionaries
        """
        try:
            # Check if directory API access is available
            directory_fields = "names,emailAddresses,organizations,phoneNumbers"
    
            # Build the request, with or without a query
            if query:
                request = self.service.people().searchDirectoryPeople(
                    query=query,
                    readMask=directory_fields,
                    sources=[
                        "DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT",
                        "DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE",
                    ],
                    pageSize=max_results,
                )
            else:
                request = self.service.people().listDirectoryPeople(
                    readMask=directory_fields,
                    sources=[
                        "DIRECTORY_SOURCE_TYPE_DOMAIN_CONTACT",
                        "DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE",
                    ],
                    pageSize=max_results,
                )
    
            # Execute the request
            response = request.execute()
            print("response; ", response)
    
            # Process the results
            people = response.get("people", [])
            if not people:
                return []
    
            # Format each person entry
            directory_contacts = []
            for person in people:
                contact = self._format_directory_person(person)
                directory_contacts.append(contact)
    
            return directory_contacts
  • Helper function to format the output of directory people list into a user-friendly string, 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)
  • Helper function to initialize the global GoogleContactsService instance, trying env vars then credential files.
    def init_service() -> Optional[GoogleContactsService]:
        """Initialize and return a Google Contacts service instance.
    
        Returns:
            GoogleContactsService instance or None if initialization fails
        """
        global contacts_service
    
        if contacts_service:
            return contacts_service
    
        try:
            # First try environment variables
            try:
                contacts_service = GoogleContactsService.from_env()
                print("Successfully loaded credentials from environment variables.")
                return contacts_service
            except GoogleContactsError:
                pass
    
            # Then try default file locations
            for path in config.credentials_paths:
                if path.exists():
                    try:
                        print(f"Found credentials file at {path}")
                        contacts_service = GoogleContactsService.from_file(path)
                        print("Successfully loaded credentials from file.")
                        return contacts_service
                    except GoogleContactsError as e:
                        print(f"Error with credentials at {path}: {e}")
                        continue
    
            print("No valid credentials found. Please provide credentials to use Google Contacts.")
            return None
    
        except Exception as e:
            print(f"Error initializing Google Contacts service: {str(e)}")
            traceback.print_exc()
            return None
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the tool can 'search and list users' and describes the parameters, but doesn't address important behavioral aspects like authentication requirements, rate limits, pagination behavior, error conditions, or what specific user information is returned beyond 'email addresses and other information'. For a directory listing tool with zero annotation coverage, this leaves significant gaps in understanding how the tool behaves.

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 appropriately sized and well-structured. It starts with a clear purpose statement, then provides parameter documentation in a formatted 'Args:' section. While slightly verbose with the introductory sentence repeating the purpose, each sentence adds value by clarifying scope and parameter usage. The formatting helps readability without excessive length.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (directory listing with search capabilities), lack of annotations, and absence of an output schema, the description is incomplete. It doesn't explain what user information is returned beyond vague 'other information', doesn't address authentication or permission requirements, and provides no examples of query syntax or result formatting. For a tool that interacts with organizational directory data, this leaves too many practical questions unanswered.

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. With 0% schema description coverage, the description compensates by explaining that 'query' is an 'optional search term to find specific users (name, email, etc.)' and 'max_results' is the 'maximum number of results to return (default: 50)'. This provides practical usage guidance that the bare schema titles ('Query', 'Max Results') lack.

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 as listing Google Workspace users in the organization's directory, including their email addresses and other information. It uses specific verbs ('list', 'search') and identifies the resource ('Google Workspace users'). However, it doesn't explicitly distinguish this tool from sibling tools like 'search_directory' or 'list_contacts', which appear to serve similar directory functions.

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. With sibling tools like 'search_directory', 'list_contacts', and 'search_contacts' available, there's no indication of how this tool differs in scope, functionality, or appropriate use cases. The description only states what the tool does, not when it should be selected over other options.

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