mcpField
G
google-workspace-cli

google-workspace-cli

github.com/hoodini生产力291455 次安装今天更新
代码仓库

关于 google-workspace-cli

google-workspace-cli(gws)是面向用户和 AI Agent 的 Google Workspace 命令行工具,可通过动态读取 Discovery Service 构建命令。它提供结构化 JSON 输出,并附带 100 多个 Agent 技能;项目并非 Google 官方支持产品。

主要功能

  1. 01覆盖多种 Google Workspace 服务
  2. 02根据 Discovery Service 动态生成命令
  3. 03结构化 JSON 输出
  4. 04支持多账号和 OAuth 登录
  5. 05提供 100 多个 Agent 技能
  6. 06支持分页与请求预览

适用场景

  1. 01通过命令行管理 Drive 文件
  2. 02查询 Gmail 邮件与 Calendar 事件
  3. 03读写 Sheets、Docs 和 Slides
  4. 04让 AI Agent 调用 Workspace API

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/hoodini/ai-agents-skills --skill google-workspace-cli

安装后在 Claude Code 中输入/google-workspace-cli确认已加载。

详细介绍

Google Workspace CLI(gws)

一个 CLI,涵盖 所有 Google Workspace 服务 — Drive、Gmail、Calendar、Sheets、Docs、Slides、Chat、Tasks、Admin、Meet、Forms、Keep 以及所有其他 Workspace API。专为人类和 AI Agent 打造。支持结构化 JSON 输出。内置 100 多项 Agent 技能。

注意: 这不是 Google 官方支持的产品。

重要: 此项目正在积极开发中。随着我们朝着 v1.0 迈进,可能会有破坏性变更。

代码库: https://github.com/googleworkspace/cli

工作原理

gws 不会附带静态命令列表。它会在运行时读取 Google 自己的 Discovery Service,并动态构建完整的命令界面。Google 添加新的 API 端点或方法时,gws 会自动获取 — 无需任何更新。

前提条件

  • Node.js 18+ — 用于运行 npm install(也可以从 GitHub Releases 下载预构建二进制文件)
  • Google Cloud 项目 — OAuth 凭据必需。你可以通过 Google Cloud Console、gcloud CLI 或 gws auth setup 命令创建项目。
  • Google 账号 — 可访问 Google Workspace

安装

# Install globally via npm (recommended — bundles native binaries, no Rust needed)
npm install -g @googleworkspace/cli

# Verify installation
gws --version

其他安装方式:

# From GitHub Releases (pre-built binaries)
# Download from: https://github.com/googleworkspace/cli/releases

# Build from source (requires Rust toolchain)
cargo install --git https://github.com/googleworkspace/cli --locked

# Nix flake
nix run github:googleworkspace/cli

快速开始

gws auth setup     # walks you through Google Cloud project config
gws auth login     # subsequent OAuth login
gws drive files list --params '{"pageSize": 5}'

身份验证

我应该使用哪种设置方式?
我有……使用
已安装并完成身份验证的 gcloudgws auth setup(最快 — 一条命令即可)
GCP 项目,但没有 gcloud在 Cloud Console 中手动设置 OAuth
现有 OAuth 访问令牌GOOGLE_WORKSPACE_CLI_TOKEN 环境变量
现有凭据 JSON(服务账号或导出的凭据)GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE 环境变量
快速设置(推荐 — 需要 gcloud CLI)
gws auth setup       # one-time: creates a Cloud project, enables APIs, logs you in
gws auth login       # subsequent logins with scope selection

凭据在静态存储时会使用 AES-256-GCM 加密,密钥存储在操作系统的密钥环中。

限定范围的登录(适用于未经验证/测试中的 OAuth 应用,最多约 25 个范围)

警告: 未经验证(测试模式)的应用最多只能使用约 25 个 OAuth 范围。recommended 范围预设包含 85 个以上的范围,未经验证的应用使用时会失败(尤其是 @gmail.com 账号)。请改为选择单项服务:

# Select only the services you need to stay under the scope limit
gws auth login -s drive,gmail,sheets
gws auth login --scopes drive,gmail,calendar,docs,chat
多个账号
gws auth login --account [email protected]
gws auth login --account [email protected]

gws auth list                                    # list registered accounts
gws auth default [email protected]                   # set the default

gws --account [email protected] drive files list  # one-off override
export [email protected]  # env var override

凭据会按账号存储为 ~/.config/gws/ 中的 credentials.<b64-email>.enc,并通过 accounts.json 注册表跟踪默认账号。

手动设置 OAuth(不使用 gcloud)

当 gws auth setup 无法自动创建项目/客户端,或你希望明确控制设置过程时,请使用此方法。

  1. 在目标项目中打开 Google Cloud Console:
    • OAuth 同意屏幕:https://console.cloud.google.com/apis/credentials/consent?project=<PROJECT_ID>
    • 凭据:https://console.cloud.google.com/apis/credentials?project=<PROJECT_ID>
  2. 根据提示配置 OAuth 品牌信息/受众群体 — 应用类型:外部(测试模式即可)
  3. 在 测试用户 下添加你的账号
  4. 创建 OAuth 客户端 — 类型:桌面应用
  5. 下载客户端 JSON → 保存到 ~/.config/gws/client_secret.json

