使用说明
服务表
生产级Google Sheets MCP服务器,具有25个工具、407个操作、安全轨道和企业功能。
什么是新的(v1.7.0后,2026-02-17→ 出席)
🧠 LLM智能Sprint、高级计算和生产强化
- ✅ 思维链提示:
_hints每一层sheets_data.read响应——数据形状、PK检测、公式机会、风险水平、下一阶段路由 - ✅ 响应情报:质量扫描器、动作推荐器、批处理提示和
_meta.apiCallsMade/_meta.executionTimeMs/_meta.quotaImpact每一个回应 - ✅ 高级计算:DuckDB SQL引擎(
sql_query,sql_join)Pyodide Python运行时(python_eval,pandas_profile,sklearn_model),公式计算器(HyperFormula v3.2.0) - ✅ 快速洞察+自动填充:
sheets_analyze.quick_insights(快速无AI结构快照),sheets_data.auto_fill(基于模式的填充:线性、日期、重复) - ✅ O(1)缓存大小跟踪:
CacheManager._totalSizeBytes运行计数器--getStats()/getTotalSize()不再是O(N) - ✅ 按电子表格调节:每个电子表格Id的令牌桶速率限制器(可通过以下方式配置
PER_SPREADSHEET_RPS,默认为3 RPS) - ✅ 计划加密:AES-256-GCM代理计划持久性(通过以下方式选择加入
PLAN_ENCRYPTION_KEY) - ✅ Webhook DNS强化:DNS默认关闭失败(
WEBHOOK_DNS_STRICT=true);选择不适用于片状环境 - ✅ 工作区事件:Google Workspace活动订阅,7天自动续订
- ✅ 调度器:
schedule_create/list/cancel/run_now具有节点cron+JSON持久性 - ✅ 类型错误类:全部
src/handlers/,src/connectors/,src/services/,src/utils/使用类型化错误类(ValidationError、ServiceError、ConfigError、NotFoundError、AuthenticationError) - ✅ 进度通知:超过25个处理程序操作为长时间运行的操作发出MCP进度通知
看 更改日志.md 了解完整细节。
v1.7.0(2026-02-17)
🚀 现代方程式智能与市场发布
- ✅ 高级兼容性界面:命名函数操作仍然公开以保持兼容性,现在返回clear
FEATURE_UNAVAILABLE当活动表单API无法支持时的指导 - ✅ 泄漏范围检测:通过查找动态数组公式
sheets_data.detect_spill_ranges - ✅ 公式预设:XLOOKUP、XMATCH、FILTER、BYROW/BYCOL通过
sheets_analyze.generate_formula - ✅ 市场就绪:
privacy_policiesserver.json中的数组(MCP注册表v0.3+) - ✅ 知识库:现代阵列和泄漏范围模式(
src/knowledge/formulas/modern-arrays.md)
快速开始
# Install globally
npm install -g servalsheets
# Or run directly with npx
npx servalsheets
# Claude Desktop config (~/.claude/claude_desktop_config.json)
{
"mcpServers": {
"servalsheets": {
"command": "npx",
"args": ["-y", "servalsheets"]
}
}
}
首次运行时,ServalSheets将指导您完成Google OAuth身份验证。
以往版本
历史发布快照保存在此处以供升级上下文使用。
v1.6.0 - Enterprise Deployment & Infrastructure (2026-01-26)
- Helm Charts、地形模块(AWS/GCP)、健康监测
- W3C跟踪上下文、模式缓存、Webhook支持
- VitePress文档(115+页)的每用户速率限制
v1.6.0 - Zod v4 & Performance (2026-01-10)
- 升级版Zod 3.25→ 4.3.5 使用本机JSON模式
- 字符串解析速度提高14倍,数组速度提高7倍
- 捆绑包尺寸减小57%
v1.6.0 - MCP Protocol Native (2026-01-06)
- MCP日志、任务、激励、采样支持
- 6个URI资源模板,完全中止控制器取消
v1.6.0 - Advanced Analytics (2026-01-05)
- 模式检测、列分析
- 基于人工智能的公式生成和图表推荐
特性
核心能力
- 25个工具,403个动作:全面的Google Sheets API v4覆盖范围
- MCP 2025-11-25支持:结构化输出、任务、提示、资源、日志记录、启发和采样
- 多个传输:STDIO、SSE和流式HTTP
- 安全围栏:试运行、影响范围限制、预期状态验证、用户确认
- OAuth 2.1支持:用于克劳德连接器目录集成
MCP协议支持
MCP 2025-11-25服务器支持包括:
- ✅ JSON-RPC 2.0:通过@modelcontextprotocol/sdk v1.27.1完全合规
- ✅ 工具25个工具,407个行动,使用歧视性工会
- ✅ 资源:6个URI模板+7个知识资源
sheets:///{spreadsheetId}-电子表格元数据sheets:///{spreadsheetId}/{range}-范围值sheets:///{spreadsheetId}/charts-图表规格sheets:///{spreadsheetId}/charts/{chartId}-个人图表详细信息sheets:///{spreadsheetId}/pivots-数据透视表配置sheets:///{spreadsheetId}/quality-数据质量分析- 公式、颜色、格式的知识资源
- ✅ 提示:48个共同业务指导工作流程
- ✅ 补全:提示/资源的参数自动补全
- ✅ 任务:支持完全取消的后台执行(SEP-1686)
- ✅ 引出:通过sheets_confirm确认计划(SEP-1036)
- ✅ 采样:通过sheets_analyze进行人工智能分析(SEP-1577)
- ✅ 日志记录:通过logging/setLevel处理程序进行动态日志级别控制
运输支持
- ✅ 工作室 -用于Claude Desktop和本地CLI使用
- ✅ HTTP/SSE -用于web客户端和远程访问
- ✅ OAuth 2.1 -托管部署的身份验证
高级分析🔬
- 模式检测:趋势分析、相关性、异常、季节性
- 柱分析:数据类型检测、分布、质量指标
- 统计分析:全面的数据质量和结构见解
AI驱动的功能🤖
- 模板建议:AI生成上下文电子表格模板
- 公式生成:自然语言→ 谷歌表格公式
- 图表建议:AI为您的数据提供最佳可视化建议
- 需要:具有MCP采样能力的客户(SEP-1577)
性能与优化⚡
- 请求重复数据删除:防止重复的API调用,减少配额使用
- 分层差分引擎:自动层选择(元数据/采样/满)
- 速率限制:内置令牌桶,对429个错误进行动态限制
- 有效载荷监测:自动大小跟踪,带有2MB警告,10MB硬限制
- 批量效率:实时优化分析和建议
- HTTP压缩:gzip中间件用于降低带宽
开发者体验🛠️
- 语义范围解析:按标题名称、命名范围或A1表示法查询
- 基于意图的架构:适用于所有突变的单批编译器
- 用户确认:破坏性操作的激励对话框(SEP-1036)
API文档📚
- OpenAPI 3.1规范:从Zod模式自动生成
- 交互式Swagger用户界面:测试终点位于
/api-docsHTTP服务器运行时 - 多种格式:用于SDK生成的JSON和YAML导出
- 25种工具记录在案:带有请求/响应架构的完整API参考
- 验证方案:记录了承载令牌和OAuth 2.0
访问文档:
npm run start:http # Start HTTP server
open http://localhost:3000/api-docs # View Swagger UI
看 OpenAPI文档指南 了解详情。
入门指南
安装
npm install servalsheets
使用克劳德桌面(STDIO)
添加 ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"servalsheets": {
"command": "npx",
"args": ["servalsheets"],
"env": {
"GOOGLE_APPLICATION_CREDENTIALS": "/path/to/service-account.json"
}
}
}
}
用作远程服务器(HTTP/SSE)
# Start HTTP server
npm run start:http
# Or with environment variables
PORT=3000 GOOGLE_CLIENT_ID=xxx GOOGLE_CLIENT_SECRET=xxx npm run start:http
OAuth作用域模式
ServalSheets使用部署感知的OAuth作用域来平衡功能和谷歌验证速度:
| 模式 | 可用操作 | 用例 | 谷歌验证时间 |
|---|---|---|---|
| 满的 (默认) | 403/403 | 自托管,企业 | 4-6周 |
| 标准 | ~340/403 | SaaS、市场应用程序 | 3-5天 |
| 最小 | ~200/403 | 仅限基本操作 | 3-5天 |
| 只读 | ~130/403 | 仅分析/报告 | 3-5天 |
自托管(默认)
所有功能都可以在完整范围内开箱即用:
npm run auth
npm run start:http
SaaS/市场部署
为了更快地进行谷歌验证(3-5天,而不是4-6周):
export DEPLOYMENT_MODE=saas
npm run auth
npm run start:http
标准模式下禁用的功能:
- 共享/协作(表格_协作)
- BigQuery集成(sheets_BigQuery)
- 应用程序脚本自动化(sheets_appscript)
- Webhook通知(sheets_Webhook)
启用所有功能: 集 OAUTH_SCOPE_MODE=full (接受更长的验证时间)
环境变量:
DEPLOYMENT_MODE:self-hosted(默认,全范围)或saas(标准范围)OAUTH_SCOPE_MODE:显式覆盖-full,standard,minimal,readonly
文档
ServalSheets具有按用例组织的全面文档:
🚀 入门指南
- 文档/指南/FIRST_TIME_USER.md -首次用户演练(从这里开始!)
- docs/guides/CLAUDE_DESKTOP_SETUP.md -Claude桌面设置
- docs/guides/INSTALLION_GUIDE.md -安装说明
- 文档/指南/快速启动_ CREDENTIALS.md -快速凭据设置
📖 用户指南
- 文档/指南/用法_GUIDE.md -完整的使用指南
- docs/guides/PROMPTS_GUIDE.md -有效的AI提示
- docs/guides/OAUTH_USER_SETUP.md -OAuth身份验证
- docs/guides/TROUBLESHOOTING.md -常见问题
- 文档/指南/SKILL.md -克劳德技能整合
🏭 生产与运营
- 文档/指南/DEPLOYMENT.md -生产部署
- docs/guides/MONITORING.md -监控和可观察性
- 文档/指南/PERFORMANCE.md -性能优化
- 安全.md -安全策略
📚 完整文档索引
- docs/README.md -包含所有指南、开发文档和发行说明的完整文档索引
🔐 生产
- 安全.md -安全最佳实践
- 文档/指南/PERFORMANCE.md -性能调优
- docs/guides/MONITORING.md -可观察性设置
- 文档/指南/DEPLOYMENT.md -部署示例
- docs/guides/TROUBLESHOOTING.md -常见问题
需要帮助? 从...开始 文档/指南/用法_GUIDE.md 以获得完整的演练。
贡献
我们欢迎捐款!ServalSheets遵循严格的质量标准,以保持生产级的可靠性。
快速链接
- 开发人员工作流程指南 -贡献者分步指南
- 克劳德代码规则 -所有捐款所需的规则
贡献者快速入门
# 1. Clone and install
git clone https://github.com/khill1269/servalsheets.git
cd servalsheets
npm install
# 2. Create feature branch
git checkout -b fix/your-bug-name
# 3. Make changes (≤3 src/ files recommended)
# Edit src/handlers/values.ts
# 4. Verify (must pass before PR)
npm run verify
# 5. Commit and push
git commit -m "fix(values): handle empty arrays gracefully"
git push origin fix/your-bug-name
核心原则
所有捐款必须遵循以下规定 克劳德代码规则:
- 索赔前核实 -为所有索赔提供文件路径+行范围
- 跟踪执行路径 -记录完整的调用堆栈
- 没有证据就没有“修复” -先写失败的测试,然后修复
- 最小变更政策 -≤3个文件
src/每次提交 - 没有沉默的退路 -记录错误,永不返回
{}默默地
验证命令
npm run verify # Full verification pipeline
npm run check:drift # Metadata synchronization
npm run check:placeholders # No TODO/FIXME in src/
npm run check:silent-fallbacks # No silent {} returns
npm run check:debug-prints # No console.log in src/
npm test # Run 8,500+ tests
创建PR之前
- []所有测试均通过(
npm test) - []验证通过(
npm run verify) - [ ] ≤3
src/修改的文件(或记录的异常) - []提交信息中提供的证据
- []以下内容 克劳德代码规则
看 开发人员工作流程指南 详细说明。
工具参考
工具总结(25个工具,407个操作)
| 工具 | 操作 | 描述 |
|---|---|---|
sheets_auth |
5 | 身份验证和OAuth 2.1 |
sheets_core |
21 | 电子表格和表格元数据/管理 |
sheets_data |
25 | 读/写值、笔记、超链接、剪贴板、交叉电子表格 |
sheets_format |
25 | 单元格格式、条件格式、数据验证、火花线 |
sheets_dimensions |
30 | 行/列、过滤器、排序、分组、冻结、视图、切片器 |
sheets_visualize |
18 | 图表和数据透视表 |
sheets_collaborate |
40 | 共享、评论、版本/快照、批准、标签 |
sheets_advanced |
31 | 命名范围、保护范围、元数据、条带、表、芯片 |
sheets_transaction |
6 | 原子批处理操作(节省API 80-95%) |
sheets_quality |
4 | 验证、冲突、影响分析 |
sheets_history |
10 | 撤消/重做、历史记录、还原、时间旅行调试器 |
sheets_confirm |
5 | 激励确认和向导 |
sheets_analyze |
22 | 人工智能辅助分析、建议和推荐 |
sheets_fix |
6 | 自动修复和数据清理管道 |
sheets_composite |
21 | 高级批量操作、NL板材生成和ETL管道 |
sheets_session |
31 | 会话上下文、首选项、检查点 |
sheets_appsscript |
19 | 应用程序脚本自动化 |
sheets_bigquery |
17 | BigQuery连接表 |
sheets_templates |
8 | 企业模板 |
sheets_webhook |
10 | Webhook注册和交付 |
sheets_federation |
4 | 远程MCP服务器联盟和跨服务器调用 |
sheets_dependencies |
10 | 公式依赖性分析和场景建模 |
sheets_agent |
8 | 具有计划/执行/回滚功能的自主多步执行 |
sheets_compute |
16 | 服务器端计算(统计、回归、预测、矩阵运算) |
sheets_connectors |
10 | 外部数据连接器(Finnhub、FRED、REST API) |
例子
示例1:读取和分析数据
// Read sales data
const result = await sheets_data({
action: 'read',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: { a1: 'Sales!A1:D100' },
valueRenderOption: 'FORMATTED_VALUE',
});
// Analyze data quality
const analysis = await sheets_analyze({
action: 'analyze_quality',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: { a1: 'Sales!A1:D100' },
});
// Returns: { completeness: 0.95, duplicates: 3, outliers: [...] }
示例2:安全批量更新与试运行
// Preview changes first (dry run)
const preview = await sheets_data({
action: 'write',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: { a1: 'Data!A2:C100' },
values: newData,
safety: {
dryRun: true,
effectScope: { maxCellsAffected: 500 },
},
});
// Returns: { dryRun: true, cellsAffected: 297 }
// Execute if safe
if (preview.data.cellsAffected < 500) {
const result = await sheets_data({
action: 'write',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: { a1: 'Data!A2:C100' },
values: newData,
safety: {
expectedState: { rowCount: 100 },
autoSnapshot: true,
},
});
}
示例3:语义范围查询
// Query by column header instead of A1 notation
const revenue = await sheets_data({
action: 'read',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: {
semantic: {
sheet: 'Q4 Sales',
column: 'Total Revenue', // Matches header in row 1
includeHeader: false,
},
},
});
// Returns cell values
// {
// success: true,
// action: 'read',
// values: [[5000], [7500], [3200], ...]
// }
示例4:创建图表
// Create a bar chart from data
const chart = await sheets_visualize({
action: 'create',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
sheetId: 0,
chartType: 'BAR',
title: 'Monthly Sales',
data: { sourceRange: { a1: 'Sales!A1:B12' } },
position: {
anchorCell: 'Sheet1!F1',
width: 600,
height: 400,
},
});
示例5:条件格式
// Add conditional formatting rule
const rule = await sheets_format({
action: 'add_conditional_format',
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
sheetId: 0,
range: { a1: 'Data!B2:B100' },
rule: {
type: 'NUMBER_GREATER',
values: [{ userEnteredValue: '1000' }],
},
format: {
backgroundColor: { red: 0.7, green: 1, blue: 0.7 }, // Light green
},
});
市场示例
为Claude Desktop或任何MCP客户端完成、复制可粘贴的提示。
示例1:带有XLOOKUP公式的销售仪表板
“在电子表格1BxiMVs0…中使用XLOOKUP公式创建销售仪表板,该公式从产品表中查找产品名称并返回其类别和价格。”
// Step 1: Generate the XLOOKUP formula
{ "action": "generate_formula", "spreadsheetId": "1BxiMVs0...", "formulaType": "xlookup",
"description": "Look up product name in Products!A:A and return the category from Products!C:C",
"targetCell": "D2" }
// Step 2: Write the formula to the dashboard
{ "action": "write", "spreadsheetId": "1BxiMVs0...", "range": "Dashboard!D2",
"values": [["=XLOOKUP(A2,Products!A:A,Products!C:C,\"Unknown\")"]] }
// Step 3: Format the dashboard
{ "action": "batch_format", "spreadsheetId": "1BxiMVs0...",
"operations": [{ "range": "Dashboard!A1:E1", "preset": "header_row" }] }
示例2:使用图表进行季度数据分析
“在‘第四季度数据’表中分析我的第四季度收入数据,并创建一个比较月度收入的柱状图。”
// Step 1: Scout the spreadsheet structure
{ "action": "scout", "spreadsheetId": "1BxiMVs0..." }
// Step 2: Comprehensive analysis
{ "action": "comprehensive", "spreadsheetId": "1BxiMVs0...", "range": "'Q4 Data'!A1:D100" }
// Step 3: Create the chart
{ "action": "suggest_chart", "spreadsheetId": "1BxiMVs0...", "range": "'Q4 Data'!A1:D13" }
示例3:导入CSV、重复数据消除和格式为表
导入此CSV客户数据,删除电子邮件列上的重复项,并将其格式化为样式表
// Step 1: Import the CSV
{ "action": "import_csv", "spreadsheetId": "1BxiMVs0...", "sheetName": "Customers",
"csvData": "Name,Email,Revenue\nAlice,alice@co.com,5000\n..." }
// Step 2: Deduplicate on Email column
{ "action": "deduplicate", "spreadsheetId": "1BxiMVs0...", "range": "Customers!A1:C100",
"keyColumns": ["Email"], "keep": "first" }
// Step 3: Create a table
{ "action": "create_table", "spreadsheetId": "1BxiMVs0...", "range": "Customers!A1:C50",
"tableName": "CustomerTable", "hasHeaders": true }
示例4:自动共享和版本快照
“与财务团队共享我的预算电子表格,在进行更改之前创建版本快照,并跟踪编辑。”
// Step 1: Create a version snapshot before editing
{ "action": "version_create_snapshot", "spreadsheetId": "1BxiMVs0...",
"name": "Pre-Q4-Budget-Edit", "description": "Snapshot before Q4 budget update" }
// Step 2: Poll until the snapshot task completes
{ "action": "version_snapshot_status", "spreadsheetId": "1BxiMVs0...",
"taskId": "task_123" }
// Step 3: Share with the team
{ "action": "share_add", "spreadsheetId": "1BxiMVs0...",
"emailAddress": "finance-team@company.com", "role": "writer",
"sendNotification": true, "emailMessage": "Q4 budget ready for review" }
// Step 4: Make changes, then create another snapshot
{ "action": "version_create_snapshot", "spreadsheetId": "1BxiMVs0...",
"name": "Post-Q4-Budget-Edit" }
示例5:创建可重用的命名范围和保护
“在我分享这个模型之前,请说出我的主要财务范围并保护假设部分。”
// Step 1: Name a key assumptions range
{ "action": "add_named_range", "spreadsheetId": "1BxiMVs0...",
"name": "ASSUMPTIONS",
"range": "Model!B2:D10" }
// Step 2: Protect it before collaboration
{ "action": "add_protected_range", "spreadsheetId": "1BxiMVs0...",
"range": "Model!B2:D10",
"description": "Locked financial assumptions",
"warningOnly": false }
// Step 3: Add metadata for downstream automation
{ "action": "add_developer_metadata", "spreadsheetId": "1BxiMVs0...",
"metadataKey": "section",
"metadataValue": "financial_assumptions",
"visibility": "DOCUMENT" }
安全围栏
干运行模式
预览更改而不执行:
{
safety: {
dryRun: true;
}
}
影响范围限制
防止意外的大规模更改:
{
safety: {
effectScope: {
maxCellsAffected: 5000,
requireExplicitRange: true
}
}
}
预期状态(乐观锁定)
确保数据自上次读取以来没有更改:
{
safety: {
expectedState: {
rowCount: 100,
sheetTitle: 'Sales Data',
checksum: 'abc123'
}
}
}
自动快照
在执行破坏性操作之前创建备份:
{
safety: {
autoSnapshot: true;
}
}
范围输入格式
ServalSheets接受多种范围格式:
// A1 notation
{ a1: "Sheet1!A1:C10" }
// Named range
{ namedRange: "SalesData" }
// Grid coordinates (0-based, end exclusive)
{ grid: { sheetId: 0, startRowIndex: 0, endRowIndex: 10, startColumnIndex: 0, endColumnIndex: 3 } }
// Semantic (header-based)
{ semantic: { sheet: "Sales", column: "Revenue", includeHeader: false } }
错误代码
| 代码 | 描述 | 可重试 |
|---|---|---|
PARSE_ERROR |
JSON无效 | 否 |
INVALID_PARAMS |
无效参数 | 否 |
SHEET_NOT_FOUND |
工作表不存在 | 否 |
RANGE_NOT_FOUND |
未找到范围 | 否 |
PERMISSION_DENIED |
无法访问 | 否 |
QUOTA_EXCEEDED |
超过API配额 | 是 |
RATE_LIMITED |
请求太多 | 是 |
PRECONDITION_FAILED |
预期状态不匹配 | 否 |
EFFECT_SCOPE_EXCEEDED |
操作太大 | 否 |
AMBIGUOUS_RANGE |
多个标头匹配 | 否 |
认证
服务帐户(建议用于自动化)
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
npx servalsheets
OAuth2访问令牌
export GOOGLE_ACCESS_TOKEN=ya29.xxx
npx servalsheets
OAuth2客户端凭据
export GOOGLE_CLIENT_ID=xxx
export GOOGLE_CLIENT_SECRET=xxx
npx servalsheets
加密令牌存储(可选)
使用加密文件存储在重启过程中持久化OAuth令牌。
export GOOGLE_TOKEN_STORE_PATH=~/.config/servalsheets/tokens.enc
export ENCRYPTION_KEY=<64-char-hex-key>
npx servalsheets
密钥必须是64个字符的十六进制字符串(32个字节)。例子:
openssl rand -hex 32
企业SSO(SAML 2.0)
对于使用身份提供者(Okta、Azure AD、Google Workspace SAML等)的组织,ServalSheets提供了一个内置的SAML 2.0服务提供者。配置后,用户通过您的IdP进行身份验证,并为后续API请求接收一个短暂的JWT。
# Required
SAML_ENTRY_POINT=https://your-idp.example.com/sso/saml
SAML_ISSUER=https://your-servalsheets.example.com
SAML_CERT=-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----
SAML_CALLBACK_URL=https://your-servalsheets.example.com/sso/callback
# Optional
SAML_PRIVATE_KEY=<your-pem-private-key> # for signed requests
SAML_WANT_ASSERTIONS_SIGNED=true # default: true
SAML_SIGNATURE_ALGORITHM=sha256 # default: sha256
SSO_JWT_TTL=3600 # token TTL in seconds (default: 1h)
SSO_ALLOWED_CLOCK_SKEW=300 # clock skew tolerance in seconds
SSO路由在以下情况下自动注册 SAML_ENTRY_POINT 已设置:
| 路线 | 描述 |
|---|---|
GET /sso/login |
重定向到IdP登录页面 |
POST /sso/callback |
接收SAML断言,发出JWT |
GET /sso/metadata |
为IdP注册提供SP元数据XML |
GET /sso/logout |
启动SLO(单次注销) |
发布的JWT携带 scope='sso' 并且被与OAuth令牌相同的Bearer令牌中间件接受。无需更改客户端,只需交换令牌即可。
传输安全模型(RBAC)
ServalSheets实施基于角色的访问控制(RBAC) 仅在HTTP传输上.STDIO传输(由Claude Desktop和本地CLI使用)通过设计信任本地进程——它在具有操作系统级权限的用户帐户下运行,因此额外的RBAC层将是多余的。
| 传输 | RBAC是否强制执行? | 备注 |
|---|---|---|
| STDIO | 否 | 受信任的本地进程(Claude Desktop模型) |
| HTTP/SSE | 是 | 基于JWT的RBAC,可通过以下方式配置角色 SERVAL_RBAC_* 环境变量 |
| 远程MCP | 是 | 每个用户的JWT声明在每个请求上都经过验证 |
如果您将ServalSheets作为暴露给多个用户的HTTP服务器运行,请确保 JWT_SECRET 和 OAUTH_CLIENT_SECRET 已设置,所有流量都通过HTTPS。
配置
ServalSheets支持通过环境变量对生产部署进行广泛配置。
生产所需(HTTP/远程服务器)
当以HTTP或支持OAuth的远程服务器运行ServalSheets时,这些环境变量是 必需的 在生产模式下:
# Required Production Secrets (generate with: openssl rand -hex 32)
export JWT_SECRET=<64-char-hex-string>
export STATE_SECRET=<64-char-hex-string>
export OAUTH_CLIENT_SECRET=<64-char-hex-string>
# OAuth Security (comma-separated list of allowed callback URIs)
export ALLOWED_REDIRECT_URIS=https://your-app.com/callback,https://another-app.com/callback
# Environment mode
export NODE_ENV=production
安全说明:
- 每个秘密都应该是一个唯一的64个字符的十六进制字符串
- 永远不要将秘密提交给版本控制
- 每90天轮换一次秘密
- 在生产中使用机密管理器(AWS机密管理器、Vault等)
看 安全.md 了解详细的安全最佳实践。
可选:用于会话存储的Redis
对于具有多个实例或高可用性要求的生产部署:
# Install Redis dependency
npm install redis
# Configure Redis URL
export REDIS_URL=redis://localhost:6379
# Optional: Maximum sessions per user (default: 5)
export MAX_SESSIONS_PER_USER=5
# Optional: Streamable HTTP event store (resumability)
export STREAMABLE_HTTP_EVENT_TTL_MS=300000
export STREAMABLE_HTTP_EVENT_MAX_EVENTS=5000
Redis提供:
- 跨多个服务器实例共享会话存储
- 跨服务器重启的持续会话
- 跨实例的可流化HTTP可恢复性
- 规模效益更好
速率限制
使用令牌存储桶速率限制来控制API配额使用情况:
# Configure rate limits (default: 300 reads/min, 60 writes/min)
export RATE_LIMIT_READS_PER_MINUTE=300
export RATE_LIMIT_WRITES_PER_MINUTE=60
Google Sheets API Quotas by Workspace版本:
| 工作区版 | 读取配额 | 写入配额 | 配置 |
|---|---|---|---|
| 免费/个人 | 300/min | 60/min | (默认值) |
| 商业标准 | 600/min | 120/min | RATE_LIMIT_READS_PER_MINUTE=600 RATE_LIMIT_WRITES_PER_MINUTE=120 |
| 商业增强版 | 900/分钟 | 180/分钟 | RATE_LIMIT_READS_PER_MINUTE=900 RATE_LIMIT_WRITES_PER_MINUTE=180 |
| 企业 | 1200/分钟 | 240/分钟 | RATE_LIMIT_READS_PER_MINUTE=1200 RATE_LIMIT_WRITES_PER_MINUTE=240 |
备注:实际配额取决于您的Google Cloud项目配置。检查你的 谷歌云控制台 为了精确的限制。
动态油门:当检测到429(速率限制)错误时,速率限制器会自动将速率降低50%,持续60秒,然后恢复正常限制。
根据您的Google Cloud项目配额调整这些。看 PERFORMANCE.md 用于调整策略。
缓存
配置缓存TTL和大小:
# Enable/disable caching (default: enabled)
export CACHE_ENABLED=true
# Cache configuration
export CACHE_MAX_SIZE_MB=100
export CACHE_TTL_MS=300000 # 5 minutes
缓存将重复读取的API调用减少了100倍。增加读取繁重工作负载的TTL。
可观测性
配置跟踪和监控:
# Enable OpenTelemetry tracing
export OTEL_ENABLED=true
export OTEL_LOG_SPANS=true # Log spans to console
# Request deduplication
export DEDUPLICATION_ENABLED=true
export DEDUP_WINDOW_MS=5000 # 5 seconds
自动监控:
- 有效载荷大小:跟踪所有Google API请求/响应
- 批量效率:分析每个电子表格的意图比率
- 速率限制:对429个错误进行动态限制
- HTTP压缩:响应大小减少60-80%
通过生命周期方法提供的统计数据:
getCacheStats()-缓存命中率、大小getDeduplicationStats()-重复数据删除率getBatchEfficiencyStats()-批量优化指标getTracingStats()-OpenTetry跨度计数
影响范围限制
防止意外的大规模操作:
效果范围安全轨道使用当前服务器中的内置默认值:
- 每次操作的估计单元格默认限制:50000
- 破坏性行删除默认限制:10000
- 破坏性列删除默认限制:100
您可以根据请求收紧限额 effectScope尤其是 maxCellsAffected 和 requireExplicitRange.
这些限制起到了安全护栏的作用。超出限制的操作将失败 EFFECT_SCOPE_EXCEEDED 错误。
日志记录
配置结构化日志记录:
# Log level: debug, info, warn, error (default: info)
export LOG_LEVEL=info
# Log format: json, text (default: json for production)
export LOG_FORMAT=json
# Log file path (optional, defaults to stdout)
export LOG_FILE=/var/log/servalsheets/app.log
建议使用JSON格式进行生产(机器可解析)。看 MONITORING.md 用于日志聚合。
超时
配置API和请求超时:
# Google API timeout (default: 30s)
export GOOGLE_API_TIMEOUT_MS=30000
# Request timeout (default: 120s)
export REQUEST_TIMEOUT_MS=120000
HTTP/2和连接池
配置HTTP/2和连接池以获得最佳性能:
# Enable/disable HTTP/2 (default: true)
export GOOGLE_API_HTTP2_ENABLED=true
# Maximum concurrent connections (default: 50)
export GOOGLE_API_MAX_SOCKETS=50
# Keep-alive timeout in milliseconds (default: 30000)
export GOOGLE_API_KEEPALIVE_TIMEOUT=30000
# Enable connection pool monitoring (default: false)
export ENABLE_HTTP2_POOL_MONITORING=true
# Monitoring interval in milliseconds (default: 300000 = 5 minutes)
export HTTP2_POOL_MONITOR_INTERVAL_MS=300000
HTTP/2的优点:
- API调用延迟降低5-15%
- 连接多路复用(每个连接有多个请求)
- 标头压缩减少了开销
连接池监控: 启用后,会定期记录连接池统计信息:
- 活动插座(使用中的连接)
- 免费插座(游泳池内有)
- 待定请求(等待连接)
- 池利用率百分比
- 利用率达到80%和100%时自动发出警告
建议在生产环境中检测连接池耗尽,以免影响性能。
度量服务器
通过HTTP端点公开性能指标以进行监控:
# Enable metrics server (default: false)
export ENABLE_METRICS_SERVER=true
# Metrics server port (default: 9090)
export METRICS_PORT=9090
# Metrics server host (default: 127.0.0.1)
export METRICS_HOST=127.0.0.1
可用端点:
| 端点 | 格式 | 描述 |
|---|---|---|
/metrics |
普罗米修斯文本 | 推荐给普罗米修斯/Grafana |
/metrics.json |
JSON | 程序化访问 |
/metrics.txt |
人类可读文本 | 快速检查 |
/health |
JSON | 健康检查端点 |
暴露的指标:
- 缓存指标:命中率、命中/未命中、驱逐、缓存类型大小
- 批处理指标:当前窗口大小、总批数、平均批数、重复数据删除计数
- API指标:按方法列出的总调用数、按代码列出的错误数、成功/错误率
Prometheus配置示例:
scrape_configs:
- job_name: 'servalsheets'
static_configs:
- targets: ['localhost:9090']
scrape_interval: 15s
访问指标:
# Prometheus format
curl http://localhost:9090/metrics
# JSON format
curl http://localhost:9090/metrics.json
# Human-readable
curl http://localhost:9090/metrics.txt
内存泄漏检测
监控Node.js堆使用情况,在内存泄漏导致崩溃之前检测内存泄漏:
# Enable heap monitoring (default: false)
export ENABLE_HEAP_MONITORING=true
# Monitoring interval in milliseconds (default: 1800000 = 30 minutes)
export HEAP_MONITOR_INTERVAL_MS=1800000
# Warning threshold (0-1, default: 0.7 = 70%)
export HEAP_WARNING_THRESHOLD=0.7
# Critical threshold (0-1, default: 0.85 = 85%)
export HEAP_CRITICAL_THRESHOLD=0.85
# Enable heap snapshots at critical threshold (default: false)
export ENABLE_HEAP_SNAPSHOTS=true
# Heap snapshot directory (default: ./heap-snapshots)
export HEAP_SNAPSHOT_PATH=./heap-snapshots
警报阈值:
- 警告(70%): 记录堆使用率的上升,监控持续增长
- 严重(85%): 记录建议错误,可选择捕获堆快照
- 自动节流: 警报限制为每5-15分钟一次,以防止垃圾邮件
堆快照: 启用后,堆快照将在临界阈值处捕获以进行事后分析:
- Chrome工具: 在内存分析器中打开快照
- clinic.js:
npm run profile:memory用途npm exec按需获取Clinic.js
按使用情况建议:
- 95%+: 需要立即重启以防止OOM崩溃
- 85-95%: 计划重启,使用堆快照进行调查
- 70-85%: 监控趋势,查看缓存策略和连接池
- <70%: 正常运行
示例:生产配置
Claude Desktop的完整生产设置:
{
"mcpServers": {
"servalsheets": {
"command": "npx",
"args": ["servalsheets"],
"env": {
"NODE_ENV": "production",
"LOG_LEVEL": "info",
"LOG_FORMAT": "json",
"GOOGLE_APPLICATION_CREDENTIALS": "/path/to/service-account.json",
"GOOGLE_TOKEN_STORE_PATH": "/path/to/tokens.enc",
"ENCRYPTION_KEY": "<64-char-hex-key>"
}
}
}
}
有关详细的配置指南,请参阅:
- 安全:
SECURITY.md-身份验证、加密、秘密管理 - 演出:
PERFORMANCE.md-速率限制策略、不同层次、批处理 - 监控:
MONITORING.md-日志记录、指标、警报、健康检查 - 部署:
DEPLOYMENT.md-Docker、Kubernetes、systemd、云平台 - 故障排除:
TROUBLESHOOTING.md-常见问题和解决方案
发展
# Clone repository
git clone https://github.com/khill1269/servalsheets.git
cd servalsheets
# Install dependencies
npm install
# Build
npm run build
# Type check (strict mode)
npm run typecheck
# Run tests (8,500+ tests)
npm test
# Run in development mode
npm run dev
# Start HTTP server
npm run start:http
# Start remote server with OAuth
npm run start:remote
建筑
src/
├── schemas/ # Zod schemas for all 25 tools
├── core/ # Core infrastructure
│ ├── intent.ts # Intent types and mappings
│ ├── batch-compiler.ts # Compiles intents to API requests
│ ├── rate-limiter.ts # Token bucket rate limiting
│ ├── diff-engine.ts # Tiered diff generation
│ ├── policy-enforcer.ts # Safety policy validation
│ └── range-resolver.ts # Semantic range resolution
├── services/ # External service integrations
│ ├── google-api.ts # Google API client
│ └── snapshot.ts # Backup/restore service
├── handlers/ # Tool handlers
├── server.ts # MCP server (STDIO)
├── http-server.ts # HTTP/SSE transport
├── oauth-provider.ts # OAuth 2.1 for Claude Connectors
├── cli.ts # CLI entry point
└── index.ts # Main exports
数据流
graph LR
A[User] -->|Natural language| B[Claude Desktop]
B -->|MCP Protocol| C[ServalSheets MCP Server]
C -->|Google API v4| D[Google Sheets]
D -->|Data| C
C -->|Structured response| B
B -->|AI response| A
style A fill:#e1f5ff
style B fill:#fff3cd
style C fill:#d4edda
style D fill:#f8d7da
组件体系结构
graph TB
subgraph "ServalSheets MCP Server"
CLI[CLI Entry Point]
MCP[MCP Server]
subgraph "Handlers (25 Tools)"
H1[sheets_core]
H2[sheets_data]
H3[sheets_format]
H4[... 22 more]
end
subgraph "Core Infrastructure"
Intent[Intent System]
Compiler[Batch Compiler]
RateLimit[Rate Limiter]
Diff[Diff Engine]
Policy[Policy Enforcer]
Range[Range Resolver]
end
subgraph "Services"
GoogleAPI[Google API Client]
Snapshot[Snapshot Service]
end
CLI --> MCP
MCP --> H1 & H2 & H3 & H4
H1 & H2 & H3 & H4 --> Intent
Intent --> Compiler
Compiler --> Policy
Policy --> RateLimit
RateLimit --> GoogleAPI
GoogleAPI --> Diff
Diff --> Range
Range --> Snapshot
end
GoogleAPI -->|API Calls| Google[Google Sheets API]
style CLI fill:#e1f5ff
style MCP fill:#fff3cd
style GoogleAPI fill:#d4edda
style Google fill:#f8d7da
协议遵从
- MCP协议:2025-11-25(受歧视工会、进度通知)
- 谷歌网页API:v4(全覆盖)
- OAuth:2.1支持PKCE
- 运输:STDIO、SSE、流式HTTP
- TypeScript:严格模式已启用,0个错误
- SDK版本:@modelcontextprotocol/sdk@1.27.1
- 测试套件:8500+通过单元、集成、合同和协议套件的测试
质量指标
- ✅ 类型安全:完全符合TypeScript严格模式
- ✅ 测试套件:8500+通过CI覆盖率报告测试
- ✅ 协议遵从:MCP 2025-11-25认证
- ✅ 生产就绪:用于Claude连接器目录
- ✅ 错误处理:带有重试提示的全面错误代码
模式架构:判别联合
ServalSheets使用 Zod歧视工会 用于25个工具和407个动作的类型安全动作调度。该架构提供:
图案概述
每个工具都定义了一个有区别的联合模式,其中 action 字段充当鉴别器:
// Example: sheets_auth tool (4 actions)
const SheetsAuthInputSchema = z.object({
request: z.discriminatedUnion('action', [
z.object({ action: z.literal('status'), verbosity: VerbositySchema }),
z.object({ action: z.literal('login'), scopes: ScopesSchema, verbosity: VerbositySchema }),
z.object({ action: z.literal('callback'), code: z.string(), verbosity: VerbositySchema }),
z.object({ action: z.literal('logout'), verbosity: VerbositySchema }),
]),
});
好处
- 类型安全:TypeScript编译器确保所有操作变量都得到处理
- 零运行时间开销:歧视性联合编译为高效的JavaScript
- 详尽性检查:处理程序必须实现所有操作类型
- Zod v4原生JSON模式:直接生成OpenAPI/MCP模式
- 演出:字符串解析速度提高14倍,数组速度提高7倍(Zod 4.3.5)
刀具结构
所有25个工具都遵循此模式:
Tool: sheets_[category]
├─ Input: Discriminated union of action variants
├─ Output: Success/Error discriminated union
├─ Type Narrowing: Auto-generated type guards per action
└─ Handlers: Single method per action variant
示例动作变体 (表_数据):
| 动作 | 输入形状 | 输出 | 用例 |
|---|---|---|---|
read |
{ action: 'read', spreadsheetId, range, valueRenderOption } |
值数组 | 获取单元格数据 |
write |
{ action: 'write', spreadsheetId, range, values, safety } |
编写摘要 | 更新单元格 |
batch_read |
{ action: 'batch_read', spreadsheetId, ranges } |
多范围值 | 获取多个范围 |
batch_write |
{ action: 'batch_write', spreadsheetId, data } |
批量汇总 | 多范围更新 |
append |
{ action: 'append', spreadsheetId, range, values } |
附加摘要 | 添加行 |
clear |
{ action: 'clear', spreadsheetId, range } |
清除摘要 | 删除值(保持格式) |
响应格式
所有工具响应都使用 歧视工会 success 领域:
// Success response
{
success: true,
action: 'read',
values: [[...cell values...]],
_meta: { requestId, duration, cacheHit, ... }
}
// Error response
{
success: false,
error: {
code: 'QUOTA_EXCEEDED',
message: '...',
retryable: true,
retryAfterMs: 60000,
resolution: '...',
resolutionSteps: ['...']
}
}
25工具概述
| 工具 | 动作 | 模式 | 用例 |
|---|---|---|---|
sheets_auth |
4 | 状态、登录、回调、注销 | OAuth和凭据 |
sheets_core |
19 | 获取、创建、删除、列出、更新 | 工作表元数据 |
sheets_data |
19 | 读取、写入、追加、清除、批处理操作 | 单元格值和注释 |
sheets_format |
23 | 颜色、边框、验证、条件 | 样式和规则 |
sheets_dimensions |
28 | 插入、删除、调整大小、筛选、排序、冻结 | 行和列 |
sheets_visualize |
18 | 创建、更新图表、数据透视表 | 图表和数据透视 |
sheets_collaborate |
35 | 分享、评论、版本、快照 | 多用户功能 |
sheets_advanced |
31 | 命名范围、受保护范围、元数据、带 | 高级功能 |
sheets_transaction |
6 | 开始、排队、提交、回滚 | 原子操作 |
sheets_quality |
4 | 验证、检测冲突、影响分析 | 数据质量 |
sheets_history |
7 | 撤消、重做、还原、列出历史记录 | 版本控制 |
sheets_confirm |
5 | 请求、向导、邀请 | 用户确认 |
sheets_analyze |
18 | 综合、侦察、计划、建议 | 人工智能分析 |
sheets_fix |
6 | 修复、清理、标准化、填充、异常、建议 | 数据清理流程 |
sheets_composite |
14 | 导入CSV、重复数据删除、生成工作表 | 批量操作和生成 |
sheets_session |
26 | 设置活动、获取上下文、保存检查点 | 会话上下文 |
sheets_appsscript |
18 | 运行、部署、获取内容 | 应用程序脚本自动化 |
sheets_bigquery |
17 | 查询、导入、连接查找器 | BigQuery集成 |
sheets_templates |
8 | 列出、创建、应用、导入内置 | 模板 |
sheets_webhook |
7 | 注册、注销、列表、测试 | 更改通知 |
sheets_dependencies |
7 | 构建、分析、检测周期、导出 | 公式分析 |
错误处理:恢复策略
ServalSheets实现了一个全面的错误分类系统,为每种错误类型提供了恢复策略。所有错误都继承自 ServalSheetsError 并提供可操作的解决步骤。
错误类别和恢复
1.验证错误(不可重试)
当:输入无效、数据格式错误、类型不匹配
恢复策略:
// Error details always include field name and expected format
{
code: 'VALIDATION_ERROR',
message: 'Invalid spreadsheetId format',
field: 'spreadsheetId',
expectedFormat: 'String matching /^[a-zA-Z0-9-_]{44}$/',
retryable: false,
resolution: "Fix the value of 'spreadsheetId' and retry the operation.",
resolutionSteps: [
"1. Check the value of 'spreadsheetId'",
"2. Ensure it matches the required format",
"3. Expected format: String matching /^[a-zA-Z0-9-_]{44}$/"
]
}
行动:修复输入并立即重试(无需回退)
2.身份验证错误(可重试)
当:令牌过期、凭据无效、身份验证流失败
恢复策略:
// Retryable auth errors include refresh instructions
{
code: 'TOKEN_EXPIRED',
message: 'Access token expired',
retryable: true,
resolution: 'Re-authenticate and retry the operation.',
resolutionSteps: [
'1. Refresh your access token',
'2. Re-authenticate if refresh fails',
'3. Retry the operation'
]
}
行动:
- 尝试刷新令牌
- 如果刷新失败,请重新启动OAuth流
- 使用新令牌重试操作
- 使用指数退避(1s、2s、4s、8s)
3.QuotaExceededError(可通过智能回退重试)
当:API配额已用尽,速率有限(429个错误)
恢复策略:
{
code: 'QUOTA_EXCEEDED',
message: 'Read quota exceeded (300 reads/min)',
retryable: true,
retryAfterMs: 60000, // Wait 60 seconds before retry
retryStrategy: 'exponential_backoff',
quotaType: 'read', // read | write | requests | unknown
resetTime: '2026-02-05T18:05:00Z',
resolution: 'Wait 60 seconds, then retry with optimized batch operations',
resolutionSteps: [
'1. Wait 60 seconds before retrying (quota resets at 2026-02-05T18:05:00Z)',
'2. Optimize future requests:',
' - Use batch operations: sheets_data action="batch_read" (saves ~80% quota)',
' - Use transactions: sheets_transaction (batches 10+ ops into 1 API call)',
' - Enable caching for repeated reads',
'3. Increase quotas in Google Cloud Console'
]
}
行动:
- 等待
retryAfterMs(通常为60秒) - 使用批处理操作减少未来的配额使用
- 启用缓存(请参阅性能调优部分)
- 实施请求重复数据删除
- 从Google Cloud控制台请求更高的配额
优化 (节省80-90%的配额):
// Before: 3 separate API calls = 3 quota units
await sheets_data({ action: 'read', range: 'A1:A100' });
await sheets_data({ action: 'read', range: 'B1:B100' });
await sheets_data({ action: 'read', range: 'C1:C100' });
// After: 1 batch API call = 1 quota unit (saves 66% quota)
await sheets_data({
action: 'batch_read',
ranges: ['A1:A100', 'B1:B100', 'C1:C100'],
});
4.SyncError(可通过冲突解决重试)
当:并发修改、合并冲突、过时数据
恢复策略 (4种冲突类型):
A) 并发修改:
{
code: 'TRANSACTION_CONFLICT',
conflictType: 'concurrent_modification',
message: 'Spreadsheet was edited by another user',
retryable: true,
resolutionSteps: [
'1. Fetch latest state: sheets_core action="get"',
'2. Apply your changes to the latest version',
'3. Use transactions for atomic updates: sheets_transaction',
'4. Lock ranges during edit: sheets_advanced action="add_protected_range"'
]
}
B) 陈旧数据 (缓存版本已过时):
{
conflictType: 'stale_data',
lastKnownVersion: 42,
currentVersion: 45,
resolutionSteps: [
'1. Fetch fresh data: sheets_core action="get"',
'2. Invalidate local cache',
'3. Use webhooks instead of polling: sheets_webhook',
'4. Set shorter cache TTL'
]
}
C) 版本不匹配:
{
conflictType: 'version_mismatch',
resolutionSteps: [
'1. Get current version: sheets_core action="get"',
'2. Check version history: sheets_collaborate action="version_list"',
'3. Use sheets_transaction for multi-step updates'
]
}
D) 合并冲突 (需要手动分辨率):
{
conflictType: 'merge_conflict',
resolutionSteps: [
'1. View current state: sheets_core action="get"',
'2. Implement resolution strategy:',
' - Last-write-wins: Use latest timestamp',
' - First-write-wins: Keep original version',
' - Three-way merge: Compare base, yours, theirs',
' - Custom: Use app-specific merge logic'
]
}
5.ApiTimeout错误(可通过优化重试)
当:请求超时(默认30秒),网络速度慢
恢复策略:
{
code: 'DEADLINE_EXCEEDED',
retryable: true,
timeoutMs: 30000,
operation: 'batch_read_large_range',
resolutionSteps: [
'1. Reduce request size by limiting rows/columns',
'2. Split into smaller batches',
'3. Use batch operations instead of individual requests',
'4. Disable formula recalculation if possible',
'5. Increase timeout setting',
'6. Verify network connection is stable'
],
retryAfterMs: 60000,
retryStrategy: 'exponential_backoff'
}
行动:
- 减少请求范围(减少行/列)
- 实现分页
- 使用批处理操作
- 缓存中间结果
- 指数退避重试
6.RangeResolution错误(不可重试)
当:范围格式无效,找不到工作表,列名不明确
恢复策略 (特定上下文):
范围格式无效:
{
code: 'INVALID_RANGE',
rangeInput: 'Sheet1!A1:B', // Invalid (missing end row)
resolutionSteps: [
'1. Check A1 notation format: Use "Sheet1!A1:D10" or "A1:D10"',
'2. Valid examples: "Sheet1!A1", "Sheet1!A:A" (column), "Sheet1!1:1" (row)',
'3. Escape sheet names with spaces: "\'My Sheet\'!A1:B10"',
'4. Verify cell coordinates are valid (column A-ZZZ, rows 1-10000000)',
'5. Try semantic range syntax: {"semantic":{"sheet":"Sales","column":"Revenue"}}'
]
}
未找到工作表:
{
code: 'SHEET_NOT_FOUND',
sheetName: 'NonexistentSheet',
resolutionSteps: [
'1. List all sheets: sheets_core action="list_sheets"',
'2. Sheet requested: "NonexistentSheet" (case-sensitive)',
'3. Verify sheet name spelling exactly as shown in Google Sheets',
'4. Try using sheet ID (numeric gid) instead of name'
]
}
列名不明确:
{
code: 'AMBIGUOUS_RANGE',
resolutionSteps: [
'1. Multiple columns match your query',
'2. Specify exact column name or use A1 notation instead',
'3. Use sheets_core to see all available columns'
]
}
7.BatchCompilationError(不可重试)
当:多个操作验证失败、循环引用、架构不匹配
恢复策略:
{
code: 'BATCH_UPDATE_ERROR',
failedOperations: [
{ index: 2, error: 'Invalid range format' },
{ index: 5, error: 'Circular reference detected' },
{ index: 8, error: 'Protected range violation' }
],
failureRate: '15.0%',
resolutionSteps: [
'1. 3 failed operations out of 20 (15.0%)',
'2. Common issues:',
' - Invalid range format in operation (use "Sheet1!A1:B10")',
' - Sheet name mismatch (case-sensitive)',
' - Circular reference in formulas',
' - Protected ranges or sheets',
'3. Fix each failed operation:',
' - Operation 2: Invalid range format',
' - Operation 5: Circular reference detected',
'4. Split into smaller batches if needed (max 50 ops recommended)',
'5. Use sheets_transaction with corrected operations'
]
}
行动:
- 检查每个失败的操作
- 修复验证错误
- 分成更小的批次(最多50次操作)
- 使用事务实现原子性
- 重试已更正的批次
重试逻辑最佳实践
// Exponential backoff with jitter
async function retryWithBackoff(operation: () => Promise<T>, maxRetries: number = 5): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
// Check if retryable
if (!error.retryable || attempt === maxRetries) {
throw error; // Non-retryable or final attempt
}
// Calculate backoff with jitter
const baseDelay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s, 8s, ...
const jitter = Math.random() * 0.1 * baseDelay; // 10% jitter
const delayMs = baseDelay + jitter;
// Check if error specifies retry delay
const specifiedDelay = error.retryAfterMs;
const actualDelayMs = specifiedDelay || delayMs;
console.log(
`Attempt ${attempt + 1}/${maxRetries + 1} failed. ` +
`Waiting ${(actualDelayMs / 1000).toFixed(1)}s before retry...`
);
await new Promise((resolve) => setTimeout(resolve, actualDelayMs));
}
}
}
错误监视
通过指标启用错误跟踪:
// Track errors by code and retryability
interface ErrorMetrics {
totalErrors: number;
errorsByCode: Record<string, number>;
retryableCount: number;
nonRetryableCount: number;
successRateAfterRetry: number;
}
性能调整
ServalSheets为不同的工作负载提供了多种性能优化策略。性能取决于:请求批处理、缓存、速率限制和有效负载大小。
1.缓存(80-100倍API调用减少)
配置:
# Enable/disable caching (default: enabled)
export CACHE_ENABLED=true
# Cache size limit (default: 100MB)
export CACHE_MAX_SIZE_MB=100
# Cache TTL (default: 5 minutes = 300000ms)
export CACHE_TTL_MS=300000
# Cache cleanup interval (default: 5 minutes)
export CACHE_CLEANUP_INTERVAL_MS=300000
按工作负载划分的缓存策略:
A) 阅读繁重的工作量 (重复访问相同的数据):
# Increase TTL to 30 minutes for stable data
export CACHE_TTL_MS=1800000
export CACHE_MAX_SIZE_MB=500 # Larger cache
# Example: Dashboard refreshing every 5 minutes
# First load: 10 API calls
# Refreshes 2-5: 0 API calls (cached)
# Result: 95% quota savings
B) 实时工作量 (数据经常变化):
# Disable caching for absolutely fresh data
export CACHE_ENABLED=false
# OR use webhook-based notifications instead of caching
# This is more efficient than polling with short TTLs
C) 混合方法 (推荐):
# Short TTL for frequently-changing data
export CACHE_TTL_MS=30000 # 30 seconds
# Use webhooks for critical updates
# Use caching for non-critical metadata
# Example: Real-time metrics with stable schema
# Metrics cache expires every 30s → fresh data
# Schema cache expires every 5 min → reduces overhead
缓存统计信息监控:
// Access cache statistics
const stats = cacheManager.getStats();
// {
// totalEntries: 1024,
// totalSize: 52000000, // 52MB
// hits: 4850,
// misses: 250,
// hitRate: 0.951, // 95.1% hit rate
// byNamespace: {
// 'metadata': 512,
// 'values': 512
// }
// }
2.批量操作(节省80-90%的配额)
模式:将多个操作合并为单个API调用
读取批处理 (配额效率):
// ❌ Inefficient: 3 API calls = 3 quota units
const range1 = await sheets_data({ action: 'read', range: 'Sales!A1:A100' });
const range2 = await sheets_data({ action: 'read', range: 'Sales!B1:B100' });
const range3 = await sheets_data({ action: 'read', range: 'Sales!C1:C100' });
// ✅ Efficient: 1 API call = 1 quota unit (66% quota savings)
const [range1, range2, range3] = await sheets_data({
action: 'batch_read',
ranges: ['Sales!A1:A100', 'Sales!B1:B100', 'Sales!C1:C100'],
});
写入批处理:
// ❌ Inefficient: 3 API calls = 3 quota units
await sheets_data({ action: 'write', range: 'Sheet1!A1:A100', values: dataA });
await sheets_data({ action: 'write', range: 'Sheet1!B1:B100', values: dataB });
await sheets_data({ action: 'write', range: 'Sheet1!C1:C100', values: dataC });
// ✅ Efficient: 1 API call = 1 quota unit
await sheets_data({
action: 'batch_write',
data: [
{ range: 'Sheet1!A1:A100', values: dataA },
{ range: 'Sheet1!B1:B100', values: dataB },
{ range: 'Sheet1!C1:C100', values: dataC },
],
});
事务批处理 (每个API调用10-50个操作):
// Use transactions for complex multi-step operations
// Each transaction = 1 API call regardless of operation count
await sheets_transaction({
action: 'begin',
spreadsheetId: '...'
});
// Queue up to 50 operations
await sheets_transaction({
action: 'queue',
operations: [
{ type: 'insert_rows', ... },
{ type: 'format_cells', ... },
{ type: 'set_formulas', ... },
// ... more operations
]
});
await sheets_transaction({
action: 'commit'
});
// Result: 50+ operations in 1 API call
按批量大小划分的配额节省:
| 策略 | API调用 | 配额单位 | 节省 |
|---|---|---|---|
| 单个操作(一次1个) | 100 | 100 | 0% |
| 批量读/写(10次操作/调用) | 10 | 10 | 90% |
| 交易(50次操作/呼叫) | 2 | 2 | 98% |
| 批处理+缓存(重复读取) | 1 | 1 | 99% |
3.速率限制(防止429错误)
配置:
# Configure per your Google Workspace edition
# Default: 300 reads/min, 60 writes/min (Free tier)
# Business Standard: 600 reads/min, 120 writes/min
export RATE_LIMIT_READS_PER_MINUTE=600
export RATE_LIMIT_WRITES_PER_MINUTE=120
# Business Plus: 900 reads/min, 180 writes/min
export RATE_LIMIT_READS_PER_MINUTE=900
export RATE_LIMIT_WRITES_PER_MINUTE=180
# Enterprise: 1200 reads/min, 240 writes/min
export RATE_LIMIT_READS_PER_MINUTE=1200
export RATE_LIMIT_WRITES_PER_MINUTE=240
令牌桶算法:
- 代币以您配置的速率(每秒)重新填充
- 每个操作都会消耗令牌
- 如果令牌不足(背压),操作将等待
- 429个错误触发自动50%的速率降低60秒
示例:带批量优化的免费套餐
// Configuration: 300 reads/min = 5 reads/sec
// Load test 30 spreadsheets worth of data
// Without batching: 30 ops * 10 fields = 300 reads
// Rate limit: 300 reads/min = 5 reads/sec
// Time needed: 300 / 5 = 60 seconds
// With batching: 3 batch_read calls (10 ranges each)
// Time needed: 3 / 5 = 0.6 seconds
// 100x faster with same quota!
动态油门 (429错误时自动):
Standard rate → 429 Error → Reduce 50% (6 months) → Gradual restore → Normal rate
300 reads/min → 150 reads/min (60s) → 225 → 300
4.有效载荷监测(防止10MB硬限制)
配置:
# Enable payload monitoring
export ENABLE_PAYLOAD_MONITORING=true
# Payload size warnings (default: 2MB warning, 10MB hard limit)
export PAYLOAD_WARNING_SIZE_MB=2
export PAYLOAD_MAX_SIZE_MB=10
监控有效载荷大小:
// Monitor request/response sizes
const metrics = googleApi.getPayloadMetrics();
// {
// largestRequest: 1500000, // 1.5MB
// largestResponse: 2500000, // 2.5MB
// averageRequestSize: 45000,
// averageResponseSize: 120000,
// requestsAbove2MB: 3,
// requestsAbove10MB: 0
// }
优化大型有效载荷:
// ❌ Inefficient: Single read of entire sheet (10K rows × 100 cols)
const allData = await sheets_data({
action: 'read',
range: 'Sheet1!A1:CV10000',
});
// ✅ Efficient: Paginated reads
const pageSize = 100;
for (let page = 0; page < 100; page++) {
const startRow = 1 + page * pageSize;
const endRow = startRow + pageSize - 1;
const pageData = await sheets_data({
action: 'read',
range: `Sheet1!A${startRow}:CV${endRow}`,
});
processPage(pageData);
}
5.连接池(HTTP/2)
配置:
# Enable HTTP/2 connection pooling (default: enabled)
export GOOGLE_API_HTTP2_ENABLED=true
# Max concurrent connections (default: 50)
export GOOGLE_API_MAX_SOCKETS=50
# Keep-alive timeout (default: 30 seconds)
export GOOGLE_API_KEEPALIVE_TIMEOUT=30000
# Enable pool monitoring
export ENABLE_HTTP2_POOL_MONITORING=true
export HTTP2_POOL_MONITOR_INTERVAL_MS=300000 # 5 minutes
好处:
- 延迟减少5-15%
- 连接多路复用(每个连接有多个请求)
- 头压缩
- 减少TCP握手开销
监控池运行状况:
// Automatic warnings logged every 5 minutes (if enabled)
// Example log output:
// [INFO] HTTP/2 Pool Status: 45 active, 5 free, 0 pending
// [WARN] HTTP/2 Pool: 90% utilization - consider increasing GOOGLE_API_MAX_SOCKETS
6.指标和可观察性
配置:
# Enable metrics server (default: disabled)
export ENABLE_METRICS_SERVER=true
# Metrics server port (default: 9090)
export METRICS_PORT=9090
# Enable tracing
export OTEL_ENABLED=true
export OTEL_LOG_SPANS=true
访问指标:
# Prometheus format
curl http://localhost:9090/metrics
# JSON format
curl http://localhost:9090/metrics.json
# Human-readable
curl http://localhost:9090/metrics.txt
# Health check
curl http://localhost:9090/health
需监控的关键指标:
| 指标 | 目标 | 行动(如果高) |
|---|---|---|
| 缓存命中率 | >90% | 很好!缓存正在工作 |
| 缓存命中率 | <50% | 增加TTL或最大大小 |
| 平均批量 | >10次操作 | 很好!批量操作 |
| 平均批量大小 | <5个操作 | 每批添加更多操作 |
| API错误429 | 0/min | 很好!费率限制正常 |
| API错误429 | >1/min | 减少请求或增加配额 |
| 响应时间p99 | <2s | 很好!性能正常 |
| 响应时间p99 | >10s | 检查有效载荷大小,添加缓存 |
7.超时配置
配置:
# Google Sheets API timeout (default: 30 seconds)
export GOOGLE_API_TIMEOUT_MS=30000
# Request timeout (default: 120 seconds)
export REQUEST_TIMEOUT_MS=120000
超时调整策略:
| 场景 | API超时 | 请求超时 | 理由 |
|---|---|---|---|
| 大有效载荷(>5MB) | 60000ms | 120000ms | 传输时间更长 |
| 复杂公式 | 45000ms | 90000ms | 公式重新计算速度较慢 |
| 标准操作 | 30000ms | 60000ms | 默认(推荐) |
| 延迟敏感 | 20000ms | 40000ms | 失败快,重试快 |
性能调整检查表
[ ] Enable caching (CACHE_ENABLED=true, CACHE_TTL_MS=300000)
[ ] Use batch operations (batch_read, batch_write, transactions)
[ ] Configure rate limits per your quota (RATE_LIMIT_READS_PER_MINUTE)
[ ] Monitor payloads (<2MB typical, <10MB max)
[ ] Enable HTTP/2 (GOOGLE_API_HTTP2_ENABLED=true)
[ ] Set up metrics server (ENABLE_METRICS_SERVER=true)
[ ] Monitor cache hit rate (target: >90%)
[ ] Implement pagination for large datasets (>10K rows)
[ ] Use webhooks instead of polling (sheets_webhook)
[ ] Enable heap monitoring for long-running servers (ENABLE_HEAP_MONITORING=true)
[ ] Review slowest requests in metrics (/metrics endpoint)
[ ] Profile connection pool usage (HTTP2_POOL_MONITOR_INTERVAL_MS)
[ ] Test with your actual data volume
[ ] Measure baseline performance before optimizing
[ ] Monitor production metrics continuously
MCP合规矩阵
ServalSheets实现了它在发现元数据中通告的MCP 2025-11-25服务器功能。下面的矩阵总结了当前的MCP表面。
协议覆盖范围
| 功能 | 状态 | 版本 | 实现 |
|---|---|---|---|
| JSON-RPC 2.0 | ✅ 完整 | 2.0 | @modelcontextprotocol/sdk v1.27.1 |
| 工具 | ✅ 完整 | 2025-11-25 | 25个工具,407个行动,歧视性工会 |
| 资源 | ✅ 完整 | 2025-11-25 | 6个URI模板+7个知识资源 |
| 提示 | ✅ 完整 | 2025-11-25 | 48个带参数的指导工作流程 |
| 补全 | ✅ 完整 | 2025-11-25 | 参数自动补全 |
| 任务 | ✅ 完整 | SEP-1686 | 后台执行,取消 |
| 引出 | ✅ 完整 | SEP-1036 | 用户对破坏性行动的确认 |
| 采样 | ✅ 完整 | SEP-1577 | AI驱动的分析(表_分析) |
| 日志记录 | ✅ 满 | 2025-11-25 | 动态日志级别控制 |
| 进展 | ✅ 完整 | 2025-11-25 | 长期运行操作报告 |
| 流媒体 | ✅ 完整 | 2025-11-25 | 可流式传输的HTTP+分页响应 |
功能检查表
工具(25个工具✅)
所有25个工具都在测试套件中实现和练习。看 工具摘要 以上为当前每工具动作计数。
判别联合模式 ✅:
- 输入:
z.discriminatedUnion('action', [...]) - 输出:
z.discriminatedUnion('success', [...]) - 类型安全处理程序调度
- 编译时的穷尽性检查
- 通过Zod进行运行时验证
资源(6个URI模板✅)
已实施和测试:
✅ sheets:///{spreadsheetId}
└─ Spreadsheet metadata (title, sheets, properties)
✅ sheets:///{spreadsheetId}/{range}
└─ Range values with formatting context
✅ sheets:///{spreadsheetId}/charts
└─ All charts in spreadsheet
✅ sheets:///{spreadsheetId}/charts/{chartId}
└─ Individual chart specification
✅ sheets:///{spreadsheetId}/pivots
└─ Pivot table configurations
✅ sheets:///{spreadsheetId}/quality
└─ Data quality analysis results
知识资源 (7个资源):
✅ Formulas Reference - All supported Google Sheets functions
✅ Colors Reference - RGB color codes and named colors
✅ Formats Reference - Number, date, currency formats
✅ Conditional Rules - Formatting rule types
✅ Data Validation - Validation condition types
✅ Named Ranges - Documentation and examples
✅ Charts - Chart types and configurations
提示(6个工作流程✅)
已实施和测试:
✅ Create Spreadsheet - Guided sheet creation
✅ Import Data - CSV to Sheets import workflow
✅ Format Data - Formatting and styling guide
✅ Analyze Data - Data analysis workflow
✅ Create Dashboard - Dashboard creation guide
✅ Troubleshoot Issues - Error diagnosis workflow
任务(1986年9月)✅)
已实现的功能:
✅ Background execution - Long-running ops don't block
✅ Progress reporting - Real-time operation status
✅ Cancellation support - AbortController integration
✅ Task store - In-memory (default) or Redis-backed
✅ Result persistence - Completed tasks accessible after execution
✅ Error propagation - Task errors returned to client
示例:长时间运行导入
// Start background import task
const task = await sheets_composite({
action: 'import_csv',
spreadsheetId: '...',
csvData: largeDataset,
targetRange: 'Sheet1!A1',
});
// Result: { taskId: 'task-123', progress: 0, status: 'running' }
// Poll for progress
const status = await getTaskStatus(task.taskId);
// { taskId: 'task-123', progress: 45, status: 'running' }
// Wait for completion
await waitForTask(task.taskId);
// { taskId: 'task-123', progress: 100, status: 'completed', result: {...} }
激发(1936年9月)✅)
实现:用户确认破坏性操作
✅ Confirmation requests - Ask before delete/overwrite
✅ Wizard patterns - Step-by-step guidance
✅ Effect scope validation - Warn about large operations
✅ Dry run preview - Preview changes before execution
✅ Undo/rollback - Automatic snapshots for recovery
示例:安全删除
// 1. Elicitation: Ask for confirmation
const confirm = await sheets_confirm({
action: 'request',
title: 'Delete 500 rows?',
description: 'This operation will delete rows 2-501 from Sheet1',
warning: 'This cannot be undone without using Sheets version history',
suggestedAction: 'Create a version snapshot before proceeding',
});
// 2. User confirms or cancels
// 3. Create snapshot before destructive op
await sheets_collaborate({
action: 'version_create_snapshot',
description: 'Before bulk delete',
});
// 4. Execute deletion
await sheets_dimensions({
action: 'delete_rows',
sheetId: 0,
startIndex: 1,
endIndex: 501,
});
取样(1977年9月✅)
实现:基于人工智能的分析和建议
✅ Comprehensive analysis - Data quality, patterns, anomalies
✅ Pattern detection - Trends, correlations, seasonality
✅ Chart recommendations - Optimal visualizations
✅ Formula generation - Natural language → formulas
✅ Template suggestions - AI-generated spreadsheet templates
✅ Conflict detection - Concurrent modification warnings
示例:从自然语言生成公式
const analysis = await sheets_analyze({
action: 'analyze_data',
spreadsheetId: '...',
range: 'Sales!A1:D100',
question: 'Calculate total revenue for Q4',
});
// Result includes:
// - Pattern analysis (seasonality, trends)
// - Anomalies detected
// - Recommended formula: =SUM(D2:D100)
// - Chart recommendations: [line_chart, bar_chart, metric_chart]
日志记录(动态液位控制✅)
实现:运行时日志级别调整
# Initial log level (default: info)
export LOG_LEVEL=info
# Change at runtime (via logging/setLevel handler)
# Useful for debugging production issues without restart
curl -X POST http://localhost:9090/logging/setLevel \
-d '{"level":"debug"}'
日志级别:调试、信息、警告、错误
运输(3种类型✅)
已实施和测试:
✅ STDIO - For Claude Desktop, local CLI
✅ HTTP/SSE - For web clients, remote access
✅ Streamable HTTP - For large responses, resumability
配置:
# STDIO (default)
npx servalsheets
# HTTP/SSE
PORT=3000 npm run start:http
# HTTP with OAuth
PORT=3000 npm run start:remote
合规性测试结果
截至2026年3月11日, npm run test:all 已成功完成:
315通过测试文件53跳过的测试文件8,613通过测试671跳过的测试
协议兼容性
SDK版本:@modelcontextprotocol/sdk v1.27.1 MCP版本: 2025-11-25 TypeScript:严格模式,0个错误 Node.js:需要20+
安全合规性
✅ OAuth 2.1 with PKCE
✅ Scoped permissions (per-user, per-resource)
✅ Token encryption (optional)
✅ Rate limiting (per-user)
✅ Input validation (Zod schemas)
✅ Error redaction (no token leakage)
✅ CORS configuration (production ready)
✅ HTTPS enforcement (production mode)
生产就绪
✅ Error handling - Comprehensive with recovery strategies
✅ Monitoring - Metrics, logging, health checks
✅ Observability - OpenTelemetry tracing
✅ High availability - Redis session store, multi-instance
✅ Performance - Batching, caching, rate limiting
✅ Security - OAuth 2.1, encryption, token rotation
✅ Testing - 8,500+ tests, coverage reported in CI
✅ Documentation - 115+ pages, examples for all tools
许可证
麻省理工学院