# https://github.com/taylorwilsdon/google_workspace_mcp 项目说明书

生成时间：2026-05-31 05:38:52 UTC

## 目录

- [项目概述](#project-overview)
- [快速入门指南](#quick-start)
- [系统架构](#system-architecture)
- [认证与授权系统](#authentication-system)
- [Gmail 集成](#gmail-integration)
- [Drive 集成](#drive-integration)
- [Docs/Sheets/Slides 集成](#docs-sheets-slides)
- [Calendar/Contacts/Chat 及其他服务](#calendar-contacts-chat)
- [部署指南](#deployment-guide)
- [CLI 工具与工具层级](#cli-usage)

<a id='project-overview'></a>

## 项目概述

### 相关页面

相关主题：[系统架构](#system-architecture), [快速入门指南](#quick-start)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)
- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [main.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/main.py)
- [core/server.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/server.py)
- [core/tool_registry.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_registry.py)
- [core/api_enablement.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/api_enablement.py)
- [gappsscript/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/README.md)
- [helm-chart/workspace-mcp/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/helm-chart/workspace-mcp/README.md)
</details>

# 项目概述

## 项目简介

Google Workspace MCP 是一个基于 Model Context Protocol (MCP) 的开源集成项目，旨在为 AI 代理提供与 Google Workspace 应用交互的标准化接口。通过该 MCP 服务器，AI 代理可以安全地访问和管理 Google Docs、Sheets、Slides、Gmail、Calendar、Drive、Chat、Forms、Tasks、Contacts 等 Workspace 服务。

该项目由 Taylor Wilsdon 开发和维护，采用 FastMCP 框架构建，支持 OAuth 2.0 认证、灵活的权限控制、多账户管理和跨平台部署。资料来源：[README.md:1-50]()

## 核心功能

### 多服务集成

Google Workspace MCP 提供了对以下 Google Workspace 服务的完整或部分支持：

| 服务类别 | 支持的工具数量 | 核心功能 |
|---------|--------------|---------|
| Docs | 17+ | 文档创建、编辑、导出、评论管理 |
| Sheets | 12+ | 电子表格操作、格式化、条件格式 |
| Slides | 6+ | 演示文稿创建、批量更新 |
| Gmail | 15+ | 邮件发送、搜索、标签管理 |
| Calendar | 10+ | 事件创建、查询、管理 |
| Drive | 20+ | 文件操作、权限管理、导入导出 |
| Chat | 8+ | 消息发送、空间管理、附件下载 |
| Forms | 7+ | 表单创建、响应管理 |
| Tasks | 7+ | 任务列表、任务管理 |
| Contacts | 8+ | 联系人搜索、批量管理 |
| Apps Script | 17+ | 脚本项目管理、执行、部署 |
| Search | 2+ | 自定义搜索集成 |

### 工具分层架构

项目采用三层工具分层设计，通过 `core/tool_tiers.yaml` 配置文件管理：

- **Core（核心层）**：包含每个服务的基本读写操作，是最常用的功能集合
- **Extended（扩展层）**：提供更高级的功能，如格式化、评论管理、批量操作
- **Complete（完整层）**：包含所有可用工具，提供最全面的功能覆盖

```yaml
# 工具分层示例
sheets:
  core:
    - create_spreadsheet
    - read_sheet_values
    - modify_sheet_values
  extended:
    - list_spreadsheets
    - get_spreadsheet_info
  complete:
    - create_sheet
    - append_table_rows
```

资料来源：[core/tool_tiers.yaml:1-80]()

## 技术架构

### 系统架构图

```mermaid
graph TB
    subgraph "客户端层"
        MCP_Client["MCP 客户端<br/>(Claude Desktop / VS Code / 其他)"]
    end
    
    subgraph "认证层"
        OAuth["OAuth 2.0 认证"]
        GoogleProvider["GoogleProvider"]
        Session["会话管理"]
    end
    
    subgraph "服务层"
        Server["FastMCP Server"]
        Registry["工具注册表"]
    end
    
    subgraph "Google Workspace API"
        Drive_API["Drive API"]
        Docs_API["Docs API"]
        Sheets_API["Sheets API"]
        Gmail_API["Gmail API"]
        Calendar_API["Calendar API"]
        Chat_API["Chat API"]
    end
    
    MCP_Client --> Server
    Server --> Registry
    Registry --> OAuth
    OAuth --> GoogleProvider
    Server --> Drive_API
    Server --> Docs_API
    Server --> Sheets_API
    Server --> Gmail_API
    Server --> Calendar_API
    Server --> Chat_API
```

### 核心组件

| 组件 | 文件位置 | 功能描述 |
|-----|---------|---------|
| server.py | core/server.py | FastMCP 服务器初始化、中间件配置、CORS 处理 |
| tool_registry.py | core/tool_registry.py | 条件工具注册系统，支持按层级启用/禁用工具 |
| oauth_config.py | auth/oauth_config.py | OAuth 2.0 配置管理 |
| permissions.py | auth/permissions.py | 权限模式和范围管理 |
| api_enablement.py | core/api_enablement.py | API 启用状态检测和错误处理 |

资料来源：[core/server.py:1-50]()

### 服务装饰器

项目使用 `require_google_service` 装饰器实现服务级别的访问控制：

```python
@require_google_service("drive", "drive_read")
async def list_drives(service, user_google_email: str) -> str:
    """列出用户可访问的所有云端硬盘"""
    ...
```

该装饰器确保只有在 OAuth 授权包含相应范围时，工具才能执行。资料来源：[auth/service_decorator.py]()
## 认证与授权

### OAuth 2.0 认证流程

```mermaid
sequenceDiagram
    participant User as 用户
    participant Client as MCP 客户端
    participant Server as Workspace MCP
    participant Google as Google OAuth
    
    User->>Client: 发起请求
    Client->>Server: 调用工具
    Server->>Server: 检查凭据有效性
    alt 凭据无效或过期
        Server->>Google: 重定向到授权页面
        User->>Google: 完成登录授权
        Google->>Server: 返回授权码
        Server->>Google: 交换访问令牌
        Google->>Server: 返回令牌和刷新令牌
        Server->>Server: 存储凭据
    end
    Server->>Google: 调用 API
    Google->>Client: 返回数据
```

### 多账户支持

项目支持多个 Google 账户的凭据管理，通过 OAuth state 参数区分不同会话。客户端可通过 `user_google_email` 参数指定目标账户：

```python
@require_google_service("drive", "drive_read")
async def list_drives(service, user_google_email: str) -> str:
    """列出指定用户的云端硬盘"""
    ...
```

资料来源：[auth/oauth_config.py]()

## 部署模式

### 本地部署

通过 pip 或 uv 安装后直接运行：

```bash
pip install workspace-mcp
python -m workspace_mcp
```

或使用 uv：

```bash
uv run main.py
```

### Docker 部署

提供官方 Docker 镜像：

```bash
docker pull ghcr.io/taylorwilsdon/workspace-mcp:latest
docker run -p 8000:8000 \
  -e GOOGLE_CLIENT_ID=your_client_id \
  -e GOOGLE_CLIENT_SECRET=your_client_secret \
  ghcr.io/taylorwilsdon/workspace-mcp:latest
```

### Kubernetes 部署

通过 Helm Chart 部署到 Kubernetes 集群：

```bash
helm install workspace-mcp ./helm-chart/workspace-mcp \
  --set secrets.googleOAuth.clientId=your_client_id \
  --set secrets.googleOAuth.clientSecret=your_client_secret
```

支持的配置项：

| 参数 | 描述 | 默认值 |
|-----|------|-------|
| image.tag | 镜像标签 | Chart.AppVersion |
| image.pullPolicy | 镜像拉取策略 | IfNotPresent |
| service.type | Kubernetes 服务类型 | ClusterIP |
| service.port | 服务端口 | 8000 |
| resources.limits.cpu | CPU 限制 | 500m |
| resources.limits.memory | 内存限制 | 512Mi |

资料来源：[helm-chart/workspace-mcp/README.md:1-50]()

## 工具注册机制

### 条件工具注册

项目实现了基于层级的条件工具注册系统：

```python
# core/tool_registry.py
def conditional_tool(server, tool_name: str):
    def decorator(func: Callable) -> Callable:
        if is_tool_enabled(tool_name):
            return server.tool()(func)
        else:
            return func  # 跳过注册
```

通过 `set_enabled_tools()` 可在运行时动态启用/禁用工具集：

```python
set_enabled_tools({"docs", "sheets", "gmail"})  # 仅启用文档、表格和邮件
```

资料来源：[core/tool_registry.py:1-50]()

### 工具注解

每个工具都包含详细的 MCP 注解，帮助客户端理解工具行为：

```python
READ_COMMENT_ANNOTATIONS = ToolAnnotations(
    readOnlyHint=True,
    destructiveHint=False,
    idempotentHint=True,
    openWorldHint=True,
)
```

## API 启用检测

项目实现了智能的 API 启用状态检测：

```python
# core/api_enablement.py
API_ENABLEMENT_LINKS = {
    "drive": "https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com",
    "gmail": "https://console.cloud.google.com/flows/enableapi?apiid=gmail.googleapis.com",
    # ... 更多 API
}
```

当用户尝试使用未启用的 API 时，系统会生成包含直接启用链接的错误消息。资料来源：[core/api_enablement.py:1-80]()

## Google Apps Script 集成

### 功能概述

Apps Script 模块提供 17+ 工具，支持完整的脚本生命周期管理：

| 功能类别 | 工具 | 说明 |
|---------|------|-----|
| 项目管理 | list_script_projects, get_script_project, create_script_project | 列出、获取、创建脚本项目 |
| 内容操作 | get_script_content, update_script_content | 读写脚本文件 |
| 执行 | run_script_function | 执行脚本函数 |
| 部署 | create_deployment, list_deployments, delete_deployment | 管理部署 |
| 版本 | create_version, list_versions, get_version | 版本控制 |
| 监控 | list_script_processes, get_script_metrics | 执行监控 |

资料来源：[gappsscript/README.md:1-100]()

### 使用模式

典型 AI 代理工作流：

```mermaid
graph LR
    A[检查] --> B[分析]
    B --> C[生成]
    C --> D[更新]
    D --> E[执行]
    E --> F[部署]
    F --> G[监控]
```

## CLI 工具

项目提供命令行界面便于调试和集成：

```bash
# 列出所有可用工具
workspace-cli list

# 调用指定工具
workspace-cli call list_drives
```

配置通过环境变量管理：

| 环境变量 | 描述 | 默认值 |
|---------|------|-------|
| WORKSPACE_MCP_URL | MCP 服务器 URL | http://localhost:8000 |
| GOOGLE_CLIENT_ID | OAuth 客户端 ID | - |
| GOOGLE_CLIENT_SECRET | OAuth 客户端密钥 | - |

资料来源：[core/cli.py:1-80]()

## 已知问题与限制

根据社区反馈，以下问题需要注意：

### 认证相关

- **问题 #810**：OAuth callback 将凭据存储在 `google-<state>` 会话中，与 MCP 会话未绑定，导致重新认证后每次工具调用都重新提示授权
- **问题 #667**：Windows 系统上 Python 子进程在父进程异常终止后可能继续运行，导致端口 8000-8004 被占用

### 工具范围问题

- **问题 #809**：`delete_script_project` 和 `create_version` 工具声明了未在 `SCOPE_GROUPS` 中注册的范围别名（`drive_full`、`script_full`），导致 `_resolve_scopes` 失败

### 功能缺失

- **问题 #568**：缺少 `import_to_google_slides` 工具，无法将 PPTX 转换为原生 Google Slides 格式
- **问题 #820**：Office 文件上传时的自动格式转换功能不完整

## 版本历史

| 版本 | 主要变更 |
|-----|---------|
| v1.21.1 | OAuth 登录体验优化，支持浏览器自动打开和 login_hint |
| v1.21.0 | Windows 文件名兼容性修复 |
| v1.20.4 | API 重试逻辑、Drive 详细列表增强 |
| v1.20.3 | 消息发送者识别改进、完整 MCP 工具注解 |

## 快速开始

### 前置要求

1. Python 3.10+
2. Google Cloud Console 项目
3. 已启用相关 Google Workspace API
4. 配置 OAuth 2.0 凭据

### 安装步骤

```bash
# 克隆仓库
git clone https://github.com/taylorwilsdon/google_workspace_mcp.git
cd google_workspace_mcp

# 安装依赖
pip install -e .

# 配置环境变量
export GOOGLE_CLIENT_ID=your_client_id
export GOOGLE_CLIENT_SECRET=your_client_secret

# 运行服务器
python main.py
```

## 相关资源

- **官方文档**：https://workspacemcp.com
- **GitHub 仓库**：https://github.com/taylorwilsdon/google_workspace_mcp
- **问题追踪**：https://github.com/taylorwilsdon/google_workspace_mcp/issues
- **FastMCP 文档**：https://gofastmcp.com

---

<a id='quick-start'></a>

## 快速入门指南

### 相关页面

相关主题：[项目概述](#project-overview), [认证与授权系统](#authentication-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)
- [Dockerfile](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/Dockerfile)
- [docker-compose.yml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/docker-compose.yml)
- [core/cli.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/cli.py)
- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [helm-chart/workspace-mcp/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/helm-chart/workspace-mcp/README.md)
- [gappsscript/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/README.md)
</details>

# 快速入门指南

本指南帮助你在本地环境或服务器上快速部署和运行 Google Workspace MCP（Model Context Protocol）服务。通过本服务，AI Agent 能够与 Google Workspace 各服务（Docs、Sheets、Gmail、Drive、Calendar 等）进行交互，实现自动化工作流程。

## 环境要求

| 组件 | 最低版本 | 推荐版本 |
|------|---------|---------|
| Python | 3.10+ | 3.11+ |
| pip | 21.0+ | 最新版 |
| Docker（可选） | 20.10+ | 24.0+ |
| kubectl（K8s部署） | 1.24+ | 1.28+ |

资料来源：[README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)

## 安装方式

### 方式一：pip 安装

```bash
# 安装稳定版本
pip install workspace-mcp

# 或从源码安装最新版本
git clone https://github.com/taylorwilsdon/google_workspace_mcp.git
cd google_workspace_mcp
pip install -e .
```

资料来源：[README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)

### 方式二：Docker 部署

```bash
# 构建镜像
docker build -t workspace-mcp .

# 运行容器
docker run -p 8000:8000 \
  -e GOOGLE_CLIENT_ID=your_client_id \
  -e GOOGLE_CLIENT_SECRET=your_client_secret \
  workspace-mcp
```

资料来源：[Dockerfile](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/Dockerfile)

### 方式三：Docker Compose 本地开发

```bash
# 启动服务
docker-compose up -d

# 查看日志
docker-compose logs -f

# 停止服务
docker-compose down
```

资料来源：[docker-compose.yml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/docker-compose.yml)

## Google Cloud Console 配置

在运行服务前，需要完成 Google Cloud 项目配置：

### 步骤 1：创建项目

1. 访问 [Google Cloud Console](https://console.cloud.google.com/)
2. 创建新项目或选择现有项目
3. 记录项目 ID

### 步骤 2：启用 API

根据需要启用的功能，启用以下 API：

| 服务功能 | 需要启用的 API |
|---------|---------------|
| Docs | Google Docs API |
| Sheets | Google Sheets API |
| Gmail | Gmail API |
| Drive | Google Drive API |
| Calendar | Google Calendar API |
| Slides | Google Slides API |
| Forms | Google Forms API |
| Chat | Google Chat API |
| Apps Script | Apps Script API |

### 步骤 3：创建 OAuth 2.0 凭据

1. 进入 **APIs & Services > Credentials**
2. 点击 **Create Credentials > OAuth client ID**
3. 选择应用类型：
   - **Web application**：适用于服务器部署
   - **Desktop app**：适用于本地桌面应用
4. 配置授权重定向 URI：
   - 本地开发：`http://localhost:8000/oauth2callback`
   - 生产环境：`http://your-domain:8000/oauth2callback`

### 步骤 4：配置 OAuth 同意屏幕

1. 设置应用名称
2. 添加需要申请的 OAuth 作用域
3. 添加测试用户（如果是内部应用）

资料来源：[README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)

## 服务配置

### 环境变量

| 变量名 | 必需 | 默认值 | 说明 |
|--------|------|--------|------|
| `GOOGLE_CLIENT_ID` | 是 | - | Google OAuth 客户端 ID |
| `GOOGLE_CLIENT_SECRET` | 是 | - | Google OAuth 客户端密钥 |
| `GOOGLE_REDIRECT_URI` | 否 | `http://localhost:8000/oauth2callback` | OAuth 重定向 URI |
| `MCP_ENABLE_OAUTH21` | 否 | `true` | 启用 OAuth 2.1 支持 |
| `TOOLS_ENABLED` | 否 | 全部启用 | 启用的工具列表 |
| `MCP_HOST` | 否 | `0.0.0.0` | 服务监听地址 |
| `MCP_PORT` | 否 | `8000` | 服务监听端口 |

资料来源：[README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)

### Helm Chart 部署（Kubernetes）

```bash
# 添加 Helm 仓库
helm repo add workspace-mcp https://taylorwilsdon.github.io/google_workspace_mcp

# 安装
helm install workspace-mcp workspace-mcp/workspace-mcp \
  --set secrets.googleOAuth.clientId=your_client_id \
  --set secrets.googleOAuth.clientSecret=your_client_secret
```

关键配置参数：

| 参数 | 说明 | 默认值 |
|------|------|--------|
| `secrets.googleOAuth.clientId` | Google OAuth 客户端 ID | 必需 |
| `secrets.googleOAuth.clientSecret` | Google OAuth 客户端密钥 | 必需 |
| `singleUserMode` | 单用户模式 | `false` |
| `service.port` | 服务端口 | `8000` |
| `resources.limits.cpu` | CPU 限制 | `500m` |
| `resources.limits.memory` | 内存限制 | `512Mi` |

资料来源：[helm-chart/workspace-mcp/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/helm-chart/workspace-mcp/README.md)

## 启动服务

### 基本启动

```bash
# 设置环境变量
export GOOGLE_CLIENT_ID=your_client_id
export GOOGLE_CLIENT_SECRET=your_client_secret

# 启动服务
python main.py
```

### 启用特定工具

```bash
# 只启用 Docs 和 Sheets 工具
python main.py --tools docs sheets

# 列出所有可用工具
python main.py --tools help
```

### 指定配置文件

```bash
python main.py --config /path/to/config.yaml
```

资料来源：[README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)

## 工具层级架构

MCP 工具按功能分为三个层级，便于渐进式使用：

```mermaid
graph TD
    A[工具层级] --> B[Core 核心层]
    A --> C[Extended 扩展层]
    A --> D[Complete 完整层]
    
    B --> B1[基础读写操作]
    B --> B2[列表查询功能]
    
    C --> C1[格式化和样式]
    C --> C2[批量操作]
    C --> C3[高级查询]
    
    D --> D1[调试工具]
    D --> D2[评论管理]
    D --> D3[复杂转换]
```

资料来源：[core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)

### 各服务工具层级

| 服务 | Core 核心 | Extended 扩展 | Complete 完整 |
|------|----------|--------------|--------------|
| **Docs** | get_doc_content, create_doc, modify_doc_text | export_doc_to_pdf, search_docs, find_and_replace_doc, list_docs_in_folder | insert_doc_image, update_doc_headers_footers, batch_update_doc, inspect_doc_structure |
| **Sheets** | create_spreadsheet, read_sheet_values, modify_sheet_values | list_spreadsheets, get_spreadsheet_info, format_sheet_range | create_sheet, append_table_rows, resize_sheet_dimensions, manage_conditional_formatting |
| **Gmail** | send_email, get_messages, search_messages, create_label | list_labels, modify_label, get_attachment | manage_gmail_settings |
| **Drive** | list_files, get_file_metadata, create_folder | search_files, update_file, delete_file, share_file | create_drive_shortcut, copy_file |
| **Calendar** | list_calendars, create_event, get_events | update_event, delete_event, list_acl | manage_calendar_settings |
| **Slides** | create_presentation, get_slides | update_slides, list_presentations | batch_update_slides |
| **Chat** | send_message, get_messages, search_messages, create_reaction | list_spaces, download_chat_attachment | - |
| **Forms** | create_form, get_form | list_form_responses | set_publish_settings, get_form_response |
| **Apps Script** | list_script_projects, get_script_project, create_script_project | create_deployment, list_deployments, delete_deployment | run_script_function, list_versions |

资料来源：[core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)

## OAuth 认证流程

### 首次认证流程

```mermaid
sequenceDiagram
    participant User as 用户
    participant MCP as MCP Server
    participant Google as Google OAuth
    participant AI as AI Agent

    User->>MCP: 发起请求（需要认证）
    MCP->>User: 返回授权 URL
    User->>Google: 访问授权页面
    Google->>User: 显示登录/授权页面
    User->>Google: 完成登录授权
    Google->>MCP: 重定向回调 + Authorization Code
    MCP->>Google: 交换访问令牌
    Google->>MCP: 返回 Access Token + Refresh Token
    MCP->>MCP: 存储凭据
    MCP->>AI: 认证成功，继续处理请求
```

### OAuth 2.1 增强功能（v1.21.1+）

最新版本包含以下改进：

- **自动打开浏览器**：首次认证时自动打开授权页面
- **login_hint 支持**：预填充用户邮箱，减少手动输入
- **硬化的主机绑定**：修复了遗留认证模式下的主机绑定问题

```bash
# 设置默认用户邮箱（可选）
export GOOGLE_USER_EMAIL=user@example.com
```

资料来源：[README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)

### 常见认证问题

| 问题 | 原因 | 解决方案 |
|------|------|---------|
| "invalid state" 错误 | OAuth 状态参数不匹配 | 清理浏览器缓存，重新授权 |
| 孤儿进程占用端口 | Windows 非正常终止 | 重启服务或手动结束残留进程 |
| 循环重新认证 | 令牌未正确绑定到 MCP session | 升级到最新版本，启用 OAuth 2.1 |

## CLI 命令行工具

服务提供独立的 CLI 客户端用于测试和调用工具：

```bash
# 列出所有可用工具
workspace-cli list

# 调用指定工具
workspace-cli call get_doc_content document_id=xxx

# 指定 MCP 服务器地址
workspace-cli --url http://localhost:8001 list
```

资料来源：[core/cli.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/cli.py)

### CLI 环境变量

| 变量 | 默认值 | 说明 |
|------|--------|------|
| `WORKSPACE_MCP_URL` | `http://localhost:8000` | MCP 服务器地址 |

## Apps Script 集成

MCP 支持完整的 Apps Script 项目管理：

### 核心功能

- 列出和查看 Apps Script 项目
- 创建新的独立脚本或绑定脚本
- 更新脚本内容（添加/修改 JavaScript 文件）
- 执行脚本函数
- 管理部署和版本

### 工作流程示例

```mermaid
graph LR
    A[创建项目] --> B[编写脚本]
    B --> C[测试执行]
    C --> D{测试结果}
    D -->|成功| E[创建部署]
    D -->|失败| F[调试修复]
    F --> B
    E --> G[设置触发器]
```

### 触发器代码生成

```bash
# 生成时间触发器代码
# In MCP client: "生成一个每分钟执行的触发器代码"
```

生成的代码示例：

```javascript
function createTimeDrivenTriggers() {
  ScriptApp.newTrigger('myFunction')
    .timeBased()
    .everyMinutes(1)
    .create();
}
```

资料来源：[gappsscript/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/README.md)

## 故障排除

### 常见问题

| 问题 | 可能原因 | 解决方法 |
|------|---------|---------|
| 服务启动失败 | 端口被占用 | 检查 8000 端口使用情况，更换端口 |
| API 调用超时 | 网络问题或配额限制 | 检查网络配置，查看 API 配额 |
| 工具未注册 | 工具名称拼写错误 | 使用 `list` 命令查看可用工具 |
| 文件上传失败 | 文件大小超限 | 检查 Google API 文件大小限制 |

### 日志查看

```bash
# Docker 环境
docker logs <container_id>

# 直接运行
python main.py  # 输出到 stdout

# 使用 journalctl (systemd)
journalctl -u workspace-mcp -f
```

### 健康检查

```bash
# 检查服务健康状态
curl http://localhost:8000/health

# Kubernetes 环境
kubectl get pods -l app=workspace-mcp
kubectl describe pod <pod_name>
```

## 安全建议

1. **保护凭据**：不要将 `GOOGLE_CLIENT_SECRET` 提交到代码仓库
2. **最小权限**：只申请必要的 OAuth 作用域
3. **生产环境**：使用 HTTPS 和强密码保护
4. **定期轮换**：定期更换 OAuth 客户端密钥
5. **监控日志**：启用审计日志，记录所有操作

## 下一步

- 阅读 [工具参考文档](docs/tools/) 了解各工具的详细用法
- 查看 [API 文档](docs/api/) 了解 REST API 接口
- 参考 [示例项目](../examples/) 获取使用案例
- 加入 [社区讨论](https://github.com/taylorwilsdon/google_workspace_mcp/discussions) 获取帮助

---

<a id='system-architecture'></a>

## 系统架构

### 相关页面

相关主题：[项目概述](#project-overview), [认证与授权系统](#authentication-system)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [core/server.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/server.py)
- [core/tool_registry.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_registry.py)
- [core/tool_tier_loader.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tier_loader.py)
- [fastmcp_server.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/fastmcp_server.py)
- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [core/comments.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/comments.py)
- [auth/service_decorator.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/service_decorator.py)
</details>

# 系统架构

## 概述

Google Workspace MCP 是一个基于 Model Context Protocol (MCP) 的服务器实现，旨在为 AI 代理提供与 Google Workspace 各服务的交互能力。该系统通过 FastMCP 框架实现工具注册、OAuth 认证管理和 HTTP 传输支持，允许 AI 代理以标准化方式操作 Google Docs、Sheets、Slides、Gmail、Drive、Calendar、Tasks、Contacts、Apps Script 等服务。

系统的核心设计目标包括：

- **模块化工具架构**：通过分层机制（core/extended/complete）组织工具，按需加载
- **统一认证管理**：集中处理 Google OAuth 2.0 认证流程，支持多用户场景
- **服务解耦**：各服务模块独立实现，通过装饰器模式与认证层解耦
- **可配置性**：支持通过环境变量、配置文件和命令行参数灵活定制行为

## 核心架构组件

### 1. 服务器入口与初始化

系统的启动入口采用分层架构模式：

```mermaid
graph TD
    A[main.py] --> B[fastmcp_server.py]
    B --> C[core/server.py]
    C --> D[auth/oauth_config.py]
    C --> E[core/tool_registry.py]
    C --> F[各服务模块]
```

`fastmcp_server.py` 负责初始化 FastMCP 实例并注册所有工具，而 `core/server.py` 包含主要的服务器配置和工具定义逻辑。 资料来源：[fastmcp_server.py:1-50]()

### 2. 工具注册与条件加载机制

系统采用了**装饰器模式**与**条件注册**相结合的架构，实现精细化的工具管理：

#### 2.1 工具注册表 (Tool Registry)

`core/tool_registry.py` 提供了全局工具注册表，支持基于白名单的工具条件加载：

| 函数 | 用途 |
|------|------|
| `set_enabled_tools()` | 设置全局启用的工具集合 |
| `get_enabled_tools()` | 获取当前启用的工具集合 |
| `is_tool_enabled()` | 检查特定工具是否启用 |
| `conditional_tool()` | 条件注册装饰器工厂 |

资料来源：[core/tool_registry.py:1-60]()

条件注册的典型用法：

```python
@conditional_tool(server, tool_name="get_doc_content")
@require_google_service("docs", "drive_read")
async def get_doc_content(...) -> ...:
    ...
```

#### 2.2 工具层级加载器 (Tool Tier Loader)

`core/tool_tier_loader.py` 实现了基于 YAML 配置的分层工具加载机制：

| 层级 | 含义 |
|------|------|
| **core** | 基础读写操作，必需功能 |
| **extended** | 扩展功能，如导出、搜索、格式化 |
| **complete** | 完整功能，包括评论管理、高级操作 |

层级配置示例（`core/tool_tiers.yaml`）：

```yaml
docs:
  core:
    - get_doc_content
    - create_doc
  extended:
    - export_doc_to_pdf
    - search_docs
  complete:
    - insert_doc_image
    - batch_update_doc
```

资料来源：[core/tool_tier_loader.py:1-80]()

### 3. 认证与权限管理

#### 3.1 服务依赖装饰器

`auth/service_decorator.py` 提供了 `require_google_service` 装饰器，确保在执行工具前验证用户是否已授权所需的服务作用域：

```python
@require_google_service("drive", "drive_read")
async def get_doc_content(service, user_google_email: str, document_id: str) -> ...:
    ...
```

该装饰器自动解析工具声明的作用域别名，并验证 OAuth 令牌是否包含相应权限。

#### 3.2 作用域解析机制

系统支持作用域别名机制，允许工具声明简化的作用域引用：

| 别名 | 完整作用域 |
|------|------------|
| `drive_full` | `https://www.googleapis.com/auth/drive` |
| `script_full` | `https://www.googleapis.com/auth/script` |
| `drive_read` | `https://www.googleapis.com/auth/drive.readonly` |

**已知问题**：`delete_script_project` 和 `create_version` 工具声明的别名 (`drive_full`, `script_full`) 未在 `SCOPE_GROUPS` 中注册，会导致永久认证失败。资料来源：[Issue #809](https://github.com/taylorwilsdon/google_workspace_mcp/issues/809)

### 4. 服务模块架构

#### 4.1 模块组织结构

```
gappsscript/          # Apps Script 服务
  - projects.py       # 项目管理工具
  - deployments.py    # 部署管理工具
  - versions.py       # 版本管理工具
  - executions.py     # 执行监控工具

core/
  - comments.py       # 通用评论管理（Docs/Sheets/Slides）
  - docs.py           # Google Docs 服务
  - sheets.py         # Google Sheets 服务
  - slides.py         # Google Slides 服务
  - drive.py          # Google Drive 服务
  - gmail.py          # Gmail 服务
  - calendar.py       # Calendar 服务
  - tasks.py          # Tasks 服务
  - contacts.py       # Contacts 服务
  - search.py         # Search 服务
```

#### 4.2 通用评论模块

`core/comments.py` 实现了一个工厂模式，为 Docs、Sheets、Slides 提供统一的评论管理接口：

```mermaid
graph LR
    A[list_document_comments] --> B[create_comment_tools]
    A --> C[manage_document_comment]
    B --> D[Drive API]
    C --> D
```

支持的操作包括：
- `create`：创建新评论
- `reply`：回复评论
- `resolve`：解决评论

资料来源：[core/comments.py:1-100]()

### 5. 日志与错误处理

#### 5.1 增强日志格式化器

`core/log_formatter.py` 提供了视觉增强的日志格式化，支持：

- ANSI 颜色编码（DEBUG: 青色, INFO: 绿色, WARNING: 黄色, ERROR: 红色）
- 服务前缀标识
- 消息内容增强

#### 5.2 HTTP 错误处理

`core/utils.py` 中的 `handle_http_errors` 装饰器统一处理 API 错误，提供友好的错误信息和 API 启用指导。

`core/api_enablement.py` 实现了智能错误分析，可从错误详情中提取 API 服务名称和项目 ID，生成直接的可点击启用链接。

### 6. 传输与部署架构

#### 6.1 支持的传输方式

| 传输方式 | 说明 |
|----------|------|
| **stdio** | 标准输入/输出，用于本地 MCP 客户端 |
| **streamable-http** | HTTP 流式传输，支持 OAuth 回调 |

#### 6.2 OAuth 回调机制

系统使用硬编码的回调端口范围（8000-8004）处理 OAuth 授权流程。**已知问题**：在 Windows 环境下，当父进程非正常终止时，Python 子进程可能无法正确退出，导致端口泄漏。资料来源：[Issue #816](https://github.com/taylorwilsdon/google_workspace_mcp/issues/816)

#### 6.3 Helm Chart 部署

支持 Kubernetes 部署，配置项包括：

| 参数 | 说明 | 默认值 |
|------|------|--------|
| `image.tag` | 镜像标签 | Chart.AppVersion |
| `secrets.googleOAuth.clientId` | OAuth 客户端 ID | 必填 |
| `singleUserMode` | 单用户模式 | false |
| `tools.enabled` | 启用的工具列表 | []（全部启用） |

资料来源：[helm-chart/workspace-mcp/README.md]()

## 工作流程

### 工具调用完整流程

```mermaid
sequenceDiagram
    participant MCP as MCP 客户端
    participant Server as FastMCP Server
    participant Auth as 认证层
    participant Service as 服务模块
    participant Google as Google API

    MCP->>Server: 调用工具 (如 get_doc_content)
    Server->>Auth: require_google_service 检查
    Auth->>Auth: 解析作用域别名
    Auth->>Auth: 验证 OAuth 令牌权限
    Alt 未授权
        Auth-->>MCP: 返回认证错误，触发 OAuth 流程
    Else 已授权
        Auth->>Service: 注入授权服务实例
        Service->>Google: 发送 API 请求
        Google-->>Service: 返回数据
        Service-->>Server: 处理并返回结果
        Server-->>MCP: 返回工具响应
    End
```

### 工具条件加载流程

```mermaid
graph TD
    A[启动时读取配置] --> B{检查 tools.enabled}
    B -->|为空| C[加载全部工具]
    B -->|有配置| D[解析 YAML 层级配置]
    D --> E{工具是否在 core 层?}
    E -->|是| F[无条件注册]
    E -->|否| G{工具是否在 extended 层?}
    G -->|是| H{启用 extended?}
    H -->|否| I[跳过注册]
    H -->|是| F
    G -->|否| J{工具是否在 complete 层?}
    J -->|是| K{启用 complete?}
    K -->|否| I
    K -->|是| F
```

## 配置体系

### 环境变量配置

| 变量 | 说明 |
|------|------|
| `WORKSPACE_MCP_URL` | MCP 服务器 URL |
| `GOOGLE_OAUTH_CLIENT_ID` | OAuth 客户端 ID |
| `GOOGLE_OAUTH_CLIENT_SECRET` | OAuth 客户端密钥 |
| `MCP_ENABLE_OAUTH21` | 启用 OAuth 2.1 支持 |
| `PERMISSIONS_MODE` | 权限模式（read_only/full） |

### OAuth 2.1 与传统模式

v1.21.1 版本增强了 OAuth 登录体验，系统支持：

- 自动打开浏览器进行 OAuth 授权
- `login_hint` 参数支持预填充用户邮箱
- 传统模式下强化主机绑定

## 已知限制与问题

| 问题 | 描述 | 状态 |
|------|------|------|
| #809 | `drive_full`/`script_full` 别名未注册导致认证失败 | 已知问题 |
| #810 | OAuth 回调凭据未绑定到 MCP 会话，导致重新认证循环 | 已知问题 |
| #816 | Windows 下进程孤儿化导致端口耗尽 | 已知问题 |
| #815 | 多账户解析机制缺乏文档说明 | 文档缺失 |

## 扩展阅读

- [Apps Script 模块文档](../gappsscript/README.md)
- [CLI 工具使用指南](../core/cli.py)
- [最新版本发布说明](https://github.com/taylorwilsdon/google_workspace_mcp/releases)

---

<a id='authentication-system'></a>

## 认证与授权系统

### 相关页面

相关主题：[系统架构](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [auth/google_auth.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/google_auth.py)
- [auth/oauth_callback_server.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/oauth_callback_server.py)
- [auth/scopes.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/scopes.py)
- [auth/credential_store.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/credential_store.py)
- [auth/mcp_session_middleware.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/mcp_session_middleware.py)
- [auth/port_resolver.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/port_resolver.py)
- [auth/oauth_config.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/oauth_config.py)
- [auth/service_decorator.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/service_decorator.py)
</details>

# 认证与授权系统

本文档详细说明 google_workspace_mcp 项目中的认证与授权系统架构、组件交互流程及常见问题处理。

## 系统概述

google_workspace_mcp 采用 OAuth 2.0 协议与 Google Workspace API 进行身份认证和授权。该系统支持两种认证模式：

- **OAuth 2.1 (Streamable HTTP)**：支持 MCP 传输协议优化的现代认证流程
- **传统 OAuth 2.0**：向后兼容的传统认证模式

核心认证模块位于 `auth/` 目录下，包含 OAuth 回调服务、凭证存储、作用域管理、会话中间件等组件。

```mermaid
graph TB
    subgraph "认证层"
        A[MCP Client] --> B[OAuth 回调服务]
        B --> C[凭证存储]
        C --> D[作用域解析器]
    end
    
    subgraph "权限层"
        D --> E[服务装饰器]
        E --> F[Google API 服务]
    end
    
    subgraph "会话层"
        G[MCP Session] --> H[会话中间件]
        H --> C
    end
```

## OAuth 2.0 认证流程

### 标准授权码流程

```mermaid
sequenceDiagram
    participant MCP as MCP Client
    participant Server as OAuth Callback Server
    participant Google as Google OAuth
    participant Store as Credential Store
    
    MCP->>Server: 发起认证请求
    Server->>Google: 重定向到授权页面
    Google-->>User: 显示授权确认页面
    User->>Google: 授权同意
    Google->>Server: 回调并返回授权码
    Server->>Google: 交换授权码为令牌
    Google-->>Server: 返回 access_token & refresh_token
    Server->>Store: 存储凭证
    Store-->>Server: 凭证存储成功
    Server-->>MCP: 认证完成
```

### 关键组件

| 组件 | 文件位置 | 职责 |
|------|----------|------|
| `GoogleAuth` | `auth/google_auth.py` | OAuth 客户端核心实现 |
| `OAuthCallbackServer` | `auth/oauth_callback_server.py` | 处理 Google OAuth 回调 |
| `CredentialStore` | `auth/credential_store.py` | 安全存储用户凭证 |
| `PortResolver` | `auth/port_resolver.py` | 管理 OAuth 回调端口 |

## 凭证存储机制

### 存储结构

凭证存储采用分层架构，按用户和会话隔离存储：

```python
# 凭证存储路径结构
~/.config/google_workspace_mcp/
├── credentials/
│   ├── google-{state_hash}.json    # 按 OAuth state 隔离
│   └── {user_email}/
│       └── credentials.json         # 按用户隔离
```

### 存储格式

```json
{
  "access_token": "ya29.xxx",
  "refresh_token": "1//xxx",
  "token_uri": "https://oauth2.googleapis.com/token",
  "client_id": "xxx.apps.googleusercontent.com",
  "client_secret": "xxx",
  "scopes": ["https://www.googleapis.com/auth/drive"],
  "expiry": "2024-01-15T10:30:00Z"
}
```

资料来源：[auth/credential_store.py:1-50]()

## 作用域管理

### 作用域分组

系统使用作用域别名简化权限配置：

```python
SCOPE_GROUPS = {
    "drive_read": ["https://www.googleapis.com/auth/drive.readonly"],
    "drive_full": ["https://www.googleapis.com/auth/drive"],
    "docs_read": ["https://www.googleapis.com/auth/documents.readonly"],
    "docs_full": ["https://www.googleapis.com/auth/documents"],
    # ...
}
```

### 作用域解析

`_resolve_scopes()` 函数负责将工具声明的作用域别名转换为实际 OAuth 作用域：

```mermaid
graph LR
    A[工具声明作用域] --> B[作用域别名]
    B --> C[SCOPE_GROUPS 查找]
    C --> D[展开为完整 URI]
    D --> E[合并去重]
    E --> F[请求令牌]
```

### 已知问题

**Issue #809**：部分工具声明的作用域别名未在 `SCOPE_GROUPS` 中注册，导致认证失败：

- `delete_script_project` 使用 `drive_full` 和 `script_full` 别名
- `create_version` 使用相同的别名
- `_resolve_scopes` 解析失败，返回空作用域列表

资料来源：[auth/scopes.py:1-100]()

## 会话绑定机制

### MCP Session 中间件

`McpSessionMiddleware` 负责将 MCP 会话 ID 与 OAuth 凭证关联：

```python
class McpSessionMiddleware:
    def __init__(self, app, credential_store):
        self.credential_store = credential_store
        # 将 MCP session ID 映射到用户凭证
```

### 关键问题

**Issue #810**：OAuth 回调将凭证存储在 `google-{state}` 键下，而非 MCP session ID：

```python
# 当前实现（存在问题）
credential_key = f"google-{state}"

# 期望实现
credential_key = mcp_session_id
```

这导致重新认证后的工具调用无法找到有效凭证，触发重复认证提示。

资料来源：[auth/mcp_session_middleware.py:1-80]()

## OAuth 回调端口管理

### 端口分配策略

系统按顺序尝试端口 8000-8004 进行 OAuth 回调：

```python
# 端口范围
CALLBACK_PORTS = range(8000, 8005)  # 8000, 8001, 8002, 8003, 8004
```

### 端口解析器

`PortResolver` 负责查找可用端口并防止冲突：

```mermaid
graph TD
    A[请求端口] --> B{端口 8000 可用?}
    B -->|是| C[返回 8000]
    B -->|否| D{端口 8001 可用?}
    D -->|是| E[返回 8001]
    D -->|否| F{端口 8002 可用?}
    F -->|是| G[返回 8002]
    F -->|否| H[...]
    H -->|全部占用| I[抛出异常]
```

### Windows 端口泄漏问题

**Issue #816**：Windows 环境下父进程异常终止时，Python 子进程可能继续存活并占用回调端口：

| 崩溃次数 | 占用端口 |
|----------|----------|
| 1 | 8000 |
| 2 | 8001 |
| 3 | 8002 |
| 4 | 8003 |
| 5 | 8004 (耗尽) |

**Issue #667**：孤儿 Python 进程持有端口 8000，导致后续认证出现 "invalid state" 错误。

资料来源：[auth/port_resolver.py:1-60]()

## 服务装饰器

### `@require_google_service` 装饰器

此装饰器确保工具调用前已完成所需 OAuth 认证：

```python
@require_google_service("drive", "drive_read")
@handle_http_errors("list_drive_files", is_read_only=True, service_type="drive")
async def list_drive_files(service, user_google_email: str, ...):
    # 服务已验证，凭证有效
    pass
```

### 装饰器参数

| 参数 | 类型 | 说明 |
|------|------|------|
| `service_type` | str | Google 服务类型（drive, docs, gmail 等）|
| `scope_alias` | str | 所需作用域别名 |

### 只读模式

启用只读模式时，系统使用受限作用域：

```python
# auth/oauth_config.py
is_read_only_mode()  # 检查是否启用只读模式
get_all_read_only_scopes()  # 获取所有只读作用域
```

资料来源：[auth/service_decorator.py:1-100]()

## 多账户支持

### 账户解析机制

系统支持存储和管理多个 Google 账户的凭证：

```python
# 凭证存储支持多账户
def store_credentials(user_email: str, credentials: dict):
    """按用户邮箱存储独立凭证"""
    
def get_credentials(user_email: str) -> dict:
    """获取指定用户的凭证"""
```

### 客户端选择

用户通过 `user_google_email` 参数指定操作的目标账户：

```python
async def list_drive_files(
    service,
    user_google_email: str,  # 指定目标用户
    folder_id: Optional[str] = None,
):
```

### 文档缺口

**Issue #815**：文档提到"多用户支持"但未详细说明工作流程和示例，实际使用方式不够清晰。

## 配置选项

### 环境变量

| 变量名 | 默认值 | 说明 |
|--------|--------|------|
| `GOOGLE_OAUTH_CLIENT_ID` | - | OAuth 客户端 ID（必需）|
| `GOOGLE_OAUTH_CLIENT_SECRET` | - | OAuth 客户端密钥（必需）|
| `MCP_ENABLE_OAUTH21` | `true` | 启用 OAuth 2.1 |
| `WORKSPACE_MCP_URL` | `http://localhost:8000` | MCP 服务地址 |

### Helm Chart 配置

```yaml
# helm-chart/values.yaml
secrets:
  googleOAuth:
    clientId: ""      # 必需
    clientSecret: ""  # 必需
    userEmail: ""     # 单用户模式

singleUserMode: false

env:
  MCP_ENABLE_OAUTH21: "true"
```

资料来源：[helm-chart/workspace-mcp/README.md:1-50]()

## OAuth 2.1 增强功能

v1.21.1 版本对 OAuth 登录体验进行了优化：

### 自动打开浏览器

认证流程可自动打开系统默认浏览器：

```python
# 包含 login_hint 支持
auth_url = build_authorization_url(login_hint="user@example.com")
```

### 传统模式主机绑定

增强了在传统认证模式下的主机地址绑定稳定性。

## 故障排除

### 常见错误

| 错误信息 | 原因 | 解决方案 |
|----------|------|----------|
| `invalid state` | OAuth state 不匹配或孤儿进程占用端口 | 重启服务，清理残留进程 |
| `Apps Script API has not been used` | API 未启用 | 在 Google Cloud Console 启用 Apps Script API |
| `Insufficient Permission` | OAuth 作用域不足 | 重新授权或检查工具所需作用域 |
| `Function not found` | 脚本函数不存在 | 确认函数名拼写和导出状态 |

### 端口耗尽处理

1. 手动终止残留进程：
   ```bash
   # Windows
   taskkill /F /IM python.exe
   
   # Linux/macOS
   pkill -f workspace-mcp
   ```

2. 重启服务以释放端口

### 清除凭证

删除凭证文件以重新进行完整认证流程：

```bash
rm -rf ~/.config/google_workspace_mcp/credentials/
```

## 架构图总览

```mermaid
graph TB
    subgraph "客户端层"
        MCP[MCP Client / Claude Code]
    end
    
    subgraph "服务层"
        Server[MCP Server<br/>workspace-mcp]
        OAuthCallback[OAuth Callback<br/>Server :8000-8004]
    end
    
    subgraph "认证层"
        GoogleAuth[GoogleAuth]
        CredentialStore[CredentialStore]
        ScopeResolver[Scope Resolver]
        SessionMiddleware[Session Middleware]
    end
    
    subgraph "Google"
        GoogleOAuth[Google OAuth<br/>2.0 / 2.1]
        GoogleAPIs[Google Workspace<br/>APIs]
    end
    
    MCP <--> Server
    Server <--> OAuthCallback
    OAuthCallback <--> GoogleOAuth
    Server --> GoogleAuth
    Server --> CredentialStore
    Server --> ScopeResolver
    Server --> SessionMiddleware
    GoogleAuth --> GoogleAPIs
```

## 相关资源

- [Apps Script OAuth 作用域文档](https://developers.google.com/apps-script/api/how-tos/authorization)
- [Google OAuth 2.0 文档](https://developers.google.com/identity/protocols/oauth2)
- [FastMCP OAuth 集成](https://gofastmcp.com/integrations/google)

## 更新日志

| 版本 | 更新内容 |
|------|----------|
| v1.21.1 | 优化 OAuth 登录体验，增强主机绑定，添加 login_hint 支持 |
| v1.21.0 | 修复 Windows 文件名兼容性 |
| v1.20.4 | 添加可配置 API 重试逻辑 |
| v1.20.3 | 改进聊天消息发送者识别处理 |

---

<a id='gmail-integration'></a>

## Gmail 集成

### 相关页面

相关主题：[项目概述](#project-overview), [系统架构](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [core/attachment_storage.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/attachment_storage.py)
- [core/utils.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/utils.py)
- [core/comments.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/comments.py)
- [core/log_formatter.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/log_formatter.py)
- [core/cli.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/cli.py)
</details>

# Gmail 集成

## 概述

Gmail 集成是 google_workspace_mcp 项目中用于与 Gmail API 交互的核心功能模块。该集成通过 MCP (Model Context Protocol) 协议提供工具化的 Gmail 访问能力，使 AI 代理能够执行邮件读取、发送、搜索和管理等操作。

### 核心功能范围

根据 `core/tool_tiers.yaml` 中的定义，Gmail 集成包含以下功能层级：

| 功能层级 | 工具数量 | 核心功能 |
|---------|---------|---------|
| Core（核心） | 6 | `get_gmail_message`、`search_gmail`、`send_email`、`create_draft`、`get_thread`、`list_threads` |
| Extended（扩展） | 2 | `batch_get_gmail_message`、`manage_labels` |
| Complete（完整） | 3 | `trash_message`、`batch_delete_messages`、`modify_message` |

资料来源：[core/tool_tiers.yaml:1-15]()

## 架构设计

### 模块依赖关系

```mermaid
graph TD
    A[MCP Client] --> B[gmail_tools.py]
    B --> C[gmail_helpers.py]
    C --> D[Gmail API]
    B --> E[attachment_storage.py]
    E --> F[Local File Storage]
    C --> G[core/utils.py]
    G --> H[XML/Content Parsing]
```

### 工具分层架构

Gmail 工具按照功能完整度分为三个层级：

```mermaid
graph LR
    subgraph Core[核心层 - Core]
        C1[get_gmail_message]
        C2[search_gmail]
        C3[send_email]
        C4[create_draft]
        C5[get_thread]
        C6[list_threads]
    end
    
    subgraph Extended[扩展层 - Extended]
        E1[batch_get_gmail_message]
        E2[manage_labels]
    end
    
    subgraph Complete[完整层 - Complete]
        F1[trash_message]
        F2[batch_delete_messages]
        F3[modify_message]
    end
```

## 核心工具详解

### 1. get_gmail_message

获取单封邮件的完整信息，包括发件人、收件人、主题、正文、附件等。

**参数配置：**

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| user_google_email | string | 是 | 用户 Google 邮箱地址 |
| message_id | string | 是 | 邮件唯一标识符 |
| format | string | 否 | 返回格式 (minimal/metadata/full/raw) |

### 2. search_gmail

支持复杂的邮件搜索功能，使用 Gmail 搜索语法。

**常用搜索操作符：**

| 操作符 | 用途 | 示例 |
|-------|------|------|
| `from:` | 按发件人搜索 | `from:example@gmail.com` |
| `to:` | 按收件人搜索 | `to:team@company.com` |
| `subject:` | 按主题搜索 | `subject:发票` |
| `has:attachment` | 仅显示有附件的邮件 | `from:bank has:attachment` |
| `after:` | 指定日期后的邮件 | `after:2024/01/01` |
| `is:unread` | 未读邮件 | `is:unread label:重要` |

### 3. send_email

发送邮件功能，支持普通文本和富文本格式。

**发送参数：**

| 参数 | 说明 |
|-----|------|
| to | 收件人邮箱（逗号分隔多个） |
| subject | 邮件主题 |
| body | 邮件正文 |
| cc | 抄送（可选） |
| bcc | 密送（可选） |
| attachments | 附件列表（可选） |

## 附件处理系统

### attachment_storage 模块

`core/attachment_storage.py` 负责管理 Gmail 附件的本地存储和检索。

```mermaid
sequenceDiagram
    participant U as User
    participant M as MCP Server
    participant S as Attachment Storage
    participant F as File System
    participant G as Gmail API
    
    U->>M: 请求邮件附件
    M->>G: 获取附件信息
    G-->>M: 附件元数据
    M->>S: 存储附件
    S->>F: 写入文件
    F-->>S: 存储确认
    S-->>M: 返回文件路径
    M-->>U: 提供下载链接
```

### Windows 文件名兼容性处理

v1.21.0 版本修复了 Windows 系统上的文件名兼容性问题：

**问题背景：**
- Windows 文件系统对文件名有严格限制
- 保留设备名称（CON、PRN、AUX、NUL 等）无法使用
- 特殊字符（`:`, `*`, `?`, `<`, `>`, `|` 等）被禁止

**处理逻辑（资料来源：[core/attachment_storage.py]()）：**

```python
# 保留设备名称映射
WINDOWS_RESERVED_NAMES = [
    'CON', 'PRN', 'AUX', 'NUL',
    'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
    'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9'
]

# 特殊字符过滤
INVALID_CHARS = r'[<>:"|?*\x00-\x1f]'
```

修复后，Gmail 附件的文件名将自动进行：
1. 移除非法字符
2. 替换 Windows 保留名称
3. 显示实际保存的文件名（而非原始文件名）

## OAuth 认证与作用域

### Gmail 所需 OAuth 作用域

Gmail 集成需要以下 OAuth 作用域：

| 作用域 | 权限级别 | 用途 |
|-------|---------|------|
| `gmail.readonly` | 只读 | 读取邮件和元数据 |
| `gmail.send` | 发送 | 发送邮件 |
| `gmail.compose` | 写入 | 创建草稿 |
| `gmail.modify` | 修改 | 修改邮件、标签 |
| `gmail.labels` | 管理 | 管理标签 |

### 认证流程

```mermaid
graph LR
    A[启动 MCP Server] --> B{检查缓存凭证}
    B -->|无/过期| C[发起 OAuth 流程]
    B -->|有效| E[执行工具调用]
    C --> D[浏览器授权]
    D --> C
    C --> F[保存凭证]
    F --> E
```

## 日志与调试

### 日志格式化

Gmail 工具使用统一的日志格式，便于问题排查：

| 日志级别 | 前缀标识 | 使用场景 |
|---------|---------|---------|
| DEBUG | `[GMAIL]` | 详细的 API 请求/响应 |
| INFO | `[GMAIL]` | 正常操作记录 |
| WARNING | `[GMAIL]` | 非致命问题（如部分附件处理失败） |
| ERROR | `[GMAIL]` | API 错误或操作失败 |

日志格式化器定义于 `core/log_formatter.py`，提供：
- 带颜色的终端输出
- 统一的日志前缀
- 结构化的错误信息

## CLI 命令行工具

### 使用方法

```bash
# 列出可用工具
workspace-cli list

# 调用 Gmail 工具
workspace-cli call get_gmail_message user_google_email=you@gmail.com message_id=123abc
```

配置方式：

| 环境变量 | 默认值 | 说明 |
|---------|-------|------|
| `WORKSPACE_MCP_URL` | `http://localhost:8000` | MCP 服务器地址 |

## 与其他模块的集成

### Gmail 与 Drive 集成

Gmail 附件可以方便地与 Drive 模块协同工作：

```mermaid
graph LR
    A[Gmail 附件] --> B[attachment_storage]
    B --> C[Drive 文件系统]
    C --> D[create_drive_file]
    D --> E[Google Drive 存储]
```

### Gmail 与 Comments 集成

邮件对话（Threads）可以配合评论系统进行协作管理。

## 已知限制与注意事项

### API 配额限制

| 配额类型 | 限制 | 说明 |
|---------|------|------|
| Gmail API 调用 | 10亿/天 | 付费账户 |
| 单次查询结果 | 500 封邮件 | 最大返回数 |
| 附件大小 | 25MB（接收）/ 35MB（发送） | Gmail 限制 |

### 安全最佳实践

1. **凭证保护**：确保 `client_secret.json` 文件安全存储
2. **最小权限**：仅请求所需的 OAuth 作用域
3. **会话管理**：使用 `login_hint` 参数优化多账户场景

## 社区反馈与改进

### 相关 Issue

| Issue | 状态 | 说明 |
|-------|------|------|
| #810 | 开放 | OAuth 回调会话绑定问题，可能导致重复认证提示 |
| #816 | 修复中 | Windows 进程终止后端口泄漏问题 |

### 版本更新历史

| 版本 | 日期 | 关键变更 |
|------|------|---------|
| v1.21.1 | 最新 | OAuth 登录体验优化 |
| v1.21.0 | 2024 | Windows 文件名兼容性修复 |
| v1.20.4 | 2024 | API 重试逻辑和可靠性改进 |

## 快速入门指南

### 首次配置步骤

1. 在 Google Cloud Console 创建项目
2. 启用 Gmail API
3. 配置 OAuth 同意屏幕
4. 下载客户端凭据 JSON 文件
5. 配置 MCP 服务器环境变量

### 基础使用示例

```
用户: "搜索张三发来的所有未读邮件"
AI: 调用 search_gmail with query="from:张三 is:unread"
AI: 返回搜索结果列表
AI: "找到 3 封未读邮件..."

用户: "给 team@company.com 发送测试邮件，主题是 MCP 测试"
AI: 调用 send_email 工具
AI: 返回发送结果

---

<a id='drive-integration'></a>

## Drive 集成

### 相关页面

相关主题：[项目概述](#project-overview), [Docs/Sheets/Slides 集成](#docs-sheets-slides)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [gdrive/drive_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gdrive/drive_tools.py)
- [gdrive/drive_helpers.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gdrive/drive_helpers.py)
- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [core/tool_tier_loader.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tier_loader.py)
- [auth/scopes.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/auth/scopes.py)
- [core/utils.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/utils.py)
</details>

# Drive 集成

Drive 集成是 google_workspace_mcp 项目中用于与 Google Drive API 交互的核心模块，提供了文件管理、共享、搜索以及 Office 文件格式转换等功能。通过该集成，AI Agent 可以执行完整的云端文件生命周期管理操作，包括创建、读取、更新、删除和搜索 Google Drive 文件。

## 核心功能概述

Drive 集成的主要功能包括：

- **文件管理**：创建、读取、更新、删除 Google Drive 文件和文件夹
- **格式转换**：支持 Office 文件（DOCX、XLSX、PPTX）上传时自动转换为原生 Google 格式（Docs、Sheets、Slides）
- **快捷方式**：创建指向其他文件的快捷方式，实现单一文件多位置显示
- **权限控制**：管理文件访问权限和共享设置
- **搜索功能**：全文搜索 Drive 文件内容
- **元数据操作**：修改文件名、描述、封面等文件属性

资料来源：[gdrive/drive_tools.py:1-50]()

## 工具分层架构

Drive 工具按照功能复杂度分为三个层级，采用分层加载机制控制可用工具集。

### 层级结构

| 层级 | 描述 | 典型工具 |
|------|------|----------|
| Core（核心） | 基本文件读写操作 | `create_drive_file`、`read_drive_file`、`update_drive_file`、`delete_drive_file`、`list_drive_files` |
| Extended（扩展） | 高级文件和权限操作 | `get_drive_file_info`、`share_drive_file`、`get_drive_file_permissions`、`copy_drive_file` |
| Complete（完整） | 所有可用功能 | `search_drive_files`、`export_drive_file`、`import_to_google_doc`、`create_drive_shortcut` |

资料来源：[core/tool_tiers.yaml]()()

### 分层加载机制

工具分层通过 `ToolTierLoader` 类实现，支持按需加载特定层级的工具：

```python
class ToolTierLoader:
    def __init__(self, config_path: Optional[str] = None):
        if config_path is None:
            config_path = Path(__file__).parent / "tool_tiers.yaml"
        self.config_path = Path(config_path)
```

配置通过 YAML 文件定义，支持按服务分组加载工具集合。启动时可指定 `--tier` 参数选择加载核心集、扩展集或完整集。

资料来源：[core/tool_tier_loader.py:1-40]()

## 核心工具详解

### create_drive_file

创建 Google Drive 文件，支持普通上传和格式转换上传。

**主要参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| name | string | 是 | 文件名称 |
| parent_id | string | 否 | 父文件夹 ID |
| mime_type | string | 否 | MIME 类型（默认 `application/octet-stream`） |
| content | string | 否 | 文件内容（Base64 编码或原始字符串） |
| file_path | string | 否 | 本地文件路径（与 content 二选一） |
| target_mime_type | string | 否 | 目标 MIME 类型（用于格式转换） |
| description | string | 否 | 文件描述 |
| convert | boolean | 否 | 是否转换为 Google 原生格式 |

**格式转换逻辑：**

当 `convert` 参数为 `true` 或指定 `target_mime_type` 时，系统会调用 Google Drive 的导入功能：

```python
# Office 文件到 Google 格式的转换映射
CONVERSION_MAP = {
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": 
        "application/vnd.google-apps.document",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": 
        "application/vnd.google-apps.spreadsheet",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation": 
        "application/vnd.google-apps.presentation",
}
```

这解决了社区提出的问题：用户希望上传 PPTX 文件后获得原生的可编辑 Google Slides 格式。

资料来源：[gdrive/drive_tools.py:100-200]()

### import_to_google_doc

专门用于将本地文档文件导入为 Google Docs 格式。

**支持的源格式：**

- DOCX（Microsoft Word）
- ODT（OpenDocument Text）
- RTF（Rich Text Format）
- HTML
- Markdown

**特性：**

- 保留文档格式和样式
- 支持图片导入
- 返回新创建的 Google Doc ID

资料来源：[core/utils.py:50-100]()

### list_drive_files

列出 Drive 文件和文件夹，支持分页和过滤。

**高级选项：**

- `folder_id`: 仅列出指定文件夹内容
- `order_by`: 排序方式（name, createdTime, modifiedTime, quotaBytesUsed）
- `include_items_from_all_drives`: 是否包含共享 Drive 内容
- `supports_all_drives`: 是否支持共享 Drive
- `drive_id`: 限定特定共享 Drive

**返回字段：**

```python
@dataclass
class DriveFile:
    id: str
    name: str
    mime_type: str
    created_time: Optional[str] = None
    modified_time: Optional[str] = None
    size: Optional[str] = None
    drive_id: Optional[str] = None
    parents: Optional[List[str]] = None
    shared: bool = False
```

资料来源：[gdrive/drive_helpers.py:50-150]()

### create_drive_shortcut

创建 Drive 文件快捷方式，这是社区强烈要求的功能。由于 Google Drive 在 2020 年 9 月移除了多父级支持，文件只能有单一父文件夹，因此快捷方式成为实现"同一文件多位置显示"的标准方案。

**参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| name | string | 是 | 快捷方式名称 |
| target_id | string | 是 | 目标文件 ID |
| parent_id | string | 否 | 快捷方式放置的文件夹 |
| target_mime_type | string | 否 | 目标文件 MIME 类型 |

**使用场景：**

- 将项目文件同时显示在"项目"和"归档"文件夹
- 创建指向团队共享文件夹的快捷方式
- 无需复制文件内容即可多位置访问

资料来源：[社区 issue #819]()

## 权限与认证

### OAuth 作用域

Drive 集成使用以下 OAuth 作用域：

| 作用域 | 别名 | 说明 |
|--------|------|------|
| `https://www.googleapis.com/auth/drive` | `drive_full` | 完全 Drive 访问 |
| `https://www.googleapis.com/auth/drive.readonly` | `drive_read` | 只读访问 |
| `https://www.googleapis.com/auth/drive.file` | `drive_file` | 应用创建的文件 |
| `https://www.googleapis.com/auth/drive.metadata` | `drive_meta` | 元数据读取 |

### 已知问题

**Issue #809：未注册的作用域别名导致认证失败**

`drive_full` 和 `script_full` 作用域别名未在 `SCOPE_GROUPS` 中注册，导致 `delete_script_project` 和 `create_version` 工具在调用时出现永久性认证失败。

```python
# 问题代码示意
def _resolve_scopes(self, scopes):
    # drive_full 和 script_full 未在 SCOPE_GROUPS 中定义
    # 导致解析失败
```

资料来源：[auth/scopes.py:100-150]()

## 高级功能

### 文件内容提取

`get_drive_file_as_text` 工具支持从 Office 文件中提取文本内容：

```python
# 支持的文件格式
TEXT_EXTRACTION_MIMES = [
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation",
]
```

提取逻辑：

1. 下载文件为 ZIP 压缩包
2. 解析内部 XML 结构
3. 从相应命名空间提取文本：
   - Word: `http://schemas.openxmlformats.org/wordprocessingml/2006/main`
   - Excel: 遍历工作表单元格
   - PowerPoint: `http://schemas.openxmlformats.org/drawingml/2006/main`

资料来源：[core/utils.py:200-300]()

### 批量操作

通过 MCP 协议的工具调用，Agent 可以编排复杂的批量操作序列：

```mermaid
graph TD
    A[开始] --> B[列出源文件夹文件]
    B --> C{文件类型判断}
    C -->|DOCX| D[调用 import_to_google_doc]
    C -->|PPTX| E[调用 create_drive_file + convert]
    C -->|XLSX| F[调用 create_drive_file + convert]
    D --> G[设置文件权限]
    E --> G
    F --> G
    G --> H[记录到索引表]
    H --> I[发送完成通知]
```

## 配置文件结构

Drive 工具的行为可通过配置文件进行定制：

```yaml
# tool_tiers.yaml
drive:
  core:
    - create_drive_file
    - read_drive_file
    - update_drive_file
    - delete_drive_file
    - list_drive_files
  extended:
    - get_drive_file_info
    - share_drive_file
    - copy_drive_file
    - create_drive_folder
  complete:
    - search_drive_files
    - export_drive_file
    - import_to_google_doc
    - create_drive_shortcut
    - get_drive_file_permissions
```

资料来源：[core/tool_tiers.yaml]()()

## 最佳实践

### 文件命名

- 避免使用 Windows 保留设备名称（CON、PRN、AUX、NUL 等）
- 移除特殊字符（:、*、?、<、>、|）
- v1.21.0 已修复 Windows 系统文件名兼容性问题

### 性能优化

- 使用 `include_items_from_all_drives: false` 以提升列表查询速度
- 避免在单个请求中处理超过 1000 个文件
- 使用 `pageSize` 参数控制分页大小

### 格式转换建议

| 源格式 | 推荐目标 | 转换方式 |
|--------|----------|----------|
| DOCX | Google Docs | `import_to_google_doc` |
| XLSX | Google Sheets | `create_drive_file` + `convert: true` |
| PPTX | Google Slides | `create_drive_file` + `convert: true` |
| PDF | Google Docs | `create_drive_file` + `convert: true` |

## 限制与已知问题

| 问题 | 严重程度 | 状态 |
|------|----------|------|
| 作用域别名 `drive_full` 未注册导致部分工具认证失败 | 高 | 待修复（Issue #809） |
| Office 格式转换不支持 `update_drive_file` 内容替换 | 中 | 功能请求（Issue #604） |
| `import_to_google_doc` 只能创建新文件，无法更新现有文件 | 中 | 功能请求 |
| 快捷方式工具尚未实现 | 中 | 计划中（Issue #819） |

## 快速开始

### 列出 Drive 文件

```
用户: "显示我的 Drive 根目录文件"
Agent 调用: list_drive_files(parent_id=None)
```

### 上传并转换文件

```
用户: "将 report.xlsx 转换为 Google Sheets"
Agent 调用: create_drive_file(
    name="report.xlsx",
    file_path="/path/to/report.xlsx",
    convert=True,
    target_mime_type="application/vnd.google-apps.spreadsheet"
)
```

### 创建文件快捷方式

```
用户: "在'归档'文件夹中创建'报告'文件的快捷方式"
Agent 调用: create_drive_shortcut(
    name="报告 - 归档副本",
    target_id="1abc123...",
    parent_id="archive_folder_id"
)

---

<a id='docs-sheets-slides'></a>

## Docs/Sheets/Slides 集成

### 相关页面

相关主题：[Drive 集成](#drive-integration), [项目概述](#project-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [core/comments.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/comments.py)
- [core/utils.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/utils.py)
- [core/tool_tier_loader.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tier_loader.py)
- [gappsscript/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/README.md)
</details>

# Docs/Sheets/Slides 集成

## 概述

Docs/Sheets/Slides 集成是 Google Workspace MCP (Model Context Protocol) 中用于与 Google 文档、电子表格和演示文稿进行交互的核心模块。该集成提供了完整的 CRUD 操作支持，包括创建、读取、更新、删除文档内容，以及管理文档评论和批量操作。

这三个应用共享相似的架构模式：
- 统一使用 Drive API 进行文件操作
- 通过专用 API（Docs API、Sheets API、Slides API）进行内容操作
- 支持评论管理（通过 Drive API 实现）
- 共享工具层级（core、extended、complete）配置

资料来源：[core/tool_tiers.yaml:1-80]()

## 架构设计

### 模块组成

```mermaid
graph TD
    subgraph "Docs/Sheets/Slides 集成架构"
        A[用户请求] --> B[MCP Server]
        B --> C{工具层级解析}
        C -->|core| D[核心工具集]
        C -->|extended| E[扩展工具集]
        C -->|complete| F[完整工具集]
        
        D --> G[Docs API / Sheets API / Slides API]
        E --> G
        F --> G
        
        G --> H[Google Drive API]
        H --> I[Google Cloud]
        
        G --> J[批量操作管理器]
        J --> K[评论管理系统]
        K --> H
    end
```

### 工具层级结构

每个应用（Docs、Sheets、Slides）都采用三层工具层级设计：

| 层级 | 用途 | 特性 |
|------|------|------|
| **core** | 基础读写操作 | 创建、读取、更新、删除 |
| **extended** | 高级内容管理 | 格式化、搜索、列表、导出 |
| **complete** | 完整功能集 | 批量操作、评论管理、调试工具 |

资料来源：[core/tool_tiers.yaml:1-80]()

## 工具层级详细配置

### Docs 工具层级

```yaml
docs:
  core:
    - get_doc_content      # 获取文档内容
    - create_doc          # 创建文档
    - modify_doc_text     # 修改文档文本
  extended:
    - export_doc_to_pdf    # 导出为PDF
    - search_docs          # 搜索文档
    - find_and_replace_doc # 查找替换
    - list_docs_in_folder  # 列出文件夹中的文档
    - insert_doc_elements  # 插入元素
    - update_paragraph_style # 更新段落样式
    - get_doc_as_markdown  # 获取Markdown格式
    - list_document_comments # 列出评论
    - manage_document_comment # 管理评论
  complete:
    - insert_doc_image     # 插入图片
    - update_doc_headers_footers # 更新页眉页脚
    - batch_update_doc     # 批量更新
    - inspect_doc_structure # 检查文档结构
    - create_table_with_data # 创建表格
    - debug_table_structure  # 调试表格结构
    - manage_doc_tab       # 管理文档标签
```

资料来源：[core/tool_tiers.yaml:6-28]()

### Sheets 工具层级

```yaml
sheets:
  core:
    - create_spreadsheet  # 创建电子表格
    - read_sheet_values   # 读取表格值
    - modify_sheet_values # 修改表格值
  extended:
    - list_spreadsheets   # 列出电子表格
    - get_spreadsheet_info # 获取电子表格信息
    - format_sheet_range  # 格式化范围
    - list_sheet_tables   # 列出表格
  complete:
    - create_sheet        # 创建工作表
    - append_table_rows   # 追加行
    - resize_sheet_dimensions # 调整尺寸
    - move_sheet_rows     # 移动行
    - list_spreadsheet_comments # 列出评论
    - manage_spreadsheet_comment # 管理评论
    - manage_conditional_formatting # 条件格式
```

资料来源：[core/tool_tiers.yaml:29-49]()

### Slides 工具层级

```yaml
slides:
  core:
    - create_presentation  # 创建演示文稿
    - get_presentation    # 获取演示文稿
  extended:
    - batch_update_presentation # 批量更新
    - get_page            # 获取页面
    - get_page_thumbnail  # 获取页面缩略图
  complete:
    - list_presentation_comments # 列出评论
    - manage_presentation_comment # 管理评论
```

资料来源：[core/tool_tiers.yaml:50-62]()

## 工具层级加载器

### ToolTierLoader 类

`ToolTierLoader` 类负责从 YAML 配置文件加载和管理工具层级：

```python
class ToolTierLoader:
    """Loads and manages tool tiers from configuration."""
    
    def __init__(self, config_path: Optional[str] = None):
        if config_path is None:
            config_path = Path(__file__).parent / "tool_tiers.yaml"
        self.config_path = Path(config_path)
        self._tiers_config: Optional[Dict] = None
```

资料来源：[core/tool_tier_loader.py:19-33]()

### 配置加载流程

```mermaid
sequenceDiagram
    participant U as 用户
    participant T as ToolTierLoader
    participant F as 文件系统
    participant Y as YAML解析器
    participant S as MCP Server

    U->>T: 初始化 ToolTierLoader
    T->>F: 读取 tool_tiers.yaml
    F-->>T: YAML内容
    T->>Y: yaml.safe_load()
    Y-->>T: 解析后的配置字典
    T->>S: 注册工具层级
    S-->>U: 工具就绪
```

## 评论管理系统

### 统一评论架构

Docs、Sheets、Slides 的评论功能通过统一的 `core/comments.py` 模块实现，所有评论操作都通过 Drive API 进行：

```python
def create_comment_tools(app_name: str, file_id_param: str):
    """
    Factory function to create comment management tools for a specific Google Workspace app.
    """
    list_func_name = f"list_{app_name}_comments"
    manage_func_name = f"manage_{app_name}_comment"
```

资料来源：[core/comments.py:42-56]()

### 支持的操作

| 操作 | 描述 | 参数要求 |
|------|------|----------|
| `create` | 创建新评论 | `comment_content` 必需 |
| `reply` | 回复评论 | `comment_id` 和 `comment_content` 必需 |
| `resolve` | 解决评论 | `comment_id` 必需 |

资料来源：[core/comments.py:30-43]()

### 评论注解

评论工具使用 MCP ToolAnnotations 来标记工具特性：

```python
READ_COMMENT_ANNOTATIONS = ToolAnnotations(
    readOnlyHint=True,
    destructiveHint=False,
    idempotentHint=True,
    openWorldHint=True,
)

MANAGE_COMMENT_ANNOTATIONS = ToolAnnotations(
    readOnlyHint=False,
    destructiveHint=False,
    idempotentHint=False,
    openWorldHint=True,
)
```

资料来源：[core/comments.py:25-38]()

## 批量操作管理器

### BatchOperationManager

批量操作管理器（`BatchOperationManager`）提供了对 Docs 进行批量修改的能力，包括：
- 批量替换文本
- 批量插入元素
- 批量更新样式

资料来源：[gappsscript/README.md:80-100]()

### 典型工作流程

```mermaid
graph LR
    A[读取文档结构] --> B[分析内容]
    B --> C[生成修改方案]
    C --> D[执行批量操作]
    D --> E{成功?}
    E -->|是| F[返回结果]
    E -->|否| G[错误处理]
    G --> H[重试或回滚]
```

## Office 文件文本提取

### 支持的格式

系统支持从以下 Office 格式中提取文本内容：

| 格式类型 | MIME 类型 | 应用 |
|----------|-----------|------|
| DOCX | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | Docs |
| PPTX | `application/vnd.openxmlformats-officedocument.presentationml.presentation` | Slides |
| XLSX | `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` | Sheets |

资料来源：[core/utils.py:80-120]()

### 文本提取逻辑

```python
# 对于 PowerPoint: 提取 <a:t> 标签中的文本
# 对于 Word: 提取 <w:t> 标签中的文本
# 对于 Excel: 遍历每个工作表(member)
if elem.tag.endswith("}t") and elem.text:
    cleaned_text = elem.text.strip()
    if cleaned_text:
        member_texts.append(cleaned_text)
```

资料来源：[core/utils.py:95-110]()

### 文本合并规则

从不同成员（工作表/幻灯片）提取的内容使用双换行符分隔：

```python
text = "\n\n".join(pieces).strip()
```

资料来源：[core/utils.py:113-115]()

## 与 Apps Script 的集成

### 跨应用自动化

Apps Script 模块能够与 Docs、Sheets、Slides 进行深度集成，实现跨应用的工作流自动化：

| 功能 | 说明 |
|------|------|
| 读取数据 | 从 Sheets 读取数据进行处理 |
| 生成文档 | 使用 Docs API 创建报告 |
| 更新演示文稿 | 自动更新 Slides 内容 |
| 发送通知 | 通过 Gmail 发送通知 |

资料来源：[gappsscript/README.md:20-35]()

### 自动化示例

```
用户: "创建一个每周一早上9点运行的脚本"
需求:
1. 从 '销售' 电子表格读取数据
2. 计算周报数据
3. 生成总结文档
4. 邮件发送给团队
```

资料来源：[gappsscript/README.md:50-70]()

## 社区相关问题

### 已知问题

| Issue | 描述 | 状态 |
|-------|------|------|
| #568 | 缺少 `import_to_google_slides` 工具（PPTX 转换） | Open |
| #820 | Office→Google 格式转换功能请求（pptx→Slides, xlsx→Sheets） | Open |
| #604 | `update_drive_file` 内容替换功能请求 | Open |

### 功能建议

社区用户希望实现：
- PPTX 文件上传时自动转换为原生 Google Slides 格式
- XLSX 文件上传时自动转换为原生 Google Sheets 格式
- 类似于 `import_to_google_doc` 的转换功能

资料来源：[github.com/taylorwilsdon/google_workspace_mcp/issues/568]()
资料来源：[github.com/taylorwilsdon/google_workspace_mcp/issues/820]()

## 配置与部署

### 工具层级过滤

在部署时可以通过配置启用特定的工具层级：

```python
# 核心层级 - 仅基础功能
# extended 层级 - 包含格式化、搜索等
# complete 层级 - 包含所有功能
```

### 环境变量配置

| 变量 | 描述 | 默认值 |
|------|------|--------|
| `MCP_ENABLE_OAUTH21` | 启用 OAuth 2.1 支持 | `"true"` |
| `WORKSPACE_MCP_URL` | MCP 服务器 URL | 本地地址 |

资料来源：[helm-chart/workspace-mcp/README.md:30-45]()

## 使用限制与注意事项

### API 配额限制

| 应用 | 读取限制 | 写入限制 |
|------|----------|----------|
| Docs API | 每项目每分钟 3000 次 | 每项目每分钟 300 次 |
| Sheets API | 每项目每分钟 3000 次 | 每项目每分钟 300 次 |
| Slides API | 每项目每分钟 3000 次 | 每项目每分钟 300 次 |

### 常见错误处理

```python
@handle_http_errors(list_func_name, is_read_only=True, service_type="drive")
async def list_comments(service, user_google_email: str, document_id: str):
    # 错误处理装饰器确保 HTTP 错误被正确捕获和处理
```

资料来源：[core/comments.py:58-62]()

## 日志系统

### 服务前缀映射

| 服务 | 日志前缀 | 模块 |
|------|----------|------|
| Docs | `[DOCS]` | `gdocs.docs_tools` |
| Sheets | `[SHEETS]` | `gsheets.sheets_tools` |
| Slides | `[SLIDES]` | `gslides.slides_tools` |
| 工具 | `[TOOL]` | `auth.service_decorator` |

资料来源：[core/log_formatter.py:40-55]()

### 日志格式化

增强型日志格式化器提供：
- ANSI 颜色支持（终端兼容）
- 层级前缀标识
- 工具层级加载信息优化显示

## 总结

Docs/Sheets/Slides 集成构成了 Google Workspace MCP 的文档处理核心，提供了：

1. **统一架构**：三层工具层级设计（core/extended/complete）支持渐进式功能暴露
2. **评论管理**：统一的评论系统通过 Drive API 实现跨应用评论功能
3. **批量操作**：BatchOperationManager 支持复杂文档修改
4. **文件转换**：Office 文件文本提取支持多格式解析
5. **Apps Script 集成**：支持跨应用自动化工作流

该集成设计遵循了 Google Workspace API 的最佳实践，通过 MCP 协议为 AI 代理提供了一套完整的文档操作能力。

---

<a id='calendar-contacts-chat'></a>

## Calendar/Contacts/Chat 及其他服务

### 相关页面

相关主题：[项目概述](#project-overview)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [gcalendar/calendar_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gcalendar/calendar_tools.py)
- [gcontacts/contacts_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gcontacts/contacts_tools.py)
- [gchat/chat_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gchat/chat_tools.py)
- [gtasks/tasks_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gtasks/tasks_tools.py)
- [gforms/forms_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gforms/forms_tools.py)
- [gsearch/search_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gsearch/search_tools.py)
- [gappsscript/apps_script_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/apps_script_tools.py)
- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
</details>

# Calendar/Contacts/Chat 及其他服务

## 概述

Google Workspace MCP (Model Context Protocol) 不仅提供核心的文档、电子表格和邮箱功能，还包含一系列重要的协作与效率工具。这些服务包括日历管理（Calendar）、联系人管理（Contacts）、即时通讯（Chat）、任务管理（Tasks）、表单收集（Forms）、自定义搜索（Search）以及 Apps Script 自动化脚本。本页面将详细说明这些服务的功能、工具层级和使用方法。

## 服务架构概览

Google Workspace MCP 的工具按照功能层级进行组织，分为 `core`（核心）、`extended`（扩展）和 `complete`（完整）三个层级：

```mermaid
graph TD
    A[Google Workspace MCP] --> B[核心服务]
    A --> C[协作服务]
    A --> D[自动化服务]
    
    B --> B1[Docs 文档]
    B --> B2[Sheets 表格]
    B --> B3[Gmail 邮箱]
    B --> B4[Drive 云盘]
    
    C --> C1[Calendar 日历]
    C --> C2[Contacts 联系人]
    C --> C3[Chat 即时通讯]
    C --> C4[Tasks 任务]
    C --> C5[Forms 表单]
    
    D --> D1[Search 搜索]
    D --> D2[Apps Script]
    
    style C1 fill:#f9f,stroke:#333,stroke-width:2px
    style C2 fill:#f9f,stroke:#333,stroke-width:2px
    style C3 fill:#f9f,stroke:#333,stroke-width:2px
    style C4 fill:#f9f,stroke:#333,stroke-width:2px
    style C5 fill:#f9f,stroke:#333,stroke-width:2px
    style D1 fill:#ff9,stroke:#333,stroke-width:2px
    style D2 fill:#ff9,stroke:#333,stroke-width:2px
```

## 工具层级配置

根据 `tool_tiers.yaml` 中的配置，各服务的工具层级分布如下：

| 服务类别 | Core 核心工具 | Extended 扩展工具 | Complete 完整工具 |
|---------|--------------|-------------------|------------------|
| **Calendar** | 4 个 | 5 个 | 4 个 |
| **Contacts** | 4 个 | 2 个 | 2 个 |
| **Chat** | 4 个 | 2 个 | 0 个 |
| **Tasks** | 3 个 | 0 个 | 3 个 |
| **Forms** | 2 个 | 1 个 | 3 个 |
| **Search** | 1 个 | 0 个 | 1 个 |
| **Apps Script** | 8 个 | 9 个 | 0 个 |

资料来源：[core/tool_tiers.yaml:1-75]()

## Calendar 日历服务

### 功能概述

Calendar 日历服务是 Google Workspace 协作功能的核心组件之一，允许 AI 代理创建、读取、更新和删除日历事件。该服务支持个人日历和团队日历管理，包括会议安排、提醒设置和事件权限控制。

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `create_calendar_event` | 创建新的日历事件 | Core |
| `get_calendar_event` | 获取指定事件的详细信息 | Core |
| `list_calendar_events` | 列出指定时间范围内的日历事件 | Core |
| `update_calendar_event` | 更新现有日历事件 | Core |
| `delete_calendar_event` | 删除日历事件 | Extended |
| `list_calendars` | 列出用户可访问的所有日历 | Extended |
| `search_calendar_events` | 搜索日历事件 | Extended |
| `manage_calendar_acl` | 管理日历访问控制列表 | Extended |
| `get_calendar_availability` | 获取日历空闲/忙碌时间 | Extended |
| `list_calendar_colors` | 列出可用的日历颜色选项 | Complete |
| `manage_calendar_setting` | 管理日历设置 | Complete |
| `create_calendar` | 创建新日历 | Complete |
| `delete_calendar` | 删除日历 | Complete |

### 典型使用场景

```mermaid
graph LR
    A[用户请求] --> B{事件是否存在?}
    B -->|不存在| C[create_calendar_event]
    B -->|存在| D{需要更新?}
    D -->|是| E[update_calendar_event]
    D -->|否| F[get_calendar_event]
    C --> G[返回事件详情]
    E --> G
    F --> G
```

**场景示例：安排团队会议**

```
用户："明天下午3点安排一个与产品团队的会议，讨论Q4路线图"
AI代理：
1. 调用 list_calendar_events 检查团队成员可用性
2. 调用 create_calendar_event 创建会议邀请
3. 返回会议详情和日历链接
```

## Contacts 联系人服务

### 功能概述

Contacts 联系人服务提供 Google Workspace 联系人目录的访问能力，支持搜索、查看和管理个人联系人及组织联系人。该服务对于需要与用户交互的 AI 代理尤为重要，例如发送邮件或消息时需要验证收件人信息。

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `search_contacts` | 搜索联系人 | Core |
| `get_contact` | 获取单个联系人详情 | Core |
| `list_contacts` | 列出所有联系人 | Core |
| `manage_contact` | 创建、更新或删除联系人 | Core |
| `list_contact_groups` | 列出联系人分组 | Extended |
| `get_contact_group` | 获取联系人分组详情 | Extended |
| `manage_contacts_batch` | 批量管理联系人 | Complete |
| `manage_contact_group` | 创建、更新或删除联系人分组 | Complete |

### 联系人数据结构

```python
# 联系人数据模型字段
Contact {
    resource_name: str,        # 联系人资源名称
    display_name: str,        # 显示名称
    email_addresses: List[EmailAddress],  # 邮箱地址
    phone_numbers: List[PhoneNumber],      # 电话号码
    organizations: List[Organization],    # 组织信息
    relations: List[Relation],             # 关系人
    bio: str,               # 个人简介
    photos: List[Photo],    # 照片
}
```

资料来源：[gcontacts/contacts_tools.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gcontacts/contacts_tools.py)

## Chat 即时通讯服务

### 功能概述

Google Chat 是 Google Workspace 的企业级即时通讯工具，Chat 服务允许 AI 代理在 Spaces（聊天室）中发送消息、获取历史记录和附件。对于团队协作场景，AI 代理可以直接在 Chat 中与用户和群组进行交互。

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `send_message` | 发送消息到 Space | Core |
| `get_messages` | 获取 Space 中的消息历史 | Core |
| `search_messages` | 搜索消息内容 | Core |
| `create_reaction` | 为消息添加表情反应 | Core |
| `list_spaces` | 列出用户所属的所有 Spaces | Extended |
| `download_chat_attachment` | 下载聊天附件 | Extended |

### Chat 工作流程

```mermaid
sequenceDiagram
    participant User as 用户
    participant AI as AI代理
    participant Chat as Google Chat API
    
    User->>AI: 请求发送消息
    AI->>AI: 验证 Space ID 和权限
    AI->>Chat: POST /v1/spaces/{spaceId}/messages
    Chat-->>AI: 消息发送成功
    AI-->>User: 返回消息详情
```

### 多账户支持说明

社区 Issue #815 指出，文档中提及"多用户支持"但未详细说明工作原理。在 Chat 服务中，多账户场景下不同客户端会如何解析账户绑定是一个需要关注的配置问题。当 AI 代理需要向特定用户的 Space 发送消息时，应明确指定用户身份或使用 `user_google_email` 参数进行身份验证。

## Tasks 任务管理服务

### 功能概述

Google Tasks 是 Google Workspace 的轻量级任务管理工具。Tasks 服务允许 AI 代理创建待办事项、列出任务列表、管理任务完成状态。这对于将 AI 工作流与用户个人任务管理集成非常有用。

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `get_task` | 获取任务详情 | Core |
| `list_tasks` | 列出任务列表中的所有任务 | Core |
| `manage_task` | 创建、更新、删除任务 | Core |
| `list_task_lists` | 列出所有任务列表 | Complete |
| `get_task_list` | 获取任务列表详情 | Complete |
| `manage_task_list` | 创建、更新、删除任务列表 | Complete |

### 社区需求

根据社区讨论（Issue #69），Google Tasks 是用户呼声较高的功能需求。尽管当前实现已覆盖基本功能，但社区成员期望 AI 能够：
- 创建任务和待办事项
- 列出需要处理的工作
- 标记任务完成

## Forms 表单服务

### 功能概述

Google Forms 是 Google Workspace 的表单收集工具，Forms 服务允许 AI 代理创建表单、收集响应和查看分析数据。这对于调查、反馈收集和预约管理等场景非常实用。

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `create_form` | 创建新表单 | Core |
| `get_form` | 获取表单详情 | Core |
| `list_form_responses` | 列出表单响应 | Extended |
| `set_publish_settings` | 设置表单发布选项 | Complete |
| `get_form_response` | 获取单个表单响应详情 | Complete |
| `batch_update_form` | 批量更新表单内容 | Complete |

### 表单创建流程

```mermaid
graph TD
    A[定义表单问题] --> B[create_form 创建表单]
    B --> C[获取表单ID]
    C --> D[batch_update_form 添加问题]
    D --> E[set_publish_settings 配置发布]
    E --> F[表单可分享使用]
```

## Search 自定义搜索服务

### 功能概述

Search 服务集成了 Google Custom Search API，允许 AI 代理执行网络搜索并返回结构化结果。这对于需要获取外部信息的 AI 工作流非常有用。

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `search_custom` | 执行自定义网络搜索 | Core |
| `get_search_engine_info` | 获取搜索引擎配置信息 | Complete |

### 使用限制

自定义搜索需要配置 Google Custom Search Engine (CSE)，包括：
- API 密钥（用于 Google Search API 访问）
- 搜索引擎 ID（Search Engine ID）

## Apps Script 自动化服务

### 功能概述

Apps Script 是 Google Workspace 的自动化引擎，Apps Script 服务提供了完整的脚本项目管理能力。通过 MCP 工具，AI 代理可以创建、编辑、执行和部署 Apps Script 项目，实现复杂的跨应用工作流自动化。

资料来源：[gappsscript/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/README.md)

### 核心工具列表

| 工具名称 | 功能说明 | 层级 |
|---------|---------|-----|
| `list_script_projects` | 列出所有 Apps Script 项目 | Core |
| `get_script_project` | 获取项目详情 | Core |
| `get_script_content` | 获取脚本内容 | Core |
| `create_script_project` | 创建新脚本项目 | Core |
| `update_script_content` | 更新脚本内容 | Core |
| `run_script_function` | 执行脚本函数 | Core |
| `generate_trigger_code` | 生成触发器代码 | Core |
| `manage_deployment` | 管理部署 | Extended |
| `list_deployments` | 列出部署 | Extended |
| `delete_script_project` | 删除脚本项目 | Extended |
| `list_versions` | 列出版本 | Extended |
| `create_version` | 创建版本快照 | Extended |
| `get_version` | 获取版本详情 | Extended |
| `list_script_processes` | 列出执行进程 | Extended |
| `get_script_metrics` | 获取执行指标 | Extended |

### Apps Script 能力矩阵

```mermaid
graph TD
    subgraph 项目管理
        A1[创建项目] --> A2[编辑代码]
        A2 --> A3[版本控制]
        A3 --> A4[删除项目]
    end
    
    subgraph 执行与部署
        B1[执行函数] --> B2[查看执行日志]
        B2 --> B3[创建部署]
        B3 --> B4[版本回滚]
    end
    
    subgraph 触发器
        C1[时间触发] --> C2[事件触发]
        C2 --> C3[生成触发代码]
    end
    
    A3 --> B3
    C3 --> A2
```

### 已知问题

根据社区 Issue #809，`delete_script_project` 和 `create_version` 工具声明的 scope 别名（`drive_full`、`script_full`）未在 `SCOPE_GROUPS` 中注册。这会导致 `_resolve_scopes` 失败，引发永久性认证失败。遇到此问题时，用户可能需要手动调整 OAuth 作用域配置。

## API 启用管理

当用户尝试使用某个服务但未启用相应 API 时，系统会生成包含启用链接的错误消息。以下是各服务对应的 API 和启用链接：

| 服务 | API 端点 | 启用链接 |
|-----|---------|---------|
| Calendar | calendar-json.googleapis.com | [启用链接](https://console.cloud.google.com/flows/enableapi?apiid=calendar-json.googleapis.com) |
| Contacts | people.googleapis.com | - |
| Chat | chat.googleapis.com | [启用链接](https://console.cloud.google.com/flows/enableapi?apiid=chat.googleapis.com) |
| Tasks | tasks.googleapis.com | [启用链接](https://console.cloud.google.com/flows/enableapi?apiid=tasks.googleapis.com) |
| Forms | forms.googleapis.com | [启用链接](https://console.cloud.google.com/flows/enableapi?apiid=forms.googleapis.com) |
| Search | customsearch.googleapis.com | [启用链接](https://console.cloud.google.com/flows/enableapi?apiid=customsearch.googleapis.com) |

资料来源：[core/api_enablement.py:1-50](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/api_enablement.py)

## 日志记录与调试

这些服务共享统一的日志格式化系统，便于调试和监控：

```python
# 日志前缀映射
LOG_PREFIXES = {
    "gcalendar.calendar_tools": "[CALENDAR]",
    "gcontacts.contacts_tools": "[CONTACTS]",
    "gchat.chat_tools": "[CHAT]",
    "gtasks.tasks_tools": "[TASKS]",
    "gforms.forms_tools": "[FORMS]",
    "gsearch.search_tools": "[SEARCH]",
    "gappsscript.apps_script_tools": "[APPSCRIPT]",
}
```

资料来源：[core/log_formatter.py:40-55](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/log_formatter.py)

## 服务依赖关系

```mermaid
graph LR
    Calendar -->|日历事件| Drive
    Forms -->|响应存储| Drive
    AppsScript -->|访问| Docs
    AppsScript -->|访问| Sheets
    AppsScript -->|访问| Gmail
    Chat -->|附件| Drive
    
    style Drive fill:#9f9,stroke:#333,stroke-width:2px
```

## 常见问题与故障排除

### 1. API 未启用错误

**症状**：调用工具时返回 "API has not been used in project" 错误

**解决方案**：
1. 访问错误消息中的启用链接
2. 选择正确的 Google Cloud 项目
3. 点击启用按钮
4. 等待 1-2 分钟让更改生效
5. 重新尝试调用工具

### 2. 权限不足

**症状**：返回 "Insufficient Permission" 错误

**解决方案**：
1. 验证 OAuth scopes 已正确授权
2. 检查 `SCOPE_GROUPS` 配置是否包含所需作用域
3. 如有必要，重新进行身份验证

### 3. Apps Script 函数未找到

**症状**：`run_script_function` 返回 "Function not found"

**排查步骤**：
1. 检查函数名称拼写
2. 确认函数存在于脚本中
3. 确保函数不是 private（私有）函数
4. 验证函数签名符合 Apps Script API 要求

### 4. OAuth 重授权循环

根据社区反馈（Issue #810），在 streamable-HTTP 传输模式下，OAuth 回调可能将凭证存储在 `google-<state>` 会话中，导致每次工具调用后都需要重新授权。这与 MCP 会话的绑定机制有关。

## 总结

Calendar/Contacts/Chat 及其他服务构成了 Google Workspace MCP 的协作和自动化能力基础。这些服务使 AI 代理能够：

| 能力 | 服务 | 应用场景 |
|-----|------|---------|
| 时间管理 | Calendar | 会议安排、日程协调 |
| 联系人管理 | Contacts | 邮件验证、用户查询 |
| 即时通讯 | Chat | 团队协作、通知推送 |
| 任务跟踪 | Tasks | 待办管理、工作流集成 |
| 数据收集 | Forms | 调查问卷、预约管理 |
| 外部搜索 | Search | 信息检索、知识补充 |
| 流程自动化 | Apps Script | 跨应用工作流、自定义业务逻辑 |

通过这些服务的组合使用，AI 代理可以为用户提供完整的 Google Workspace 协作体验，实现从个人效率工具到企业级自动化解决方案的各种用例。

---

<a id='deployment-guide'></a>

## 部署指南

### 相关页面

相关主题：[快速入门指南](#quick-start), [CLI 工具与工具层级](#cli-usage)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [helm-chart/workspace-mcp/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/helm-chart/workspace-mcp/README.md)
- [Dockerfile](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/Dockerfile)
- [docker-compose.yml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/docker-compose.yml)
- [README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/README.md)
- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
</details>

# 部署指南

## 概述

Google Workspace MCP 支持多种部署方式，包括本地开发、Docker容器化部署和Kubernetes集群部署。本指南涵盖从开发环境到生产环境的完整部署流程，帮助用户根据实际需求选择合适的部署方案。

Workspace MCP 的核心功能通过 FastMCP 框架实现，支持OAuth 2.0/2.1认证、工具分层加载、多账户管理等企业级特性。部署时需要关注认证凭证配置、网络可达性、资源限制和安全性配置等关键要素。

## 部署架构

### 系统组件架构

```mermaid
graph TD
    A[用户/MCP客户端] --> B[Workspace MCP 服务]
    B --> C[Google OAuth 2.0 Provider]
    C --> D[Google Workspace APIs]
    
    E[(OAuth 凭证存储)] -.-> B
    F[Kubernetes/Docker 运行时] --> B
    
    subgraph 部署模式
        G[本地开发模式]
        H[Docker 单节点部署]
        I[Kubernetes 集群部署]
    end
```

### 认证流程架构

```mermaid
sequenceDiagram
    participant User as 用户
    participant MCP as Workspace MCP
    participant OAuth as Google OAuth
    participant API as Google APIs
    
    User->>MCP: 请求工具调用
    MCP->>OAuth: 发起OAuth认证
    OAuth->>User: 浏览器登录
    User->>OAuth: 完成认证
    OAuth->>MCP: 返回凭证
    MCP->>API: 授权请求
    API-->>MCP: 返回数据
    MCP-->>User: 返回结果
```

## 环境要求

### 硬件与系统要求

| 配置级别 | CPU | 内存 | 磁盘 | 适用场景 |
|---------|-----|------|------|---------|
| 最低配置 | 500m | 512Mi | 1GB | 开发测试 |
| 推荐配置 | 1000m | 1Gi | 5GB | 生产使用 |
| 高可用配置 | 2000m | 2Gi | 10GB | 多用户环境 |

### 软件依赖

- Python 3.10+
- Docker 20.10+ (容器部署)
- Kubernetes 1.24+ (集群部署)
- Helm 3.8+ (Kubernetes包管理)

## Docker 部署

### Dockerfile 配置

Workspace MCP 提供优化的 Docker 镜像，采用多阶段构建以减小镜像体积：

```dockerfile
# 使用多阶段构建
FROM python:3.10-slim as builder

# 安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 生产镜像
FROM python:3.10-slim
COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages
COPY . /app
WORKDIR /app
USER non-root-user

CMD ["python", "main.py"]
```

### Docker Compose 配置

基础部署配置：

```yaml
version: '3.8'

services:
  workspace-mcp:
    build: .
    container_name: workspace-mcp
    environment:
      - GOOGLE_OAUTH_CLIENT_ID=${GOOGLE_OAUTH_CLIENT_ID}
      - GOOGLE_OAUTH_CLIENT_SECRET=${GOOGLE_OAUTH_CLIENT_SECRET}
      - MCP_ENABLE_OAUTH21=true
    ports:
      - "8000:8000"
    volumes:
      - ./credentials:/app/credentials
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
```

### 启动命令

```bash
# 构建并启动
docker-compose up -d

# 查看日志
docker-compose logs -f

# 停止服务
docker-compose down
```

## Kubernetes 部署

### Helm Chart 架构

```mermaid
graph LR
    A[Helm] --> B[workspace-mcp Chart]
    B --> C[Deployment]
    B --> D[Service]
    B --> E[ConfigMap]
    B --> F[Secret]
    B --> G[Ingress]
    B --> H[HPA]
```

### 安装步骤

#### 1. 添加 Helm 仓库

```bash
# 如果已克隆仓库
cd helm-chart/workspace-mcp

# 或从远程安装（如适用）
helm repo add workspace-mcp https://taylorwilsdon.github.io/google_workspace_mcp
```

#### 2. 配置 OAuth 凭证

创建 Kubernetes Secret 存储敏感信息：

```bash
kubectl create secret generic workspace-mcp-secrets \
  --from-literal=GOOGLE_OAUTH_CLIENT_ID="your-client-id" \
  --from-literal=GOOGLE_OAUTH_CLIENT_SECRET="your-client-secret" \
  --from-literal=GOOGLE_OAUTH_USER_EMAIL="user@example.com"
```

#### 3. 安装 Chart

```bash
# 使用本地 Chart
helm install workspace-mcp ./helm-chart/workspace-mcp \
  --set secrets.googleOAuth.clientId="your-client-id" \
  --set secrets.googleOAuth.clientSecret="your-client-secret" \
  --set secrets.googleOAuth.userEmail="user@example.com"

# 使用自定义配置
helm install workspace-mcp ./helm-chart/workspace-mcp \
  --values ./custom-values.yaml
```

## 配置参数

### Helm Chart 配置选项

| 参数 | 描述 | 默认值 |
|------|------|--------|
| `replicaCount` | 副本数量 | `1` |
| `image.repository` | 镜像仓库 | `taylorwilsdon/workspace-mcp` |
| `image.tag` | 镜像标签 | `""` (使用 Chart.AppVersion) |
| `image.pullPolicy` | 镜像拉取策略 | `IfNotPresent` |
| `secrets.googleOAuth.clientId` | Google OAuth 客户端 ID | `""` (必填) |
| `secrets.googleOAuth.clientSecret` | Google OAuth 客户端密钥 | `""` (必填) |
| `secrets.googleOAuth.userEmail` | 单用户模式默认邮箱 | `""` |
| `singleUserMode` | 启用单用户模式 | `false` |
| `tools.enabled` | 启用的工具列表 | `[]` (全部启用) |
| `env.MCP_ENABLE_OAUTH21` | 启用 OAuth 2.1 支持 | `"true"` |
| `service.type` | Kubernetes Service 类型 | `ClusterIP` |
| `service.port` | Service 端口 | `8000` |
| `ingress.enabled` | 启用 Ingress | `false` |
| `resources.limits.cpu` | CPU 限制 | `500m` |
| `resources.limits.memory` | 内存限制 | `512Mi` |
| `autoscaling.enabled` | 启用 HPA | `false` |

### 工具层级配置

通过 `tools.enabled` 参数可以限制启用的工具，支持按服务分组：

```yaml
tools:
  enabled:
    # 核心文档工具
    - gdocs
    # 核心表格工具
    - gsheets
    # Gmail 工具
    - gmail
    # 日历工具
    - gcalendar
```

可用服务分组：

| 服务 | 说明 | 核心工具数 |
|------|------|-----------|
| `gdocs` | Google Docs 文档 | 3 |
| `gsheets` | Google Sheets 电子表格 | 3 |
| `gslides` | Google Slides 演示文稿 | 2 |
| `gmail` | Gmail 邮件服务 | - |
| `gcalendar` | Calendar 日历 | - |
| `gdrive` | Drive 云端硬盘 | - |
| `gchat` | Chat 即时通讯 | 2 |
| `gforms` | Forms 表单 | 2 |
| `gtasks` | Tasks 任务管理 | 3 |
| `gcontacts` | Contacts 联系人 | 4 |
| `gsearch` | 自定义搜索 | 1 |
| `gappsscript` | Apps Script 脚本 | 7 |

## Google OAuth 配置

### 创建 OAuth 凭证

1. 访问 [Google Cloud Console](https://console.cloud.google.com/)
2. 创建新项目或选择现有项目
3. 启用所需的 Google Workspace API：
   - Google Drive API
   - Google Docs API
   - Google Sheets API
   - Gmail API
   - Calendar API
   - Apps Script API

4. 配置 OAuth 同意屏幕：
   - 选择用户类型（内部/外部）
   - 填写应用信息
   - 配置授权域名

5. 创建 OAuth 2.0 客户端凭证：
   - 应用类型：Web 应用
   - 配置授权重定向 URI

### OAuth 回调配置

| 部署模式 | 回调 URI |
|---------|---------|
| 本地开发 | `http://localhost:8000/oauth2callback` |
| Docker | `http://<服务器IP>:8000/oauth2callback` |
| Kubernetes | `http://<域名>:8000/oauth2callback` |

### OAuth 2.1 支持

v1.21.1 版本引入了 OAuth 2.1 支持，通过 `MCP_ENABLE_OAUTH21=true` 环境变量启用。新版本包含以下改进：

- 自动打开浏览器进行 OAuth 认证
- 支持 `login_hint` 参数预填充用户邮箱
- 改进的主机绑定安全性

## 安全配置

### 容器安全设置

Workspace MCP 镜像采用安全强化配置：

```yaml
securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  readOnlyRootFilesystem: true
  capabilities:
    drop:
      - ALL
```

### 网络策略

建议配置 Kubernetes NetworkPolicy 限制网络访问：

```yaml
networkPolicy:
  enabled: true
  ingress:
    - from:
        - podSelector:
            matchLabels:
              app: mcp-client
  egress:
    - to:
        - podSelector:
            matchLabels:
              app: workspace-mcp
```

### 凭证管理

| 存储方式 | 适用场景 | 安全等级 |
|---------|---------|---------|
| Kubernetes Secret | 生产环境 | 高 |
| 环境变量 | 开发测试 | 中 |
| ConfigMap | 非敏感配置 | - |

## 健康检查

Helm Chart 包含内置健康检查配置：

```yaml
healthCheck:
  liveness:
    enabled: true
    path: /health
    initialDelaySeconds: 30
    periodSeconds: 10
  readiness:
    enabled: true
    path: /health
    initialDelaySeconds: 5
    periodSeconds: 5
```

健康检查端点：

- **Liveness Probe**: 验证应用进程存活
- **Readiness Probe**: 验证服务是否可接收流量

## 高可用配置

### 水平 Pod 自动扩缩容

```yaml
autoscaling:
  enabled: true
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
  targetMemoryUtilizationPercentage: 80
```

### 多副本部署

```yaml
replicaCount: 3

affinity:
  podAntiAffinity:
    preferredDuringSchedulingIgnoredDuringExecution:
      - weight: 100
        podAffinityTerm:
          labelSelector:
            matchExpressions:
              - key: app
                operator: In
                values:
                  - workspace-mcp
          topologyKey: kubernetes.io/hostname
```

## 故障排除

### 常见部署问题

#### 1. OAuth 认证失败

**问题症状**：部署后首次访问出现认证错误

**排查步骤**：

```bash
# 检查日志
kubectl logs -f deployment/workspace-mcp

# 验证 Secret 配置
kubectl get secret workspace-mcp-secrets -o yaml

# 检查 OAuth 回调 URI 配置是否匹配
```

**解决方案**：
- 确认 Google Cloud Console 中的回调 URI 与实际部署地址匹配
- 验证 `GOOGLE_OAUTH_CLIENT_ID` 和 `GOOGLE_OAUTH_CLIENT_SECRET` 正确配置

#### 2. 端口冲突

**问题症状**：`Port 8000 already in use` 错误

**背景**：在 Windows 系统上，如果父进程异常终止，Python 子进程可能残留并占用端口。资料来源：[issue #816](https://github.com/taylorwilsdon/google_workspace_mcp/issues/816)

**排查步骤**：

```bash
# Linux/Mac
lsof -i :8000
kill -9 <PID>

# Windows
netstat -ano | findstr :8000
taskkill /PID <PID> /F
```

#### 3. 孤儿进程导致认证失败

**问题症状**：每次认证尝试都返回 "invalid state" 错误

**原因**：之前的 workspace-mcp 进程未正确终止，仍持有 OAuth 回调端口

**解决方案**：

```bash
# 终止所有相关进程
pkill -f "python.*main.py"
# 或在 Windows 上
taskkill /IM python.exe /F
```

### 验证部署

```bash
# 检查 Pod 状态
kubectl get pods -l app=workspace-mcp

# 检查服务状态
kubectl get svc workspace-mcp

# 测试健康端点
kubectl port-forward svc/workspace-mcp 8000:8000
curl http://localhost:8000/health
```

## 升级指南

### Helm 升级

```bash
# 拉取最新 Chart
helm repo update

# 升级部署
helm upgrade workspace-mcp ./helm-chart/workspace-mcp \
  --set secrets.googleOAuth.clientId="your-client-id" \
  --set secrets.googleOAuth.clientSecret="your-client-secret"
```

### 版本兼容性

| Chart 版本 | Workspace MCP 版本 | 关键特性 |
|-----------|-------------------|---------|
| 1.21.x | 1.21.x | OAuth 2.1 支持、健康检查增强 |
| 1.20.x | 1.20.x | API 重试逻辑、driveId 字段 |

## 监控与日志

### 日志配置

Workspace MCP 使用增强日志格式化器：

```yaml
env:
  LOG_LEVEL: INFO
  LOG_FORMAT: enhanced
```

日志前缀映射：

| 服务模块 | 日志前缀 |
|---------|---------|
| 工具注册 | `[TOOLS]` |
| OAuth 认证 | `[OAUTH]` |
| Drive 工具 | `[DRIVE]` |
| Gmail 工具 | `[GMAIL]` |
| Docs 工具 | `[DOCS]` |
| Sheets 工具 | `[SHEETS]` |

### 资源监控

```yaml
resources:
  requests:
    cpu: 250m
    memory: 256Mi
  limits:
    cpu: 500m
    memory: 512Mi
```

## 相关资源

- [官方文档](https://workspacemcp.com)
- [GitHub 仓库](https://github.com/taylorwilsdon/google_workspace_mcp)
- [问题反馈](https://github.com/taylorwilsdon/google_workspace_mcp/issues)
- [版本发布](https://github.com/taylorwilsdon/google_workspace_mcp/releases)

---

<a id='cli-usage'></a>

## CLI 工具与工具层级

### 相关页面

相关主题：[项目概述](#project-overview), [部署指南](#deployment-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [core/tool_tiers.yaml](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tiers.yaml)
- [core/cli.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/cli.py)
- [core/tool_tier_loader.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_tier_loader.py)
- [core/tool_registry.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/tool_registry.py)
- [core/server.py](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/core/server.py)
- [gappsscript/README.md](https://github.com/taylorwilsdon/google_workspace_mcp/blob/main/gappsscript/README.md)
</details>

# CLI 工具与工具层级

## 概述

Google Workspace MCP 提供两套访问接口：一是通过 MCP 协议与 AI 代理交互，二是通过命令行界面（CLI）直接调用工具。工具层级系统（Tool Tiers）则允许用户根据需要选择性加载不同功能集的工具，从最小化的核心工具到完整功能集的分层架构。

CLI 工具位于 `core/cli.py` 模块，提供持久化 OAuth 令牌缓存的独立命令行接口。工具层级系统由 `core/tool_tiers.yaml` 配置文件定义，通过 `core/tool_tier_loader.py` 模块加载解析，实现条件化工具注册机制。

## 工具层级架构

### 三层设计

工具系统按照功能完整性和使用频率划分为三个层级：

| 层级 | 含义 | 用途 |
|------|------|------|
| `core` | 核心工具 | 基础读写操作，必备功能 |
| `extended` | 扩展工具 | 高级功能，列表查询 |
| `complete` | 完整工具 | 全部功能，管理操作 |

这种分层设计使用户能够根据部署场景和安全策略选择合适的工具集。例如，在只读场景下可仅启用核心工具，减少权限暴露。

### 服务与工具映射

工具按服务类型分组，每个服务在不同层级包含不同数量的工具：

```yaml
docs:
  core:
    - get_doc_content
    - create_doc
    - modify_doc_text
  extended:
    - export_doc_to_pdf
    - search_docs
    - find_and_replace_doc
  complete:
    - insert_doc_image
    - batch_update_doc

sheets:
  core:
    - create_spreadsheet
    - read_sheet_values
    - modify_sheet_values
  extended:
    - list_spreadsheets
    - get_spreadsheet_info
  complete:
    - create_sheet
    - append_table_rows
```

资料来源：[core/tool_tiers.yaml:1-30]()

## 层级加载机制

### ToolTierLoader 类

`ToolTierLoader` 类负责从 YAML 配置文件加载层级定义：

```python
class ToolTierLoader:
    def __init__(self, config_path: Optional[str] = None):
        if config_path is None:
            config_path = Path(__file__).parent / "tool_tiers.yaml"
        self.config_path = Path(config_path)
```

资料来源：[core/tool_tier_loader.py:25-32]()

### 层级解析流程

```mermaid
graph TD
    A[加载 tool_tiers.yaml] --> B[resolve_tools_from_tier tier services]
    B --> C{指定服务过滤?}
    C -->|是| D[筛选指定服务的工具]
    C -->|否| E[获取所有服务工具]
    D --> F[返回工具名称列表]
    E --> F
    F --> G[映射到服务名称]
    G --> H[日志记录加载结果]
```

`resolve_tools_from_tier` 函数根据指定层级和服务返回对应的工具列表和服务名称：

```python
def resolve_tools_from_tier(
    tier: TierLevel, services: Optional[List[str]] = None
) -> tuple[List[str], List[str]]:
    loader = ToolTierLoader()
    tools = loader.get_tools_up_to_tier(tier, services)
    service_names = loader.get_services_for_tools(tools)
    return tools, sorted(service_names)
```

资料来源：[core/tool_tier_loader.py:104-117]()

## 条件化工具注册

### ToolRegistry 模块

`core/tool_registry.py` 实现了条件化工具注册机制，允许基于已启用工具集合动态注册工具：

```python
def conditional_tool(server, tool_name: str):
    def decorator(func: Callable) -> Callable:
        if is_tool_enabled(tool_name):
            logger.debug(f"Registering tool: {tool_name}")
            return server.tool()(func)
        else:
            logger.debug(f"Tool disabled: {tool_name}")
            return func  # No-op decorator
```

资料来源：[core/tool_registry.py:43-53]()

### 启用工具管理

工具注册状态通过全局变量管理：

```python
_enabled_tools: Optional[Set[str]] = None

def set_enabled_tools(tool_names: Optional[Set[str]]):
    global _enabled_tools
    _enabled_tools = tool_names

def is_tool_enabled(tool_name: str) -> bool:
    if _enabled_tools is None:
        return True  # 所有工具默认启用
    return tool_name in _enabled_tools
```

资料来源：[core/tool_registry.py:10-25]()

## CLI 命令行工具

### 基本用法

`workspace-cli` 是 MCP 服务器的命令行客户端，位于 `core/cli.py`：

```bash
# 列出可用工具
workspace-cli list

# 调用指定工具
workspace-cli call <tool_name> [args...]
```

资料来源：[core/cli.py:48-60]()

### 环境配置

CLI 支持通过环境变量或参数指定 MCP 服务器地址：

```python
parser.add_argument(
    "--url",
    default=os.getenv("WORKSPACE_MCP_URL", DEFAULT_URL),
    help=f"MCP server URL (default: {DEFAULT_URL})",
)
```

资料来源：[core/cli.py:32-35]()

### 工具调用格式

```bash
# 格式：tool_name key=value key2=value2
workspace-cli call create_doc title="我的文档" content="# Hello"

# 列出所有可用工具
workspace-cli list
```

## 服务与层级对应关系

### 完整服务映射表

| 服务 | Core 工具数 | Extended 工具数 | Complete 工具数 | 说明 |
|------|-------------|-----------------|-----------------|------|
| docs | 3 | 7 | 9 | Google 文档 |
| sheets | 3 | 5 | 11 | Google 表格 |
| slides | 2 | 5 | 9 | Google 幻灯片 |
| forms | 2 | 3 | 6 | Google 表单 |
| chat | 4 | 6 | 6 | Google Chat |
| drive | 3 | 7 | 11 | Google Drive |
| calendar | 3 | 8 | 12 | Google 日历 |
| gmail | 4 | 10 | 15 | Gmail |
| contacts | 2 | 4 | 6 | 联系人 |
| tasks | 2 | 4 | 6 | 任务 |
| search | 1 | 3 | 5 | 搜索 |
| appsscript | 7 | 10 | 17 | Apps Script |

资料来源：[core/tool_tiers.yaml]()

### Apps Script 工具层级详解

Apps Script 提供最丰富的工具集，支持脚本项目的完整生命周期管理：

**Core 层级（7个工具）**

- `list_script_projects` - 列出所有项目
- `get_script_project` - 获取项目详情
- `get_script_content` - 获取文件内容
- `create_script_project` - 创建新项目
- `update_script_content` - 更新文件
- `run_script_function` - 执行函数
- `generate_trigger_code` - 生成触发器代码

**Extended 层级（10个工具）**

- `create_deployment` - 创建部署
- `list_deployments` - 列出部署
- `update_deployment` - 更新部署
- `delete_deployment` - 删除部署
- `delete_script_project` - 删除项目
- `list_versions` - 列出版本
- `create_version` - 创建版本快照

**Complete 层级（17个工具）**

包含执行历史监控、指标分析等高级功能。

资料来源：[gappsscript/README.md]()

## 配置与集成

### Helm Chart 配置

在 Kubernetes 部署中，可通过 values.yaml 控制工具启用：

```yaml
tools:
  enabled: []  # 空数组表示启用全部工具

# 启用指定工具
tools:
  enabled:
    - list_script_projects
    - get_script_project
```

资料来源：[helm-chart/workspace-mcp/README.md]()

### OAuth 与权限模式

工具层级系统与权限模式集成，支持只读模式限制：

```python
from auth.scopes import is_read_only_mode, get_all_read_only_scopes

def conditional_tool(server, tool_name: str):
    # 检查工具是否在只读允许范围内
```

资料来源：[core/tool_registry.py:1-10]()

## 常见问题

### 工具未注册

如果某工具不可用，检查：

1. 层级配置是否包含该工具
2. 服务模块是否正确导入
3. 权限范围是否满足

### Windows 平台注意

在 Windows 上，OAuth 回调端口（8000-8004）可能因进程未正常退出而被占用。如遇连接问题，参考 v1.21.0 版本的 Windows 文件名兼容性修复。

### 已知问题：未注册的作用域别名

Apps Script 模块中的 `delete_script_project` 和 `create_version` 工具声明了未在 `SCOPE_GROUPS` 中注册的作用域别名（`drive_full`, `script_full`），可能导致权限解析失败。详见 [GitHub Issue #809](https://github.com/taylorwilsdon/google_workspace_mcp/issues/809)。

## 最佳实践

### 生产环境部署

1. **最小权限原则**：根据实际需求选择合适的工具层级，避免启用完整工具集
2. **层级渐进式启用**：先启用 core 层级，测试通过后再扩展
3. **日志监控**：利用增强日志格式化（`core/log_formatter.py`）追踪工具调用

### 开发调试

1. 使用 `workspace-cli list` 查看当前启用的工具
2. 通过 CLI 直接调用工具进行快速测试
3. 查看工具注册日志确认加载状态

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：taylorwilsdon/google_workspace_mcp

摘要：发现 31 个潜在踩坑项，其中 4 个为 high/blocking；最高优先级：安装坑 - 来源证据：[Feature Request] Add import_to_google_slides tool for PPTX conversion。

## 1. 安装坑 · 来源证据：[Feature Request] Add import_to_google_slides tool for PPTX conversion

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature Request] Add import_to_google_slides tool for PPTX conversion
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f871a29d45124aa7b0a5ddf0927e595a | https://github.com/taylorwilsdon/google_workspace_mcp/issues/568 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 安全/权限坑 · 失败模式：security_permissions: Add content replacement support to `update_drive_file` (re-import with format conversion)

- 严重度：high
- 证据强度：source_linked
- 发现：Developers should check this security_permissions risk before relying on the project: Add content replacement support to `update_drive_file` (re-import with format conversion)
- 对用户的影响：Developers may expose sensitive permissions or credentials: Add content replacement support to `update_drive_file` (re-import with format conversion)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Add content replacement support to `update_drive_file` (re-import with format conversion). Context: Observed during version upgrade or migration.
- 防护动作：Do not recommend enabling privileged or credential-bearing paths until the source-backed risk is reviewed: https://github.com/taylorwilsdon/google_workspace_mcp/issues/604
- 证据：failure_mode_cluster:github_issue | fmev_3c8303e858d6e3babf62908a594c01d5 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/604 | Add content replacement support to `update_drive_file` (re-import with format conversion)

## 3. 安全/权限坑 · 来源证据：Add content replacement support to `update_drive_file` (re-import with format conversion)

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Add content replacement support to `update_drive_file` (re-import with format conversion)
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_80d9501239cf445d97725797177e9bee | https://github.com/taylorwilsdon/google_workspace_mcp/issues/604 | 来源类型 github_issue 暴露的待验证使用条件。

## 4. 安全/权限坑 · 来源证据：Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callback port (8000-8004 exhaus…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callback port (8000-8004 exhausted after 5 crashes)
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_36a1aade8bf74121947b6fbe430ec6a1 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/816 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 5. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `google_workspace_mcp` 与安装入口 `workspace-mcp` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`uvx workspace-mcp`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | repo=google_workspace_mcp; install=workspace-mcp

## 6. 安装坑 · 失败模式：installation: Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `de...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `delete_script_project` and `create_version`
- 对用户的影响：Developers may fail before the first successful local run: Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `delete_script_project` and `create_version`
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `delete_script_project` and `create_version`. Context: Observed when using python
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_e7cb2e2b3e59870680f53a03ba2ecf81 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/809 | Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `delete_script_project` and `create_version`

## 7. 安装坑 · 失败模式：installation: v1.17.1

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.17.1
- 对用户的影响：Upgrade or migration may change expected behavior: v1.17.1
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.17.1. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_212825a3c03db512b74b1674278bd9c0 | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.17.1 | v1.17.1

## 8. 配置坑 · 失败模式：configuration: Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound t...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound to the live MCP session — every tool call after re-auth re-prompts
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound to the live MCP session — every tool call after re-auth re-prompts
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound to the live MCP session — every tool call after re-auth re-prompts. Context: Observed when using python
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_6c9d034c0e1c92375af2d9eaa8490794 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/810 | Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound to the live MCP session — every tool call after re-auth re-prompts

## 9. 配置坑 · 失败模式：configuration: Scary Mode

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Scary Mode
- 对用户的影响：Upgrade or migration may change expected behavior: Scary Mode
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Scary Mode. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_f7ece854c6d958a3a069caa7373df268 | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.18.0 | Scary Mode

## 10. 配置坑 · 失败模式：configuration: Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callb...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callback port (8000-8004 exhausted after 5 crashes)
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callback port (8000-8004 exhausted after 5 crashes)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callback port (8000-8004 exhausted after 5 crashes). Context: Observed when using python, windows, macos
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_c2dc89d9e3e849d9cddbb644aa4b75c1 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/816 | Windows: workspace-mcp Python child survives ungraceful parent termination, leaks OAuth callback port (8000-8004 exhausted after 5 crashes)

## 11. 配置坑 · 失败模式：configuration: docs: explain how multiple accounts are resolved by chat clients

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: docs: explain how multiple accounts are resolved by chat clients
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: docs: explain how multiple accounts are resolved by chat clients
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: docs: explain how multiple accounts are resolved by chat clients. Context: Observed during installation or first-run setup.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_373216a0ef880973a052e78391fffab8 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/815 | docs: explain how multiple accounts are resolved by chat clients

## 12. 配置坑 · 失败模式：configuration: v1.17.3

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: v1.17.3
- 对用户的影响：Upgrade or migration may change expected behavior: v1.17.3
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.17.3. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_23ae9dba36e9bcb4f30c233e5a6d4f3d | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.17.3 | v1.17.3

## 13. 配置坑 · 失败模式：configuration: v1.20.0

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: v1.20.0
- 对用户的影响：Upgrade or migration may change expected behavior: v1.20.0
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.20.0. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_335f77ccce1a25fdb7bb7210e1812380 | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.20.0 | v1.20.0

## 14. 配置坑 · 失败模式：configuration: v1.20.1

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: v1.20.1
- 对用户的影响：Upgrade or migration may change expected behavior: v1.20.1
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.20.1. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_cf32907b41b3d9932942b000c4911686 | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.20.1 | v1.20.1

## 15. 配置坑 · 失败模式：configuration: v1.20.3

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: v1.20.3
- 对用户的影响：Upgrade or migration may change expected behavior: v1.20.3
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.20.3. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_e6f9983131253c5196a0cc80fccdd25f | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.20.3 | v1.20.3

## 16. 配置坑 · 失败模式：configuration: v1.20.4

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: v1.20.4
- 对用户的影响：Upgrade or migration may change expected behavior: v1.20.4
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.20.4. Context: Source discussion did not expose a precise runtime context.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_f3468cf79495c8fe79a956d1869cedb1 | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.20.4 | v1.20.4

## 17. 配置坑 · 失败模式：configuration: v1.21.0

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: v1.21.0
- 对用户的影响：Upgrade or migration may change expected behavior: v1.21.0
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.21.0. Context: Observed when using windows
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_8511fb78f35540ce59157311860e4ef2 | https://github.com/taylorwilsdon/google_workspace_mcp/releases/tag/v1.21.0 | v1.21.0

## 18. 配置坑 · 来源证据：run_script_function broken after FastMCP v3 upgrade — parameters list received as JSON string

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：run_script_function broken after FastMCP v3 upgrade — parameters list received as JSON string
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_97ef2c42407f47709e72d3dba61ae3ab | https://github.com/taylorwilsdon/google_workspace_mcp/issues/712 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 19. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | README/documentation is current enough for a first validation pass.

## 20. 维护坑 · 失败模式：migration: feat(drive): add a create_drive_shortcut tool (files.create with shortcutDetails.targetId)

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this migration risk before relying on the project: feat(drive): add a create_drive_shortcut tool (files.create with shortcutDetails.targetId)
- 对用户的影响：Developers may hit a documented source-backed failure mode: feat(drive): add a create_drive_shortcut tool (files.create with shortcutDetails.targetId)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: feat(drive): add a create_drive_shortcut tool (files.create with shortcutDetails.targetId). Context: Observed when using python
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_2ec87f1d72214674879309753defc8a1 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/819 | feat(drive): add a create_drive_shortcut tool (files.create with shortcutDetails.targetId)

## 21. 维护坑 · 来源证据：feat(drive): Office→Google conversion on upload (pptx→Slides, xlsx→Sheets) — target mimeType ≠ media mimeType

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：feat(drive): Office→Google conversion on upload (pptx→Slides, xlsx→Sheets) — target mimeType ≠ media mimeType
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_30ea68889f9a4e4da2c609ff3d03088c | https://github.com/taylorwilsdon/google_workspace_mcp/issues/820 | 来源类型 github_issue 暴露的待验证使用条件。

## 22. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | last_activity_observed missing

## 23. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | no_demo; severity=medium

## 24. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | no_demo; severity=medium

## 25. 安全/权限坑 · 来源证据：Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound to the live MCP session — e…

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Re-auth loop: OAuth callback stores credentials under `google-<state>` session, never bound to the live MCP session — every tool call after re-auth re-prompts
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_70dcca3c374840d3bf8827dd387e1b97 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/810 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 26. 安全/权限坑 · 来源证据：Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `delete_script_project` and `…

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Unregistered scope aliases `drive_full` and `script_full` cause permanent auth-failure on `delete_script_project` and `create_version`
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ecdc714d95d44a269de52e7dfa33a6d1 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/809 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 27. 安全/权限坑 · 来源证据：docs: explain how multiple accounts are resolved by chat clients

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：docs: explain how multiple accounts are resolved by chat clients
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_cfa9fa150ca8402baa139651788b227a | https://github.com/taylorwilsdon/google_workspace_mcp/issues/815 | 来源类型 github_issue 暴露的待验证使用条件。

## 28. 能力坑 · 失败模式：conceptual: [Feature Request] Add import_to_google_slides tool for PPTX conversion

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this conceptual risk before relying on the project: [Feature Request] Add import_to_google_slides tool for PPTX conversion
- 对用户的影响：Developers may hit a documented source-backed failure mode: [Feature Request] Add import_to_google_slides tool for PPTX conversion
- 建议检查：复核 source-backed failure mode cluster，并把适用版本和验证路径写入资产。
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_a6cc303a74645a267da4d766f12cb139 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/568 | [Feature Request] Add import_to_google_slides tool for PPTX conversion

## 29. 能力坑 · 失败模式：conceptual: feat(drive): Office→Google conversion on upload (pptx→Slides, xlsx→Sheets) — target mimeType...

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this conceptual risk before relying on the project: feat(drive): Office→Google conversion on upload (pptx→Slides, xlsx→Sheets) — target mimeType ≠ media mimeType
- 对用户的影响：Developers may hit a documented source-backed failure mode: feat(drive): Office→Google conversion on upload (pptx→Slides, xlsx→Sheets) — target mimeType ≠ media mimeType
- 建议检查：复核 source-backed failure mode cluster，并把适用版本和验证路径写入资产。
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_b24e630634d2e4b6a4475a89ac58c670 | https://github.com/taylorwilsdon/google_workspace_mcp/issues/820 | feat(drive): Office→Google conversion on upload (pptx→Slides, xlsx→Sheets) — target mimeType ≠ media mimeType

## 30. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | issue_or_pr_quality=unknown

## 31. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:973788136 | https://github.com/taylorwilsdon/google_workspace_mcp | release_recency=unknown

<!-- canonical_name: taylorwilsdon/google_workspace_mcp; human_manual_source: deepwiki_human_wiki -->