重要: 你必须将自己添加为测试用户。在 OAuth 同意屏幕中,点击 测试用户 → 添加用户,然后输入你的 Google 账号邮箱。否则,登录时会出现笼统的“访问遭到屏蔽”错误。

然后运行:

gws auth login
无头模式/CI
# On a machine with a browser:
gws auth export --unmasked > credentials.json

# On the headless machine:
export GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE=/path/to/credentials.json
gws drive files list   # just works
服务账号(服务器到服务器)
export GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE=/path/to/service-account.json
gws drive files list

# For Domain-Wide Delegation:
export [email protected]
预先获取的访问令牌
export GOOGLE_WORKSPACE_CLI_TOKEN=$(gcloud auth print-access-token)
浏览器辅助式身份验证(适用于 AI Agent)

Agent 可以通过浏览器自动化完成 OAuth:

  • **人工流程:**运行 gws auth login,打开打印出的 URL,并批准授权范围。
  • **Agent 辅助流程:**Agent 打开 URL,选择账号,处理授权提示,并在本地主机回调成功后交还控制权。

如果授权提示显示“Google 尚未验证此应用”(测试模式),请点击 继续。如果出现授权范围复选框,请在继续之前选择所需范围(或选择 全选)。

身份验证优先级
优先级方法来源
1访问令牌GOOGLE_WORKSPACE_CLI_TOKEN
2凭据文件GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE
3每个账号单独加密的凭据gws auth login --account EMAIL
4明文凭据~/.config/gws/credentials.json

账号解析顺序:--account 标志 > GOOGLE_WORKSPACE_CLI_ACCOUNT 环境变量 > accounts.json 中的默认值。

所有环境变量也可以放在项目根目录的 .env 文件中。

命令结构

所有 gws 命令的通用模式:

gws <service> <resource> <method> [--params '{ JSON }'] [--json '{ JSON }'] [flags]
全局标志
标志说明
--help显示任意服务、资源或方法的帮助信息
--params '{ JSON }'以 JSON 格式指定 URL/查询参数
--json '{ JSON }'以 JSON 格式指定请求正文
--dry-run预览 HTTP 请求,但不执行
--page-all自动翻页,每页输出一行 JSON(NDJSON)
--page-limit <N>最多获取的页数(默认值:10)
--page-delay <MS>翻页间隔(默认值:100ms)
--upload <path>多部分文件上传
--account <email>使用指定的已认证账号
--sanitize <template>使用 Model Armor 清理响应内容
检查架构
# See the full request/response schema for any method
gws schema drive.files.list
gws schema gmail.users.messages.send
gws schema calendar.events.insert

核心服务——命令与示例

Google Drive
# List files (paginated)
gws drive files list --params '{"pageSize": 10}'

# List ALL files (auto-paginate as NDJSON)
gws drive files list --params '{"pageSize": 100}' --page-all

# Search for files
gws drive files list --params '{"q": "name contains '\''report'\'' and mimeType = '\''application/pdf'\''", "pageSize": 20}'

# Get file metadata
gws drive files get --params '{"fileId": "FILE_ID"}'

# Upload a file
gws drive files create --json '{"name": "report.pdf", "parents": ["FOLDER_ID"]}' --upload ./report.pdf

# Create a folder
gws drive files create --json '{"name": "Project Docs", "mimeType": "application/vnd.google-apps.folder"}'

# Move a file to a folder
gws drive files update --params '{"fileId": "FILE_ID", "addParents": "FOLDER_ID", "removeParents": "OLD_PARENT_ID"}'

# Share a file
gws drive permissions create --params '{"fileId": "FILE_ID"}' --json '{"role": "writer", "type": "user", "emailAddress": "[email protected]"}'

# Download a file (export Google Docs as PDF)
gws drive files export --params '{"fileId": "FILE_ID", "mimeType": "application/pdf"}'

# Delete a file
gws drive files delete --params '{"fileId": "FILE_ID"}'

# List shared drives
gws drive drives list --params '{"pageSize": 10}'

# Create a shared drive
gws drive drives create --params '{"requestId": "unique-id"}' --json '{"name": "Team Drive"}'
Gmail
# List messages in inbox
gws gmail users messages list --params '{"userId": "me", "maxResults": 10}'

# Search messages
gws gmail users messages list --params '{"userId": "me", "q": "from:[email protected] is:unread", "maxResults": 20}'

# Get a specific message
gws gmail users messages get --params '{"userId": "me", "id": "MESSAGE_ID"}'

# Send an email
gws gmail users messages send --params '{"userId": "me"}' --json '{
  "raw": "<BASE64_ENCODED_RFC2822_MESSAGE>"
}'

