Skip to main content
Glama
RayanZaki

MCP Google Contacts Server

by RayanZaki

list_workspace_users

Search and list users in your Google Workspace directory to find email addresses and organizational information. Use optional search terms to locate specific users by name or email.

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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'list_workspace_users' tool. It is decorated with @mcp.tool() for automatic registration and executes the tool logic by invoking the Google Contacts service and formatting the output.
    @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 in GoogleContactsService that performs the actual API call to list or search Google Workspace directory users using People API's listDirectoryPeople or searchDirectoryPeople endpoints.
    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
            
        except HttpError as error:
            # Handle gracefully if not a Google Workspace account
            if error.resp.status == 403:
                print("Directory API access forbidden. This may not be a Google Workspace account.")
                return []
            raise Exception(f"Error listing directory people: {error}")
  • Helper function that formats the list of Workspace users into a human-readable string, used by the tool 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)
  • In main.py, register_tools(mcp) is called, which defines and registers the list_workspace_users tool along with others using FastMCP decorators.
    # 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. While it mentions the tool 'allows you to search and list users' and describes parameters, it doesn't cover important behavioral aspects like authentication requirements, rate limits, pagination behavior, error conditions, or what specific user information beyond email addresses is returned. 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 with clear sections. The purpose is stated upfront, followed by additional context, then parameter explanations. While slightly verbose with some redundancy ('list' appears twice in the opening), each sentence adds value and there's no wasted text. The parameter documentation is neatly formatted.

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 an output schema exists (so return values are documented elsewhere), the description covers the basic purpose and parameters adequately. However, for a directory listing tool with no annotations and multiple sibling tools, it should provide more context about when to use it versus alternatives and more behavioral transparency about how it operates. The parameter explanations help compensate for the 0% schema coverage.

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?

With 0% schema description coverage, the description compensates well by explaining both parameters: 'query' is described as 'Optional search term to find specific users (name, email, etc.)' and 'max_results' as 'Maximum number of results to return (default: 50)'. This adds meaningful context beyond the bare schema, clarifying the query scope and default value. However, it doesn't specify format constraints or validation rules.

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: 'List Google Workspace users in your organization's directory' with the verb 'list' and resource 'Google Workspace users'. It specifies the scope ('your organization's directory') and mentions what information is included ('email addresses and other information'). However, it doesn't explicitly differentiate from sibling tools like 'search_directory' or 'list_contacts', which appear to be related directory/search tools.

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 when this specific workspace user listing tool is appropriate versus those other directory/contact tools. The description only states what the tool does, not when to choose it.

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