Google Workspace CLI

repository·main·Indexed 12 days ago

https://github.com/googleworkspace/cli

A command-line interface for Google Workspace that dynamically builds its command surface from Google's Discovery Service. It allows developers and AI agents to interact with APIs like Drive, Gmail, and Calendar using structured JSON output, schema introspection, and specialized helper commands for multi-step orchestration.

Tokens
72.1K
Snippets
276
Records
371
Agent score
91%

What's inside gws

  1. Use the google-workspace Rust library

    main

    The google-workspace crate is a core Rust library for interacting with Google Workspace APIs using dynamic discovery. Instead of using pre-generated client crates, it fetches Google's Discovery Documents at runtime, allowing your code to automatically pick up new or updated API endpoints. It provides foundational types for discovery, service resolution, error handling, and HTTP client management.

    use google_workspace::discovery::fetch_discovery_document;
    use google_workspace::services::resolve_service;
    
    #[tokio::main]
    async fn main() -> anyhow::Result<()> {
        let (api, version) = resolve_service("drive").unwrap();
        let doc = fetch_discovery_document(api, version, None).await?;
    
        println!("{} {} — {} resources",
            doc.name, doc.version,
            doc.resources.len(),
        );
        Ok(())
    }
  2. Explore Google Workspace CLI Skills

    main

    The gws CLI is organized into 'Skills', which are functional bundles for interacting with Google Workspace. Skills are categorized into three main types:

    1. Services: Core Google Workspace API skills that provide direct access to specific services (e.g., gws-drive, gws-sheets, gws-gmail, gws-calendar).
    2. Helpers: Shortcut commands designed for common, high-level operations (e.g., gws-gmail-send for sending emails, gws-sheets-append for adding rows, or gws-drive-upload for uploading files with automatic metadata).
    3. Personas: Role-based bundles that combine multiple services and helpers to automate specific professional workflows (e.g., persona-exec-assistant for schedule and inbox management, or persona-project-manager for task and meeting coordination).

    You can use these skills to build automation, scripts, or interactive agents that interact with the Google Workspace ecosystem.

  3. Core Syntax of the Google Workspace CLI (`gws`)

    main

    The gws CLI uses a hierarchical command structure based on the Google Workspace service, resource, and method. You can traverse the help system at any level of the hierarchy to discover available commands and flags.

    Command Structure:

    gws <service> <resource> [sub-resource] <method> [flags]

    Help Discovery:

    • gws --help: Global help
    • gws <service> --help: Service-specific help
    • gws <service> <resource> --help: Resource-specific help
    • gws <service> <resource> <method> --help: Method-specific help
    gws <service> <resource> [sub-resource] <method> [flags]
  4. Choosing between `+sanitize-response` and `+sanitize-prompt`

    main

    When implementing safety layers with Model Armor, choose the command based on the direction of the data flow:

    • Outbound Safety (Model $\rightarrow$ User): Use modelarmor +sanitize-response to clean model outputs before they are shown to users.
    • Inbound Safety (User $\rightarrow$ Model): Use modelarmor +sanitize-prompt to clean user inputs before they are sent to the model.
  5. Design rules for Helper Command flags

    main

    When using or designing helper commands, flags must follow strict rules to prevent the CLI from becoming an unbounded maintenance burden.

    ✅ Good Flags (Orchestration Control)

    Flags should control how the command is orchestrated or which resources are targeted.

    • --spreadsheet, --range: Identifies the resource for operation (e.g., in +read).
    • --to, --subject, --body: Inputs for complex construction (e.g., in +send).
    • --dry-run: Controls whether API calls are actually executed.
    • --subscription: Switches orchestration paths (e.g., "create new" vs. "use existing").
    • --target, --project: Required for multi-service resource creation.

    ❌ Bad Flags (API Parameters or Output Data)

    Do not add flags that simply expose data already present in the API response or duplicate Discovery parameters.

    • Exposing API response data: If a value like thread-id or delivered-to is in the API response, do not add a flag for it. Instead, use --format or jq to extract it.
    • Duplicating Discovery parameters: Do not re-expose parameters like pageSize, fields, or orderBy. Use the --params passthrough instead.

    Decision Checklist for New Flags

    1. Does this flag control what API call to make or how to orchestrate multiple calls? → YES (Add it)
    2. Does this flag control what data appears in output? → NO (Use --format/jq)
    3. Does this flag duplicate a Discovery parameter? → NO (Use --params)
    4. Could the user achieve this with existing flags + post-processing? → NO (Don't add it)
  6. Use helper commands (prefixed with +)

    main

    In addition to standard Discovery-based API methods, gws provides hand-crafted helper commands. These are prefixed with + to distinguish them from standard API methods and are designed for common workflows.

    Key Characteristics:

    • Time-awareness: Helpers like +agenda automatically use your Google account timezone (cached for 24 hours). You can override this with --timezone or --tz.
    • Discovery: Run gws <service> --help to see a combined list of standard methods and helper commands.

    Common Helpers by Service:

    ServiceCommandDescription
    gmail+sendSend an email
    gmail+replyReply to a message (handles threading automatically)
    gmail+triageShow unread inbox summary (sender, subject, date)
    sheets+appendAppend a row to a spreadsheet
    sheets+readRead values from a spreadsheet
    drive+uploadUpload a file with automatic metadata
    calendar+agendaShow upcoming events
    workflow+standup-reportToday's meetings + open tasks as a standup summary
    workflow+weekly-digestWeekly summary: this week's meetings + unread email count
    events+subscribeSubscribe to Workspace events and stream them as NDJSON
    modelarmor+sanitize-promptSanitize a user prompt through a Model Armor template
    # Send an email
    gws gmail +send --to alice@example.com --subject "Hello" --body "Hi there"
    
    # Reply to a message
    gws gmail +reply --message-id MESSAGE_ID --body "Thanks!"
    
    # Append a row to a spreadsheet
    gws sheets +append --spreadsheet SPREADSHEET_ID --values "Alice,95"
    
    # Show today's calendar agenda
    gws calendar +agenda
    
    # Show today's agenda in a specific timezone
    gws calendar +agenda --today --timezone America/New_York
  7. Tips for using gws gmail +reply

    main

    HTML Formatting

    When using the --html flag:

    • Use fragment tags like <p>, <b>, or <a>. Do not include <html> or <body> wrappers.
    • The quoted original message will use Gmail's gmail_quote CSS classes and preserve HTML formatting.
    • Inline images in the quoted message are preserved via cid: references.

    Attachments and Recipients

    • Attachments: Use -a or --attach to add files. This flag can be specified multiple times to attach multiple files.
    • Recipients: The --to flag adds extra recipients to the To field in addition to the original sender.

    Modes of Operation

    • Drafts: Use --draft to save the reply as a draft instead of sending it immediately.
    • Dry Run: Use --dry-run to inspect the request payload without actually sending the email.
    • Reply All: If you need to perform a 'Reply All' instead of a standard reply, use the +reply-all command instead of +reply.
  8. Tips for sending Gmail messages with `gws`

    main

    Formatting and Encoding

    • The CLI automatically handles RFC 5322 formatting, MIME encoding, and base64.
    • When using --html, you do not need <html> or <body> wrappers; you can use fragment tags like <p>, <b>, <a, or <br> directly in the --body.

    Attachments and Aliases

    • Attachments: Use -a or --attach to add files. You can specify this flag multiple times for multiple files. The total size limit is 25MB.
    • Aliases: Use --from to send from a configured 'send-as' alias instead of your primary account address.

    Workflow

    • Drafts: Use --draft to save a message to your Gmail drafts folder instead of sending it immediately.
  9. Input Validation and URL Safety for AI/LLM Agents

    main

    Because this CLI is designed for invocation by AI/LLM agents, all user-supplied inputs must be treated as potentially adversarial. Use the following patterns to ensure safety:

    TaskRequired Method/Pattern
    Accepting a file path (--output-dir, --dir)validate::validate_safe_output_dir() or validate_safe_dir_path()
    Embedding a value in a URL path segmenthelpers::encode_path_segment()
    Passing query parametersUse reqwest .query() builder (never use string interpolation)
    Using a resource name in a URL (--project, --space)helpers::validate_resource_name()
    Accepting an enum flag (--msg-format)Use clap value_parser
  10. Understand the design of Helper Commands (`+verb`)

    main

    The gws CLI is primarily schema-driven, meaning commands are dynamically generated from Google Discovery Documents at runtime.

    Helper Commands (prefixed with +, e.g., +subscribe) are specialized commands designed to complement the Discovery-driven model. They should only be used when a task requires logic that a single API call cannot provide.

    When to use a Helper

    A helper is justified if it performs one of the following:

    • Multi-step orchestration: Chaining multiple API calls (e.g., +subscribe creating a Pub/Sub topic, subscription, and Workspace Events subscription).
    • Format translation: Converting data formats (e.g., +write transforming Markdown into Docs batchUpdate JSON).
    • Multi-API composition: Combining data from different APIs (e.g., +triage listing messages and then fetching metadata).
    • Complex body construction: Building complex payloads like RFC 2822 MIME from simple flags (e.g., +send).
    • Multipart upload: Managing complex protocols like resumable uploads (e.g., +upload).
    • Workflow recipes: Chaining calls across multiple services (e.g., +standup-report).

    Litmus Test: If a user can achieve the same result using gws <service> <resource> <method> --params '{...}', a helper command is not justified.