# List labels
gws gmail users labels list --params '{"userId": "me"}'

# Create a label
gws gmail users labels create --params '{"userId": "me"}' --json '{"name": "Important/Projects"}'

# Modify message labels
gws gmail users messages modify --params '{"userId": "me", "id": "MESSAGE_ID"}' --json '{"addLabelIds": ["LABEL_ID"], "removeLabelIds": ["INBOX"]}'

# Trash a message
gws gmail users messages trash --params '{"userId": "me", "id": "MESSAGE_ID"}'

# List drafts
gws gmail users drafts list --params '{"userId": "me"}'

# Create a draft
gws gmail users drafts create --params '{"userId": "me"}' --json '{
  "message": {"raw": "<BASE64_ENCODED_RFC2822_MESSAGE>"}
}'

# Set vacation auto-reply
gws gmail users settings updateVacation --params '{"userId": "me"}' --json '{
  "enableAutoReply": true,
  "responseSubject": "Out of Office",
  "responseBodyPlainText": "I am out of office until March 10.",
  "restrictToContacts": false,
  "restrictToDomain": false
}'
Google Calendar
# List upcoming events
gws calendar events list --params '{"calendarId": "primary", "timeMin": "2026-03-05T00:00:00Z", "maxResults": 10, "singleEvents": true, "orderBy": "startTime"}'

# Get a specific event
gws calendar events get --params '{"calendarId": "primary", "eventId": "EVENT_ID"}'

# Create an event
gws calendar events insert --params '{"calendarId": "primary"}' --json '{
  "summary": "Team Standup",
  "description": "Daily standup meeting",
  "start": {"dateTime": "2026-03-06T09:00:00-05:00", "timeZone": "America/New_York"},
  "end": {"dateTime": "2026-03-06T09:30:00-05:00", "timeZone": "America/New_York"},
  "attendees": [{"email": "[email protected]"}, {"email": "[email protected]"}]
}'

# Update an event
gws calendar events update --params '{"calendarId": "primary", "eventId": "EVENT_ID"}' --json '{
  "summary": "Updated Standup",
  "start": {"dateTime": "2026-03-06T10:00:00-05:00"},
  "end": {"dateTime": "2026-03-06T10:30:00-05:00"}
}'

# Delete an event
gws calendar events delete --params '{"calendarId": "primary", "eventId": "EVENT_ID"}'

# List calendars
gws calendar calendarList list

# Check free/busy
gws calendar freebusy query --json '{
  "timeMin": "2026-03-06T08:00:00Z",
  "timeMax": "2026-03-06T18:00:00Z",
  "items": [{"id": "[email protected]"}, {"id": "[email protected]"}]
}'

# Create a recurring event
gws calendar events insert --params '{"calendarId": "primary"}' --json '{
  "summary": "Weekly Review",
  "recurrence": ["RRULE:FREQ=WEEKLY;BYDAY=FR"],
  "start": {"dateTime": "2026-03-06T16:00:00-05:00", "timeZone": "America/New_York"},
  "end": {"dateTime": "2026-03-06T17:00:00-05:00", "timeZone": "America/New_York"}
}'
Google Sheets

**重要:**Sheets 范围使用 !,bash 会将其解释为历史扩展。请始终用单引号括起取值。

# Create a spreadsheet
gws sheets spreadsheets create --json '{"properties": {"title": "Q1 Budget"}}'

# Read cells
gws sheets spreadsheets values get --params '{"spreadsheetId": "SPREADSHEET_ID", "range": "Sheet1!A1:C10"}'

# Write cells
gws sheets spreadsheets values update --params '{"spreadsheetId": "SPREADSHEET_ID", "range": "Sheet1!A1", "valueInputOption": "USER_ENTERED"}' --json '{"values": [["Name", "Score"], ["Alice", 95], ["Bob", 87]]}'

# Append rows
gws sheets spreadsheets values append --params '{"spreadsheetId": "SPREADSHEET_ID", "range": "Sheet1!A1", "valueInputOption": "USER_ENTERED"}' --json '{"values": [["Charlie", 92]]}'

# Get spreadsheet metadata
gws sheets spreadsheets get --params '{"spreadsheetId": "SPREADSHEET_ID"}'

# Clear a range
gws sheets spreadsheets values clear --params '{"spreadsheetId": "SPREADSHEET_ID", "range": "Sheet1!A1:C10"}'

# Batch update (add sheet, format cells, etc.)
gws sheets spreadsheets batchUpdate --params '{"spreadsheetId": "SPREADSHEET_ID"}' --json '{
  "requests": [
    {"addSheet": {"properties": {"title": "March Data"}}},
    {"repeatCell": {
      "range": {"sheetId": 0, "startRowIndex": 0, "endRowIndex": 1},
      "cell": {"userEnteredFormat": {"textFormat": {"bold": true}}},
      "fields": "userEnteredFormat.textFormat.bold"
    }}
  ]
}'
Google Docs
# Create a document
gws docs documents create --json '{"title": "Meeting Notes"}'

