From f61b919701d85f519fd41d472d3468c6bb92d098 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:28:13 -0600 Subject: [PATCH] feat(google-workspace): REST-backed Docs and Slides tools; mark Calendar update_event destructive (#22029) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Google Workspace connector gives agents Google tools through the tool gateway > - Google's hosted Workspace MCP servers are a Developer Preview, so Paperclip launches on its own tools over Google's REST APIs, in `server/src/google-workspace-rest-tools/` > - Gmail and Calendar are done there; Docs and Slides have no tools yet > - This pull request adds `read_doc`, `update_doc`, `read_presentation` and `update_presentation` with the same names and inputs as Google's MCP tools > - The benefit is that the Docs and Slides services can switch to `paperclip_rest` once their API is enabled, and reviewers see a full document in Paperclip ## Linked Issues or Issue Description **Subsystem affected** Google Workspace REST tool set (`server/src/google-workspace-rest-tools/`), Docs and Slides services. **Problem or motivation** The REST tool set has no Docs or Slides tools. The allowlist (`toolScopes.docs`, `toolScopes.slides`) names two tools for each service. A service cannot switch to `paperclip_rest` until all of its allowlisted tools exist. **Proposed solution** Add the four tools in new `docs/` and `slides/` folders. Each tool makes exactly one REST call. The read tools return the whole file as Markdown-style text plus an index structure for edits. The update tools post `batchUpdate` requests in order and require the revision ID that the caller read. **Alternatives considered** Return the raw `documents.get` JSON. It is 10 to 20 times larger than the text, so ordinary documents go over the result size limit, and it is hard to compare with Google Docs. Reorder edit requests by index. That changes what dependent requests do, and Google's tool does not do it. Refs #22000, #22014, #22017 ## What Changed - `docs/`: `read_doc` (`documents.get` with `includeTabsContent=true`) and `update_doc` (`documents.batchUpdate`), a renderer for every tab, child tab, heading, list (real numbering), table, link, header, footer, footnote, chip, suggestion and comment, and an index structure where each paragraph's `text.length` equals `endIndex - startIndex`. - `slides/`: `read_presentation` (`presentations.get`; with `fields` it returns Google's resource as is) and `update_presentation` (`presentations.batchUpdate`), a renderer for every slide's text, tables, groups, media and speaker notes. - `documents-shared.ts`: the 250,000-byte limit on the final serialized result (an error, never a cut-short result), the revision-conflict error, comment rendering, and argument checks. - Update tools require `writeControl.requiredRevisionId` and refuse `targetRevisionId`. A revision conflict returns "nothing was changed; read it again". Writes are never retried. - `google-http.ts`: allows `docs.googleapis.com` only under `/v1/documents/` and `slides.googleapis.com` only under `/v1/presentations/`. - `tools.ts`, `probe.ts`: register the services. Docs and Slides have no network probe, because every read needs a file ID. - Update tools accept only a closed list of batch request kinds (`docs/request-kinds.ts`, `slides/request-kinds.ts`). Kinds and forms that read another file are refused by name: `insertRichLink`, the Sheets chart kinds, `importSlides`, `createAudio`, Drive videos, and images from Drive or Docs links. Unknown kinds are refused too. - `read_doc` always requests `SUGGESTIONS_INLINE` and falls back to an explicit `PREVIEW_WITHOUT_SUGGESTIONS` read for view-only users; the result says which view it used. - Tables with merged cells are placed on the full grid; covered cells read `(merged left)` or `(merged up)`. - Revision conflicts are recognized from Google's `error.status` and `error.details` first, with the message as a fallback. - Annotations: `update_doc` and `update_presentation` are destructive and not idempotent. **Calendar `update_event` is now also marked destructive** (it overwrites fields, removes attendees and replaces reminders). Google's references mark both non-destructive; the README records this. - `README.md`: endpoint and scope table with Google's documentation links, the result format, what cannot be shown, update order and revision rules, and every difference from Google's tools. ## Verification - `cd server && npx vitest run src/google-workspace-rest-tools`: 33 files, 573 tests pass (169 new in `docs/` and `slides/`, plus host, probe and allowlist tests). - `cd server && pnpm typecheck`: passes. - `pnpm verify`: exit 2 (README is a broad input), so required CI supplies broad coverage. - `src/services/google-workspace-rest-dispatch.test.ts` fails the same way on `master` (it still expects Gmail to be incomplete after #22014). This PR does not touch it. ## Risks - Low risk. Nothing calls these tools until the Docs or Slides transport is set to `paperclip_rest`; both stay `google_mcp`. - The inner format of `content` differs from Google's tool, which Google does not publish. The README lists this. - Revision-conflict detection matches Google's 400 message on "revision". Any 400 rejects the whole batch, so nothing changes in either case. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code execution. ## 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 --- .../src/google-workspace-rest-tools/README.md | 248 ++++++++- .../allowlist.test.ts | 36 ++ .../calendar/update-event.ts | 2 +- .../docs/document.ts | 129 +++++ .../docs/fixtures/docs-rest.ts | 166 ++++++ .../google-workspace-rest-tools/docs/index.ts | 5 + .../docs/read-doc.test.ts | 125 +++++ .../docs/read-doc.ts | 75 +++ .../docs/render.test.ts | 327 ++++++++++++ .../docs/render.ts | 492 ++++++++++++++++++ .../docs/request-kinds.test.ts | 79 +++ .../docs/request-kinds.ts | 59 +++ .../docs/update-doc.test.ts | 152 ++++++ .../docs/update-doc.ts | 97 ++++ .../documents-shared.test.ts | 87 ++++ .../documents-shared.ts | 191 +++++++ .../src/google-workspace-rest-tools/errors.ts | 9 +- .../google-http.test.ts | 21 + .../google-http.ts | 8 +- .../google-workspace-rest-tools/probe.test.ts | 10 + .../src/google-workspace-rest-tools/probe.ts | 2 + .../sheets/spreadsheet.ts | 4 +- .../slides/fixtures/slides-rest.ts | 117 +++++ .../slides/index.ts | 5 + .../slides/presentation.ts | 72 +++ .../slides/read-presentation.test.ts | 71 +++ .../slides/read-presentation.ts | 80 +++ .../slides/render.test.ts | 240 +++++++++ .../slides/render.ts | 261 ++++++++++ .../slides/request-kinds.test.ts | 75 +++ .../slides/request-kinds.ts | 63 +++ .../slides/update-presentation.test.ts | 102 ++++ .../slides/update-presentation.ts | 83 +++ .../src/google-workspace-rest-tools/tool.ts | 2 + .../src/google-workspace-rest-tools/tools.ts | 6 +- 35 files changed, 3487 insertions(+), 14 deletions(-) create mode 100644 server/src/google-workspace-rest-tools/docs/document.ts create mode 100644 server/src/google-workspace-rest-tools/docs/fixtures/docs-rest.ts create mode 100644 server/src/google-workspace-rest-tools/docs/index.ts create mode 100644 server/src/google-workspace-rest-tools/docs/read-doc.test.ts create mode 100644 server/src/google-workspace-rest-tools/docs/read-doc.ts create mode 100644 server/src/google-workspace-rest-tools/docs/render.test.ts create mode 100644 server/src/google-workspace-rest-tools/docs/render.ts create mode 100644 server/src/google-workspace-rest-tools/docs/request-kinds.test.ts create mode 100644 server/src/google-workspace-rest-tools/docs/request-kinds.ts create mode 100644 server/src/google-workspace-rest-tools/docs/update-doc.test.ts create mode 100644 server/src/google-workspace-rest-tools/docs/update-doc.ts create mode 100644 server/src/google-workspace-rest-tools/documents-shared.test.ts create mode 100644 server/src/google-workspace-rest-tools/documents-shared.ts create mode 100644 server/src/google-workspace-rest-tools/slides/fixtures/slides-rest.ts create mode 100644 server/src/google-workspace-rest-tools/slides/index.ts create mode 100644 server/src/google-workspace-rest-tools/slides/presentation.ts create mode 100644 server/src/google-workspace-rest-tools/slides/read-presentation.test.ts create mode 100644 server/src/google-workspace-rest-tools/slides/read-presentation.ts create mode 100644 server/src/google-workspace-rest-tools/slides/render.test.ts create mode 100644 server/src/google-workspace-rest-tools/slides/render.ts create mode 100644 server/src/google-workspace-rest-tools/slides/request-kinds.test.ts create mode 100644 server/src/google-workspace-rest-tools/slides/request-kinds.ts create mode 100644 server/src/google-workspace-rest-tools/slides/update-presentation.test.ts create mode 100644 server/src/google-workspace-rest-tools/slides/update-presentation.ts diff --git a/server/src/google-workspace-rest-tools/README.md b/server/src/google-workspace-rest-tools/README.md index b6c855b9da3..581bb5530d1 100644 --- a/server/src/google-workspace-rest-tools/README.md +++ b/server/src/google-workspace-rest-tools/README.md @@ -12,8 +12,9 @@ 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) -and all six allowlisted Sheets tools (see "Sheets tools" below). +It also has all nine allowlisted Calendar tools (see "Calendar tools" below), +both Docs tools and both Slides tools (see "Docs and Slides tools" below), and +all six allowlisted Sheets tools (see "Sheets tools" below). ## Why this exists, and why it is temporary @@ -58,9 +59,11 @@ 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/` 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 + is allowed only under `/calendar/v3/`, `docs.googleapis.com` only under + `/v1/documents/`, `slides.googleapis.com` only under `/v1/presentations/` + and `sheets.googleapis.com` only under `/v4/spreadsheets/`, checked after + URL normalization. +- **One tool, one file.** Each tool in `gmail/`, `calendar/`, `docs/`, `slides/` 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`. @@ -143,6 +146,10 @@ 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` | + Docs and Slides have no probe: every read of either API needs a document or + presentation ID, and Google does not document what a made-up ID returns, so + a probe could wrongly mark a working grant unavailable. + Sheets has no probe: every Sheets REST read needs a spreadsheet ID, so a Sheets grant is listed without one. @@ -322,6 +329,12 @@ Google's servers return if they ever expose tools with these names: A switch back to `google_mcp` would drop these three unless Google adds them. +To check when a live tester exists: record `read_doc` and `read_presentation` +answers from Google's Docs and Slides MCP servers for a test document and +deck, and compare their `content` with ours. Google publishes only that +`content` is an object; our text form and structure are unverified against +Google's server. + ## Calendar tools Names, input fields, enums, result shapes and annotations come from Google's @@ -417,6 +430,13 @@ earliest first; working hours and out-of-office settings are not read. ### Differences from Google's Calendar MCP tools +- **`update_event` is annotated `destructiveHint: true`** (deliberate). It + overwrites fields, can remove attendees and replaces reminders, so + approval and confirmation in Paperclip must treat it as destructive. + Google's reference marks it non-destructive. It stays `idempotentHint: + true`: the same patch applied twice leaves the event the same. + `respond_to_event` stays non-destructive (it changes only the user's own + response). `allowlist.test.ts` checks the write tools' annotations. - **Time zone when none is given.** Google says its server resolves the user's time zone. Here it is the target calendar's time zone (the primary calendar for `suggest_time`), read from `events.list`, since the user @@ -462,6 +482,222 @@ earliest first; working hours and out-of-office settings are not read. comes from REST `transparency`; `conferenceUrl` from `hangoutLink` or the video entry point. +## Docs and Slides tools + +Names and input fields come from Google's MCP references +(, +`.../update_doc`, + +and `.../update_presentation`, recorded 2026-11-17). Annotations follow them +except `destructiveHint` on `update_doc` (see the differences below). Each +tool makes one REST call; `read_doc` makes a second only when Google refuses +the first for the user's access (see "Suggestions and comments"). + +| Tool | REST call | Works with | Google documentation | +| --- | --- | --- | --- | +| `read_doc` | `documents.get` with `includeTabsContent=true` and an explicit `suggestionsViewMode` | `documents.readonly` or `documents` | | +| `update_doc` | `documents.batchUpdate` | `documents` | | +| `read_presentation` | `presentations.get` | `presentations.readonly` or `presentations` | | +| `update_presentation` | `presentations.batchUpdate` | `presentations` | | + +### What the read tools return + +Google documents both results only as `{ content: object }`, "a JSON +representation" of the file, and does not say what is inside. Here `content` +holds: + +- `text`: the whole file as Markdown-style text. Docs: every tab (child tabs + included, each under `=== Tab: Parent / Child ===` when there is more than + one), headings as `#`, list items with their real numbering (`1.`, `a.`, + `iv.`, nested formats such as `1.2.`, start numbers, numbering that + continues across interrupting paragraphs), tables as `| cells |` with nested + tables flattened into one cell, merged table cells placed on the full grid + (every row has the table's column count; cells covered by a merge read + `(merged left)` or `(merged up)`, never a blank), links as `[text](url)` (heading, bookmark and + tab links as `#heading=…`, `#bookmark=…`, `#tab=…`), footnote references as + `[^n]` with the footnotes after the body, headers and footers labelled + default, first page or even pages, person and date chips, rich links, page + and column breaks, and, in the `SUGGESTIONS_INLINE` view only, pending + suggestions as `{+inserted+}` and `{-deleted-}`. Slides: each slide as `## Slide n` (marked skipped when it + is), title placeholders as `###`, bullets with their own glyph, tables, + groups, word art, and each slide's speaker notes under `Speaker notes:`. +- A structure for edits. Docs: `tabs[]` with every paragraph's and table + cell's `startIndex`, `endIndex`, named style and list, plus headers, footers + and footnotes by segment ID. A paragraph's `text` is exact: each non-text + index (an image, a footnote reference, a chip) is one U+FFFC, so + `text.length` equals `endIndex - startIndex`. Slides: `slides[]` with each + page element's `objectId`, type, placeholder and raw text, table cells by + row and column (Slides tables are placed on the grid by each cell's + `location` and spans, since `tableCells` leaves out covered cells), and the + speaker notes shape's `objectId`. +- `revisionId`, which the update tools require. +- `notes`: what could not be shown as text, with a count, and for Docs always + which suggestions view was used. +- Docs: `suggestionsViewMode`, the view the document was read in. +- With `commentsIncluded`, a `[Comments]` section (`commentsViewMode` on both + APIs). + +### Suggestions and comments + +`read_doc` always asks for `suggestionsViewMode=SUGGESTIONS_INLINE`, so +pending suggested edits are shown and the indices are the ones +`documents.batchUpdate` needs (the Document reference: "When editing a +document, changes must be based on a document with SUGGESTIONS_INLINE"). +Google answers 403 to that view when the user may not see suggestions; without +an explicit view a viewer would silently get `PREVIEW_WITHOUT_SUGGESTIONS`. +On a 403 permission answer the tool reads again with +`PREVIEW_WITHOUT_SUGGESTIONS` (without comments, which Google returns only +with inline suggestions). That result says, in `suggestionsViewMode` and +`notes`, that pending suggestions are not shown and that its indices may not +be valid for `update_doc`; if comments were asked for, `[Comments]` and +`notes` say they are not available with the user's access. Any other failure +(not found, API disabled, a missing Docs permission on the grant) is returned +as is, without a second read. A document that is readable is never turned +into an error by these options. + +`read_presentation` with `commentsIncluded` asks for +`commentsViewMode=COMMENTS_VIEW_MODE_INCLUDED`. If Google refuses that with a +permission error, the tool reads only the presentation's ID to check that the +presentation itself is readable; if it is, it returns an error saying comments +are not available with the user's access and that it can be read without +`commentsIncluded`. If not, Google's own error is returned. + +`read_presentation` with `fields` returns Google's resource limited to those +fields, unchanged, as Google's tool does. + +What cannot be represented, and is listed in `notes` when present: pictures +(shown as `[image: title or alt text]`), drawings, charts, equations (the Docs +API does not return their content), dropdown values, Slides videos (shown with +their link), and text that slide masters and layouts put on every slide. +Formatting other than headings, lists and links (bold, colors, fonts, sizes) +is not in `text`. Checklist items render as plain list items: the Docs API +does not say whether a box is ticked. + +A result over 250,000 bytes is refused with an error that gives the size and +returns nothing; it is never cut short. It is the folder's one limit, +`MAX_RESULT_BYTES` in `tool.ts`, checked by `boundedStructuredResult` (which +`sizedResult` in `documents-shared.ts` calls) on the final serialized MCP +result, which carries the content twice (as +JSON text and as structured content), so the content itself is limited to +about 125,000 bytes. Paperclip delivers tool results over 500,000 bytes as a +pointer instead of content; the lower limit keeps every read inline with +room to spare. To read a +large presentation in parts, pass `fields`, for example +`["slides(objectId,pageElements(objectId,shape.text))"]`. `read_doc` has no +way to read part of a document, since Google's tool has no such input and +`documents.get` cannot select one tab; a document whose result would be over +the limit cannot be read through this tool. + +### How the update tools work + +Google's tools take `documents.batchUpdate` and `presentations.batchUpdate` +requests as they are, so these do too: the requests are posted unchanged and +in the caller's order, in one call. Google applies them in order and all or +none; each request sees the file as changed by those before it. Reordering +them here would change what dependent requests (insert, then style the +inserted text) do, so nothing is reordered. The descriptions tell callers to +order several index-based edits from one read from the highest index to the +lowest; the tests show that order gives the intended result and the reverse +does not. + +`writeControl.requiredRevisionId` is required (Google makes it optional). It +is the `revisionId` from the read tool. If the file changed since, Google +rejects the whole batch and the tool answers that the file is no longer at +the revision you read, nothing was changed, and to read it again. A rejection +counts as a conflict when Google's structured `error.status` is +`FAILED_PRECONDITION` or `ABORTED`, or a reason in `error.details` names a +revision or an unmet condition; only when neither field says so does the +message decide ("required revision", "revision ID" or "latest revision"). +Any other 400 returns Google's own message. +`targetRevisionId` (Docs), which would apply the edit to a newer version, is +refused. The answer includes the new revision in `writeControl`, also for +Slides (Google's Slides tool lists only `replies`). A write is never retried; +a failure after it was sent carries the uncertain-outcome warning. + +Each request must name exactly one request kind; at most 500 per call. + +The requests can delete or replace content in the one file the call names: +text (`deleteContentRange`, `deleteText`, `replaceAllText`), tabs +(`deleteTab`) and slides or page elements (`deleteObject`), as in Google's +tools. Both update descriptions say so. The tools cannot create, delete, move, +copy or share files, and there is no tool that can. + +#### Allowed request kinds + +Each update tool accepts only the request kinds in a closed list: +`DOCS_REQUEST_KINDS` in `docs/request-kinds.ts` and `SLIDES_REQUEST_KINDS` in +`slides/request-kinds.ts`, built from Google's REST request references +(, +, +recorded 2026-11-17). A kind is allowed only when it acts within the one file +being edited. Any kind not on the list, including one Google adds later, is +refused with an error that names it, and nothing is sent. The same table +builds the lists in the tool descriptions and drives the tests, and a test +checks it covers every kind in Google's reference. + +Docs: every kind in Google's `documents.batchUpdate` reference and in its +`update_doc` MCP reference is listed. All are allowed except `insertRichLink` +(refused); `insertInlineImage` and `replaceImage` are allowed only in the +restricted form below. + +Slides: every kind in Google's `presentations.batchUpdate` reference and in +its `update_presentation` MCP reference (which adds `importSlides`, +`createAudio` and `updateAudioProperties`) is listed. All are allowed except +`createSheetsChart`, `replaceAllShapesWithSheetsChart`, `refreshSheetsChart`, +`importSlides` and `createAudio` (refused); `createVideo`, `createImage`, +`replaceImage`, `replaceAllShapesWithImage` and `updatePageProperties` are +allowed only in the restricted forms below. No other kind can link content +from another file: linked charts come only from the refused Sheets chart +kinds, and linked slides only from the refused `importSlides`. + +The tests keep Google's full lists and check that each kind is classified +explicitly; only a kind on neither list falls through to "not a request kind +this tool accepts". + +Refused, because they read another file: + +| Tool | Kind | Reason | +| --- | --- | --- | +| `update_doc` | `insertRichLink` | A smart chip that points to another file and shows its title. | +| `update_presentation` | `createSheetsChart`, `replaceAllShapesWithSheetsChart`, `refreshSheetsChart` | Read a chart from a Google Sheets spreadsheet. | +| `update_presentation` | `importSlides` | Copies slides from another presentation (in Google's MCP tool list, not in REST). | +| `update_presentation` | `createAudio` | Inserts an audio file from Google Drive (in Google's MCP tool list, not in REST). | + +Refused forms of allowed kinds: `createVideo` is accepted only with +`source: "YOUTUBE"` (a `DRIVE` video is another file). Image kinds +(`insertInlineImage` and `replaceImage` in Docs; `createImage`, `replaceImage`, +`replaceAllShapesWithImage` and a `stretchedPictureFill.contentUrl` page +background in Slides) are allowed with a public image link, since Google +fetches it without the user's data, but refused when the link is on +`drive.google.com` or `docs.google.com`, which names another file. Links in +text styles stay allowed: they only point somewhere and read nothing. + +This is a deliberate difference from Google's tools, which accept every +request kind. + +Both update tools are annotated `destructiveHint: true` and +`idempotentHint: false`, because a batch can delete or overwrite content and +repeating it repeats the edit. Google marks `update_doc` non-destructive; this +is a deliberate difference so that approval and confirmation in Paperclip +match what the tool can do. `allowlist.test.ts` checks all four tools' +annotations. + +### Differences from Google's Docs and Slides MCP tools + +- `content` is the text form and structure above, not the raw REST resource + (except `read_presentation` with `fields`). Google does not publish the + inner format of `content`, and ours has not been compared with an answer + from Google's server (see "Not verified against Google's servers"). +- `requiredRevisionId` is required and `targetRevisionId` is refused. +- `update_doc` is annotated destructive (Google: not destructive). +- `read_doc` always sets `suggestionsViewMode` and falls back to + `PREVIEW_WITHOUT_SUGGESTIONS` for users who may not see suggestions. +- Both update tools accept only a closed list of request kinds and refuse + kinds and forms that read another file (see "Allowed request kinds"). +- At least one request is required. +- Descriptions are our own wording. The `documentId` description does not + name Drive's file ID field, since the Drive tool is not in this folder. + ## Sheets tools Names, input fields, result shapes and annotations come from Google's Sheets @@ -639,5 +875,5 @@ says `false`. cd server && npx vitest run src/google-workspace-rest-tools ``` -Test fixtures in `fixtures/`, `gmail/fixtures/`, `calendar/fixtures/` and `sheets/fixtures/` are synthetic, in the shape +Test fixtures in `fixtures/` and each service's `fixtures/` folder are synthetic, in the shape of Google's REST responses. They contain no real mail, addresses or IDs. diff --git a/server/src/google-workspace-rest-tools/allowlist.test.ts b/server/src/google-workspace-rest-tools/allowlist.test.ts index 9fd97c2ca3d..7823bdd0cee 100644 --- a/server/src/google-workspace-rest-tools/allowlist.test.ts +++ b/server/src/google-workspace-rest-tools/allowlist.test.ts @@ -76,6 +76,42 @@ describe("tool allowlist", () => { expect(listGoogleWorkspaceRestTools("calendar").map((tool) => tool.name).sort()).toEqual([...allowlisted].sort()); }); + it.each([ + ["docs", ["read_doc", "update_doc"], ["update_doc"]], + ["slides", ["read_presentation", "update_presentation"], ["update_presentation"]], + ] as const)("implements every allowlisted %s tool (2 of 2), writing only through its update tool", (service, allowlisted, writes) => { + for (const name of allowlisted) expect(googleWorkspaceToolTarget(googleWorkspaceToolName(service, name)), name).not.toBeNull(); + expect(listGoogleWorkspaceRestTools(service).map((tool) => tool.name).sort()).toEqual([...allowlisted].sort()); + expect(listGoogleWorkspaceRestTools(service).filter((tool) => tool.annotations?.readOnlyHint !== true).map((tool) => tool.name)).toEqual(writes); + }); + + it("marks the Docs and Slides update tools destructive and not idempotent, and the reads read-only", () => { + const annotations = Object.fromEntries((["docs", "slides"] as const).flatMap((service) => listGoogleWorkspaceRestTools(service).map((tool) => [tool.name, tool.annotations]))); + expect(annotations).toEqual({ + read_doc: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + update_doc: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, + read_presentation: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + update_presentation: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, + }); + }); + + it("marks the Calendar tools that overwrite or remove data destructive", () => { + const annotations = Object.fromEntries(listGoogleWorkspaceRestTools("calendar") + .filter((tool) => tool.annotations?.readOnlyHint !== true) + .map((tool) => [tool.name, tool.annotations])); + expect(annotations).toEqual({ + create_event: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, + update_event: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, + delete_event: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, + respond_to_event: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + }); + }); + + it("adds no create, delete, share or permission tool for Docs or Slides", () => { + const names = (["docs", "slides"] as const).flatMap((service) => listGoogleWorkspaceRestTools(service).map((tool) => tool.name)); + expect(names.filter((name) => /create|delete|share|permission|copy|trash/i.test(name))).toEqual([]); + }); + 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(); diff --git a/server/src/google-workspace-rest-tools/calendar/update-event.ts b/server/src/google-workspace-rest-tools/calendar/update-event.ts index 36df72ae9da..91b122ed2e5 100644 --- a/server/src/google-workspace-rest-tools/calendar/update-event.ts +++ b/server/src/google-workspace-rest-tools/calendar/update-event.ts @@ -241,7 +241,7 @@ export const updateEvent = defineTool({ required: ["eventId"], }, outputSchema: eventSchema, - annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }, }, args, async run(input, http) { diff --git a/server/src/google-workspace-rest-tools/docs/document.ts b/server/src/google-workspace-rest-tools/docs/document.ts new file mode 100644 index 00000000000..375aaa2a6e8 --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/document.ts @@ -0,0 +1,129 @@ +import type { RestCommentThread } from "../documents-shared.js"; + +export const DOCS_HOST = "docs.googleapis.com" as const; +export const DOCS_BASE = "/v1/documents"; + +export const documentPath = (documentId: string) => `${DOCS_BASE}/${encodeURIComponent(documentId)}`; + +export interface RestDocsLink { + url?: string; + tabId?: string; + headingId?: string; + bookmarkId?: string; + heading?: { id?: string; tabId?: string }; + bookmark?: { id?: string; tabId?: string }; +} + +export interface RestSuggestible { + suggestedInsertionIds?: string[]; + suggestedDeletionIds?: string[]; +} + +export interface RestParagraphElement { + startIndex?: number; + endIndex?: number; + textRun?: RestSuggestible & { content?: string; textStyle?: { link?: RestDocsLink } }; + autoText?: RestSuggestible & { type?: string }; + pageBreak?: RestSuggestible; + columnBreak?: RestSuggestible; + footnoteReference?: RestSuggestible & { footnoteId?: string; footnoteNumber?: string }; + horizontalRule?: RestSuggestible; + equation?: RestSuggestible; + inlineObjectElement?: RestSuggestible & { inlineObjectId?: string }; + person?: RestSuggestible & { personProperties?: { name?: string; email?: string } }; + richLink?: RestSuggestible & { richLinkProperties?: { title?: string; uri?: string } }; + dateElement?: RestSuggestible & { dateElementProperties?: { displayText?: string } }; + dropdown?: RestSuggestible; +} + +export interface RestParagraph { + elements?: RestParagraphElement[]; + paragraphStyle?: { namedStyleType?: string; headingId?: string }; + bullet?: { listId?: string; nestingLevel?: number }; + positionedObjectIds?: string[]; +} + +export interface RestTableCell { + startIndex?: number; + endIndex?: number; + content?: RestStructuralElement[]; + tableCellStyle?: { rowSpan?: number; columnSpan?: number }; +} + +export interface RestTable { + rows?: number; + columns?: number; + tableRows?: Array<{ startIndex?: number; endIndex?: number; tableCells?: RestTableCell[] }>; +} + +export interface RestStructuralElement { + startIndex?: number; + endIndex?: number; + paragraph?: RestParagraph; + table?: RestTable; + sectionBreak?: Record; + tableOfContents?: { content?: RestStructuralElement[] }; +} + +export interface RestSegment { + headerId?: string; + footerId?: string; + footnoteId?: string; + content?: RestStructuralElement[]; +} + +export interface RestNestingLevel { + glyphType?: string; + glyphSymbol?: string; + glyphFormat?: string; + startNumber?: number; +} + +export interface RestEmbeddedObject { + title?: string; + description?: string; + imageProperties?: Record; + embeddedDrawingProperties?: Record; + linkedContentReference?: { sheetsChartReference?: Record }; +} + +export interface RestDocumentStyle { + defaultHeaderId?: string; + firstPageHeaderId?: string; + evenPageHeaderId?: string; + defaultFooterId?: string; + firstPageFooterId?: string; + evenPageFooterId?: string; +} + +export interface RestDocumentTab { + body?: { content?: RestStructuralElement[] }; + headers?: Record; + footers?: Record; + footnotes?: Record; + documentStyle?: RestDocumentStyle; + lists?: Record; + inlineObjects?: Record; + positionedObjects?: Record; + commentAnchors?: Record }>; +} + +export interface RestTab { + tabProperties?: { tabId?: string; title?: string; parentTabId?: string; index?: number; nestingLevel?: number }; + documentTab?: RestDocumentTab; + childTabs?: RestTab[]; +} + +export interface RestDocument { + documentId?: string; + title?: string; + revisionId?: string; + tabs?: RestTab[]; + comments?: RestCommentThread[]; +} + +export interface RestBatchUpdateResponse { + documentId?: string; + replies?: Array>; + writeControl?: { requiredRevisionId?: string; targetRevisionId?: string }; +} diff --git a/server/src/google-workspace-rest-tools/docs/fixtures/docs-rest.ts b/server/src/google-workspace-rest-tools/docs/fixtures/docs-rest.ts new file mode 100644 index 00000000000..2bfc2428ec7 --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/fixtures/docs-rest.ts @@ -0,0 +1,166 @@ +import type { + RestDocument, + RestDocumentTab, + RestParagraph, + RestParagraphElement, + RestStructuralElement, + RestTab, + RestTableCell, +} from "../document.js"; + +export function run(content: string, extra: Partial> = {}): RestParagraphElement { + return { textRun: { content, ...extra } }; +} + +export function withIndices(start: number, elements: RestParagraphElement[]): { elements: RestParagraphElement[]; end: number } { + let at = start; + const placed = elements.map((element) => { + const length = element.textRun ? (element.textRun.content ?? "").length : 1; + const result = { startIndex: at, endIndex: at + length, ...element }; + at += length; + return result; + }); + return { elements: placed, end: at }; +} + +export function para(elements: RestParagraphElement[], style: Omit = {}, start = 1): RestStructuralElement { + const placed = withIndices(start, elements); + return { startIndex: start, endIndex: placed.end, paragraph: { elements: placed.elements, ...style } }; +} + +export function text(value: string, style: Omit = {}): RestStructuralElement { + return para([run(`${value}\n`)], style); +} + +export function cell(...paragraphs: string[]): RestTableCell { + return { content: paragraphs.map((value) => text(value)) }; +} + +export function table(rows: RestTableCell[][]): RestStructuralElement { + return { startIndex: 1, endIndex: 2, table: { rows: rows.length, columns: rows[0]?.length ?? 0, tableRows: rows.map((tableCells) => ({ tableCells })) } }; +} + +export function oneTab(body: RestStructuralElement[], extra: RestDocumentTab = {}): RestDocument { + return { + documentId: "doc-synthetic-1", + title: "Synthetic", + revisionId: "rev-1", + tabs: [{ tabProperties: { tabId: "t.0", title: "Tab 1", index: 0 }, documentTab: { body: { content: [{ endIndex: 1, sectionBreak: {} }, ...body] }, ...extra } }], + }; +} + +const PLAN_TAB: RestTab = { + tabProperties: { tabId: "t.0", title: "Plan", index: 0 }, + documentTab: { + body: { + content: [ + { endIndex: 1, sectionBreak: {} }, + para([run("Launch plan\n")], { paragraphStyle: { namedStyleType: "TITLE" } }, 1), + para([ + run("See "), + run("the brief", { textStyle: { link: { url: "https://example.test/brief" } } }), + run(" and "), + { footnoteReference: { footnoteId: "kix.fn1", footnoteNumber: "1" } }, + run(".\n"), + ], {}, 13), + para([run("Goals\n")], { paragraphStyle: { namedStyleType: "HEADING_1", headingId: "h.goals" } }, 34), + para([run("Ship docs\n")], { bullet: { listId: "kix.list1" } }, 40), + para([run("Write tests\n")], { bullet: { listId: "kix.list1", nestingLevel: 1 } }, 50), + para([run("First\n")], { bullet: { listId: "kix.list2" } }, 62), + para([run("Second\n")], { bullet: { listId: "kix.list2" } }, 68), + para([run("Detail\n")], { bullet: { listId: "kix.list2", nestingLevel: 1 } }, 75), + para([run("Third\n")], { bullet: { listId: "kix.list2" } }, 82), + { + startIndex: 88, + endIndex: 117, + table: { + rows: 2, + columns: 2, + tableRows: [ + { tableCells: [{ startIndex: 89, endIndex: 96, content: [para([run("Owner\n")], {}, 90)] }, { startIndex: 96, endIndex: 101, content: [para([run("Due\n")], {}, 97)] }] }, + { tableCells: [{ startIndex: 102, endIndex: 109, content: [para([run("Avery | Ops\n")], {}, 103)] }, { startIndex: 109, endIndex: 116, content: [para([run("Friday\n")], {}, 110)] }] }, + ], + }, + }, + para([{ inlineObjectElement: { inlineObjectId: "kix.img1" } }, run("\n")], {}, 117), + para([ + run("Status: "), + run("new", { suggestedInsertionIds: ["suggest.1"] }), + run("old", { suggestedDeletionIds: ["suggest.2"] }), + run("\n"), + ], {}, 119), + para([run("\n")], {}, 134), + ], + }, + headers: { "kix.h1": { headerId: "kix.h1", content: [para([run("Confidential\n")], {}, 0)] } }, + footers: { "kix.f1": { footerId: "kix.f1", content: [para([{ autoText: { type: "PAGE_NUMBER" } }, run("\n")], {}, 0)] } }, + footnotes: { "kix.fn1": { footnoteId: "kix.fn1", content: [para([run(" Source: survey.\n")], {}, 0)] } }, + documentStyle: { defaultHeaderId: "kix.h1", defaultFooterId: "kix.f1" }, + lists: { + "kix.list1": { listProperties: { nestingLevels: [{ glyphSymbol: "●", glyphFormat: "%0" }, { glyphSymbol: "○", glyphFormat: "%1" }] } }, + "kix.list2": { listProperties: { nestingLevels: [{ glyphType: "DECIMAL", glyphFormat: "%0." }, { glyphType: "ALPHA", glyphFormat: "%1." }] } }, + }, + inlineObjects: { "kix.img1": { inlineObjectProperties: { embeddedObject: { title: "Roadmap chart", imageProperties: {} } } } }, + }, + childTabs: [ + { + tabProperties: { tabId: "t.1", title: "Notes", parentTabId: "t.0", index: 0, nestingLevel: 1 }, + documentTab: { body: { content: [{ endIndex: 1, sectionBreak: {} }, para([run("Child tab text\n")], {}, 1)] } }, + }, + ], +}; + +const APPENDIX_TAB: RestTab = { + tabProperties: { tabId: "t.2", title: "Appendix", index: 1 }, + documentTab: { + body: { + content: [ + { endIndex: 1, sectionBreak: {} }, + para([run("Glossary\n")], { paragraphStyle: { namedStyleType: "HEADING_2" } }, 1), + { startIndex: 10, endIndex: 15, paragraph: { elements: [{ startIndex: 10, endIndex: 14, equation: {} }, { startIndex: 14, endIndex: 15, textRun: { content: "\n" } }] } }, + ], + }, + }, +}; + +export const MULTI_TAB_DOCUMENT: RestDocument = { + documentId: "doc-synthetic-multi", + title: "Synthetic launch plan", + revisionId: "ALm37BV-synthetic-rev", + tabs: [PLAN_TAB, APPENDIX_TAB], +}; + +export const MULTI_TAB_TEXT = [ + "=== Tab: Plan ===", + "# Launch plan", + "See [the brief](https://example.test/brief) and [^1].", + "# Goals", + "- Ship docs", + " - Write tests", + "1. First", + "2. Second", + " a. Detail", + "3. Third", + "", + "| Owner | Due |", + "| --- | --- |", + "| Avery \\| Ops | Friday |", + "", + "[image: Roadmap chart]", + "Status: {+new+}{-old-}", + "", + "[Header (default)]", + "Confidential", + "", + "[Footer (default)]", + "[page number]", + "", + "[^1]: Source: survey.", + "", + "=== Tab: Plan / Notes ===", + "Child tab text", + "", + "=== Tab: Appendix ===", + "## Glossary", + "[equation]", +].join("\n"); diff --git a/server/src/google-workspace-rest-tools/docs/index.ts b/server/src/google-workspace-rest-tools/docs/index.ts new file mode 100644 index 00000000000..55f4bcf690c --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/index.ts @@ -0,0 +1,5 @@ +import type { RestTool } from "../tool.js"; +import { readDoc } from "./read-doc.js"; +import { updateDoc } from "./update-doc.js"; + +export const DOCS_TOOLS: readonly RestTool[] = [readDoc, updateDoc]; diff --git a/server/src/google-workspace-rest-tools/docs/read-doc.test.ts b/server/src/google-workspace-rest-tools/docs/read-doc.test.ts new file mode 100644 index 00000000000..1b714a7f29d --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/read-doc.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from "vitest"; +import { MAX_RESULT_BYTES } from "../tool.js"; +import { fakeGoogle, json } from "../fixtures/fake-google.js"; +import { createGoogleHttp } from "../google-http.js"; +import { MULTI_TAB_DOCUMENT, MULTI_TAB_TEXT, oneTab, para, run, text } from "./fixtures/docs-rest.js"; +import { readDoc, readDocRequest } from "./read-doc.js"; +import { COMMENTS_UNAVAILABLE_NOTE, INLINE_NOTE, PREVIEW_NOTE } from "./render.js"; + +const INLINE = "?includeTabsContent=true&suggestionsViewMode=SUGGESTIONS_INLINE"; +const INLINE_WITH_COMMENTS = `${INLINE}&commentsViewMode=COMMENTS_VIEW_MODE_INCLUDED`; +const PREVIEW = "?includeTabsContent=true&suggestionsViewMode=PREVIEW_WITHOUT_SUGGESTIONS"; +const denied = () => json({ error: { code: 403, status: "PERMISSION_DENIED", message: "The caller does not have permission" } }, 403); +const SUGGESTED = oneTab([para([run("Keep "), run("new", { suggestedInsertionIds: ["s1"] }), run("\n")])]); +const PREVIEWED = oneTab([text("Keep")]); + +function content(result: { structuredContent?: unknown }): Record { + return (result.structuredContent as { content: Record }).content; +} + +describe("read_doc request", () => { + it.each([ + [{ documentId: "1AbC-d_9" }, undefined, { includeTabsContent: true, suggestionsViewMode: "SUGGESTIONS_INLINE" }], + [{ documentId: "1AbC-d_9", commentsIncluded: false }, undefined, { includeTabsContent: true, suggestionsViewMode: "SUGGESTIONS_INLINE" }], + [{ documentId: "1AbC-d_9", commentsIncluded: true }, undefined, { includeTabsContent: true, suggestionsViewMode: "SUGGESTIONS_INLINE", commentsViewMode: "COMMENTS_VIEW_MODE_INCLUDED" }], + [{ documentId: "1AbC-d_9" }, "PREVIEW_WITHOUT_SUGGESTIONS", { includeTabsContent: true, suggestionsViewMode: "PREVIEW_WITHOUT_SUGGESTIONS" }], + [{ documentId: "1AbC-d_9", commentsIncluded: true }, "PREVIEW_WITHOUT_SUGGESTIONS", { includeTabsContent: true, suggestionsViewMode: "PREVIEW_WITHOUT_SUGGESTIONS" }], + ] as const)("reads every tab of %j in view %s with an explicit suggestions view", (input, view, query) => { + expect(readDocRequest(input, view)).toEqual({ method: "GET", host: "docs.googleapis.com", path: "/v1/documents/1AbC-d_9", query }); + }); +}); + +describe("read_doc tool", () => { + it("reads the document once with suggestions inline and returns its text, structure, view and revision", async () => { + const { fetch, calls } = fakeGoogle(() => json(MULTI_TAB_DOCUMENT)); + const result = await readDoc.call({ documentId: "doc-synthetic-multi" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls.map((call) => `${call.method} ${call.url.host}${call.url.pathname}${call.url.search}`)).toEqual([ + `GET docs.googleapis.com/v1/documents/doc-synthetic-multi${INLINE}`, + ]); + expect(content(result)).toMatchObject({ documentId: "doc-synthetic-multi", revisionId: "ALm37BV-synthetic-rev", suggestionsViewMode: "SUGGESTIONS_INLINE", text: MULTI_TAB_TEXT }); + expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual(result.structuredContent); + }); + + it("shows an editor's pending suggestions inline", async () => { + const { fetch, calls } = fakeGoogle(() => json(SUGGESTED)); + const result = await readDoc.call({ documentId: "doc-1" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls).toHaveLength(1); + expect(content(result)).toMatchObject({ suggestionsViewMode: "SUGGESTIONS_INLINE", text: "Keep {+new+}" }); + expect(content(result).notes).toEqual([INLINE_NOTE]); + }); + + it("reads a viewer's document without suggestions when Google refuses the inline view, and says so", async () => { + const { fetch, calls } = fakeGoogle(({ url }) => (url.searchParams.get("suggestionsViewMode") === "SUGGESTIONS_INLINE" ? denied() : json(PREVIEWED))); + const result = await readDoc.call({ documentId: "doc-1" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls.map((call) => call.url.search)).toEqual([INLINE, PREVIEW]); + expect(result.isError).toBeUndefined(); + expect(content(result)).toMatchObject({ suggestionsViewMode: "PREVIEW_WITHOUT_SUGGESTIONS", text: "Keep", notes: [PREVIEW_NOTE] }); + expect(PREVIEW_NOTE).toMatch(/may not be valid for update_doc/); + }); + + it("returns a viewer's document without comments when comments were asked for, and says so", async () => { + const { fetch, calls } = fakeGoogle(({ url }) => (url.searchParams.get("suggestionsViewMode") === "SUGGESTIONS_INLINE" ? denied() : json(PREVIEWED))); + const result = await readDoc.call({ documentId: "doc-1", commentsIncluded: true }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls.map((call) => call.url.search)).toEqual([INLINE_WITH_COMMENTS, PREVIEW]); + expect(content(result)).toMatchObject({ + suggestionsViewMode: "PREVIEW_WITHOUT_SUGGESTIONS", + text: "Keep\n\n[Comments]\nNot available with your access to this document.", + notes: [PREVIEW_NOTE, COMMENTS_UNAVAILABLE_NOTE], + }); + }); + + it("returns the real access error when the document cannot be read in either view", async () => { + const { fetch, calls } = fakeGoogle(denied); + const result = await readDoc.call({ documentId: "doc-1" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(result).toEqual({ isError: true, content: [{ type: "text", text: "The caller does not have permission" }] }); + expect(calls.map((call) => call.url.search)).toEqual([INLINE, PREVIEW]); + }); + + it.each([ + ["a missing document", () => json({ error: { code: 404 } }, 404), "Google could not find that item."], + ["a bad request", () => json({ error: { code: 400, message: "Invalid document." } }, 400), "Invalid document."], + ["a disabled API", () => json({ error: { code: 403, errors: [{ reason: "accessNotConfigured" }] } }, 403), "This Google API is not enabled for the Google Cloud project behind this connection."], + ])("does not fall back for %s", async (_name, answer, message) => { + const { fetch, calls } = fakeGoogle(answer); + const result = await readDoc.call({ documentId: "doc-1" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(result).toEqual({ isError: true, content: [{ type: "text", text: message }] }); + expect(calls).toHaveLength(1); + }); + + it("does not fall back when the grant lacks the Docs permission", async () => { + const { fetch, calls } = fakeGoogle(() => json({ error: { code: 403, details: [{ reason: "ACCESS_TOKEN_SCOPE_INSUFFICIENT" }] } }, 403)); + await expect(readDoc.call({ documentId: "doc-1" }, createGoogleHttp({ accessToken: "t", fetch }))).rejects.toMatchObject({ reason: "insufficient_scope" }); + expect(calls).toHaveLength(1); + }); + + it("refuses a malformed document ID without calling Google", async () => { + const { fetch, calls } = fakeGoogle(() => json({})); + const http = createGoogleHttp({ accessToken: "t", fetch }); + for (const documentId of ["", "../x", "a/b", "a b", "a:batchUpdate", "x".repeat(257)]) { + expect((await readDoc.call({ documentId }, http)).isError, documentId).toBe(true); + } + expect(calls).toHaveLength(0); + }); + + it("measures the limit on the whole result, which carries the content twice", async () => { + const under = (count: number) => oneTab(Array.from({ length: count }, () => text("z".repeat(1_000)))); + const perParagraph = 2 * 2 * 1_000; + const fits = Math.floor(MAX_RESULT_BYTES / perParagraph) - 10; + const http = (doc: unknown) => createGoogleHttp({ accessToken: "t", fetch: fakeGoogle(() => json(doc)).fetch }); + const ok = await readDoc.call({ documentId: "d" }, http(under(fits))); + expect(ok.isError).toBeUndefined(); + expect(Buffer.byteLength(JSON.stringify(ok), "utf8")).toBeLessThanOrEqual(MAX_RESULT_BYTES); + expect(Buffer.byteLength(JSON.stringify(ok.structuredContent), "utf8")).toBeLessThan(MAX_RESULT_BYTES / 2 + 1); + expect((await readDoc.call({ documentId: "d" }, http(under(fits + 40)))).isError).toBe(true); + }); + + it("refuses a result over the size limit with a clear error instead of cutting it short", async () => { + const paragraph = "x".repeat(10_000); + const big = oneTab(Array.from({ length: Math.ceil(MAX_RESULT_BYTES / 20_000) + 5 }, () => text(paragraph))); + const { fetch } = fakeGoogle(() => json(big)); + const result = await readDoc.call({ documentId: "big" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(result.isError).toBe(true); + expect((result.content[0] as { text: string }).text).toMatch(/^This document is too large to return in one result \(\d+ KB; the limit is 250 KB\)\. Nothing was returned\./); + expect(result.structuredContent).toBeUndefined(); + }); +}); diff --git a/server/src/google-workspace-rest-tools/docs/read-doc.ts b/server/src/google-workspace-rest-tools/docs/read-doc.ts new file mode 100644 index 00000000000..94a3ab54bce --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/read-doc.ts @@ -0,0 +1,75 @@ +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import { fileIdArg, sizedResult } from "../documents-shared.js"; +import { GoogleToolError } from "../errors.js"; +import type { GoogleHttp, GoogleRequest } from "../google-http.js"; +import { defineTool } from "../tool.js"; +import { DOCS_HOST, documentPath, type RestDocument } from "./document.js"; +import { renderDocument, type SuggestionsView } from "./render.js"; + +const args = z.object({ + documentId: fileIdArg("Docs document"), + commentsIncluded: z.boolean().optional(), +}); +export type ReadDocArgs = z.infer; + +export function readDocRequest(input: ReadDocArgs, view: SuggestionsView = "SUGGESTIONS_INLINE"): GoogleRequest { + const comments = input.commentsIncluded && view === "SUGGESTIONS_INLINE"; + return { + method: "GET", + host: DOCS_HOST, + path: documentPath(input.documentId), + query: { + includeTabsContent: true, + suggestionsViewMode: view, + ...(comments ? { commentsViewMode: "COMMENTS_VIEW_MODE_INCLUDED" } : {}), + }, + }; +} + +export async function readDocument(http: GoogleHttp, input: ReadDocArgs): Promise<{ document: RestDocument; view: SuggestionsView }> { + try { + return { document: await http.send(readDocRequest(input)), view: "SUGGESTIONS_INLINE" }; + } catch (error) { + if (!(error instanceof GoogleToolError) || error.kind !== "permission_denied") throw error; + return { document: await http.send(readDocRequest(input, "PREVIEW_WITHOUT_SUGGESTIONS")), view: "PREVIEW_WITHOUT_SUGGESTIONS" }; + } +} + +export function readDocResult(document: RestDocument, input: ReadDocArgs, view: SuggestionsView = "SUGGESTIONS_INLINE"): CallToolResult { + const content = renderDocument(document, { commentsRequested: input.commentsIncluded === true, suggestionsView: view }); + return sizedResult({ content }, "document", "Google Docs cannot return part of a document through this tool."); +} + +export const readDoc = defineTool({ + definition: { + name: "read_doc", + description: [ + "Reads a Google Doc, every tab included, and returns its content.", + "content.text is the whole document as Markdown-style text: headings start with #, list items with - or their number, tables use | cells |, links are [text](url), footnote references are [^1] with the footnote text after the body, headers and footers follow the body under [Header] and [Footer], and each tab starts with === Tab: title === when there is more than one.", + "Items that have no text form are shown in brackets, such as [image: alt text], [equation] or [page break], and content.notes says what was left out.", + "content.tabs gives each tab's paragraphs and tables with their startIndex and endIndex (UTF-16 code units), for use with update_doc; in a paragraph's text, every non-text item such as an image takes one index and appears as U+FFFC.", + "content.revisionId is required by update_doc.", + "content.suggestionsViewMode says how pending suggested edits were read: SUGGESTIONS_INLINE shows them marked; when your access does not include suggestions the document is read as PREVIEW_WITHOUT_SUGGESTIONS, without them, and content.notes says so.", + ].join(" "), + inputSchema: { + type: "object", + properties: { + documentId: { type: "string", description: "Required. The ID of the document to read: the part of its docs.google.com link after /d/." }, + commentsIncluded: { type: "boolean", description: "Optional. If true, comment threads are listed at the end of content.text. When your access does not include comments and suggestions, the document is returned without them and content.notes says so. Default: false." }, + }, + required: ["documentId"], + }, + outputSchema: { + type: "object", + properties: { content: { type: "object", description: "The document's text, structure and revision ID." } }, + required: ["content"], + }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + }, + args, + async run(input, http) { + const { document, view } = await readDocument(http, input); + return readDocResult(document, input, view); + }, +}); diff --git a/server/src/google-workspace-rest-tools/docs/render.test.ts b/server/src/google-workspace-rest-tools/docs/render.test.ts new file mode 100644 index 00000000000..a4c406fb080 --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/render.test.ts @@ -0,0 +1,327 @@ +import { describe, expect, it } from "vitest"; +import type { RestDocument, RestDocumentTab, RestStructuralElement } from "./document.js"; +import { cell, MULTI_TAB_DOCUMENT, MULTI_TAB_TEXT, oneTab, para, run, table, text } from "./fixtures/docs-rest.js"; +import { formatListNumber, INLINE_NOTE, renderDocument } from "./render.js"; + +const render = (body: RestStructuralElement[], extra: RestDocumentTab = {}) => renderDocument(oneTab(body, extra)).text; + +describe("read_doc text rendering", () => { + it("renders a whole multi-tab document: headings, links, lists, tables, images, suggestions, headers, footers, footnotes and child tabs", () => { + const content = renderDocument(MULTI_TAB_DOCUMENT); + expect(content.text).toBe(MULTI_TAB_TEXT); + expect(content).toMatchObject({ documentId: "doc-synthetic-multi", title: "Synthetic launch plan", revisionId: "ALm37BV-synthetic-rev" }); + expect(content.notes).toEqual([ + INLINE_NOTE, + "1 image is shown as [image] with its title or alt text; the picture itself is not included.", + "1 equation is shown as [equation]; the Docs API does not return equation content.", + ]); + }); + + it.each([ + ["TITLE", "# Words"], + ["SUBTITLE", "## Words"], + ["HEADING_1", "# Words"], + ["HEADING_2", "## Words"], + ["HEADING_3", "### Words"], + ["HEADING_4", "#### Words"], + ["HEADING_5", "##### Words"], + ["HEADING_6", "###### Words"], + ["NORMAL_TEXT", "Words"], + ])("renders a %s paragraph as %j", (namedStyleType, expected) => { + expect(render([text("Words", { paragraphStyle: { namedStyleType } })])).toBe(expected); + }); + + it("leaves an empty heading paragraph empty", () => { + expect(render([text("Above"), text("", { paragraphStyle: { namedStyleType: "HEADING_1" } }), text("Below")])).toBe("Above\n\nBelow"); + }); + + it.each([ + ["unordered, nested three deep", [{ glyphSymbol: "●" }, { glyphSymbol: "○" }, { glyphSymbol: "■" }], [0, 1, 2, 1, 0], ["- a", " - b", " - c", " - d", "- e"]], + ["decimal with lettered sub-items, restarting the sub-level", [{ glyphType: "DECIMAL", glyphFormat: "%0." }, { glyphType: "ALPHA", glyphFormat: "%1." }], [0, 1, 1, 0, 1], ["1. a", " a. b", " b. c", "2. d", " a. e"]], + ["nested decimal format", [{ glyphType: "DECIMAL", glyphFormat: "%0." }, { glyphType: "DECIMAL", glyphFormat: "%0.%1." }], [0, 1, 1, 0], ["1. a", " 1.1. b", " 1.2. c", "2. d"]], + ["roman and upper alpha with parentheses", [{ glyphType: "UPPER_ROMAN", glyphFormat: "%0)" }, { glyphType: "UPPER_ALPHA", glyphFormat: "(%1)" }], [0, 0, 0, 1], ["I) a", "II) b", "III) c", " (A) d"]], + ["custom start number", [{ glyphType: "DECIMAL", glyphFormat: "%0.", startNumber: 5 }], [0, 0], ["5. a", "6. b"]], + ["zero-padded decimal", [{ glyphType: "ZERO_DECIMAL", glyphFormat: "%0." }], [0, 0], ["01. a", "02. b"]], + ["checklist without a glyph", [{ glyphType: "GLYPH_TYPE_UNSPECIFIED" }], [0, 0], ["- a", "- b"]], + ] as const)("renders a %s list", (_name, nestingLevels, levels, expected) => { + const body = levels.map((nestingLevel, index) => text(String.fromCharCode(97 + index), { bullet: { listId: "kix.l", nestingLevel } })); + expect(render(body, { lists: { "kix.l": { listProperties: { nestingLevels: [...nestingLevels] } } } })).toBe(expected.join("\n")); + }); + + it("keeps numbering a list across an interrupting paragraph, and numbers separate lists separately", () => { + const lists = { + "kix.a": { listProperties: { nestingLevels: [{ glyphType: "DECIMAL", glyphFormat: "%0." }] } }, + "kix.b": { listProperties: { nestingLevels: [{ glyphType: "DECIMAL", glyphFormat: "%0." }] } }, + }; + const body = [ + text("one", { bullet: { listId: "kix.a" } }), + text("between"), + text("two", { bullet: { listId: "kix.a" } }), + text("other", { bullet: { listId: "kix.b" } }), + ]; + expect(render(body, { lists })).toBe("1. one\nbetween\n2. two\n1. other"); + }); + + it("renders a bullet whose list is missing as an unordered item", () => { + expect(render([text("orphan", { bullet: { listId: "kix.missing", nestingLevel: 1 } })])).toBe(" - orphan"); + }); + + it.each([ + ["a web link", { url: "https://example.test/a" }, "[here](https://example.test/a)"], + ["a heading link", { heading: { id: "h.abc", tabId: "t.0" } }, "[here](#heading=h.abc)"], + ["a legacy heading link", { headingId: "h.old" }, "[here](#heading=h.old)"], + ["a bookmark link", { bookmark: { id: "id.bm" } }, "[here](#bookmark=id.bm)"], + ["a tab link", { tabId: "t.9" }, "[here](#tab=t.9)"], + ["an empty link", {}, "here"], + ])("renders %s", (_name, link, expected) => { + expect(render([para([run("Go "), run("here", { textStyle: { link } }), run("\n")])])).toBe(`Go ${expected}`); + }); + + it("keeps a link's closing bracket before the paragraph's newline", () => { + expect(render([para([run("whole line\n", { textStyle: { link: { url: "https://example.test" } } })]), text("next")])).toBe("[whole line](https://example.test)\nnext"); + }); + + it.each([ + ["an image with a title", { title: "Logo", imageProperties: {} }, "[image: Logo]", "1 image is"], + ["an image with only alt text", { description: "A red\nlogo", imageProperties: {} }, "[image: A red logo]", "1 image is"], + ["an image with no description", { imageProperties: {} }, "[image]", "1 image is"], + ["a drawing", { embeddedDrawingProperties: {} }, "[drawing]", "1 drawing is"], + ["a linked chart", { title: "Sales", linkedContentReference: { sheetsChartReference: {} } }, "[chart: Sales]", "1 chart is"], + ])("renders %s and says what was left out", (_name, embeddedObject, expected, note) => { + const document = oneTab([para([run("A "), { inlineObjectElement: { inlineObjectId: "obj" } }, run("\n")])], { + inlineObjects: { obj: { inlineObjectProperties: { embeddedObject } } }, + }); + const content = renderDocument(document); + expect(content.text).toBe(`A ${expected}`); + expect(content.notes[1]).toMatch(new RegExp(`^${note.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`)); + }); + + it("renders positioned images after their paragraph and counts them", () => { + const document = oneTab([text("Caption", { positionedObjectIds: ["pos1", "pos2"] }), text("", { positionedObjectIds: ["pos3"] })], { + positionedObjects: { + pos1: { positionedObjectProperties: { embeddedObject: { title: "Map", imageProperties: {} } } }, + pos2: { positionedObjectProperties: { embeddedObject: { imageProperties: {} } } }, + pos3: { positionedObjectProperties: { embeddedObject: { description: "Floor plan", imageProperties: {} } } }, + }, + }); + const content = renderDocument(document); + expect(content.text).toBe("Caption [image: Map] [image]\n[image: Floor plan]"); + expect(content.notes).toEqual([INLINE_NOTE, "3 images are shown as [image] with its title or alt text; the picture itself is not included."]); + }); + + it.each([ + ["a person chip with name and email", { person: { personProperties: { name: "Avery", email: "avery@example.test" } } }, "Avery "], + ["a person chip with only an email", { person: { personProperties: { email: "blake@example.test" } } }, "blake@example.test"], + ["a rich link", { richLink: { richLinkProperties: { title: "Budget", uri: "https://docs.google.com/spreadsheets/d/abc" } } }, "[Budget](https://docs.google.com/spreadsheets/d/abc)"], + ["a date chip", { dateElement: { dateElementProperties: { displayText: "Nov 17, 2026" } } }, "Nov 17, 2026"], + ["a date chip without display text", { dateElement: {} }, "[date]"], + ["a page break", { pageBreak: {} }, "[page break]"], + ["a column break", { columnBreak: {} }, "[column break]"], + ["a horizontal rule", { horizontalRule: {} }, "---"], + ["a page count", { autoText: { type: "PAGE_COUNT" } }, "[page count]"], + ["other automatic text", { autoText: { type: "TYPE_UNSPECIFIED" } }, "[auto text]"], + ])("renders %s", (_name, element, expected) => { + expect(render([para([run("x "), element, run("\n")])])).toBe(`x ${expected}`); + }); + + it("renders a dropdown as a placeholder and says its value is not available", () => { + const content = renderDocument(oneTab([para([{ dropdown: {} }, run("\n")])])); + expect(content.text).toBe("[dropdown]"); + expect(content.notes).toEqual([INLINE_NOTE, "1 dropdown is shown as [dropdown]; the Docs API does not return the selected value."]); + }); + + it("turns soft line breaks into new lines inside the same item", () => { + expect(render([text("first\u000bsecond", { bullet: { listId: "kix.x" } })])).toBe("- first\nsecond"); + }); + + it("marks suggested insertions and deletions, including on non-text items", () => { + const content = renderDocument(oneTab([para([ + run("keep "), + run("add", { suggestedInsertionIds: ["s1"] }), + run(" "), + run("drop", { suggestedDeletionIds: ["s2"] }), + { pageBreak: { suggestedInsertionIds: ["s3"] } }, + run("\n"), + ])])); + expect(content.text).toBe("keep {+add+} {-drop-}{+[page break]+}"); + expect(content.notes).toEqual([INLINE_NOTE]); + }); + + it("renders tables with escaped pipes, multi-paragraph cells, nested tables and blank lines around them", () => { + const nested = table([[cell("n1"), cell("n2")], [cell("n3"), cell("n4")]]); + const body = [ + text("Before"), + table([[cell("H1"), cell("H|2")], [cell("line one", "line two"), { content: [nested, text("")] }]]), + text("After"), + ]; + expect(render(body)).toBe([ + "Before", + "", + "| H1 | H\\|2 |", + "| --- | --- |", + "| line one
line two | [table: n1 / n2; n3 / n4] |", + "", + "After", + ].join("\n")); + }); + + it("renders a table with a single row and an empty table", () => { + expect(render([table([[cell("only"), cell("")]])])).toBe("| only | |\n| --- | --- |"); + expect(render([{ startIndex: 1, endIndex: 2, table: { rows: 0, columns: 0, tableRows: [] } }])).toBe("[empty table]"); + }); + + it.each([ + [ + "a header spanning two columns", + [[{ ...cell("Q1 and Q2"), tableCellStyle: { columnSpan: 2 } }, { ...cell(""), tableCellStyle: { columnSpan: 1 } }, cell("Q3")], [cell("1"), cell("2"), cell("3")]], + ["| Q1 and Q2 | (merged left) | Q3 |", "| --- | --- | --- |", "| 1 | 2 | 3 |"], + ], + [ + "a cell spanning two rows", + [[{ ...cell("North"), tableCellStyle: { rowSpan: 2 } }, cell("x")], [cell(""), cell("y")]], + ["| North | x |", "| --- | --- |", "| (merged up) | y |"], + ], + [ + "a two-by-two merge", + [[{ ...cell("Big"), tableCellStyle: { rowSpan: 2, columnSpan: 2 } }, cell(""), cell("r")], [cell(""), cell(""), cell("s")]], + ["| Big | (merged left) | r |", "| --- | --- | --- |", "| (merged up) | (merged up) | s |"], + ], + [ + "rows that leave out covered cells", + [[{ ...cell("Wide"), tableCellStyle: { columnSpan: 2 } }], [cell("a"), cell("b")]], + ["| Wide | (merged left) |", "| --- | --- |", "| a | b |"], + ], + ])("renders %s with every row as wide as the table and the merged region marked", (_name, rows, expected) => { + const element = table(rows); + element.table!.columns = Math.max(...rows.map((row) => row.length)); + expect(render([element])).toBe(expected.join("\n")); + }); + + it("escapes a nested table's cells exactly once, so the outer row keeps its column count", () => { + const nested = table([[cell("a|b"), cell("c\\d")], [cell("e\u000bf"), cell("x")]]); + const rendered = render([table([[cell("Outer"), { content: [nested] }, cell("p|q\\")]])]); + const row = rendered.split("\n")[0]!; + expect(row).toBe("| Outer | [table: a\\|b / c\\\\d; e
f / x] | p\\|q\\\\ |"); + expect(row.split(/(? { + const nested = table([[{ ...cell("Span"), tableCellStyle: { columnSpan: 2 } }, cell("")], [cell("a"), cell("b")]]); + expect(render([table([[cell("Outer"), { content: [nested] }]])])).toBe("| Outer | [table: Span / (merged left); a / b] |\n| --- | --- |"); + }); + + it("does not add a blank line after a table when the next paragraph is already empty", () => { + expect(render([table([[cell("a")]]), text(""), text("x")])).toBe("| a |\n| --- |\n\nx"); + }); + + it("renders a table of contents and section breaks after the first", () => { + const toc: RestStructuralElement = { startIndex: 1, endIndex: 20, tableOfContents: { content: [para([run("Goals", { textStyle: { link: { heading: { id: "h.goals" } } } }), run("\n")])] } }; + expect(render([toc, { startIndex: 20, endIndex: 21, sectionBreak: {} }, text("Next section")])).toBe("[Table of contents]\n[Goals](#heading=h.goals)\n[section break]\nNext section"); + }); + + it("labels first-page and even-page headers and footers", () => { + const content = renderDocument(oneTab([text("Body")], { + headers: { a: { content: [text("Default head")] }, b: { content: [text("First head")] } }, + footers: { c: { content: [text("Even foot")] }, d: { content: [text("Unused foot")] } }, + documentStyle: { defaultHeaderId: "a", firstPageHeaderId: "b", evenPageFooterId: "c" }, + })); + expect(content.text).toBe("Body\n\n[Header (default)]\nDefault head\n\n[Header (first page)]\nFirst head\n\n[Footer (even pages)]\nEven foot\n\n[Footer]\nUnused foot"); + expect(content.tabs[0]!.headers.map((header) => header.kind)).toEqual(["default", "first page"]); + }); + + it("lists footnotes in number order after the body, including multi-paragraph and unreferenced ones", () => { + const content = renderDocument(oneTab([ + para([run("A"), { footnoteReference: { footnoteId: "fn.b", footnoteNumber: "1" } }, run(" B"), { footnoteReference: { footnoteId: "fn.a", footnoteNumber: "2" } }, run("\n")]), + ], { + footnotes: { + "fn.a": { content: [text(" Second note")] }, + "fn.b": { content: [text(" First note"), text("continued")] }, + "fn.c": { content: [text("Orphan")] }, + }, + })); + expect(content.text).toBe("A[^1] B[^2]\n\n[^1]: First note continued\n[^2]: Second note\n[^?]: Orphan"); + expect(content.tabs[0]!.footnotes.map((footnote) => footnote.footnoteNumber ?? null)).toEqual(["1", "2", null]); + }); + + it("lists comments with quotes, replies and resolved state when asked, and says when there are none", () => { + const document: RestDocument = { + ...oneTab([text("Body")]), + comments: [ + { commentId: "c1", anchorId: "a1", plainTextQuote: "Body", headPost: { content: "Is this\nright?", author: { displayName: "Avery" } }, replies: [{ content: "Yes", author: { displayName: "Blake" } }, { deleted: true }] }, + { commentId: "c2", status: "RESOLVED", headPost: { content: "Done", author: { anonymous: true } } }, + ], + }; + expect(renderDocument(document, { commentsRequested: true }).text).toBe([ + "Body", + "", + "[Comments]", + "- Avery: Is this right? on \"Body\"", + " - Blake: Yes", + " - (deleted)", + "- Anonymous: Done (resolved)", + ].join("\n")); + expect(renderDocument(oneTab([text("Body")]), { commentsRequested: true }).text).toBe("Body\n\n[Comments]\nNo comments."); + expect(renderDocument(document).text).toBe("Body"); + }); + + it("names the tab a comment is in when the document has several tabs", () => { + const document: RestDocument = { + ...MULTI_TAB_DOCUMENT, + tabs: [ + MULTI_TAB_DOCUMENT.tabs![0]!, + { ...MULTI_TAB_DOCUMENT.tabs![1]!, documentTab: { ...MULTI_TAB_DOCUMENT.tabs![1]!.documentTab, commentAnchors: { a9: { anchorId: "a9" } } } }, + ], + comments: [{ anchorId: "a9", headPost: { content: "Define terms", author: { displayName: "Avery" } } }], + }; + expect(renderDocument(document, { commentsRequested: true }).text.endsWith("[Comments]\n- Avery: Define terms [Appendix]")).toBe(true); + }); + + it("renders an empty document as empty text", () => { + expect(renderDocument({ documentId: "d", title: "Empty", tabs: [] })).toEqual({ documentId: "d", title: "Empty", suggestionsViewMode: "SUGGESTIONS_INLINE", text: "", tabs: [], notes: [INLINE_NOTE] }); + expect(render([text("")])).toBe(""); + }); +}); + +describe("read_doc structure", () => { + it("gives every paragraph its indices and exact text, with one U+FFFC per non-text index", () => { + const content = renderDocument(MULTI_TAB_DOCUMENT); + const [plan, notes, appendix] = content.tabs; + expect(plan).toMatchObject({ tabId: "t.0", title: "Plan" }); + expect(notes).toMatchObject({ tabId: "t.1", title: "Notes", parentTabId: "t.0", nestingLevel: 1 }); + expect(plan!.body[1]).toEqual({ type: "paragraph", startIndex: 1, endIndex: 13, text: "Launch plan\n", style: "TITLE" }); + expect(plan!.body[2]).toEqual({ type: "paragraph", startIndex: 13, endIndex: 34, text: "See the brief and .\n" }); + expect(plan!.body[4]).toEqual({ type: "paragraph", startIndex: 40, endIndex: 50, text: "Ship docs\n", list: { listId: "kix.list1", nestingLevel: 0 } }); + expect(appendix!.body[2]).toEqual({ type: "paragraph", startIndex: 10, endIndex: 15, text: "\n" }); + const paragraphs = [plan!, notes!, appendix!].flatMap((tab) => tab.body).filter((element) => element.type === "paragraph"); + for (const paragraph of paragraphs) expect(paragraph.text.length, paragraph.text).toBe(paragraph.endIndex - paragraph.startIndex); + }); + + it("gives tables their size and every cell's indices and content", () => { + const tableView = renderDocument(MULTI_TAB_DOCUMENT).tabs[0]!.body.find((element) => element.type === "table"); + expect(tableView).toMatchObject({ type: "table", startIndex: 88, endIndex: 117, rows: 2, columns: 2 }); + expect(tableView!.type === "table" && tableView!.cells[1]![0]).toEqual({ + startIndex: 102, endIndex: 109, content: [{ type: "paragraph", startIndex: 103, endIndex: 115, text: "Avery | Ops\n" }], + }); + }); + + it("keeps merged-cell spans, the section break and headers, footers and footnotes", () => { + const merged = table([[{ ...cell("wide"), tableCellStyle: { columnSpan: 2 } }, { ...cell(""), tableCellStyle: { columnSpan: 1 } }]]); + const tab = renderDocument(oneTab([merged])).tabs[0]!; + expect(tab.body[0]).toEqual({ type: "sectionBreak", startIndex: 0, endIndex: 1 }); + expect(tab.body[1]!.type === "table" && tab.body[1]!.cells[0]!.map((item) => item.columnSpan ?? 1)).toEqual([2, 1]); + const plan = renderDocument(MULTI_TAB_DOCUMENT).tabs[0]!; + expect(plan.headers).toEqual([{ segmentId: "kix.h1", kind: "default", content: [{ type: "paragraph", startIndex: 0, endIndex: 13, text: "Confidential\n" }] }]); + expect(plan.footnotes[0]).toMatchObject({ segmentId: "kix.fn1", footnoteNumber: "1" }); + }); +}); + +describe("list numbers", () => { + it.each([ + [1, "DECIMAL", "1"], [12, "DECIMAL", "12"], [3, "ZERO_DECIMAL", "03"], [10, "ZERO_DECIMAL", "10"], + [1, "ALPHA", "a"], [26, "ALPHA", "z"], [27, "ALPHA", "aa"], [28, "UPPER_ALPHA", "AB"], + [4, "ROMAN", "iv"], [9, "ROMAN", "ix"], [14, "UPPER_ROMAN", "XIV"], [1994, "UPPER_ROMAN", "MCMXCIV"], + [5, undefined, "5"], + ] as const)("formats %d as %s: %s", (value, glyphType, expected) => { + expect(formatListNumber(value, glyphType)).toBe(expected); + }); +}); diff --git a/server/src/google-workspace-rest-tools/docs/render.ts b/server/src/google-workspace-rest-tools/docs/render.ts new file mode 100644 index 00000000000..2741e751ebd --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/render.ts @@ -0,0 +1,492 @@ +import { markdownTable, OBJECT_PLACEHOLDER, plural, renderComments, tableGrid, type TableCellText } from "../documents-shared.js"; +import type { + RestDocsLink, + RestDocument, + RestDocumentTab, + RestEmbeddedObject, + RestNestingLevel, + RestParagraph, + RestParagraphElement, + RestSegment, + RestStructuralElement, + RestSuggestible, + RestTab, +} from "./document.js"; + +export interface DocsParagraphView { + type: "paragraph"; + startIndex: number; + endIndex: number; + text: string; + style?: string; + list?: { listId: string; nestingLevel: number }; +} + +export interface DocsTableCellView { + startIndex: number; + endIndex: number; + rowSpan?: number; + columnSpan?: number; + content: DocsElementView[]; +} + +export interface DocsTableView { + type: "table"; + startIndex: number; + endIndex: number; + rows: number; + columns: number; + cells: DocsTableCellView[][]; +} + +export interface DocsTableOfContentsView { + type: "tableOfContents"; + startIndex: number; + endIndex: number; + content: DocsElementView[]; +} + +export interface DocsSectionBreakView { + type: "sectionBreak"; + startIndex: number; + endIndex: number; +} + +export type DocsElementView = DocsParagraphView | DocsTableView | DocsTableOfContentsView | DocsSectionBreakView; + +export interface DocsSegmentView { + segmentId: string; + kind?: string; + footnoteNumber?: string; + content: DocsElementView[]; +} + +export interface DocsTabView { + tabId: string; + title: string; + parentTabId?: string; + nestingLevel?: number; + body: DocsElementView[]; + headers: DocsSegmentView[]; + footers: DocsSegmentView[]; + footnotes: DocsSegmentView[]; +} + +export interface DocsContent { + documentId: string; + title: string; + revisionId?: string; + suggestionsViewMode: SuggestionsView; + text: string; + tabs: DocsTabView[]; + notes: string[]; + [key: string]: unknown; +} + +interface Tally { + images: number; + drawings: number; + charts: number; + equations: number; + dropdowns: number; +} + +interface TabContext { + tab: RestDocumentTab; + tally: Tally; + counters: Map; + footnoteNumbers: Map; +} + +const ORDERED_GLYPHS = new Set(["DECIMAL", "ZERO_DECIMAL", "ALPHA", "UPPER_ALPHA", "ROMAN", "UPPER_ROMAN"]); +const HEADING_PREFIX: Record = { + TITLE: "# ", + SUBTITLE: "## ", + HEADING_1: "# ", + HEADING_2: "## ", + HEADING_3: "### ", + HEADING_4: "#### ", + HEADING_5: "##### ", + HEADING_6: "###### ", +}; + +const indexOf = (value: number | undefined) => value ?? 0; + +function letters(value: number): string { + let result = ""; + for (let n = value; n > 0; n = Math.floor((n - 1) / 26)) result = String.fromCharCode(97 + ((n - 1) % 26)) + result; + return result || "0"; +} + +function roman(value: number): string { + if (value <= 0 || value >= 4000) return String(value); + const table: Array<[number, string]> = [[1000, "m"], [900, "cm"], [500, "d"], [400, "cd"], [100, "c"], [90, "xc"], [50, "l"], [40, "xl"], [10, "x"], [9, "ix"], [5, "v"], [4, "iv"], [1, "i"]]; + let rest = value; + let result = ""; + for (const [amount, symbol] of table) { + while (rest >= amount) { + result += symbol; + rest -= amount; + } + } + return result; +} + +export function formatListNumber(value: number, glyphType: string | undefined): string { + switch (glyphType) { + case "ZERO_DECIMAL": return value < 10 ? `0${value}` : String(value); + case "ALPHA": return letters(value); + case "UPPER_ALPHA": return letters(value).toUpperCase(); + case "ROMAN": return roman(value); + case "UPPER_ROMAN": return roman(value).toUpperCase(); + default: return String(value); + } +} + +export function listMarker(levels: readonly RestNestingLevel[], counters: number[], level: number): string { + const spec = levels[level] ?? {}; + const previous = counters[level]; + counters.length = level + 1; + counters[level] = previous === undefined ? (spec.startNumber ?? 1) : previous + 1; + if (!spec.glyphType || !ORDERED_GLYPHS.has(spec.glyphType)) return "-"; + const format = spec.glyphFormat || `%${level}.`; + return format.replace(/%(\d)/g, (_match, digit: string) => { + const at = Number(digit); + return formatListNumber(counters[at] ?? levels[at]?.startNumber ?? 1, levels[at]?.glyphType); + }); +} + +export function linkTarget(link: RestDocsLink | undefined): string | undefined { + if (!link) return undefined; + if (link.url) return link.url; + const heading = link.heading?.id ?? link.headingId; + if (heading) return `#heading=${heading}`; + const bookmark = link.bookmark?.id ?? link.bookmarkId; + if (bookmark) return `#bookmark=${bookmark}`; + if (link.tabId) return `#tab=${link.tabId}`; + return undefined; +} + +function embeddedLabel(object: RestEmbeddedObject | undefined, tally: Tally): string { + const label = (object?.title || object?.description || "").replace(/\s+/g, " ").trim(); + const suffix = label ? `: ${label}` : ""; + if (object?.linkedContentReference?.sheetsChartReference) { + tally.charts += 1; + return `[chart${suffix}]`; + } + if (object?.embeddedDrawingProperties) { + tally.drawings += 1; + return `[drawing${suffix}]`; + } + tally.images += 1; + return `[image${suffix}]`; +} + +function suggestible(element: RestParagraphElement): RestSuggestible | undefined { + return element.textRun ?? element.autoText ?? element.pageBreak ?? element.columnBreak ?? element.footnoteReference + ?? element.horizontalRule ?? element.equation ?? element.inlineObjectElement ?? element.person ?? element.richLink + ?? element.dateElement ?? element.dropdown; +} + +function inlineText(element: RestParagraphElement, context: TabContext): string { + if (element.textRun) return element.textRun.content ?? ""; + if (element.autoText) { + if (element.autoText.type === "PAGE_NUMBER") return "[page number]"; + if (element.autoText.type === "PAGE_COUNT") return "[page count]"; + return "[auto text]"; + } + if (element.pageBreak) return "[page break]"; + if (element.columnBreak) return "[column break]"; + if (element.footnoteReference) { + const number = element.footnoteReference.footnoteNumber ?? "?"; + if (element.footnoteReference.footnoteId) context.footnoteNumbers.set(element.footnoteReference.footnoteId, number); + return `[^${number}]`; + } + if (element.horizontalRule) return "---"; + if (element.equation) { + context.tally.equations += 1; + return "[equation]"; + } + if (element.inlineObjectElement) { + const id = element.inlineObjectElement.inlineObjectId ?? ""; + return embeddedLabel(context.tab.inlineObjects?.[id]?.inlineObjectProperties?.embeddedObject, context.tally); + } + if (element.person) { + const { name, email } = element.person.personProperties ?? {}; + if (name && email) return `${name} <${email}>`; + return name || email || "[person]"; + } + if (element.richLink) { + const { title, uri } = element.richLink.richLinkProperties ?? {}; + return uri ? `[${title || uri}](${uri})` : title || "[link]"; + } + if (element.dateElement) return element.dateElement.dateElementProperties?.displayText || "[date]"; + if (element.dropdown) { + context.tally.dropdowns += 1; + return "[dropdown]"; + } + return ""; +} + +function renderInline(element: RestParagraphElement, context: TabContext): string { + const raw = inlineText(element, context); + const trailing = raw.match(/\n*$/)![0]; + let body = raw.slice(0, raw.length - trailing.length); + if (!body) return raw; + const target = linkTarget(element.textRun?.textStyle?.link); + if (target) body = `[${body}](${target})`; + const marks = suggestible(element); + if (marks?.suggestedInsertionIds?.length) body = `{+${body}+}`; + else if (marks?.suggestedDeletionIds?.length) body = `{-${body}-}`; + return body + trailing; +} + +export function paragraphRawText(paragraph: RestParagraph): string { + return (paragraph.elements ?? []).map((element) => { + if (element.textRun) return element.textRun.content ?? ""; + const length = Math.max(1, indexOf(element.endIndex) - indexOf(element.startIndex)); + return OBJECT_PLACEHOLDER.repeat(length); + }).join(""); +} + +function paragraphLine(paragraph: RestParagraph, context: TabContext): string { + let text = (paragraph.elements ?? []).map((element) => renderInline(element, context)).join(""); + text = text.replace(/\n$/, "").replace(/\u000b/g, "\n"); + for (const id of paragraph.positionedObjectIds ?? []) { + const label = embeddedLabel(context.tab.positionedObjects?.[id]?.positionedObjectProperties?.embeddedObject, context.tally); + text = text ? `${text} ${label}` : label; + } + if (paragraph.bullet) { + const listId = paragraph.bullet.listId ?? ""; + const level = paragraph.bullet.nestingLevel ?? 0; + const counters = context.counters.get(listId) ?? []; + context.counters.set(listId, counters); + const levels = context.tab.lists?.[listId]?.listProperties?.nestingLevels ?? []; + return `${" ".repeat(level)}${listMarker(levels, counters, level)} ${text}`; + } + const prefix = HEADING_PREFIX[paragraph.paragraphStyle?.namedStyleType ?? ""]; + return prefix && text ? `${prefix}${text}` : text; +} + +function cellText(content: readonly RestStructuralElement[], context: TabContext): string { + const parts: string[] = []; + for (const element of content) { + if (element.paragraph) parts.push(paragraphLine(element.paragraph, context)); + else if (element.table) { + const rows = tableGrid(tableCells(element, context), element.table.columns ?? 0).map((cells) => cells.join(" / ")); + parts.push(`[table: ${rows.join("; ")}]`); + } else if (element.tableOfContents) parts.push(cellText(element.tableOfContents.content ?? [], context)); + } + while (parts.length > 1 && parts[parts.length - 1] === "") parts.pop(); + return parts.join("\n"); +} + +function tableCells(element: RestStructuralElement, context: TabContext): TableCellText[][] { + return (element.table?.tableRows ?? []).map((row) => (row.tableCells ?? []).map((cell) => ({ + text: cellText(cell.content ?? [], context), + rowSpan: cell.tableCellStyle?.rowSpan, + columnSpan: cell.tableCellStyle?.columnSpan, + }))); +} + +function tableLines(element: RestStructuralElement, context: TabContext): string[] { + return markdownTable(tableCells(element, context), element.table?.columns ?? 0); +} + +export function renderContent(content: readonly RestStructuralElement[], context: TabContext): string[] { + const lines: string[] = []; + let afterTable = false; + for (const element of content) { + if (element.paragraph) { + const line = paragraphLine(element.paragraph, context); + if (afterTable && line !== "") lines.push(""); + lines.push(line); + afterTable = false; + } else if (element.table) { + if (lines.length > 0 && lines[lines.length - 1] !== "") lines.push(""); + lines.push(...tableLines(element, context)); + afterTable = true; + } else if (element.tableOfContents) { + lines.push("[Table of contents]", ...renderContent(element.tableOfContents.content ?? [], context)); + afterTable = false; + } else if (element.sectionBreak && indexOf(element.startIndex) > 0) { + lines.push("[section break]"); + afterTable = false; + } + } + return lines; +} + +function structure(content: readonly RestStructuralElement[]): DocsElementView[] { + const views: DocsElementView[] = []; + for (const element of content) { + const startIndex = indexOf(element.startIndex); + const endIndex = indexOf(element.endIndex); + if (element.paragraph) { + const style = element.paragraph.paragraphStyle?.namedStyleType; + const bullet = element.paragraph.bullet; + views.push({ + type: "paragraph", + startIndex, + endIndex, + text: paragraphRawText(element.paragraph), + ...(style && style !== "NORMAL_TEXT" ? { style } : {}), + ...(bullet ? { list: { listId: bullet.listId ?? "", nestingLevel: bullet.nestingLevel ?? 0 } } : {}), + }); + } else if (element.table) { + views.push({ + type: "table", + startIndex, + endIndex, + rows: element.table.rows ?? element.table.tableRows?.length ?? 0, + columns: element.table.columns ?? element.table.tableRows?.[0]?.tableCells?.length ?? 0, + cells: (element.table.tableRows ?? []).map((row) => (row.tableCells ?? []).map((cell) => { + const rowSpan = cell.tableCellStyle?.rowSpan; + const columnSpan = cell.tableCellStyle?.columnSpan; + return { + startIndex: indexOf(cell.startIndex), + endIndex: indexOf(cell.endIndex), + ...(rowSpan !== undefined && rowSpan !== 1 ? { rowSpan } : {}), + ...(columnSpan !== undefined && columnSpan !== 1 ? { columnSpan } : {}), + content: structure(cell.content ?? []), + }; + })), + }); + } else if (element.tableOfContents) { + views.push({ type: "tableOfContents", startIndex, endIndex, content: structure(element.tableOfContents.content ?? []) }); + } else if (element.sectionBreak) { + views.push({ type: "sectionBreak", startIndex, endIndex }); + } + } + return views; +} + +const HEADER_KINDS: Array<[keyof NonNullable, string]> = [ + ["defaultHeaderId", "default"], ["firstPageHeaderId", "first page"], ["evenPageHeaderId", "even pages"], + ["defaultFooterId", "default"], ["firstPageFooterId", "first page"], ["evenPageFooterId", "even pages"], +]; + +function segmentKind(tab: RestDocumentTab, id: string): string | undefined { + return HEADER_KINDS.find(([field]) => tab.documentStyle?.[field] === id)?.[1]; +} + +function flattenTabs(tabs: readonly RestTab[], path: string[] = []): Array<{ tab: RestTab; path: string[] }> { + return tabs.flatMap((tab) => { + const here = [...path, tab.tabProperties?.title || "Untitled tab"]; + return [{ tab, path: here }, ...flattenTabs(tab.childTabs ?? [], here)]; + }); +} + +function numericOrder(value: string | undefined): number { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : Number.MAX_SAFE_INTEGER; +} + +interface RenderedTab { + view: DocsTabView; + lines: string[]; +} + +function renderTab(tab: RestTab, tally: Tally): RenderedTab { + const documentTab = tab.documentTab ?? {}; + const context: TabContext = { tab: documentTab, tally, counters: new Map(), footnoteNumbers: new Map() }; + const lines = renderContent(documentTab.body?.content ?? [], context); + const segments = (kind: "Header" | "Footer", record: Record | undefined): DocsSegmentView[] => + Object.entries(record ?? {}).map(([id, segment]) => { + const label = segmentKind(documentTab, id); + const segmentLines = renderContent(segment.content ?? [], { ...context, counters: new Map() }); + while (segmentLines.length && segmentLines[segmentLines.length - 1] === "") segmentLines.pop(); + if (lines.length && lines[lines.length - 1] !== "") lines.push(""); + lines.push(`[${kind}${label ? ` (${label})` : ""}]`, ...segmentLines); + return { segmentId: id, ...(label ? { kind: label } : {}), content: structure(segment.content ?? []) }; + }); + const headers = segments("Header", documentTab.headers); + const footers = segments("Footer", documentTab.footers); + const footnoteEntries = Object.entries(documentTab.footnotes ?? {}) + .map(([id, segment]) => ({ id, segment, number: context.footnoteNumbers.get(id) })) + .sort((a, b) => numericOrder(a.number) - numericOrder(b.number)); + const footnotes = footnoteEntries.map(({ id, segment, number }) => { + const footnoteLines = renderContent(segment.content ?? [], { ...context, counters: new Map() }) + .map((line) => line.trim()).filter((line) => line !== ""); + if (lines.length && lines[lines.length - 1] !== "" && !lines[lines.length - 1]!.startsWith("[^")) lines.push(""); + lines.push(`[^${number ?? "?"}]: ${footnoteLines.join(" ")}`); + return { segmentId: id, ...(number ? { footnoteNumber: number } : {}), content: structure(segment.content ?? []) }; + }); + const properties = tab.tabProperties ?? {}; + return { + lines, + view: { + tabId: properties.tabId ?? "", + title: properties.title ?? "", + ...(properties.parentTabId ? { parentTabId: properties.parentTabId } : {}), + ...(properties.nestingLevel ? { nestingLevel: properties.nestingLevel } : {}), + body: structure(documentTab.body?.content ?? []), + headers, + footers, + footnotes, + }, + }; +} + +function trimBlankEdges(lines: string[]): string[] { + let start = 0; + let end = lines.length; + while (start < end && lines[start] === "") start += 1; + while (end > start && lines[end - 1] === "") end -= 1; + return lines.slice(start, end); +} + +export function tallyNotes(tally: Tally): string[] { + const notes: string[] = []; + if (tally.images) notes.push(`${plural(tally.images, "image is", "images are")} shown as [image] with its title or alt text; the picture itself is not included.`); + if (tally.drawings) notes.push(`${plural(tally.drawings, "drawing is", "drawings are")} shown as [drawing]; the Docs API does not return drawing content.`); + if (tally.charts) notes.push(`${plural(tally.charts, "chart is", "charts are")} shown as [chart]; chart data is not included.`); + if (tally.equations) notes.push(`${plural(tally.equations, "equation is", "equations are")} shown as [equation]; the Docs API does not return equation content.`); + if (tally.dropdowns) notes.push(`${plural(tally.dropdowns, "dropdown is", "dropdowns are")} shown as [dropdown]; the Docs API does not return the selected value.`); + return notes; +} + +export type SuggestionsView = "SUGGESTIONS_INLINE" | "PREVIEW_WITHOUT_SUGGESTIONS"; + +export interface RenderDocumentOptions { + commentsRequested?: boolean; + suggestionsView?: SuggestionsView; +} + +export const PREVIEW_NOTE = "Pending suggested edits are not shown: your access to this document does not include suggestions, so it was read in Google's PREVIEW_WITHOUT_SUGGESTIONS view. Google requires edits to be based on the SUGGESTIONS_INLINE view, so these indices may not be valid for update_doc."; +export const INLINE_NOTE = "Read in Google's SUGGESTIONS_INLINE view: pending suggested edits are included, marked {+inserted+} and {-deleted-}, and the indices are valid for update_doc."; +export const COMMENTS_UNAVAILABLE_NOTE = "Comments were asked for but are not available with your access to this document."; + +export function renderDocument(document: RestDocument, options: RenderDocumentOptions = {}): DocsContent { + const tally: Tally = { images: 0, drawings: 0, charts: 0, equations: 0, dropdowns: 0 }; + const flat = flattenTabs(document.tabs ?? []); + const rendered = flat.map(({ tab, path }) => ({ path, ...renderTab(tab, tally) })); + const sections = rendered.map(({ path, lines }) => { + const body = trimBlankEdges(lines); + return rendered.length > 1 ? [`=== Tab: ${path.join(" / ")} ===`, ...body] : body; + }); + const lines = sections.flatMap((section, index) => (index === 0 ? section : ["", ...section])); + const view = options.suggestionsView ?? "SUGGESTIONS_INLINE"; + const preview = view === "PREVIEW_WITHOUT_SUGGESTIONS"; + if (options.commentsRequested && preview) lines.push("", "[Comments]", "Not available with your access to this document."); + else if (options.commentsRequested) { + const comments = document.comments ?? []; + const tabTitles = new Map(); + for (const { tab, path } of flat) { + for (const anchorId of Object.keys(tab.documentTab?.commentAnchors ?? {})) tabTitles.set(anchorId, path.join(" / ")); + } + lines.push("", "[Comments]", ...(comments.length + ? renderComments(comments, (thread) => (flat.length > 1 && thread.anchorId ? tabTitles.get(thread.anchorId) : undefined)) + : ["No comments."])); + } + const notes = [preview ? PREVIEW_NOTE : INLINE_NOTE, ...(preview && options.commentsRequested ? [COMMENTS_UNAVAILABLE_NOTE] : []), ...tallyNotes(tally)]; + return { + documentId: document.documentId ?? "", + title: document.title ?? "", + ...(document.revisionId ? { revisionId: document.revisionId } : {}), + suggestionsViewMode: view, + text: trimBlankEdges(lines).join("\n"), + tabs: rendered.map(({ view }) => view), + notes, + }; +} diff --git a/server/src/google-workspace-rest-tools/docs/request-kinds.test.ts b/server/src/google-workspace-rest-tools/docs/request-kinds.test.ts new file mode 100644 index 00000000000..b98ef341678 --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/request-kinds.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vitest"; +import { fakeGoogle, json } from "../fixtures/fake-google.js"; +import { createGoogleHttp } from "../google-http.js"; +import { DOCS_REQUEST_KINDS } from "./request-kinds.js"; +import { updateDoc } from "./update-doc.js"; + +const REVISION = { requiredRevisionId: "rev-1" }; +const rules = Object.entries(DOCS_REQUEST_KINDS); +const allowed = rules.flatMap(([kind, rule]) => (rule.allowed ? [[kind, rule.example ?? {}] as const] : [])); +const refused = rules.flatMap(([kind, rule]) => (rule.allowed ? [] : [[kind, rule.reason] as const])); + +async function send(requests: Array>) { + const { fetch, calls } = fakeGoogle(() => json({ replies: requests.map(() => ({})), writeControl: { requiredRevisionId: "rev-2" } })); + const result = await updateDoc.call({ documentId: "d", requests, writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + return { result, calls, text: (result.content[0] as { text: string }).text }; +} + +describe("update_doc request kinds", () => { + it("classifies every kind in Google's REST and MCP references explicitly: allowed, allowed in a restricted form, or refused", () => { + const restKinds = [ + "replaceAllText", "insertText", "updateTextStyle", "createParagraphBullets", "deleteParagraphBullets", "createNamedRange", "deleteNamedRange", + "updateParagraphStyle", "deleteContentRange", "insertInlineImage", "insertTable", "insertTableRow", "insertTableColumn", "deleteTableRow", + "deleteTableColumn", "insertPageBreak", "deletePositionedObject", "updateTableColumnProperties", "updateTableCellStyle", "updateTableRowStyle", + "replaceImage", "updateDocumentStyle", "mergeTableCells", "unmergeTableCells", "createHeader", "createFooter", "createFootnote", + "replaceNamedRangeContent", "updateSectionStyle", "insertSectionBreak", "deleteHeader", "deleteFooter", "pinTableHeaderRows", "addDocumentTab", + "deleteTab", "updateDocumentTabProperties", "insertPerson", "updateNamedStyle", "insertRichLink", "insertDate", "insertComment", + "addCommentReply", "updateCommentPost", "deleteComment", "deleteCommentReply", "acceptSuggestion", "rejectSuggestion", "deleteSuggestion", + "createDropdownDefinition", "updateDropdownDefinitionProperties", "insertDropdown", "updateDropdownProperties", "deleteDropdownDefinition", + ]; + const mcpKinds = [ + "replaceAllText", "insertText", "updateTextStyle", "updateParagraphStyle", "updateNamedStyle", "updateSectionStyle", "updateDocumentStyle", + "createParagraphBullets", "deleteParagraphBullets", "createNamedRange", "deleteNamedRange", "replaceNamedRangeContent", "deleteContentRange", + "insertInlineImage", "insertTable", "insertPageBreak", "insertSectionBreak", "insertPerson", "insertRichLink", "insertDate", "createFootnote", + "insertTableRow", "insertTableColumn", "deleteTableRow", "deleteTableColumn", "updateTableColumnProperties", "updateTableCellStyle", + "updateTableRowStyle", "mergeTableCells", "unmergeTableCells", "pinTableHeaderRows", "replaceImage", "deletePositionedObject", "createHeader", + "createFooter", "deleteHeader", "deleteFooter", "addDocumentTab", "deleteTab", "updateDocumentTabProperties", "insertComment", + "addCommentReply", "updateCommentPost", "deleteComment", "deleteCommentReply", "acceptSuggestion", "rejectSuggestion", "deleteSuggestion", + ]; + expect(rules.map(([kind]) => kind).sort()).toEqual([...new Set([...restKinds, ...mcpKinds])].sort()); + const restricted = rules.filter(([, rule]) => rule.allowed && rule.refuse).map(([kind]) => kind).sort(); + expect(restricted).toEqual(["insertInlineImage", "replaceImage"]); + expect(refused.map(([kind]) => kind)).toEqual(["insertRichLink"]); + }); + + it.each(allowed)("passes %s through unchanged", async (kind, body) => { + const request = { [kind]: body }; + const { result, calls } = await send([request]); + expect(result.isError).toBeUndefined(); + expect((calls[0]!.body as { requests: unknown[] }).requests).toEqual([request]); + }); + + it.each(refused)("refuses %s and sends nothing", async (kind, reason) => { + const { result, calls, text } = await send([{ insertText: { text: "a", location: { index: 1 } } }, { [kind]: {} }]); + expect(result.isError).toBe(true); + expect(text).toBe(`requests[1].${kind} ${reason} This tool only changes the one file it is given, so nothing was changed.`); + expect(calls).toHaveLength(0); + }); + + it.each([ + ["insertInlineImage", { uri: "https://drive.google.com/uc?id=file-1", location: { index: 1 } }, "uri"], + ["replaceImage", { imageObjectId: "kix.img1", uri: "https://docs.google.com/drawings/d/x/export/png" }, "uri"], + ])("refuses %s with a picture from another Google file, and sends nothing", async (kind, body, field) => { + const { calls, text } = await send([{ [kind]: body }]); + expect(text).toContain(`requests[0].${kind} takes its picture from a Google Drive or Docs link (${field}), which is another file.`); + expect(calls).toHaveLength(0); + }); + + it.each(["copyDocument", "deleteDocument", "insertAudio", "futureRequestKind"])("refuses the unknown kind %s and sends nothing", async (kind) => { + const { calls, text } = await send([{ [kind]: {} }]); + expect(text).toBe(`requests[0].${kind} is not a request kind this tool accepts. This tool only changes the one file it is given, so nothing was changed.`); + expect(calls).toHaveLength(0); + }); + + it("lists the accepted and refused kinds in the tool description from the same table", () => { + const description = updateDoc.definition.description!; + for (const [kind] of allowed) expect(description).toContain(kind); + expect(description).toContain(`Refused because they read another file: ${refused.map(([kind]) => kind).join(", ")}.`); + }); +}); diff --git a/server/src/google-workspace-rest-tools/docs/request-kinds.ts b/server/src/google-workspace-rest-tools/docs/request-kinds.ts new file mode 100644 index 00000000000..38e4dc96d72 --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/request-kinds.ts @@ -0,0 +1,59 @@ +import { refuseGoogleFileUrl, type RequestKindRules } from "../documents-shared.js"; + +const allow = { allowed: true } as const; + +export const DOCS_REQUEST_KINDS: RequestKindRules = { + replaceAllText: allow, + insertText: allow, + updateTextStyle: allow, + createParagraphBullets: allow, + deleteParagraphBullets: allow, + createNamedRange: allow, + deleteNamedRange: allow, + updateParagraphStyle: allow, + deleteContentRange: allow, + insertInlineImage: { allowed: true, refuse: refuseGoogleFileUrl("uri"), example: { uri: "https://example.test/logo.png", location: { index: 1 } } }, + insertTable: allow, + insertTableRow: allow, + insertTableColumn: allow, + deleteTableRow: allow, + deleteTableColumn: allow, + insertPageBreak: allow, + deletePositionedObject: allow, + updateTableColumnProperties: allow, + updateTableCellStyle: allow, + updateTableRowStyle: allow, + replaceImage: { allowed: true, refuse: refuseGoogleFileUrl("uri"), example: { imageObjectId: "kix.img1", uri: "https://example.test/logo.png" } }, + updateDocumentStyle: allow, + mergeTableCells: allow, + unmergeTableCells: allow, + createHeader: allow, + createFooter: allow, + createFootnote: allow, + replaceNamedRangeContent: allow, + updateSectionStyle: allow, + insertSectionBreak: allow, + deleteHeader: allow, + deleteFooter: allow, + pinTableHeaderRows: allow, + addDocumentTab: allow, + deleteTab: allow, + updateDocumentTabProperties: allow, + insertPerson: allow, + updateNamedStyle: allow, + insertDate: allow, + insertComment: allow, + addCommentReply: allow, + updateCommentPost: allow, + deleteComment: allow, + deleteCommentReply: allow, + acceptSuggestion: allow, + rejectSuggestion: allow, + deleteSuggestion: allow, + createDropdownDefinition: allow, + updateDropdownDefinitionProperties: allow, + insertDropdown: allow, + updateDropdownProperties: allow, + deleteDropdownDefinition: allow, + insertRichLink: { allowed: false, reason: "inserts a smart chip that points to another file and shows its title, so it reads another file." }, +}; diff --git a/server/src/google-workspace-rest-tools/docs/update-doc.test.ts b/server/src/google-workspace-rest-tools/docs/update-doc.test.ts new file mode 100644 index 00000000000..3fd020ca5b0 --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/update-doc.test.ts @@ -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 { updateDoc, updateDocRequest } from "./update-doc.js"; + +const REVISION = { requiredRevisionId: "rev-7" }; + +type Edit = { insertText?: { text: string; location: { index: number } }; deleteContentRange?: { range: { startIndex: number; endIndex: number } } }; + +function applyInOrder(body: string, requests: Edit[]): string { + let current = body; + for (const request of requests) { + if (request.insertText) { + const at = request.insertText.location.index - 1; + current = current.slice(0, at) + request.insertText.text + current.slice(at); + } else if (request.deleteContentRange) { + const { startIndex, endIndex } = request.deleteContentRange.range; + current = current.slice(0, startIndex - 1) + current.slice(endIndex - 1); + } + } + return current; +} + +function body(call: { body: unknown }): { requests: Edit[]; writeControl: Record } { + return call.body as { requests: Edit[]; writeControl: Record }; +} + +describe("update_doc request", () => { + it("posts the requests unchanged and in order, with the revision the caller read", () => { + const requests = [ + { insertText: { text: "!", location: { index: 12 } } }, + { updateTextStyle: { range: { startIndex: 1, endIndex: 6 }, textStyle: { bold: true }, fields: "bold" } }, + { replaceAllText: { containsText: { text: "draft", matchCase: true }, replaceText: "final" } }, + ]; + expect(updateDocRequest({ documentId: "doc-1", requests, writeControl: REVISION })).toEqual({ + method: "POST", + host: "docs.googleapis.com", + path: "/v1/documents/doc-1:batchUpdate", + body: { requests, writeControl: { requiredRevisionId: "rev-7" } }, + }); + }); + + it.each(["EDIT", "SUGGEST", "WRITE_MODE_UNSPECIFIED"] as const)("passes writeMode %s through", (writeMode) => { + const request = updateDocRequest({ documentId: "d", requests: [{ insertText: { text: "a", location: { index: 1 } } }], writeControl: { ...REVISION, writeMode } }); + expect((request.body as { writeControl: unknown }).writeControl).toEqual({ requiredRevisionId: "rev-7", writeMode }); + }); + + it.each([ + ["no writeControl", undefined, /writeControl\.requiredRevisionId is required/], + ["an empty writeControl", {}, /writeControl\.requiredRevisionId is required/], + ["only a write mode", { writeMode: "EDIT" as const }, /writeControl\.requiredRevisionId is required/], + ["targetRevisionId", { targetRevisionId: "rev-7" }, /targetRevisionId is not supported/], + ["both revision fields", { requiredRevisionId: "rev-7", targetRevisionId: "rev-7" }, /targetRevisionId is not supported/], + ])("refuses %s", (_name, writeControl, message) => { + expect(() => updateDocRequest({ documentId: "d", requests: [{ insertText: { text: "a", location: { index: 1 } } }], writeControl })).toThrow(message); + }); +}); + +describe("update_doc edit order", () => { + const read = "Hello world."; + const fromOneRead: Edit[] = [ + { insertText: { text: " and goodbye", location: { index: 12 } } }, + { deleteContentRange: { range: { startIndex: 7, endIndex: 8 } } }, + { insertText: { text: "Well, ", location: { index: 1 } } }, + ]; + + it("applies edits made from one read correctly when they go from the highest index to the lowest, as the description says", () => { + expect(applyInOrder(read, fromOneRead)).toBe("Well, Hello orld and goodbye."); + expect(applyInOrder(read, [...fromOneRead].reverse())).not.toBe("Well, Hello orld and goodbye."); + }); + + it("sends several edits in one call, exactly in the caller's order, in a single request", async () => { + const { fetch, calls } = fakeGoogle(() => json({ documentId: "d", replies: [{}, {}, {}], writeControl: { requiredRevisionId: "rev-8" } })); + const result = await updateDoc.call({ documentId: "d", requests: fromOneRead, writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls).toHaveLength(1); + expect(body(calls[0]!).requests).toEqual(fromOneRead); + expect(applyInOrder(read, body(calls[0]!).requests)).toBe("Well, Hello orld and goodbye."); + expect(result.structuredContent).toEqual({ replies: [{}, {}, {}], writeControl: { requiredRevisionId: "rev-8" } }); + }); + + it("keeps dependent edits in order: an insertion and then styling of the inserted text", async () => { + const requests = [ + { insertText: { text: "Title\n", location: { index: 1 } } }, + { updateParagraphStyle: { range: { startIndex: 1, endIndex: 7 }, paragraphStyle: { namedStyleType: "HEADING_1" }, fields: "namedStyleType" } }, + ]; + const { fetch, calls } = fakeGoogle(() => json({ replies: [{}, {}], writeControl: { requiredRevisionId: "rev-8" } })); + await updateDoc.call({ documentId: "d", requests, writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect(body(calls[0]!).requests.map((request) => Object.keys(request)[0])).toEqual(["insertText", "updateParagraphStyle"]); + }); +}); + +describe("update_doc tool", () => { + it("returns a clear error and changes nothing when the document changed since it was read", async () => { + const { fetch, calls } = fakeGoogle(() => json({ error: { code: 400, status: "INVALID_ARGUMENT", message: "The required revision ID 'rev-7' does not match the latest revision." } }, 400)); + const result = await updateDoc.call({ documentId: "d", requests: [{ insertText: { text: "a", location: { index: 1 } } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls).toHaveLength(1); + expect(result).toEqual({ + isError: true, + content: [{ type: "text", text: "The document is no longer at the revision you read (or that revision ID is not valid), so nothing was changed. Read it again with read_doc and retry with its new revisionId." }], + }); + }); + + it.each([ + ["FAILED_PRECONDITION", { code: 400, status: "FAILED_PRECONDITION", message: "Precondition check failed." }, 400], + ["a revision reason in the details", { code: 400, status: "INVALID_ARGUMENT", message: "Request failed.", details: [{ "@type": "type.googleapis.com/google.rpc.ErrorInfo", reason: "REVISION_MISMATCH" }] }, 400], + ["ABORTED on 409", { code: 409, status: "ABORTED", message: "Aborted." }, 409], + ])("recognizes a conflict from Google's structured %s", async (_name, error, status) => { + const { fetch } = fakeGoogle(() => json({ error }, status)); + const result = await updateDoc.call({ documentId: "d", requests: [{ insertText: { text: "a", location: { index: 1 } } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect((result.content[0] as { text: string }).text).toMatch(/^The document is no longer at the revision you read/); + }); + + it("does not call a 400 that only mentions revisions a conflict", async () => { + const { fetch } = fakeGoogle(() => json({ error: { code: 400, status: "INVALID_ARGUMENT", message: "Invalid requests[0].updateDocumentStyle: revisions of the page size are not allowed." } }, 400)); + const result = await updateDoc.call({ documentId: "d", requests: [{ updateDocumentStyle: {} }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect((result.content[0] as { text: string }).text).toBe("Invalid requests[0].updateDocumentStyle: revisions of the page size are not allowed."); + }); + + it("passes other rejections through with Google's message", async () => { + const { fetch } = fakeGoogle(() => json({ error: { code: 400, message: "Invalid requests[0].insertText: Index 99 must be less than the end index of the referenced segment, 12." } }, 400)); + const result = await updateDoc.call({ documentId: "d", requests: [{ insertText: { text: "a", location: { index: 99 } } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect((result.content[0] as { text: string }).text).toBe("Invalid requests[0].insertText: Index 99 must be less than the end index of the referenced segment, 12."); + }); + + it.each([ + ["a server error", () => json({ error: { code: 503 } }, 503)], + ["a dropped connection", () => { throw new TypeError("fetch failed"); }], + ])("never retries the write after %s and warns that it may have happened", async (_name, answer) => { + const { fetch, calls } = fakeGoogle(answer); + const result = await updateDoc.call({ documentId: "d", requests: [{ insertText: { text: "a", location: { index: 1 } } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 })); + expect(calls).toHaveLength(1); + expect(result.isError).toBe(true); + expect((result.content[0] as { text: string }).text).toMatch(/may or may not have been made/); + }); + + it.each([ + ["no requests", { documentId: "d", writeControl: REVISION }], + ["an empty request list", { documentId: "d", requests: [], writeControl: REVISION }], + ["a request with two kinds", { documentId: "d", requests: [{ insertText: {}, deleteContentRange: {} }], writeControl: REVISION }], + ["a request with no kind", { documentId: "d", requests: [{}], writeControl: REVISION }], + ["a request that is not an object", { documentId: "d", requests: ["insertText"], writeControl: REVISION }], + ["a bad document ID", { documentId: "../d", requests: [{ insertText: {} }], writeControl: REVISION }], + ["no revision", { documentId: "d", requests: [{ insertText: {} }] }], + ["a target revision", { documentId: "d", requests: [{ insertText: {} }], writeControl: { targetRevisionId: "r" } }], + ["an unknown write mode", { documentId: "d", requests: [{ insertText: {} }], writeControl: { ...REVISION, writeMode: "FORCE" } }], + ["too many requests", { documentId: "d", requests: Array.from({ length: 501 }, () => ({ insertText: {} })), writeControl: REVISION }], + ])("sends nothing for %s", async (_name, input) => { + const { fetch, calls } = fakeGoogle(() => json({})); + expect((await updateDoc.call(input, createGoogleHttp({ accessToken: "t", fetch }))).isError).toBe(true); + expect(calls).toHaveLength(0); + }); +}); diff --git a/server/src/google-workspace-rest-tools/docs/update-doc.ts b/server/src/google-workspace-rest-tools/docs/update-doc.ts new file mode 100644 index 00000000000..39ffc9e732f --- /dev/null +++ b/server/src/google-workspace-rest-tools/docs/update-doc.ts @@ -0,0 +1,97 @@ +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import { allowedKinds, assertRequestKinds, batchRequestArg, fileIdArg, MAX_BATCH_REQUESTS, refusedKinds, revisionIdArg, sendBatchUpdate } from "../documents-shared.js"; +import { GoogleToolError } from "../errors.js"; +import type { GoogleRequest } from "../google-http.js"; +import { compact, defineTool, structuredResult } from "../tool.js"; +import { DOCS_HOST, documentPath, type RestBatchUpdateResponse } from "./document.js"; +import { DOCS_REQUEST_KINDS } from "./request-kinds.js"; + +const WRITE_MODES = ["WRITE_MODE_UNSPECIFIED", "EDIT", "SUGGEST"] as const; + +const args = z.object({ + documentId: fileIdArg("Docs document"), + requests: z.array(batchRequestArg).min(1).max(MAX_BATCH_REQUESTS), + writeControl: z.object({ + requiredRevisionId: revisionIdArg.optional(), + targetRevisionId: z.string().max(1024).optional(), + writeMode: z.enum(WRITE_MODES).optional(), + }).optional(), +}); +export type UpdateDocArgs = z.infer; + +export function updateDocRequest(input: UpdateDocArgs): GoogleRequest { + assertRequestKinds(input.requests, DOCS_REQUEST_KINDS); + const control = input.writeControl ?? {}; + if (control.targetRevisionId !== undefined) { + throw new GoogleToolError("invalid_argument", "targetRevisionId is not supported because it can apply edits to a newer version than the one you read. Pass writeControl.requiredRevisionId from read_doc instead. Nothing was changed."); + } + if (!control.requiredRevisionId) { + throw new GoogleToolError("invalid_argument", "writeControl.requiredRevisionId is required: pass content.revisionId from read_doc, so the edit is applied only to the version you read. Nothing was changed."); + } + return { + method: "POST", + host: DOCS_HOST, + path: `${documentPath(input.documentId)}:batchUpdate`, + body: { + requests: input.requests, + writeControl: compact({ requiredRevisionId: control.requiredRevisionId, writeMode: control.writeMode }), + }, + }; +} + +export function updateDocResult(response: RestBatchUpdateResponse): CallToolResult { + return structuredResult({ replies: response.replies ?? [], writeControl: response.writeControl ?? {} }); +} + +export const updateDoc = defineTool({ + definition: { + name: "update_doc", + description: [ + "Edits an existing Google Doc with a list of Docs API batchUpdate requests (for example insertText, deleteContentRange, replaceAllText, updateTextStyle, updateParagraphStyle, createParagraphBullets, insertTable or insertInlineImage), and returns one reply per request.", + "Requests are applied in the order given, all or none: if any request is invalid, nothing is changed.", + "The requests can delete or replace content in this one document, for example deleteContentRange, replaceAllText or deleteTab. This tool cannot create, delete, move, copy or share files.", + `Accepted request kinds: ${allowedKinds(DOCS_REQUEST_KINDS).join(", ")}. Images are accepted only from links outside drive.google.com and docs.google.com.`, + `Refused because they read another file: ${refusedKinds(DOCS_REQUEST_KINDS).join(", ")}. Any other kind is refused too.`, + "Each request sees the document as changed by the requests before it, so indices after an insertion or deletion move. When making several edits by index from one read_doc result, order them from the highest index to the lowest.", + "Indices are UTF-16 code units from read_doc's content.tabs; the body starts at index 1. Pass tabId in locations and ranges to edit a tab other than the first.", + "writeControl.requiredRevisionId is required: pass content.revisionId from read_doc. If the document changed since, nothing is changed and you must read it again. The new revision ID is returned in writeControl.", + ].join(" "), + inputSchema: { + type: "object", + properties: { + documentId: { type: "string", description: "Required. The ID of the document to edit." }, + requests: { + type: "array", + items: { type: "object", additionalProperties: true }, + description: "Required. Docs API batchUpdate requests, each an object with exactly one request kind, such as {\"insertText\": {\"text\": \"Hello\", \"location\": {\"index\": 1}}}. See https://developers.google.com/workspace/docs/api/reference/rest/v1/documents/request.", + }, + writeControl: { + type: "object", + properties: { + requiredRevisionId: { type: "string", description: "Required. The revisionId from read_doc. If the document is no longer at this revision, nothing is changed." }, + targetRevisionId: { type: "string", description: "Not supported: use requiredRevisionId." }, + writeMode: { type: "string", enum: [...WRITE_MODES], description: "Optional. EDIT (default) applies the changes; SUGGEST makes them as suggestions." }, + }, + required: ["requiredRevisionId"], + description: "Required. Controls how the edit is applied.", + }, + }, + required: ["documentId", "requests", "writeControl"], + }, + outputSchema: { + type: "object", + properties: { + replies: { type: "array", items: { type: "object" }, description: "One reply per request, in order; some are empty." }, + writeControl: { type: "object", description: "The document's revision after the edit, as requiredRevisionId." }, + }, + required: ["replies", "writeControl"], + }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, + }, + args, + async run(input, http) { + const request = updateDocRequest(input); + return updateDocResult(await sendBatchUpdate(http, request, "document", "read_doc")); + }, +}); diff --git a/server/src/google-workspace-rest-tools/documents-shared.test.ts b/server/src/google-workspace-rest-tools/documents-shared.test.ts new file mode 100644 index 00000000000..ce2eb51bc5d --- /dev/null +++ b/server/src/google-workspace-rest-tools/documents-shared.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "vitest"; +import { assertRequestKinds, escapeTableCell, googleFileUrl, isRevisionConflict, markdownTable, refuseGoogleFileUrl, tableGrid, type RequestKindRules } from "./documents-shared.js"; +import { GoogleToolError, type GoogleErrorDetail } from "./errors.js"; + +describe("revision conflicts", () => { + it.each([ + ["status FAILED_PRECONDITION with an unrelated message", 400, "Precondition check failed.", { status: "FAILED_PRECONDITION" }, true], + ["status ABORTED on 409", 409, "Aborted.", { status: "ABORTED" }, true], + ["a revision reason in the details", 400, "Request failed.", { status: "INVALID_ARGUMENT", reasons: ["REVISION_MISMATCH"] }, true], + ["a legacy conditionNotMet reason", 400, "Request failed.", { reasons: ["conditionNotMet"] }, true], + ["only the message, as a fallback", 400, "The required revision ID 'r1' does not match the latest revision.", { status: "INVALID_ARGUMENT" }, true], + ["a message that names the revision ID, with no structured fields", 400, "Invalid revision ID.", {}, true], + ["an unrelated invalid request", 400, "Invalid requests[0].insertText: Index 99 must be less than the end index.", { status: "INVALID_ARGUMENT" }, false], + ["an unrelated message that only mentions revisions", 400, "Invalid requests[0]: revisions of this kind are not allowed.", { status: "INVALID_ARGUMENT" }, false], + ["a 413", 413, "Too large: required revision", { status: "FAILED_PRECONDITION" }, false], + ] as const)("%s: %s", (_name, httpStatus, message, google, expected) => { + const error = new GoogleToolError("invalid_argument", message, httpStatus, google as GoogleErrorDetail); + expect(isRevisionConflict(error)).toBe(expected); + }); + + it("never treats other kinds of failure as a conflict", () => { + expect(isRevisionConflict(new GoogleToolError("permission_denied", "required revision", 403, { status: "FAILED_PRECONDITION" }))).toBe(false); + expect(isRevisionConflict(new GoogleToolError("unavailable", "x", 503))).toBe(false); + }); +}); + +describe("request kinds", () => { + const rules: RequestKindRules = { + insertText: { allowed: true }, + createImage: { allowed: true, refuse: refuseGoogleFileUrl("url") }, + createSheetsChart: { allowed: false, reason: "reads another file." }, + }; + + it("names every refused request by position, and says nothing was changed", () => { + expect(() => assertRequestKinds([{ insertText: {} }, { createSheetsChart: {} }, { mystery: {} }, { createImage: { url: "https://drive.google.com/uc?id=f1" } }], rules)) + .toThrow("requests[1].createSheetsChart reads another file. requests[2].mystery is not a request kind this tool accepts. requests[3].createImage takes its picture from a Google Drive or Docs link (url), which is another file. This tool only changes the one file it is given, so nothing was changed."); + }); + + it("refuses kinds named like object properties, and accepts allowed forms", () => { + expect(() => assertRequestKinds([{ toString: {} }], rules)).toThrow(/requests\[0\]\.toString is not a request kind/); + expect(() => assertRequestKinds([{ constructor: {} }], rules)).toThrow(/requests\[0\]\.constructor is not a request kind/); + expect(() => assertRequestKinds([{ insertText: {} }, { createImage: { url: "https://example.test/a.png" } }, { createImage: "x" }], rules)).not.toThrow(); + }); + + it.each([ + ["https://drive.google.com/file/d/f1/view", true], + ["https://DOCS.google.com/document/d/x", true], + ["https://lh3.googleusercontent.com/abc", false], + ["https://example.test/drive.google.com.png", false], + ["not a url", false], + [42, false], + ])("treats %s as a Google file link: %s", (value, expected) => { + expect(googleFileUrl(value)).toBe(expected); + }); +}); + +describe("table grid", () => { + it("pads short rows, widens for spans past the stated width, and stops row spans at the last row", () => { + expect(tableGrid([[{ text: "a" }], [{ text: "b", columnSpan: 3, rowSpan: 4 }]], 2)).toEqual([ + ["a", "", ""], + ["b", "(merged left)", "(merged left)"], + ]); + }); + + it("places cells by their column when given", () => { + expect(tableGrid([[{ text: "z", column: 2 }, { text: "x", column: 0 }]], 3)).toEqual([["x", "", "z"]]); + }); + + it("places cells by their row when given", () => { + expect(tableGrid([[{ text: "top", column: 0 }], [{ text: "moved", row: 0, column: 1 }, { text: "own", column: 0 }]], 2)).toEqual([["top", "moved"], ["own", ""]]); + }); + + it.each([ + ["a|b", "a\\|b"], + ["c\\d", "c\\\\d"], + ["ends\\", "ends\\\\"], + ["e\\|f", "e\\\\\\|f"], + ["g\nh\r\ni", "g
h
i"], + ])("escapes the table cell %j once as %j", (raw, escaped) => { + expect(escapeTableCell(raw)).toBe(escaped); + expect(markdownTable([[{ text: raw }, { text: "z" }]], 2)[0]).toBe(`| ${escaped} | z |`); + }); + + it("renders an empty table", () => { + expect(markdownTable([], 0)).toEqual(["[empty table]"]); + }); +}); diff --git a/server/src/google-workspace-rest-tools/documents-shared.ts b/server/src/google-workspace-rest-tools/documents-shared.ts new file mode 100644 index 00000000000..901a4f45775 --- /dev/null +++ b/server/src/google-workspace-rest-tools/documents-shared.ts @@ -0,0 +1,191 @@ +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, MAX_RESULT_BYTES } from "./tool.js"; + +export const MAX_BATCH_REQUESTS = 500; +export const OBJECT_PLACEHOLDER = ""; + +export const fileIdArg = (kind: string) => z.string().regex(/^[A-Za-z0-9_-]{1,256}$/, `Must be a Google ${kind} ID`); +export const revisionIdArg = z.string().min(1).max(1024); + +export const batchRequestArg = z.record(z.string(), z.unknown()).refine( + (value) => Object.keys(value).length === 1, + "Each request must name exactly one kind of update, such as insertText", +); + +export function sizedResult(value: Record, what: string, hint: string): CallToolResult { + return boundedStructuredResult(value, MAX_RESULT_BYTES, (bytes) => + `This ${what} is too large to return in one result (${Math.ceil(bytes / 1000)} KB; the limit is ${MAX_RESULT_BYTES / 1000} KB). Nothing was returned. ${hint}`); +} + +const CONFLICT_STATUSES = new Set(["FAILED_PRECONDITION", "ABORTED"]); +const CONFLICT_REASON = /REVISION|CONDITION_NOT_MET|conditionNotMet/i; +const CONFLICT_MESSAGE = /\brequired revision\b|\brevision id\b|\blatest revision\b/i; + +export function isRevisionConflict(error: GoogleToolError): boolean { + if (error.kind !== "invalid_argument" || (error.httpStatus !== 400 && error.httpStatus !== 409)) return false; + if (error.google.status && CONFLICT_STATUSES.has(error.google.status)) return true; + if ((error.google.reasons ?? []).some((reason) => CONFLICT_REASON.test(reason))) return true; + return CONFLICT_MESSAGE.test(error.message); +} + +export type RequestKindRule = + | { allowed: true; refuse?: (body: Record) => string | undefined; example?: Record } + | { allowed: false; reason: string }; + +export type RequestKindRules = Readonly>; + +const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); +const GOOGLE_FILE_HOSTS = new Set(["drive.google.com", "docs.google.com"]); + +export function googleFileUrl(value: unknown): boolean { + if (typeof value !== "string") return false; + try { + return GOOGLE_FILE_HOSTS.has(new URL(value).hostname.toLowerCase()); + } catch { + return false; + } +} + +export const refuseGoogleFileUrl = (...path: string[]) => (body: Record): string | undefined => { + let value: unknown = body; + for (const key of path) value = isRecord(value) ? value[key] : undefined; + return googleFileUrl(value) ? `takes its picture from a Google Drive or Docs link (${path.join(".")}), which is another file.` : undefined; +}; + +export function allowedKinds(rules: RequestKindRules): string[] { + return Object.entries(rules).filter(([, rule]) => rule.allowed).map(([kind]) => kind); +} + +export function refusedKinds(rules: RequestKindRules): string[] { + return Object.entries(rules).filter(([, rule]) => !rule.allowed).map(([kind]) => kind); +} + +export function assertRequestKinds(requests: ReadonlyArray>, rules: RequestKindRules): void { + const problems: string[] = []; + for (const [index, request] of requests.entries()) { + const kind = Object.keys(request)[0]!; + const rule = Object.hasOwn(rules, kind) ? rules[kind] : undefined; + if (!rule) problems.push(`requests[${index}].${kind} is not a request kind this tool accepts.`); + else if (!rule.allowed) problems.push(`requests[${index}].${kind} ${rule.reason}`); + else { + const body = request[kind]; + const reason = rule.refuse?.(isRecord(body) ? body : {}); + if (reason) problems.push(`requests[${index}].${kind} ${reason}`); + } + } + if (problems.length) { + throw new GoogleToolError("invalid_argument", `${problems.join(" ")} This tool only changes the one file it is given, so nothing was changed.`); + } +} + +export interface TableCellText { + text: string; + rowSpan?: number; + columnSpan?: number; + row?: number; + column?: number; +} + +export const MERGED_LEFT = "(merged left)"; +export const MERGED_UP = "(merged up)"; + +const span = (value: number | undefined) => (value !== undefined && value > 1 ? Math.floor(value) : 1); + +export function tableGrid(rows: readonly (readonly TableCellText[])[], columns: number): string[][] { + const grid: Array> = rows.map(() => []); + for (const [listedRow, cells] of rows.entries()) { + const positional = cells.length === columns && cells.every((cell) => cell.column === undefined); + let column = 0; + for (const [cellIndex, cell] of cells.entries()) { + const rowIndex = cell.row !== undefined && cell.row >= 0 && cell.row < rows.length ? cell.row : listedRow; + if (positional) column = cellIndex; + else if (cell.column !== undefined) column = cell.column; + else while (grid[rowIndex]![column] !== undefined) column += 1; + if (positional && grid[rowIndex]![column] !== undefined && cell.text === "") continue; + grid[rowIndex]![column] = cell.text; + for (let down = 0; down < span(cell.rowSpan) && rowIndex + down < rows.length; down += 1) { + for (let across = 0; across < span(cell.columnSpan); across += 1) { + if (down === 0 && across === 0) continue; + grid[rowIndex + down]![column + across] = down === 0 ? MERGED_LEFT : MERGED_UP; + } + } + column += span(cell.columnSpan); + } + } + const width = Math.max(columns, ...grid.map((row) => row.length)); + return grid.map((row) => Array.from({ length: width }, (_, index) => row[index] ?? "")); +} + +export function escapeTableCell(text: string): string { + return text.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r?\n/g, "
"); +} + +export function markdownTable(rows: readonly (readonly TableCellText[])[], columns: number): string[] { + if (rows.length === 0) return ["[empty table]"]; + const grid = tableGrid(rows, columns).map((cells) => cells.map(escapeTableCell)); + const lines = grid.map((cells) => `| ${cells.join(" | ")} |`); + return [lines[0]!, `| ${grid[0]!.map(() => "---").join(" | ")} |`, ...lines.slice(1)]; +} + +export async function readWithComments(http: GoogleHttp, request: GoogleRequest, plain: GoogleRequest | undefined, unavailable: string): Promise { + try { + return await http.send(request); + } catch (error) { + if (!plain || !(error instanceof GoogleToolError) || error.kind !== "permission_denied") throw error; + await http.send(plain); + throw new GoogleToolError("permission_denied", unavailable, error.httpStatus); + } +} + +export async function sendBatchUpdate(http: GoogleHttp, request: GoogleRequest, what: string, readTool: string): Promise { + try { + return await http.send(request); + } catch (error) { + if (error instanceof GoogleToolError && isRevisionConflict(error)) { + throw new GoogleToolError( + "invalid_argument", + `The ${what} is no longer at the revision you read (or that revision ID is not valid), so nothing was changed. Read it again with ${readTool} and retry with its new revisionId.`, + error.httpStatus, + ); + } + throw error; + } +} + +export interface RestCommentPost { + content?: string; + author?: { displayName?: string; anonymous?: boolean }; + deleted?: boolean; +} + +export interface RestCommentThread { + commentId?: string; + anchorId?: string; + status?: string; + plainTextQuote?: string; + headPost?: RestCommentPost; + replies?: RestCommentPost[]; +} + +function postLine(post: RestCommentPost): string { + if (post.deleted) return "(deleted)"; + const author = post.author?.displayName || (post.author?.anonymous ? "Anonymous" : "Unknown author"); + return `${author}: ${(post.content ?? "").replace(/\s*\n\s*/g, " ").trim()}`; +} + +export function renderComments(threads: readonly RestCommentThread[], where: (thread: RestCommentThread) => string | undefined): string[] { + return threads.map((thread) => { + const place = where(thread); + const quote = thread.plainTextQuote ? ` on "${thread.plainTextQuote.replace(/\s+/g, " ").trim()}"` : ""; + const state = thread.status === "RESOLVED" ? " (resolved)" : ""; + const head = `- ${thread.headPost ? postLine(thread.headPost) : "(no text)"}${quote}${place ? ` [${place}]` : ""}${state}`; + return [head, ...(thread.replies ?? []).map((reply) => ` - ${postLine(reply)}`)].join("\n"); + }); +} + +export function plural(count: number, one: string, many: string): string { + return count === 1 ? `1 ${one}` : `${count} ${many}`; +} diff --git a/server/src/google-workspace-rest-tools/errors.ts b/server/src/google-workspace-rest-tools/errors.ts index be01d8e9fac..181aee30508 100644 --- a/server/src/google-workspace-rest-tools/errors.ts +++ b/server/src/google-workspace-rest-tools/errors.ts @@ -36,14 +36,21 @@ export type GoogleToolErrorKind = | "unsupported" | "incomplete"; +export interface GoogleErrorDetail { + status?: string; + reasons?: readonly string[]; +} + export class GoogleToolError extends Error { readonly kind: GoogleToolErrorKind; readonly httpStatus: number | null; + readonly google: GoogleErrorDetail; - constructor(kind: GoogleToolErrorKind, message: string, httpStatus: number | null = null) { + constructor(kind: GoogleToolErrorKind, message: string, httpStatus: number | null = null, google: GoogleErrorDetail = {}) { super(message); this.name = "GoogleToolError"; this.kind = kind; this.httpStatus = httpStatus; + this.google = google; } } diff --git a/server/src/google-workspace-rest-tools/google-http.test.ts b/server/src/google-workspace-rest-tools/google-http.test.ts index 3673660a77b..ad562bb0860 100644 --- a/server/src/google-workspace-rest-tools/google-http.test.ts +++ b/server/src/google-workspace-rest-tools/google-http.test.ts @@ -83,6 +83,16 @@ describe("createGoogleHttp", () => { expect(error).toMatchObject({ kind, httpStatus: status }); }); + it("keeps Google's structured status and reasons on 400, 409 and 403 errors", async () => { + const rejected = await failure(client(() => json({ error: { code: 400, status: "FAILED_PRECONDITION", message: "x", details: [{ reason: "STALE" }] } }, 400)).http.send(POST)); + expect(rejected).toMatchObject({ kind: "invalid_argument", google: { status: "FAILED_PRECONDITION", reasons: ["STALE"] } }); + const aborted = await failure(client(() => json({ error: { code: 409, status: "ABORTED" } }, 409)).http.send(POST)); + expect(aborted).toMatchObject({ google: { status: "ABORTED", reasons: [] } }); + const denied = await failure(client(() => json({ error: { code: 403, status: "PERMISSION_DENIED", message: "no" } }, 403)).http.send(GET)); + expect(denied).toMatchObject({ kind: "permission_denied", google: { status: "PERMISSION_DENIED" } }); + expect(await failure(client(() => json({}, 404)).http.send(GET))).toMatchObject({ google: {} }); + }); + it("retries a read once after 503, then succeeds", async () => { let count = 0; const { http, calls } = client(() => (count++ === 0 ? json({}, 503) : json({ labels: [] }))); @@ -268,4 +278,15 @@ describe("writes beyond POST", () => { expect(() => googleRequestUrl({ ...GET, host: "www.googleapis.com", path: "/calendar/v3/../../drive/v3/files" })).toThrow(/not allowed/); expect(() => googleRequestUrl({ ...GET, host: "www.googleapis.com", path: "/calendar/v30/x" })).toThrow(/not allowed/); }); + + it.each([ + ["docs.googleapis.com", "/v1/documents/doc-1", "/v1/documents/doc-1:batchUpdate", + ["/v1/documents", "/v1/documents:create", "/v2/documents/x", "/v1/documentsx/y", "/v1/documents/../../drive/v3/files", "/v1/presentations/x", "/upload/v1/documents/x"]], + ["slides.googleapis.com", "/v1/presentations/deck-1", "/v1/presentations/deck-1:batchUpdate", + ["/v1/presentations", "/v1/presentations:create", "/v1/presentations/../x", "/v1/presentationsx/y", "/v1/documents/x", "/v2/presentations/x"]], + ] as const)("allows %s only under its documents path, after path normalization", (host, read, write, rejected) => { + expect(googleRequestUrl({ ...GET, host, path: read })).toBe(`https://${host}${read}`); + expect(googleRequestUrl({ ...GET, method: "POST", host, path: write })).toBe(`https://${host}${write}`); + for (const path of rejected) expect(() => googleRequestUrl({ ...GET, host, path }), path).toThrow(/not allowed/); + }); }); diff --git a/server/src/google-workspace-rest-tools/google-http.ts b/server/src/google-workspace-rest-tools/google-http.ts index db55aa90ee4..843c4a146de 100644 --- a/server/src/google-workspace-rest-tools/google-http.ts +++ b/server/src/google-workspace-rest-tools/google-http.ts @@ -1,9 +1,11 @@ import { GoogleToolError, GoogleWorkspaceAuthError } from "./errors.js"; -export const GOOGLE_API_HOSTS = ["gmail.googleapis.com", "www.googleapis.com", "sheets.googleapis.com"] as const; +export const GOOGLE_API_HOSTS = ["gmail.googleapis.com", "www.googleapis.com", "docs.googleapis.com", "slides.googleapis.com", "sheets.googleapis.com"] as const; export type GoogleApiHost = (typeof GOOGLE_API_HOSTS)[number]; export const GOOGLE_API_PATH_PREFIXES: Partial> = { "www.googleapis.com": "/calendar/v3/", + "docs.googleapis.com": "/v1/documents/", + "slides.googleapis.com": "/v1/presentations/", "sheets.googleapis.com": "/v4/spreadsheets/", }; @@ -201,11 +203,11 @@ export function googleError( if (status === 429 || reasons.has("RATE_LIMIT_EXCEEDED") || reasons.has("rateLimitExceeded") || reasons.has("userRateLimitExceeded")) { return new GoogleToolError("rate_limited", "Google is rate limiting requests. Try again shortly.", status); } - if (status === 403) return new GoogleToolError("permission_denied", message ?? "Google denied access to this item.", status); + if (status === 403) return new GoogleToolError("permission_denied", message ?? "Google denied access to this item.", status, { status: error?.status, reasons: [...reasons] }); if (status === 404 || status === 410) return new GoogleToolError("not_found", "Google could not find that item.", status); if (status === 412) return new GoogleToolError("invalid_argument", "The item changed after it was read, so nothing was changed. Read it again and retry.", status); if (status === 400 || status === 409 || status === 413) { - return new GoogleToolError("invalid_argument", message ?? "Google rejected the request.", status); + return new GoogleToolError("invalid_argument", message ?? "Google rejected the request.", status, { status: error?.status, reasons: [...reasons] }); } if (status >= 500) { const unavailable = "Google is temporarily unavailable."; diff --git a/server/src/google-workspace-rest-tools/probe.test.ts b/server/src/google-workspace-rest-tools/probe.test.ts index 4fda38784f2..f9d5ae9fe87 100644 --- a/server/src/google-workspace-rest-tools/probe.test.ts +++ b/server/src/google-workspace-rest-tools/probe.test.ts @@ -56,4 +56,14 @@ describe("probeGoogleWorkspaceRestService", () => { .resolves.toEqual({ ok: true, probed: false }); expect(fetch).not.toHaveBeenCalled(); }); + + it.each(["docs", "slides"] as const)("lists %s without a network probe, since every read needs a file ID", async (service) => { + const fetch = vi.fn(); + for (const scopes of [["documents.readonly", "documents"], ["presentations.readonly", "presentations"]]) { + expect(googleWorkspaceRestProbeFor(service, scopes.map(scope))).toBeNull(); + await expect(probeGoogleWorkspaceRestService({ service, accessToken: "t", grantedScopes: scopes.map(scope), fetch })) + .resolves.toEqual({ ok: true, probed: false }); + } + expect(fetch).not.toHaveBeenCalled(); + }); }); diff --git a/server/src/google-workspace-rest-tools/probe.ts b/server/src/google-workspace-rest-tools/probe.ts index b5c00f76a7d..50fd6458b33 100644 --- a/server/src/google-workspace-rest-tools/probe.ts +++ b/server/src/google-workspace-rest-tools/probe.ts @@ -37,6 +37,8 @@ export const GOOGLE_WORKSPACE_REST_PROBES: Readonly freeBusyRequest(["primary"], { start: now, end: now + PROBE_WINDOW_MS }, "UTC"), }, ], + docs: [], + slides: [], sheets: [], }; diff --git a/server/src/google-workspace-rest-tools/sheets/spreadsheet.ts b/server/src/google-workspace-rest-tools/sheets/spreadsheet.ts index 06be00a200f..a97c9c5c24e 100644 --- a/server/src/google-workspace-rest-tools/sheets/spreadsheet.ts +++ b/server/src/google-workspace-rest-tools/sheets/spreadsheet.ts @@ -2,13 +2,13 @@ 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 { boundedStructuredResult, MAX_RESULT_BYTES } 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 { MAX_RESULT_BYTES }; export const MAX_REQUEST_CHARS = 1_000_000; const formatCount = (value: number) => value.toLocaleString("en-US"); diff --git a/server/src/google-workspace-rest-tools/slides/fixtures/slides-rest.ts b/server/src/google-workspace-rest-tools/slides/fixtures/slides-rest.ts new file mode 100644 index 00000000000..cb415719e87 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/fixtures/slides-rest.ts @@ -0,0 +1,117 @@ +import type { RestPage, RestPageElement, RestPresentation, RestTextContent, RestTextElement } from "../presentation.js"; + +type Paragraph = { text: string; bullet?: { nestingLevel?: number; glyph?: string }; link?: string }; + +export function textContent(...paragraphs: Paragraph[]): RestTextContent { + const textElements: RestTextElement[] = []; + let at = 0; + for (const paragraph of paragraphs) { + const content = `${paragraph.text}\n`; + textElements.push({ startIndex: at, endIndex: at + content.length, paragraphMarker: paragraph.bullet ? { bullet: { listId: "list.1", ...paragraph.bullet } } : {} }); + textElements.push({ startIndex: at, endIndex: at + content.length, textRun: { content, style: paragraph.link ? { link: { url: paragraph.link } } : {} } }); + at += content.length; + } + return { textElements }; +} + +export function shape(objectId: string, paragraphs: Paragraph[], placeholder?: string): RestPageElement { + return { objectId, shape: { shapeType: "TEXT_BOX", text: textContent(...paragraphs), ...(placeholder ? { placeholder: { type: placeholder } } : {}) } }; +} + +export function slide(objectId: string, elements: RestPageElement[], notes?: string, extra: Partial = {}): RestPage { + const notesId = `${objectId}-notes`; + return { + objectId, + pageType: "SLIDE", + pageElements: elements, + ...extra, + slideProperties: { + layoutObjectId: "layout-1", + ...extra.slideProperties, + notesPage: { + objectId: `${objectId}-notes-page`, + pageType: "NOTES", + notesProperties: { speakerNotesObjectId: notesId }, + pageElements: [ + { objectId: `${objectId}-thumb`, image: {} }, + { objectId: notesId, shape: { shapeType: "TEXT_BOX", placeholder: { type: "BODY" }, ...(notes === undefined ? {} : { text: textContent(...notes.split("\n").map((text) => ({ text }))) }) } }, + ], + }, + }, + }; +} + +export const DECK: RestPresentation = { + presentationId: "deck-synthetic-1", + title: "Synthetic quarterly review", + revisionId: "rev-deck-1", + slides: [ + slide("s1", [ + shape("s1-title", [{ text: "Quarterly review" }], "CENTERED_TITLE"), + shape("s1-sub", [{ text: "Prepared for the team" }], "SUBTITLE"), + ], "Welcome everyone.\nKeep it short."), + slide("s2", [ + shape("s2-title", [{ text: "Highlights" }], "TITLE"), + shape("s2-body", [ + { text: "Revenue up", bullet: { glyph: "●" } }, + { text: "Two regions", bullet: { nestingLevel: 1, glyph: "○" } }, + { text: "Details", bullet: { glyph: "●" }, link: "https://example.test/details" }, + ], "BODY"), + { objectId: "s2-img", title: "Growth chart", image: { contentUrl: "https://lh3.example.test/img" } }, + { objectId: "s2-line", line: {} }, + ]), + slide("s3", [ + { + objectId: "s3-table", + table: { + rows: 2, + columns: 2, + tableRows: [ + { tableCells: [{ location: { rowIndex: 0, columnIndex: 0 }, text: textContent({ text: "Region" }) }, { location: { rowIndex: 0, columnIndex: 1 }, text: textContent({ text: "Total" }) }] }, + { tableCells: [{ location: { rowIndex: 1, columnIndex: 0 }, text: textContent({ text: "North | East" }) }, { location: { rowIndex: 1, columnIndex: 1 }, text: textContent({ text: "12" }, { text: "up 3" }) }] }, + ], + }, + }, + { + objectId: "s3-group", + elementGroup: { + children: [ + shape("s3-g1", [{ text: "Grouped note" }]), + { objectId: "s3-video", video: { url: "https://www.youtube.com/watch?v=synthetic", source: "YOUTUBE", id: "synthetic" } }, + ], + }, + }, + ], "", { slideProperties: { isSkipped: true } }), + ], + layouts: [{ objectId: "layout-1", pageElements: [{ objectId: "l-ph", shape: { placeholder: { type: "TITLE" }, text: textContent({ text: "Click to add title" }) } }] }], + masters: [{ objectId: "master-1", pageElements: [{ objectId: "m-footer", shape: { text: textContent({ text: "Synthetic Co confidential" }) } }] }], +}; + +export const DECK_TEXT = [ + "## Slide 1", + "### Quarterly review", + "", + "Prepared for the team", + "", + "Speaker notes:", + "Welcome everyone.", + "Keep it short.", + "", + "## Slide 2", + "### Highlights", + "", + "● Revenue up", + " ○ Two regions", + "● [Details](https://example.test/details)", + "", + "[image: Growth chart]", + "", + "## Slide 3 (skipped)", + "| Region | Total |", + "| --- | --- |", + "| North \\| East | 12
up 3 |", + "", + "Grouped note", + "", + "[video: https://www.youtube.com/watch?v=synthetic]", +].join("\n"); diff --git a/server/src/google-workspace-rest-tools/slides/index.ts b/server/src/google-workspace-rest-tools/slides/index.ts new file mode 100644 index 00000000000..b4ce34da497 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/index.ts @@ -0,0 +1,5 @@ +import type { RestTool } from "../tool.js"; +import { readPresentation } from "./read-presentation.js"; +import { updatePresentation } from "./update-presentation.js"; + +export const SLIDES_TOOLS: readonly RestTool[] = [readPresentation, updatePresentation]; diff --git a/server/src/google-workspace-rest-tools/slides/presentation.ts b/server/src/google-workspace-rest-tools/slides/presentation.ts new file mode 100644 index 00000000000..152be5fbdf1 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/presentation.ts @@ -0,0 +1,72 @@ +import type { RestCommentThread } from "../documents-shared.js"; + +export const SLIDES_HOST = "slides.googleapis.com" as const; +export const SLIDES_BASE = "/v1/presentations"; + +export const presentationPath = (presentationId: string) => `${SLIDES_BASE}/${encodeURIComponent(presentationId)}`; + +export interface RestSlidesLink { + url?: string; + relativeLink?: string; + pageObjectId?: string; + slideIndex?: number; +} + +export interface RestTextElement { + startIndex?: number; + endIndex?: number; + paragraphMarker?: { bullet?: { listId?: string; nestingLevel?: number; glyph?: string } }; + textRun?: { content?: string; style?: { link?: RestSlidesLink } }; + autoText?: { type?: string; content?: string; style?: { link?: RestSlidesLink } }; +} + +export interface RestTextContent { + textElements?: RestTextElement[]; +} + +export interface RestTableCell { + location?: { rowIndex?: number; columnIndex?: number }; + rowSpan?: number; + columnSpan?: number; + text?: RestTextContent; +} + +export interface RestPageElement { + objectId?: string; + title?: string; + description?: string; + shape?: { shapeType?: string; text?: RestTextContent; placeholder?: { type?: string; index?: number } }; + table?: { rows?: number; columns?: number; tableRows?: Array<{ tableCells?: RestTableCell[] }> }; + image?: { contentUrl?: string; sourceUrl?: string }; + video?: { url?: string; source?: string; id?: string }; + line?: Record; + wordArt?: { renderedText?: string }; + sheetsChart?: { spreadsheetId?: string; chartId?: number }; + elementGroup?: { children?: RestPageElement[] }; + speakerSpotlight?: Record; +} + +export interface RestPage { + objectId?: string; + pageType?: string; + pageElements?: RestPageElement[]; + slideProperties?: { layoutObjectId?: string; isSkipped?: boolean; notesPage?: RestPage }; + notesProperties?: { speakerNotesObjectId?: string }; + comments?: RestCommentThread[]; +} + +export interface RestPresentation { + presentationId?: string; + title?: string; + revisionId?: string; + slides?: RestPage[]; + layouts?: RestPage[]; + masters?: RestPage[]; + comments?: RestCommentThread[]; +} + +export interface RestBatchUpdateResponse { + presentationId?: string; + replies?: Array>; + writeControl?: { requiredRevisionId?: string }; +} diff --git a/server/src/google-workspace-rest-tools/slides/read-presentation.test.ts b/server/src/google-workspace-rest-tools/slides/read-presentation.test.ts new file mode 100644 index 00000000000..8ad339724e4 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/read-presentation.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { MAX_RESULT_BYTES } from "../tool.js"; +import { fakeGoogle, json } from "../fixtures/fake-google.js"; +import { createGoogleHttp } from "../google-http.js"; +import { DECK, DECK_TEXT, shape, slide } from "./fixtures/slides-rest.js"; +import { readPresentation, readPresentationRequest } from "./read-presentation.js"; + +describe("read_presentation request", () => { + it.each([ + [{ presentationId: "deck-1" }, {}], + [{ presentationId: "deck-1", commentsIncluded: true }, { commentsViewMode: "COMMENTS_VIEW_MODE_INCLUDED" }], + [{ presentationId: "deck-1", fields: ["revisionId", "slides(objectId,pageElements(objectId,shape.text))"] }, { fields: "revisionId,slides(objectId,pageElements(objectId,shape.text))" }], + [{ presentationId: "deck-1", fields: [] }, {}], + ])("reads %j", (input, query) => { + const request = readPresentationRequest(input); + expect(request).toMatchObject({ method: "GET", host: "slides.googleapis.com", path: "/v1/presentations/deck-1" }); + expect(Object.fromEntries(Object.entries(request.query ?? {}).filter(([, value]) => value !== undefined))).toEqual(query); + }); +}); + +describe("read_presentation tool", () => { + it("returns the text form, structure and revision without fields", async () => { + const { fetch, calls } = fakeGoogle(() => json(DECK)); + const result = await readPresentation.call({ presentationId: "deck-synthetic-1" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls.map((call) => `${call.method} ${call.url.host}${call.url.pathname}${call.url.search}`)).toEqual(["GET slides.googleapis.com/v1/presentations/deck-synthetic-1"]); + expect((result.structuredContent as { content: Record }).content).toMatchObject({ revisionId: "rev-deck-1", text: DECK_TEXT }); + }); + + it("returns Google's answer unchanged when fields are given", async () => { + const partial = { revisionId: "rev-deck-1", slides: [{ objectId: "s1" }] }; + const { fetch, calls } = fakeGoogle(() => json(partial)); + const result = await readPresentation.call({ presentationId: "deck-1", fields: ["revisionId", "slides.objectId"] }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls[0]!.url.searchParams.get("fields")).toBe("revisionId,slides.objectId"); + expect(result.structuredContent).toEqual({ content: partial }); + }); + + it("refuses malformed IDs and field masks without calling Google", async () => { + const { fetch, calls } = fakeGoogle(() => json({})); + const http = createGoogleHttp({ accessToken: "t", fetch }); + for (const input of [ + { presentationId: "../x" }, + { presentationId: "a/b" }, + { presentationId: "deck", fields: ["slides&key=x"] }, + { presentationId: "deck", fields: ["slides objectId"] }, + { presentationId: "deck", fields: [""] }, + { presentationId: "deck", fields: "slides" }, + ]) { + expect((await readPresentation.call(input, http)).isError, JSON.stringify(input)).toBe(true); + } + expect(calls).toHaveLength(0); + }); + + it("says when comments are not available with the user's access, after checking the presentation itself can be read", async () => { + const { fetch, calls } = fakeGoogle(({ url }) => (url.searchParams.get("fields") === "presentationId" + ? json({ presentationId: "deck-1" }) + : json({ error: { code: 403, status: "PERMISSION_DENIED", message: "The caller does not have permission" } }, 403))); + const result = await readPresentation.call({ presentationId: "deck-1", commentsIncluded: true }, createGoogleHttp({ accessToken: "t", fetch })); + expect((result.content[0] as { text: string }).text).toBe("Comments are not available for this presentation with your access, so nothing was returned. The presentation can be read without them: call read_presentation again without commentsIncluded."); + expect(calls.map((call) => call.url.search)).toEqual(["?commentsViewMode=COMMENTS_VIEW_MODE_INCLUDED", "?fields=presentationId"]); + }); + + it("refuses a result over the size limit and suggests fields", async () => { + const line = "y".repeat(10_000); + const big = { presentationId: "big", slides: Array.from({ length: Math.ceil(MAX_RESULT_BYTES / 20_000) + 5 }, (_, index) => slide(`s${index}`, [shape(`e${index}`, [{ text: line }])])) }; + const { fetch } = fakeGoogle(() => json(big)); + const result = await readPresentation.call({ presentationId: "big" }, createGoogleHttp({ accessToken: "t", fetch })); + expect(result.isError).toBe(true); + expect((result.content[0] as { text: string }).text).toMatch(/^This presentation is too large to return in one result .*Pass fields to read only part of it/); + expect((result.content[0] as { text: string }).text).toMatch(/\(\d+ KB; the limit is 250 KB\)/); + }); +}); diff --git a/server/src/google-workspace-rest-tools/slides/read-presentation.ts b/server/src/google-workspace-rest-tools/slides/read-presentation.ts new file mode 100644 index 00000000000..0bebe0bfcf3 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/read-presentation.ts @@ -0,0 +1,80 @@ +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import { fileIdArg, readWithComments, sizedResult } from "../documents-shared.js"; +import type { GoogleRequest } from "../google-http.js"; +import { defineTool } from "../tool.js"; +import { presentationPath, SLIDES_HOST, type RestPresentation } from "./presentation.js"; +import { renderPresentation } from "./render.js"; + +const fieldPath = z.string().min(1).max(2000).regex(/^[A-Za-z0-9_.,()*/]+$/, "Must be a field mask path such as slides.pageElements(objectId,shape.text)"); + +const args = z.object({ + presentationId: fileIdArg("Slides presentation"), + fields: z.array(fieldPath).max(50).optional(), + commentsIncluded: z.boolean().optional(), +}); +export type ReadPresentationArgs = z.infer; + +export function readPresentationRequest(input: ReadPresentationArgs): GoogleRequest { + return { + method: "GET", + host: SLIDES_HOST, + path: presentationPath(input.presentationId), + query: { + fields: input.fields?.length ? input.fields.join(",") : undefined, + commentsViewMode: input.commentsIncluded ? "COMMENTS_VIEW_MODE_INCLUDED" : undefined, + }, + }; +} + +export function readPresentationAccessCheckRequest(input: ReadPresentationArgs): GoogleRequest { + return { method: "GET", host: SLIDES_HOST, path: presentationPath(input.presentationId), query: { fields: "presentationId" } }; +} + +export const COMMENTS_UNAVAILABLE = "Comments are not available for this presentation with your access, so nothing was returned. The presentation can be read without them: call read_presentation again without commentsIncluded."; + +export function readPresentationResult(presentation: RestPresentation, input: ReadPresentationArgs): CallToolResult { + if (input.fields?.length) { + return sizedResult({ content: presentation as Record }, "presentation", "Ask for fewer fields."); + } + const content = renderPresentation(presentation, { commentsRequested: input.commentsIncluded === true }); + return sizedResult({ content }, "presentation", "Pass fields to read only part of it, for example [\"slides.objectId\", \"slides.pageElements(objectId,shape.text)\"]."); +} + +export const readPresentation = defineTool({ + definition: { + name: "read_presentation", + description: [ + "Reads a Google Slides presentation.", + "Without fields, content.text is every slide in order as Markdown-style text: each slide starts with ## Slide N, title placeholders start with ###, bullets keep their glyph, tables use | cells |, links are [text](url), and each slide's speaker notes follow under Speaker notes:.", + "Items that have no text form are shown in brackets, such as [image: alt text] or [chart], and content.notes says what was left out.", + "content.slides gives each slide's objectId and its page elements with their objectId, type and raw text (character indices for update_presentation count from 0 in that text), plus the speaker notes shape's objectId.", + "content.revisionId is required by update_presentation.", + "With fields, content is the Slides API presentation resource limited to those fields, as Google returns it.", + ].join(" "), + inputSchema: { + type: "object", + properties: { + presentationId: { type: "string", description: "Required. The ID of the presentation to read: the part of its docs.google.com link after /d/." }, + fields: { + type: "array", + items: { type: "string" }, + description: "Optional. A field mask over the Slides API presentation resource, such as [\"revisionId\", \"slides(objectId,pageElements(objectId,shape.text))\"]. When set, content is the raw resource limited to these fields instead of the text form.", + }, + commentsIncluded: { type: "boolean", description: "Optional. If true, comment threads are included. Needs access to comments; without it the call fails and says so. Default: false." }, + }, + required: ["presentationId"], + }, + outputSchema: { + type: "object", + properties: { content: { type: "object", description: "The presentation's text, structure and revision ID, or the fields asked for." } }, + required: ["content"], + }, + annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }, + }, + args, + async run(input, http) { + const plain = input.commentsIncluded ? readPresentationAccessCheckRequest(input) : undefined; + return readPresentationResult(await readWithComments(http, readPresentationRequest(input), plain, COMMENTS_UNAVAILABLE), input); + }, +}); diff --git a/server/src/google-workspace-rest-tools/slides/render.test.ts b/server/src/google-workspace-rest-tools/slides/render.test.ts new file mode 100644 index 00000000000..14427dbe0fe --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/render.test.ts @@ -0,0 +1,240 @@ +import { describe, expect, it } from "vitest"; +import { DECK, DECK_TEXT, shape, slide, textContent } from "./fixtures/slides-rest.js"; +import type { RestPageElement, RestPresentation } from "./presentation.js"; +import { elementType, renderPresentation, slidesLinkTarget, textLines } from "./render.js"; + +const deck = (elements: RestPageElement[], notes?: string): RestPresentation => ({ presentationId: "p", title: "T", slides: [slide("s1", elements, notes)] }); +const body = (elements: RestPageElement[], notes?: string) => renderPresentation(deck(elements, notes)).text.split("\n").slice(1).join("\n"); + +describe("read_presentation text rendering", () => { + it("renders every slide in order with titles, bullets, links, tables, groups, media and speaker notes", () => { + const content = renderPresentation(DECK); + expect(content.text).toBe(DECK_TEXT); + expect(content).toMatchObject({ presentationId: "deck-synthetic-1", title: "Synthetic quarterly review", revisionId: "rev-deck-1" }); + expect(content.notes).toEqual([ + "1 image is shown as [image] with its title or alt text; the picture itself is not included.", + "1 video is shown as [video] with its link when there is one.", + "1 text item on slide masters or layouts (for example a footer or logo text shown on every slide) is not included.", + ]); + }); + + it.each([ + ["TITLE", "### Words"], + ["CENTERED_TITLE", "### Words"], + ["SUBTITLE", "Words"], + ["BODY", "Words"], + [undefined, "Words"], + ])("renders a %s placeholder as %j", (placeholder, expected) => { + expect(body([shape("e", [{ text: "Words" }], placeholder)])).toBe(expected); + }); + + it("marks only the first line of a multi-paragraph title", () => { + expect(body([shape("e", [{ text: "Line one" }, { text: "Line two" }], "TITLE")])).toBe("### Line one\nLine two"); + }); + + it.each([ + ["a glyph", { glyph: "◆" }, "◆ item"], + ["a numbered glyph", { glyph: "3." }, "3. item"], + ["a nested glyph", { glyph: "-", nestingLevel: 2 }, " - item"], + ["no glyph", {}, "- item"], + ["a glyph with spaces", { glyph: " • " }, "• item"], + ])("renders a bullet with %s", (_name, bullet, expected) => { + expect(body([shape("e", [{ text: "item", bullet }])])).toBe(expected); + }); + + it.each([ + ["a web link", { url: "https://example.test" }, "https://example.test"], + ["a slide link", { pageObjectId: "s9" }, "#slide=s9"], + ["a slide number link", { slideIndex: 2 }, "#slide-number=3"], + ["a relative link", { relativeLink: "NEXT_SLIDE" }, "#NEXT_SLIDE"], + ["no link", undefined, undefined], + ])("turns %s into a target", (_name, link, expected) => { + expect(slidesLinkTarget(link)).toBe(expected); + }); + + it("renders links inside a paragraph, automatic slide numbers and soft line breaks", () => { + const text = { + textElements: [ + { paragraphMarker: {} }, + { textRun: { content: "See " } }, + { textRun: { content: "slide 2", style: { link: { pageObjectId: "s2" } } } }, + { textRun: { content: " now\u000bthen\n" } }, + { paragraphMarker: {} }, + { autoText: { type: "SLIDE_NUMBER", content: "7" } }, + { textRun: { content: "\n" } }, + ], + }; + expect(textLines(text)).toEqual(["See [slide 2](#slide=s2) now\nthen", "7"]); + }); + + it("keeps empty lines inside a shape but drops trailing ones, and renders nothing for an empty shape", () => { + expect(body([shape("e", [{ text: "a" }, { text: "" }, { text: "b" }, { text: "" }, { text: "" }])])).toBe("a\n\nb"); + expect(body([shape("e", [{ text: "" }]), { objectId: "x", shape: { shapeType: "RECTANGLE" } }, shape("f", [{ text: "only" }])])).toBe("only"); + }); + + it("renders text that starts without a paragraph marker", () => { + expect(textLines({ textElements: [{ textRun: { content: "loose\n" } }] })).toEqual(["loose"]); + expect(textLines(undefined)).toEqual([]); + }); + + it.each([ + ["an image with alt text", { objectId: "i", description: "A team\nphoto", image: {} }, "[image: A team photo]", "1 image is"], + ["an untitled image", { objectId: "i", image: {} }, "[image]", "1 image is"], + ["a linked video", { objectId: "v", video: { url: "https://www.youtube.com/watch?v=x" } }, "[video: https://www.youtube.com/watch?v=x]", "1 video is"], + ["a Drive video", { objectId: "v", title: "Demo", video: { source: "DRIVE", id: "f1" } }, "[video: Demo]", "1 video is"], + ["a chart", { objectId: "c", sheetsChart: { spreadsheetId: "sheet-1", chartId: 4 } }, "[chart]", "1 chart is"], + ] as const)("renders %s and says what was left out", (_name, element, expected, note) => { + const content = renderPresentation(deck([element as RestPageElement])); + expect(content.text).toBe(`## Slide 1\n${expected}`); + expect(content.notes?.[0]?.startsWith(note)).toBe(true); + }); + + it("renders word art text, and nothing for lines and speaker spotlights", () => { + expect(body([{ objectId: "w", wordArt: { renderedText: "BIG" } }, { objectId: "l", line: {} }, { objectId: "s", speakerSpotlight: {} }])).toBe("BIG"); + }); + + it("renders tables with escaped pipes, multi-line cells and empty tables", () => { + const table: RestPageElement = { + objectId: "t", + table: { + rows: 2, + columns: 2, + tableRows: [ + { tableCells: [{ location: { rowIndex: 0, columnIndex: 0 }, text: textContent({ text: "A | B" }) }, { location: { rowIndex: 0, columnIndex: 1 }, text: textContent({ text: "C" }) }] }, + { tableCells: [{ location: { rowIndex: 1, columnIndex: 0 }, text: textContent({ text: "a", bullet: { glyph: "●" } }, { text: "b", bullet: { glyph: "●" } }) }, { location: { rowIndex: 1, columnIndex: 1 }, text: textContent({ text: "" }) }] }, + ], + }, + }; + expect(body([table])).toBe("| A \\| B | C |\n| --- | --- |\n| ● a
● b | |"); + expect(body([{ objectId: "e", table: { rows: 0, columns: 0, tableRows: [] } }])).toBe("[empty table]"); + }); + + it.each([ + [ + "a header spanning two columns", + 3, + [ + [{ location: { rowIndex: 0, columnIndex: 0 }, columnSpan: 2, text: textContent({ text: "Q1 and Q2" }) }, { location: { rowIndex: 0, columnIndex: 2 }, text: textContent({ text: "Q3" }) }], + [{ location: { rowIndex: 1, columnIndex: 0 }, text: textContent({ text: "1" }) }, { location: { rowIndex: 1, columnIndex: 1 }, text: textContent({ text: "2" }) }, { location: { rowIndex: 1, columnIndex: 2 }, text: textContent({ text: "3" }) }], + ], + ["| Q1 and Q2 | (merged left) | Q3 |", "| --- | --- | --- |", "| 1 | 2 | 3 |"], + ], + [ + "a cell spanning two rows", + 2, + [ + [{ location: { rowIndex: 0, columnIndex: 0 }, rowSpan: 2, text: textContent({ text: "North" }) }, { location: { rowIndex: 0, columnIndex: 1 }, text: textContent({ text: "x" }) }], + [{ location: { rowIndex: 1, columnIndex: 1 }, text: textContent({ text: "y" }) }], + ], + ["| North | x |", "| --- | --- |", "| (merged up) | y |"], + ], + [ + "a two-by-two merge without locations", + 3, + [ + [{ rowSpan: 2, columnSpan: 2, text: textContent({ text: "Big" }) }, { text: textContent({ text: "r" }) }], + [{ text: textContent({ text: "s" }) }], + ], + ["| Big | (merged left) | r |", "| --- | --- | --- |", "| (merged up) | (merged up) | s |"], + ], + ])("renders %s with every row as wide as the table and the merged region marked", (_name, columns, tableRows, expected) => { + const table = { objectId: "t", table: { rows: tableRows.length, columns, tableRows: tableRows.map((tableCells) => ({ tableCells })) } } as RestPageElement; + expect(body([table])).toBe(expected.join("\n")); + }); + + it("escapes a table cell's backslashes and pipes exactly once", () => { + const table: RestPageElement = { + objectId: "t", + table: { rows: 1, columns: 2, tableRows: [{ tableCells: [{ location: { rowIndex: 0, columnIndex: 0 }, text: textContent({ text: "a\\|b" }) }, { location: { rowIndex: 0, columnIndex: 1 }, text: textContent({ text: "c" }) }] }] }, + }; + expect(body([table])).toBe("| a\\\\\\|b | c |\n| --- | --- |"); + }); + + it("renders nested groups in order", () => { + const group: RestPageElement = { objectId: "g", elementGroup: { children: [shape("a", [{ text: "outer" }]), { objectId: "g2", elementGroup: { children: [shape("b", [{ text: "inner" }])] } }] } }; + expect(body([group])).toBe("outer\n\ninner"); + }); + + it("leaves out empty speaker notes and slides without a notes page", () => { + expect(renderPresentation(deck([shape("a", [{ text: "x" }])], "")).text).toBe("## Slide 1\nx"); + const bare: RestPresentation = { slides: [{ objectId: "s", pageElements: [shape("a", [{ text: "x" }])] }] }; + expect(renderPresentation(bare)).toEqual({ presentationId: "", title: "", text: "## Slide 1\nx", slides: [{ objectId: "s", slideNumber: 1, elements: [{ objectId: "a", type: "shape", text: "x\n" }] }] }); + }); + + it("renders a presentation with no slides as empty text", () => { + expect(renderPresentation({ presentationId: "p", title: "Empty", slides: [] })).toEqual({ presentationId: "p", title: "Empty", text: "", slides: [] }); + }); + + it("lists comments for the presentation and for slides when asked, and says when there are none", () => { + const withComments: RestPresentation = { + ...deck([shape("a", [{ text: "x" }])]), + comments: [{ headPost: { content: "Overall fine", author: { displayName: "Avery" } } }], + }; + withComments.slides![0]!.comments = [{ status: "RESOLVED", plainTextQuote: "x", headPost: { content: "Typo", author: { displayName: "Blake" } }, replies: [{ content: "Fixed", author: { displayName: "Avery" } }] }]; + expect(renderPresentation(withComments, { commentsRequested: true }).text).toBe([ + "## Slide 1", + "x", + "", + "[Comments]", + "- Avery: Overall fine", + "- Blake: Typo on \"x\" [slide 1] (resolved)", + " - Avery: Fixed", + ].join("\n")); + expect(renderPresentation(deck([shape("a", [{ text: "x" }])]), { commentsRequested: true }).text).toBe("## Slide 1\nx\n\n[Comments]\nNo comments."); + expect(renderPresentation(withComments).text).toBe("## Slide 1\nx"); + }); + + it("counts master and layout text that is not a placeholder", () => { + const presentation: RestPresentation = { + ...deck([]), + masters: [{ pageElements: [shape("m1", [{ text: "Footer" }]), shape("m2", [{ text: "" }]), shape("m3", [{ text: "Title" }], "TITLE")] }], + layouts: [{ pageElements: [{ objectId: "g", elementGroup: { children: [shape("l1", [{ text: "Logo" }])] } }, { objectId: "t", table: { tableRows: [{ tableCells: [{ text: textContent({ text: "cell" }) }] }] } }] }], + }; + expect(renderPresentation(presentation).notes).toEqual(["3 text items on slide masters or layouts (for example a footer or logo text shown on every slide) are not included."]); + }); +}); + +describe("read_presentation structure", () => { + it("gives each slide its objectId, number, elements with raw text, and the speaker notes shape", () => { + const [first, second, third] = renderPresentation(DECK).slides; + expect(first).toEqual({ + objectId: "s1", + slideNumber: 1, + elements: [ + { objectId: "s1-title", type: "shape", placeholder: "CENTERED_TITLE", text: "Quarterly review\n" }, + { objectId: "s1-sub", type: "shape", placeholder: "SUBTITLE", text: "Prepared for the team\n" }, + ], + speakerNotes: { objectId: "s1-notes", text: "Welcome everyone.\nKeep it short.\n" }, + }); + expect(second!.elements.map((element) => element.type)).toEqual(["shape", "shape", "image", "line"]); + expect(second!.elements[1]!.text).toBe("Revenue up\nTwo regions\nDetails\n"); + expect(second!.elements[2]).toEqual({ objectId: "s2-img", type: "image", title: "Growth chart" }); + expect(third).toMatchObject({ objectId: "s3", slideNumber: 3, skipped: true }); + expect(third!.elements[0]).toEqual({ + objectId: "s3-table", + type: "table", + rows: 2, + columns: 2, + cells: [ + [{ rowIndex: 0, columnIndex: 0, text: "Region\n" }, { rowIndex: 0, columnIndex: 1, text: "Total\n" }], + [{ rowIndex: 1, columnIndex: 0, text: "North | East\n" }, { rowIndex: 1, columnIndex: 1, text: "12\nup 3\n" }], + ], + }); + expect(third!.elements[1]).toEqual({ + objectId: "s3-group", + type: "group", + children: [{ objectId: "s3-g1", type: "shape", text: "Grouped note\n" }, { objectId: "s3-video", type: "video", url: "https://www.youtube.com/watch?v=synthetic" }], + }); + }); + + it.each([ + [{ shape: {} }, "shape"], [{ table: {} }, "table"], [{ image: {} }, "image"], [{ video: {} }, "video"], [{ line: {} }, "line"], + [{ wordArt: {} }, "wordArt"], [{ sheetsChart: {} }, "sheetsChart"], [{ elementGroup: {} }, "group"], [{ speakerSpotlight: {} }, "speakerSpotlight"], [{}, "unknown"], + ] as const)("names the element type of %j", (element, expected) => { + expect(elementType(element as RestPageElement)).toBe(expected); + }); + + it("gives a chart its spreadsheet and chart IDs", () => { + expect(renderPresentation(deck([{ objectId: "c", sheetsChart: { spreadsheetId: "sheet-1", chartId: 4 } }])).slides[0]!.elements[0]).toEqual({ objectId: "c", type: "sheetsChart", spreadsheetId: "sheet-1", chartId: 4 }); + }); +}); diff --git a/server/src/google-workspace-rest-tools/slides/render.ts b/server/src/google-workspace-rest-tools/slides/render.ts new file mode 100644 index 00000000000..f9e5f0b4dbc --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/render.ts @@ -0,0 +1,261 @@ +import { markdownTable, plural, renderComments, type RestCommentThread } from "../documents-shared.js"; +import type { RestPage, RestPageElement, RestPresentation, RestSlidesLink, RestTextContent, RestTextElement } from "./presentation.js"; + +export interface SlidesTableCellView { + rowIndex: number; + columnIndex: number; + rowSpan?: number; + columnSpan?: number; + text: string; +} + +export interface SlidesElementView { + objectId: string; + type: string; + title?: string; + description?: string; + placeholder?: string; + text?: string; + rows?: number; + columns?: number; + cells?: SlidesTableCellView[][]; + url?: string; + spreadsheetId?: string; + chartId?: number; + children?: SlidesElementView[]; +} + +export interface SlideView { + objectId: string; + slideNumber: number; + skipped?: boolean; + elements: SlidesElementView[]; + speakerNotes?: { objectId: string; text: string }; +} + +export interface SlidesContent { + presentationId: string; + title: string; + revisionId?: string; + text: string; + slides: SlideView[]; + notes?: string[]; + [key: string]: unknown; +} + +interface Tally { + images: number; + videos: number; + charts: number; +} + +const TITLE_PLACEHOLDERS = new Set(["TITLE", "CENTERED_TITLE"]); + +const ELEMENT_KINDS = ["shape", "table", "image", "video", "line", "wordArt", "sheetsChart", "elementGroup", "speakerSpotlight"] as const; + +export function elementType(element: RestPageElement): string { + const kind = ELEMENT_KINDS.find((name) => element[name] !== undefined); + if (kind === "elementGroup") return "group"; + return kind ?? "unknown"; +} + +export function rawText(text: RestTextContent | undefined): string { + return (text?.textElements ?? []).map((element) => element.textRun?.content ?? element.autoText?.content ?? "").join(""); +} + +export function slidesLinkTarget(link: RestSlidesLink | undefined): string | undefined { + if (!link) return undefined; + if (link.url) return link.url; + if (link.pageObjectId) return `#slide=${link.pageObjectId}`; + if (link.slideIndex !== undefined) return `#slide-number=${link.slideIndex + 1}`; + if (link.relativeLink) return `#${link.relativeLink}`; + return undefined; +} + +function renderRun(element: RestTextElement): string { + const run = element.textRun ?? element.autoText; + const raw = run?.content ?? ""; + const trailing = raw.match(/\n*$/)![0]; + const body = raw.slice(0, raw.length - trailing.length); + const target = slidesLinkTarget(run?.style?.link); + return (body && target ? `[${body}](${target})` : body) + trailing; +} + +export function textLines(text: RestTextContent | undefined): string[] { + const paragraphs: Array<{ prefix: string; body: string }> = []; + let current: { prefix: string; body: string } | undefined; + for (const element of text?.textElements ?? []) { + if (element.paragraphMarker) { + const bullet = element.paragraphMarker.bullet; + const prefix = bullet ? `${" ".repeat(bullet.nestingLevel ?? 0)}${bullet.glyph?.trim() || "-"} ` : ""; + current = { prefix, body: "" }; + paragraphs.push(current); + } else if (element.textRun || element.autoText) { + if (!current) { + current = { prefix: "", body: "" }; + paragraphs.push(current); + } + current.body += renderRun(element); + } + } + const lines = paragraphs.map(({ prefix, body }) => `${prefix}${body.replace(/\n$/, "").replace(/\u000b/g, "\n")}`); + while (lines.length && lines[lines.length - 1]!.trim() === "") lines.pop(); + return lines; +} + +function cellText(text: RestTextContent | undefined): string { + return textLines(text).join("\n"); +} + +function label(kind: string, element: RestPageElement): string { + const name = (element.title || element.description || "").replace(/\s+/g, " ").trim(); + return name ? `[${kind}: ${name}]` : `[${kind}]`; +} + +export function elementLines(element: RestPageElement, tally: Tally): string[] { + if (element.shape) { + const lines = textLines(element.shape.text); + if (lines.length && TITLE_PLACEHOLDERS.has(element.shape.placeholder?.type ?? "")) lines[0] = `### ${lines[0]}`; + return lines; + } + if (element.table) { + const rows = (element.table.tableRows ?? []).map((row) => (row.tableCells ?? []).map((cell) => ({ + text: cellText(cell.text), + rowSpan: cell.rowSpan, + columnSpan: cell.columnSpan, + row: cell.location?.rowIndex, + column: cell.location?.columnIndex, + }))); + return markdownTable(rows, element.table.columns ?? 0); + } + if (element.image) { + tally.images += 1; + return [label("image", element)]; + } + if (element.video) { + tally.videos += 1; + return [element.video.url ? `[video: ${element.video.url}]` : label("video", element)]; + } + if (element.sheetsChart) { + tally.charts += 1; + return [label("chart", element)]; + } + if (element.wordArt) return element.wordArt.renderedText ? [element.wordArt.renderedText] : []; + if (element.elementGroup) return joinBlocks((element.elementGroup.children ?? []).map((child) => elementLines(child, tally))); + return []; +} + +function joinBlocks(blocks: string[][]): string[] { + return blocks.filter((block) => block.length > 0).flatMap((block, index) => (index === 0 ? block : ["", ...block])); +} + +export function elementView(element: RestPageElement): SlidesElementView { + const base = { + objectId: element.objectId ?? "", + type: elementType(element), + ...(element.title ? { title: element.title } : {}), + ...(element.description ? { description: element.description } : {}), + }; + if (element.shape) { + const placeholder = element.shape.placeholder?.type; + const text = rawText(element.shape.text); + return { ...base, ...(placeholder ? { placeholder } : {}), ...(text ? { text } : {}) }; + } + if (element.table) { + return { + ...base, + rows: element.table.rows ?? element.table.tableRows?.length ?? 0, + columns: element.table.columns ?? element.table.tableRows?.[0]?.tableCells?.length ?? 0, + cells: (element.table.tableRows ?? []).map((row, rowIndex) => (row.tableCells ?? []).map((cell, columnIndex) => ({ + rowIndex: cell.location?.rowIndex ?? rowIndex, + columnIndex: cell.location?.columnIndex ?? columnIndex, + ...(cell.rowSpan !== undefined && cell.rowSpan !== 1 ? { rowSpan: cell.rowSpan } : {}), + ...(cell.columnSpan !== undefined && cell.columnSpan !== 1 ? { columnSpan: cell.columnSpan } : {}), + text: rawText(cell.text), + }))), + }; + } + if (element.video?.url) return { ...base, url: element.video.url }; + if (element.sheetsChart) return { ...base, spreadsheetId: element.sheetsChart.spreadsheetId, chartId: element.sheetsChart.chartId }; + if (element.wordArt?.renderedText) return { ...base, text: element.wordArt.renderedText }; + if (element.elementGroup) return { ...base, children: (element.elementGroup.children ?? []).map(elementView) }; + return base; +} + +export function speakerNotes(slide: RestPage): { objectId: string; element?: RestPageElement } | undefined { + const notesPage = slide.slideProperties?.notesPage; + const objectId = notesPage?.notesProperties?.speakerNotesObjectId; + if (!objectId) return undefined; + return { objectId, element: notesPage?.pageElements?.find((element) => element.objectId === objectId) }; +} + +function hasText(element: RestPageElement): boolean { + if (element.shape) return !element.shape.placeholder && rawText(element.shape.text).trim() !== ""; + if (element.table) return (element.table.tableRows ?? []).some((row) => (row.tableCells ?? []).some((cell) => rawText(cell.text).trim() !== "")); + if (element.wordArt) return Boolean(element.wordArt.renderedText); + if (element.elementGroup) return (element.elementGroup.children ?? []).some(hasText); + return false; +} + +export function inheritedTextCount(presentation: RestPresentation): number { + return [...(presentation.masters ?? []), ...(presentation.layouts ?? [])] + .reduce((count, page) => count + (page.pageElements ?? []).filter(hasText).length, 0); +} + +export interface RenderPresentationOptions { + commentsRequested?: boolean; +} + +export function renderPresentation(presentation: RestPresentation, options: RenderPresentationOptions = {}): SlidesContent { + const tally: Tally = { images: 0, videos: 0, charts: 0 }; + const slides = presentation.slides ?? []; + const sections: string[][] = []; + const views: SlideView[] = slides.map((slide, index) => { + const skipped = slide.slideProperties?.isSkipped === true; + const elements = slide.pageElements ?? []; + const notes = speakerNotes(slide); + const notesLines = textLines(notes?.element?.shape?.text); + const body = joinBlocks(elements.map((element) => elementLines(element, tally))); + sections.push([ + `## Slide ${index + 1}${skipped ? " (skipped)" : ""}`, + ...body, + ...(notesLines.length ? ["", "Speaker notes:", ...notesLines] : []), + ]); + return { + objectId: slide.objectId ?? "", + slideNumber: index + 1, + ...(skipped ? { skipped } : {}), + elements: elements.map(elementView), + ...(notes ? { speakerNotes: { objectId: notes.objectId, text: rawText(notes.element?.shape?.text) } } : {}), + }; + }); + const lines = sections.flatMap((section, index) => (index === 0 ? section : ["", ...section])); + if (options.commentsRequested) { + const threads: Array<{ thread: RestCommentThread; slide?: number }> = [ + ...(presentation.comments ?? []).map((thread) => ({ thread })), + ...slides.flatMap((slide, index) => (slide.comments ?? []).map((thread) => ({ thread, slide: index + 1 }))), + ]; + const where = new Map(threads.map(({ thread, slide }) => [thread, slide])); + if (lines.length) lines.push(""); + lines.push("[Comments]", ...(threads.length + ? renderComments(threads.map(({ thread }) => thread), (thread) => { + const slide = where.get(thread); + return slide ? `slide ${slide}` : undefined; + }) + : ["No comments."])); + } + const notes: string[] = []; + if (tally.images) notes.push(`${plural(tally.images, "image is", "images are")} shown as [image] with its title or alt text; the picture itself is not included.`); + if (tally.videos) notes.push(`${plural(tally.videos, "video is", "videos are")} shown as [video] with its link when there is one.`); + if (tally.charts) notes.push(`${plural(tally.charts, "chart is", "charts are")} shown as [chart]; chart data is not included.`); + const inherited = inheritedTextCount(presentation); + if (inherited) notes.push(`${plural(inherited, "text item", "text items")} on slide masters or layouts (for example a footer or logo text shown on every slide) ${inherited === 1 ? "is" : "are"} not included.`); + return { + presentationId: presentation.presentationId ?? "", + title: presentation.title ?? "", + ...(presentation.revisionId ? { revisionId: presentation.revisionId } : {}), + text: lines.join("\n"), + slides: views, + ...(notes.length ? { notes } : {}), + }; +} diff --git a/server/src/google-workspace-rest-tools/slides/request-kinds.test.ts b/server/src/google-workspace-rest-tools/slides/request-kinds.test.ts new file mode 100644 index 00000000000..727e5058f79 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/request-kinds.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { fakeGoogle, json } from "../fixtures/fake-google.js"; +import { createGoogleHttp } from "../google-http.js"; +import { SLIDES_REQUEST_KINDS } from "./request-kinds.js"; +import { updatePresentation } from "./update-presentation.js"; + +const REVISION = { requiredRevisionId: "rev-1" }; +const rules = Object.entries(SLIDES_REQUEST_KINDS); +const allowed = rules.flatMap(([kind, rule]) => (rule.allowed ? [[kind, rule.example ?? {}] as const] : [])); +const refused = rules.flatMap(([kind, rule]) => (rule.allowed ? [] : [[kind, rule.reason] as const])); + +async function send(requests: Array>) { + const { fetch, calls } = fakeGoogle(() => json({ replies: requests.map(() => ({})), writeControl: { requiredRevisionId: "rev-2" } })); + const result = await updatePresentation.call({ presentationId: "p", requests, writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + return { result, calls, text: (result.content[0] as { text: string }).text }; +} + +describe("update_presentation request kinds", () => { + it("classifies every kind in Google's REST and MCP references explicitly: allowed, allowed in a restricted form, or refused", () => { + const restKinds = [ + "createSlide", "createShape", "createTable", "insertText", "insertTableRows", "insertTableColumns", "deleteTableRow", "deleteTableColumn", + "replaceAllText", "deleteObject", "updatePageElementTransform", "updateSlidesPosition", "deleteText", "createImage", "createVideo", + "createSheetsChart", "createLine", "refreshSheetsChart", "updateShapeProperties", "updateImageProperties", "updateVideoProperties", + "updatePageProperties", "updateTableCellProperties", "updateLineProperties", "createParagraphBullets", "replaceAllShapesWithImage", + "duplicateObject", "updateTextStyle", "replaceAllShapesWithSheetsChart", "deleteParagraphBullets", "updateParagraphStyle", + "updateTableBorderProperties", "updateTableColumnProperties", "updateTableRowProperties", "mergeTableCells", "unmergeTableCells", + "groupObjects", "ungroupObjects", "updatePageElementAltText", "replaceImage", "updateSlideProperties", "updatePageElementsZOrder", + "updateLineCategory", "rerouteLine", "insertComment", "addCommentReply", "updateCommentPost", "deleteComment", "deleteCommentReply", + ]; + const mcpOnlyKinds = ["importSlides", "createAudio", "updateAudioProperties"]; + expect(rules.map(([kind]) => kind).sort()).toEqual([...restKinds, ...mcpOnlyKinds].sort()); + const restricted = rules.filter(([, rule]) => rule.allowed && rule.refuse).map(([kind]) => kind).sort(); + expect(restricted).toEqual(["createImage", "createVideo", "replaceAllShapesWithImage", "replaceImage", "updatePageProperties"]); + expect(refused.map(([kind]) => kind).sort()).toEqual(["createAudio", "createSheetsChart", "importSlides", "refreshSheetsChart", "replaceAllShapesWithSheetsChart"]); + }); + + it.each(allowed)("passes %s through unchanged", async (kind, body) => { + const request = { [kind]: body }; + const { result, calls } = await send([request]); + expect(result.isError).toBeUndefined(); + expect((calls[0]!.body as { requests: unknown[] }).requests).toEqual([request]); + }); + + it.each(refused)("refuses %s and sends nothing", async (kind, reason) => { + const { result, calls, text } = await send([{ insertText: { objectId: "a", text: "x" } }, { [kind]: {} }]); + expect(result.isError).toBe(true); + expect(text).toBe(`requests[1].${kind} ${reason} This tool only changes the one file it is given, so nothing was changed.`); + expect(calls).toHaveLength(0); + }); + + it.each([ + ["createVideo", { source: "DRIVE", id: "file-1" }, "is accepted only with source YOUTUBE; a DRIVE video is another file."], + ["createVideo", { id: "file-1" }, "is accepted only with source YOUTUBE; a DRIVE video is another file."], + ["createImage", { url: "https://drive.google.com/uc?id=file-1" }, "takes its picture from a Google Drive or Docs link (url), which is another file."], + ["replaceImage", { imageObjectId: "i", url: "https://docs.google.com/drawings/d/x/export/png" }, "takes its picture from a Google Drive or Docs link (url), which is another file."], + ["replaceAllShapesWithImage", { imageUrl: "https://drive.google.com/uc?id=f" }, "takes its picture from a Google Drive or Docs link (imageUrl), which is another file."], + ["updatePageProperties", { objectId: "s1", pageProperties: { pageBackgroundFill: { stretchedPictureFill: { contentUrl: "https://drive.google.com/uc?id=f" } } }, fields: "pageBackgroundFill" }, "takes its picture from a Google Drive or Docs link (pageProperties.pageBackgroundFill.stretchedPictureFill.contentUrl), which is another file."], + ])("refuses %s in a form that reads another file (%j), and sends nothing", async (kind, body, reason) => { + const { calls, text } = await send([{ [kind]: body }]); + expect(text).toBe(`requests[0].${kind} ${reason} This tool only changes the one file it is given, so nothing was changed.`); + expect(calls).toHaveLength(0); + }); + + it.each(["createPresentation", "copyPresentation", "futureRequestKind"])("refuses the unknown kind %s and sends nothing", async (kind) => { + const { calls, text } = await send([{ [kind]: {} }]); + expect(text).toBe(`requests[0].${kind} is not a request kind this tool accepts. This tool only changes the one file it is given, so nothing was changed.`); + expect(calls).toHaveLength(0); + }); + + it("lists the accepted and refused kinds in the tool description from the same table", () => { + const description = updatePresentation.definition.description!; + for (const [kind] of allowed) expect(description).toContain(kind); + expect(description).toContain(`Refused because they read another file: ${refused.map(([kind]) => kind).join(", ")}.`); + }); +}); diff --git a/server/src/google-workspace-rest-tools/slides/request-kinds.ts b/server/src/google-workspace-rest-tools/slides/request-kinds.ts new file mode 100644 index 00000000000..115c8a38750 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/request-kinds.ts @@ -0,0 +1,63 @@ +import { refuseGoogleFileUrl, type RequestKindRules } from "../documents-shared.js"; + +const allow = { allowed: true } as const; +const SHEETS = "reads a chart from a Google Sheets spreadsheet, which is another file."; + +function youtubeOnly(body: Record): string | undefined { + return body.source === "YOUTUBE" ? undefined : "is accepted only with source YOUTUBE; a DRIVE video is another file."; +} + +export const SLIDES_REQUEST_KINDS: RequestKindRules = { + createSlide: allow, + createShape: allow, + createTable: allow, + insertText: allow, + insertTableRows: allow, + insertTableColumns: allow, + deleteTableRow: allow, + deleteTableColumn: allow, + replaceAllText: allow, + deleteObject: allow, + updatePageElementTransform: allow, + updateSlidesPosition: allow, + deleteText: allow, + createImage: { allowed: true, refuse: refuseGoogleFileUrl("url"), example: { url: "https://example.test/chart.png", elementProperties: { pageObjectId: "s1" } } }, + createVideo: { allowed: true, refuse: youtubeOnly, example: { source: "YOUTUBE", id: "synthetic", elementProperties: { pageObjectId: "s1" } } }, + createLine: allow, + updateShapeProperties: allow, + updateImageProperties: allow, + updateVideoProperties: allow, + updateAudioProperties: allow, + updatePageProperties: { allowed: true, refuse: refuseGoogleFileUrl("pageProperties", "pageBackgroundFill", "stretchedPictureFill", "contentUrl"), example: { objectId: "s1", pageProperties: { pageBackgroundFill: { stretchedPictureFill: { contentUrl: "https://example.test/bg.png" } } }, fields: "pageBackgroundFill" } }, + updateTableCellProperties: allow, + updateLineProperties: allow, + createParagraphBullets: allow, + replaceAllShapesWithImage: { allowed: true, refuse: refuseGoogleFileUrl("imageUrl"), example: { imageUrl: "https://example.test/logo.png", containsText: { text: "{{logo}}" } } }, + duplicateObject: allow, + updateTextStyle: allow, + deleteParagraphBullets: allow, + updateParagraphStyle: allow, + updateTableBorderProperties: allow, + updateTableColumnProperties: allow, + updateTableRowProperties: allow, + mergeTableCells: allow, + unmergeTableCells: allow, + groupObjects: allow, + ungroupObjects: allow, + updatePageElementAltText: allow, + replaceImage: { allowed: true, refuse: refuseGoogleFileUrl("url"), example: { imageObjectId: "img1", url: "https://example.test/logo.png" } }, + updateSlideProperties: allow, + updatePageElementsZOrder: allow, + updateLineCategory: allow, + rerouteLine: allow, + insertComment: allow, + addCommentReply: allow, + updateCommentPost: allow, + deleteComment: allow, + deleteCommentReply: allow, + createSheetsChart: { allowed: false, reason: SHEETS }, + replaceAllShapesWithSheetsChart: { allowed: false, reason: SHEETS }, + refreshSheetsChart: { allowed: false, reason: SHEETS }, + importSlides: { allowed: false, reason: "copies slides from another presentation, which is another file." }, + createAudio: { allowed: false, reason: "inserts an audio file from Google Drive, which is another file." }, +}; diff --git a/server/src/google-workspace-rest-tools/slides/update-presentation.test.ts b/server/src/google-workspace-rest-tools/slides/update-presentation.test.ts new file mode 100644 index 00000000000..7e7bd77f6f2 --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/update-presentation.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; +import { fakeGoogle, json } from "../fixtures/fake-google.js"; +import { createGoogleHttp } from "../google-http.js"; +import { updatePresentation, updatePresentationRequest } from "./update-presentation.js"; + +const REVISION = { requiredRevisionId: "rev-deck-1" }; + +type Edit = { insertText?: { objectId: string; text: string; insertionIndex?: number }; deleteText?: { objectId: string; textRange: { type: "FIXED_RANGE"; startIndex: number; endIndex: number } } }; + +function applyInOrder(shapes: Record, requests: Edit[]): Record { + const result = { ...shapes }; + for (const request of requests) { + if (request.insertText) { + const { objectId, text, insertionIndex = 0 } = request.insertText; + result[objectId] = result[objectId]!.slice(0, insertionIndex) + text + result[objectId]!.slice(insertionIndex); + } else if (request.deleteText) { + const { objectId, textRange } = request.deleteText; + result[objectId] = result[objectId]!.slice(0, textRange.startIndex) + result[objectId]!.slice(textRange.endIndex); + } + } + return result; +} + +describe("update_presentation request", () => { + it("posts the requests unchanged and in order, with the revision the caller read", () => { + const requests = [ + { createSlide: { objectId: "new-slide", insertionIndex: 1 } }, + { insertText: { objectId: "title-1", text: "Hi", insertionIndex: 0 } }, + ]; + expect(updatePresentationRequest({ presentationId: "deck-1", requests, writeControl: REVISION })).toEqual({ + method: "POST", + host: "slides.googleapis.com", + path: "/v1/presentations/deck-1:batchUpdate", + body: { requests, writeControl: { requiredRevisionId: "rev-deck-1" } }, + }); + }); + + it.each([undefined, {}])("refuses a call without the revision it read: %j", (writeControl) => { + expect(() => updatePresentationRequest({ presentationId: "d", requests: [{ deleteObject: { objectId: "x" } }], writeControl })).toThrow(/writeControl\.requiredRevisionId is required/); + }); +}); + +describe("update_presentation edit order", () => { + const read = { title: "Plan", body: "Ship it" }; + const fromOneRead: Edit[] = [ + { insertText: { objectId: "body", text: " today", insertionIndex: 7 } }, + { deleteText: { objectId: "body", textRange: { type: "FIXED_RANGE", startIndex: 4, endIndex: 5 } } }, + { insertText: { objectId: "body", text: "We ", insertionIndex: 0 } }, + { insertText: { objectId: "title", text: "Q4 ", insertionIndex: 0 } }, + ]; + + it("applies edits in one shape correctly from the highest index to the lowest, as the description says", () => { + expect(applyInOrder(read, fromOneRead)).toEqual({ title: "Q4 Plan", body: "We Shipit today" }); + expect(applyInOrder(read, [...fromOneRead].reverse())).not.toEqual({ title: "Q4 Plan", body: "We Shipit today" }); + }); + + it("sends several edits in one call, exactly in the caller's order, and returns the replies and new revision", async () => { + const { fetch, calls } = fakeGoogle(() => json({ presentationId: "d", replies: [{}, {}, {}, {}], writeControl: { requiredRevisionId: "rev-deck-2" } })); + const result = await updatePresentation.call({ presentationId: "d", requests: fromOneRead, writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls).toHaveLength(1); + expect((calls[0]!.body as { requests: Edit[] }).requests).toEqual(fromOneRead); + expect(result.structuredContent).toEqual({ replies: [{}, {}, {}, {}], writeControl: { requiredRevisionId: "rev-deck-2" } }); + }); +}); + +describe("update_presentation tool", () => { + it("returns a clear error and changes nothing when the presentation changed since it was read", async () => { + const { fetch, calls } = fakeGoogle(() => json({ error: { code: 400, status: "FAILED_PRECONDITION", message: "The required revision ID 'rev-deck-1' doesn't match the latest revision ID." } }, 400)); + const result = await updatePresentation.call({ presentationId: "d", requests: [{ deleteObject: { objectId: "x" } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect(calls).toHaveLength(1); + expect(result).toEqual({ + isError: true, + content: [{ type: "text", text: "The presentation is no longer at the revision you read (or that revision ID is not valid), so nothing was changed. Read it again with read_presentation and retry with its new revisionId." }], + }); + }); + + it("never retries the write after a timeout-like failure and warns that it may have happened", async () => { + const { fetch, calls } = fakeGoogle(() => json({ error: { code: 502 } }, 502)); + const result = await updatePresentation.call({ presentationId: "d", requests: [{ deleteObject: { objectId: "x" } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch, retryDelayMs: 0 })); + expect(calls).toHaveLength(1); + expect((result.content[0] as { text: string }).text).toMatch(/may or may not have been made/); + }); + + it("recognizes a conflict from Google's structured status", async () => { + const { fetch } = fakeGoogle(() => json({ error: { code: 400, status: "FAILED_PRECONDITION", message: "Precondition check failed." } }, 400)); + const result = await updatePresentation.call({ presentationId: "d", requests: [{ deleteObject: { objectId: "x" } }], writeControl: REVISION }, createGoogleHttp({ accessToken: "t", fetch })); + expect((result.content[0] as { text: string }).text).toMatch(/^The presentation is no longer at the revision you read/); + }); + + it.each([ + ["no requests", { presentationId: "d", writeControl: REVISION }], + ["an empty request list", { presentationId: "d", requests: [], writeControl: REVISION }], + ["a request with two kinds", { presentationId: "d", requests: [{ createSlide: {}, deleteObject: {} }], writeControl: REVISION }], + ["a bad presentation ID", { presentationId: "d/../x", requests: [{ createSlide: {} }], writeControl: REVISION }], + ["no revision", { presentationId: "d", requests: [{ createSlide: {} }] }], + ["an empty revision", { presentationId: "d", requests: [{ createSlide: {} }], writeControl: { requiredRevisionId: "" } }], + ])("sends nothing for %s", async (_name, input) => { + const { fetch, calls } = fakeGoogle(() => json({})); + expect((await updatePresentation.call(input, createGoogleHttp({ accessToken: "t", fetch }))).isError).toBe(true); + expect(calls).toHaveLength(0); + }); +}); diff --git a/server/src/google-workspace-rest-tools/slides/update-presentation.ts b/server/src/google-workspace-rest-tools/slides/update-presentation.ts new file mode 100644 index 00000000000..8fabcec26ef --- /dev/null +++ b/server/src/google-workspace-rest-tools/slides/update-presentation.ts @@ -0,0 +1,83 @@ +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import { z } from "zod"; +import { allowedKinds, assertRequestKinds, batchRequestArg, fileIdArg, MAX_BATCH_REQUESTS, refusedKinds, revisionIdArg, sendBatchUpdate } from "../documents-shared.js"; +import { GoogleToolError } from "../errors.js"; +import type { GoogleRequest } from "../google-http.js"; +import { defineTool, structuredResult } from "../tool.js"; +import { presentationPath, SLIDES_HOST, type RestBatchUpdateResponse } from "./presentation.js"; +import { SLIDES_REQUEST_KINDS } from "./request-kinds.js"; + +const args = z.object({ + presentationId: fileIdArg("Slides presentation"), + requests: z.array(batchRequestArg).min(1).max(MAX_BATCH_REQUESTS), + writeControl: z.object({ requiredRevisionId: revisionIdArg.optional() }).optional(), +}); +export type UpdatePresentationArgs = z.infer; + + +export function updatePresentationRequest(input: UpdatePresentationArgs): GoogleRequest { + assertRequestKinds(input.requests, SLIDES_REQUEST_KINDS); + const requiredRevisionId = input.writeControl?.requiredRevisionId; + if (!requiredRevisionId) { + throw new GoogleToolError("invalid_argument", "writeControl.requiredRevisionId is required: pass content.revisionId from read_presentation, so the edit is applied only to the version you read. Nothing was changed."); + } + return { + method: "POST", + host: SLIDES_HOST, + path: `${presentationPath(input.presentationId)}:batchUpdate`, + body: { requests: input.requests, writeControl: { requiredRevisionId } }, + }; +} + +export function updatePresentationResult(response: RestBatchUpdateResponse): CallToolResult { + return structuredResult({ replies: response.replies ?? [], writeControl: response.writeControl ?? {} }); +} + +export const updatePresentation = defineTool({ + definition: { + name: "update_presentation", + description: [ + "Edits an existing Google Slides presentation with a list of Slides API batchUpdate requests (for example insertText, deleteText, replaceAllText, createSlide, createShape, createTable, updateTextStyle, duplicateObject or deleteObject), and returns one reply per request.", + "Requests are applied in the order given, all or none: if any request is invalid, nothing is changed.", + "Each request sees the presentation as changed by the requests before it, so text indices in a shape move after an insertion or deletion in that shape. When making several edits by index in one shape from one read_presentation result, order them from the highest index to the lowest.", + "The requests can delete or replace content in this one presentation: deleteObject removes a slide or page element, and replaceAllText and deleteText change text everywhere they match. This tool cannot create, delete, move, copy or share files.", + `Accepted request kinds: ${allowedKinds(SLIDES_REQUEST_KINDS).join(", ")}. createVideo is accepted only with source YOUTUBE, and images only from links outside drive.google.com and docs.google.com.`, + `Refused because they read another file: ${refusedKinds(SLIDES_REQUEST_KINDS).join(", ")}. Any other kind is refused too.`, + "writeControl.requiredRevisionId is required: pass content.revisionId from read_presentation. If the presentation changed since, nothing is changed and you must read it again. The new revision ID is returned in writeControl.", + ].join(" "), + inputSchema: { + type: "object", + properties: { + presentationId: { type: "string", description: "Required. The ID of the presentation to edit." }, + requests: { + type: "array", + items: { type: "object", additionalProperties: true }, + description: "Required. Slides API batchUpdate requests, each an object with exactly one request kind, such as {\"insertText\": {\"objectId\": \"shape-1\", \"text\": \"Hello\", \"insertionIndex\": 0}}. See https://developers.google.com/workspace/slides/api/reference/rest/v1/presentations/request.", + }, + writeControl: { + type: "object", + properties: { + requiredRevisionId: { type: "string", description: "Required. The revisionId from read_presentation. If the presentation is no longer at this revision, nothing is changed." }, + }, + required: ["requiredRevisionId"], + description: "Required. Controls how the edit is applied.", + }, + }, + required: ["presentationId", "requests", "writeControl"], + }, + outputSchema: { + type: "object", + properties: { + replies: { type: "array", items: { type: "object" }, description: "One reply per request, in order; some are empty." }, + writeControl: { type: "object", description: "The presentation's revision after the edit, as requiredRevisionId." }, + }, + required: ["replies", "writeControl"], + }, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, + }, + args, + async run(input, http) { + const request = updatePresentationRequest(input); + return updatePresentationResult(await sendBatchUpdate(http, request, "presentation", "read_presentation")); + }, +}); diff --git a/server/src/google-workspace-rest-tools/tool.ts b/server/src/google-workspace-rest-tools/tool.ts index 347353966e2..0fcad1221c5 100644 --- a/server/src/google-workspace-rest-tools/tool.ts +++ b/server/src/google-workspace-rest-tools/tool.ts @@ -37,6 +37,8 @@ export function structuredResult(value: Record): CallToolResult return { content: [{ type: "text", text: JSON.stringify(value) }], structuredContent: value }; } +export const MAX_RESULT_BYTES = 250_000; + export function serializedResultBytes(result: CallToolResult): number { return Buffer.byteLength(JSON.stringify(result), "utf8"); } diff --git a/server/src/google-workspace-rest-tools/tools.ts b/server/src/google-workspace-rest-tools/tools.ts index 0f1d4f88a15..ad631e5a4fa 100644 --- a/server/src/google-workspace-rest-tools/tools.ts +++ b/server/src/google-workspace-rest-tools/tools.ts @@ -2,17 +2,21 @@ import type { CallToolResult, Tool } from "@modelcontextprotocol/sdk/types.js"; import { McpError, ErrorCode } from "@modelcontextprotocol/sdk/types.js"; import { GoogleWorkspaceAuthError } from "./errors.js"; import { CALENDAR_TOOLS } from "./calendar/index.js"; +import { DOCS_TOOLS } from "./docs/index.js"; import { GMAIL_TOOLS } from "./gmail/index.js"; +import { SLIDES_TOOLS } from "./slides/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", "sheets"] as const; +export const GOOGLE_WORKSPACE_REST_SERVICES = ["gmail", "calendar", "docs", "slides", "sheets"] as const; export type GoogleWorkspaceRestService = (typeof GOOGLE_WORKSPACE_REST_SERVICES)[number]; const TOOLS: Record = { gmail: GMAIL_TOOLS, calendar: CALENDAR_TOOLS, + docs: DOCS_TOOLS, + slides: SLIDES_TOOLS, sheets: SHEETS_TOOLS, };