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
| Name | Required | Description | Default |
|---|---|---|---|
| query | No | ||
| max_results | No |
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)
- mcp_google_contacts_server/main.py:83-84 (registration)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)