# Get document content
gws docs documents get --params '{"documentId": "DOC_ID"}'

# Update document (insert text)
gws docs documents batchUpdate --params '{"documentId": "DOC_ID"}' --json '{
  "requests": [
    {"insertText": {"location": {"index": 1}, "text": "Hello, World!\n"}}
  ]
}'
Google Slides
# Create a presentation
gws slides presentations create --json '{"title": "Q1 Review"}'

# Get presentation
gws slides presentations get --params '{"presentationId": "PRES_ID"}'

# Add a slide
gws slides presentations batchUpdate --params '{"presentationId": "PRES_ID"}' --json '{
  "requests": [
    {"createSlide": {"slideLayoutReference": {"predefinedLayout": "TITLE_AND_BODY"}}}
  ]
}'
Google Chat
# List spaces
gws chat spaces list

# Send a message to a space
gws chat spaces messages create --params '{"parent": "spaces/SPACE_ID"}' --json '{"text": "Deploy complete."}'

# Get a message
gws chat spaces messages get --params '{"name": "spaces/SPACE_ID/messages/MSG_ID"}'

# List messages in a space
gws chat spaces messages list --params '{"parent": "spaces/SPACE_ID", "pageSize": 25}'

# Create a space
gws chat spaces create --json '{"displayName": "Project Alpha", "spaceType": "SPACE"}'
Google Tasks
# List task lists
gws tasks tasklists list

# Create a task list
gws tasks tasklists insert --json '{"title": "Sprint 42"}'

# List tasks in a list
gws tasks tasks list --params '{"tasklist": "TASKLIST_ID"}'

# Create a task
gws tasks tasks insert --params '{"tasklist": "TASKLIST_ID"}' --json '{"title": "Review PR #123", "due": "2026-03-07T00:00:00Z"}'

# Complete a task
gws tasks tasks update --params '{"tasklist": "TASKLIST_ID", "task": "TASK_ID"}' --json '{"status": "completed"}'
Google Meet
# Create a meeting space
gws meet spaces create --json '{}'

# Get meeting space info
gws meet spaces get --params '{"name": "spaces/SPACE_ID"}'
Google Forms
# Create a form
gws forms forms create --json '{"info": {"title": "Feedback Survey"}}'

# Get form
gws forms forms get --params '{"formId": "FORM_ID"}'

# List responses
gws forms forms responses list --params '{"formId": "FORM_ID"}'
Google Admin(Directory)
# List users
gws admin users list --params '{"domain": "example.com", "maxResults": 100}'

# Get a user
gws admin users get --params '{"userKey": "[email protected]"}'

# Create a user
gws admin users insert --json '{
  "primaryEmail": "[email protected]",
  "name": {"givenName": "Jane", "familyName": "Doe"},
  "password": "TempP@ssw0rd!"
}'

# List groups
gws admin groups list --params '{"domain": "example.com"}'

# Add member to group
gws admin members insert --params '{"groupKey": "[email protected]"}' --json '{"email": "[email protected]", "role": "MEMBER"}'
Google Keep
# List notes
gws keep notes list

# Get a note
gws keep notes get --params '{"name": "notes/NOTE_ID"}'
Google People(联系人与个人资料)
# List contacts
gws people people connections list --params '{"resourceName": "people/me", "personFields": "names,emailAddresses,phoneNumbers", "pageSize": 50}'

# Get a specific contact
gws people people get --params '{"resourceName": "people/PERSON_ID", "personFields": "names,emailAddresses,organizations"}'

# Search contacts
gws people people searchContacts --params '{"query": "Alice", "readMask": "names,emailAddresses"}'

# Create a contact
gws people people createContact --json '{
  "names": [{"givenName": "Jane", "familyName": "Smith"}],
  "emailAddresses": [{"value": "[email protected]"}],
  "phoneNumbers": [{"value": "+1-555-0100"}]
}'

# List directory (domain contacts)
gws people people listDirectoryPeople --params '{"readMask": "names,emailAddresses", "sources": ["DIRECTORY_SOURCE_TYPE_DOMAIN_PROFILE"], "pageSize": 100}'
Google Workspace Events
# Create a subscription to watch for changes
gws events subscriptions create --json '{
  "targetResource": "//calendar.googleapis.com/calendars/primary",
  "eventTypes": ["google.workspace.calendar.event.v1.created"],
  "notificationEndpoint": {"pubsubTopic": "projects/PROJECT/topics/TOPIC"},
  "payloadOptions": {"includeResource": true}
}'

# List subscriptions
gws events subscriptions list

# Delete a subscription
gws events subscriptions delete --params '{"name": "subscriptions/SUB_ID"}'
Google Vault(电子取证)
# List matters
gws vault matters list

# Create a matter
gws vault matters create --json '{"name": "Investigation Q1", "description": "Q1 compliance audit"}'

