mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 00:48:44 +01:00
feat(google-workspace): REST-backed Sheets tools in server/src/google-workspace-rest-tools (#22027)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents reach Google Workspace through the built-in Google connector and its tool gateway > - Google's hosted Workspace MCP servers are a Developer Preview, so Paperclip will launch on its own tools over Google's REST APIs (`server/src/google-workspace-rest-tools/`) > - Gmail and Calendar are there; Sheets has no REST tools yet, so a Sheets grant has no tools when the connector runs on REST > - This pull request adds the six Sheets tools that `toolScopes.sheets` allows, with the same names, inputs and result shapes as Google's Sheets MCP tools > - The benefit is that Sheets can switch to `paperclip_rest`, and later back to Google's MCP servers, without a rewrite ## Linked Issues or Issue Description Refs #22000 Refs #22017 **Subsystem affected** Google Workspace REST tool set, `server/src/google-workspace-rest-tools/`. **Problem or motivation** The REST tool set has no Sheets tools. Agents with a Sheets grant cannot read or write spreadsheets when the connector runs on REST. **Proposed solution** One file per tool under `sheets/`, with pure argument-to-request and response-to-result functions. Names, fields and annotations come from Google's Sheets MCP reference (https://developers.google.com/workspace/sheets/api/reference/mcp). Each tool uses only the scopes its allowlist entry permits. The README lists the endpoint, scope and Google documentation URL for each tool, the value handling, the bounds, and every difference from Google's tools. **Alternatives considered** Reuse `packages/google-sheets-mcp-server`. It has its own tool names and shapes, and the folder's boundary test forbids the import. ## What Changed - `sheets/get-values.ts`: `get_values` over `spreadsheets.values.get`, formatted values, rows first (the REST defaults, sent explicitly). Google's answer is returned unchanged (`range`, `values`). - `sheets/get-spreadsheet.ts`: `get_spreadsheet` over `spreadsheets.get` with `includeGridData`, `ranges` and `fields`. `commentsIncluded: true` is refused because REST cannot return comments. - `sheets/update-values.ts` and `sheets/update-formulas.ts`: `spreadsheets.values.update` with `valueInputOption` `RAW` and `USER_ENTERED`. Each description names its option. - `sheets/insert-dimension.ts`: one `insertDimension` request through `spreadsheets.batchUpdate`. - `sheets/update-spreadsheet.ts`: `spreadsheets.batchUpdate` with the 64 request types Google documents that REST supports. Comment and data source requests, unknown request types and `writeControl` are refused before sending. The tool is marked `destructiveHint: true` because Google's list includes `deleteSheet`, `deleteDimension`, `deleteRange` and other removing operations. - `sheets/range.ts`: A1 and R1C1 range validation, sheet-name quoting, and range descriptions for write results. - Bounds: at most 50,000 cells read or written per call and 450,000 characters per read result (under the gateway's 1 MB limit). Over a limit, the tool returns an error that asks for a narrower range. It never returns a cut-off result. - Write results: Google's REST response under `content`, plus a `status` sentence that names the changed ranges and the number of cells. - `google-http.ts`: allows `sheets.googleapis.com` only under `/v4/spreadsheets/`. - `probe.ts`: Sheets has no probe, because every Sheets read needs a spreadsheet ID. - `tools.ts`, `allowlist.test.ts`, `README.md`: register the service, check Sheets 6 of 6, and document the tools. ## Verification - `cd server && npx vitest run src/google-workspace-rest-tools`: 34 files, 647 tests pass. The Sheets tests use synthetic fixtures and a fake fetch. There is no network and no real spreadsheet. - Table-driven tests cover ranges (accepted and refused, quoting round trips), request building for each tool, result shapes, cell and size bounds, the uncertain-outcome warning on failed writes without a retry, the host path restriction, the absent probe, and each tool's scopes. - `npx tsc --noEmit -p server`: no errors in `server/src/google-workspace-rest-tools/`. Other errors in this local run come from workspace packages that were not built. - `pnpm verify`: exit 2 (the README is a broad input). Required CI supplies the broad coverage. ## Risks - Low risk. Nothing calls these tools until Sheets is set to `paperclip_rest` in `GOOGLE_WORKSPACE_TOOL_TRANSPORT`. That setting stays `google_mcp`. - Google's reference does not name the value input option of `update_values` or the render option of `get_values`. This PR uses `RAW` and formatted values. A recorded comparison on Google's servers can confirm both. The README lists this. - `update_spreadsheet` accepts the removing operations that Google documents, such as `deleteSheet`. Approval and audit stay with the gateway. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code with tool use (shell, file edits, web fetch). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9c776cdf39
commit
c366a606b1
24 files changed
+1821
-7
No files matched your search
@@ -12,7 +12,8 @@ Gmail has all nine allowlisted tools: `get_message`, `get_thread`,
|
||||
`search_threads`, `list_threads`, `search_messages`, `get_draft`,
|
||||
`list_drafts`, `list_labels` and `create_draft`. Only `create_draft` writes.
|
||||
There is no send, trash, delete or label-changing tool, and none may be added.
|
||||
It also has all nine allowlisted Calendar tools (see "Calendar tools" below).
|
||||
It also has all nine allowlisted Calendar tools (see "Calendar tools" below)
|
||||
and all six allowlisted Sheets tools (see "Sheets tools" below).
|
||||
|
||||
## Why this exists, and why it is temporary
|
||||
|
||||
@@ -57,8 +58,9 @@ so they can be deleted cleanly when that happens.
|
||||
says that the change may or may not have been made. Every method other than
|
||||
GET (POST, PATCH, PUT, DELETE) is a write; the only exception is a POST the
|
||||
request marks `readOnly` (Calendar's free/busy query). `www.googleapis.com`
|
||||
is allowed only under `/calendar/v3/`, checked after URL normalization.
|
||||
- **One tool, one file.** Each tool in `gmail/` and `calendar/` is a set of pure functions
|
||||
is allowed only under `/calendar/v3/` and `sheets.googleapis.com` only under
|
||||
`/v4/spreadsheets/`, checked after URL normalization.
|
||||
- **One tool, one file.** Each tool in `gmail/`, `calendar/` and `sheets/` is a set of pure functions
|
||||
(arguments to REST request, REST response to MCP result) plus a short `run`
|
||||
that sequences them. The pure functions are unit tested without network.
|
||||
- **`server.ts` is thin MCP wiring:** `tools/list` and `tools/call`.
|
||||
@@ -141,6 +143,9 @@ plain constant: no environment variable, instance setting or database row.
|
||||
| Calendar | one event of the primary calendar | `calendar.events.readonly`, `calendar.events`, `calendar.readonly` |
|
||||
| Calendar | one minute of `freeBusy.query` on the primary calendar | `calendar.events.freebusy` |
|
||||
|
||||
Sheets has no probe: every Sheets REST read needs a spreadsheet ID, so a
|
||||
Sheets grant is listed without one.
|
||||
|
||||
A grant that allows none of them (for example compose-only Gmail) is listed
|
||||
without a probe. An insufficient-scope answer to a probe never makes a
|
||||
service unavailable. A 401 refreshes the token and probes once more; a
|
||||
@@ -457,6 +462,150 @@ earliest first; working hours and out-of-office settings are not read.
|
||||
comes from REST `transparency`; `conferenceUrl` from `hangoutLink` or the
|
||||
video entry point.
|
||||
|
||||
## Sheets tools
|
||||
|
||||
Names, input fields, result shapes and annotations come from Google's Sheets
|
||||
MCP reference
|
||||
(<https://developers.google.com/workspace/sheets/api/reference/mcp>, recorded
|
||||
2026-11-17). All calls go to the Sheets REST API v4 at
|
||||
`https://sheets.googleapis.com/v4/spreadsheets/`; `google-http.ts` allows that
|
||||
host only under that path, checked after URL normalization. Each tool works
|
||||
with exactly the scopes `toolScopes.sheets` allows.
|
||||
|
||||
| Tool | REST call | Works with | Google documentation |
|
||||
| --- | --- | --- | --- |
|
||||
| `get_values` | `spreadsheets.values.get` | `spreadsheets.readonly` or `spreadsheets` | <https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets.values/get> |
|
||||
| `get_spreadsheet` | `spreadsheets.get` | `spreadsheets.readonly` or `spreadsheets` | <https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets/get> |
|
||||
| `update_values` | `spreadsheets.values.update`, `valueInputOption=RAW` | `spreadsheets` | <https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets.values/update> |
|
||||
| `update_formulas` | `spreadsheets.values.update`, `valueInputOption=USER_ENTERED` | `spreadsheets` | <https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets.values/update> |
|
||||
| `insert_dimension` | `spreadsheets.batchUpdate` with one `insertDimension` | `spreadsheets` | <https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets/batchUpdate> |
|
||||
| `update_spreadsheet` | `spreadsheets.batchUpdate` | `spreadsheets` | <https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets/batchUpdate> |
|
||||
|
||||
Every tool makes exactly one Google request. Writes are never retried; a write
|
||||
that fails after it was sent carries the usual "may or may not have been
|
||||
made" warning.
|
||||
|
||||
### Values
|
||||
|
||||
- **`get_values` returns formatted values**, as Google Sheets displays them
|
||||
(`valueRenderOption=FORMATTED_VALUE`, `majorDimension=ROWS`, both sent
|
||||
explicitly; these are the REST defaults, and Google's tool exposes no render
|
||||
option). Numbers, currency, percentages and dates come back as the displayed
|
||||
text (`"$1,200.50"`, `"12%"`, `"1/5/2026"`), booleans as `"TRUE"`/`"FALSE"`,
|
||||
errors as their text (`"#DIV/0!"`), and formula cells as their result.
|
||||
Google's answer is returned unchanged: trailing empty rows and columns are
|
||||
left out, so rows can differ in length; an empty range has no `values`
|
||||
field; in a merged area only the top-left cell holds the value. One range per
|
||||
call, as in Google's tool (no `values.batchGet`).
|
||||
- **Unformatted values, formulas and several ranges** come from
|
||||
`get_spreadsheet` with `ranges` and `includeGridData`: each cell has
|
||||
`userEnteredValue` (including the formula), `effectiveValue` (dates and
|
||||
times as serial numbers, days since 1899-12-30) and `formattedValue`; merged
|
||||
areas are listed in `merges`. The Spreadsheet resource is returned unchanged
|
||||
under `content`. `fields` takes Google's field-mask syntax, including
|
||||
groups such as `sheets.properties(sheetId,title)`; a mask with any character
|
||||
other than letters, digits, `_ . , ( ) / *`, or with unbalanced parentheses,
|
||||
is refused before sending.
|
||||
- **`update_values` writes raw values** (`RAW`): strings are stored as given,
|
||||
so `"=A1"`, `"2026-01-05"` and `"1,000"` stay text. Google's reference does
|
||||
not name the option; RAW is our reading of it, because Google ships a
|
||||
separate `update_formulas` tool. **`update_formulas`** uses `USER_ENTERED`,
|
||||
so a string starting with `=` becomes a formula and other text may be parsed
|
||||
by the spreadsheet's locale. Both take strings, finite numbers, booleans and
|
||||
`null` (skip the cell); `""` clears a cell; anything else is refused before
|
||||
sending.
|
||||
- **Ranges** are checked before sending (`sheets/range.ts`): A1 (`A1`,
|
||||
`A1:C10`, `A:C`, `2:5`, `A2:C`, `$A$1`) or R1C1 (`R1C1:R10C3`), with an
|
||||
optional sheet name. A sheet name with anything other than letters, digits
|
||||
and `_` must be in single quotes with apostrophes doubled (`'Q1 Plan'!A1`,
|
||||
`'Bob''s list'!A:A`); an unquoted one is refused with that hint. A bare name
|
||||
is a sheet or named range. Columns are limited to `ZZZ` and rows to
|
||||
10,000,000.
|
||||
|
||||
### Bounds
|
||||
|
||||
- At most **50,000 cells** per call, read or written (`MAX_CELLS_PER_CALL`).
|
||||
Reads count the cells Google returns (`values` rows, or `rowData` values in
|
||||
grid data); writes count the cells sent (`values`/`formulas`, or the rows of
|
||||
`updateCells` and `appendCells`).
|
||||
- A read's whole tool result is at most **250,000 bytes** of UTF-8 JSON
|
||||
(`MAX_RESULT_BYTES`, checked by `boundedStructuredResult` in `tool.ts`). The
|
||||
measure is this folder's own result, which carries the value twice (as
|
||||
`structuredContent` and as JSON text, since MCP clients read either). This
|
||||
is a conservative default, not a measured fit: how a caller wraps and
|
||||
delivers the result, and its byte budget, are the caller's business and are
|
||||
not modeled here. The caller, which knows its own delivery budget, is
|
||||
expected to supply the exact limit in a follow-up that applies one rule to
|
||||
every service in this folder.
|
||||
A write request body is at most 1,000,000 characters.
|
||||
- Over a limit, a read returns an error that starts with the size and asks for
|
||||
a narrower range, fewer or narrower `ranges`, or fewer `fields`, to read in
|
||||
smaller pieces; a write sends nothing. Nothing
|
||||
is ever cut short and presented as complete. A Google answer over the 20 MB
|
||||
transport limit gets the same narrowing message.
|
||||
- Server-side operations in `update_spreadsheet` (for example `repeatCell`,
|
||||
`sortRange`, `findReplace`, `copyPaste`) are bounded by Google, not here.
|
||||
|
||||
### Write results
|
||||
|
||||
Write results are Google's REST response under `content`, plus `status`, a
|
||||
sentence naming what changed. Google says its result has a `status` field but
|
||||
not what it holds.
|
||||
|
||||
- `update_values`/`update_formulas`: `Updated 4 cells in 'Q1 Plan'!A1:B2
|
||||
(2 rows × 2 columns) as raw values.`, from Google's `updatedRange` and
|
||||
`updatedCells`.
|
||||
- `insert_dimension`: the inserted rows or columns, 1-based (`sheet ID 0,
|
||||
rows 6–8`), and that no values were written.
|
||||
- `update_spreadsheet`: each request in order with the range it touched
|
||||
(`1. deleteDimension on sheet ID 0, columns B–C`), and the cells written by
|
||||
`updateCells`/`appendCells`. Where each request type keeps its range (for
|
||||
example `addNamedRange.namedRange.range`) is listed once in
|
||||
`REQUEST_TARGETS`; a test fails if a supported type has no entry.
|
||||
|
||||
### `update_spreadsheet` operations
|
||||
|
||||
Google's reference lists 74 request types. 64 are accepted, each request must
|
||||
have exactly one of them, and anything else is refused before sending. Refused:
|
||||
|
||||
- **Comments** (`insertComment`, `addCommentReply`, `updateCommentPost`,
|
||||
`deleteComment`, `deleteCommentReply`): not part of the Sheets REST API.
|
||||
- **Data sources** (`addDataSource`, `updateDataSource`, `deleteDataSource`,
|
||||
`refreshDataSource`, `cancelDataSourceRefresh`): they need a BigQuery scope
|
||||
outside the allowlist, and Google's insufficient-scope answer would wrongly
|
||||
ask the user to reconnect.
|
||||
|
||||
Google's documented list includes operations that remove content, and they
|
||||
are accepted as documented: `deleteSheet`, `deleteDimension`, `deleteRange`,
|
||||
`deleteDuplicates`, `deleteTable`, `deleteNamedRange`, `deleteEmbeddedObject`,
|
||||
`deleteFilterView`, `deleteConditionalFormatRule`, `deleteProtectedRange`,
|
||||
`deleteBanding`, `deleteDeveloperMetadata`, `deleteDimensionGroup` and
|
||||
`clearBasicFilter`; `cutPaste`, `findReplace`, `sortRange`, `pasteData`,
|
||||
`trimWhitespace` and `randomizeRange` change existing cells. No operation
|
||||
deletes or creates a spreadsheet or changes its sharing. Because of these,
|
||||
`update_spreadsheet` says `destructiveHint: true`, where Google's reference
|
||||
says `false`.
|
||||
|
||||
### Differences from Google's Sheets MCP tools
|
||||
|
||||
- **`get_spreadsheet` `commentsIncluded: true` is refused.** `spreadsheets.get`
|
||||
cannot return comments (they are in the Drive API, outside the Sheets
|
||||
scopes). `false` or unset works.
|
||||
- **`update_spreadsheet` `writeControl` is refused.** Sheets
|
||||
`spreadsheets.batchUpdate` has no required-revision check, so a write cannot
|
||||
be made conditional; any `writeControl` is an error rather than ignored.
|
||||
- **`update_spreadsheet` refuses comment and data source requests** (above)
|
||||
and is marked destructive.
|
||||
- **`insert_dimension` refuses `DIMENSION_UNSPECIFIED`** (Google says not to
|
||||
use it), `endIndex` not greater than `startIndex`, and `inheritFromBefore`
|
||||
with `startIndex` 0, before sending.
|
||||
- **`status`** in write results is our sentence; Google's value is not
|
||||
documented.
|
||||
- **Not verified against Google's servers:** whether Google's `get_values`
|
||||
uses formatted values and whether its `update_values` uses `RAW` (both are
|
||||
the closest reading of the reference). A recorded comparison on the
|
||||
enrolled internal account would settle both.
|
||||
|
||||
## Open questions
|
||||
|
||||
- Whether an OAuth client marked as an AI-powered agent may call the REST APIs.
|
||||
@@ -490,5 +639,5 @@ earliest first; working hours and out-of-office settings are not read.
|
||||
cd server && npx vitest run src/google-workspace-rest-tools
|
||||
```
|
||||
|
||||
Test fixtures in `fixtures/`, `gmail/fixtures/` and `calendar/fixtures/` are synthetic, in the shape
|
||||
Test fixtures in `fixtures/`, `gmail/fixtures/`, `calendar/fixtures/` and `sheets/fixtures/` are synthetic, in the shape
|
||||
of Google's REST responses. They contain no real mail, addresses or IDs.
|
||||
@@ -75,4 +75,11 @@ describe("tool allowlist", () => {
|
||||
expect(googleWorkspaceToolTarget(googleWorkspaceToolName("calendar", "unlisted_tool"))).toBeNull();
|
||||
expect(listGoogleWorkspaceRestTools("calendar").map((tool) => tool.name).sort()).toEqual([...allowlisted].sort());
|
||||
});
|
||||
|
||||
it("implements every allowlisted Sheets tool (6 of 6)", () => {
|
||||
const allowlisted = ["get_values", "get_spreadsheet", "update_spreadsheet", "update_values", "update_formulas", "insert_dimension"];
|
||||
for (const name of allowlisted) expect(googleWorkspaceToolTarget(googleWorkspaceToolName("sheets", name)), name).not.toBeNull();
|
||||
expect(googleWorkspaceToolTarget(googleWorkspaceToolName("sheets", "delete_spreadsheet"))).toBeNull();
|
||||
expect(listGoogleWorkspaceRestTools("sheets").map((tool) => tool.name).sort()).toEqual([...allowlisted].sort());
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,11 @@
|
||||
import { GoogleToolError, GoogleWorkspaceAuthError } from "./errors.js";
|
||||
|
||||
export const GOOGLE_API_HOSTS = ["gmail.googleapis.com", "www.googleapis.com"] as const;
|
||||
export const GOOGLE_API_HOSTS = ["gmail.googleapis.com", "www.googleapis.com", "sheets.googleapis.com"] as const;
|
||||
export type GoogleApiHost = (typeof GOOGLE_API_HOSTS)[number];
|
||||
export const GOOGLE_API_PATH_PREFIXES: Partial<Record<GoogleApiHost, string>> = { "www.googleapis.com": "/calendar/v3/" };
|
||||
export const GOOGLE_API_PATH_PREFIXES: Partial<Record<GoogleApiHost, string>> = {
|
||||
"www.googleapis.com": "/calendar/v3/",
|
||||
"sheets.googleapis.com": "/v4/spreadsheets/",
|
||||
};
|
||||
|
||||
export type QueryValue = string | number | boolean | readonly string[] | undefined;
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ export const GOOGLE_WORKSPACE_REST_PROBES: Readonly<Record<GoogleWorkspaceRestSe
|
||||
request: (now) => freeBusyRequest(["primary"], { start: now, end: now + PROBE_WINDOW_MS }, "UTC"),
|
||||
},
|
||||
],
|
||||
sheets: [],
|
||||
};
|
||||
|
||||
export function googleWorkspaceRestProbeFor(service: GoogleWorkspaceRestService, grantedScopes: readonly string[]): ProbeCandidate | null {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
export const SPREADSHEET_ID = "1SyntheticSheetId_0123456789abcdefghijklmn";
|
||||
|
||||
export const FORMATTED_VALUES = {
|
||||
range: "'Q1 Plan'!A1:D4",
|
||||
majorDimension: "ROWS",
|
||||
values: [
|
||||
["Item", "Amount", "Due", "Paid"],
|
||||
["Hosting", "$1,200.50", "1/5/2026", "TRUE"],
|
||||
["Merged label", "", "12%"],
|
||||
["", "", "", "#DIV/0!"],
|
||||
],
|
||||
};
|
||||
|
||||
export const EMPTY_VALUES = { range: "Sheet1!A1:Z100", majorDimension: "ROWS" };
|
||||
|
||||
export const SPREADSHEET_METADATA = {
|
||||
spreadsheetId: SPREADSHEET_ID,
|
||||
properties: { title: "Synthetic budget", locale: "en_US", timeZone: "America/New_York" },
|
||||
sheets: [
|
||||
{ properties: { sheetId: 0, title: "Q1 Plan", index: 0, gridProperties: { rowCount: 1000, columnCount: 26, frozenRowCount: 1 } } },
|
||||
{ properties: { sheetId: 7, title: "Bob's list", index: 1, gridProperties: { rowCount: 100, columnCount: 5 } } },
|
||||
],
|
||||
spreadsheetUrl: `https://docs.google.com/spreadsheets/d/${SPREADSHEET_ID}/edit`,
|
||||
};
|
||||
|
||||
export const SPREADSHEET_WITH_GRID = {
|
||||
...SPREADSHEET_METADATA,
|
||||
sheets: [{
|
||||
properties: SPREADSHEET_METADATA.sheets[0]!.properties,
|
||||
merges: [{ sheetId: 0, startRowIndex: 2, endRowIndex: 3, startColumnIndex: 0, endColumnIndex: 2 }],
|
||||
data: [{
|
||||
startRow: 0,
|
||||
rowData: [
|
||||
{ values: [
|
||||
{ userEnteredValue: { stringValue: "Due" }, effectiveValue: { stringValue: "Due" }, formattedValue: "Due" },
|
||||
{ userEnteredValue: { numberValue: 46027 }, effectiveValue: { numberValue: 46027 }, formattedValue: "1/5/2026", userEnteredFormat: { numberFormat: { type: "DATE", pattern: "M/d/yyyy" } } },
|
||||
] },
|
||||
{ values: [
|
||||
{ userEnteredValue: { formulaValue: "=SUM(B1:B2)" }, effectiveValue: { numberValue: 1200.5 }, formattedValue: "$1,200.50" },
|
||||
] },
|
||||
],
|
||||
}],
|
||||
}],
|
||||
};
|
||||
|
||||
export const UPDATE_VALUES_RESPONSE = {
|
||||
spreadsheetId: SPREADSHEET_ID,
|
||||
updatedRange: "'Q1 Plan'!A1:B2",
|
||||
updatedRows: 2,
|
||||
updatedColumns: 2,
|
||||
updatedCells: 4,
|
||||
};
|
||||
|
||||
export const BATCH_UPDATE_RESPONSE = { spreadsheetId: SPREADSHEET_ID, replies: [{}] };
|
||||
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { SPREADSHEET_ID, SPREADSHEET_METADATA, SPREADSHEET_WITH_GRID } from "./fixtures/sheets-rest.js";
|
||||
import { serializedResultBytes } from "../tool.js";
|
||||
import { MAX_RESULT_BYTES } from "./spreadsheet.js";
|
||||
import { getSpreadsheet, getSpreadsheetRequest, getSpreadsheetResult, gridCellCount } from "./get-spreadsheet.js";
|
||||
|
||||
const text = (result: { content: unknown[] }) => (result.content[0] as { text: string }).text;
|
||||
|
||||
describe("get_spreadsheet request", () => {
|
||||
it.each([
|
||||
[{ spreadsheetId: SPREADSHEET_ID }, { includeGridData: false, ranges: undefined, fields: undefined }],
|
||||
[{ spreadsheetId: SPREADSHEET_ID, includeGridData: true, ranges: ["'Q1 Plan'!A1:B2", "Sheet2"] },
|
||||
{ includeGridData: true, ranges: ["'Q1 Plan'!A1:B2", "Sheet2"], fields: undefined }],
|
||||
[{ spreadsheetId: SPREADSHEET_ID, fields: ["sheets.properties.sheetId", "sheets.properties.title"] },
|
||||
{ includeGridData: false, ranges: undefined, fields: "sheets.properties.sheetId,sheets.properties.title" }],
|
||||
[{ spreadsheetId: SPREADSHEET_ID, fields: [], ranges: [], commentsIncluded: false }, { includeGridData: false, ranges: undefined, fields: undefined }],
|
||||
])("%j", (input, query) => {
|
||||
expect(getSpreadsheetRequest(input)).toEqual({ method: "GET", host: "sheets.googleapis.com", path: `/v4/spreadsheets/${SPREADSHEET_ID}`, query });
|
||||
});
|
||||
|
||||
it.each([
|
||||
"sheets.properties.title",
|
||||
"sheets.properties(sheetId,title)",
|
||||
"sheets(properties(sheetId,title),merges)",
|
||||
"spreadsheetId,properties.title",
|
||||
"sheets/properties/title",
|
||||
"sheets.data.rowData.values(formattedValue,effectiveValue)",
|
||||
"*",
|
||||
"sheets.properties.*",
|
||||
])("accepts the field mask %s and sends it unchanged", async (mask) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(SPREADSHEET_METADATA));
|
||||
const result = await getSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID, fields: [mask, "spreadsheetId"] }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBeFalsy();
|
||||
expect(calls[0]!.url.searchParams.get("fields")).toBe(`${mask},spreadsheetId`);
|
||||
expect([...calls[0]!.url.searchParams.keys()].sort()).toEqual(["fields", "includeGridData"]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"sheets.properties.title&key=x",
|
||||
"sheets.properties.title=x",
|
||||
"sheets.properties%2Ctitle",
|
||||
"sheets.properties.title\nx",
|
||||
"sheets. properties",
|
||||
" sheets",
|
||||
"sheets\tproperties",
|
||||
"sheets.properties(sheetId,title",
|
||||
"sheets.properties)sheetId(",
|
||||
"sheets#x",
|
||||
"sheets?x",
|
||||
"sheets;x",
|
||||
"",
|
||||
"x".repeat(1_001),
|
||||
])("refuses the field mask %j without sending", async (mask) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({}));
|
||||
const result = await getSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID, fields: [mask] }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(/field mask/);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("sends each range as its own ranges parameter", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(SPREADSHEET_METADATA));
|
||||
await getSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID, ranges: ["Sheet1!A1:B2", "'Q1 Plan'!C:C"] }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(calls[0]!.url.searchParams.getAll("ranges")).toEqual(["Sheet1!A1:B2", "'Q1 Plan'!C:C"]);
|
||||
expect(calls[0]!.url.searchParams.get("includeGridData")).toBe("false");
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_spreadsheet result", () => {
|
||||
it("returns the Spreadsheet resource as content, with cell data, dates as serial numbers and merges unchanged", () => {
|
||||
const result = getSpreadsheetResult(SPREADSHEET_WITH_GRID);
|
||||
expect(result.structuredContent).toEqual({ content: SPREADSHEET_WITH_GRID });
|
||||
expect(gridCellCount(SPREADSHEET_WITH_GRID)).toBe(3);
|
||||
});
|
||||
|
||||
it("bounds the whole serialized result in bytes and asks for fewer or narrower ranges", () => {
|
||||
const sheet = (note: string) => ({ properties: { title: note } });
|
||||
const near = getSpreadsheetResult({ sheets: [sheet("x".repeat(124_900))] });
|
||||
expect(serializedResultBytes(near)).toBeLessThanOrEqual(MAX_RESULT_BYTES);
|
||||
expect(() => getSpreadsheetResult({ sheets: [sheet("x".repeat(125_000))] })).toThrow(/bytes; the limit is 250,000 per call\. Pass fewer or narrower ranges/);
|
||||
});
|
||||
|
||||
it("refuses a result over the cell limit instead of cutting it", () => {
|
||||
const big = { sheets: [{ data: [{ rowData: Array.from({ length: 1_001 }, () => ({ values: Array.from({ length: 50 }, () => ({})) })) }] }] };
|
||||
expect(() => getSpreadsheetResult(big)).toThrow(/50,050 cells; the limit is 50,000 per call\. Pass fewer or narrower ranges/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_spreadsheet tool", () => {
|
||||
it("reads metadata", async () => {
|
||||
const { fetch } = fakeGoogle(() => json(SPREADSHEET_METADATA));
|
||||
const result = await getSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.structuredContent).toEqual({ content: SPREADSHEET_METADATA });
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ spreadsheetId: SPREADSHEET_ID, commentsIncluded: true }, /Comments are not available/],
|
||||
[{ spreadsheetId: SPREADSHEET_ID, ranges: ["Q1 Plan!A1"] }, /must be quoted/],
|
||||
[{ spreadsheetId: SPREADSHEET_ID, ranges: Array.from({ length: 101 }, () => "A1") }, /ranges/],
|
||||
[{ spreadsheetId: "a/b" }, /spreadsheet ID/],
|
||||
])("refuses %j without sending", async (args, message) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({}));
|
||||
const result = await getSpreadsheet.call(args, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(message);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { GoogleToolError } from "../errors.js";
|
||||
import type { GoogleRequest } from "../google-http.js";
|
||||
import { defineTool } from "../tool.js";
|
||||
import {
|
||||
boundedReadResult,
|
||||
contentOutputSchema,
|
||||
RANGE_RULES,
|
||||
sendRead,
|
||||
SHEETS_HOST,
|
||||
sheetRange,
|
||||
spreadsheetId,
|
||||
spreadsheetIdInput,
|
||||
spreadsheetPath,
|
||||
} from "./spreadsheet.js";
|
||||
|
||||
export const MAX_RANGES = 100;
|
||||
export const MAX_FIELDS = 100;
|
||||
|
||||
export const MAX_FIELD_MASK_LENGTH = 1_000;
|
||||
const FIELD_MASK_HINT = "must be a field mask such as sheets.properties.title or sheets.properties(sheetId,title), using only letters, digits, _ . , ( ) / and *";
|
||||
|
||||
export function isBalancedFieldMask(mask: string): boolean {
|
||||
let depth = 0;
|
||||
for (const character of mask) {
|
||||
if (character === "(") depth += 1;
|
||||
if (character === ")") depth -= 1;
|
||||
if (depth < 0) return false;
|
||||
}
|
||||
return depth === 0;
|
||||
}
|
||||
|
||||
const fieldPath = z.string()
|
||||
.regex(new RegExp(`^[A-Za-z0-9_.,()*/]{1,${MAX_FIELD_MASK_LENGTH}}$`), FIELD_MASK_HINT)
|
||||
.refine(isBalancedFieldMask, FIELD_MASK_HINT);
|
||||
|
||||
const args = z.object({
|
||||
spreadsheetId,
|
||||
includeGridData: z.boolean().optional(),
|
||||
fields: z.array(fieldPath).max(MAX_FIELDS).optional(),
|
||||
ranges: z.array(sheetRange).max(MAX_RANGES).optional(),
|
||||
commentsIncluded: z.boolean().optional(),
|
||||
});
|
||||
export type GetSpreadsheetArgs = z.infer<typeof args>;
|
||||
|
||||
interface RestGridData { rowData?: Array<{ values?: unknown[] }> }
|
||||
export interface RestSpreadsheet {
|
||||
spreadsheetId?: string;
|
||||
sheets?: Array<{ data?: RestGridData[]; [key: string]: unknown }>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
const NARROW = "Pass fewer or narrower ranges (for example one sheet, or Sheet1!A1:Z1000), leave includeGridData off, or ask for fewer fields; read the rest in further calls.";
|
||||
|
||||
export function getSpreadsheetRequest(input: GetSpreadsheetArgs): GoogleRequest {
|
||||
if (input.commentsIncluded) {
|
||||
throw new GoogleToolError("unsupported", "Comments are not available from this tool. Call it again without commentsIncluded.");
|
||||
}
|
||||
return {
|
||||
method: "GET",
|
||||
host: SHEETS_HOST,
|
||||
path: spreadsheetPath(input.spreadsheetId),
|
||||
query: {
|
||||
includeGridData: input.includeGridData ?? false,
|
||||
ranges: input.ranges?.length ? input.ranges : undefined,
|
||||
fields: input.fields?.length ? input.fields.join(",") : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function gridCellCount(spreadsheet: RestSpreadsheet): number {
|
||||
let cells = 0;
|
||||
for (const sheet of spreadsheet.sheets ?? []) {
|
||||
for (const grid of sheet.data ?? []) {
|
||||
for (const row of grid.rowData ?? []) cells += row.values?.length ?? 0;
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
export function getSpreadsheetResult(spreadsheet: RestSpreadsheet): CallToolResult {
|
||||
return boundedReadResult({ content: spreadsheet }, gridCellCount(spreadsheet), NARROW);
|
||||
}
|
||||
|
||||
export const getSpreadsheet = defineTool({
|
||||
definition: {
|
||||
name: "get_spreadsheet",
|
||||
description: "Returns a spreadsheet as Google's Sheets API Spreadsheet resource: its title, locale, time zone, sheets (names, IDs, sizes, frozen rows), named ranges and other metadata. With includeGridData it also returns cell data for ranges (or every sheet): each cell has userEnteredValue (what was typed, including formulas), effectiveValue (the computed value; dates and times are serial numbers counted in days from December 30, 1899), formattedValue (the text shown) and its format; merged areas are listed under merges. Use fields to return only what you need. Returns at most 50,000 cells per call; a larger result is an error asking for narrower ranges or fewer fields, never a cut-off result. Comments are not available (commentsIncluded is refused).",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
spreadsheetId: spreadsheetIdInput,
|
||||
includeGridData: { type: "boolean", description: "Optional. True to return cell data. Ignored when fields is set. Default: false." },
|
||||
fields: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
description: "Optional. Field masks naming the parts of the Spreadsheet resource to return, as paths in its JSON, for example sheets.properties.sheetId and sheets.properties.title, or grouped as sheets.properties(sheetId,title). Default: everything except cell data.",
|
||||
},
|
||||
ranges: {
|
||||
type: "array",
|
||||
items: { type: "string" },
|
||||
description: `Optional. The ranges to return, each in ${RANGE_RULES} Default: the whole spreadsheet.`,
|
||||
},
|
||||
commentsIncluded: { type: "boolean", description: "Optional. Not supported here: true is refused. Default: false." },
|
||||
},
|
||||
required: ["spreadsheetId"],
|
||||
},
|
||||
outputSchema: contentOutputSchema,
|
||||
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
return getSpreadsheetResult(await sendRead<RestSpreadsheet>(http, getSpreadsheetRequest(input), NARROW));
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { EMPTY_VALUES, FORMATTED_VALUES, SPREADSHEET_ID } from "./fixtures/sheets-rest.js";
|
||||
import { getValues, getValuesRequest, getValuesResult } from "./get-values.js";
|
||||
import { serializedResultBytes } from "../tool.js";
|
||||
import { boundedReadResult, MAX_CELLS_PER_CALL, MAX_RESULT_BYTES } from "./spreadsheet.js";
|
||||
|
||||
const text = (result: { content: unknown[] }) => (result.content[0] as { text: string }).text;
|
||||
|
||||
describe("get_values request", () => {
|
||||
it.each([
|
||||
["Sheet1!A1:B2", `/v4/spreadsheets/${SPREADSHEET_ID}/values/Sheet1!A1%3AB2`],
|
||||
["'Q1 Plan'!A1:D4", `/v4/spreadsheets/${SPREADSHEET_ID}/values/'Q1%20Plan'!A1%3AD4`],
|
||||
["'Bob''s list'!A:A", `/v4/spreadsheets/${SPREADSHEET_ID}/values/'Bob''s%20list'!A%3AA`],
|
||||
["Sheet1!R1C1:R2C2", `/v4/spreadsheets/${SPREADSHEET_ID}/values/Sheet1!R1C1%3AR2C2`],
|
||||
])("reads %s as formatted values, rows first", async (range, pathname) => {
|
||||
const request = getValuesRequest({ spreadsheetId: SPREADSHEET_ID, range });
|
||||
expect(request).toMatchObject({ method: "GET", host: "sheets.googleapis.com", query: { majorDimension: "ROWS", valueRenderOption: "FORMATTED_VALUE" } });
|
||||
const { fetch, calls } = fakeGoogle(() => json(EMPTY_VALUES));
|
||||
await getValues.call({ spreadsheetId: SPREADSHEET_ID, range }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(calls[0]!.url.pathname).toBe(pathname);
|
||||
expect(calls[0]!.url.searchParams.get("valueRenderOption")).toBe("FORMATTED_VALUE");
|
||||
expect(decodeURIComponent(calls[0]!.url.pathname.split("/values/")[1]!)).toBe(range);
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_values result", () => {
|
||||
it("returns Google's range and formatted values unchanged, keeping ragged rows, merged blanks and error text", () => {
|
||||
expect(getValuesResult(FORMATTED_VALUES).structuredContent).toEqual({ range: FORMATTED_VALUES.range, values: FORMATTED_VALUES.values });
|
||||
});
|
||||
|
||||
it("leaves values out for an empty range, as Google does", () => {
|
||||
expect(getValuesResult(EMPTY_VALUES).structuredContent).toEqual({ range: "Sheet1!A1:Z100" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["too many cells", [Array.from({ length: MAX_CELLS_PER_CALL + 1 }, () => "")], /50,001 cells; the limit is 50,000/],
|
||||
["too many bytes", [["x".repeat(130_000)]], /bytes; the limit is 250,000 per call\. Ask for a narrower range/],
|
||||
])("refuses %s instead of cutting the result", (_name, values, message) => {
|
||||
expect(() => getValuesResult({ range: "Sheet1!A1:Z", values })).toThrow(message);
|
||||
});
|
||||
|
||||
it.each([["x"], ["é"], ["\""]])("bounds the whole serialized result, text and structured content together, for cells of %j", (unit) => {
|
||||
const sized = (count: number) => ({ range: "Sheet1!A1:B2", values: [[unit.repeat(count)], ["tail"]] });
|
||||
const bytes = (count: number) => serializedResultBytes({ content: [{ type: "text", text: JSON.stringify(sized(count)) }], structuredContent: sized(count) });
|
||||
let largest = 0;
|
||||
for (let step = 1 << 20; step >= 1; step >>= 1) if (bytes(largest + step) <= MAX_RESULT_BYTES) largest += step;
|
||||
const near = getValuesResult(sized(largest));
|
||||
expect(serializedResultBytes(near)).toBe(bytes(largest));
|
||||
expect(serializedResultBytes(near)).toBeLessThanOrEqual(MAX_RESULT_BYTES);
|
||||
expect(serializedResultBytes(near)).toBeGreaterThan(MAX_RESULT_BYTES - 16);
|
||||
expect(bytes(largest + 1)).toBeGreaterThan(MAX_RESULT_BYTES);
|
||||
expect(() => getValuesResult(sized(largest + 1))).toThrow(/bytes; the limit is 250,000 per call\. Ask for a narrower range/);
|
||||
});
|
||||
|
||||
it("accepts exactly the cell limit and refuses one more", () => {
|
||||
expect(boundedReadResult({ range: "Sheet1!A1" }, MAX_CELLS_PER_CALL, "narrow").isError).toBeUndefined();
|
||||
expect(() => boundedReadResult({ range: "Sheet1!A1" }, MAX_CELLS_PER_CALL + 1, "narrow")).toThrow(/50,001 cells/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("get_values tool", () => {
|
||||
it("returns a narrowing error when the result is too large", async () => {
|
||||
const values = Array.from({ length: 1_001 }, () => Array.from({ length: 50 }, () => "1"));
|
||||
const { fetch } = fakeGoogle(() => json({ range: "Sheet1!A1:AX1001", values }));
|
||||
const result = await getValues.call({ spreadsheetId: SPREADSHEET_ID, range: "Sheet1" }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(/Ask for a narrower range/);
|
||||
});
|
||||
|
||||
it("turns Google's too-large response into the same narrowing error", async () => {
|
||||
const { fetch } = fakeGoogle(() => new Response("{}", { status: 200, headers: { "content-length": String(21 * 1024 * 1024) } }));
|
||||
const result = await getValues.call({ spreadsheetId: SPREADSHEET_ID, range: "Sheet1" }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(text(result)).toMatch(/too large to return\. Ask for a narrower range/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ spreadsheetId: SPREADSHEET_ID, range: "Q1 Plan!A1" }, /must be quoted/],
|
||||
[{ spreadsheetId: "../other", range: "A1" }, /spreadsheet ID/],
|
||||
[{ spreadsheetId: SPREADSHEET_ID }, /range/],
|
||||
[{ spreadsheetId: SPREADSHEET_ID, range: "Sheet1!A1", valueRenderOption: "FORMULA" }, null],
|
||||
])("validates %j before sending", async (args, message) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(EMPTY_VALUES));
|
||||
const result = await getValues.call(args, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
if (message) {
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(message);
|
||||
expect(calls).toHaveLength(0);
|
||||
} else {
|
||||
expect(calls[0]!.url.searchParams.get("valueRenderOption")).toBe("FORMATTED_VALUE");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import type { GoogleRequest } from "../google-http.js";
|
||||
import { compact, defineTool } from "../tool.js";
|
||||
import {
|
||||
boundedReadResult,
|
||||
countCells,
|
||||
RANGE_RULES,
|
||||
sendRead,
|
||||
SHEETS_HOST,
|
||||
sheetRange,
|
||||
spreadsheetId,
|
||||
spreadsheetIdInput,
|
||||
valuesPath,
|
||||
} from "./spreadsheet.js";
|
||||
|
||||
const args = z.object({ spreadsheetId, range: sheetRange });
|
||||
export type GetValuesArgs = z.infer<typeof args>;
|
||||
|
||||
export interface RestValueRange {
|
||||
range?: string;
|
||||
majorDimension?: string;
|
||||
values?: unknown[][];
|
||||
}
|
||||
|
||||
const NARROW = "Ask for a narrower range, with fewer rows or columns (for example Sheet1!A1:Z1000), and read the rest in further calls.";
|
||||
|
||||
export function getValuesRequest(input: GetValuesArgs): GoogleRequest {
|
||||
return {
|
||||
method: "GET",
|
||||
host: SHEETS_HOST,
|
||||
path: valuesPath(input.spreadsheetId, input.range),
|
||||
query: { majorDimension: "ROWS", valueRenderOption: "FORMATTED_VALUE" },
|
||||
};
|
||||
}
|
||||
|
||||
export function getValuesResult(response: RestValueRange): CallToolResult {
|
||||
const value = compact({ range: response.range, values: response.values });
|
||||
return boundedReadResult(value, countCells(response.values), NARROW);
|
||||
}
|
||||
|
||||
export const getValues = defineTool({
|
||||
definition: {
|
||||
name: "get_values",
|
||||
description: "Returns the values in one range of a spreadsheet, row by row, exactly as Google Sheets displays them (formatted values): numbers, currency, percentages, dates and booleans come back as the formatted text shown in the cell (for example \"$1,200.50\", \"12%\", \"1/5/2026\", \"TRUE\"), and formula cells return their result, not the formula. Empty rows and columns at the end of the range are left out, so rows can have different lengths and an empty range has no values. In a merged area only the top-left cell holds the value. Reads at most 50,000 cells per call; a larger result is an error asking for a smaller range, never a cut-off result. For several ranges at once, formulas, or unformatted numbers and date serial numbers, use get_spreadsheet with ranges and includeGridData.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
spreadsheetId: spreadsheetIdInput,
|
||||
range: { type: "string", description: `Required. The range to read, in ${RANGE_RULES}` },
|
||||
},
|
||||
required: ["spreadsheetId", "range"],
|
||||
},
|
||||
outputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
range: { type: "string", description: "The range the values cover, in A1 notation." },
|
||||
values: {
|
||||
type: "array",
|
||||
description: "The values, one array per row. Empty trailing rows and columns are omitted.",
|
||||
items: { type: "array", items: {} },
|
||||
},
|
||||
},
|
||||
},
|
||||
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
return getValuesResult(await sendRead<RestValueRange>(http, getValuesRequest(input), NARROW));
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { RestTool } from "../tool.js";
|
||||
import { getSpreadsheet } from "./get-spreadsheet.js";
|
||||
import { getValues } from "./get-values.js";
|
||||
import { insertDimension } from "./insert-dimension.js";
|
||||
import { updateFormulas } from "./update-formulas.js";
|
||||
import { updateSpreadsheet } from "./update-spreadsheet.js";
|
||||
import { updateValues } from "./update-values.js";
|
||||
|
||||
export const SHEETS_TOOLS: readonly RestTool[] = [
|
||||
getValues, getSpreadsheet, updateSpreadsheet, updateValues, updateFormulas, insertDimension,
|
||||
];
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { BATCH_UPDATE_RESPONSE, SPREADSHEET_ID } from "./fixtures/sheets-rest.js";
|
||||
import { insertDimension, insertDimensionRequest, insertDimensionStatus } from "./insert-dimension.js";
|
||||
|
||||
const base = { spreadsheetId: SPREADSHEET_ID, sheetId: 0, dimension: "ROWS" as const, startIndex: 5, endIndex: 8 };
|
||||
const text = (result: { content: unknown[] }) => (result.content[0] as { text: string }).text;
|
||||
|
||||
describe("insert_dimension request", () => {
|
||||
it.each([
|
||||
[base, { range: { sheetId: 0, dimension: "ROWS", startIndex: 5, endIndex: 8 } }],
|
||||
[{ ...base, inheritFromBefore: true }, { range: { sheetId: 0, dimension: "ROWS", startIndex: 5, endIndex: 8 }, inheritFromBefore: true }],
|
||||
[{ ...base, dimension: "COLUMNS" as const, sheetId: 7, startIndex: 0, endIndex: 1, inheritFromBefore: false },
|
||||
{ range: { sheetId: 7, dimension: "COLUMNS", startIndex: 0, endIndex: 1 }, inheritFromBefore: false }],
|
||||
])("%j", (input, insert) => {
|
||||
expect(insertDimensionRequest(input)).toEqual({
|
||||
method: "POST",
|
||||
host: "sheets.googleapis.com",
|
||||
path: `/v4/spreadsheets/${SPREADSHEET_ID}:batchUpdate`,
|
||||
body: { requests: [{ insertDimension: insert }] },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[base, "Inserted 3 empty rows (now sheet ID 0, rows 6–8); existing cells from there on moved down. No cell values were written."],
|
||||
[{ ...base, dimension: "COLUMNS" as const, startIndex: 2, endIndex: 3 }, "Inserted 1 empty column (now sheet ID 0, column C); existing cells from there on moved right. No cell values were written."],
|
||||
])("status for %j", (input, status) => {
|
||||
expect(insertDimensionStatus(input)).toBe(status);
|
||||
});
|
||||
});
|
||||
|
||||
describe("insert_dimension tool", () => {
|
||||
it("sends one batchUpdate and returns Google's answer with the status", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(BATCH_UPDATE_RESPONSE));
|
||||
const result = await insertDimension.call(base, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(calls.map((call) => `${call.method} ${call.url.pathname}`)).toEqual([`POST /v4/spreadsheets/${SPREADSHEET_ID}:batchUpdate`]);
|
||||
expect(result.structuredContent).toEqual({ content: { ...BATCH_UPDATE_RESPONSE, status: insertDimensionStatus(base) } });
|
||||
});
|
||||
|
||||
it("never retries and warns the insert may have happened", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({ error: { code: 500 } }, 500));
|
||||
const result = await insertDimension.call(base, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 }));
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(text(result)).toMatch(/may or may not have been made/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ ...base, dimension: "DIMENSION_UNSPECIFIED" }, /ROWS or COLUMNS/],
|
||||
[{ ...base, dimension: "CELLS" }, /dimension/],
|
||||
[{ ...base, endIndex: 5 }, /greater than startIndex/],
|
||||
[{ ...base, startIndex: -1 }, /startIndex/],
|
||||
[{ ...base, startIndex: 0, endIndex: 2, inheritFromBefore: true }, /startIndex is greater than 0/],
|
||||
[{ ...base, sheetId: 1.5 }, /sheetId/],
|
||||
[{ ...base, endIndex: 2 ** 31 }, /endIndex/],
|
||||
])("refuses %j without sending", async (args, message) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({}));
|
||||
const result = await insertDimension.call(args, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(message);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import type { GoogleRequest } from "../google-http.js";
|
||||
import { defineTool, structuredResult } from "../tool.js";
|
||||
import { describeDimensionRange } from "./range.js";
|
||||
import { batchUpdatePath, SHEETS_HOST, spreadsheetId, spreadsheetIdInput, writeOutputSchema } from "./spreadsheet.js";
|
||||
|
||||
const INT32_MAX = 2_147_483_647;
|
||||
export const DIMENSIONS = ["DIMENSION_UNSPECIFIED", "COLUMNS", "ROWS"] as const;
|
||||
const index = z.number().int().min(0).max(INT32_MAX);
|
||||
|
||||
const args = z.object({
|
||||
spreadsheetId,
|
||||
sheetId: index,
|
||||
dimension: z.enum(DIMENSIONS).refine((value) => value !== "DIMENSION_UNSPECIFIED", "must be ROWS or COLUMNS"),
|
||||
startIndex: index,
|
||||
endIndex: index,
|
||||
inheritFromBefore: z.boolean().optional(),
|
||||
}).superRefine((input, context) => {
|
||||
if (input.endIndex <= input.startIndex) context.addIssue({ code: "custom", path: ["endIndex"], message: "must be greater than startIndex" });
|
||||
if (input.inheritFromBefore && input.startIndex === 0) {
|
||||
context.addIssue({ code: "custom", path: ["inheritFromBefore"], message: "can be true only when startIndex is greater than 0" });
|
||||
}
|
||||
});
|
||||
export type InsertDimensionArgs = z.infer<typeof args>;
|
||||
|
||||
export interface BatchUpdateResponse {
|
||||
spreadsheetId?: string;
|
||||
replies?: unknown[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export function insertDimensionRequest(input: InsertDimensionArgs): GoogleRequest {
|
||||
return {
|
||||
method: "POST",
|
||||
host: SHEETS_HOST,
|
||||
path: batchUpdatePath(input.spreadsheetId),
|
||||
body: {
|
||||
requests: [{
|
||||
insertDimension: {
|
||||
range: { sheetId: input.sheetId, dimension: input.dimension, startIndex: input.startIndex, endIndex: input.endIndex },
|
||||
...(input.inheritFromBefore === undefined ? {} : { inheritFromBefore: input.inheritFromBefore }),
|
||||
},
|
||||
}],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function insertDimensionStatus(input: InsertDimensionArgs): string {
|
||||
const count = input.endIndex - input.startIndex;
|
||||
const noun = input.dimension === "COLUMNS" ? (count === 1 ? "column" : "columns") : (count === 1 ? "row" : "rows");
|
||||
const range = { sheetId: input.sheetId, dimension: input.dimension, startIndex: input.startIndex, endIndex: input.endIndex };
|
||||
return `Inserted ${count} empty ${noun} (now ${describeDimensionRange(range)}); existing cells from there on moved ${input.dimension === "COLUMNS" ? "right" : "down"}. No cell values were written.`;
|
||||
}
|
||||
|
||||
export function insertDimensionResult(input: InsertDimensionArgs, response: BatchUpdateResponse): CallToolResult {
|
||||
return structuredResult({ content: { ...response, status: insertDimensionStatus(input) } });
|
||||
}
|
||||
|
||||
export const insertDimension = defineTool({
|
||||
definition: {
|
||||
name: "insert_dimension",
|
||||
description: "Inserts empty rows or columns into one sheet at a 0-based position, moving the existing rows down or columns right. It writes no cell values and deletes nothing. The result's status says which rows or columns were inserted. A failed insert is never retried automatically.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
spreadsheetId: spreadsheetIdInput,
|
||||
sheetId: { type: "integer", description: "Required. The ID of the sheet to insert into (sheets.properties.sheetId from get_spreadsheet; the first sheet is often 0)." },
|
||||
dimension: { type: "string", enum: [...DIMENSIONS], description: "Required. ROWS or COLUMNS. DIMENSION_UNSPECIFIED is refused." },
|
||||
startIndex: { type: "integer", description: "Required. The 0-based start index of the insertion (inclusive). Row 1 is index 0; column A is index 0." },
|
||||
endIndex: { type: "integer", description: "Required. The 0-based end index of the insertion (exclusive). endIndex minus startIndex rows or columns are inserted." },
|
||||
inheritFromBefore: { type: "boolean", description: "Optional. True to copy formatting and size from the row or column before the insertion (startIndex must then be greater than 0); false to copy from the one after. Default: false." },
|
||||
},
|
||||
required: ["spreadsheetId", "sheetId", "dimension", "startIndex", "endIndex"],
|
||||
},
|
||||
outputSchema: writeOutputSchema,
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
return insertDimensionResult(input, await http.send<BatchUpdateResponse>(insertDimensionRequest(input)));
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
checkSheetRange,
|
||||
columnLetters,
|
||||
columnNumber,
|
||||
describeDimensionRange,
|
||||
describeGridRange,
|
||||
formatSheetRange,
|
||||
quoteSheetName,
|
||||
} from "./range.js";
|
||||
|
||||
describe("checkSheetRange accepts", () => {
|
||||
it.each([
|
||||
["A1", { cells: "A1" }],
|
||||
["a1:c10", { cells: "a1:c10" }],
|
||||
["Sheet1", { sheet: "Sheet1" }],
|
||||
["Sheet1!A1:B2", { sheet: "Sheet1", cells: "A1:B2" }],
|
||||
["Sheet1!A:C", { sheet: "Sheet1", cells: "A:C" }],
|
||||
["Sheet1!2:5", { sheet: "Sheet1", cells: "2:5" }],
|
||||
["Sheet1!A2:C", { sheet: "Sheet1", cells: "A2:C" }],
|
||||
["Sheet1!A5:A", { sheet: "Sheet1", cells: "A5:A" }],
|
||||
["Sheet1!$A$1:$B$2", { sheet: "Sheet1", cells: "$A$1:$B$2" }],
|
||||
["Sheet1!B2:A1", { sheet: "Sheet1", cells: "B2:A1" }],
|
||||
["Sheet1!ZZZ10000000", { sheet: "Sheet1", cells: "ZZZ10000000" }],
|
||||
["Sheet1!R1C1:R10C3", { sheet: "Sheet1", cells: "R1C1:R10C3" }],
|
||||
["R2C2", { cells: "R2C2" }],
|
||||
["'Q1 Plan'!A1:B2", { sheet: "Q1 Plan", cells: "A1:B2" }],
|
||||
["'Bob''s list'!A:A", { sheet: "Bob's list", cells: "A:A" }],
|
||||
["'''quoted'''!A1", { sheet: "'quoted'", cells: "A1" }],
|
||||
["'Q1 Plan'", { sheet: "Q1 Plan" }],
|
||||
["'Sales!2026'!C3", { sheet: "Sales!2026", cells: "C3" }],
|
||||
["Données!A1", { sheet: "Données", cells: "A1" }],
|
||||
["売上!B2:C3", { sheet: "売上", cells: "B2:C3" }],
|
||||
["Budget_2026", { sheet: "Budget_2026" }],
|
||||
])("%s", (text, range) => {
|
||||
expect(checkSheetRange(text)).toEqual({ ok: true, range });
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkSheetRange refuses", () => {
|
||||
it.each([
|
||||
["", /empty/],
|
||||
[" Sheet1!A1", /space/],
|
||||
["Sheet1!A1 ", /space/],
|
||||
["Sheet1!A1\nB2", /line break/],
|
||||
["Q1 Plan!A1", /must be quoted/],
|
||||
["Bob's list!A1", /must be quoted/],
|
||||
["Q1 Plan", /neither a cell range nor a plain sheet name/],
|
||||
["'Q1 Plan!A1", /not closed/],
|
||||
["'Q1 Plan'A1", /Expected !/],
|
||||
["'Q1 Plan'!", /Expected !/],
|
||||
["''!A1", /sheet name is empty/],
|
||||
["!A1", /before ! is empty/],
|
||||
["Sheet1!", /after !/],
|
||||
["Sheet1!A", /not a cell range/],
|
||||
["Sheet1!1", /not a cell range/],
|
||||
["Sheet1!A:1", /not a cell range/],
|
||||
["Sheet1!A1:B2:C3", /not a cell range/],
|
||||
["Sheet1!A0", /not a cell range/],
|
||||
["Sheet1!AAAA1", /not a cell range/],
|
||||
["Sheet1!ZZZ10000001", /not a cell range/],
|
||||
["Sheet1!A1,B2", /not a cell range/],
|
||||
["Sheet1!R0C1", /not a cell range/],
|
||||
["..", /neither/],
|
||||
["Sheet1!../x", /not a cell range/],
|
||||
["x".repeat(1001), /longer than 1000/],
|
||||
])("%j", (text, message) => {
|
||||
const check = checkSheetRange(text);
|
||||
expect(check.ok).toBe(false);
|
||||
expect(check.ok ? "" : check.message).toMatch(message);
|
||||
});
|
||||
|
||||
it("explains how to quote a sheet name", () => {
|
||||
const check = checkSheetRange("Q1 Plan!A1");
|
||||
expect(check.ok ? "" : check.message).toContain("'Q1 Plan'!A1:B2");
|
||||
});
|
||||
});
|
||||
|
||||
describe("quoteSheetName", () => {
|
||||
it.each([
|
||||
["Sheet1", "Sheet1"],
|
||||
["Budget_2026", "Budget_2026"],
|
||||
["Données", "Données"],
|
||||
["Q1 Plan", "'Q1 Plan'"],
|
||||
["Bob's list", "'Bob''s list'"],
|
||||
["Sales!2026", "'Sales!2026'"],
|
||||
["A1", "'A1'"],
|
||||
["R1C1", "'R1C1'"],
|
||||
["2026", "'2026'"],
|
||||
["a-b", "'a-b'"],
|
||||
])("%s -> %s", (name, quoted) => {
|
||||
expect(quoteSheetName(name)).toBe(quoted);
|
||||
});
|
||||
|
||||
it.each(["Q1 Plan", "Bob's list", "'quoted'", "Sales!2026", "A1"])("round-trips %s through checkSheetRange", (name) => {
|
||||
expect(checkSheetRange(formatSheetRange({ sheet: name, cells: "A1:B2" }))).toEqual({ ok: true, range: { sheet: name, cells: "A1:B2" } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("columns", () => {
|
||||
it.each([[0, "A"], [25, "Z"], [26, "AA"], [701, "ZZ"], [702, "AAA"], [18_277, "ZZZ"]])("%i is %s", (index, letters) => {
|
||||
expect(columnLetters(index)).toBe(letters);
|
||||
expect(columnNumber(letters)).toBe(index + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("describing grid and dimension ranges", () => {
|
||||
it.each([
|
||||
[{ sheetId: 0, startRowIndex: 0, endRowIndex: 2, startColumnIndex: 0, endColumnIndex: 3 }, "sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ sheetId: 4, startRowIndex: 9, endRowIndex: 10, startColumnIndex: 27, endColumnIndex: 28 }, "sheet ID 4, row 10, column AB"],
|
||||
[{ sheetId: 4 }, "sheet ID 4, all rows, all columns"],
|
||||
[{ sheetId: 1, startRowIndex: 5 }, "sheet ID 1, rows 6 onward, all columns"],
|
||||
[{}, "sheet ID 0, all rows, all columns"],
|
||||
])("%j", (range, text) => {
|
||||
expect(describeGridRange(range)).toBe(text);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ sheetId: 0, dimension: "ROWS", startIndex: 5, endIndex: 8 }, "sheet ID 0, rows 6–8"],
|
||||
[{ sheetId: 2, dimension: "COLUMNS", startIndex: 2, endIndex: 3 }, "sheet ID 2, column C"],
|
||||
])("%j", (range, text) => {
|
||||
expect(describeDimensionRange(range)).toBe(text);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
export const MAX_COLUMN = 18_278;
|
||||
export const MAX_ROW = 10_000_000;
|
||||
export const MAX_RANGE_LENGTH = 1_000;
|
||||
|
||||
export interface SheetRange {
|
||||
sheet?: string;
|
||||
cells?: string;
|
||||
}
|
||||
|
||||
export type RangeCheck = { ok: true; range: SheetRange } | { ok: false; message: string };
|
||||
|
||||
const UNQUOTED_NAME = /^[\p{L}\p{N}_]+$/u;
|
||||
const A1_PART = /^(\$?([A-Za-z]{1,3}))?(\$?([1-9]\d{0,7}))?$/;
|
||||
const R1C1 = /^R([1-9]\d{0,7})C([1-9]\d{0,4})(?::R([1-9]\d{0,7})C([1-9]\d{0,4}))?$/i;
|
||||
const QUOTING_HINT = "Put a sheet name with spaces or punctuation in single quotes and double any apostrophe, for example 'Q1 Plan'!A1:B2 or 'Bob''s list'!A:A.";
|
||||
|
||||
export function columnNumber(letters: string): number {
|
||||
return [...letters.toUpperCase()].reduce((total, letter) => total * 26 + (letter.charCodeAt(0) - 64), 0);
|
||||
}
|
||||
|
||||
export function columnLetters(index: number): string {
|
||||
let letters = "";
|
||||
for (let rest = index + 1; rest > 0; rest = Math.floor((rest - 1) / 26)) {
|
||||
letters = String.fromCharCode(65 + ((rest - 1) % 26)) + letters;
|
||||
}
|
||||
return letters;
|
||||
}
|
||||
|
||||
interface A1Part { column?: number; row?: number }
|
||||
|
||||
function a1Part(text: string): A1Part | null {
|
||||
const match = A1_PART.exec(text);
|
||||
if (!match || text.length === 0) return null;
|
||||
return {
|
||||
column: match[2] ? columnNumber(match[2]) : undefined,
|
||||
row: match[4] ? Number(match[4]) : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function inBounds(part: A1Part): boolean {
|
||||
return (part.column ?? 1) <= MAX_COLUMN && (part.row ?? 1) <= MAX_ROW;
|
||||
}
|
||||
|
||||
export function isCellReference(text: string): boolean {
|
||||
const r1c1 = R1C1.exec(text);
|
||||
if (r1c1) return [r1c1[1], r1c1[3]].every((row) => row === undefined || Number(row) <= MAX_ROW)
|
||||
&& [r1c1[2], r1c1[4]].every((column) => column === undefined || Number(column) <= MAX_COLUMN);
|
||||
const pieces = text.split(":");
|
||||
if (pieces.length > 2) return false;
|
||||
const parts = pieces.map(a1Part);
|
||||
if (parts.some((part) => part === null || !inBounds(part))) return false;
|
||||
const [start, end] = parts as A1Part[];
|
||||
if (!end) return start!.column !== undefined && start!.row !== undefined;
|
||||
const bothColumns = start!.column !== undefined && end.column !== undefined;
|
||||
const bothRows = start!.row !== undefined && end.row !== undefined;
|
||||
return bothColumns || bothRows;
|
||||
}
|
||||
|
||||
function checkCells(cells: string, sheet: string | undefined): RangeCheck {
|
||||
if (!isCellReference(cells)) {
|
||||
return { ok: false, message: `"${cells}" is not a cell range. Use A1 notation (A1, A1:C10, A:C, 2:5, A2:C) or R1C1 notation (R1C1:R10C3).` };
|
||||
}
|
||||
return { ok: true, range: { sheet, cells } };
|
||||
}
|
||||
|
||||
export function checkSheetRange(text: string): RangeCheck {
|
||||
if (text.length === 0) return { ok: false, message: "The range is empty." };
|
||||
if (text.length > MAX_RANGE_LENGTH) return { ok: false, message: `The range is longer than ${MAX_RANGE_LENGTH} characters.` };
|
||||
if (/[\u0000-\u001f\u007f]/.test(text)) return { ok: false, message: "The range contains a line break or control character." };
|
||||
if (text !== text.trim()) return { ok: false, message: "The range starts or ends with a space." };
|
||||
|
||||
if (text.startsWith("'")) {
|
||||
let name = "";
|
||||
let index = 1;
|
||||
for (; index < text.length; index += 1) {
|
||||
if (text[index] !== "'") {
|
||||
name += text[index];
|
||||
continue;
|
||||
}
|
||||
if (text[index + 1] === "'") {
|
||||
name += "'";
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (index >= text.length) return { ok: false, message: `The quoted sheet name is not closed. ${QUOTING_HINT}` };
|
||||
if (name.length === 0) return { ok: false, message: "The sheet name is empty." };
|
||||
const rest = text.slice(index + 1);
|
||||
if (rest.length === 0) return { ok: true, range: { sheet: name } };
|
||||
if (!rest.startsWith("!") || rest.length === 1) return { ok: false, message: `Expected ! and a cell range after the quoted sheet name. ${QUOTING_HINT}` };
|
||||
return checkCells(rest.slice(1), name);
|
||||
}
|
||||
|
||||
const bang = text.indexOf("!");
|
||||
if (bang === -1) {
|
||||
if (isCellReference(text)) return { ok: true, range: { cells: text } };
|
||||
if (UNQUOTED_NAME.test(text)) return { ok: true, range: { sheet: text } };
|
||||
return { ok: false, message: `"${text}" is neither a cell range nor a plain sheet name. ${QUOTING_HINT}` };
|
||||
}
|
||||
const sheet = text.slice(0, bang);
|
||||
if (sheet.length === 0) return { ok: false, message: "The sheet name before ! is empty." };
|
||||
if (!UNQUOTED_NAME.test(sheet)) return { ok: false, message: `The sheet name ${sheet} must be quoted. ${QUOTING_HINT}` };
|
||||
const cells = text.slice(bang + 1);
|
||||
if (cells.length === 0) return { ok: false, message: "Expected a cell range after !." };
|
||||
return checkCells(cells, sheet);
|
||||
}
|
||||
|
||||
export function quoteSheetName(name: string): string {
|
||||
if (UNQUOTED_NAME.test(name) && !isCellReference(name) && !/^\d+$/.test(name)) return name;
|
||||
return `'${name.replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
export function formatSheetRange(range: SheetRange): string {
|
||||
if (range.sheet === undefined) return range.cells ?? "";
|
||||
return range.cells === undefined ? quoteSheetName(range.sheet) : `${quoteSheetName(range.sheet)}!${range.cells}`;
|
||||
}
|
||||
|
||||
export interface GridRange {
|
||||
sheetId?: number;
|
||||
startRowIndex?: number;
|
||||
endRowIndex?: number;
|
||||
startColumnIndex?: number;
|
||||
endColumnIndex?: number;
|
||||
}
|
||||
|
||||
export interface DimensionRange {
|
||||
sheetId?: number;
|
||||
dimension?: string;
|
||||
startIndex?: number;
|
||||
endIndex?: number;
|
||||
}
|
||||
|
||||
function span(start: number | undefined, end: number | undefined, label: (index: number) => string, plural: string): string {
|
||||
if (start === undefined && end === undefined) return `all ${plural}`;
|
||||
const first = label(start ?? 0);
|
||||
if (end === undefined) return `${plural} ${first} onward`;
|
||||
const last = label(end - 1);
|
||||
return first === last ? `${plural.replace(/s$/, "")} ${first}` : `${plural} ${first}–${last}`;
|
||||
}
|
||||
|
||||
const rowLabel = (index: number) => String(index + 1);
|
||||
|
||||
export function describeGridRange(range: GridRange): string {
|
||||
return [
|
||||
`sheet ID ${range.sheetId ?? 0}`,
|
||||
span(range.startRowIndex, range.endRowIndex, rowLabel, "rows"),
|
||||
span(range.startColumnIndex, range.endColumnIndex, columnLetters, "columns"),
|
||||
].join(", ");
|
||||
}
|
||||
|
||||
export function describeDimensionRange(range: DimensionRange): string {
|
||||
const columns = range.dimension === "COLUMNS";
|
||||
return `sheet ID ${range.sheetId ?? 0}, ${span(range.startIndex, range.endIndex, columns ? columnLetters : rowLabel, columns ? "columns" : "rows")}`;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { GoogleToolError } from "../errors.js";
|
||||
import type { GoogleHttp, GoogleRequest } from "../google-http.js";
|
||||
import { boundedStructuredResult } from "../tool.js";
|
||||
import { checkSheetRange } from "./range.js";
|
||||
|
||||
export const SHEETS_HOST = "sheets.googleapis.com" as const;
|
||||
export const SHEETS_BASE = "/v4/spreadsheets";
|
||||
export const MAX_CELLS_PER_CALL = 50_000;
|
||||
export const MAX_RESULT_BYTES = 250_000;
|
||||
export const MAX_REQUEST_CHARS = 1_000_000;
|
||||
|
||||
const formatCount = (value: number) => value.toLocaleString("en-US");
|
||||
|
||||
export const spreadsheetId = z.string().regex(/^[A-Za-z0-9_-]{1,200}$/, "must be a spreadsheet ID (letters, digits, - and _), as in the spreadsheet's URL after /d/");
|
||||
|
||||
export const sheetRange = z.string().superRefine((value, context) => {
|
||||
const check = checkSheetRange(value);
|
||||
if (!check.ok) context.addIssue({ code: "custom", message: check.message });
|
||||
});
|
||||
|
||||
export const cellValue = z.union([z.string(), z.number().finite(), z.boolean(), z.null()]);
|
||||
export const cellGrid = z.array(z.array(cellValue)).min(1, "must contain at least one row");
|
||||
|
||||
export function spreadsheetPath(id: string): string {
|
||||
return `${SHEETS_BASE}/${id}`;
|
||||
}
|
||||
|
||||
export function batchUpdatePath(id: string): string {
|
||||
return `${SHEETS_BASE}/${id}:batchUpdate`;
|
||||
}
|
||||
|
||||
export function valuesPath(id: string, range: string): string {
|
||||
return `${SHEETS_BASE}/${id}/values/${encodeURIComponent(range)}`;
|
||||
}
|
||||
|
||||
export function countCells(rows: readonly (readonly unknown[] | undefined)[] | undefined): number {
|
||||
return (rows ?? []).reduce((total, row) => total + (row?.length ?? 0), 0);
|
||||
}
|
||||
|
||||
export function assertWriteWithinBounds(cells: number, body: unknown): void {
|
||||
if (cells > MAX_CELLS_PER_CALL) {
|
||||
throw new GoogleToolError("invalid_argument", `This call would write ${formatCount(cells)} cells; the limit is ${formatCount(MAX_CELLS_PER_CALL)} per call. Split it into smaller ranges. Nothing was written.`);
|
||||
}
|
||||
const size = JSON.stringify(body).length;
|
||||
if (size > MAX_REQUEST_CHARS) {
|
||||
throw new GoogleToolError("invalid_argument", `This call would send ${formatCount(size)} characters; the limit is ${formatCount(MAX_REQUEST_CHARS)} per call. Split it into smaller writes. Nothing was written.`);
|
||||
}
|
||||
}
|
||||
|
||||
export function boundedReadResult(value: Record<string, unknown>, cells: number, narrow: string): CallToolResult {
|
||||
if (cells > MAX_CELLS_PER_CALL) {
|
||||
throw new GoogleToolError("incomplete", `The result has ${formatCount(cells)} cells; the limit is ${formatCount(MAX_CELLS_PER_CALL)} per call. ${narrow}`);
|
||||
}
|
||||
return boundedStructuredResult(value, MAX_RESULT_BYTES, (bytes) => `The result is ${formatCount(bytes)} bytes; the limit is ${formatCount(MAX_RESULT_BYTES)} per call. ${narrow}`);
|
||||
}
|
||||
|
||||
export async function sendRead<T>(http: GoogleHttp, request: GoogleRequest, narrow: string): Promise<T> {
|
||||
try {
|
||||
return await http.send<T>(request);
|
||||
} catch (error) {
|
||||
if (error instanceof GoogleToolError && error.kind === "invalid_response" && /too large/.test(error.message)) {
|
||||
throw new GoogleToolError("incomplete", `Google's response is too large to return. ${narrow}`, error.httpStatus);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export const contentOutputSchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
content: { type: "object", description: "Google's Sheets API response, as JSON." },
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const writeOutputSchema = {
|
||||
type: "object",
|
||||
properties: {
|
||||
content: {
|
||||
type: "object",
|
||||
description: "Google's Sheets API response, as JSON, plus status: a sentence saying exactly what changed.",
|
||||
properties: { status: { type: "string", description: "What changed: which ranges and how many cells." } },
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const spreadsheetIdInput = { type: "string", description: "Required. The ID of the spreadsheet, the part of its URL after /d/." } as const;
|
||||
|
||||
export const RANGE_RULES = "A1 notation (Sheet1!A1:C10, Sheet1!A:C, Sheet1!2:5) or R1C1 notation (Sheet1!R1C1:R10C3). Without a sheet name the first sheet is used. Put a sheet name with spaces or punctuation in single quotes and double any apostrophe: 'Q1 Plan'!A1:B2, 'Bob''s list'!A:A.";
|
||||
|
||||
export interface UpdateValuesResponse {
|
||||
spreadsheetId?: string;
|
||||
updatedRange?: string;
|
||||
updatedRows?: number;
|
||||
updatedColumns?: number;
|
||||
updatedCells?: number;
|
||||
}
|
||||
|
||||
export function valuesWriteStatus(response: UpdateValuesResponse, requestedRange: string, how: string): string {
|
||||
const cells = response.updatedCells ?? 0;
|
||||
if (cells === 0) return `No cells changed in ${response.updatedRange ?? requestedRange}.`;
|
||||
const rows = response.updatedRows ?? 0;
|
||||
const columns = response.updatedColumns ?? 0;
|
||||
return `Updated ${formatCount(cells)} ${cells === 1 ? "cell" : "cells"} in ${response.updatedRange ?? requestedRange} (${rows} ${rows === 1 ? "row" : "rows"} × ${columns} ${columns === 1 ? "column" : "columns"}) ${how}.`;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
import { defineTool } from "../tool.js";
|
||||
import { cellGrid, RANGE_RULES, sheetRange, spreadsheetId, spreadsheetIdInput, writeOutputSchema } from "./spreadsheet.js";
|
||||
import { runValuesUpdate } from "./values-write.js";
|
||||
|
||||
const args = z.object({ spreadsheetId, range: sheetRange, formulas: cellGrid });
|
||||
export type UpdateFormulasArgs = z.infer<typeof args>;
|
||||
|
||||
export const updateFormulas = defineTool({
|
||||
definition: {
|
||||
name: "update_formulas",
|
||||
description: "Writes formulas into one range of a spreadsheet. Each item is entered as if typed into Google Sheets (Sheets valueInputOption USER_ENTERED): a string starting with = becomes a formula, such as \"=SUM(A1:A3)\" or \"=VLOOKUP(B2,Prices!A:B,2,FALSE)\"; other text may be turned into a number or date by the spreadsheet's locale. Use update_values to store text exactly as given. null leaves a cell unchanged; an empty string clears it. Writes at most 50,000 cells per call. The result's status says which range changed and how many cells. A failed write is never retried automatically.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
spreadsheetId: spreadsheetIdInput,
|
||||
range: { type: "string", description: `Required. The range to write, in ${RANGE_RULES} Formulas fill it from the top-left cell.` },
|
||||
formulas: {
|
||||
type: "array",
|
||||
items: { type: "array", items: {} },
|
||||
description: "Required. The formulas, one array per row, one item per cell, for example [[\"=A1+B1\"], [\"=A2+B2\"]]. Items may also be numbers, booleans or null. null skips the cell; an empty string clears it.",
|
||||
},
|
||||
},
|
||||
required: ["spreadsheetId", "range", "formulas"],
|
||||
},
|
||||
outputSchema: writeOutputSchema,
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
return runValuesUpdate(http, input.spreadsheetId, input.range, input.formulas, "USER_ENTERED");
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { BATCH_UPDATE_RESPONSE, SPREADSHEET_ID } from "./fixtures/sheets-rest.js";
|
||||
import {
|
||||
COMMENT_REQUESTS,
|
||||
DATA_SOURCE_REQUESTS,
|
||||
describeRequest,
|
||||
REQUEST_TARGETS,
|
||||
SUPPORTED_REQUESTS,
|
||||
updateSpreadsheet,
|
||||
updateSpreadsheetRequest,
|
||||
updateSpreadsheetStatus,
|
||||
} from "./update-spreadsheet.js";
|
||||
|
||||
const text = (result: { content: unknown[] }) => (result.content[0] as { text: string }).text;
|
||||
const grid = { sheetId: 0, startRowIndex: 0, endRowIndex: 2, startColumnIndex: 0, endColumnIndex: 3 };
|
||||
const cellRow = (count: number) => ({ values: Array.from({ length: count }, () => ({ userEnteredValue: { numberValue: 1 } })) });
|
||||
|
||||
describe("update_spreadsheet operations", () => {
|
||||
it("supports exactly the operations Google's reference lists, less comments and data sources", () => {
|
||||
expect(SUPPORTED_REQUESTS).toHaveLength(64);
|
||||
for (const kind of [...COMMENT_REQUESTS, ...DATA_SOURCE_REQUESTS]) expect(SUPPORTED_REQUESTS).not.toContain(kind);
|
||||
});
|
||||
|
||||
it.each(SUPPORTED_REQUESTS.map((kind) => [kind]))("accepts %s", (kind) => {
|
||||
expect(() => updateSpreadsheetRequest({ spreadsheetId: SPREADSHEET_ID, requests: [{ [kind]: {} }] })).not.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[[{ insertComment: {} }], /insertComment is not available here; comments/],
|
||||
[[{ updateCells: {} }, { deleteCommentReply: {} }], /Request 2: deleteCommentReply is not available/],
|
||||
[[{ addDataSource: {} }], /data sources need BigQuery access/],
|
||||
[[{ refreshDataSource: {} }], /data sources/],
|
||||
[[{ deleteSpreadsheet: {} }], /deleteSpreadsheet is not a supported operation/],
|
||||
[[{ updateDriveSharing: {} }], /not a supported operation/],
|
||||
[[{ mergeCells: {}, unmergeCells: {} }], /exactly one operation.* it has 2/],
|
||||
[[{}], /exactly one operation/],
|
||||
[[{ mergeCells: "A1:B2" }], /mergeCells must be an object/],
|
||||
[[{ mergeCells: [] }], /must be an object/],
|
||||
])("refuses %j", (requests, message) => {
|
||||
expect(() => updateSpreadsheetRequest({ spreadsheetId: SPREADSHEET_ID, requests })).toThrow(message);
|
||||
});
|
||||
|
||||
it("refuses writeControl, which the Sheets API cannot honor", () => {
|
||||
expect(() => updateSpreadsheetRequest({ spreadsheetId: SPREADSHEET_ID, requests: [{ addSheet: {} }], writeControl: { requiredRevisionId: "r1" } }))
|
||||
.toThrow(/writeControl is not available/);
|
||||
});
|
||||
|
||||
it("bounds the cells updateCells and appendCells write", () => {
|
||||
const requests = [
|
||||
{ updateCells: { start: { sheetId: 0, rowIndex: 0, columnIndex: 0 }, rows: Array.from({ length: 500 }, () => cellRow(50)), fields: "userEnteredValue" } },
|
||||
{ appendCells: { sheetId: 0, rows: Array.from({ length: 501 }, () => cellRow(50)), fields: "userEnteredValue" } },
|
||||
];
|
||||
expect(() => updateSpreadsheetRequest({ spreadsheetId: SPREADSHEET_ID, requests })).toThrow(/50,050 cells; the limit is 50,000/);
|
||||
});
|
||||
|
||||
it("sends the requests unchanged in one batchUpdate", () => {
|
||||
const requests = [{ mergeCells: { range: grid, mergeType: "MERGE_ALL" } }, { addSheet: { properties: { title: "Notes" } } }];
|
||||
expect(updateSpreadsheetRequest({ spreadsheetId: SPREADSHEET_ID, requests })).toEqual({
|
||||
method: "POST", host: "sheets.googleapis.com", path: `/v4/spreadsheets/${SPREADSHEET_ID}:batchUpdate`, body: { requests },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_spreadsheet status", () => {
|
||||
it.each([
|
||||
[{ updateCells: { range: grid, rows: [cellRow(3), cellRow(3)], fields: "userEnteredValue" } }, "1. updateCells on sheet ID 0, rows 1–2, columns A–C (6 cells written)"],
|
||||
[{ updateCells: { start: { sheetId: 3, rowIndex: 4, columnIndex: 1 }, rows: [cellRow(1)], fields: "*" } }, "1. updateCells on sheet ID 3, rows 5 onward, columns B onward (1 cell written)"],
|
||||
[{ appendCells: { sheetId: 2, rows: [cellRow(2)], fields: "userEnteredValue" } }, "1. appendCells on sheet ID 2 (2 cells written)"],
|
||||
[{ deleteDimension: { range: { sheetId: 0, dimension: "COLUMNS", startIndex: 1, endIndex: 3 } } }, "1. deleteDimension on sheet ID 0, columns B–C"],
|
||||
[{ deleteSheet: { sheetId: 9 } }, "1. deleteSheet on sheet ID 9"],
|
||||
[{ duplicateSheet: { sourceSheetId: 4, newSheetName: "Copy" } }, "1. duplicateSheet on sheet ID 4"],
|
||||
[{ updateSheetProperties: { properties: { sheetId: 5, title: "Renamed" }, fields: "title" } }, "1. updateSheetProperties on sheet ID 5"],
|
||||
[{ copyPaste: { source: grid, destination: { ...grid, sheetId: 1 } } }, "1. copyPaste on sheet ID 0, rows 1–2, columns A–C to sheet ID 1, rows 1–2, columns A–C"],
|
||||
[{ cutPaste: { source: grid, destination: { sheetId: 0, rowIndex: 9, columnIndex: 3 } } }, "1. cutPaste on sheet ID 0, rows 1–2, columns A–C to sheet ID 0, rows 10 onward, columns D onward"],
|
||||
[{ moveDimension: { source: { sheetId: 0, dimension: "ROWS", startIndex: 1, endIndex: 2 }, destinationIndex: 7 } }, "1. moveDimension on sheet ID 0, row 2 to 0-based index 7"],
|
||||
[{ pasteData: { coordinate: { sheetId: 0, rowIndex: 0, columnIndex: 0 }, data: "a,b", delimiter: "," } }, "1. pasteData on sheet ID 0, rows 1 onward, columns A onward"],
|
||||
[{ autoResizeDimensions: { dimensions: { sheetId: 0, dimension: "ROWS", startIndex: 0, endIndex: 10 } } }, "1. autoResizeDimensions on sheet ID 0, rows 1–10"],
|
||||
])("%j", (request, description) => {
|
||||
expect(describeRequest(request, 0)).toBe(description);
|
||||
});
|
||||
|
||||
it("has a target entry for every supported request type, and none for anything else", () => {
|
||||
expect(Object.keys(REQUEST_TARGETS).sort()).toEqual([...SUPPORTED_REQUESTS].sort());
|
||||
for (const kind of SUPPORTED_REQUESTS) expect(REQUEST_TARGETS[kind].length, kind).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ addNamedRange: { namedRange: { name: "Totals", range: grid } } }, "1. addNamedRange on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ updateNamedRange: { namedRange: { namedRangeId: "nr1", range: grid }, fields: "range" } }, "1. updateNamedRange on namedRangeId nr1 and sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ deleteNamedRange: { namedRangeId: "nr1" } }, "1. deleteNamedRange on namedRangeId nr1"],
|
||||
[{ addProtectedRange: { protectedRange: { range: grid, description: "Locked" } } }, "1. addProtectedRange on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ updateProtectedRange: { protectedRange: { protectedRangeId: 4, warningOnly: true }, fields: "warningOnly" } }, "1. updateProtectedRange on protectedRangeId 4"],
|
||||
[{ addConditionalFormatRule: { rule: { ranges: [grid, { ...grid, sheetId: 2 }] }, index: 0 } }, "1. addConditionalFormatRule on sheet ID 0, rows 1–2, columns A–C and sheet ID 2, rows 1–2, columns A–C"],
|
||||
[{ deleteConditionalFormatRule: { sheetId: 1, index: 3 } }, "1. deleteConditionalFormatRule on sheet ID 1 and rule index 3"],
|
||||
[{ findReplace: { find: "a", replacement: "b", allSheets: true } }, "1. findReplace on all sheets"],
|
||||
[{ findReplace: { find: "a", replacement: "b", sheetId: 6 } }, "1. findReplace on sheet ID 6"],
|
||||
[{ addFilterView: { filter: { title: "Open", range: grid } } }, "1. addFilterView on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ setBasicFilter: { filter: { range: grid } } }, "1. setBasicFilter on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ addBanding: { bandedRange: { range: grid } } }, "1. addBanding on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ updateDimensionGroup: { dimensionGroup: { range: { sheetId: 0, dimension: "ROWS", startIndex: 0, endIndex: 4 } }, fields: "collapsed" } }, "1. updateDimensionGroup on sheet ID 0, rows 1–4"],
|
||||
[{ addChart: { chart: { position: { overlayPosition: { anchorCell: { sheetId: 3, rowIndex: 1, columnIndex: 1 } } } } } }, "1. addChart on sheet ID 3, rows 2 onward, columns B onward"],
|
||||
[{ addTable: { table: { name: "T", range: grid } } }, "1. addTable on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ deleteTable: { tableId: "t1" } }, "1. deleteTable on tableId t1"],
|
||||
[{ autoFill: { sourceAndDestination: { source: grid, dimension: "ROWS", fillLength: 3 } } }, "1. autoFill on sheet ID 0, rows 1–2, columns A–C"],
|
||||
[{ createDeveloperMetadata: { developerMetadata: { metadataKey: "k", location: { sheetId: 2 } } } }, "1. createDeveloperMetadata on sheet ID 2"],
|
||||
[{ createDeveloperMetadata: { developerMetadata: { metadataKey: "k", location: { spreadsheet: true } } } }, "1. createDeveloperMetadata on the spreadsheet"],
|
||||
[{ deleteDeveloperMetadata: { dataFilter: {} } }, "1. deleteDeveloperMetadata on matching developer metadata"],
|
||||
[{ updateSpreadsheetProperties: { properties: { title: "Budget" }, fields: "title" } }, "1. updateSpreadsheetProperties on the spreadsheet's properties"],
|
||||
[{ addSheet: { properties: { title: "Notes" } } }, "1. addSheet on title Notes"],
|
||||
[{ appendDimension: { sheetId: 0, dimension: "ROWS", length: 5 } }, "1. appendDimension on sheet ID 0"],
|
||||
])("names the nested range of %j", (request, description) => {
|
||||
expect(describeRequest(request, 0)).toBe(description);
|
||||
});
|
||||
|
||||
it("lists every request", () => {
|
||||
expect(updateSpreadsheetStatus([{ deleteSheet: { sheetId: 9 } }, { addSheet: { properties: { title: "New" } } }]))
|
||||
.toBe("Applied 2 requests: 1. deleteSheet on sheet ID 9; 2. addSheet on title New.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_spreadsheet tool", () => {
|
||||
it("applies the requests once and returns Google's answer with the status", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(BATCH_UPDATE_RESPONSE));
|
||||
const requests = [{ repeatCell: { range: grid, cell: { userEnteredFormat: { textFormat: { bold: true } } }, fields: "userEnteredFormat.textFormat.bold" } }];
|
||||
const result = await updateSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID, requests }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.body).toEqual({ requests });
|
||||
expect(result.structuredContent).toEqual({ content: { ...BATCH_UPDATE_RESPONSE, status: "Applied 1 request: 1. repeatCell on sheet ID 0, rows 1–2, columns A–C." } });
|
||||
});
|
||||
|
||||
it("never retries and warns the update may have happened", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({ error: { code: 502 } }, 502));
|
||||
const result = await updateSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID, requests: [{ addSheet: {} }] }, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 }));
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(text(result)).toMatch(/may or may not have been made/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ requests: [] }, /requests/],
|
||||
[{ requests: [{ insertComment: {} }] }, /comments/],
|
||||
[{ requests: [{ addSheet: {} }], writeControl: {} }, /writeControl/],
|
||||
[{ requests: Array.from({ length: 501 }, () => ({ addSheet: {} })) }, /requests/],
|
||||
])("refuses %j without sending", async (args, message) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({}));
|
||||
const result = await updateSpreadsheet.call({ spreadsheetId: SPREADSHEET_ID, ...args }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(message);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,239 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { z } from "zod";
|
||||
import { GoogleToolError } from "../errors.js";
|
||||
import type { GoogleRequest } from "../google-http.js";
|
||||
import { defineTool, structuredResult } from "../tool.js";
|
||||
import type { BatchUpdateResponse } from "./insert-dimension.js";
|
||||
import { describeDimensionRange, describeGridRange, type DimensionRange, type GridRange } from "./range.js";
|
||||
import { assertWriteWithinBounds, batchUpdatePath, SHEETS_HOST, spreadsheetId, spreadsheetIdInput, writeOutputSchema } from "./spreadsheet.js";
|
||||
|
||||
export const MAX_REQUESTS = 500;
|
||||
|
||||
export const SUPPORTED_REQUESTS = [
|
||||
"updateSpreadsheetProperties", "updateSheetProperties", "updateDimensionProperties", "updateNamedRange", "repeatCell",
|
||||
"addNamedRange", "deleteNamedRange", "addSheet", "deleteSheet", "autoFill", "cutPaste", "copyPaste", "mergeCells",
|
||||
"unmergeCells", "updateBorders", "updateCells", "addFilterView", "appendCells", "clearBasicFilter", "deleteDimension",
|
||||
"deleteEmbeddedObject", "deleteFilterView", "duplicateFilterView", "duplicateSheet", "findReplace", "insertDimension",
|
||||
"insertRange", "moveDimension", "updateEmbeddedObjectPosition", "pasteData", "textToColumns", "updateFilterView",
|
||||
"deleteRange", "appendDimension", "addConditionalFormatRule", "updateConditionalFormatRule", "deleteConditionalFormatRule",
|
||||
"sortRange", "setDataValidation", "setBasicFilter", "addProtectedRange", "updateProtectedRange", "deleteProtectedRange",
|
||||
"autoResizeDimensions", "addChart", "updateChartSpec", "updateBanding", "addBanding", "deleteBanding",
|
||||
"createDeveloperMetadata", "updateDeveloperMetadata", "deleteDeveloperMetadata", "randomizeRange", "addDimensionGroup",
|
||||
"deleteDimensionGroup", "updateDimensionGroup", "trimWhitespace", "deleteDuplicates", "updateEmbeddedObjectBorder",
|
||||
"addSlicer", "updateSlicerSpec", "addTable", "updateTable", "deleteTable",
|
||||
] as const;
|
||||
|
||||
export const COMMENT_REQUESTS = ["insertComment", "addCommentReply", "updateCommentPost", "deleteComment", "deleteCommentReply"] as const;
|
||||
export const DATA_SOURCE_REQUESTS = ["addDataSource", "updateDataSource", "deleteDataSource", "refreshDataSource", "cancelDataSourceRefresh"] as const;
|
||||
|
||||
export const REMOVING_REQUESTS = new Set([
|
||||
"deleteSheet", "deleteDimension", "deleteRange", "deleteNamedRange", "deleteEmbeddedObject", "deleteFilterView",
|
||||
"deleteConditionalFormatRule", "deleteProtectedRange", "deleteBanding", "deleteDeveloperMetadata", "deleteDimensionGroup",
|
||||
"deleteDuplicates", "deleteTable", "clearBasicFilter",
|
||||
]);
|
||||
|
||||
const supported = new Set<string>(SUPPORTED_REQUESTS);
|
||||
const comments = new Set<string>(COMMENT_REQUESTS);
|
||||
const dataSources = new Set<string>(DATA_SOURCE_REQUESTS);
|
||||
|
||||
const args = z.object({
|
||||
spreadsheetId,
|
||||
requests: z.array(z.record(z.string(), z.unknown())).min(1).max(MAX_REQUESTS),
|
||||
writeControl: z.object({ requiredRevisionId: z.string().optional() }).optional(),
|
||||
});
|
||||
export type UpdateSpreadsheetArgs = z.infer<typeof args>;
|
||||
|
||||
type SheetsRequest = Record<string, unknown>;
|
||||
|
||||
export function requestKind(request: SheetsRequest, position: number): string {
|
||||
const keys = Object.keys(request);
|
||||
const label = `Request ${position + 1}`;
|
||||
if (keys.length !== 1) throw new GoogleToolError("invalid_argument", `${label} must have exactly one operation, such as updateCells or addSheet; it has ${keys.length}. Nothing was changed.`);
|
||||
const kind = keys[0]!;
|
||||
const body = request[kind];
|
||||
if (comments.has(kind)) throw new GoogleToolError("unsupported", `${label}: ${kind} is not available here; comments cannot be changed through this tool. Nothing was changed.`);
|
||||
if (dataSources.has(kind)) throw new GoogleToolError("unsupported", `${label}: ${kind} is not available here; data sources need BigQuery access that this connection does not have. Nothing was changed.`);
|
||||
if (!supported.has(kind)) throw new GoogleToolError("invalid_argument", `${label}: ${kind} is not a supported operation. Nothing was changed.`);
|
||||
if (!body || typeof body !== "object" || Array.isArray(body)) throw new GoogleToolError("invalid_argument", `${label}: ${kind} must be an object. Nothing was changed.`);
|
||||
return kind;
|
||||
}
|
||||
|
||||
interface RowData { values?: unknown[] }
|
||||
|
||||
export function writtenCells(kind: string, body: Record<string, unknown>): number {
|
||||
if (kind !== "updateCells" && kind !== "appendCells") return 0;
|
||||
const rows = Array.isArray(body.rows) ? (body.rows as RowData[]) : [];
|
||||
return rows.reduce((total, row) => total + (Array.isArray(row?.values) ? row.values.length : 0), 0);
|
||||
}
|
||||
|
||||
const isObject = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
|
||||
function describeArea(value: Record<string, unknown>): string {
|
||||
if ("dimension" in value) return describeDimensionRange(value as DimensionRange);
|
||||
if ("rowIndex" in value || "columnIndex" in value) {
|
||||
const coordinate = value as { sheetId?: number; rowIndex?: number; columnIndex?: number };
|
||||
return describeGridRange({ sheetId: coordinate.sheetId, startRowIndex: coordinate.rowIndex ?? 0, startColumnIndex: coordinate.columnIndex ?? 0 });
|
||||
}
|
||||
return describeGridRange(value as GridRange);
|
||||
}
|
||||
|
||||
type SupportedRequest = (typeof SUPPORTED_REQUESTS)[number];
|
||||
|
||||
export const REQUEST_TARGETS: Readonly<Record<SupportedRequest, readonly string[]>> = {
|
||||
updateSpreadsheetProperties: ["=the spreadsheet's properties"],
|
||||
updateSheetProperties: ["properties.sheetId"],
|
||||
updateDimensionProperties: ["range", "dataSourceSheetRange"],
|
||||
updateNamedRange: ["namedRange.namedRangeId", "namedRange.range"],
|
||||
repeatCell: ["range"],
|
||||
addNamedRange: ["namedRange.range"],
|
||||
deleteNamedRange: ["namedRangeId"],
|
||||
addSheet: ["properties.title", "properties.sheetId"],
|
||||
deleteSheet: ["sheetId"],
|
||||
autoFill: ["range", "sourceAndDestination.source"],
|
||||
cutPaste: ["source", "destination"],
|
||||
copyPaste: ["source", "destination"],
|
||||
mergeCells: ["range"],
|
||||
unmergeCells: ["range"],
|
||||
updateBorders: ["range"],
|
||||
updateCells: ["range", "start"],
|
||||
addFilterView: ["filter.range"],
|
||||
appendCells: ["sheetId", "tableId"],
|
||||
clearBasicFilter: ["sheetId"],
|
||||
deleteDimension: ["range"],
|
||||
deleteEmbeddedObject: ["objectId"],
|
||||
deleteFilterView: ["filterId"],
|
||||
duplicateFilterView: ["filterId"],
|
||||
duplicateSheet: ["sourceSheetId"],
|
||||
findReplace: ["range", "sheetId", "allSheets"],
|
||||
insertDimension: ["range"],
|
||||
insertRange: ["range"],
|
||||
moveDimension: ["source", "destinationIndex"],
|
||||
updateEmbeddedObjectPosition: ["objectId", "newPosition.overlayPosition.anchorCell", "newPosition.sheetId"],
|
||||
pasteData: ["coordinate"],
|
||||
textToColumns: ["source"],
|
||||
updateFilterView: ["filter.filterViewId", "filter.range"],
|
||||
deleteRange: ["range"],
|
||||
appendDimension: ["sheetId"],
|
||||
addConditionalFormatRule: ["rule.ranges"],
|
||||
updateConditionalFormatRule: ["sheetId", "index", "rule.ranges"],
|
||||
deleteConditionalFormatRule: ["sheetId", "index"],
|
||||
sortRange: ["range"],
|
||||
setDataValidation: ["range"],
|
||||
setBasicFilter: ["filter.range", "filter.tableId"],
|
||||
addProtectedRange: ["protectedRange.range", "protectedRange.namedRangeId", "protectedRange.tableId"],
|
||||
updateProtectedRange: ["protectedRange.protectedRangeId", "protectedRange.range"],
|
||||
deleteProtectedRange: ["protectedRangeId"],
|
||||
autoResizeDimensions: ["dimensions", "dataSourceSheetDimensions"],
|
||||
addChart: ["chart.position.sheetId", "chart.position.overlayPosition.anchorCell"],
|
||||
updateChartSpec: ["chartId"],
|
||||
updateBanding: ["bandedRange.bandedRangeId", "bandedRange.range"],
|
||||
addBanding: ["bandedRange.range"],
|
||||
deleteBanding: ["bandedRangeId"],
|
||||
createDeveloperMetadata: ["developerMetadata.location.dimensionRange", "developerMetadata.location.sheetId", "developerMetadata.location.spreadsheet"],
|
||||
updateDeveloperMetadata: ["=matching developer metadata"],
|
||||
deleteDeveloperMetadata: ["=matching developer metadata"],
|
||||
randomizeRange: ["range"],
|
||||
addDimensionGroup: ["range"],
|
||||
deleteDimensionGroup: ["range"],
|
||||
updateDimensionGroup: ["dimensionGroup.range"],
|
||||
trimWhitespace: ["range"],
|
||||
deleteDuplicates: ["range"],
|
||||
updateEmbeddedObjectBorder: ["objectId"],
|
||||
addSlicer: ["slicer.spec.dataRange", "slicer.position.sheetId", "slicer.position.overlayPosition.anchorCell"],
|
||||
updateSlicerSpec: ["slicerId"],
|
||||
addTable: ["table.range"],
|
||||
updateTable: ["table.tableId", "table.range"],
|
||||
deleteTable: ["tableId"],
|
||||
};
|
||||
|
||||
const PAIRED = new Set<string>(["cutPaste", "copyPaste", "moveDimension"]);
|
||||
const NUMBER_LABELS: Record<string, string> = { sheetId: "sheet ID", sourceSheetId: "sheet ID", destinationIndex: "0-based index", index: "rule index" };
|
||||
const FLAG_LABELS: Record<string, string> = { allSheets: "all sheets", spreadsheet: "the spreadsheet" };
|
||||
|
||||
function valueAt(body: Record<string, unknown>, path: string): unknown {
|
||||
return path.split(".").reduce<unknown>((value, key) => (isObject(value) ? value[key] : undefined), body);
|
||||
}
|
||||
|
||||
function describeValue(key: string, value: unknown): string | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
const parts = value.filter(isObject).map(describeArea);
|
||||
return parts.length ? parts.join(" and ") : undefined;
|
||||
}
|
||||
if (isObject(value)) return describeArea(value);
|
||||
if (value === true) return FLAG_LABELS[key];
|
||||
if (typeof value === "number" || (typeof value === "string" && value.length > 0)) return `${NUMBER_LABELS[key] ?? key} ${value}`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function target(kind: string, body: Record<string, unknown>): string | undefined {
|
||||
const locators = REQUEST_TARGETS[kind as SupportedRequest] ?? [];
|
||||
const parts = locators.flatMap((locator) => {
|
||||
if (locator.startsWith("=")) return [locator.slice(1)];
|
||||
const description = describeValue(locator.split(".").pop()!, valueAt(body, locator));
|
||||
return description ? [description] : [];
|
||||
});
|
||||
if (parts.length === 0) return undefined;
|
||||
return parts.join(PAIRED.has(kind) ? " to " : " and ");
|
||||
}
|
||||
|
||||
export function describeRequest(request: SheetsRequest, position: number): string {
|
||||
const kind = Object.keys(request)[0]!;
|
||||
const body = request[kind] as Record<string, unknown>;
|
||||
const where = target(kind, body);
|
||||
const cells = writtenCells(kind, body);
|
||||
const written = cells > 0 ? ` (${cells.toLocaleString("en-US")} ${cells === 1 ? "cell" : "cells"} written)` : "";
|
||||
return `${position + 1}. ${kind}${where ? ` on ${where}` : ""}${written}`;
|
||||
}
|
||||
|
||||
export function updateSpreadsheetRequest(input: UpdateSpreadsheetArgs): GoogleRequest {
|
||||
if (input.writeControl !== undefined) {
|
||||
throw new GoogleToolError("unsupported", "writeControl is not available here: the Sheets API cannot make this change conditional on a revision. Call again without writeControl. Nothing was changed.");
|
||||
}
|
||||
let cells = 0;
|
||||
input.requests.forEach((request, position) => {
|
||||
const kind = requestKind(request, position);
|
||||
cells += writtenCells(kind, request[kind] as Record<string, unknown>);
|
||||
});
|
||||
const body = { requests: input.requests };
|
||||
assertWriteWithinBounds(cells, body);
|
||||
return { method: "POST", host: SHEETS_HOST, path: batchUpdatePath(input.spreadsheetId), body };
|
||||
}
|
||||
|
||||
export function updateSpreadsheetStatus(requests: readonly SheetsRequest[]): string {
|
||||
const count = requests.length;
|
||||
return `Applied ${count} ${count === 1 ? "request" : "requests"}: ${requests.map(describeRequest).join("; ")}.`;
|
||||
}
|
||||
|
||||
export function updateSpreadsheetResult(input: UpdateSpreadsheetArgs, response: BatchUpdateResponse): CallToolResult {
|
||||
return structuredResult({ content: { ...response, status: updateSpreadsheetStatus(input.requests) } });
|
||||
}
|
||||
|
||||
export const updateSpreadsheet = defineTool({
|
||||
definition: {
|
||||
name: "update_spreadsheet",
|
||||
description: "Applies one or more Sheets API batchUpdate requests to a spreadsheet, in order and all together: if any request is invalid, none is applied. Each request is an object with one operation, such as updateCells, repeatCell, mergeCells, addSheet, updateSheetProperties, addChart, sortRange or findReplace. Some operations remove content: deleteSheet, deleteDimension, deleteRange, deleteDuplicates and deleteTable delete sheets, rows, columns or cells, and cutPaste, findReplace, sortRange and pasteData overwrite cells. It never deletes the spreadsheet itself, changes who it is shared with, or creates a spreadsheet. Comment and data source operations are refused, and so is writeControl. updateCells and appendCells may write at most 50,000 cells per call. The result's status lists each operation and the range it changed. A failed update is never retried automatically.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
spreadsheetId: spreadsheetIdInput,
|
||||
requests: {
|
||||
type: "array",
|
||||
items: { type: "object", additionalProperties: { description: "Properties of the object." } },
|
||||
description: "Required. The updates, each a Sheets API Request object with exactly one operation (https://developers.google.com/workspace/sheets/api/reference/rest/v4/spreadsheets/request). Applied in order; if any is invalid, none is applied. Ranges use 0-based sheetId, row and column indexes, with end indexes exclusive.",
|
||||
},
|
||||
writeControl: {
|
||||
type: "object",
|
||||
properties: { requiredRevisionId: { type: "string", description: "Not supported here." } },
|
||||
description: "Optional. Not supported here: any value is refused.",
|
||||
},
|
||||
},
|
||||
required: ["spreadsheetId", "requests"],
|
||||
},
|
||||
outputSchema: writeOutputSchema,
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
return updateSpreadsheetResult(input, await http.send<BatchUpdateResponse>(updateSpreadsheetRequest(input)));
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { createGoogleHttp } from "../google-http.js";
|
||||
import { SPREADSHEET_ID, UPDATE_VALUES_RESPONSE } from "./fixtures/sheets-rest.js";
|
||||
import { MAX_CELLS_PER_CALL, valuesWriteStatus } from "./spreadsheet.js";
|
||||
import { updateFormulas } from "./update-formulas.js";
|
||||
import { updateValues } from "./update-values.js";
|
||||
import { valuesUpdateRequest } from "./values-write.js";
|
||||
|
||||
const text = (result: { content: unknown[] }) => (result.content[0] as { text: string }).text;
|
||||
|
||||
describe("values.update request", () => {
|
||||
it.each([
|
||||
["RAW", [["Item", 12.5, true, null, ""]]],
|
||||
["USER_ENTERED", [["=SUM(A1:A3)"], ["=VLOOKUP(B2,Prices!A:B,2,FALSE)"]]],
|
||||
] as const)("writes with valueInputOption %s, rows first", (option, values) => {
|
||||
expect(valuesUpdateRequest(SPREADSHEET_ID, "'Q1 Plan'!A1", values.map((row) => [...row]), option)).toEqual({
|
||||
method: "PUT",
|
||||
host: "sheets.googleapis.com",
|
||||
path: `/v4/spreadsheets/${SPREADSHEET_ID}/values/'Q1%20Plan'!A1`,
|
||||
query: { valueInputOption: option },
|
||||
body: { range: "'Q1 Plan'!A1", majorDimension: "ROWS", values },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses more cells than the limit before sending", () => {
|
||||
const values = Array.from({ length: 1_001 }, () => Array.from({ length: 50 }, () => 1));
|
||||
expect(() => valuesUpdateRequest(SPREADSHEET_ID, "Sheet1!A1", values, "RAW")).toThrow(/50,050 cells; the limit is 50,000 per call\. Split it .* Nothing was written\./);
|
||||
expect(() => valuesUpdateRequest(SPREADSHEET_ID, "Sheet1!A1", [Array.from({ length: MAX_CELLS_PER_CALL }, () => 1)], "RAW")).not.toThrow();
|
||||
});
|
||||
|
||||
it("refuses a request body over the size limit", () => {
|
||||
expect(() => valuesUpdateRequest(SPREADSHEET_ID, "Sheet1!A1", Array.from({ length: 30 }, () => ["x".repeat(40_000)]), "RAW")).toThrow(/characters; the limit is 1,000,000/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("values write status", () => {
|
||||
it.each([
|
||||
[UPDATE_VALUES_RESPONSE, "as raw values", "Updated 4 cells in 'Q1 Plan'!A1:B2 (2 rows × 2 columns) as raw values."],
|
||||
[{ updatedRange: "Sheet1!C1", updatedRows: 1, updatedColumns: 1, updatedCells: 1 }, "as if typed into Google Sheets", "Updated 1 cell in Sheet1!C1 (1 row × 1 column) as if typed into Google Sheets."],
|
||||
[{ spreadsheetId: SPREADSHEET_ID }, "as raw values", "No cells changed in Sheet1!A1:B2."],
|
||||
])("%j", (response, how, status) => {
|
||||
expect(valuesWriteStatus(response, "Sheet1!A1:B2", how)).toBe(status);
|
||||
});
|
||||
});
|
||||
|
||||
describe("update_values and update_formulas tools", () => {
|
||||
it.each([
|
||||
[updateValues, "values", "RAW", "as raw values"],
|
||||
[updateFormulas, "formulas", "USER_ENTERED", "as if typed into Google Sheets"],
|
||||
] as const)("%s writes once and reports what changed", async (tool, field, option, how) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(UPDATE_VALUES_RESPONSE));
|
||||
const result = await tool.call({ spreadsheetId: SPREADSHEET_ID, range: "'Q1 Plan'!A1:B2", [field]: [["=1+1", 2], [null, ""]] }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]!.url.searchParams.get("valueInputOption")).toBe(option);
|
||||
expect(calls[0]!.body).toEqual({ range: "'Q1 Plan'!A1:B2", majorDimension: "ROWS", values: [["=1+1", 2], [null, ""]] });
|
||||
expect(result.structuredContent).toEqual({ content: { ...UPDATE_VALUES_RESPONSE, status: `Updated 4 cells in 'Q1 Plan'!A1:B2 (2 rows × 2 columns) ${how}.` } });
|
||||
});
|
||||
|
||||
it.each([updateValues, updateFormulas])("$definition.name never retries a failed write and warns it may have happened", async (tool) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({ error: { code: 503 } }, 503));
|
||||
const field = tool === updateValues ? "values" : "formulas";
|
||||
const result = await tool.call({ spreadsheetId: SPREADSHEET_ID, range: "Sheet1!A1", [field]: [[1]] }, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 }));
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(text(result)).toMatch(/may or may not have been made/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ range: "Sheet1!A1", values: [] }, /at least one row/],
|
||||
[{ range: "Sheet1!A1", values: [[{ a: 1 }]] }, /values/],
|
||||
[{ range: "Sheet1!A1", values: [[[1]]] }, /values/],
|
||||
[{ range: "Sheet1!A1", values: [[Number.NaN]] }, /values/],
|
||||
[{ range: "Sheet1!A1", values: ["a"] }, /values/],
|
||||
[{ range: "My Sheet!A1", values: [["a"]] }, /must be quoted/],
|
||||
])("update_values refuses %j without sending", async (args, message) => {
|
||||
const { fetch, calls } = fakeGoogle(() => json({}));
|
||||
const result = await updateValues.call({ spreadsheetId: SPREADSHEET_ID, ...args }, createGoogleHttp({ accessToken: "t", fetch }));
|
||||
expect(result.isError).toBe(true);
|
||||
expect(text(result)).toMatch(message);
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("states the value input option in each description", () => {
|
||||
expect(updateValues.definition.description).toMatch(/valueInputOption RAW/);
|
||||
expect(updateFormulas.definition.description).toMatch(/valueInputOption USER_ENTERED/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
import { defineTool } from "../tool.js";
|
||||
import { cellGrid, RANGE_RULES, sheetRange, spreadsheetId, spreadsheetIdInput, writeOutputSchema } from "./spreadsheet.js";
|
||||
import { runValuesUpdate } from "./values-write.js";
|
||||
|
||||
const args = z.object({ spreadsheetId, range: sheetRange, values: cellGrid });
|
||||
export type UpdateValuesArgs = z.infer<typeof args>;
|
||||
|
||||
export const updateValues = defineTool({
|
||||
definition: {
|
||||
name: "update_values",
|
||||
description: "Writes values into one range of a spreadsheet as raw values (Sheets valueInputOption RAW): every string is stored exactly as given, so \"=SUM(A1:A3)\" stays text, and \"2026-01-05\", \"1,000\" or \"12%\" stay text rather than becoming a date or a number. Pass numbers and booleans as JSON numbers and booleans. To write formulas, use update_formulas. null leaves a cell unchanged; an empty string clears it. Writes at most 50,000 cells per call. The result's status says which range changed and how many cells. A failed write is never retried automatically.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
spreadsheetId: spreadsheetIdInput,
|
||||
range: { type: "string", description: `Required. The range to write, in ${RANGE_RULES} Values fill it from the top-left cell.` },
|
||||
values: {
|
||||
type: "array",
|
||||
items: { type: "array", items: {} },
|
||||
description: "Required. The values, one array per row, one item per cell. Each item is a string, number, boolean or null. null skips the cell; an empty string clears it.",
|
||||
},
|
||||
},
|
||||
required: ["spreadsheetId", "range", "values"],
|
||||
},
|
||||
outputSchema: writeOutputSchema,
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
||||
},
|
||||
args,
|
||||
async run(input, http) {
|
||||
return runValuesUpdate(http, input.spreadsheetId, input.range, input.values, "RAW");
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import type { z } from "zod";
|
||||
import type { GoogleHttp, GoogleRequest } from "../google-http.js";
|
||||
import { structuredResult } from "../tool.js";
|
||||
import {
|
||||
assertWriteWithinBounds,
|
||||
type cellValue,
|
||||
countCells,
|
||||
SHEETS_HOST,
|
||||
type UpdateValuesResponse,
|
||||
valuesPath,
|
||||
valuesWriteStatus,
|
||||
} from "./spreadsheet.js";
|
||||
|
||||
export type ValueInputOption = "RAW" | "USER_ENTERED";
|
||||
export type CellValue = z.infer<typeof cellValue>;
|
||||
|
||||
export const HOW_WRITTEN: Record<ValueInputOption, string> = {
|
||||
RAW: "as raw values",
|
||||
USER_ENTERED: "as if typed into Google Sheets",
|
||||
};
|
||||
|
||||
export function valuesUpdateRequest(id: string, range: string, values: CellValue[][], option: ValueInputOption): GoogleRequest {
|
||||
const body = { range, majorDimension: "ROWS", values };
|
||||
assertWriteWithinBounds(countCells(values), body);
|
||||
return {
|
||||
method: "PUT",
|
||||
host: SHEETS_HOST,
|
||||
path: valuesPath(id, range),
|
||||
query: { valueInputOption: option },
|
||||
body,
|
||||
};
|
||||
}
|
||||
|
||||
export function valuesUpdateResult(response: UpdateValuesResponse, range: string, option: ValueInputOption): CallToolResult {
|
||||
return structuredResult({ content: { ...response, status: valuesWriteStatus(response, range, HOW_WRITTEN[option]) } });
|
||||
}
|
||||
|
||||
export async function runValuesUpdate(http: GoogleHttp, id: string, range: string, values: CellValue[][], option: ValueInputOption): Promise<CallToolResult> {
|
||||
const response = await http.send<UpdateValuesResponse>(valuesUpdateRequest(id, range, values, option));
|
||||
return valuesUpdateResult(response, range, option);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { googleWorkspaceToolName, googleWorkspaceToolTarget } from "@paperclipai/shared";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { googleRequestUrl, type GoogleRequest } from "../google-http.js";
|
||||
import { googleWorkspaceRestProbeFor, probeGoogleWorkspaceRestService } from "../probe.js";
|
||||
import { callGoogleWorkspaceRestTool, listGoogleWorkspaceRestTools } from "../tools.js";
|
||||
import { fakeGoogle, json } from "../fixtures/fake-google.js";
|
||||
import { FORMATTED_VALUES, SPREADSHEET_ID } from "./fixtures/sheets-rest.js";
|
||||
|
||||
const scope = (name: string) => `https://www.googleapis.com/auth/${name}`;
|
||||
const GET: GoogleRequest = { method: "GET", host: "sheets.googleapis.com", path: `/v4/spreadsheets/${SPREADSHEET_ID}` };
|
||||
|
||||
describe("sheets.googleapis.com host", () => {
|
||||
it.each([
|
||||
`/v4/spreadsheets/${SPREADSHEET_ID}`,
|
||||
`/v4/spreadsheets/${SPREADSHEET_ID}/values/Sheet1!A1%3AB2`,
|
||||
`/v4/spreadsheets/${SPREADSHEET_ID}:batchUpdate`,
|
||||
])("allows %s", (path) => {
|
||||
expect(googleRequestUrl({ ...GET, path })).toBe(`https://sheets.googleapis.com${path}`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"/v4/spreadsheets",
|
||||
"/v3/spreadsheets/x",
|
||||
"/v4/spreadsheetsx/y",
|
||||
"/v4/spreadsheets/../../drive/v3/files",
|
||||
"/v4/spreadsheets/%2e%2e/%2e%2e/v4/other",
|
||||
"/upload/v4/spreadsheets/x",
|
||||
"/v4/other/x",
|
||||
])("refuses %s", (path) => {
|
||||
expect(() => googleRequestUrl({ ...GET, path })).toThrow(/not allowed/);
|
||||
});
|
||||
|
||||
it("does not let other hosts serve Sheets paths", () => {
|
||||
expect(() => googleRequestUrl({ ...GET, host: "www.googleapis.com" })).toThrow(/not allowed/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Sheets service", () => {
|
||||
it("lists the six allowlisted tools, each runnable with exactly its allowlisted scope", () => {
|
||||
const tools = listGoogleWorkspaceRestTools("sheets");
|
||||
expect(tools.map((tool) => tool.name)).toEqual(["get_values", "get_spreadsheet", "update_spreadsheet", "update_values", "update_formulas", "insert_dimension"]);
|
||||
const scopes = Object.fromEntries(tools.map((tool) => [tool.name, googleWorkspaceToolTarget(googleWorkspaceToolName("sheets", tool.name))?.requiredScopes]));
|
||||
expect(scopes).toMatchObject({
|
||||
get_values: [[scope("spreadsheets.readonly"), scope("spreadsheets")]],
|
||||
get_spreadsheet: [[scope("spreadsheets.readonly"), scope("spreadsheets")]],
|
||||
update_spreadsheet: [[scope("spreadsheets")]],
|
||||
update_values: [[scope("spreadsheets")]],
|
||||
update_formulas: [[scope("spreadsheets")]],
|
||||
insert_dimension: [[scope("spreadsheets")]],
|
||||
});
|
||||
});
|
||||
|
||||
it("calls a Sheets tool through the service entry point", async () => {
|
||||
const { fetch, calls } = fakeGoogle(() => json(FORMATTED_VALUES));
|
||||
const result = await callGoogleWorkspaceRestTool({ service: "sheets", name: "get_values", arguments: { spreadsheetId: SPREADSHEET_ID, range: "'Q1 Plan'!A1:D4" }, accessToken: "token-1", fetch });
|
||||
expect(result.structuredContent).toMatchObject({ range: FORMATTED_VALUES.range });
|
||||
expect(calls[0]!.url.host).toBe("sheets.googleapis.com");
|
||||
expect(calls[0]!.headers.authorization).toBe("Bearer token-1");
|
||||
});
|
||||
|
||||
it("is listed without a network probe, since every Sheets read needs a spreadsheet ID", async () => {
|
||||
expect(googleWorkspaceRestProbeFor("sheets", [scope("spreadsheets.readonly"), scope("spreadsheets")])).toBeNull();
|
||||
const fetch = vi.fn();
|
||||
await expect(probeGoogleWorkspaceRestService({ service: "sheets", accessToken: "t", grantedScopes: [scope("spreadsheets")], fetch }))
|
||||
.resolves.toEqual({ ok: true, probed: false });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,17 @@ export function structuredResult(value: Record<string, unknown>): CallToolResult
|
||||
return { content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value };
|
||||
}
|
||||
|
||||
export function serializedResultBytes(result: CallToolResult): number {
|
||||
return Buffer.byteLength(JSON.stringify(result), "utf8");
|
||||
}
|
||||
|
||||
export function boundedStructuredResult(value: Record<string, unknown>, maxBytes: number, tooLarge: (bytes: number) => string): CallToolResult {
|
||||
const result = structuredResult(value);
|
||||
const bytes = serializedResultBytes(result);
|
||||
if (bytes > maxBytes) throw new GoogleToolError("incomplete", tooLarge(bytes));
|
||||
return result;
|
||||
}
|
||||
|
||||
export function toolErrorResult(error: GoogleToolError): CallToolResult {
|
||||
return { isError: true, content: [{ type: "text", text: error.message }] };
|
||||
}
|
||||
|
||||
@@ -4,14 +4,16 @@ import { GoogleWorkspaceAuthError } from "./errors.js";
|
||||
import { CALENDAR_TOOLS } from "./calendar/index.js";
|
||||
import { GMAIL_TOOLS } from "./gmail/index.js";
|
||||
import { createGoogleHttp, type GoogleFetch } from "./google-http.js";
|
||||
import { SHEETS_TOOLS } from "./sheets/index.js";
|
||||
import type { RestTool } from "./tool.js";
|
||||
|
||||
export const GOOGLE_WORKSPACE_REST_SERVICES = ["gmail", "calendar"] as const;
|
||||
export const GOOGLE_WORKSPACE_REST_SERVICES = ["gmail", "calendar", "sheets"] as const;
|
||||
export type GoogleWorkspaceRestService = (typeof GOOGLE_WORKSPACE_REST_SERVICES)[number];
|
||||
|
||||
const TOOLS: Record<GoogleWorkspaceRestService, readonly RestTool[]> = {
|
||||
gmail: GMAIL_TOOLS,
|
||||
calendar: CALENDAR_TOOLS,
|
||||
sheets: SHEETS_TOOLS,
|
||||
};
|
||||
|
||||
export function isGoogleWorkspaceRestService(value: string): value is GoogleWorkspaceRestService {
|
||||
|
||||
Reference in new issue
Block a user