关于 google-workspace
面向开发者的 Google Workspace API 技能,涵盖常见服务的调用、认证与配额处理,并提供各 API 的详细参考。
主要功能
- 01覆盖 Gmail、Calendar、Drive 等 API
- 02提供 OAuth 2.0 与服务账号认证模式
- 03说明批量请求与配额处理
- 04包含各 API 的专项参考指南
适用场景
- 01构建邮件与日历自动化
- 02在服务端执行 Workspace API 操作
- 03排查认证、权限或配额错误
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ jezweb/ claude-skills --skill google-workspace安装后在 Claude Code 中输入/google-workspace确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.md.claude-plugin/plugin.jsonreferences/chat-api.mdtemplates/oauth-worker.ts详细介绍
Google Workspace API
状态:已可投入生产 最后更新:2026-01-09 依赖项:Cloudflare Workers(推荐)、Google Cloud 项目 技能版本:1.0.0
快速参考
| API | 常见用途 | 参考 |
|---|---|---|
| Gmail | 电子邮件自动化、收件箱管理 | gmail-api.md |
| Calendar | 活动管理、日程安排 | calendar-api.md |
| Drive | 文件存储、共享 | drive-api.md |
| Sheets | 电子表格数据、报告 | sheets-api.md |
| Docs | 文档生成 | docs-api.md |
| Chat | 机器人、Webhook、空间 | chat-api.md |
| Meet | 视频会议 | meet-api.md |
| Forms | 表单回复、创建 | forms-api.md |
| Tasks | 任务管理 | tasks-api.md |
| Admin SDK | 用户/群组管理 | admin-sdk.md |
| People | 联系人管理 | people-api.md |
通用身份验证模式
所有 Google Workspace API 都使用相同的身份验证机制。请根据使用场景进行选择。
选项 1:OAuth 2.0(用户上下文)
适用于:代表用户执行操作、访问用户专属数据。
// Authorization URL
const authUrl = new URL('https://accounts.google.com/o/oauth2/v2/auth')
authUrl.searchParams.set('client_id', env.GOOGLE_CLIENT_ID)
authUrl.searchParams.set('redirect_uri', `${env.BASE_URL}/callback`)
authUrl.searchParams.set('response_type', 'code')
authUrl.searchParams.set('scope', SCOPES.join(' '))
authUrl.searchParams.set('access_type', 'offline') // For refresh tokens
authUrl.searchParams.set('prompt', 'consent') // Force consent for refresh token
// Token exchange
async function exchangeCode(code: string): Promise<TokenResponse> {
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
code,
client_id: env.GOOGLE_CLIENT_ID,
client_secret: env.GOOGLE_CLIENT_SECRET,
redirect_uri: `${env.BASE_URL}/callback`,
grant_type: 'authorization_code',
}),
})
return response.json()
}
// Refresh token
async function refreshToken(refresh_token: string): Promise<TokenResponse> {
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
refresh_token,
client_id: env.GOOGLE_CLIENT_ID,
client_secret: env.GOOGLE_CLIENT_SECRET,
grant_type: 'refresh_token',
}),
})
return response.json()
}
重要事项:
- 始终请求
access_type=offline以获取刷新令牌 - 使用
prompt=consent确保返回刷新令牌 - 安全存储刷新令牌(Cloudflare KV 或 D1)
- 访问令牌约 1 小时后过期
选项 2:服务账号(服务器到服务器)
适用于:后端自动化、无需用户交互、全网域委派。
import { SignJWT } from 'jose'
async function getServiceAccountToken(
serviceAccount: ServiceAccountKey,
scopes: string[]
): Promise<string> {
const now = Math.floor(Date.now() / 1000)
// Create JWT
const jwt = await new SignJWT({
iss: serviceAccount.client_email,
scope: scopes.join(' '),
aud: 'https://oauth2.googleapis.com/token',
iat: now,
exp: now + 3600,
})
.setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
.sign(await importPKCS8(serviceAccount.private_key, 'RS256'))
// Exchange JWT for access token
const response = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: jwt,
}),
})
const data = await response.json()
return data.access_token
}
全网域委派(模拟用户):
const jwt = await new SignJWT({
iss: serviceAccount.client_email,
sub: '[email protected]', // User to impersonate
scope: scopes.join(' '),
aud: 'https://oauth2.googleapis.com/token',
iat: now,
exp: now + 3600,
})
所需设置:
- 在 Google Cloud Console 中创建服务账号
- 下载 JSON 密钥文件
- 在 Admin Console 中启用全网域委派(如果要模拟用户)
- 将密钥存储为 Cloudflare 密钥(JSON 字符串化)
常见速率限制
所有 Google Workspace API 都会实施配额限制。以下数值为近似值——请查看各 API 的具体限制。
每用户限制(OAuth)
| API | 读取 | 写入 | 备注 |
|---|---|---|---|
| Gmail | 250/user/sec | 250/user/sec | 所有方法的总和 |
| Calendar | 500/user/100sec | 500/user/100sec | 每个日历 |
| Drive | 1000/user/100sec | 1000/user/100sec | |
| Sheets | 100/user/100sec | 100/user/100sec | 低于其他 API |
每项目限制
| API | 每日配额 | 每分钟 | 备注 |
|---|---|---|---|
| Gmail | 1B 单位 | 不定 | 按单位计费(发送 = 100 单位) |
| Calendar | 1M 次查询 | 500/sec | |
| Drive | 1B 次查询 | 1000/sec | |
| Sheets | 无限制 | 500/user/100sec |
处理速率限制
async function withRetry<T>(
fn: () => Promise<T>,
maxRetries = 5
): Promise<T> {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn()
} catch (error: any) {
const status = error.status || error.code
if (status === 429 || status === 503) {
// Rate limited or service unavailable
const retryAfter = error.headers?.get('Retry-After') || Math.pow(2, i)
await new Promise(r => setTimeout(r, retryAfter * 1000))
continue
}
if (status === 403 && error.message?.includes('rateLimitExceeded')) {
// Quota exceeded - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000))
continue
}
throw error
}
}
throw new Error('Max retries exceeded')
}
批量请求
大多数 Google API 都支持将多个请求合并到一次 HTTP 调用中。
async function batchRequest(
accessToken: string,
requests: BatchRequestItem[]
): Promise<BatchResponse[]> {
const boundary = 'batch_boundary'
let body = ''
requests.forEach((req, i) => {
body += `--${boundary}\r\n`
body += 'Content-Type: application/http\r\n'
body += `Content-ID: <item${i}>\r\n\r\n`
body += `${req.method} ${req.path} HTTP/1.1\r\n`
body += 'Content-Type: application/json\r\n\r\n'
if (req.body) body += JSON.stringify(req.body)
body += '\r\n'
})
body += `--${boundary}--`
const response = await fetch('https://www.googleapis.com/batch/v1', {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': `multipart/mixed; boundary=${boundary}`,
},
body,
})
// Parse multipart response...
return parseBatchResponse(await response.text())
}
限制:
- 每批最多 100 个请求(大多数 API)
- 每批最多 1000 个请求(部分 API,例如 Drive)
- 批次中的每个请求都会计入配额
Cloudflare Workers 配置
// wrangler.jsonc
{
"name": "google-workspace-mcp",
"main": "src/index.ts",
"compatibility_date": "2026-01-03",
"compatibility_flags": ["nodejs_compat"],
// Store OAuth tokens
"kv_namespaces": [
{ "binding": "TOKENS", "id": "xxx" }
],
// Or use D1 for structured storage
"d1_databases": [
{ "binding": "DB", "database_name": "workspace-mcp", "database_id": "xxx" }
]
}
需设置的密钥:
echo "your-client-id" | npx wrangler secret put GOOGLE_CLIENT_ID
echo "your-client-secret" | npx wrangler secret put GOOGLE_CLIENT_SECRET
# For service accounts:
cat service-account.json | npx wrangler secret put GOOGLE_SERVICE_ACCOUNT
常见错误
错误:"invalid_grant"(刷新令牌时)
原因:刷新令牌已撤销或过期(6 个月未使用) 解决方法:重新验证用户身份,并请求新的刷新令牌
错误:"access_denied"(OAuth 时)
原因:应用尚未通过验证,或用户不在测试用户列表中 解决方法:将用户添加到 OAuth 同意屏幕的测试用户列表,或完成应用验证
错误:"insufficientPermissions"(403)
原因:缺少必要的 scope 解决方法:检查授权 URL 中的 scope,使用正确的 scope 重新验证身份
错误:"rateLimitExceeded"(403)
原因:超出配额 解决方法:实施指数退避、降低请求频率、申请提高配额
错误:“notFound”(404),资源已知
原因:使用了错误的 API 版本,或资源位于回收站中 解决方法:检查 URL 中的 API 版本,检查回收站中是否有已删除的项目
特定 API 指南
references/ 目录中包含各个 API 的详细使用模式。使用特定 API 时,请加载相应文档。
Gmail API
- 邮件的 CRUD 操作、标签、会话
- MIME 处理、附件
- 推送通知(Pub/Sub)
Calendar API
- 事件的 CRUD 操作、重复事件
- 空闲/忙碌查询
- 日历共享
Drive API
- 文件上传/下载
- 权限、共享
- 搜索查询
Sheets API
- 读取/写入单元格
- A1 表示法、范围
- 批量更新
Chat API
- 机器人、Webhook
- Cards v2、交互式表单
- 空间、成员、回应
(随着 MCP 服务的构建,将添加更多 API 参考文档)
软件包版本(已于 2026-01-09 验证)
{
"devDependencies": {
"@cloudflare/workers-types": "^4.20260109.0",
"wrangler": "^4.58.0",
"jose": "^6.1.3"
}
}
官方文档
- Google Workspace API:https://developers.google.com/workspace
- OAuth 2.0:https://developers.google.com/identity/protocols/oauth2
- 服务账号:https://cloud.google.com/iam/docs/service-accounts
- API Explorer:https://developers.google.com/apis-explorer
- 配额信息中心:https://console.cloud.google.com/iam-admin/quotas
技能路线图
将 API 文档化为 MCP 服务时:
- Gmail API
- Calendar API
- Drive API
- Sheets API
- Docs API
- Chat API(从 google-chat-api 技能迁移)
- Meet API
- Forms API
- Tasks API
- Admin SDK
- People API