# Create a hold
gws vault matters holds create --params '{"matterId": "MATTER_ID"}' --json '{
  "name": "Email Hold",
  "corpus": "MAIL",
  "accounts": [{"accountId": "[email protected]"}]
}'
Google Classroom
# List courses
gws classroom courses list

# Create a course
gws classroom courses create --json '{"name": "CS101", "section": "Fall 2026", "ownerId": "me"}'

# List students in a course
gws classroom courses students list --params '{"courseId": "COURSE_ID"}'

# Create coursework
gws classroom courses courseWork create --params '{"courseId": "COURSE_ID"}' --json '{
  "title": "Assignment 1",
  "workType": "ASSIGNMENT",
  "dueDate": {"year": 2026, "month": 3, "day": 15}
}'
管理员报告(审计日志)
# List admin activities
gws admin-reports activities list --params '{"userKey": "all", "applicationName": "admin", "maxResults": 50}'

# List login activities
gws admin-reports activities list --params '{"userKey": "all", "applicationName": "login", "maxResults": 50}'

# List Drive audit logs
gws admin-reports activities list --params '{"userKey": "all", "applicationName": "drive", "maxResults": 50}'
Alert Center(安全警报)
# List alerts
gws alertcenter alerts list

# Get alert details
gws alertcenter alerts get --params '{"alertId": "ALERT_ID"}'
Cloud Identity
# List groups
gws cloudidentity groups list --params '{"parent": "customers/CUSTOMER_ID"}'

# Search groups
gws cloudidentity groups search --params '{"query": "parent == \"customers/CUSTOMER_ID\""}'

# List memberships
gws cloudidentity groups memberships list --params '{"parent": "groups/GROUP_ID"}'
Groups Settings
# Get group settings
gws groupssettings groups get --params '{"groupUniqueId": "[email protected]"}'

# Update group settings
gws groupssettings groups update --params '{"groupUniqueId": "[email protected]"}' --json '{
  "whoCanPostMessage": "ALL_MEMBERS_CAN_POST",
  "messageModerationLevel": "MODERATE_NONE"
}'
Licensing
# List license assignments
gws licensing licenseAssignments listForProduct --params '{"productId": "Google-Apps", "customerId": "CUSTOMER_ID"}'

# Assign a license
gws licensing licenseAssignments insert --params '{"productId": "Google-Apps", "skuId": "SKU_ID"}' --json '{"userId": "[email protected]"}'
Reseller
# List subscriptions
gws reseller subscriptions list --params '{"customerId": "CUSTOMER_ID"}'

# Get a subscription
gws reseller subscriptions get --params '{"customerId": "CUSTOMER_ID", "subscriptionId": "SUB_ID"}'
Apps Script
# List projects
gws apps-script projects list

# Get project content
gws apps-script projects getContent --params '{"scriptId": "SCRIPT_ID"}'

# Deploy a project
gws apps-script projects deployments create --params '{"scriptId": "SCRIPT_ID"}' --json '{"versionNumber": 1}'

# Run a function
gws apps-script scripts run --params '{"scriptId": "SCRIPT_ID"}' --json '{"function": "myFunction", "parameters": []}'

工作流助手(快捷命令)

gws 附带更高层级的助手命令,可处理最常见的多步骤操作:

# --- Drive ---
# Upload a file to Drive with automatic metadata
gws drive-upload ./report.pdf

# --- Sheets ---
# Append a row to a sheet
gws sheets-append --spreadsheet-id ID --range 'Sheet1!A1' --values '[["Name", "Score"]]'

# Read sheet values
gws sheets-read --spreadsheet-id ID --range 'Sheet1!A1:C10'

# --- Gmail ---
# Send an email (simplified)
gws gmail-send --to [email protected] --subject "Hello" --body "Hi there"

# Triage inbox — show unread summary (sender, subject, date)
gws gmail-triage

# Watch for new emails and stream them as NDJSON
gws gmail-watch

# --- Calendar ---
# Show upcoming calendar agenda across all calendars
gws calendar-agenda

# Insert a calendar event quickly
gws calendar-insert --summary "Lunch" --start "2026-03-06T12:00:00" --end "2026-03-06T13:00:00"

# --- Docs ---
# Append text to a Google Doc
gws docs-write --document-id DOC_ID --text "New paragraph here"

# --- Chat ---
# Send a Chat message to a space
gws chat-send --space "spaces/SPACE_ID" --text "Hello team!"

# --- Apps Script ---
# Upload local files to an Apps Script project
gws apps-script-push --script-id SCRIPT_ID --source ./src

# --- Workspace Events ---
# Subscribe to Workspace events and stream them as NDJSON
gws events-subscribe --target "//calendar.googleapis.com/calendars/primary" --event-types "google.workspace.calendar.event.v1.created"

# Renew/reactivate Workspace Events subscriptions
gws events-renew --subscription-id SUB_ID

