mcp-gsuite

repository·main·Indexed 19 days ago

https://github.com/markuspfundstein/mcp-gsuite

An MCP (Model Context Protocol) server that enables AI models to interact with Google Workspace products, specifically Gmail and Google Calendar, across multiple Google accounts. Version 0.4.1 provides capabilities to list, retrieve, create, and delete calendar events via CalendarService, and query emails using Gmail search syntax via GmailService. It supports OAuth2 authorization for Google Workspace APIs and can be configured for use with Claude Desktop.

Tokens
8.1K
Snippets
25
Records
40
Agent score
67%

What's inside mcp-gsuite

  1. Configure OAuth2 for Google Workspace APIs

    main

    The mcp-gsuite server requires OAuth2 authorization to interact with Gmail and Calendar APIs.

    1. Google Cloud Console Setup

    • Create a project in the Google Cloud Console.
    • Enable the Gmail API and Google Calendar API.
    • Create OAuth client ID credentials (select 'Desktop app' or 'Web application').
    • Configure the OAuth consent screen.
    • Add http://localhost:4100/code to your authorized redirect URIs.

    2. Required Scopes

    The following scopes must be used:

    [
      "openid",
      "https://mail.google.com/",
      "https://www.googleapis.com/auth/calendar",
      "https://www.googleapis.com/auth/userinfo.email"
    ]

    3. Create Configuration Files

    Create a .gauth.json file in your working directory to store client credentials:

    {
        "web": {
            "client_id": "$your_client_id",
            "client_secret": "$your_client_secret",
            "redirect_uris": ["http://localhost:4100/code"],
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token"
        }
    }

    Create a .accounts.json file to define the Google accounts the server can access:

    {
        "accounts": [
            {
                "email": "alice@bob.com",
                "account_type": "personal",
                "extra_info": "Additional info that you want to tell Claude: E.g. 'Contains Family Calendar'"
            }
        ]
    }

    4. Initial Authorization

    When you first execute a tool for a specific account, a browser will open for you to log in. After successful authentication, the server stores credentials in a local file named .oauth.{email}.json.

  2. Configure mcp-gsuite in Claude Desktop

    main

    To use mcp-gsuite with Claude Desktop, add the server configuration to your claude_desktop_config.json file.

    File Locations:

    • MacOS: ~/Library/Application\ Support/Claude/claude_desktop_config.json
    • Windows: %APPDATA%/Claude/claude_desktop_config.json

    Configuration for Development/Unpublished Servers

    Use this if you are running the server from a local directory using uv:

    {
      "mcpServers": {
        "mcp-gsuite": {
          "command": "uv",
          "args": [
            "--directory",
            "<dir_to>/mcp-gsuite",
            "run",
            "mcp-gsuite"
          ]
        }
      }
    }

    Note: You can pass additional arguments like --accounts-file or --credentials-dir within the args array to customize paths.

    Configuration for Published Servers

    Use this to run the server via uvx:

    {
      "mcpServers": {
        "mcp-gsuite": {
          "command": "uvx",
          "args": [
            "mcp-gsuite",
            "--accounts-file",
            "/path/to/custom/.accounts.json",
            "--credentials-dir",
            "/path/to/custom/credentials"
          ]
        }
      }
    }
  3. Implement a custom MCP tool using ToolHandler

    main

    To add new Google Workspace capabilities to the MCP server, you must implement a subclass of ToolHandler. The base class provides helper methods to handle user identity and account selection, ensuring that the LLM (e.g., Claude) knows which Google account to use for specific actions.

    When implementing a tool, you must provide implementations for:

    1. get_tool_description(): Returns a mcp.types.Tool object defining the tool's name and input schema.
    2. run_tool(args): Executes the tool logic and returns a sequence of TextContent, ImageContent, or EmbeddedResource.

    If your tool requires a specific user identity, use the provided helper methods to inject the available Google account emails into the tool's description and argument schema. This allows the LLM to select a valid email from the list of authorized accounts.

    from mcp_gsuite.toolhandler import ToolHandler
    
    class MyCustomGoogleTool(ToolHandler):
        def __init__(self):
            super().__init__("my_custom_tool")
    
        def get_tool_description(self) -> Tool:
            # Use get_user_id_arg_schema() if the tool needs a __user_id__
            return Tool(
                name=self.name,
                description="Does something in GSuite",
                input_schema={
                    "type": "object",
                    "properties": self.get_user_id_arg_schema(),
                    "required": ["__user_id__"]
                }
            )
    
        def run_tool(self, args: dict):
            user_email = args.get("__user_id__")
            # Execute logic using user_email...
            return [TextContent(type="text", text=f"Executed for {user_email}")]
  4. How the mcp-gsuite tool execution flow works

    main

    The mcp-gsuite server uses a centralized tool handler pattern. When a tool is called via the MCP call_tool interface, the server performs the following steps:

    1. Argument Validation: It ensures the arguments provided is a dictionary.
    2. Identity Resolution: It requires a user_id argument (defined by the constant toolhandler.USER_ID_ARG).
    3. OAuth2 Setup: It calls setup_oauth2(user_id=...) to ensure valid credentials exist for that specific user. If credentials are missing or expired, it triggers an OAuth2 flow.
    4. Handler Execution: It retrieves the registered ToolHandler for the requested tool name and executes its run_tool(arguments) method.

    To use a tool, you must always include the user_id in your tool arguments, which corresponds to the email address configured in your .gauth.json file.

  5. Configure OAuth2 authentication for GSuite tools

    main

    The server manages authentication via a .gauth.json file. Before calling tools, you must ensure the user_id (the user's email address) is authorized.

    Authentication Workflow

    1. Account Specification: Your target email must be listed in the .gauth.json file. If it is not, setup_oauth2 will raise a RuntimeError.
    2. Automatic Flow: If credentials for the user_id are not found, the server automatically starts an OAuth2 flow by opening a browser window to the Google authorization URL.
    3. Callback: The server listens on port 4100 for a /code callback to complete the exchange.

    Troubleshooting Credentials

    If you see the error credentials expired. try refresh, the server will attempt to refresh the access token using the stored credentials and then re-store them.

  6. Perform the OAuth2 authorization flow

    main

    To authenticate a user, follow this flow:

    1. Generate Authorization URL: Call get_authorization_url(email_address, state) to get a URL. Redirect the user to this URL to grant permissions. This request requests offline access to ensure a refresh token is provided.
    2. Exchange Code for Credentials: After the user authorizes, they will be redirected to the REDIRECT_URI (http://localhost:4100/code) with an authorization code. Pass this code to get_credentials(authorization_code, state).
    3. Handle Results: get_credentials will exchange the code, fetch user info, and automatically store the credentials if a refresh token is present.
    # 1. Get URL
    auth_url = get_authorization_url("user@example.com", "random_state")
    
    # 2. After user redirects back with code
    # This will exchange the code and store credentials automatically
    credentials = get_credentials(auth_code, "random_state")
  7. Debug mcp-gsuite using MCP Inspector

    main

    Since MCP servers communicate over stdio, use the MCP Inspector for debugging. Run the following command to launch the inspector for your local mcp-gsuite installation:

    npx @modelcontextprotocol/inspector uv --directory /path/to/mcp-gsuite run mcp-gsuite

    To monitor server logs on MacOS, use:

    tail -n 20 -f ~/Library/Logs/Claude/mcp-server-mcp-gsuite.log
  8. Reference: mcp-gsuite CLI Options

    main

    The following command-line options allow you to specify custom paths for authentication and account management:

    • --gauth-file: Path to the .gauth.json file containing OAuth2 client configuration. (Default: ./.gauth.json)
    • --accounts-file: Path to the .accounts.json file containing information about the Google accounts. (Default: ./.accounts.json)
    • --credentials-dir: Directory where OAuth credentials (e.g., .oauth.{email}.json) are stored. (Default: current working directory)
    uv run mcp-gsuite --gauth-file /path/to/custom/.gauth.json --accounts-file /path/to/custom/.accounts.json --credentials-dir /path/to/custom/credentials
  9. Configure authentication file paths via CLI flags

    main

    The mcp-gsuite authentication utilities allow customizing the locations of sensitive configuration files using command-line arguments. These flags are parsed using argparse and can be passed when running the application:

    • --gauth-file: Specifies the path to the Google client secrets JSON file. Defaults to ./.gauth.json.
    • --accounts-file: Specifies the path to the accounts configuration JSON file. Defaults to ./.accounts.json.
    • --credentials-dir: Specifies the directory where OAuth2 credential files (e.g., .oauth2.<user_id>.json) are stored. Defaults to the current directory (.).
    # Example usage of CLI flags
    python -m mcp_gsuite.gauth --gauth-file ./config/secrets.json --accounts-file ./config/accounts.json --credentials-dir ./auth_storage
  10. Query Gmail emails with `query_gmail_emails`

    main

    Search for Gmail emails using a search query. Results are returned in reverse chronological order (newest first) and include metadata like subject and a short content summary.

    Arguments:

    • __user_id__ (required): The user identifier.
    • query (optional): A Gmail search query string. Examples:
      • is:unread for unread emails.
      • from:example@gmail.com for specific senders.
      • newer_than:2d for emails from the last 2 days.
      • has:attachment for emails with attachments.
    • max_results (optional): Maximum number of emails to retrieve (1-500). Defaults to 100.
  11. Run the mcp-gsuite server via the main() function

    main

    The mcp-gsuite package provides a main() function that serves as the primary entry point to start the MCP server. It uses asyncio to run the server's main loop. This is useful if you are integrating the server into a Python script or running it directly as a module.

    from mcp_gsuite import main
    
    if __name__ == "__main__":
        main()