# --- Model Armor ---
# Sanitize a user prompt through a Model Armor template
gws modelarmor-sanitize-prompt --template "projects/P/locations/L/templates/T" --text "user input here"

# Sanitize a model response through a Model Armor template
gws modelarmor-sanitize-response --template "projects/P/locations/L/templates/T" --text "model output here"

# Create a new Model Armor template
gws modelarmor-create-template --project PROJECT --location LOCATION --template-id my-template

# --- Cross-service Workflows ---
# Today's standup report (meetings + open tasks)
gws workflow-standup-report

# Meeting prep (agenda, attendees, linked docs)
gws workflow-meeting-prep

# Convert email to task
gws workflow-email-to-task --message-id MSG_ID

# Weekly digest (meetings + unread count)
gws workflow-weekly-digest

# Announce a Drive file in a Chat space
gws workflow-file-announce --file-id FILE_ID --space "spaces/SPACE_ID"

将 gws 技能安装到 Agent 项目中

gws 仓库附带 100 多个 SKILL.md 文件,可直接安装到 Agent 的技能目录中:

# Install ALL gws skills at once
npx skills add https://github.com/googleworkspace/cli

# Or pick only what you need
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/gws-drive
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/gws-gmail
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/gws-calendar
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/gws-sheets
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/gws-docs
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/gws-chat
OpenClaw 设置
# Symlink all skills (stays in sync with repo)
ln -s $(pwd)/skills/gws-* ~/.openclaw/skills/

# Or copy specific skills
cp -r skills/gws-drive skills/gws-gmail ~/.openclaw/skills/

如果 PATH 中找不到 gws,gws-shared 技能包含一个 install 块,可让 OpenClaw 通过 npm 自动安装 CLI。

此操作会将 SKILL.md 文件放入项目的 .github/skills/(Copilot)、.claude/skills/(Claude Code)或相应目录中,为 Agent 提供各服务的深入知识。

Persona(基于角色的技能包)

gws 仓库包含 10 个预构建的 Persona 技能包,可组合多项服务以满足常见角色的需求:

Persona描述使用的服务
persona-exec-assistant管理高管的日程安排、收件箱和沟通Calendar、Gmail、Chat、Tasks
persona-project-manager协调项目——跟踪任务、安排会议、共享文档Tasks、Calendar、Drive、Chat
persona-hr-coordinator处理 HR 工作流——入职、公告和员工沟通Admin、Gmail、Calendar、Docs
persona-sales-ops管理销售工作流——跟踪交易、安排通话、与客户沟通Sheets、Gmail、Calendar、Chat
persona-it-admin管理 IT——管理用户、监控安全、配置 WorkspaceAdmin、Alert Center、Cloud Identity
persona-content-creator在 Workspace 中创建、整理和分发内容Docs、Slides、Drive、Gmail
persona-customer-support管理客户支持——跟踪工单、回复并升级问题Gmail、Sheets、Chat、Tasks
persona-event-coordinator策划和管理活动——安排日程、发送邀请并处理后勤Calendar、Gmail、Drive、Chat
persona-team-lead领导团队——主持站会、协调任务并沟通Calendar、Tasks、Chat、Gmail
persona-researcher整理研究资料——管理参考文献、笔记和协作Drive、Docs、Keep、Sheets

安装 Persona:

npx skills add https://github.com/googleworkspace/cli/tree/main/skills/persona-exec-assistant
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/persona-it-admin

配方(多步骤任务序列)

gws 仓库附带 50 个精选配方——包含实际命令的多步骤任务序列。主要配方:

配方功能
recipe-audit-external-sharing查找并检查组织外共享的 Drive 文件
recipe-label-and-archive-emails为匹配的邮件应用 Gmail 标签并将其归档
recipe-send-personalized-emails从 Sheets 读取内容,为每一行发送个性化 Gmail 邮件
recipe-draft-email-from-doc读取 Google Doc,并将其用作 Gmail 邮件正文
recipe-organize-drive-folder创建文件夹结构并将文件移动到相应位置
recipe-share-folder-with-team与协作者共享 Drive 文件夹
recipe-email-drive-link共享文件并通过邮件发送链接
recipe-create-doc-from-template复制 Docs 模板、填写内容并共享
recipe-create-expense-tracker设置用于追踪费用的 Sheets
recipe-block-focus-time在 Calendar 中创建定期专注时段
recipe-reschedule-meeting更改活动时间并通知参会者
recipe-search-and-export-emails查找匹配的 Gmail 邮件并导出
recipe-create-gmail-filter自动为收到的邮件添加标签或星标
recipe-cancel-and-notify删除活动并发送取消邮件
recipe-find-free-time查询多位用户的忙闲状态
recipe-bulk-download-folder下载 Drive 文件夹中的所有文件
recipe-find-large-files找出占用存储空间的大型 Drive 文件
recipe-create-shared-drive创建 Shared Drive 并添加成员
recipe-transfer-file-ownership在用户之间转移 Drive 文件所有权
recipe-post-mortem-setup创建 Doc、安排 Calendar 复盘并通过 Chat 通知
recipe-save-email-attachments将 Gmail 附件保存到 Drive
recipe-send-team-announcement同时通过 Gmail 和 Chat 发布公告
recipe-create-feedback-form创建 Form 并通过 Gmail 分享
recipe-sync-contacts-to-sheet将联系人目录导出到 Sheets
recipe-create-events-from-sheet读取 Sheets 数据并创建 Calendar 活动
recipe-generate-report-from-sheet读取 Sheets 数据并创建 Docs 报告
recipe-save-email-to-doc将 Gmail 邮件正文归档到 Doc 中
recipe-batch-reply-to-emails查找匹配的邮件并发送标准回复
recipe-batch-rename-files将 Drive 文件重命名为统一格式
recipe-create-vacation-responder启用 Gmail 自动休假回复
recipe-triage-security-alerts检查 Workspace 安全警报
recipe-deploy-apps-script将本地文件推送到 Apps Script 项目
recipe-create-meet-space创建 Meet 空间并分享加入链接
recipe-create-presentation创建 Slides 演示文稿并添加初始幻灯片
recipe-create-classroom-course创建 Classroom 课程并邀请学生

安装配方:

npx skills add https://github.com/googleworkspace/cli/tree/main/skills/recipe-send-personalized-emails
npx skills add https://github.com/googleworkspace/cli/tree/main/skills/recipe-audit-external-sharing

完整列表:https://github.com/googleworkspace/cli/blob/main/docs/skills.md

MCP 服务集成

gws mcp 会通过 stdio 启动 Model Context Protocol 服务,将 Google Workspace API 作为结构化工具提供给任何兼容 MCP 的客户端。

# Start MCP server for specific services
gws mcp -s drive                  # Drive only
gws mcp -s drive,gmail,calendar   # multiple services
gws mcp -s all                    # all services (many tools!)

# Include workflow and helper tools
gws mcp -s drive,gmail -w -e

# Compact tool mode — reduces context window usage for LLMs
gws mcp -s drive,gmail --compact
MCP 客户端配置

VS Code / Copilot(settings.json 或 .vscode/mcp.json):

{
  "mcpServers": {
    "gws": {
      "command": "gws",
      "args": ["mcp", "-s", "drive,gmail,calendar,sheets,docs"]
    }
  }
}

Claude Desktop(claude_desktop_config.json):

{
  "mcpServers": {
    "gws": {
      "command": "gws",
      "args": ["mcp", "-s", "drive,gmail,calendar,sheets,docs"]
    }
  }
}

Cursor(.cursor/mcp.json):

{
  "mcpServers": {
    "gws": {
      "command": "gws",
      "args": ["mcp", "-s", "drive,gmail,calendar"]
    }
  }
}

Gemini CLI 扩展:

gws auth setup
gemini extensions install https://github.com/googleworkspace/cli

安装 Gemini 扩展后,Gemini CLI Agent 即可直接访问所有 gws 命令和技能。该扩展会自动继承终端凭据。

提示: 每项服务会增加约 10–80 个工具。请仅保留实际需要的工具,以免超过客户端的工具数量上限(通常为 50–100 个工具)。使用 --compact 标志可减少上下文窗口占用。

MCP 标志
标志描述
-s, --services <list>要公开的服务,以逗号分隔;也可使用 all
-w, --workflows同时公开工作流工具
-e, --helpers同时公开辅助工具
--compact紧凑工具模式 — 缩短工具描述以节省上下文窗口

高级用法

Dry Run(预览请求但不执行)
gws drive files list --params '{"pageSize": 5}' --dry-run
分页
# Auto-paginate everything as NDJSON
gws drive files list --params '{"pageSize": 100}' --page-all

# Limit pages
gws drive files list --params '{"pageSize": 100}' --page-all --page-limit 5

# Delay between pages (rate limiting)
gws drive files list --params '{"pageSize": 100}' --page-all --page-delay 200
管道与输出处理

所有输出均为结构化 JSON。使用 jq 进行处理:

# Get just file names
gws drive files list --params '{"pageSize": 100}' --page-all | jq -r '.files[].name'

# Get unread email subjects
gws gmail users messages list --params '{"userId": "me", "q": "is:unread", "maxResults": 5}' | jq '.messages[].id'

# Count events this week
gws calendar events list --params '{"calendarId": "primary", "timeMin": "2026-03-02T00:00:00Z", "timeMax": "2026-03-08T00:00:00Z", "singleEvents": true}' | jq '.items | length'
Multipart 上传
gws drive files create --json '{"name": "report.pdf"}' --upload ./report.pdf
Model Armor(响应净化)

在 API 响应到达 Agent 之前,扫描其中的提示词注入:

gws gmail users messages get --params '{"userId": "me", "id": "MSG_ID"}' \
  --sanitize "projects/P/locations/L/templates/T"
环境变量描述
GOOGLE_WORKSPACE_CLI_SANITIZE_TEMPLATE默认 Model Armor 模板
GOOGLE_WORKSPACE_CLI_SANITIZE_MODEwarn(默认)或 block

Agent 决策指南

根据用户的需求,使用此表决定运行哪个 gws 命令:

用户意图服务示例命令
列出、搜索、上传、下载和共享文件drivegws drive files list
创建文件夹、管理权限drivegws drive files create、gws drive permissions create
阅读、发送、搜索和标记电子邮件gmailgws gmail users messages list/send
创建草稿、管理过滤器gmailgws gmail users drafts create
查看、创建、更新和删除日历活动calendargws calendar events list/insert/update/delete
检查可用时间/忙闲状态calendargws calendar freebusy query
读取、写入和追加电子表格数据sheetsgws sheets spreadsheets values get/update/append
创建电子表格、设置单元格格式sheetsgws sheets spreadsheets create/batchUpdate
创建、读取和编辑文档docsgws docs documents create/get/batchUpdate
创建和编辑演示文稿slidesgws slides presentations create/batchUpdate
发送消息、管理聊天空间chatgws chat spaces messages create
管理任务和待办事项列表tasksgws tasks tasks list/insert/update
创建会议链接meetgws meet spaces create
创建表单、读取回复formsgws forms forms create、gws forms forms responses list
管理联系人和个人资料peoplegws people people connections list
管理用户、群组和设备admingws admin users list、gws admin groups list
管理笔记keepgws keep notes list
运行/部署 Apps Script 项目apps-scriptgws apps-script projects list
审计日志和使用情况报告admin-reportsgws admin-reports activities list
管理安全警报alertcentergws alertcenter alerts list
管理身份和群组cloudidentitygws cloudidentity groups list
订阅 Workspace 事件eventsgws events subscriptions create
管理 Google Vault(电子取证)vaultgws vault matters list
管理 Workspace 许可证licensinggws licensing licenseAssignments list
管理 Google Classroomclassroomgws classroom courses list
配置 Google Groups 设置groupssettingsgws groupssettings groups get/update
管理 Workspace 订阅resellergws reseller subscriptions list
净化内容以确保安全modelarmorgws modelarmor-sanitize-prompt

环境变量参考

变量描述
GOOGLE_WORKSPACE_CLI_TOKEN预先获取的 OAuth 访问令牌
GOOGLE_WORKSPACE_CLI_CREDENTIALS_FILE凭据 JSON 文件的路径(服务账号或导出的凭据)
GOOGLE_WORKSPACE_CLI_ACCOUNT默认账号邮箱
GOOGLE_WORKSPACE_CLI_IMPERSONATED_USER要模拟的用户(全网域委派)
GOOGLE_WORKSPACE_CLI_SANITIZE_TEMPLATE默认 Model Armor 模板
GOOGLE_WORKSPACE_CLI_SANITIZE_MODEwarn 或 block

故障排查

错误解决方法
登录期间出现“Access blocked”或 403在 OAuth 同意屏幕中将自己添加为测试用户
“Google hasn't verified this app”点击 Advanced → Continue(个人使用安全)
范围过多错误使用 gws auth login -s drive,gmail,sheets 选择较少的服务
未找到 gcloud CLI安装 gcloud,或在 Cloud Console 中手动设置 OAuth
redirect_uri_mismatch重新创建 OAuth 客户端,并选择 Desktop 应用类型
accessNotConfigured查看下方的详细解决方法
凭据过期运行 gws auth login 重新进行身份验证
API 未启用 — accessNotConfigured

如果 GCP 项目未启用所需的 Google API,你会看到 403 错误:

{
  "error": {
    "code": 403,
    "message": "Gmail API has not been used in project 549352339482 ...",
    "reason": "accessNotConfigured",
    "enable_url": "https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=549352339482"
  }
}

gws 还会在 stderr 中打印可操作的提示:

💡 API not enabled for your GCP project.
   Enable it at: https://console.developers.google.com/apis/api/gmail.googleapis.com/overview?project=549352339482
   After enabling, wait a few seconds and retry your command.

解决步骤:

  1. 点击 enable_url 链接(或从 JSON 的 enable_url 字段中复制该链接)。
  2. 在 GCP Console 中,点击 Enable。
  3. 等待约 10 秒,然后重试 gws 命令。

提示: 你也可以运行 gws auth setup,它会引导你自动为项目启用所有必需的 API。

架构

gws 使用两阶段解析策略:

  1. 读取 argv[1] 以识别服务(例如 drive)
  2. 获取该服务的 Discovery Document(缓存 24 小时)
  3. 根据文档中的资源和方法构建 clap::Command 树
  4. 重新解析剩余参数
  5. 进行身份验证、构建 HTTP 请求并执行

所有输出——成功信息、错误和下载元数据——都采用结构化 JSON。这意味着 Agent 可以直接解析每个响应,无需提取文本。

资源

许可证

Apache-2.0

评论

支持 Markdown